@theokit/gateway-mattermost 0.3.0 → 0.4.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 +35 -0
- package/README.md +20 -0
- package/dist/index.cjs +98 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +40 -1
- package/dist/index.d.ts +40 -1
- package/dist/index.js +99 -4
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- bc799e9: Export `matrixChannel`, `mattermostChannel` and `emailChannel`: `ChannelDescriptor`s with `MATRIX_*`, `MATTERMOST_*` and `EMAIL_*` environment bindings for `createChannels` and `configFromEnv`. The peer range on `@theokit/gateway` is now `>=0.21.0`.
|
|
8
|
+
|
|
9
|
+
## 0.3.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
|
|
14
|
+
|
|
15
|
+
`@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
|
|
16
|
+
`filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
|
|
17
|
+
carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
|
|
18
|
+
`supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
|
|
19
|
+
field. The runner and the router refuse an outbound carrying attachments as
|
|
20
|
+
`attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
|
|
21
|
+
`supportsAttachments`.
|
|
22
|
+
|
|
23
|
+
`@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
|
|
24
|
+
`sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
|
|
25
|
+
when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
|
|
26
|
+
than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
|
|
27
|
+
|
|
28
|
+
Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
|
|
29
|
+
with `attachments_unsupported` and makes no platform call, instead of sending the text and
|
|
30
|
+
dropping the image.
|
|
31
|
+
|
|
32
|
+
The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
|
|
33
|
+
throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
|
|
34
|
+
as a handler error is. Dispatch still does not throw.
|
|
35
|
+
|
|
36
|
+
- 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.
|
|
37
|
+
|
|
3
38
|
## 0.3.0
|
|
4
39
|
|
|
5
40
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -91,6 +91,26 @@ Override with `requireMention: false` to make the bot respond to every message i
|
|
|
91
91
|
| Slash command incoming webhooks | Not supported v0.1 | — |
|
|
92
92
|
| Ephemeral / hidden messages | Not supported v0.1 | — |
|
|
93
93
|
|
|
94
|
+
## Channel descriptor
|
|
95
|
+
|
|
96
|
+
`mattermostChannel` describes the channel as data for `createChannels` and `configFromEnv` from `@theokit/gateway`. Its transport is `socket`.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { configFromEnv, createChannels } from "@theokit/gateway";
|
|
100
|
+
import { mattermostChannel } from "@theokit/gateway-mattermost";
|
|
101
|
+
|
|
102
|
+
const { config, missing, secrets } = configFromEnv(mattermostChannel, process.env, "APP_");
|
|
103
|
+
const { adapters, rejected } = createChannels([{ descriptor: mattermostChannel, config, envPrefix: "APP_" }]);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Config key | Env name | Required | Secret |
|
|
107
|
+
| --- | --- | --- | --- |
|
|
108
|
+
| `baseUrl` | `MATTERMOST_BASE_URL` | yes | no |
|
|
109
|
+
| `accessToken` | `MATTERMOST_ACCESS_TOKEN` | yes | yes |
|
|
110
|
+
| `requireMention` | `MATTERMOST_REQUIRE_MENTION` | no | no |
|
|
111
|
+
|
|
112
|
+
The `APP_` prefix is the app's choice. A value of the wrong type throws `invalid_config` naming the key; a list may be an array or a comma-separated string, a boolean `true`/`false` or the same strings, a number a number or a digit string.
|
|
113
|
+
|
|
94
114
|
## ADRs
|
|
95
115
|
|
|
96
116
|
D397 – D404 in `.claude/knowledge-base/adrs/`.
|
package/dist/index.cjs
CHANGED
|
@@ -23,7 +23,10 @@ var SDKNotInstalledError = class extends ConfigurationError {
|
|
|
23
23
|
async function loadMattermost() {
|
|
24
24
|
try {
|
|
25
25
|
const mod = await import('@mattermost/client');
|
|
26
|
-
return
|
|
26
|
+
return {
|
|
27
|
+
Client4: mod.Client4 ?? mod.default?.Client4,
|
|
28
|
+
WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient
|
|
29
|
+
};
|
|
27
30
|
} catch {
|
|
28
31
|
throw new SDKNotInstalledError("@mattermost/client");
|
|
29
32
|
}
|
|
@@ -122,12 +125,25 @@ function postToMessageEvent(post, channel, senderUsername) {
|
|
|
122
125
|
}
|
|
123
126
|
};
|
|
124
127
|
}
|
|
128
|
+
|
|
129
|
+
// src/refuse-attachments.ts
|
|
130
|
+
function refuseAttachments(out) {
|
|
131
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
132
|
+
return {
|
|
133
|
+
ok: false,
|
|
134
|
+
error: {
|
|
135
|
+
code: "attachments_unsupported",
|
|
136
|
+
message: "mattermost adapter cannot send attachments"
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
125
140
|
var MATTERMOST_MAX_POST = 16383;
|
|
126
141
|
var SAFE_CHUNK = 16e3;
|
|
127
142
|
var BOUNDARIES = {
|
|
128
143
|
boundaries: ["\n\n", "\n", " "],
|
|
129
144
|
lastResort: "last-boundary",
|
|
130
|
-
stripLeading: /^\s
|
|
145
|
+
stripLeading: /^\s+/,
|
|
146
|
+
keepTableRows: true
|
|
131
147
|
};
|
|
132
148
|
function splitForMattermost(text) {
|
|
133
149
|
return gateway.chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });
|
|
@@ -193,6 +209,9 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
193
209
|
this.inboundHandler = void 0;
|
|
194
210
|
}
|
|
195
211
|
async sendMessage(out) {
|
|
212
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
213
|
+
}
|
|
214
|
+
async sendText(out) {
|
|
196
215
|
if (out.text.length === 0) {
|
|
197
216
|
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
198
217
|
}
|
|
@@ -227,6 +246,9 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
227
246
|
* with no request, so an edit is refused for exactly the texts a send delivers as several posts.
|
|
228
247
|
*/
|
|
229
248
|
async editMessage(messageId, out) {
|
|
249
|
+
return refuseAttachments(out) ?? this.editText(messageId, out);
|
|
250
|
+
}
|
|
251
|
+
async editText(messageId, out) {
|
|
230
252
|
if (out.text.length === 0) {
|
|
231
253
|
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
232
254
|
}
|
|
@@ -306,8 +328,27 @@ var MattermostAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
306
328
|
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
307
329
|
*/
|
|
308
330
|
async deliver(event) {
|
|
331
|
+
if (!this.passesMentionGate(event)) return "ok";
|
|
309
332
|
return this.runHandler(this.inboundHandler, event);
|
|
310
333
|
}
|
|
334
|
+
/**
|
|
335
|
+
* The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
|
|
336
|
+
*
|
|
337
|
+
* Needs the bot identity from a live connection and the raw post on the event; when either is
|
|
338
|
+
* missing there is nothing to judge by, so the event passes as it did before.
|
|
339
|
+
*/
|
|
340
|
+
passesMentionGate(event) {
|
|
341
|
+
const handle = this.handle;
|
|
342
|
+
const mm = event.mattermost;
|
|
343
|
+
if (handle === void 0 || mm?.raw === void 0) return true;
|
|
344
|
+
return shouldRespond({
|
|
345
|
+
post: mm.raw,
|
|
346
|
+
channelType: event.channel.type === "thread" ? "thread" : event.channel.type === "dm" ? "dm" : "group",
|
|
347
|
+
botUserId: handle.botUserId,
|
|
348
|
+
botUsername: handle.botUsername,
|
|
349
|
+
requireMention: this.opts.requireMention ?? true
|
|
350
|
+
});
|
|
351
|
+
}
|
|
311
352
|
};
|
|
312
353
|
function parsePostFromWS(msg) {
|
|
313
354
|
const raw = msg.data?.post;
|
|
@@ -385,6 +426,60 @@ function mapMattermostError(err) {
|
|
|
385
426
|
function escapeMarkdown(text) {
|
|
386
427
|
return text.replace(/([\\*_`~])/g, "\\$1");
|
|
387
428
|
}
|
|
429
|
+
var readers = gateway.channelConfigReaders(
|
|
430
|
+
"gateway-mattermost",
|
|
431
|
+
(options) => new ConfigurationError(options)
|
|
432
|
+
);
|
|
433
|
+
var { invalid } = readers;
|
|
434
|
+
var read = {
|
|
435
|
+
string: readers.requiredString,
|
|
436
|
+
boolean(config, key) {
|
|
437
|
+
const value = config[key];
|
|
438
|
+
if (value === void 0) return void 0;
|
|
439
|
+
if (value === true || value === "true") return true;
|
|
440
|
+
if (value === false || value === "false") return false;
|
|
441
|
+
throw invalid(key, 'a boolean or the string "true" or "false"');
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
var CONFIG = [
|
|
445
|
+
{
|
|
446
|
+
key: "baseUrl",
|
|
447
|
+
required: true,
|
|
448
|
+
secret: false,
|
|
449
|
+
description: "Base URL of the Mattermost server, e.g. https://mattermost.example.org.",
|
|
450
|
+
env: "MATTERMOST_BASE_URL"
|
|
451
|
+
},
|
|
452
|
+
{
|
|
453
|
+
key: "accessToken",
|
|
454
|
+
required: true,
|
|
455
|
+
secret: true,
|
|
456
|
+
description: "Personal access token or bot token.",
|
|
457
|
+
env: "MATTERMOST_ACCESS_TOKEN"
|
|
458
|
+
},
|
|
459
|
+
{
|
|
460
|
+
key: "requireMention",
|
|
461
|
+
required: false,
|
|
462
|
+
secret: false,
|
|
463
|
+
description: "When true, channel messages reach the handler only if they mention the bot.",
|
|
464
|
+
env: "MATTERMOST_REQUIRE_MENTION"
|
|
465
|
+
}
|
|
466
|
+
];
|
|
467
|
+
var mattermostChannel = {
|
|
468
|
+
platform: "mattermost",
|
|
469
|
+
transport: "socket",
|
|
470
|
+
senderIdentity: "authenticated",
|
|
471
|
+
config: CONFIG,
|
|
472
|
+
create(config) {
|
|
473
|
+
const baseUrl = read.string(config, "baseUrl");
|
|
474
|
+
const accessToken = read.string(config, "accessToken");
|
|
475
|
+
const requireMention = read.boolean(config, "requireMention");
|
|
476
|
+
return new MattermostAdapter({
|
|
477
|
+
baseUrl,
|
|
478
|
+
accessToken,
|
|
479
|
+
...requireMention === void 0 ? {} : { requireMention }
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
};
|
|
388
483
|
|
|
389
484
|
exports.ConfigurationError = ConfigurationError;
|
|
390
485
|
exports.MattermostAdapter = MattermostAdapter;
|
|
@@ -393,6 +488,7 @@ exports.connectMattermost = connectMattermost;
|
|
|
393
488
|
exports.getChannelCached = getChannelCached;
|
|
394
489
|
exports.hasMentionWithBoundary = hasMentionWithBoundary;
|
|
395
490
|
exports.mapChannelType = mapChannelType;
|
|
491
|
+
exports.mattermostChannel = mattermostChannel;
|
|
396
492
|
exports.normalizeMattermostType = normalizeMattermostType;
|
|
397
493
|
exports.parsePostFromWS = parsePostFromWS;
|
|
398
494
|
exports.postToMessageEvent = postToMessageEvent;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.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GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,cAAc,OAAA,EAAS,CAAA,CAAE,WAAW,uBAAA;AAAwB,KAC7E;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,mBAAA;AAAA,QACN,OAAA,EAAS,EAAE,OAAA,IAAW;AAAA;AACxB,KACF;AAAA,EACF;AACA,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */\n patchPost(patch: { id: string; message: string }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = await import(\"@mattermost/client\");\n return mod as unknown as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nexport const MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n} as const;\n\n/**\n * Split `text` into posts that fit Mattermost's post cap.\n *\n * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a\n * 16000-character window at a blank line, a newline or a space, in that order of\n * preference.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order, each with leading whitespace stripped at the cut.\n */\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });\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 8191 characters fits\n * one post once escaped. The adapter calls this only for a part whose escaped body passed the cap,\n * so the parts of an ordinary text are the ones `splitForMattermost` returns.\n */\nexport function splitForEscapedMattermost(text: string): string[] {\n return chunkText(text, {\n limit: Math.floor(MATTERMOST_MAX_POST / 2),\n safeLimit: SAFE_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { MATTERMOST_MAX_POST, splitForEscapedMattermost, splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n for (const message of renderPosts(out)) {\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n /** Mattermost edits a sent post's text through `Client4.patchPost`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a post this bot sent, through `patchPost({ id, message })`.\n *\n * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and\n * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all\n * with no request, so an edit is refused for exactly the texts a send delivers as several posts.\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: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const posts = renderPosts(out);\n if (posts.length !== 1) return editPartsRefusal(posts.length);\n const message = posts[0] as string;\n try {\n await this.handle.client.patchPost({ id: messageId, message });\n } catch (err) {\n return mapMattermostError(err);\n }\n return { ok: true, messageId };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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.inboundHandler, event);\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\n/**\n * The refusal for a text that is not exactly one Mattermost post.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since\n * `splitForMattermost` returns at least one part for any non-empty text and empty text is refused\n * earlier; the arm 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} Mattermost posts; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\n/**\n * The post bodies a text goes out as, each within `MATTERMOST_MAX_POST`.\n *\n * Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the case that needs\n * work, because raw text would be parsed anyway. Split first, escape per part, the ordering Discord\n * needs for the same reason: a cut between a backslash and its character produces a stray\n * backslash in one post and a bare marker in the next. The splitter measures the caller's text,\n * and escaping can double a part, so a part whose escaped body passes the cap is split again at\n * half the cap, which every escaped body fits. `sendMessage` and `editMessage` both send what this\n * returns.\n */\nfunction renderPosts(out: OutboundMessage): string[] {\n if (out.format !== \"plain\") return splitForMattermost(out.text);\n return splitForMattermost(out.text).flatMap((part) => {\n const escaped = escapeMarkdown(part);\n if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];\n return splitForEscapedMattermost(part).map(escapeMarkdown);\n });\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts"],"names":["GatewayConfigurationError","chunkText","BasePlatformAdapter","channelConfigReaders"],"mappings":";;;;;AAoBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,8BAAA,EAAiC,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MAC1F,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACCA,eAAe,cAAA,GAA4C;AACzD,E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U,IAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa,yEAAA;AAAA,IACb,GAAA,EAAK;AAAA,GACP;AAAA,EACA;AAAA,IACE,GAAA,EAAK,aAAA;AAAA,IACL,QAAA,EAAU,IAAA;AAAA,IACV,MAAA,EAAQ,IAAA;AAAA,IACR,WAAA,EAAa,qCAAA;AAAA,IACb,GAAA,EAAK;AAAA,GACP;AAAA,EACA;AAAA,IACE,GAAA,EAAK,gBAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa,6EAAA;AAAA,IACb,GAAA,EAAK;AAAA;AAET,CAAA;AASO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,QAAA,EAAU,YAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAA8D;AACnE,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,SAAS,CAAA;AAC7C,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,aAAa,CAAA;AACrD,IAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,gBAAgB,CAAA;AAC5D,IAAA,OAAO,IAAI,iBAAA,CAAkB;AAAA,MAC3B,OAAA;AAAA,MACA,WAAA;AAAA,MACA,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA;AAAe,KAC1D,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */\n patchPost(patch: { id: string; message: string }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = (await import(\"@mattermost/client\")) as unknown as Partial<MattermostModule> & {\n default?: MattermostModule;\n };\n // Node's CommonJS namespace does not expose the SDK's getter-defined exports.\n return {\n Client4: mod.Client4 ?? mod.default?.Client4,\n WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient,\n } as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\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: {\n code: \"attachments_unsupported\",\n message: \"mattermost adapter cannot send attachments\",\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nexport const MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into posts that fit Mattermost's post cap.\n *\n * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a\n * 16000-character window at a blank line, a newline or a space, in that order of\n * preference.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order, each with leading whitespace stripped at the cut.\n */\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });\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 8191 characters fits\n * one post once escaped. The adapter calls this only for a part whose escaped body passed the cap,\n * so the parts of an ordinary text are the ones `splitForMattermost` returns.\n */\nexport function splitForEscapedMattermost(text: string): string[] {\n return chunkText(text, {\n limit: Math.floor(MATTERMOST_MAX_POST / 2),\n safeLimit: SAFE_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { MATTERMOST_MAX_POST, splitForEscapedMattermost, splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n 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: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n for (const message of renderPosts(out)) {\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n /** Mattermost edits a sent post's text through `Client4.patchPost`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a post this bot sent, through `patchPost({ id, message })`.\n *\n * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and\n * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all\n * with no request, so an edit is refused for exactly the texts a send delivers as several posts.\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: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const posts = renderPosts(out);\n if (posts.length !== 1) return editPartsRefusal(posts.length);\n const message = posts[0] as string;\n try {\n await this.handle.client.patchPost({ id: messageId, message });\n } catch (err) {\n return mapMattermostError(err);\n }\n return { ok: true, messageId };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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 if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.inboundHandler, event);\n }\n\n /**\n * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.\n *\n * Needs the bot identity from a live connection and the raw post on the event; when either is\n * missing there is nothing to judge by, so the event passes as it did before.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n const handle = this.handle;\n const mm = (event as { mattermost?: { raw?: MattermostPost } }).mattermost;\n if (handle === undefined || mm?.raw === undefined) return true;\n return shouldRespond({\n post: mm.raw,\n channelType:\n event.channel.type === \"thread\" ? \"thread\" : event.channel.type === \"dm\" ? \"dm\" : \"group\",\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention: this.opts.requireMention ?? true,\n });\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\n/**\n * The refusal for a text that is not exactly one Mattermost post.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since\n * `splitForMattermost` returns at least one part for any non-empty text and empty text is refused\n * earlier; the arm 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} Mattermost posts; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\n/**\n * The post bodies a text goes out as, each within `MATTERMOST_MAX_POST`.\n *\n * Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the case that needs\n * work, because raw text would be parsed anyway. Split first, escape per part, the ordering Discord\n * needs for the same reason: a cut between a backslash and its character produces a stray\n * backslash in one post and a bare marker in the next. The splitter measures the caller's text,\n * and escaping can double a part, so a part whose escaped body passes the cap is split again at\n * half the cap, which every escaped body fits. `sendMessage` and `editMessage` both send what this\n * returns.\n */\nfunction renderPosts(out: OutboundMessage): string[] {\n if (out.format !== \"plain\") return splitForMattermost(out.text);\n return splitForMattermost(out.text).flatMap((part) => {\n const escaped = escapeMarkdown(part);\n if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];\n return splitForEscapedMattermost(part).map(escapeMarkdown);\n });\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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","/**\n * `mattermostChannel` — the Mattermost channel described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration\n * package's typecheck is where a drift between the two fails.\n */\n\nimport { channelConfigReaders } from \"@theokit/gateway\";\nimport { MattermostAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nconst readers = channelConfigReaders(\n \"gateway-mattermost\",\n (options) => new ConfigurationError(options),\n);\nconst { invalid } = readers;\n\ntype Config = Readonly<Record<string, unknown>>;\n\n/** Readers for values that may arrive as env strings; only `undefined` is absent. */\nconst read = {\n string: readers.requiredString,\n boolean(config: Config, key: string): boolean | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (value === true || value === \"true\") return true;\n if (value === false || value === \"false\") return false;\n throw invalid(key, 'a boolean or the string \"true\" or \"false\"');\n },\n};\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"baseUrl\",\n required: true,\n secret: false,\n description: \"Base URL of the Mattermost server, e.g. https://mattermost.example.org.\",\n env: \"MATTERMOST_BASE_URL\",\n },\n {\n key: \"accessToken\",\n required: true,\n secret: true,\n description: \"Personal access token or bot token.\",\n env: \"MATTERMOST_ACCESS_TOKEN\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"When true, channel messages reach the handler only if they mention the bot.\",\n env: \"MATTERMOST_REQUIRE_MENTION\",\n },\n];\n\n/**\n * The Mattermost channel: a WebSocket the adapter opens itself, so it needs no webhook route.\n *\n * `create` validates each value with this package's `ConfigurationError` and makes no network call.\n *\n * @public\n */\nexport const mattermostChannel = {\n platform: \"mattermost\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): MattermostAdapter {\n const baseUrl = read.string(config, \"baseUrl\");\n const accessToken = read.string(config, \"accessToken\");\n const requireMention = read.boolean(config, \"requireMention\");\n return new MattermostAdapter({\n baseUrl,\n accessToken,\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -159,6 +159,7 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
159
159
|
connect(): Promise<boolean>;
|
|
160
160
|
disconnect(): Promise<void>;
|
|
161
161
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
162
|
+
private sendText;
|
|
162
163
|
/** Mattermost edits a sent post's text through `Client4.patchPost`. */
|
|
163
164
|
readonly supportsEdit = true;
|
|
164
165
|
/**
|
|
@@ -169,6 +170,7 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
169
170
|
* with no request, so an edit is refused for exactly the texts a send delivers as several posts.
|
|
170
171
|
*/
|
|
171
172
|
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
173
|
+
private editText;
|
|
172
174
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
173
175
|
/** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */
|
|
174
176
|
getClient(): MattermostClientHandle | undefined;
|
|
@@ -181,6 +183,13 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
181
183
|
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
182
184
|
*/
|
|
183
185
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
186
|
+
/**
|
|
187
|
+
* The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
|
|
188
|
+
*
|
|
189
|
+
* Needs the bot identity from a live connection and the raw post on the event; when either is
|
|
190
|
+
* missing there is nothing to judge by, so the event passes as it did before.
|
|
191
|
+
*/
|
|
192
|
+
private passesMentionGate;
|
|
184
193
|
}
|
|
185
194
|
/**
|
|
186
195
|
* Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.
|
|
@@ -189,6 +198,36 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
189
198
|
*/
|
|
190
199
|
declare function parsePostFromWS(msg: WSMessage): MattermostPost | undefined;
|
|
191
200
|
|
|
201
|
+
/**
|
|
202
|
+
* `mattermostChannel` — the Mattermost channel described as data.
|
|
203
|
+
*
|
|
204
|
+
* Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration
|
|
205
|
+
* package's typecheck is where a drift between the two fails.
|
|
206
|
+
*/
|
|
207
|
+
|
|
208
|
+
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
|
|
209
|
+
interface ConfigField {
|
|
210
|
+
readonly key: string;
|
|
211
|
+
readonly required: boolean;
|
|
212
|
+
readonly secret: boolean;
|
|
213
|
+
readonly description: string;
|
|
214
|
+
readonly env?: string;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The Mattermost channel: a WebSocket the adapter opens itself, so it needs no webhook route.
|
|
218
|
+
*
|
|
219
|
+
* `create` validates each value with this package's `ConfigurationError` and makes no network call.
|
|
220
|
+
*
|
|
221
|
+
* @public
|
|
222
|
+
*/
|
|
223
|
+
declare const mattermostChannel: {
|
|
224
|
+
platform: "mattermost";
|
|
225
|
+
transport: "socket";
|
|
226
|
+
senderIdentity: "authenticated";
|
|
227
|
+
config: readonly ConfigField[];
|
|
228
|
+
create(config: Readonly<Record<string, unknown>>): MattermostAdapter;
|
|
229
|
+
};
|
|
230
|
+
|
|
192
231
|
/**
|
|
193
232
|
* Typed errors for `@theokit/gateway-mattermost`.
|
|
194
233
|
*
|
|
@@ -302,4 +341,4 @@ declare function postToMessageEvent(post: MattermostPost, channel: MattermostCha
|
|
|
302
341
|
*/
|
|
303
342
|
declare function splitForMattermost(text: string): string[];
|
|
304
343
|
|
|
305
|
-
export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
|
|
344
|
+
export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, mattermostChannel, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
|
package/dist/index.d.ts
CHANGED
|
@@ -159,6 +159,7 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
159
159
|
connect(): Promise<boolean>;
|
|
160
160
|
disconnect(): Promise<void>;
|
|
161
161
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
162
|
+
private sendText;
|
|
162
163
|
/** Mattermost edits a sent post's text through `Client4.patchPost`. */
|
|
163
164
|
readonly supportsEdit = true;
|
|
164
165
|
/**
|
|
@@ -169,6 +170,7 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
169
170
|
* with no request, so an edit is refused for exactly the texts a send delivers as several posts.
|
|
170
171
|
*/
|
|
171
172
|
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
173
|
+
private editText;
|
|
172
174
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
173
175
|
/** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */
|
|
174
176
|
getClient(): MattermostClientHandle | undefined;
|
|
@@ -181,6 +183,13 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
181
183
|
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
182
184
|
*/
|
|
183
185
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
186
|
+
/**
|
|
187
|
+
* The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
|
|
188
|
+
*
|
|
189
|
+
* Needs the bot identity from a live connection and the raw post on the event; when either is
|
|
190
|
+
* missing there is nothing to judge by, so the event passes as it did before.
|
|
191
|
+
*/
|
|
192
|
+
private passesMentionGate;
|
|
184
193
|
}
|
|
185
194
|
/**
|
|
186
195
|
* Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.
|
|
@@ -189,6 +198,36 @@ declare class MattermostAdapter extends BasePlatformAdapter {
|
|
|
189
198
|
*/
|
|
190
199
|
declare function parsePostFromWS(msg: WSMessage): MattermostPost | undefined;
|
|
191
200
|
|
|
201
|
+
/**
|
|
202
|
+
* `mattermostChannel` — the Mattermost channel described as data.
|
|
203
|
+
*
|
|
204
|
+
* Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration
|
|
205
|
+
* package's typecheck is where a drift between the two fails.
|
|
206
|
+
*/
|
|
207
|
+
|
|
208
|
+
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
|
|
209
|
+
interface ConfigField {
|
|
210
|
+
readonly key: string;
|
|
211
|
+
readonly required: boolean;
|
|
212
|
+
readonly secret: boolean;
|
|
213
|
+
readonly description: string;
|
|
214
|
+
readonly env?: string;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The Mattermost channel: a WebSocket the adapter opens itself, so it needs no webhook route.
|
|
218
|
+
*
|
|
219
|
+
* `create` validates each value with this package's `ConfigurationError` and makes no network call.
|
|
220
|
+
*
|
|
221
|
+
* @public
|
|
222
|
+
*/
|
|
223
|
+
declare const mattermostChannel: {
|
|
224
|
+
platform: "mattermost";
|
|
225
|
+
transport: "socket";
|
|
226
|
+
senderIdentity: "authenticated";
|
|
227
|
+
config: readonly ConfigField[];
|
|
228
|
+
create(config: Readonly<Record<string, unknown>>): MattermostAdapter;
|
|
229
|
+
};
|
|
230
|
+
|
|
192
231
|
/**
|
|
193
232
|
* Typed errors for `@theokit/gateway-mattermost`.
|
|
194
233
|
*
|
|
@@ -302,4 +341,4 @@ declare function postToMessageEvent(post: MattermostPost, channel: MattermostCha
|
|
|
302
341
|
*/
|
|
303
342
|
declare function splitForMattermost(text: string): string[];
|
|
304
343
|
|
|
305
|
-
export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
|
|
344
|
+
export { ConfigurationError, MattermostAdapter, type MattermostAdapterOptions, type MattermostChannel, type MattermostPost, type MattermostUser, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, mattermostChannel, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GatewayConfigurationError, chunkText, BasePlatformAdapter } from '@theokit/gateway';
|
|
1
|
+
import { channelConfigReaders, GatewayConfigurationError, chunkText, BasePlatformAdapter } from '@theokit/gateway';
|
|
2
2
|
|
|
3
3
|
// src/adapter.ts
|
|
4
4
|
var ConfigurationError = class extends GatewayConfigurationError {
|
|
@@ -21,7 +21,10 @@ var SDKNotInstalledError = class extends ConfigurationError {
|
|
|
21
21
|
async function loadMattermost() {
|
|
22
22
|
try {
|
|
23
23
|
const mod = await import('@mattermost/client');
|
|
24
|
-
return
|
|
24
|
+
return {
|
|
25
|
+
Client4: mod.Client4 ?? mod.default?.Client4,
|
|
26
|
+
WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient
|
|
27
|
+
};
|
|
25
28
|
} catch {
|
|
26
29
|
throw new SDKNotInstalledError("@mattermost/client");
|
|
27
30
|
}
|
|
@@ -120,12 +123,25 @@ function postToMessageEvent(post, channel, senderUsername) {
|
|
|
120
123
|
}
|
|
121
124
|
};
|
|
122
125
|
}
|
|
126
|
+
|
|
127
|
+
// src/refuse-attachments.ts
|
|
128
|
+
function refuseAttachments(out) {
|
|
129
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
130
|
+
return {
|
|
131
|
+
ok: false,
|
|
132
|
+
error: {
|
|
133
|
+
code: "attachments_unsupported",
|
|
134
|
+
message: "mattermost adapter cannot send attachments"
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
123
138
|
var MATTERMOST_MAX_POST = 16383;
|
|
124
139
|
var SAFE_CHUNK = 16e3;
|
|
125
140
|
var BOUNDARIES = {
|
|
126
141
|
boundaries: ["\n\n", "\n", " "],
|
|
127
142
|
lastResort: "last-boundary",
|
|
128
|
-
stripLeading: /^\s
|
|
143
|
+
stripLeading: /^\s+/,
|
|
144
|
+
keepTableRows: true
|
|
129
145
|
};
|
|
130
146
|
function splitForMattermost(text) {
|
|
131
147
|
return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });
|
|
@@ -191,6 +207,9 @@ var MattermostAdapter = class extends BasePlatformAdapter {
|
|
|
191
207
|
this.inboundHandler = void 0;
|
|
192
208
|
}
|
|
193
209
|
async sendMessage(out) {
|
|
210
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
211
|
+
}
|
|
212
|
+
async sendText(out) {
|
|
194
213
|
if (out.text.length === 0) {
|
|
195
214
|
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
196
215
|
}
|
|
@@ -225,6 +244,9 @@ var MattermostAdapter = class extends BasePlatformAdapter {
|
|
|
225
244
|
* with no request, so an edit is refused for exactly the texts a send delivers as several posts.
|
|
226
245
|
*/
|
|
227
246
|
async editMessage(messageId, out) {
|
|
247
|
+
return refuseAttachments(out) ?? this.editText(messageId, out);
|
|
248
|
+
}
|
|
249
|
+
async editText(messageId, out) {
|
|
228
250
|
if (out.text.length === 0) {
|
|
229
251
|
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
230
252
|
}
|
|
@@ -304,8 +326,27 @@ var MattermostAdapter = class extends BasePlatformAdapter {
|
|
|
304
326
|
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
305
327
|
*/
|
|
306
328
|
async deliver(event) {
|
|
329
|
+
if (!this.passesMentionGate(event)) return "ok";
|
|
307
330
|
return this.runHandler(this.inboundHandler, event);
|
|
308
331
|
}
|
|
332
|
+
/**
|
|
333
|
+
* The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.
|
|
334
|
+
*
|
|
335
|
+
* Needs the bot identity from a live connection and the raw post on the event; when either is
|
|
336
|
+
* missing there is nothing to judge by, so the event passes as it did before.
|
|
337
|
+
*/
|
|
338
|
+
passesMentionGate(event) {
|
|
339
|
+
const handle = this.handle;
|
|
340
|
+
const mm = event.mattermost;
|
|
341
|
+
if (handle === void 0 || mm?.raw === void 0) return true;
|
|
342
|
+
return shouldRespond({
|
|
343
|
+
post: mm.raw,
|
|
344
|
+
channelType: event.channel.type === "thread" ? "thread" : event.channel.type === "dm" ? "dm" : "group",
|
|
345
|
+
botUserId: handle.botUserId,
|
|
346
|
+
botUsername: handle.botUsername,
|
|
347
|
+
requireMention: this.opts.requireMention ?? true
|
|
348
|
+
});
|
|
349
|
+
}
|
|
309
350
|
};
|
|
310
351
|
function parsePostFromWS(msg) {
|
|
311
352
|
const raw = msg.data?.post;
|
|
@@ -383,7 +424,61 @@ function mapMattermostError(err) {
|
|
|
383
424
|
function escapeMarkdown(text) {
|
|
384
425
|
return text.replace(/([\\*_`~])/g, "\\$1");
|
|
385
426
|
}
|
|
427
|
+
var readers = channelConfigReaders(
|
|
428
|
+
"gateway-mattermost",
|
|
429
|
+
(options) => new ConfigurationError(options)
|
|
430
|
+
);
|
|
431
|
+
var { invalid } = readers;
|
|
432
|
+
var read = {
|
|
433
|
+
string: readers.requiredString,
|
|
434
|
+
boolean(config, key) {
|
|
435
|
+
const value = config[key];
|
|
436
|
+
if (value === void 0) return void 0;
|
|
437
|
+
if (value === true || value === "true") return true;
|
|
438
|
+
if (value === false || value === "false") return false;
|
|
439
|
+
throw invalid(key, 'a boolean or the string "true" or "false"');
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
var CONFIG = [
|
|
443
|
+
{
|
|
444
|
+
key: "baseUrl",
|
|
445
|
+
required: true,
|
|
446
|
+
secret: false,
|
|
447
|
+
description: "Base URL of the Mattermost server, e.g. https://mattermost.example.org.",
|
|
448
|
+
env: "MATTERMOST_BASE_URL"
|
|
449
|
+
},
|
|
450
|
+
{
|
|
451
|
+
key: "accessToken",
|
|
452
|
+
required: true,
|
|
453
|
+
secret: true,
|
|
454
|
+
description: "Personal access token or bot token.",
|
|
455
|
+
env: "MATTERMOST_ACCESS_TOKEN"
|
|
456
|
+
},
|
|
457
|
+
{
|
|
458
|
+
key: "requireMention",
|
|
459
|
+
required: false,
|
|
460
|
+
secret: false,
|
|
461
|
+
description: "When true, channel messages reach the handler only if they mention the bot.",
|
|
462
|
+
env: "MATTERMOST_REQUIRE_MENTION"
|
|
463
|
+
}
|
|
464
|
+
];
|
|
465
|
+
var mattermostChannel = {
|
|
466
|
+
platform: "mattermost",
|
|
467
|
+
transport: "socket",
|
|
468
|
+
senderIdentity: "authenticated",
|
|
469
|
+
config: CONFIG,
|
|
470
|
+
create(config) {
|
|
471
|
+
const baseUrl = read.string(config, "baseUrl");
|
|
472
|
+
const accessToken = read.string(config, "accessToken");
|
|
473
|
+
const requireMention = read.boolean(config, "requireMention");
|
|
474
|
+
return new MattermostAdapter({
|
|
475
|
+
baseUrl,
|
|
476
|
+
accessToken,
|
|
477
|
+
...requireMention === void 0 ? {} : { requireMention }
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
};
|
|
386
481
|
|
|
387
|
-
export { ConfigurationError, MattermostAdapter, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
|
|
482
|
+
export { ConfigurationError, MattermostAdapter, SDKNotInstalledError, connectMattermost, getChannelCached, hasMentionWithBoundary, mapChannelType, mattermostChannel, normalizeMattermostType, parsePostFromWS, postToMessageEvent, shouldRespond, splitForMattermost, wsUrlFromBase };
|
|
388
483
|
//# sourceMappingURL=index.js.map
|
|
389
484
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;AAoBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YA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AA,QACN,OAAA,EAAS,EAAE,OAAA,IAAW;AAAA;AACxB,KACF;AAAA,EACF;AACA,EAAA,IAAI,WAAW,GAAA,EAAK;AAClB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,mBAAmB,OAAA,EAAS,CAAA,CAAE,WAAW,6BAAA;AAA8B,KACxF;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,aAAA;AAAA,MACN,OAAA,EAAS,EAAE,OAAA,KAAY,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAAA;AACxE,GACF;AACF;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */\n patchPost(patch: { id: string; message: string }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = await import(\"@mattermost/client\");\n return mod as unknown as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nexport const MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n} as const;\n\n/**\n * Split `text` into posts that fit Mattermost's post cap.\n *\n * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a\n * 16000-character window at a blank line, a newline or a space, in that order of\n * preference.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order, each with leading whitespace stripped at the cut.\n */\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });\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 8191 characters fits\n * one post once escaped. The adapter calls this only for a part whose escaped body passed the cap,\n * so the parts of an ordinary text are the ones `splitForMattermost` returns.\n */\nexport function splitForEscapedMattermost(text: string): string[] {\n return chunkText(text, {\n limit: Math.floor(MATTERMOST_MAX_POST / 2),\n safeLimit: SAFE_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { MATTERMOST_MAX_POST, splitForEscapedMattermost, splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n for (const message of renderPosts(out)) {\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n /** Mattermost edits a sent post's text through `Client4.patchPost`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a post this bot sent, through `patchPost({ id, message })`.\n *\n * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and\n * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all\n * with no request, so an edit is refused for exactly the texts a send delivers as several posts.\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: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const posts = renderPosts(out);\n if (posts.length !== 1) return editPartsRefusal(posts.length);\n const message = posts[0] as string;\n try {\n await this.handle.client.patchPost({ id: messageId, message });\n } catch (err) {\n return mapMattermostError(err);\n }\n return { ok: true, messageId };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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.inboundHandler, event);\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\n/**\n * The refusal for a text that is not exactly one Mattermost post.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since\n * `splitForMattermost` returns at least one part for any non-empty text and empty text is refused\n * earlier; the arm 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} Mattermost posts; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\n/**\n * The post bodies a text goes out as, each within `MATTERMOST_MAX_POST`.\n *\n * Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the case that needs\n * work, because raw text would be parsed anyway. Split first, escape per part, the ordering Discord\n * needs for the same reason: a cut between a backslash and its character produces a stray\n * backslash in one post and a bare marker in the next. The splitter measures the caller's text,\n * and escaping can double a part, so a part whose escaped body passes the cap is split again at\n * half the cap, which every escaped body fits. `sendMessage` and `editMessage` both send what this\n * returns.\n */\nfunction renderPosts(out: OutboundMessage): string[] {\n if (out.format !== \"plain\") return splitForMattermost(out.text);\n return splitForMattermost(out.text).flatMap((part) => {\n const escaped = escapeMarkdown(part);\n if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];\n return splitForEscapedMattermost(part).map(escapeMarkdown);\n });\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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/errors.ts","../src/client.ts","../src/filters.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts"],"names":[],"mappings":";;;AAoBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,sBAAsB,IAAI,CAAA;AAAA,EAClC;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,8BAAA,EAAiC,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MAC1F,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACCA,eAAe,cAAA,GAA4C;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAO,MAAM,OAAO,oBAAoB,CAAA;AAI9C,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,GAAA,CAAI,OAAA,IAAW,GAAA,CAAI,OAAA,EAAS,OAAA;AAAA,MACrC,eAAA,EAAiB,GAAA,CAAI,eAAA,IAAmB,GAAA,CAAI,OAAA,EAAS;AAAA,KACvD;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,oBAAoB,CAAA;AAAA,EACrD;AACF;AAuBA,eAAsB,kBAAkB,IAAA,EAAuD;AAC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EAAA;AAAA,IACb,GAAA,EAAK;AAAA;AAET,CAAA;AASO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,QAAA,EAAU,YAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAA8D;AACnE,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,SAAS,CAAA;AAC7C,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,aAAa,CAAA;AACrD,IAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,gBAAgB,CAAA;AAC5D,IAAA,OAAO,IAAI,iBAAA,CAAkB;AAAA,MAC3B,OAAA;AAAA,MACA,WAAA;AAAA,MACA,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA;AAAe,KAC1D,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-mattermost`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2). Behavior byte-identical (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-mattermost\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-mattermost\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-mattermost: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Wrapper over `@mattermost/client` — lazy import + lifecycle.\n *\n * Owns:\n * - Client4 (REST) for outbound posts + channel/user lookup.\n * - WebSocketClient for real-time `posted` events.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\ninterface Client4Like {\n setUrl(url: string): void;\n setToken(token: string): void;\n getMe(): Promise<{ id: string; username: string }>;\n getChannel(channelId: string): Promise<MattermostChannel>;\n createPost(post: {\n channel_id: string;\n message: string;\n root_id?: string;\n }): Promise<MattermostPost>;\n /** Replace the fields a patch names on an existing post; the adapter's edit sends `message`. */\n patchPost(patch: { id: string; message: string }): Promise<MattermostPost>;\n}\n\ninterface WebSocketClientLike {\n initialize(url: string, token: string): void;\n addMessageListener(listener: (msg: WSMessage) => void): void;\n removeMessageListener(listener: (msg: WSMessage) => void): void;\n close(): void;\n}\n\nexport interface WSMessage {\n readonly event: string;\n readonly data: Record<string, unknown>;\n readonly broadcast?: { readonly channel_id?: string; readonly team_id?: string };\n}\n\ninterface MattermostModule {\n Client4: new () => Client4Like;\n WebSocketClient: new () => WebSocketClientLike;\n}\n\nasync function loadMattermost(): Promise<MattermostModule> {\n try {\n const mod = (await import(\"@mattermost/client\")) as unknown as Partial<MattermostModule> & {\n default?: MattermostModule;\n };\n // Node's CommonJS namespace does not expose the SDK's getter-defined exports.\n return {\n Client4: mod.Client4 ?? mod.default?.Client4,\n WebSocketClient: mod.WebSocketClient ?? mod.default?.WebSocketClient,\n } as MattermostModule;\n } catch {\n throw new SDKNotInstalledError(\"@mattermost/client\");\n }\n}\n\nexport interface MattermostClientHandle {\n readonly client: Client4Like;\n readonly ws: WebSocketClientLike;\n readonly botUserId: string;\n readonly botUsername: string;\n /** Channel-id LRU cache (max 200) to avoid extra getChannel calls. */\n readonly channelCache: Map<string, MattermostChannel>;\n}\n\nexport interface ConnectOptions {\n readonly baseUrl: string;\n readonly accessToken: string;\n}\n\n/**\n * Authenticate against a Mattermost server and open the websocket that carries inbound posts.\n *\n * The SDK is loaded lazily, so a project that installs this package without using it never pays for\n * the dependency. Returns the handle every other function here takes — client, websocket and the\n * channel cache, kept together because they share a lifetime.\n */\nexport async function connectMattermost(opts: ConnectOptions): Promise<MattermostClientHandle> {\n const mod = await loadMattermost();\n const client = new mod.Client4();\n client.setUrl(opts.baseUrl);\n client.setToken(opts.accessToken);\n const me = await client.getMe();\n const ws = new mod.WebSocketClient();\n const wsUrl = wsUrlFromBase(opts.baseUrl);\n ws.initialize(wsUrl, opts.accessToken);\n return {\n client,\n ws,\n botUserId: me.id,\n botUsername: me.username,\n channelCache: new Map(),\n };\n}\n\n/**\n * Convert REST base URL to WebSocket URL:\n * `https://x.com` → `wss://x.com/api/v4/websocket`\n * `http://localhost:8065` → `ws://localhost:8065/api/v4/websocket`\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function wsUrlFromBase(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/$/, \"\");\n const wsScheme = trimmed.startsWith(\"https://\") ? \"wss://\" : \"ws://\";\n const hostPart = trimmed.replace(/^https?:\\/\\//, \"\");\n return `${wsScheme}${hostPart}/api/v4/websocket`;\n}\n\n/**\n * Fetch a channel by id, remembering the answer on the handle.\n *\n * Normalising an inbound post needs the channel's type, and a busy channel would otherwise cost one\n * API call per message. Returns `undefined` rather than throwing when the channel cannot be read —\n * a post from a channel the bot cannot see is a normal event, not a failure.\n */\nexport async function getChannelCached(\n handle: MattermostClientHandle,\n channelId: string,\n): Promise<MattermostChannel | undefined> {\n const cached = handle.channelCache.get(channelId);\n if (cached !== undefined) return cached;\n try {\n const channel = await handle.client.getChannel(channelId);\n // LRU cap: drop oldest when full.\n if (handle.channelCache.size >= 200) {\n const firstKey = handle.channelCache.keys().next().value;\n if (firstKey !== undefined) handle.channelCache.delete(firstKey);\n }\n handle.channelCache.set(channelId, channel);\n return channel;\n } catch {\n return undefined;\n }\n}\n","/**\n * Inbound dispatch pipeline (D403, EC-2).\n *\n * Order matters — these checks compose:\n *\n * 1. Loop guard: drop bot's own posts (D275 mirror).\n * 2. DM channels: always respond.\n * 3. `requireMention === false`: respond.\n * 4. **Metadata.mentions** array contains bot user-id → respond (PRIORITY).\n * 5. **Word-boundary text regex** `\\b@${botUsername}\\b` → respond.\n * 6. Else: ignore.\n *\n * EC-2: substring match (`post.message.includes(\"@theo\")`) catches\n * `@theory_dept` and dispatches false-positive. The fix is two-fold:\n * prefer the unambiguous `metadata.mentions` array (API-provided\n * user-ids), and when text fallback is required, use `\\b` boundaries.\n */\n\nimport type { MattermostPost } from \"./types.js\";\n\n/** @knipignore — input shape for `shouldRespond`; useful for callers wrapping the filter pipeline. */\nexport interface ShouldRespondOptions {\n readonly post: MattermostPost;\n readonly channelType: \"dm\" | \"group\" | \"thread\";\n readonly botUserId: string;\n readonly botUsername: string;\n readonly requireMention: boolean;\n}\n\n/**\n * Decide whether the bot should answer a post.\n *\n * Three rules in order: never answer itself (the loop guard), always answer a direct message, and in\n * a channel answer only when mentioned unless `requireMention` is turned off. The mention default\n * is what keeps a bot added to a busy channel from replying to every message in it.\n */\nexport function shouldRespond(opts: ShouldRespondOptions): boolean {\n const { post, channelType, botUserId, botUsername, requireMention } = opts;\n // 1. Loop guard.\n if (post.user_id === botUserId) return false;\n // 2. DM — always.\n if (channelType === \"dm\") return true;\n // 3. Opt-out of mention enforcement.\n if (!requireMention) return true;\n // 4. metadata.mentions takes priority — never ambiguous.\n const mentioned = post.metadata?.mentions?.includes(botUserId) ?? false;\n if (mentioned) return true;\n // 5. Text fallback with word boundary (EC-2).\n if (botUsername.length > 0 && hasMentionWithBoundary(post.message, botUsername)) {\n return true;\n }\n return false;\n}\n\n/**\n * Word-boundary match for `@${botUsername}`. Word boundaries land at\n * `\\b` (start/end of `\\w` regions), so `@theo` at the head of `@theory`\n * does NOT match because `\\b` is between `o` and `r` only when the\n * NEXT char is a non-word char.\n *\n * @public — exported for unit tests + consumer-side reuse.\n */\nexport function hasMentionWithBoundary(text: string, botUsername: string): boolean {\n // Escape regex metacharacters in username (Mattermost allows `.`, `_`, `-`).\n const safe = botUsername.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(`(^|[^\\\\w])@${safe}(?![\\\\w.])`, \"u\");\n return re.test(text);\n}\n","/**\n * Inbound normalization: Mattermost Post → MattermostMessageEvent.\n *\n * Channel-type mapping (D402):\n * - `D` (Direct) → `\"dm\"`\n * - `G`/`O`/`P` (Group/Open/Private) → `\"group\"`\n * - Posts with `root_id !== \"\"` → `\"thread\"` with `topicId = root_id` (D399).\n */\n\nimport type { MattermostMessageEvent } from \"@theokit/gateway\";\n\nimport type { MattermostChannel, MattermostPost } from \"./types.js\";\n\nexport function normalizeMattermostType(\n channel: MattermostChannel | undefined,\n): \"D\" | \"G\" | \"O\" | \"P\" | (string & {}) {\n return channel?.type ?? \"O\";\n}\n\n/**\n * Map Mattermost's channel type to the gateway's conversation kind.\n *\n * A post carrying a root id is a threaded reply whatever channel it sits in, so that wins over the\n * channel's own type; `\"D\"` is a direct message, and everything else is treated as a group.\n */\nexport function mapChannelType(rawType: string, hasRootId: boolean): \"dm\" | \"group\" | \"thread\" {\n if (hasRootId) return \"thread\";\n if (rawType === \"D\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn a Mattermost post into a `MattermostMessageEvent`.\n *\n * `channel` and `senderUsername` are optional because both are fetched separately and either can be\n * unavailable; the event is still produced, with the conversation kind falling back to a group.\n */\nexport function postToMessageEvent(\n post: MattermostPost,\n channel: MattermostChannel | undefined,\n senderUsername: string | undefined,\n): MattermostMessageEvent {\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n return {\n id: post.id,\n platform: \"mattermost\",\n sender: {\n id: post.user_id,\n ...(senderUsername !== undefined ? { username: senderUsername } : {}),\n },\n channel: {\n id: post.channel_id,\n type: channelType,\n ...(channelType === \"thread\" ? { topicId: post.root_id } : {}),\n },\n text: post.message,\n receivedAt: post.create_at > 0 ? post.create_at : Date.now(),\n mattermost: {\n postId: post.id,\n channelId: post.channel_id,\n teamId: channel?.team_id ?? \"\",\n ...(post.root_id.length > 0 ? { rootId: post.root_id } : {}),\n channelType: rawType,\n raw: post,\n },\n };\n}\n","/**\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: {\n code: \"attachments_unsupported\",\n message: \"mattermost adapter cannot send attachments\",\n },\n };\n}\n","/**\n * `splitForMattermost` — segment outbound text to Mattermost's post cap.\n *\n * This package shipped without any splitting at all, alone among the ten\n * adapters. `sendMessage` handed `out.text` to `createPost` whole, so an agent\n * reply longer than the cap came back:\n *\n * HTTP 400 — \"Post Message property is longer than the maximum permitted length.\"\n *\n * and the user saw nothing. No unit test could catch it, because there was no\n * cap in the code to assert against; it took a real server to answer 400.\n * Verified against Mattermost directly on 2026-08-17: 16000 chars posts fine,\n * 16384 is refused.\n *\n * The server counts RUNES, not bytes — `MaxPostSize` is 16383 by default. This\n * splits on code points via the core chunker, which is the closest the JS side\n * gets without walking graphemes; a message of astral-plane characters could\n * still exceed the server's count, which is why the window leaves headroom.\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** Mattermost's default `MaxPostSize`, in runes. */\nexport const MATTERMOST_MAX_POST = 16_383;\n\n/**\n * Cut inside a smaller window than the cap.\n *\n * The headroom absorbs the gap between how JavaScript counts a string and how\n * the server counts runes. Landing exactly on the limit is the one place this\n * can still fail, and the failure is a 400 the user never sees.\n */\nconst SAFE_CHUNK = 16_000;\n\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n stripLeading: /^\\s+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into posts that fit Mattermost's post cap.\n *\n * Each chunk is at most {@link MATTERMOST_MAX_POST} code points, cut inside a\n * 16000-character window at a blank line, a newline or a space, in that order of\n * preference.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order, each with leading whitespace stripped at the cut.\n */\nexport function splitForMattermost(text: string): string[] {\n return chunkText(text, { limit: MATTERMOST_MAX_POST, safeLimit: SAFE_CHUNK, ...BOUNDARIES });\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 8191 characters fits\n * one post once escaped. The adapter calls this only for a part whose escaped body passed the cap,\n * so the parts of an ordinary text are the ones `splitForMattermost` returns.\n */\nexport function splitForEscapedMattermost(text: string): string[] {\n return chunkText(text, {\n limit: Math.floor(MATTERMOST_MAX_POST / 2),\n safeLimit: SAFE_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `MattermostAdapter` — implements BasePlatformAdapter over Client4 + WS.\n * ADRs D397-D404.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport {\n type ConnectOptions,\n connectMattermost,\n getChannelCached,\n type MattermostClientHandle,\n type WSMessage,\n} from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { shouldRespond } from \"./filters.js\";\nimport { mapChannelType, normalizeMattermostType, postToMessageEvent } from \"./normalize.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { MATTERMOST_MAX_POST, splitForEscapedMattermost, splitForMattermost } from \"./split.js\";\nimport type { MattermostAdapterOptions, MattermostPost } from \"./types.js\";\n\nexport class MattermostAdapter extends BasePlatformAdapter {\n readonly platform = \"mattermost\" as const;\n private readonly opts: MattermostAdapterOptions;\n private handle: MattermostClientHandle | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private wsListener: ((msg: WSMessage) => void) | undefined;\n private connected = false;\n\n constructor(opts: MattermostAdapterOptions) {\n super();\n if (opts.baseUrl.length === 0) {\n throw new ConfigurationError({\n code: \"base_url_required\",\n message: 'gateway-mattermost: opts.baseUrl is empty (e.g. \"https://mattermost.acme.com\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-mattermost: opts.accessToken is empty (generate one in System Console → Integrations → Bot Accounts)\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n this.handle = await connectMattermost({\n baseUrl: this.opts.baseUrl,\n accessToken: this.opts.accessToken,\n } satisfies ConnectOptions);\n this.attachWsListener();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n if (this.handle !== undefined && this.wsListener !== undefined) {\n this.handle.ws.removeMessageListener(this.wsListener);\n }\n this.handle?.ws.close();\n this.handle = undefined;\n this.wsListener = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n }\n\n 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: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n try {\n // Split before sending. This package used to post `out.text` whole, alone\n // among the ten adapters, so anything past Mattermost's 16383-rune cap came\n // back HTTP 400 and the user saw nothing at all.\n let lastId: string | undefined;\n for (const message of renderPosts(out)) {\n const post = await this.handle.client.createPost({\n channel_id: out.channel.id,\n message,\n ...(out.channel.type === \"thread\" && out.channel.topicId !== undefined\n ? { root_id: out.channel.topicId }\n : {}),\n });\n lastId = post.id;\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n } catch (err) {\n return mapMattermostError(err);\n }\n }\n\n /** Mattermost edits a sent post's text through `Client4.patchPost`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a post this bot sent, through `patchPost({ id, message })`.\n *\n * Applies `sendMessage`'s checks (`empty_text`, then `not_connected`), refuses an empty id, and\n * refuses as `edit_too_long` a text the shared `renderPosts` turns into more than one post, all\n * with no request, so an edit is refused for exactly the texts a send delivers as several posts.\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: \"outbound text is empty\" } };\n }\n if (this.handle === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MattermostAdapter.connect() not called\" },\n };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const posts = renderPosts(out);\n if (posts.length !== 1) return editPartsRefusal(posts.length);\n const message = posts[0] as string;\n try {\n await this.handle.client.patchPost({ id: messageId, message });\n } catch (err) {\n return mapMattermostError(err);\n }\n return { ok: true, messageId };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller can drive REST directly when v0.1 doesn't expose a feature. */\n getClient(): MattermostClientHandle | undefined {\n return this.handle;\n }\n\n private attachWsListener(): void {\n if (this.handle === undefined) return;\n const handle = this.handle;\n this.wsListener = (msg: WSMessage) => {\n if (msg.event !== \"posted\") return;\n void this.processPostedEvent(handle, msg).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] processPostedEvent failed: ${m}\\n`);\n });\n };\n handle.ws.addMessageListener(this.wsListener);\n }\n\n private async processPostedEvent(handle: MattermostClientHandle, msg: WSMessage): Promise<void> {\n const post = parsePostFromWS(msg);\n if (post === undefined) return;\n const channel = await getChannelCached(handle, post.channel_id);\n const rawType = normalizeMattermostType(channel);\n const channelType = mapChannelType(rawType, post.root_id.length > 0);\n const requireMention = this.opts.requireMention ?? true;\n if (\n !shouldRespond({\n post,\n channelType,\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention,\n })\n ) {\n return;\n }\n const senderUsername =\n typeof msg.data.sender_name === \"string\"\n ? (msg.data.sender_name as string).replace(/^@/, \"\")\n : undefined;\n const event = postToMessageEvent(post, channel, senderUsername);\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(event);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-mattermost] handler threw: ${m}\\n`);\n }\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 if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.inboundHandler, event);\n }\n\n /**\n * The same `shouldRespond` gate the websocket path applies, run on an out-of-band event.\n *\n * Needs the bot identity from a live connection and the raw post on the event; when either is\n * missing there is nothing to judge by, so the event passes as it did before.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n const handle = this.handle;\n const mm = (event as { mattermost?: { raw?: MattermostPost } }).mattermost;\n if (handle === undefined || mm?.raw === undefined) return true;\n return shouldRespond({\n post: mm.raw,\n channelType:\n event.channel.type === \"thread\" ? \"thread\" : event.channel.type === \"dm\" ? \"dm\" : \"group\",\n botUserId: handle.botUserId,\n botUsername: handle.botUsername,\n requireMention: this.opts.requireMention ?? true,\n });\n }\n}\n\n/**\n * Parse the `data.post` JSON envelope from a Mattermost WS `posted` event.\n *\n * @public — exposed so consumers can drive their own WS listener too.\n */\nexport function parsePostFromWS(msg: WSMessage): MattermostPost | undefined {\n const raw = msg.data?.post;\n if (typeof raw !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<MattermostPost>;\n if (\n typeof parsed.id !== \"string\" ||\n typeof parsed.user_id !== \"string\" ||\n typeof parsed.channel_id !== \"string\" ||\n typeof parsed.message !== \"string\"\n ) {\n return undefined;\n }\n return {\n id: parsed.id,\n user_id: parsed.user_id,\n channel_id: parsed.channel_id,\n root_id: typeof parsed.root_id === \"string\" ? parsed.root_id : \"\",\n message: parsed.message,\n create_at: typeof parsed.create_at === \"number\" ? parsed.create_at : 0,\n metadata: parsed.metadata,\n };\n } catch {\n return undefined;\n }\n}\n\ninterface MattermostRestError {\n status_code?: number;\n message?: string;\n}\n\n/**\n * The refusal for a text that is not exactly one Mattermost post.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since\n * `splitForMattermost` returns at least one part for any non-empty text and empty text is refused\n * earlier; the arm 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} Mattermost posts; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\n/**\n * The post bodies a text goes out as, each within `MATTERMOST_MAX_POST`.\n *\n * Mattermost parses markdown natively, so `markdown` needs no flag; `plain` is the case that needs\n * work, because raw text would be parsed anyway. Split first, escape per part, the ordering Discord\n * needs for the same reason: a cut between a backslash and its character produces a stray\n * backslash in one post and a bare marker in the next. The splitter measures the caller's text,\n * and escaping can double a part, so a part whose escaped body passes the cap is split again at\n * half the cap, which every escaped body fits. `sendMessage` and `editMessage` both send what this\n * returns.\n */\nfunction renderPosts(out: OutboundMessage): string[] {\n if (out.format !== \"plain\") return splitForMattermost(out.text);\n return splitForMattermost(out.text).flatMap((part) => {\n const escaped = escapeMarkdown(part);\n if (escaped.length <= MATTERMOST_MAX_POST) return [escaped];\n return splitForEscapedMattermost(part).map(escapeMarkdown);\n });\n}\n\nfunction mapMattermostError(err: unknown): SendResult {\n const e = err as MattermostRestError;\n const status = e.status_code ?? 0;\n if (status === 429) {\n return {\n ok: false,\n error: { code: \"rate_limit\", message: e.message ?? \"Mattermost rate limit\" },\n };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: {\n code: \"permission_denied\",\n message: e.message ?? \"Mattermost auth/permission error\",\n },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"Mattermost rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\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","/**\n * `mattermostChannel` — the Mattermost channel described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration\n * package's typecheck is where a drift between the two fails.\n */\n\nimport { channelConfigReaders } from \"@theokit/gateway\";\nimport { MattermostAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nconst readers = channelConfigReaders(\n \"gateway-mattermost\",\n (options) => new ConfigurationError(options),\n);\nconst { invalid } = readers;\n\ntype Config = Readonly<Record<string, unknown>>;\n\n/** Readers for values that may arrive as env strings; only `undefined` is absent. */\nconst read = {\n string: readers.requiredString,\n boolean(config: Config, key: string): boolean | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (value === true || value === \"true\") return true;\n if (value === false || value === \"false\") return false;\n throw invalid(key, 'a boolean or the string \"true\" or \"false\"');\n },\n};\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"baseUrl\",\n required: true,\n secret: false,\n description: \"Base URL of the Mattermost server, e.g. https://mattermost.example.org.\",\n env: \"MATTERMOST_BASE_URL\",\n },\n {\n key: \"accessToken\",\n required: true,\n secret: true,\n description: \"Personal access token or bot token.\",\n env: \"MATTERMOST_ACCESS_TOKEN\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"When true, channel messages reach the handler only if they mention the bot.\",\n env: \"MATTERMOST_REQUIRE_MENTION\",\n },\n];\n\n/**\n * The Mattermost channel: a WebSocket the adapter opens itself, so it needs no webhook route.\n *\n * `create` validates each value with this package's `ConfigurationError` and makes no network call.\n *\n * @public\n */\nexport const mattermostChannel = {\n platform: \"mattermost\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): MattermostAdapter {\n const baseUrl = read.string(config, \"baseUrl\");\n const accessToken = read.string(config, \"accessToken\");\n const requireMention = read.boolean(config, \"requireMention\");\n return new MattermostAdapter({\n baseUrl,\n accessToken,\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-mattermost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Mattermost platform adapter for @theokit/gateway. WebSocket gateway + REST. ADRs D397-D404.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
],
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"@mattermost/client": "^9.0.0 || ^11.0.0",
|
|
40
|
-
"@theokit/gateway": ">=0.
|
|
40
|
+
"@theokit/gateway": ">=0.21.0 <1.0.0",
|
|
41
41
|
"ws": "^8.0.0"
|
|
42
42
|
},
|
|
43
43
|
"peerDependenciesMeta": {
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"typescript": "5.9.3",
|
|
58
58
|
"vitest": "^4.1.11",
|
|
59
59
|
"zod": "^4.0.0",
|
|
60
|
-
"@theokit/gateway": "0.
|
|
60
|
+
"@theokit/gateway": "0.24.0"
|
|
61
61
|
},
|
|
62
62
|
"publishConfig": {
|
|
63
63
|
"access": "public",
|