@theokit/gateway-discord 0.4.0 → 0.5.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/CHANGELOG.md +47 -0
- package/README.md +14 -0
- package/dist/index.cjs +51 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -2
- package/dist/index.d.ts +26 -2
- package/dist/index.js +51 -4
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- e5a2603: Group messages that do not mention the bot are no longer delivered by default on Discord, Matrix
|
|
8
|
+
and Teams; pass `requireMention: false` to keep the old behaviour.
|
|
9
|
+
|
|
10
|
+
Discord, Matrix and Teams gain a `requireMention` option that defaults to `true`. With it on, a
|
|
11
|
+
group or thread message reaches the handler only when it mentions the bot, and a DM always does.
|
|
12
|
+
Discord reads the bot's id in `mentions.users` (a direct mention or a reply that pings it; not
|
|
13
|
+
`@everyone`, `@here` or roles), and drops group messages with one stderr line until the client is
|
|
14
|
+
ready. Matrix reads `m.mentions.user_ids`, and falls back to the full user id in `body` or
|
|
15
|
+
`formatted_body` when a client sends no `m.mentions`. Teams reads `mention` entities against the
|
|
16
|
+
activity's `recipient.id`, and drops a group activity that names no recipient with one stderr line.
|
|
17
|
+
|
|
18
|
+
LINE's `deliver()` now applies the mention guard its webhook route already applied.
|
|
19
|
+
|
|
20
|
+
On all four adapters `deliver()` and the adapter's own inbound path use one rule, and `deliver()`
|
|
21
|
+
answers `"ok"` for an event the rule drops, with or without a handler subscribed.
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
|
|
26
|
+
|
|
27
|
+
`@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
|
|
28
|
+
`filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
|
|
29
|
+
carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
|
|
30
|
+
`supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
|
|
31
|
+
field. The runner and the router refuse an outbound carrying attachments as
|
|
32
|
+
`attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
|
|
33
|
+
`supportsAttachments`.
|
|
34
|
+
|
|
35
|
+
`@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
|
|
36
|
+
`sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
|
|
37
|
+
when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
|
|
38
|
+
than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
|
|
39
|
+
|
|
40
|
+
Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
|
|
41
|
+
with `attachments_unsupported` and makes no platform call, instead of sending the text and
|
|
42
|
+
dropping the image.
|
|
43
|
+
|
|
44
|
+
The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
|
|
45
|
+
throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
|
|
46
|
+
as a handler error is. Dispatch still does not throw.
|
|
47
|
+
|
|
48
|
+
- 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
|
|
49
|
+
|
|
3
50
|
## 0.4.0
|
|
4
51
|
|
|
5
52
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -38,6 +38,20 @@ const runner = new GatewayRunner({
|
|
|
38
38
|
await runner.start();
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
## Group messages and mentions
|
|
42
|
+
|
|
43
|
+
`requireMention` decides which guild and thread messages reach your handler. It defaults to
|
|
44
|
+
`true`: a message there is delivered only when it mentions the bot, meaning the bot's user id is
|
|
45
|
+
in the message's `mentions.users`. A direct `<@id>` counts, and so does a reply that pings the
|
|
46
|
+
bot. `@everyone`, `@here` and role mentions do not. A DM is always delivered.
|
|
47
|
+
|
|
48
|
+
Until the client is ready the bot's user id is unknown, so group messages are dropped and one
|
|
49
|
+
stderr line says why. `deliver()` and the socket path apply the same rule, and `deliver()` answers
|
|
50
|
+
`"ok"` for a message it drops.
|
|
51
|
+
|
|
52
|
+
**Upgrading:** before this option the adapter delivered every group message. Pass
|
|
53
|
+
`requireMention: false` to keep that behaviour.
|
|
54
|
+
|
|
41
55
|
## Limitations (v0.1)
|
|
42
56
|
|
|
43
57
|
- **Text-trigger commands only.** Proper Discord slash commands (registered via Application Commands API) are out of scope — use `event.text.startsWith("!cmd")` for now.
|
package/dist/index.cjs
CHANGED
|
@@ -4,12 +4,22 @@ var gateway = require('@theokit/gateway');
|
|
|
4
4
|
var discord_js = require('discord.js');
|
|
5
5
|
|
|
6
6
|
// src/adapter.ts
|
|
7
|
+
|
|
8
|
+
// src/refuse-attachments.ts
|
|
9
|
+
function refuseAttachments(out) {
|
|
10
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
11
|
+
return {
|
|
12
|
+
ok: false,
|
|
13
|
+
error: { code: "attachments_unsupported", message: "discord adapter cannot send attachments" }
|
|
14
|
+
};
|
|
15
|
+
}
|
|
7
16
|
var DISCORD_MAX_MESSAGE = 2e3;
|
|
8
17
|
var SAFE_DISCORD_CHUNK = 1900;
|
|
9
18
|
var BOUNDARIES = {
|
|
10
19
|
boundaries: ["\n\n", "\n"],
|
|
11
20
|
lastResort: "window",
|
|
12
|
-
stripLeading: /^\n
|
|
21
|
+
stripLeading: /^\n+/,
|
|
22
|
+
keepTableRows: true
|
|
13
23
|
};
|
|
14
24
|
function splitForDiscord(text) {
|
|
15
25
|
return gateway.chunkText(text, {
|
|
@@ -40,9 +50,12 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
40
50
|
token;
|
|
41
51
|
handler;
|
|
42
52
|
connected = false;
|
|
53
|
+
requireMention;
|
|
54
|
+
warnedMissingBotId = false;
|
|
43
55
|
constructor(opts) {
|
|
44
56
|
super();
|
|
45
57
|
this.token = opts.token;
|
|
58
|
+
this.requireMention = opts.requireMention ?? true;
|
|
46
59
|
const intents = opts.intents ?? DEFAULT_DISCORD_INTENTS;
|
|
47
60
|
if (intents.length === 0) {
|
|
48
61
|
process.stderr.write(
|
|
@@ -92,6 +105,9 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
92
105
|
return this.client;
|
|
93
106
|
}
|
|
94
107
|
async sendMessage(out) {
|
|
108
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
109
|
+
}
|
|
110
|
+
async sendText(out) {
|
|
95
111
|
if (out.text.length === 0) {
|
|
96
112
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
97
113
|
}
|
|
@@ -141,6 +157,9 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
141
157
|
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
142
158
|
*/
|
|
143
159
|
async editMessage(messageId, out) {
|
|
160
|
+
return refuseAttachments(out) ?? this.editText(messageId, out);
|
|
161
|
+
}
|
|
162
|
+
async editText(messageId, out) {
|
|
144
163
|
if (out.text.length === 0) {
|
|
145
164
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
146
165
|
}
|
|
@@ -168,7 +187,33 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
168
187
|
async handleInbound(msg) {
|
|
169
188
|
if (this.handler === void 0) return;
|
|
170
189
|
if (msg.author.bot) return;
|
|
171
|
-
|
|
190
|
+
const event = normalizeEvent(msg);
|
|
191
|
+
if (!this.passesMentionGate(event)) return;
|
|
192
|
+
await this.dispatchEvent(event);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Whether an event may reach the handler: always for a DM or with `requireMention` off,
|
|
196
|
+
* otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
|
|
197
|
+
* it, so the two entries cannot disagree.
|
|
198
|
+
*/
|
|
199
|
+
passesMentionGate(event) {
|
|
200
|
+
if (event.channel.type === "dm" || !this.requireMention) return true;
|
|
201
|
+
const botId = this.client.user?.id;
|
|
202
|
+
if (botId === void 0) {
|
|
203
|
+
this.warnMissingBotIdOnce();
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
const raw = event.platform === "discord" ? event.discord.raw : void 0;
|
|
207
|
+
const mentionedUsers = raw?.mentions?.users;
|
|
208
|
+
if (typeof mentionedUsers?.has === "function") return mentionedUsers.has(botId) === true;
|
|
209
|
+
return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);
|
|
210
|
+
}
|
|
211
|
+
warnMissingBotIdOnce() {
|
|
212
|
+
if (this.warnedMissingBotId) return;
|
|
213
|
+
this.warnedMissingBotId = true;
|
|
214
|
+
process.stderr.write(
|
|
215
|
+
"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\n"
|
|
216
|
+
);
|
|
172
217
|
}
|
|
173
218
|
/**
|
|
174
219
|
* Dispatch a pre-built event to the current handler, honouring EC-H replace
|
|
@@ -199,10 +244,12 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
199
244
|
/**
|
|
200
245
|
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
201
246
|
*
|
|
202
|
-
*
|
|
203
|
-
*
|
|
247
|
+
* The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
|
|
248
|
+
* without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
|
|
249
|
+
* throw is named as the handler's failure rather than the platform's, and delivery continues.
|
|
204
250
|
*/
|
|
205
251
|
async deliver(event) {
|
|
252
|
+
if (!this.passesMentionGate(event)) return "ok";
|
|
206
253
|
return this.runHandler(this.handler, event);
|
|
207
254
|
}
|
|
208
255
|
};
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Events","Routes","DiscordAPIError"],"mappings":";;;;;;AAeO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ,YAAA,EAAc;AAChB,CAAA;AAaO,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,GAAG;AAAA,GACJ,CAAA;AACH;AASO,SAAS,uBAAuB,IAAA,EAAwB;AAC7D,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,OAAO,mBAAA,GAAsB,CAAA;AAAA,IAC7B,WAAW,kBAAA,GAAqB,CAAA;AAAA,IAChC,GAAG;AAAA,GACJ,CAAA;AACH;;;ACZO,IAAM,uBAAA,GAA4D;AAAA,EACvEC,4BAAA,CAAkB,MAAA;AAAA,EAClBA,4BAAA,CAAkB,aAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB;AACpB,CAAA;AASO,IAAM,cAAA,GAAN,cAA6BC,2BAAA,CAAoB;AAAA,EAC7C,QAAA,GAAW,SAAA;AAAA,EACH,MAAA;AAAA,EACA,KAAA;AAAA,EACT,OAAA;AAAA,EACA,SAAA,GAAY,KAAA;AAAA,EAEpB,YAAY,IAAA,EAA6B;AACvC,IAAA,KAAA,EAAM;AACN,I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A,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Routes,\n} from \"discord.js\";\n\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n await this.dispatchEvent(normalizeEvent(msg));\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Events","Routes","DiscordAPIError"],"mappings":";;;;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ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AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -29,6 +29,18 @@ interface DiscordAdapterOptions {
|
|
|
29
29
|
* empty `msg.content` (EC-C silent failure).
|
|
30
30
|
*/
|
|
31
31
|
readonly intents?: GatewayIntentBits[];
|
|
32
|
+
/**
|
|
33
|
+
* Deliver a guild or thread message only when it mentions the bot. Default `true`.
|
|
34
|
+
*
|
|
35
|
+
* A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a
|
|
36
|
+
* reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is
|
|
37
|
+
* not a mention). `@everyone`, `@here` and role mentions do not count. An event with no
|
|
38
|
+
* discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or
|
|
39
|
+
* `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is
|
|
40
|
+
* unknown, so every group message is dropped and one stderr line says why. Pass `false` to
|
|
41
|
+
* deliver every message, as the adapter did before this option existed.
|
|
42
|
+
*/
|
|
43
|
+
readonly requireMention?: boolean;
|
|
32
44
|
}
|
|
33
45
|
/**
|
|
34
46
|
* Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.
|
|
@@ -43,6 +55,8 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
43
55
|
private readonly token;
|
|
44
56
|
private handler?;
|
|
45
57
|
private connected;
|
|
58
|
+
private readonly requireMention;
|
|
59
|
+
private warnedMissingBotId;
|
|
46
60
|
constructor(opts: DiscordAdapterOptions);
|
|
47
61
|
connect(): Promise<boolean>;
|
|
48
62
|
disconnect(): Promise<void>;
|
|
@@ -57,6 +71,7 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
57
71
|
*/
|
|
58
72
|
getBot(): Client;
|
|
59
73
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
74
|
+
private sendText;
|
|
60
75
|
/** Discord edits a sent message's text with one REST call. */
|
|
61
76
|
readonly supportsEdit = true;
|
|
62
77
|
/**
|
|
@@ -69,13 +84,22 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
69
84
|
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
70
85
|
*/
|
|
71
86
|
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
87
|
+
private editText;
|
|
72
88
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
73
89
|
private handleInbound;
|
|
90
|
+
/**
|
|
91
|
+
* Whether an event may reach the handler: always for a DM or with `requireMention` off,
|
|
92
|
+
* otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
|
|
93
|
+
* it, so the two entries cannot disagree.
|
|
94
|
+
*/
|
|
95
|
+
private passesMentionGate;
|
|
96
|
+
private warnMissingBotIdOnce;
|
|
74
97
|
/**
|
|
75
98
|
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
76
99
|
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
100
|
+
* The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
|
|
101
|
+
* without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
|
|
102
|
+
* throw is named as the handler's failure rather than the platform's, and delivery continues.
|
|
79
103
|
*/
|
|
80
104
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
81
105
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -29,6 +29,18 @@ interface DiscordAdapterOptions {
|
|
|
29
29
|
* empty `msg.content` (EC-C silent failure).
|
|
30
30
|
*/
|
|
31
31
|
readonly intents?: GatewayIntentBits[];
|
|
32
|
+
/**
|
|
33
|
+
* Deliver a guild or thread message only when it mentions the bot. Default `true`.
|
|
34
|
+
*
|
|
35
|
+
* A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a
|
|
36
|
+
* reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is
|
|
37
|
+
* not a mention). `@everyone`, `@here` and role mentions do not count. An event with no
|
|
38
|
+
* discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or
|
|
39
|
+
* `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is
|
|
40
|
+
* unknown, so every group message is dropped and one stderr line says why. Pass `false` to
|
|
41
|
+
* deliver every message, as the adapter did before this option existed.
|
|
42
|
+
*/
|
|
43
|
+
readonly requireMention?: boolean;
|
|
32
44
|
}
|
|
33
45
|
/**
|
|
34
46
|
* Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.
|
|
@@ -43,6 +55,8 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
43
55
|
private readonly token;
|
|
44
56
|
private handler?;
|
|
45
57
|
private connected;
|
|
58
|
+
private readonly requireMention;
|
|
59
|
+
private warnedMissingBotId;
|
|
46
60
|
constructor(opts: DiscordAdapterOptions);
|
|
47
61
|
connect(): Promise<boolean>;
|
|
48
62
|
disconnect(): Promise<void>;
|
|
@@ -57,6 +71,7 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
57
71
|
*/
|
|
58
72
|
getBot(): Client;
|
|
59
73
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
74
|
+
private sendText;
|
|
60
75
|
/** Discord edits a sent message's text with one REST call. */
|
|
61
76
|
readonly supportsEdit = true;
|
|
62
77
|
/**
|
|
@@ -69,13 +84,22 @@ declare class DiscordAdapter extends BasePlatformAdapter {
|
|
|
69
84
|
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
70
85
|
*/
|
|
71
86
|
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
87
|
+
private editText;
|
|
72
88
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
73
89
|
private handleInbound;
|
|
90
|
+
/**
|
|
91
|
+
* Whether an event may reach the handler: always for a DM or with `requireMention` off,
|
|
92
|
+
* otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
|
|
93
|
+
* it, so the two entries cannot disagree.
|
|
94
|
+
*/
|
|
95
|
+
private passesMentionGate;
|
|
96
|
+
private warnMissingBotIdOnce;
|
|
74
97
|
/**
|
|
75
98
|
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
76
99
|
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
100
|
+
* The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
|
|
101
|
+
* without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
|
|
102
|
+
* throw is named as the handler's failure rather than the platform's, and delivery continues.
|
|
79
103
|
*/
|
|
80
104
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
81
105
|
}
|
package/dist/index.js
CHANGED
|
@@ -2,12 +2,22 @@ import { chunkText, BasePlatformAdapter } from '@theokit/gateway';
|
|
|
2
2
|
import { GatewayIntentBits, Client, Events, Routes, DiscordAPIError } from 'discord.js';
|
|
3
3
|
|
|
4
4
|
// src/adapter.ts
|
|
5
|
+
|
|
6
|
+
// src/refuse-attachments.ts
|
|
7
|
+
function refuseAttachments(out) {
|
|
8
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
9
|
+
return {
|
|
10
|
+
ok: false,
|
|
11
|
+
error: { code: "attachments_unsupported", message: "discord adapter cannot send attachments" }
|
|
12
|
+
};
|
|
13
|
+
}
|
|
5
14
|
var DISCORD_MAX_MESSAGE = 2e3;
|
|
6
15
|
var SAFE_DISCORD_CHUNK = 1900;
|
|
7
16
|
var BOUNDARIES = {
|
|
8
17
|
boundaries: ["\n\n", "\n"],
|
|
9
18
|
lastResort: "window",
|
|
10
|
-
stripLeading: /^\n
|
|
19
|
+
stripLeading: /^\n+/,
|
|
20
|
+
keepTableRows: true
|
|
11
21
|
};
|
|
12
22
|
function splitForDiscord(text) {
|
|
13
23
|
return chunkText(text, {
|
|
@@ -38,9 +48,12 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
38
48
|
token;
|
|
39
49
|
handler;
|
|
40
50
|
connected = false;
|
|
51
|
+
requireMention;
|
|
52
|
+
warnedMissingBotId = false;
|
|
41
53
|
constructor(opts) {
|
|
42
54
|
super();
|
|
43
55
|
this.token = opts.token;
|
|
56
|
+
this.requireMention = opts.requireMention ?? true;
|
|
44
57
|
const intents = opts.intents ?? DEFAULT_DISCORD_INTENTS;
|
|
45
58
|
if (intents.length === 0) {
|
|
46
59
|
process.stderr.write(
|
|
@@ -90,6 +103,9 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
90
103
|
return this.client;
|
|
91
104
|
}
|
|
92
105
|
async sendMessage(out) {
|
|
106
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
107
|
+
}
|
|
108
|
+
async sendText(out) {
|
|
93
109
|
if (out.text.length === 0) {
|
|
94
110
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
95
111
|
}
|
|
@@ -139,6 +155,9 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
139
155
|
* deliver as more than one message is refused as `edit_too_long` with no request.
|
|
140
156
|
*/
|
|
141
157
|
async editMessage(messageId, out) {
|
|
158
|
+
return refuseAttachments(out) ?? this.editText(messageId, out);
|
|
159
|
+
}
|
|
160
|
+
async editText(messageId, out) {
|
|
142
161
|
if (out.text.length === 0) {
|
|
143
162
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
144
163
|
}
|
|
@@ -166,7 +185,33 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
166
185
|
async handleInbound(msg) {
|
|
167
186
|
if (this.handler === void 0) return;
|
|
168
187
|
if (msg.author.bot) return;
|
|
169
|
-
|
|
188
|
+
const event = normalizeEvent(msg);
|
|
189
|
+
if (!this.passesMentionGate(event)) return;
|
|
190
|
+
await this.dispatchEvent(event);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Whether an event may reach the handler: always for a DM or with `requireMention` off,
|
|
194
|
+
* otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
|
|
195
|
+
* it, so the two entries cannot disagree.
|
|
196
|
+
*/
|
|
197
|
+
passesMentionGate(event) {
|
|
198
|
+
if (event.channel.type === "dm" || !this.requireMention) return true;
|
|
199
|
+
const botId = this.client.user?.id;
|
|
200
|
+
if (botId === void 0) {
|
|
201
|
+
this.warnMissingBotIdOnce();
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
const raw = event.platform === "discord" ? event.discord.raw : void 0;
|
|
205
|
+
const mentionedUsers = raw?.mentions?.users;
|
|
206
|
+
if (typeof mentionedUsers?.has === "function") return mentionedUsers.has(botId) === true;
|
|
207
|
+
return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);
|
|
208
|
+
}
|
|
209
|
+
warnMissingBotIdOnce() {
|
|
210
|
+
if (this.warnedMissingBotId) return;
|
|
211
|
+
this.warnedMissingBotId = true;
|
|
212
|
+
process.stderr.write(
|
|
213
|
+
"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\n"
|
|
214
|
+
);
|
|
170
215
|
}
|
|
171
216
|
/**
|
|
172
217
|
* Dispatch a pre-built event to the current handler, honouring EC-H replace
|
|
@@ -197,10 +242,12 @@ var DiscordAdapter = class extends BasePlatformAdapter {
|
|
|
197
242
|
/**
|
|
198
243
|
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
199
244
|
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
245
|
+
* The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
|
|
246
|
+
* without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
|
|
247
|
+
* throw is named as the handler's failure rather than the platform's, and delivery continues.
|
|
202
248
|
*/
|
|
203
249
|
async deliver(event) {
|
|
250
|
+
if (!this.passesMentionGate(event)) return "ok";
|
|
204
251
|
return this.runHandler(this.handler, event);
|
|
205
252
|
}
|
|
206
253
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;AAeO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,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AAI,OAAA,EAAQ,EAAE;AAAA,IAC5E;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,IAAA,EAAM,CAAA,QAAA,EAAW,OAAO,CAAA,CAAA,EAAI,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;AAaA,SAAS,eAAe,GAAA,EAAgC;AACtD,EAAA,OAAO,gBAAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Routes,\n} from \"discord.js\";\n\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n await this.dispatchEvent(normalizeEvent(msg));\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,EAAe;AACjB,CAAA;AAaO,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,GAAG;AAAA,GACJ,CAAA;AACH;AASO,SAAS,uBAAuB,IAAA,EAAwB;AAC7D,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,OAAO,mBAAA,GAAsB,CAAA;AAAA,IAC7B,WAAW,kBAAA,GAAqB,CAAA;AAAA,IAChC,GAAG;AAAA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,CAAA,CAAA,EAAI,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,EAAE;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;AAaA,SAAS,eAAe,GAAA,EAAgC;AACtD,EAAA,OAAO,gBAAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-discord",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Discord (discord.js) platform adapter for @theokit/gateway. ADRs D171, D179.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"typescript": "5.9.3",
|
|
49
49
|
"vitest": "^4.1.11",
|
|
50
50
|
"zod": "^4.0.0",
|
|
51
|
-
"@theokit/gateway": "0.
|
|
51
|
+
"@theokit/gateway": "0.14.0"
|
|
52
52
|
},
|
|
53
53
|
"publishConfig": {
|
|
54
54
|
"access": "public",
|