@theokit/gateway-discord 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - @theokit/sdk@1.3.0
9
+ - @theokit/gateway@2.0.0
10
+
11
+ ## 1.0.0
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies
16
+ - @theokit/sdk@1.2.0
17
+ - @theokit/gateway@1.0.0
18
+
19
+ ## [0.1.0] — 2026-05-20
20
+
21
+ ### Added
22
+
23
+ - Initial release. `DiscordAdapter` wraps discord.js in the `@theokit/gateway` `BasePlatformAdapter` contract.
24
+ - Default intents include `MessageContent` so `msg.content` is delivered (EC-C silent-failure guard).
25
+ - Bot-to-bot messages auto-ignored (`msg.author.bot === true`).
26
+ - WebSocket Gateway mode only (ADR D179).
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # @theokit/gateway-discord
2
+
3
+ Discord platform adapter for `@theokit/gateway`. Wraps [discord.js](https://discord.js.org/) in the `BasePlatformAdapter` contract.
4
+
5
+ > **Status: 0.1.0 — pre-release.**
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @theokit/gateway-discord @theokit/gateway @theokit/sdk discord.js
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import { GatewayRunner } from "@theokit/gateway";
17
+ import { DiscordAdapter } from "@theokit/gateway-discord";
18
+
19
+ const adapter = new DiscordAdapter({
20
+ token: process.env.DISCORD_BOT_TOKEN!,
21
+ // intents defaults to [Guilds, GuildMessages, MessageContent,
22
+ // DirectMessages, DirectMessageReactions]. Without MessageContent
23
+ // the bot receives empty msg.content — silent failure (EC-C).
24
+ });
25
+
26
+ const runner = new GatewayRunner({
27
+ adapters: [adapter],
28
+ handler: async (event, ctx) => {
29
+ await ctx.reply(`got: ${event.text}`);
30
+ },
31
+ });
32
+
33
+ await runner.start();
34
+ ```
35
+
36
+ ## Limitations (v0.1)
37
+
38
+ - **Text-trigger commands only.** Proper Discord slash commands (registered via Application Commands API) are out of scope — use `event.text.startsWith("!cmd")` for now.
39
+ - **WebSocket only** (ADR D179). No webhook-based bot mode.
40
+ - **Voice channels** not exposed via `MessageEvent`. Use `event.discord?.raw` for advanced cases.
41
+
42
+ ## License
43
+
44
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,196 @@
1
+ 'use strict';
2
+
3
+ var gateway = require('@theokit/gateway');
4
+ var discord_js = require('discord.js');
5
+
6
+ // src/adapter.ts
7
+ var DEFAULT_DISCORD_INTENTS = [
8
+ discord_js.GatewayIntentBits.Guilds,
9
+ discord_js.GatewayIntentBits.GuildMessages,
10
+ discord_js.GatewayIntentBits.MessageContent,
11
+ discord_js.GatewayIntentBits.DirectMessages,
12
+ discord_js.GatewayIntentBits.DirectMessageReactions
13
+ ];
14
+ var DISCORD_MAX_MESSAGE = 2e3;
15
+ var SAFE_DISCORD_CHUNK = 1900;
16
+ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
17
+ platform = "discord";
18
+ client;
19
+ token;
20
+ handler;
21
+ connected = false;
22
+ constructor(opts) {
23
+ super();
24
+ this.token = opts.token;
25
+ const intents = opts.intents ?? DEFAULT_DISCORD_INTENTS;
26
+ if (intents.length === 0) {
27
+ process.stderr.write(
28
+ "[discord] WARN \u2014 intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\n"
29
+ );
30
+ }
31
+ this.client = new discord_js.Client({ intents });
32
+ this.client.on(discord_js.Events.MessageCreate, async (msg) => this.handleInbound(msg));
33
+ this.client.on(discord_js.Events.Error, (err) => {
34
+ process.stderr.write(`[discord] client error: ${err.message}
35
+ `);
36
+ });
37
+ }
38
+ async connect() {
39
+ if (this.connected) return true;
40
+ try {
41
+ await new Promise((resolve, reject) => {
42
+ this.client.once(discord_js.Events.ClientReady, () => resolve());
43
+ this.client.login(this.token).catch(reject);
44
+ });
45
+ this.connected = true;
46
+ return true;
47
+ } catch (err) {
48
+ process.stderr.write(`[discord] connect failed: ${err.message}
49
+ `);
50
+ return false;
51
+ }
52
+ }
53
+ async disconnect() {
54
+ if (!this.connected) return;
55
+ this.connected = false;
56
+ try {
57
+ await this.client.destroy();
58
+ } catch {
59
+ }
60
+ }
61
+ /**
62
+ * Expose the underlying discord.js `Client` so consumers can register
63
+ * platform-specific events that don't fit the portable contract —
64
+ * `interactionCreate` (slash commands via Application Commands),
65
+ * `error` event boundary, presence updates, etc. Register BEFORE
66
+ * calling `runner.start()`.
67
+ *
68
+ * @public
69
+ */
70
+ getBot() {
71
+ return this.client;
72
+ }
73
+ async sendMessage(out) {
74
+ if (out.text.length === 0) {
75
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
76
+ }
77
+ let channel;
78
+ try {
79
+ channel = await this.client.channels.fetch(out.channel.id);
80
+ } catch (err) {
81
+ return {
82
+ ok: false,
83
+ error: { code: "channel_fetch_failed", message: err.message }
84
+ };
85
+ }
86
+ const sendable = channel;
87
+ if (sendable === null || typeof sendable.send !== "function") {
88
+ return {
89
+ ok: false,
90
+ error: {
91
+ code: "channel_not_sendable",
92
+ message: `channel "${out.channel.id}" not text-based or missing`
93
+ }
94
+ };
95
+ }
96
+ const chunks = splitForDiscord(out.text);
97
+ let lastId;
98
+ for (const chunk of chunks) {
99
+ try {
100
+ const msg = await sendable.send({
101
+ content: chunk,
102
+ ...out.replyTo !== void 0 ? { reply: { messageReference: out.replyTo } } : {}
103
+ });
104
+ lastId = msg.id;
105
+ } catch (err) {
106
+ return mapSendError(err);
107
+ }
108
+ }
109
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
110
+ }
111
+ onInbound(handler) {
112
+ this.handler = handler;
113
+ return () => {
114
+ if (this.handler === handler) this.handler = void 0;
115
+ };
116
+ }
117
+ async handleInbound(msg) {
118
+ if (this.handler === void 0) return;
119
+ if (msg.author.bot) return;
120
+ const event = normalizeEvent(msg);
121
+ await this.handler(event);
122
+ }
123
+ };
124
+ function normalizeEvent(msg) {
125
+ let channelType;
126
+ if (msg.guildId === null) {
127
+ channelType = "dm";
128
+ } else if (msg.channel.isThread()) {
129
+ channelType = "thread";
130
+ } else {
131
+ channelType = "group";
132
+ }
133
+ const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;
134
+ return {
135
+ id: `dc-${msg.channelId}-${msg.id}`,
136
+ platform: "discord",
137
+ sender: {
138
+ id: msg.author.id,
139
+ username: msg.author.username,
140
+ displayName
141
+ },
142
+ channel: {
143
+ id: msg.channelId,
144
+ type: channelType,
145
+ ...msg.channel.isThread() ? { topicId: msg.channel.id } : {}
146
+ },
147
+ text: msg.content,
148
+ receivedAt: msg.createdTimestamp,
149
+ ...msg.reference?.messageId !== void 0 ? { replyTo: msg.reference.messageId } : {},
150
+ discord: {
151
+ guildId: msg.guildId,
152
+ channelId: msg.channelId,
153
+ messageId: msg.id,
154
+ raw: msg
155
+ }
156
+ };
157
+ }
158
+ function splitForDiscord(text) {
159
+ if (text.length <= DISCORD_MAX_MESSAGE) return [text];
160
+ const parts = [];
161
+ let remaining = text;
162
+ while (remaining.length > 0) {
163
+ if (remaining.length <= SAFE_DISCORD_CHUNK) {
164
+ parts.push(remaining);
165
+ break;
166
+ }
167
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_DISCORD_CHUNK);
168
+ if (boundary < SAFE_DISCORD_CHUNK / 2) {
169
+ boundary = remaining.lastIndexOf("\n", SAFE_DISCORD_CHUNK);
170
+ }
171
+ if (boundary < SAFE_DISCORD_CHUNK / 2) boundary = SAFE_DISCORD_CHUNK;
172
+ parts.push(remaining.slice(0, boundary));
173
+ remaining = remaining.slice(boundary).replace(/^\n+/, "");
174
+ }
175
+ return parts;
176
+ }
177
+ function mapSendError(err) {
178
+ if (err instanceof discord_js.DiscordAPIError) {
179
+ const codeStr = String(err.code);
180
+ if (codeStr === "50007") {
181
+ return { ok: false, error: { code: "dm_blocked", message: err.message } };
182
+ }
183
+ if (codeStr === "50001" || codeStr === "50013") {
184
+ return { ok: false, error: { code: "no_permission", message: err.message } };
185
+ }
186
+ if (err.status === 429) {
187
+ return { ok: false, error: { code: "rate_limited", message: err.message } };
188
+ }
189
+ return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };
190
+ }
191
+ return { ok: false, error: { code: "unknown", message: err.message } };
192
+ }
193
+
194
+ exports.DiscordAdapter = DiscordAdapter;
195
+ //# sourceMappingURL=index.cjs.map
196
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapter.ts"],"names":["GatewayIntentBits","BasePlatformAdapter","Client","Events","DiscordAPIError"],"mappings":";;;;;;AA2BO,IAAM,uBAAA,GAA4D;AAAA,EACvEA,4BAAA,CAAkB,MAAA;AAAA,EAClBA,4BAAA,CAAkB,aAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB;AACpB,CAAA;AAEA,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,kBAAA,GAAqB,IAAA;AAEpB,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,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,MAAM,OAAA,GAAW,KAAK,OAAA,IAAW,uBAAA;AACjC,IAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,MAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,QACb;AAAA,OACF;AAAA,IACF;AACA,IAAA,IAAA,CAAK,MAAA,G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O,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,cAAA,EAAgB,OAAA,EAAS,GAAA,CAAI,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","file":"index.cjs","sourcesContent":["/**\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 { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nexport interface DiscordAdapterOptions {\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\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\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 = splitForDiscord(out.text);\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 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 await 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\nfunction splitForDiscord(text: string): string[] {\n if (text.length <= DISCORD_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_DISCORD_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_DISCORD_CHUNK);\n if (boundary < SAFE_DISCORD_CHUNK / 2) {\n boundary = remaining.lastIndexOf(\"\\n\", SAFE_DISCORD_CHUNK);\n }\n if (boundary < SAFE_DISCORD_CHUNK / 2) boundary = SAFE_DISCORD_CHUNK;\n parts.push(remaining.slice(0, boundary));\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return 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"]}
@@ -0,0 +1,50 @@
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
2
+ import { GatewayIntentBits, Client } from 'discord.js';
3
+
4
+ /**
5
+ * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`
6
+ * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).
7
+ *
8
+ * - `connect()` calls `client.login(token)` and awaits the `ready` event.
9
+ * - WebSocket Gateway only (D179) — no webhook variant in v0.1.
10
+ * - Default intents include `MessageContent` (EC-C silent-failure guard).
11
+ * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).
12
+ * - 2000-char message split (Discord's hard limit).
13
+ *
14
+ * @public
15
+ */
16
+
17
+ interface DiscordAdapterOptions {
18
+ readonly token: string;
19
+ /**
20
+ * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,
21
+ * DirectMessageReactions]. Without MessageContent the bot receives
22
+ * empty `msg.content` (EC-C silent failure).
23
+ */
24
+ readonly intents?: GatewayIntentBits[];
25
+ }
26
+ declare class DiscordAdapter extends BasePlatformAdapter {
27
+ readonly platform: "discord";
28
+ private readonly client;
29
+ private readonly token;
30
+ private handler?;
31
+ private connected;
32
+ constructor(opts: DiscordAdapterOptions);
33
+ connect(): Promise<boolean>;
34
+ disconnect(): Promise<void>;
35
+ /**
36
+ * Expose the underlying discord.js `Client` so consumers can register
37
+ * platform-specific events that don't fit the portable contract —
38
+ * `interactionCreate` (slash commands via Application Commands),
39
+ * `error` event boundary, presence updates, etc. Register BEFORE
40
+ * calling `runner.start()`.
41
+ *
42
+ * @public
43
+ */
44
+ getBot(): Client;
45
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
46
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
47
+ private handleInbound;
48
+ }
49
+
50
+ export { DiscordAdapter, type DiscordAdapterOptions };
@@ -0,0 +1,50 @@
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
2
+ import { GatewayIntentBits, Client } from 'discord.js';
3
+
4
+ /**
5
+ * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`
6
+ * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).
7
+ *
8
+ * - `connect()` calls `client.login(token)` and awaits the `ready` event.
9
+ * - WebSocket Gateway only (D179) — no webhook variant in v0.1.
10
+ * - Default intents include `MessageContent` (EC-C silent-failure guard).
11
+ * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).
12
+ * - 2000-char message split (Discord's hard limit).
13
+ *
14
+ * @public
15
+ */
16
+
17
+ interface DiscordAdapterOptions {
18
+ readonly token: string;
19
+ /**
20
+ * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,
21
+ * DirectMessageReactions]. Without MessageContent the bot receives
22
+ * empty `msg.content` (EC-C silent failure).
23
+ */
24
+ readonly intents?: GatewayIntentBits[];
25
+ }
26
+ declare class DiscordAdapter extends BasePlatformAdapter {
27
+ readonly platform: "discord";
28
+ private readonly client;
29
+ private readonly token;
30
+ private handler?;
31
+ private connected;
32
+ constructor(opts: DiscordAdapterOptions);
33
+ connect(): Promise<boolean>;
34
+ disconnect(): Promise<void>;
35
+ /**
36
+ * Expose the underlying discord.js `Client` so consumers can register
37
+ * platform-specific events that don't fit the portable contract —
38
+ * `interactionCreate` (slash commands via Application Commands),
39
+ * `error` event boundary, presence updates, etc. Register BEFORE
40
+ * calling `runner.start()`.
41
+ *
42
+ * @public
43
+ */
44
+ getBot(): Client;
45
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
46
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
47
+ private handleInbound;
48
+ }
49
+
50
+ export { DiscordAdapter, type DiscordAdapterOptions };
package/dist/index.js ADDED
@@ -0,0 +1,194 @@
1
+ import { BasePlatformAdapter } from '@theokit/gateway';
2
+ import { GatewayIntentBits, Client, Events, DiscordAPIError } from 'discord.js';
3
+
4
+ // src/adapter.ts
5
+ var DEFAULT_DISCORD_INTENTS = [
6
+ GatewayIntentBits.Guilds,
7
+ GatewayIntentBits.GuildMessages,
8
+ GatewayIntentBits.MessageContent,
9
+ GatewayIntentBits.DirectMessages,
10
+ GatewayIntentBits.DirectMessageReactions
11
+ ];
12
+ var DISCORD_MAX_MESSAGE = 2e3;
13
+ var SAFE_DISCORD_CHUNK = 1900;
14
+ var DiscordAdapter = class extends BasePlatformAdapter {
15
+ platform = "discord";
16
+ client;
17
+ token;
18
+ handler;
19
+ connected = false;
20
+ constructor(opts) {
21
+ super();
22
+ this.token = opts.token;
23
+ const intents = opts.intents ?? DEFAULT_DISCORD_INTENTS;
24
+ if (intents.length === 0) {
25
+ process.stderr.write(
26
+ "[discord] WARN \u2014 intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\n"
27
+ );
28
+ }
29
+ this.client = new Client({ intents });
30
+ this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));
31
+ this.client.on(Events.Error, (err) => {
32
+ process.stderr.write(`[discord] client error: ${err.message}
33
+ `);
34
+ });
35
+ }
36
+ async connect() {
37
+ if (this.connected) return true;
38
+ try {
39
+ await new Promise((resolve, reject) => {
40
+ this.client.once(Events.ClientReady, () => resolve());
41
+ this.client.login(this.token).catch(reject);
42
+ });
43
+ this.connected = true;
44
+ return true;
45
+ } catch (err) {
46
+ process.stderr.write(`[discord] connect failed: ${err.message}
47
+ `);
48
+ return false;
49
+ }
50
+ }
51
+ async disconnect() {
52
+ if (!this.connected) return;
53
+ this.connected = false;
54
+ try {
55
+ await this.client.destroy();
56
+ } catch {
57
+ }
58
+ }
59
+ /**
60
+ * Expose the underlying discord.js `Client` so consumers can register
61
+ * platform-specific events that don't fit the portable contract —
62
+ * `interactionCreate` (slash commands via Application Commands),
63
+ * `error` event boundary, presence updates, etc. Register BEFORE
64
+ * calling `runner.start()`.
65
+ *
66
+ * @public
67
+ */
68
+ getBot() {
69
+ return this.client;
70
+ }
71
+ async sendMessage(out) {
72
+ if (out.text.length === 0) {
73
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
74
+ }
75
+ let channel;
76
+ try {
77
+ channel = await this.client.channels.fetch(out.channel.id);
78
+ } catch (err) {
79
+ return {
80
+ ok: false,
81
+ error: { code: "channel_fetch_failed", message: err.message }
82
+ };
83
+ }
84
+ const sendable = channel;
85
+ if (sendable === null || typeof sendable.send !== "function") {
86
+ return {
87
+ ok: false,
88
+ error: {
89
+ code: "channel_not_sendable",
90
+ message: `channel "${out.channel.id}" not text-based or missing`
91
+ }
92
+ };
93
+ }
94
+ const chunks = splitForDiscord(out.text);
95
+ let lastId;
96
+ for (const chunk of chunks) {
97
+ try {
98
+ const msg = await sendable.send({
99
+ content: chunk,
100
+ ...out.replyTo !== void 0 ? { reply: { messageReference: out.replyTo } } : {}
101
+ });
102
+ lastId = msg.id;
103
+ } catch (err) {
104
+ return mapSendError(err);
105
+ }
106
+ }
107
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
108
+ }
109
+ onInbound(handler) {
110
+ this.handler = handler;
111
+ return () => {
112
+ if (this.handler === handler) this.handler = void 0;
113
+ };
114
+ }
115
+ async handleInbound(msg) {
116
+ if (this.handler === void 0) return;
117
+ if (msg.author.bot) return;
118
+ const event = normalizeEvent(msg);
119
+ await this.handler(event);
120
+ }
121
+ };
122
+ function normalizeEvent(msg) {
123
+ let channelType;
124
+ if (msg.guildId === null) {
125
+ channelType = "dm";
126
+ } else if (msg.channel.isThread()) {
127
+ channelType = "thread";
128
+ } else {
129
+ channelType = "group";
130
+ }
131
+ const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;
132
+ return {
133
+ id: `dc-${msg.channelId}-${msg.id}`,
134
+ platform: "discord",
135
+ sender: {
136
+ id: msg.author.id,
137
+ username: msg.author.username,
138
+ displayName
139
+ },
140
+ channel: {
141
+ id: msg.channelId,
142
+ type: channelType,
143
+ ...msg.channel.isThread() ? { topicId: msg.channel.id } : {}
144
+ },
145
+ text: msg.content,
146
+ receivedAt: msg.createdTimestamp,
147
+ ...msg.reference?.messageId !== void 0 ? { replyTo: msg.reference.messageId } : {},
148
+ discord: {
149
+ guildId: msg.guildId,
150
+ channelId: msg.channelId,
151
+ messageId: msg.id,
152
+ raw: msg
153
+ }
154
+ };
155
+ }
156
+ function splitForDiscord(text) {
157
+ if (text.length <= DISCORD_MAX_MESSAGE) return [text];
158
+ const parts = [];
159
+ let remaining = text;
160
+ while (remaining.length > 0) {
161
+ if (remaining.length <= SAFE_DISCORD_CHUNK) {
162
+ parts.push(remaining);
163
+ break;
164
+ }
165
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_DISCORD_CHUNK);
166
+ if (boundary < SAFE_DISCORD_CHUNK / 2) {
167
+ boundary = remaining.lastIndexOf("\n", SAFE_DISCORD_CHUNK);
168
+ }
169
+ if (boundary < SAFE_DISCORD_CHUNK / 2) boundary = SAFE_DISCORD_CHUNK;
170
+ parts.push(remaining.slice(0, boundary));
171
+ remaining = remaining.slice(boundary).replace(/^\n+/, "");
172
+ }
173
+ return parts;
174
+ }
175
+ function mapSendError(err) {
176
+ if (err instanceof DiscordAPIError) {
177
+ const codeStr = String(err.code);
178
+ if (codeStr === "50007") {
179
+ return { ok: false, error: { code: "dm_blocked", message: err.message } };
180
+ }
181
+ if (codeStr === "50001" || codeStr === "50013") {
182
+ return { ok: false, error: { code: "no_permission", message: err.message } };
183
+ }
184
+ if (err.status === 429) {
185
+ return { ok: false, error: { code: "rate_limited", message: err.message } };
186
+ }
187
+ return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };
188
+ }
189
+ return { ok: false, error: { code: "unknown", message: err.message } };
190
+ }
191
+
192
+ export { DiscordAdapter };
193
+ //# sourceMappingURL=index.js.map
194
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapter.ts"],"names":[],"mappings":";;;;AA2BO,IAAM,uBAAA,GAA4D;AAAA,EACvE,iBAAA,CAAkB,MAAA;AAAA,EAClB,iBAAA,CAAkB,aAAA;AAAA,EAClB,iBAAA,CAAkB,cAAA;AAAA,EAClB,iBAAA,CAAkB,cAAA;AAAA,EAClB,iBAAA,CAAkB;AACpB,CAAA;AAEA,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,kBAAA,GAAqB,IAAA;AAEpB,IAAM,cAAA,GAAN,cAA6B,mBAAA,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,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,MAAM,OAAA,GAAW,KAAK,OAAA,IAAW,uBAAA;AACjC,IAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,MAAA,OAA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E;AAAA,IAC7E;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,GAAA,EAAK;AACtB,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,cAAA,EAAgB,OAAA,EAAS,GAAA,CAAI,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","file":"index.js","sourcesContent":["/**\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 { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nexport interface DiscordAdapterOptions {\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\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\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 = splitForDiscord(out.text);\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 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 await 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\nfunction splitForDiscord(text: string): string[] {\n if (text.length <= DISCORD_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_DISCORD_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_DISCORD_CHUNK);\n if (boundary < SAFE_DISCORD_CHUNK / 2) {\n boundary = remaining.lastIndexOf(\"\\n\", SAFE_DISCORD_CHUNK);\n }\n if (boundary < SAFE_DISCORD_CHUNK / 2) boundary = SAFE_DISCORD_CHUNK;\n parts.push(remaining.slice(0, boundary));\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return 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"]}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@theokit/gateway-discord",
3
+ "version": "0.1.0",
4
+ "description": "Discord (discord.js) platform adapter for @theokit/gateway. ADRs D171, D179.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.12.0"
9
+ },
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "require": {
20
+ "types": "./dist/index.d.cts",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsup",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "vitest run"
35
+ },
36
+ "peerDependencies": {
37
+ "@theokit/gateway": "workspace:^",
38
+ "@theokit/sdk": "workspace:^",
39
+ "discord.js": "^14.16.0"
40
+ },
41
+ "devDependencies": {
42
+ "@theokit/gateway": "workspace:*",
43
+ "@theokit/sdk": "workspace:*",
44
+ "discord.js": "^14.16.0",
45
+ "tsup": "^8.5.0",
46
+ "typescript": "^5.8.0",
47
+ "vitest": "^3.0.0"
48
+ }
49
+ }