@theokit/gateway-matrix 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +97 -0
- package/dist/index.cjs +326 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +192 -0
- package/dist/index.d.ts +192 -0
- package/dist/index.js +316 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.0.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @theokit/sdk@1.3.0
|
|
9
|
+
- @theokit/gateway@2.0.0
|
|
10
|
+
|
|
11
|
+
## 1.0.0
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- Updated dependencies
|
|
16
|
+
- @theokit/sdk@1.2.0
|
|
17
|
+
- @theokit/gateway@1.0.0
|
|
18
|
+
|
|
19
|
+
## [Unreleased]
|
|
20
|
+
|
|
21
|
+
### Added — `@theokit/gateway-matrix@0.1.0` (ADRs D413-D421)
|
|
22
|
+
|
|
23
|
+
- Initial release of the Matrix protocol adapter for `@theokit/gateway`.
|
|
24
|
+
- `matrix-js-sdk@^32.0.0` peer-dep (lazy import — full SDK is ~2MB).
|
|
25
|
+
- `MatrixAdapter` extending `BasePlatformAdapter`:
|
|
26
|
+
- `connect()` initializes `MatrixClient` with `homeserverUrl + accessToken + userId`; starts sync loop with `initialSyncLimit: 10` (D414, D415).
|
|
27
|
+
- `disconnect()` stops client gracefully; idempotent.
|
|
28
|
+
- `sendMessage()` posts via `client.sendTextMessage(roomId, text)`; reply to alias resolves to room id via `getRoomIdForAlias` (D419).
|
|
29
|
+
- `onInbound()` replace semantics (EC-H).
|
|
30
|
+
- Sync loop wrapper (`sync.ts`) filters out:
|
|
31
|
+
- Non-`m.room.message` events (D413).
|
|
32
|
+
- Bot's own messages (loop guard).
|
|
33
|
+
- **EC-3 absorbed**: events older than 60s (initial sync flood prevention — a bot in 50 rooms × 10 events = 500 LLM calls on boot).
|
|
34
|
+
- Room state (`room-state.ts`):
|
|
35
|
+
- DM detection (D416): `room.getJoinedMemberCount() === 2` → `channel.type: "dm"`; else `"group"`.
|
|
36
|
+
- Alias resolution (D419): caller passes `#general:matrix.org` OR `!abc123:matrix.org`; adapter resolves alias → room id on first use, caches.
|
|
37
|
+
- E2EE rooms refused with warn stderr (D418) — v0.1 only operates on unencrypted rooms.
|
|
38
|
+
- Federation transparent (D420) — Matrix SDK handles cross-homeserver routing.
|
|
39
|
+
- Matrix events preserved in `event.matrix.raw` (D421) for caller access to redactions, relations, etc.
|
|
40
|
+
- Threads (MSC4140) deferred to v0.2 (D417).
|
|
41
|
+
- E2EE (Olm/Megolm) deferred to v0.2 (D418).
|
package/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# @theokit/gateway-matrix
|
|
2
|
+
|
|
3
|
+
Matrix protocol platform adapter for [`@theokit/gateway`](../gateway).
|
|
4
|
+
|
|
5
|
+
Decentralized federation. Works with matrix.org, element.io, self-hosted Synapse/Dendrite, etc. Bot in `@bot:matrix.org` can receive from `@alice:element.io` via federation built-in.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @theokit/sdk @theokit/gateway @theokit/gateway-matrix
|
|
11
|
+
pnpm add matrix-js-sdk # ~2MB peer-dep
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Quick start
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { Agent } from "@theokit/sdk";
|
|
18
|
+
import { GatewayRunner } from "@theokit/gateway";
|
|
19
|
+
import { MatrixAdapter } from "@theokit/gateway-matrix";
|
|
20
|
+
|
|
21
|
+
const adapter = new MatrixAdapter({
|
|
22
|
+
homeserverUrl: "https://matrix.org",
|
|
23
|
+
accessToken: process.env.MATRIX_ACCESS_TOKEN!,
|
|
24
|
+
userId: "@theo-bot:matrix.org",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const runner = new GatewayRunner({
|
|
28
|
+
adapters: [adapter],
|
|
29
|
+
handler: async (event, ctx) => {
|
|
30
|
+
if (event.platform !== "matrix") return;
|
|
31
|
+
await ctx.reply(`Echo: ${event.text}`);
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
await runner.start();
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Access token
|
|
39
|
+
|
|
40
|
+
Element web UI is the easiest path:
|
|
41
|
+
|
|
42
|
+
1. Sign in as the bot account.
|
|
43
|
+
2. **Settings → Help & About → Advanced**.
|
|
44
|
+
3. Click "**Access Token**" → reveal + copy.
|
|
45
|
+
4. Save as `MATRIX_ACCESS_TOKEN` in `.env`.
|
|
46
|
+
|
|
47
|
+
Keep this token secret — it grants full account access.
|
|
48
|
+
|
|
49
|
+
## DM detection (D416)
|
|
50
|
+
|
|
51
|
+
Matrix has no native "DM" concept — DMs are simply rooms with 2 members. The adapter applies the canonical heuristic:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
room.getJoinedMemberCount() === 2 → channel.type: "dm"
|
|
55
|
+
≥3 members → channel.type: "group"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Edge case: a user who creates a 2-person room intended as a small group will still be detected as a DM. Use `event.matrix.roomId` + Matrix's `m.direct` account-data to override if you need precision.
|
|
59
|
+
|
|
60
|
+
## Initial sync flood guard (EC-3 absorbed)
|
|
61
|
+
|
|
62
|
+
On startup, `matrix-js-sdk` delivers the most recent ~10 events per room. A bot in 50 rooms = 500 events fired in seconds → 500 LLM calls = cost explosion. **The adapter filters events older than 60s** (`event.getTs() < Date.now() - 60_000`) so initial sync only delivers genuinely live messages. To replay history programmatically, use the raw `MatrixClient` via `adapter.getClient()`.
|
|
63
|
+
|
|
64
|
+
## Alias resolution (D419)
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// All three accepted (caller's choice):
|
|
68
|
+
await ctx.reply("hi"); // event.channel.id = room id from inbound
|
|
69
|
+
await adapter.sendMessage({
|
|
70
|
+
channel: { id: "#general:matrix.org", type: "group" }, // alias resolved
|
|
71
|
+
text: "...",
|
|
72
|
+
});
|
|
73
|
+
await adapter.sendMessage({
|
|
74
|
+
channel: { id: "!abc123:matrix.org", type: "group" }, // room id direct
|
|
75
|
+
text: "...",
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Aliases are resolved + cached on first use. If the admin renames an alias mid-process, sends to the cached value fail (rare — restart resolves).
|
|
80
|
+
|
|
81
|
+
## What's NOT supported in v0.1
|
|
82
|
+
|
|
83
|
+
| Feature | Status | Workaround |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| E2EE rooms | Refused with warn stderr (D418) | Use unencrypted rooms; E2EE in v0.2 |
|
|
86
|
+
| Threads (MSC4140) | Deferred to v0.2 (D417) | All replies land at room root |
|
|
87
|
+
| Reactions / redactions | Inbound preserved via `event.matrix.raw` | Outbound: `adapter.getClient().sendEvent(...)` |
|
|
88
|
+
| Media (image/file/audio) | Inbound delivered with empty `text` | Read `event.matrix.raw.getContent()` for the file URL |
|
|
89
|
+
| Sync token persistence | Process-local | Restart re-syncs (mitigated by 60s freshness filter) |
|
|
90
|
+
|
|
91
|
+
## Federation transparency (D420)
|
|
92
|
+
|
|
93
|
+
The adapter doesn't handle federation — Matrix protocol does. Your bot in `@theo-bot:matrix.org` can be added to rooms by users on any homeserver and the conversation flows transparently. Outbound performance varies with remote homeserver latency; failure modes (e.g. remote unreachable) surface as `SendResult{send_failed}`.
|
|
94
|
+
|
|
95
|
+
## ADRs
|
|
96
|
+
|
|
97
|
+
D413 – D421 in `.claude/knowledge-base/adrs/`.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var gateway = require('@theokit/gateway');
|
|
4
|
+
|
|
5
|
+
// src/adapter.ts
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
var ConfigurationError = class extends Error {
|
|
9
|
+
name = "ConfigurationError";
|
|
10
|
+
code;
|
|
11
|
+
detail;
|
|
12
|
+
constructor(opts) {
|
|
13
|
+
super(opts.message ?? `gateway-matrix: ${opts.code}`);
|
|
14
|
+
this.code = opts.code;
|
|
15
|
+
this.detail = opts.detail;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var SDKNotInstalledError = class extends ConfigurationError {
|
|
19
|
+
constructor() {
|
|
20
|
+
super({
|
|
21
|
+
code: "sdk_not_installed",
|
|
22
|
+
message: 'gateway-matrix: peer-dep "matrix-js-sdk" not installed. Run: pnpm add matrix-js-sdk',
|
|
23
|
+
detail: "matrix-js-sdk"
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
var EncryptedRoomError = class extends ConfigurationError {
|
|
28
|
+
constructor(roomId) {
|
|
29
|
+
super({
|
|
30
|
+
code: "encrypted_room_unsupported",
|
|
31
|
+
message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,
|
|
32
|
+
detail: roomId
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/alias.ts
|
|
38
|
+
var AliasCache = class {
|
|
39
|
+
cache = /* @__PURE__ */ new Map();
|
|
40
|
+
/** Returns the room id; resolves aliases via the client + caches. */
|
|
41
|
+
async resolve(client, refOrId) {
|
|
42
|
+
if (refOrId.startsWith("!")) return refOrId;
|
|
43
|
+
if (!refOrId.startsWith("#")) {
|
|
44
|
+
throw new ConfigurationError({
|
|
45
|
+
code: "invalid_room_ref",
|
|
46
|
+
message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} \u2014 expected '!' (room id) or '#' (alias)`
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const cached = this.cache.get(refOrId);
|
|
50
|
+
if (cached !== void 0) return cached;
|
|
51
|
+
const { room_id } = await client.getRoomIdForAlias(refOrId);
|
|
52
|
+
this.cache.set(refOrId, room_id);
|
|
53
|
+
return room_id;
|
|
54
|
+
}
|
|
55
|
+
/** Drop all cached resolutions. Useful for tests + admin-rename recovery. */
|
|
56
|
+
clear() {
|
|
57
|
+
this.cache.clear();
|
|
58
|
+
}
|
|
59
|
+
size() {
|
|
60
|
+
return this.cache.size;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
// src/client.ts
|
|
65
|
+
async function loadMatrixSdk() {
|
|
66
|
+
try {
|
|
67
|
+
const mod = await import('matrix-js-sdk');
|
|
68
|
+
return mod;
|
|
69
|
+
} catch {
|
|
70
|
+
throw new SDKNotInstalledError();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/room-state.ts
|
|
75
|
+
function detectChannelType(room) {
|
|
76
|
+
if (room === void 0) return "group";
|
|
77
|
+
return room.getJoinedMemberCount() === 2 ? "dm" : "group";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// src/normalize.ts
|
|
81
|
+
function matrixEventToMessageEvent(event, room) {
|
|
82
|
+
const eventId = event.getId();
|
|
83
|
+
const sender = event.getSender();
|
|
84
|
+
if (eventId === void 0 || sender === void 0) return void 0;
|
|
85
|
+
const channelType = detectChannelType(room);
|
|
86
|
+
const content = event.getContent();
|
|
87
|
+
const body = content.body ?? "";
|
|
88
|
+
return {
|
|
89
|
+
id: eventId,
|
|
90
|
+
platform: "matrix",
|
|
91
|
+
sender: { id: sender },
|
|
92
|
+
channel: {
|
|
93
|
+
id: room.roomId,
|
|
94
|
+
type: channelType
|
|
95
|
+
},
|
|
96
|
+
text: body,
|
|
97
|
+
receivedAt: event.getTs(),
|
|
98
|
+
matrix: {
|
|
99
|
+
roomId: room.roomId,
|
|
100
|
+
eventId,
|
|
101
|
+
memberCount: room.getJoinedMemberCount(),
|
|
102
|
+
raw: event
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/sync.ts
|
|
108
|
+
function shouldDispatchSyncEvent(event, opts, now = Date.now()) {
|
|
109
|
+
if (event.getType() !== "m.room.message") return false;
|
|
110
|
+
const sender = event.getSender();
|
|
111
|
+
if (sender === opts.botUserId) return false;
|
|
112
|
+
if (event.getTs() < now - opts.freshnessWindowMs) return false;
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
function subscribeToTimeline(client, handler, opts) {
|
|
116
|
+
const wrapped = (event, room) => {
|
|
117
|
+
if (!shouldDispatchSyncEvent(event, opts)) return;
|
|
118
|
+
handler(event, room);
|
|
119
|
+
};
|
|
120
|
+
client.on("Room.timeline", wrapped);
|
|
121
|
+
return {
|
|
122
|
+
unsubscribe() {
|
|
123
|
+
client.off("Room.timeline", wrapped);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/adapter.ts
|
|
129
|
+
var DEFAULT_FRESHNESS_MS = 6e4;
|
|
130
|
+
var INITIAL_SYNC_LIMIT = 10;
|
|
131
|
+
var MatrixAdapter = class extends gateway.BasePlatformAdapter {
|
|
132
|
+
platform = "matrix";
|
|
133
|
+
opts;
|
|
134
|
+
client;
|
|
135
|
+
subscription;
|
|
136
|
+
inboundHandler;
|
|
137
|
+
aliasCache = new AliasCache();
|
|
138
|
+
connected = false;
|
|
139
|
+
warnedEncrypted = /* @__PURE__ */ new Set();
|
|
140
|
+
constructor(opts) {
|
|
141
|
+
super();
|
|
142
|
+
if (opts.homeserverUrl.length === 0) {
|
|
143
|
+
throw new ConfigurationError({
|
|
144
|
+
code: "homeserver_url_required",
|
|
145
|
+
message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. "https://matrix.org")'
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
if (opts.accessToken.length === 0) {
|
|
149
|
+
throw new ConfigurationError({
|
|
150
|
+
code: "access_token_required",
|
|
151
|
+
message: "gateway-matrix: opts.accessToken is empty (Element \u2192 Settings \u2192 Help & About \u2192 Advanced \u2192 Access Token)"
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (opts.userId.length === 0 || !opts.userId.startsWith("@")) {
|
|
155
|
+
throw new ConfigurationError({
|
|
156
|
+
code: "user_id_required",
|
|
157
|
+
message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. "@bot:matrix.org")'
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
this.opts = opts;
|
|
161
|
+
}
|
|
162
|
+
async connect() {
|
|
163
|
+
if (this.connected) return true;
|
|
164
|
+
try {
|
|
165
|
+
const mod = await loadMatrixSdk();
|
|
166
|
+
this.client = mod.createClient({
|
|
167
|
+
baseUrl: this.opts.homeserverUrl,
|
|
168
|
+
accessToken: this.opts.accessToken,
|
|
169
|
+
userId: this.opts.userId
|
|
170
|
+
});
|
|
171
|
+
await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });
|
|
172
|
+
this.attachSync();
|
|
173
|
+
this.connected = true;
|
|
174
|
+
return true;
|
|
175
|
+
} catch (err) {
|
|
176
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
177
|
+
process.stderr.write(`[gateway-matrix] connect failed: ${msg}
|
|
178
|
+
`);
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async disconnect() {
|
|
183
|
+
if (!this.connected) return;
|
|
184
|
+
this.subscription?.unsubscribe();
|
|
185
|
+
this.subscription = void 0;
|
|
186
|
+
this.client?.stopClient();
|
|
187
|
+
this.client = void 0;
|
|
188
|
+
this.connected = false;
|
|
189
|
+
this.inboundHandler = void 0;
|
|
190
|
+
this.aliasCache.clear();
|
|
191
|
+
}
|
|
192
|
+
async sendMessage(out) {
|
|
193
|
+
if (out.text.length === 0) {
|
|
194
|
+
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
195
|
+
}
|
|
196
|
+
if (this.client === void 0) {
|
|
197
|
+
return {
|
|
198
|
+
ok: false,
|
|
199
|
+
error: { code: "not_connected", message: "MatrixAdapter.connect() not called" }
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
const roomId = await this.aliasCache.resolve(this.client, out.channel.id);
|
|
204
|
+
if (this.isEncrypted(roomId)) {
|
|
205
|
+
this.warnEncryptedOnce(roomId);
|
|
206
|
+
return {
|
|
207
|
+
ok: false,
|
|
208
|
+
error: {
|
|
209
|
+
code: "encrypted_room_unsupported",
|
|
210
|
+
message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
const res = await this.client.sendTextMessage(roomId, out.text);
|
|
215
|
+
return { ok: true, messageId: res.event_id };
|
|
216
|
+
} catch (err) {
|
|
217
|
+
return mapMatrixError(err);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
onInbound(handler) {
|
|
221
|
+
this.inboundHandler = handler;
|
|
222
|
+
return () => {
|
|
223
|
+
if (this.inboundHandler === handler) this.inboundHandler = void 0;
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/** Escape hatch (D421) — caller can drive matrix-js-sdk directly for advanced features. */
|
|
227
|
+
getClient() {
|
|
228
|
+
return this.client;
|
|
229
|
+
}
|
|
230
|
+
/** Used by tests to install a mock SDK client + flip connected flag. */
|
|
231
|
+
_installClient(client) {
|
|
232
|
+
this.client = client;
|
|
233
|
+
this.connected = true;
|
|
234
|
+
this.attachSync();
|
|
235
|
+
}
|
|
236
|
+
attachSync() {
|
|
237
|
+
if (this.client === void 0) return;
|
|
238
|
+
const client = this.client;
|
|
239
|
+
const opts = {
|
|
240
|
+
botUserId: this.opts.userId,
|
|
241
|
+
freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS
|
|
242
|
+
};
|
|
243
|
+
this.subscription = subscribeToTimeline(
|
|
244
|
+
client,
|
|
245
|
+
(ev, room) => {
|
|
246
|
+
void this.dispatchTimelineEvent(ev, room).catch((err) => {
|
|
247
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
248
|
+
process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}
|
|
249
|
+
`);
|
|
250
|
+
});
|
|
251
|
+
},
|
|
252
|
+
opts
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
async dispatchTimelineEvent(event, room) {
|
|
256
|
+
if (this.isEncrypted(room.roomId)) {
|
|
257
|
+
this.warnEncryptedOnce(room.roomId);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const normalized = matrixEventToMessageEvent(event, room);
|
|
261
|
+
if (normalized === void 0) return;
|
|
262
|
+
if (this.inboundHandler === void 0) return;
|
|
263
|
+
try {
|
|
264
|
+
await this.inboundHandler(normalized);
|
|
265
|
+
} catch (err) {
|
|
266
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
267
|
+
process.stderr.write(`[gateway-matrix] handler threw: ${m}
|
|
268
|
+
`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
isEncrypted(roomId) {
|
|
272
|
+
if (this.client === void 0) return false;
|
|
273
|
+
if (this.client.isRoomEncrypted === void 0) return false;
|
|
274
|
+
try {
|
|
275
|
+
return this.client.isRoomEncrypted(roomId);
|
|
276
|
+
} catch {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
warnEncryptedOnce(roomId) {
|
|
281
|
+
if (this.warnedEncrypted.has(roomId)) return;
|
|
282
|
+
this.warnedEncrypted.add(roomId);
|
|
283
|
+
process.stderr.write(
|
|
284
|
+
`[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)
|
|
285
|
+
`
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
function mapMatrixError(err) {
|
|
290
|
+
const e = err;
|
|
291
|
+
const status = e.httpStatus ?? 0;
|
|
292
|
+
if (status === 429 || e.errcode === "M_LIMIT_EXCEEDED") {
|
|
293
|
+
return { ok: false, error: { code: "rate_limit", message: e.message ?? "Matrix rate limit" } };
|
|
294
|
+
}
|
|
295
|
+
if (status === 401 || status === 403 || e.errcode === "M_FORBIDDEN") {
|
|
296
|
+
return {
|
|
297
|
+
ok: false,
|
|
298
|
+
error: { code: "permission_denied", message: e.message ?? "Matrix permission error" }
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
if (status === 404 || e.errcode === "M_NOT_FOUND") {
|
|
302
|
+
return {
|
|
303
|
+
ok: false,
|
|
304
|
+
error: { code: "not_found", message: e.message ?? "Matrix resource not found" }
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
ok: false,
|
|
309
|
+
error: {
|
|
310
|
+
code: "send_failed",
|
|
311
|
+
message: e.message ?? (err instanceof Error ? err.message : String(err))
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
exports.AliasCache = AliasCache;
|
|
317
|
+
exports.ConfigurationError = ConfigurationError;
|
|
318
|
+
exports.EncryptedRoomError = EncryptedRoomError;
|
|
319
|
+
exports.MatrixAdapter = MatrixAdapter;
|
|
320
|
+
exports.SDKNotInstalledError = SDKNotInstalledError;
|
|
321
|
+
exports.detectChannelType = detectChannelType;
|
|
322
|
+
exports.matrixEventToMessageEvent = matrixEventToMessageEvent;
|
|
323
|
+
exports.shouldDispatchSyncEvent = shouldDispatchSyncEvent;
|
|
324
|
+
exports.subscribeToTimeline = subscribeToTimeline;
|
|
325
|
+
//# sourceMappingURL=index.cjs.map
|
|
326
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/alias.ts","../src/client.ts","../src/room-state.ts","../src/normalize.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AAO,CAAA,CAAE,OAAA,KAAY,kBAAA,EAAoB;AACtD,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,IAAA,EAAM,YAAA,EAAc,OAAA,EAAS,CAAA,CAAE,OAAA,IAAW,mBAAA,EAAoB,EAAE;AAAA,EAC/F;AACA,EAAA,IAAI,WAAW,GAAA,IAAO,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,YAAY,aAAA,EAAe;AACnE,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,qBAAqB,OAAA,EAAS,CAAA,CAAE,WAAW,yBAAA;AAA0B,KACtF;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,OAAA,KAAY,aAAA,EAAe;AACjD,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,CAAA,CAAE,WAAW,2BAAA;AAA4B,KAChF;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","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-matrix`.\n */\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport interface ConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\nexport class ConfigurationError extends Error {\n override readonly name = \"ConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n constructor(opts: ConfigurationErrorOptions) {\n super(opts.message ?? `gateway-matrix: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\n super({\n code: \"sdk_not_installed\",\n message:\n 'gateway-matrix: peer-dep \"matrix-js-sdk\" not installed. Run: pnpm add matrix-js-sdk',\n detail: \"matrix-js-sdk\",\n });\n }\n}\n\nexport class EncryptedRoomError extends ConfigurationError {\n constructor(roomId: string) {\n super({\n code: \"encrypted_room_unsupported\",\n message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,\n detail: roomId,\n });\n }\n}\n","/**\n * Matrix alias resolution + caching (D419).\n *\n * Accepts:\n * - Room id (`!abc123:server`) — pass-through.\n * - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.\n *\n * Other shapes throw `ConfigurationError({ code: \"invalid_room_ref\" })`.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */\nexport interface AliasResolverClient {\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n}\n\nexport class AliasCache {\n private readonly cache = new Map<string, string>();\n\n /** Returns the room id; resolves aliases via the client + caches. */\n async resolve(client: AliasResolverClient, refOrId: string): Promise<string> {\n if (refOrId.startsWith(\"!\")) return refOrId;\n if (!refOrId.startsWith(\"#\")) {\n throw new ConfigurationError({\n code: \"invalid_room_ref\",\n message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} — expected '!' (room id) or '#' (alias)`,\n });\n }\n const cached = this.cache.get(refOrId);\n if (cached !== undefined) return cached;\n const { room_id } = await client.getRoomIdForAlias(refOrId);\n this.cache.set(refOrId, room_id);\n return room_id;\n }\n\n /** Drop all cached resolutions. Useful for tests + admin-rename recovery. */\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n","/**\n * Lazy `matrix-js-sdk` loader.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MatrixClientLike } from \"./sync.js\";\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport interface MatrixSdkClient extends MatrixClientLike {\n startClient(opts: { initialSyncLimit: number }): Promise<void>;\n stopClient(): void;\n sendTextMessage(roomId: string, text: string): Promise<{ event_id: string }>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n getRoom(roomId: string): MatrixRoomLike | null;\n isRoomEncrypted?(roomId: string): boolean;\n /** Best-effort current user id; matrix-js-sdk returns `string | null`. */\n getUserId(): string | null;\n}\n\ninterface MatrixSdkModule {\n createClient(opts: { baseUrl: string; accessToken: string; userId: string }): MatrixSdkClient;\n}\n\nexport async function loadMatrixSdk(): Promise<MatrixSdkModule> {\n try {\n const mod = await import(\"matrix-js-sdk\");\n return mod as unknown as MatrixSdkModule;\n } catch {\n throw new SDKNotInstalledError();\n }\n}\n","/**\n * Room state helpers (D416).\n *\n * Matrix has no native \"DM\" concept — DMs are rooms with 2 members.\n * The canonical heuristic: `member_count === 2 → \"dm\"`, else `\"group\"`.\n */\n\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport function detectChannelType(room: MatrixRoomLike | undefined): \"dm\" | \"group\" {\n if (room === undefined) return \"group\";\n return room.getJoinedMemberCount() === 2 ? \"dm\" : \"group\";\n}\n","/**\n * Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.\n *\n * @public\n */\n\nimport type { MatrixMessageEvent } from \"@theokit/gateway\";\n\nimport { detectChannelType } from \"./room-state.js\";\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport function matrixEventToMessageEvent(\n event: MatrixEventLike,\n room: MatrixRoomLike,\n): MatrixMessageEvent | undefined {\n const eventId = event.getId();\n const sender = event.getSender();\n if (eventId === undefined || sender === undefined) return undefined;\n const channelType = detectChannelType(room);\n const content = event.getContent();\n const body = content.body ?? \"\";\n return {\n id: eventId,\n platform: \"matrix\",\n sender: { id: sender },\n channel: {\n id: room.roomId,\n type: channelType,\n },\n text: body,\n receivedAt: event.getTs(),\n matrix: {\n roomId: room.roomId,\n eventId,\n memberCount: room.getJoinedMemberCount(),\n raw: event,\n },\n };\n}\n","/**\n * Sync timeline filter (D415, EC-3 absorbed).\n *\n * Wraps `client.on(\"Room.timeline\", listener)` with 3 filters:\n *\n * 1. Drop non-`m.room.message` events (D413).\n * 2. Drop bot's own messages (loop guard, D275 mirror).\n * 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)\n * — initial sync from `matrix-js-sdk` delivers ~10 historical events\n * per joined room, which would otherwise trigger an LLM-call storm.\n */\n\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport interface SyncFilterOpts {\n readonly botUserId: string;\n readonly freshnessWindowMs: number;\n}\n\nexport function shouldDispatchSyncEvent(\n event: MatrixEventLike,\n opts: SyncFilterOpts,\n now = Date.now(),\n): boolean {\n if (event.getType() !== \"m.room.message\") return false;\n const sender = event.getSender();\n if (sender === opts.botUserId) return false;\n if (event.getTs() < now - opts.freshnessWindowMs) return false;\n return true;\n}\n\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\nexport interface MatrixClientLike {\n on(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n off(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n}\n\nexport function subscribeToTimeline(\n client: MatrixClientLike,\n handler: (event: MatrixEventLike, room: MatrixRoomLike) => void,\n opts: SyncFilterOpts,\n): TimelineSubscription {\n const wrapped = (event: MatrixEventLike, room: MatrixRoomLike): void => {\n if (!shouldDispatchSyncEvent(event, opts)) return;\n handler(event, room);\n };\n client.on(\"Room.timeline\", wrapped);\n return {\n unsubscribe(): void {\n client.off(\"Room.timeline\", wrapped);\n },\n };\n}\n","/**\n * `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.\n * ADRs D413-D421.\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 { AliasCache } from \"./alias.js\";\nimport { loadMatrixSdk, type MatrixSdkClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { subscribeToTimeline, type TimelineSubscription } from \"./sync.js\";\nimport type { MatrixAdapterOptions, MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nconst DEFAULT_FRESHNESS_MS = 60_000;\nconst INITIAL_SYNC_LIMIT = 10;\n\nexport class MatrixAdapter extends BasePlatformAdapter {\n readonly platform = \"matrix\" as const;\n private readonly opts: MatrixAdapterOptions;\n private client: MatrixSdkClient | undefined;\n private subscription: TimelineSubscription | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private readonly aliasCache = new AliasCache();\n private connected = false;\n private readonly warnedEncrypted = new Set<string>();\n\n constructor(opts: MatrixAdapterOptions) {\n super();\n if (opts.homeserverUrl.length === 0) {\n throw new ConfigurationError({\n code: \"homeserver_url_required\",\n message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. \"https://matrix.org\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-matrix: opts.accessToken is empty (Element → Settings → Help & About → Advanced → Access Token)\",\n });\n }\n if (opts.userId.length === 0 || !opts.userId.startsWith(\"@\")) {\n throw new ConfigurationError({\n code: \"user_id_required\",\n message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. \"@bot:matrix.org\")',\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const mod = await loadMatrixSdk();\n this.client = mod.createClient({\n baseUrl: this.opts.homeserverUrl,\n accessToken: this.opts.accessToken,\n userId: this.opts.userId,\n });\n await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });\n this.attachSync();\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-matrix] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n this.client?.stopClient();\n this.client = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n this.aliasCache.clear();\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.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(this.client, out.channel.id);\n if (this.isEncrypted(roomId)) {\n this.warnEncryptedOnce(roomId);\n return {\n ok: false,\n error: {\n code: \"encrypted_room_unsupported\",\n message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`,\n },\n };\n }\n const res = await this.client.sendTextMessage(roomId, out.text);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(err);\n }\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 (D421) — caller can drive matrix-js-sdk directly for advanced features. */\n getClient(): MatrixSdkClient | undefined {\n return this.client;\n }\n\n /** Used by tests to install a mock SDK client + flip connected flag. */\n _installClient(client: MatrixSdkClient): void {\n this.client = client;\n this.connected = true;\n this.attachSync();\n }\n\n private attachSync(): void {\n if (this.client === undefined) return;\n const client = this.client;\n const opts = {\n botUserId: this.opts.userId,\n freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS,\n };\n this.subscription = subscribeToTimeline(\n client,\n (ev: MatrixEventLike, room: MatrixRoomLike) => {\n void this.dispatchTimelineEvent(ev, room).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}\\n`);\n });\n },\n opts,\n );\n }\n\n private async dispatchTimelineEvent(event: MatrixEventLike, room: MatrixRoomLike): Promise<void> {\n if (this.isEncrypted(room.roomId)) {\n this.warnEncryptedOnce(room.roomId);\n return;\n }\n const normalized = matrixEventToMessageEvent(event, room);\n if (normalized === undefined) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] handler threw: ${m}\\n`);\n }\n }\n\n private isEncrypted(roomId: string): boolean {\n if (this.client === undefined) return false;\n if (this.client.isRoomEncrypted === undefined) return false;\n try {\n return this.client.isRoomEncrypted(roomId);\n } catch {\n return false;\n }\n }\n\n private warnEncryptedOnce(roomId: string): void {\n if (this.warnedEncrypted.has(roomId)) return;\n this.warnedEncrypted.add(roomId);\n process.stderr.write(\n `[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)\\n`,\n );\n }\n}\n\ninterface MatrixRestError {\n httpStatus?: number;\n errcode?: string;\n message?: string;\n name?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\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"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, MatrixMessageEvent } from '@theokit/gateway';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Public option types + minimal Matrix shape narrowing (kept local so
|
|
5
|
+
* we don't force `matrix-js-sdk` types on consumers).
|
|
6
|
+
*
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
interface MatrixAdapterOptions {
|
|
10
|
+
/** Homeserver URL (e.g. `https://matrix.org`). No trailing slash. (D414) */
|
|
11
|
+
readonly homeserverUrl: string;
|
|
12
|
+
/** Long-lived access token (`syt_xxx`). Generate via Element → Settings → Help & About → Advanced. */
|
|
13
|
+
readonly accessToken: string;
|
|
14
|
+
/** Bot's full Matrix user id (`@bot:matrix.org`). */
|
|
15
|
+
readonly userId: string;
|
|
16
|
+
/**
|
|
17
|
+
* EC-3 freshness window in milliseconds — events older than this on
|
|
18
|
+
* initial sync are dropped. Default 60000 (60s).
|
|
19
|
+
*/
|
|
20
|
+
readonly freshnessWindowMs?: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Minimal subset of `MatrixEvent` we read. Real events from
|
|
24
|
+
* `matrix-js-sdk` carry many more methods — preserved via
|
|
25
|
+
* `event.matrix.raw`.
|
|
26
|
+
*
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
interface MatrixEventLike {
|
|
30
|
+
getId(): string | undefined;
|
|
31
|
+
getSender(): string | undefined;
|
|
32
|
+
getRoomId(): string | undefined;
|
|
33
|
+
getType(): string;
|
|
34
|
+
getContent(): {
|
|
35
|
+
body?: string;
|
|
36
|
+
msgtype?: string;
|
|
37
|
+
};
|
|
38
|
+
getTs(): number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Minimal subset of `Room` (sync timeline target).
|
|
42
|
+
*
|
|
43
|
+
* @public
|
|
44
|
+
*/
|
|
45
|
+
interface MatrixRoomLike {
|
|
46
|
+
readonly roomId: string;
|
|
47
|
+
getJoinedMemberCount(): number;
|
|
48
|
+
name?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Sync timeline filter (D415, EC-3 absorbed).
|
|
53
|
+
*
|
|
54
|
+
* Wraps `client.on("Room.timeline", listener)` with 3 filters:
|
|
55
|
+
*
|
|
56
|
+
* 1. Drop non-`m.room.message` events (D413).
|
|
57
|
+
* 2. Drop bot's own messages (loop guard, D275 mirror).
|
|
58
|
+
* 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)
|
|
59
|
+
* — initial sync from `matrix-js-sdk` delivers ~10 historical events
|
|
60
|
+
* per joined room, which would otherwise trigger an LLM-call storm.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
interface SyncFilterOpts {
|
|
64
|
+
readonly botUserId: string;
|
|
65
|
+
readonly freshnessWindowMs: number;
|
|
66
|
+
}
|
|
67
|
+
declare function shouldDispatchSyncEvent(event: MatrixEventLike, opts: SyncFilterOpts, now?: number): boolean;
|
|
68
|
+
interface TimelineSubscription {
|
|
69
|
+
unsubscribe(): void;
|
|
70
|
+
}
|
|
71
|
+
interface MatrixClientLike {
|
|
72
|
+
on(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
73
|
+
off(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
74
|
+
}
|
|
75
|
+
declare function subscribeToTimeline(client: MatrixClientLike, handler: (event: MatrixEventLike, room: MatrixRoomLike) => void, opts: SyncFilterOpts): TimelineSubscription;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Lazy `matrix-js-sdk` loader.
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
interface MatrixSdkClient extends MatrixClientLike {
|
|
82
|
+
startClient(opts: {
|
|
83
|
+
initialSyncLimit: number;
|
|
84
|
+
}): Promise<void>;
|
|
85
|
+
stopClient(): void;
|
|
86
|
+
sendTextMessage(roomId: string, text: string): Promise<{
|
|
87
|
+
event_id: string;
|
|
88
|
+
}>;
|
|
89
|
+
getRoomIdForAlias(alias: string): Promise<{
|
|
90
|
+
room_id: string;
|
|
91
|
+
}>;
|
|
92
|
+
getRoom(roomId: string): MatrixRoomLike | null;
|
|
93
|
+
isRoomEncrypted?(roomId: string): boolean;
|
|
94
|
+
/** Best-effort current user id; matrix-js-sdk returns `string | null`. */
|
|
95
|
+
getUserId(): string | null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.
|
|
100
|
+
* ADRs D413-D421.
|
|
101
|
+
*
|
|
102
|
+
* @public
|
|
103
|
+
*/
|
|
104
|
+
|
|
105
|
+
declare class MatrixAdapter extends BasePlatformAdapter {
|
|
106
|
+
readonly platform: "matrix";
|
|
107
|
+
private readonly opts;
|
|
108
|
+
private client;
|
|
109
|
+
private subscription;
|
|
110
|
+
private inboundHandler;
|
|
111
|
+
private readonly aliasCache;
|
|
112
|
+
private connected;
|
|
113
|
+
private readonly warnedEncrypted;
|
|
114
|
+
constructor(opts: MatrixAdapterOptions);
|
|
115
|
+
connect(): Promise<boolean>;
|
|
116
|
+
disconnect(): Promise<void>;
|
|
117
|
+
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
118
|
+
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
119
|
+
/** Escape hatch (D421) — caller can drive matrix-js-sdk directly for advanced features. */
|
|
120
|
+
getClient(): MatrixSdkClient | undefined;
|
|
121
|
+
/** Used by tests to install a mock SDK client + flip connected flag. */
|
|
122
|
+
_installClient(client: MatrixSdkClient): void;
|
|
123
|
+
private attachSync;
|
|
124
|
+
private dispatchTimelineEvent;
|
|
125
|
+
private isEncrypted;
|
|
126
|
+
private warnEncryptedOnce;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Matrix alias resolution + caching (D419).
|
|
131
|
+
*
|
|
132
|
+
* Accepts:
|
|
133
|
+
* - Room id (`!abc123:server`) — pass-through.
|
|
134
|
+
* - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.
|
|
135
|
+
*
|
|
136
|
+
* Other shapes throw `ConfigurationError({ code: "invalid_room_ref" })`.
|
|
137
|
+
*/
|
|
138
|
+
/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */
|
|
139
|
+
interface AliasResolverClient {
|
|
140
|
+
getRoomIdForAlias(alias: string): Promise<{
|
|
141
|
+
room_id: string;
|
|
142
|
+
}>;
|
|
143
|
+
}
|
|
144
|
+
declare class AliasCache {
|
|
145
|
+
private readonly cache;
|
|
146
|
+
/** Returns the room id; resolves aliases via the client + caches. */
|
|
147
|
+
resolve(client: AliasResolverClient, refOrId: string): Promise<string>;
|
|
148
|
+
/** Drop all cached resolutions. Useful for tests + admin-rename recovery. */
|
|
149
|
+
clear(): void;
|
|
150
|
+
size(): number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Typed errors for `@theokit/gateway-matrix`.
|
|
155
|
+
*/
|
|
156
|
+
/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
|
|
157
|
+
interface ConfigurationErrorOptions {
|
|
158
|
+
readonly code: string;
|
|
159
|
+
readonly message?: string;
|
|
160
|
+
readonly detail?: string;
|
|
161
|
+
}
|
|
162
|
+
declare class ConfigurationError extends Error {
|
|
163
|
+
readonly name = "ConfigurationError";
|
|
164
|
+
readonly code: string;
|
|
165
|
+
readonly detail: string | undefined;
|
|
166
|
+
constructor(opts: ConfigurationErrorOptions);
|
|
167
|
+
}
|
|
168
|
+
declare class SDKNotInstalledError extends ConfigurationError {
|
|
169
|
+
constructor();
|
|
170
|
+
}
|
|
171
|
+
declare class EncryptedRoomError extends ConfigurationError {
|
|
172
|
+
constructor(roomId: string);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.
|
|
177
|
+
*
|
|
178
|
+
* @public
|
|
179
|
+
*/
|
|
180
|
+
|
|
181
|
+
declare function matrixEventToMessageEvent(event: MatrixEventLike, room: MatrixRoomLike): MatrixMessageEvent | undefined;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Room state helpers (D416).
|
|
185
|
+
*
|
|
186
|
+
* Matrix has no native "DM" concept — DMs are rooms with 2 members.
|
|
187
|
+
* The canonical heuristic: `member_count === 2 → "dm"`, else `"group"`.
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
declare function detectChannelType(room: MatrixRoomLike | undefined): "dm" | "group";
|
|
191
|
+
|
|
192
|
+
export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, type MatrixAdapterOptions, type MatrixClientLike, type MatrixEventLike, type MatrixRoomLike, SDKNotInstalledError, type SyncFilterOpts, type TimelineSubscription, detectChannelType, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, MatrixMessageEvent } from '@theokit/gateway';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Public option types + minimal Matrix shape narrowing (kept local so
|
|
5
|
+
* we don't force `matrix-js-sdk` types on consumers).
|
|
6
|
+
*
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
interface MatrixAdapterOptions {
|
|
10
|
+
/** Homeserver URL (e.g. `https://matrix.org`). No trailing slash. (D414) */
|
|
11
|
+
readonly homeserverUrl: string;
|
|
12
|
+
/** Long-lived access token (`syt_xxx`). Generate via Element → Settings → Help & About → Advanced. */
|
|
13
|
+
readonly accessToken: string;
|
|
14
|
+
/** Bot's full Matrix user id (`@bot:matrix.org`). */
|
|
15
|
+
readonly userId: string;
|
|
16
|
+
/**
|
|
17
|
+
* EC-3 freshness window in milliseconds — events older than this on
|
|
18
|
+
* initial sync are dropped. Default 60000 (60s).
|
|
19
|
+
*/
|
|
20
|
+
readonly freshnessWindowMs?: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Minimal subset of `MatrixEvent` we read. Real events from
|
|
24
|
+
* `matrix-js-sdk` carry many more methods — preserved via
|
|
25
|
+
* `event.matrix.raw`.
|
|
26
|
+
*
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
interface MatrixEventLike {
|
|
30
|
+
getId(): string | undefined;
|
|
31
|
+
getSender(): string | undefined;
|
|
32
|
+
getRoomId(): string | undefined;
|
|
33
|
+
getType(): string;
|
|
34
|
+
getContent(): {
|
|
35
|
+
body?: string;
|
|
36
|
+
msgtype?: string;
|
|
37
|
+
};
|
|
38
|
+
getTs(): number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Minimal subset of `Room` (sync timeline target).
|
|
42
|
+
*
|
|
43
|
+
* @public
|
|
44
|
+
*/
|
|
45
|
+
interface MatrixRoomLike {
|
|
46
|
+
readonly roomId: string;
|
|
47
|
+
getJoinedMemberCount(): number;
|
|
48
|
+
name?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Sync timeline filter (D415, EC-3 absorbed).
|
|
53
|
+
*
|
|
54
|
+
* Wraps `client.on("Room.timeline", listener)` with 3 filters:
|
|
55
|
+
*
|
|
56
|
+
* 1. Drop non-`m.room.message` events (D413).
|
|
57
|
+
* 2. Drop bot's own messages (loop guard, D275 mirror).
|
|
58
|
+
* 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)
|
|
59
|
+
* — initial sync from `matrix-js-sdk` delivers ~10 historical events
|
|
60
|
+
* per joined room, which would otherwise trigger an LLM-call storm.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
interface SyncFilterOpts {
|
|
64
|
+
readonly botUserId: string;
|
|
65
|
+
readonly freshnessWindowMs: number;
|
|
66
|
+
}
|
|
67
|
+
declare function shouldDispatchSyncEvent(event: MatrixEventLike, opts: SyncFilterOpts, now?: number): boolean;
|
|
68
|
+
interface TimelineSubscription {
|
|
69
|
+
unsubscribe(): void;
|
|
70
|
+
}
|
|
71
|
+
interface MatrixClientLike {
|
|
72
|
+
on(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
73
|
+
off(event: "Room.timeline", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;
|
|
74
|
+
}
|
|
75
|
+
declare function subscribeToTimeline(client: MatrixClientLike, handler: (event: MatrixEventLike, room: MatrixRoomLike) => void, opts: SyncFilterOpts): TimelineSubscription;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Lazy `matrix-js-sdk` loader.
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
interface MatrixSdkClient extends MatrixClientLike {
|
|
82
|
+
startClient(opts: {
|
|
83
|
+
initialSyncLimit: number;
|
|
84
|
+
}): Promise<void>;
|
|
85
|
+
stopClient(): void;
|
|
86
|
+
sendTextMessage(roomId: string, text: string): Promise<{
|
|
87
|
+
event_id: string;
|
|
88
|
+
}>;
|
|
89
|
+
getRoomIdForAlias(alias: string): Promise<{
|
|
90
|
+
room_id: string;
|
|
91
|
+
}>;
|
|
92
|
+
getRoom(roomId: string): MatrixRoomLike | null;
|
|
93
|
+
isRoomEncrypted?(roomId: string): boolean;
|
|
94
|
+
/** Best-effort current user id; matrix-js-sdk returns `string | null`. */
|
|
95
|
+
getUserId(): string | null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.
|
|
100
|
+
* ADRs D413-D421.
|
|
101
|
+
*
|
|
102
|
+
* @public
|
|
103
|
+
*/
|
|
104
|
+
|
|
105
|
+
declare class MatrixAdapter extends BasePlatformAdapter {
|
|
106
|
+
readonly platform: "matrix";
|
|
107
|
+
private readonly opts;
|
|
108
|
+
private client;
|
|
109
|
+
private subscription;
|
|
110
|
+
private inboundHandler;
|
|
111
|
+
private readonly aliasCache;
|
|
112
|
+
private connected;
|
|
113
|
+
private readonly warnedEncrypted;
|
|
114
|
+
constructor(opts: MatrixAdapterOptions);
|
|
115
|
+
connect(): Promise<boolean>;
|
|
116
|
+
disconnect(): Promise<void>;
|
|
117
|
+
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
118
|
+
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
119
|
+
/** Escape hatch (D421) — caller can drive matrix-js-sdk directly for advanced features. */
|
|
120
|
+
getClient(): MatrixSdkClient | undefined;
|
|
121
|
+
/** Used by tests to install a mock SDK client + flip connected flag. */
|
|
122
|
+
_installClient(client: MatrixSdkClient): void;
|
|
123
|
+
private attachSync;
|
|
124
|
+
private dispatchTimelineEvent;
|
|
125
|
+
private isEncrypted;
|
|
126
|
+
private warnEncryptedOnce;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Matrix alias resolution + caching (D419).
|
|
131
|
+
*
|
|
132
|
+
* Accepts:
|
|
133
|
+
* - Room id (`!abc123:server`) — pass-through.
|
|
134
|
+
* - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.
|
|
135
|
+
*
|
|
136
|
+
* Other shapes throw `ConfigurationError({ code: "invalid_room_ref" })`.
|
|
137
|
+
*/
|
|
138
|
+
/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */
|
|
139
|
+
interface AliasResolverClient {
|
|
140
|
+
getRoomIdForAlias(alias: string): Promise<{
|
|
141
|
+
room_id: string;
|
|
142
|
+
}>;
|
|
143
|
+
}
|
|
144
|
+
declare class AliasCache {
|
|
145
|
+
private readonly cache;
|
|
146
|
+
/** Returns the room id; resolves aliases via the client + caches. */
|
|
147
|
+
resolve(client: AliasResolverClient, refOrId: string): Promise<string>;
|
|
148
|
+
/** Drop all cached resolutions. Useful for tests + admin-rename recovery. */
|
|
149
|
+
clear(): void;
|
|
150
|
+
size(): number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Typed errors for `@theokit/gateway-matrix`.
|
|
155
|
+
*/
|
|
156
|
+
/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
|
|
157
|
+
interface ConfigurationErrorOptions {
|
|
158
|
+
readonly code: string;
|
|
159
|
+
readonly message?: string;
|
|
160
|
+
readonly detail?: string;
|
|
161
|
+
}
|
|
162
|
+
declare class ConfigurationError extends Error {
|
|
163
|
+
readonly name = "ConfigurationError";
|
|
164
|
+
readonly code: string;
|
|
165
|
+
readonly detail: string | undefined;
|
|
166
|
+
constructor(opts: ConfigurationErrorOptions);
|
|
167
|
+
}
|
|
168
|
+
declare class SDKNotInstalledError extends ConfigurationError {
|
|
169
|
+
constructor();
|
|
170
|
+
}
|
|
171
|
+
declare class EncryptedRoomError extends ConfigurationError {
|
|
172
|
+
constructor(roomId: string);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.
|
|
177
|
+
*
|
|
178
|
+
* @public
|
|
179
|
+
*/
|
|
180
|
+
|
|
181
|
+
declare function matrixEventToMessageEvent(event: MatrixEventLike, room: MatrixRoomLike): MatrixMessageEvent | undefined;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Room state helpers (D416).
|
|
185
|
+
*
|
|
186
|
+
* Matrix has no native "DM" concept — DMs are rooms with 2 members.
|
|
187
|
+
* The canonical heuristic: `member_count === 2 → "dm"`, else `"group"`.
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
declare function detectChannelType(room: MatrixRoomLike | undefined): "dm" | "group";
|
|
191
|
+
|
|
192
|
+
export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, type MatrixAdapterOptions, type MatrixClientLike, type MatrixEventLike, type MatrixRoomLike, SDKNotInstalledError, type SyncFilterOpts, type TimelineSubscription, detectChannelType, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { BasePlatformAdapter } from '@theokit/gateway';
|
|
2
|
+
|
|
3
|
+
// src/adapter.ts
|
|
4
|
+
|
|
5
|
+
// src/errors.ts
|
|
6
|
+
var ConfigurationError = class extends Error {
|
|
7
|
+
name = "ConfigurationError";
|
|
8
|
+
code;
|
|
9
|
+
detail;
|
|
10
|
+
constructor(opts) {
|
|
11
|
+
super(opts.message ?? `gateway-matrix: ${opts.code}`);
|
|
12
|
+
this.code = opts.code;
|
|
13
|
+
this.detail = opts.detail;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var SDKNotInstalledError = class extends ConfigurationError {
|
|
17
|
+
constructor() {
|
|
18
|
+
super({
|
|
19
|
+
code: "sdk_not_installed",
|
|
20
|
+
message: 'gateway-matrix: peer-dep "matrix-js-sdk" not installed. Run: pnpm add matrix-js-sdk',
|
|
21
|
+
detail: "matrix-js-sdk"
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var EncryptedRoomError = class extends ConfigurationError {
|
|
26
|
+
constructor(roomId) {
|
|
27
|
+
super({
|
|
28
|
+
code: "encrypted_room_unsupported",
|
|
29
|
+
message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,
|
|
30
|
+
detail: roomId
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// src/alias.ts
|
|
36
|
+
var AliasCache = class {
|
|
37
|
+
cache = /* @__PURE__ */ new Map();
|
|
38
|
+
/** Returns the room id; resolves aliases via the client + caches. */
|
|
39
|
+
async resolve(client, refOrId) {
|
|
40
|
+
if (refOrId.startsWith("!")) return refOrId;
|
|
41
|
+
if (!refOrId.startsWith("#")) {
|
|
42
|
+
throw new ConfigurationError({
|
|
43
|
+
code: "invalid_room_ref",
|
|
44
|
+
message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} \u2014 expected '!' (room id) or '#' (alias)`
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
const cached = this.cache.get(refOrId);
|
|
48
|
+
if (cached !== void 0) return cached;
|
|
49
|
+
const { room_id } = await client.getRoomIdForAlias(refOrId);
|
|
50
|
+
this.cache.set(refOrId, room_id);
|
|
51
|
+
return room_id;
|
|
52
|
+
}
|
|
53
|
+
/** Drop all cached resolutions. Useful for tests + admin-rename recovery. */
|
|
54
|
+
clear() {
|
|
55
|
+
this.cache.clear();
|
|
56
|
+
}
|
|
57
|
+
size() {
|
|
58
|
+
return this.cache.size;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/client.ts
|
|
63
|
+
async function loadMatrixSdk() {
|
|
64
|
+
try {
|
|
65
|
+
const mod = await import('matrix-js-sdk');
|
|
66
|
+
return mod;
|
|
67
|
+
} catch {
|
|
68
|
+
throw new SDKNotInstalledError();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/room-state.ts
|
|
73
|
+
function detectChannelType(room) {
|
|
74
|
+
if (room === void 0) return "group";
|
|
75
|
+
return room.getJoinedMemberCount() === 2 ? "dm" : "group";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/normalize.ts
|
|
79
|
+
function matrixEventToMessageEvent(event, room) {
|
|
80
|
+
const eventId = event.getId();
|
|
81
|
+
const sender = event.getSender();
|
|
82
|
+
if (eventId === void 0 || sender === void 0) return void 0;
|
|
83
|
+
const channelType = detectChannelType(room);
|
|
84
|
+
const content = event.getContent();
|
|
85
|
+
const body = content.body ?? "";
|
|
86
|
+
return {
|
|
87
|
+
id: eventId,
|
|
88
|
+
platform: "matrix",
|
|
89
|
+
sender: { id: sender },
|
|
90
|
+
channel: {
|
|
91
|
+
id: room.roomId,
|
|
92
|
+
type: channelType
|
|
93
|
+
},
|
|
94
|
+
text: body,
|
|
95
|
+
receivedAt: event.getTs(),
|
|
96
|
+
matrix: {
|
|
97
|
+
roomId: room.roomId,
|
|
98
|
+
eventId,
|
|
99
|
+
memberCount: room.getJoinedMemberCount(),
|
|
100
|
+
raw: event
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/sync.ts
|
|
106
|
+
function shouldDispatchSyncEvent(event, opts, now = Date.now()) {
|
|
107
|
+
if (event.getType() !== "m.room.message") return false;
|
|
108
|
+
const sender = event.getSender();
|
|
109
|
+
if (sender === opts.botUserId) return false;
|
|
110
|
+
if (event.getTs() < now - opts.freshnessWindowMs) return false;
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
function subscribeToTimeline(client, handler, opts) {
|
|
114
|
+
const wrapped = (event, room) => {
|
|
115
|
+
if (!shouldDispatchSyncEvent(event, opts)) return;
|
|
116
|
+
handler(event, room);
|
|
117
|
+
};
|
|
118
|
+
client.on("Room.timeline", wrapped);
|
|
119
|
+
return {
|
|
120
|
+
unsubscribe() {
|
|
121
|
+
client.off("Room.timeline", wrapped);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/adapter.ts
|
|
127
|
+
var DEFAULT_FRESHNESS_MS = 6e4;
|
|
128
|
+
var INITIAL_SYNC_LIMIT = 10;
|
|
129
|
+
var MatrixAdapter = class extends BasePlatformAdapter {
|
|
130
|
+
platform = "matrix";
|
|
131
|
+
opts;
|
|
132
|
+
client;
|
|
133
|
+
subscription;
|
|
134
|
+
inboundHandler;
|
|
135
|
+
aliasCache = new AliasCache();
|
|
136
|
+
connected = false;
|
|
137
|
+
warnedEncrypted = /* @__PURE__ */ new Set();
|
|
138
|
+
constructor(opts) {
|
|
139
|
+
super();
|
|
140
|
+
if (opts.homeserverUrl.length === 0) {
|
|
141
|
+
throw new ConfigurationError({
|
|
142
|
+
code: "homeserver_url_required",
|
|
143
|
+
message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. "https://matrix.org")'
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
if (opts.accessToken.length === 0) {
|
|
147
|
+
throw new ConfigurationError({
|
|
148
|
+
code: "access_token_required",
|
|
149
|
+
message: "gateway-matrix: opts.accessToken is empty (Element \u2192 Settings \u2192 Help & About \u2192 Advanced \u2192 Access Token)"
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
if (opts.userId.length === 0 || !opts.userId.startsWith("@")) {
|
|
153
|
+
throw new ConfigurationError({
|
|
154
|
+
code: "user_id_required",
|
|
155
|
+
message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. "@bot:matrix.org")'
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
this.opts = opts;
|
|
159
|
+
}
|
|
160
|
+
async connect() {
|
|
161
|
+
if (this.connected) return true;
|
|
162
|
+
try {
|
|
163
|
+
const mod = await loadMatrixSdk();
|
|
164
|
+
this.client = mod.createClient({
|
|
165
|
+
baseUrl: this.opts.homeserverUrl,
|
|
166
|
+
accessToken: this.opts.accessToken,
|
|
167
|
+
userId: this.opts.userId
|
|
168
|
+
});
|
|
169
|
+
await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });
|
|
170
|
+
this.attachSync();
|
|
171
|
+
this.connected = true;
|
|
172
|
+
return true;
|
|
173
|
+
} catch (err) {
|
|
174
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
175
|
+
process.stderr.write(`[gateway-matrix] connect failed: ${msg}
|
|
176
|
+
`);
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async disconnect() {
|
|
181
|
+
if (!this.connected) return;
|
|
182
|
+
this.subscription?.unsubscribe();
|
|
183
|
+
this.subscription = void 0;
|
|
184
|
+
this.client?.stopClient();
|
|
185
|
+
this.client = void 0;
|
|
186
|
+
this.connected = false;
|
|
187
|
+
this.inboundHandler = void 0;
|
|
188
|
+
this.aliasCache.clear();
|
|
189
|
+
}
|
|
190
|
+
async sendMessage(out) {
|
|
191
|
+
if (out.text.length === 0) {
|
|
192
|
+
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
193
|
+
}
|
|
194
|
+
if (this.client === void 0) {
|
|
195
|
+
return {
|
|
196
|
+
ok: false,
|
|
197
|
+
error: { code: "not_connected", message: "MatrixAdapter.connect() not called" }
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const roomId = await this.aliasCache.resolve(this.client, out.channel.id);
|
|
202
|
+
if (this.isEncrypted(roomId)) {
|
|
203
|
+
this.warnEncryptedOnce(roomId);
|
|
204
|
+
return {
|
|
205
|
+
ok: false,
|
|
206
|
+
error: {
|
|
207
|
+
code: "encrypted_room_unsupported",
|
|
208
|
+
message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
const res = await this.client.sendTextMessage(roomId, out.text);
|
|
213
|
+
return { ok: true, messageId: res.event_id };
|
|
214
|
+
} catch (err) {
|
|
215
|
+
return mapMatrixError(err);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
onInbound(handler) {
|
|
219
|
+
this.inboundHandler = handler;
|
|
220
|
+
return () => {
|
|
221
|
+
if (this.inboundHandler === handler) this.inboundHandler = void 0;
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** Escape hatch (D421) — caller can drive matrix-js-sdk directly for advanced features. */
|
|
225
|
+
getClient() {
|
|
226
|
+
return this.client;
|
|
227
|
+
}
|
|
228
|
+
/** Used by tests to install a mock SDK client + flip connected flag. */
|
|
229
|
+
_installClient(client) {
|
|
230
|
+
this.client = client;
|
|
231
|
+
this.connected = true;
|
|
232
|
+
this.attachSync();
|
|
233
|
+
}
|
|
234
|
+
attachSync() {
|
|
235
|
+
if (this.client === void 0) return;
|
|
236
|
+
const client = this.client;
|
|
237
|
+
const opts = {
|
|
238
|
+
botUserId: this.opts.userId,
|
|
239
|
+
freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS
|
|
240
|
+
};
|
|
241
|
+
this.subscription = subscribeToTimeline(
|
|
242
|
+
client,
|
|
243
|
+
(ev, room) => {
|
|
244
|
+
void this.dispatchTimelineEvent(ev, room).catch((err) => {
|
|
245
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
246
|
+
process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}
|
|
247
|
+
`);
|
|
248
|
+
});
|
|
249
|
+
},
|
|
250
|
+
opts
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
async dispatchTimelineEvent(event, room) {
|
|
254
|
+
if (this.isEncrypted(room.roomId)) {
|
|
255
|
+
this.warnEncryptedOnce(room.roomId);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const normalized = matrixEventToMessageEvent(event, room);
|
|
259
|
+
if (normalized === void 0) return;
|
|
260
|
+
if (this.inboundHandler === void 0) return;
|
|
261
|
+
try {
|
|
262
|
+
await this.inboundHandler(normalized);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
265
|
+
process.stderr.write(`[gateway-matrix] handler threw: ${m}
|
|
266
|
+
`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
isEncrypted(roomId) {
|
|
270
|
+
if (this.client === void 0) return false;
|
|
271
|
+
if (this.client.isRoomEncrypted === void 0) return false;
|
|
272
|
+
try {
|
|
273
|
+
return this.client.isRoomEncrypted(roomId);
|
|
274
|
+
} catch {
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
warnEncryptedOnce(roomId) {
|
|
279
|
+
if (this.warnedEncrypted.has(roomId)) return;
|
|
280
|
+
this.warnedEncrypted.add(roomId);
|
|
281
|
+
process.stderr.write(
|
|
282
|
+
`[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)
|
|
283
|
+
`
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
function mapMatrixError(err) {
|
|
288
|
+
const e = err;
|
|
289
|
+
const status = e.httpStatus ?? 0;
|
|
290
|
+
if (status === 429 || e.errcode === "M_LIMIT_EXCEEDED") {
|
|
291
|
+
return { ok: false, error: { code: "rate_limit", message: e.message ?? "Matrix rate limit" } };
|
|
292
|
+
}
|
|
293
|
+
if (status === 401 || status === 403 || e.errcode === "M_FORBIDDEN") {
|
|
294
|
+
return {
|
|
295
|
+
ok: false,
|
|
296
|
+
error: { code: "permission_denied", message: e.message ?? "Matrix permission error" }
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
if (status === 404 || e.errcode === "M_NOT_FOUND") {
|
|
300
|
+
return {
|
|
301
|
+
ok: false,
|
|
302
|
+
error: { code: "not_found", message: e.message ?? "Matrix resource not found" }
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
ok: false,
|
|
307
|
+
error: {
|
|
308
|
+
code: "send_failed",
|
|
309
|
+
message: e.message ?? (err instanceof Error ? err.message : String(err))
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export { AliasCache, ConfigurationError, EncryptedRoomError, MatrixAdapter, SDKNotInstalledError, detectChannelType, matrixEventToMessageEvent, shouldDispatchSyncEvent, subscribeToTimeline };
|
|
315
|
+
//# sourceMappingURL=index.js.map
|
|
316
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/alias.ts","../src/client.ts","../src/room-state.ts","../src/normalize.ts","../src/sync.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;AAWO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC1B,IAAA,GAAO,oBAAA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A,EAAS,CAAA,CAAE,OAAA,IAAW,mBAAA,EAAoB,EAAE;AAAA,EAC/F;AACA,EAAA,IAAI,WAAW,GAAA,IAAO,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,YAAY,aAAA,EAAe;AACnE,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,qBAAqB,OAAA,EAAS,CAAA,CAAE,WAAW,yBAAA;AAA0B,KACtF;AAAA,EACF;AACA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,CAAA,CAAE,OAAA,KAAY,aAAA,EAAe;AACjD,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,CAAA,CAAE,WAAW,2BAAA;AAA4B,KAChF;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","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-matrix`.\n */\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport interface ConfigurationErrorOptions {\n readonly code: string;\n readonly message?: string;\n readonly detail?: string;\n}\n\nexport class ConfigurationError extends Error {\n override readonly name = \"ConfigurationError\";\n readonly code: string;\n readonly detail: string | undefined;\n constructor(opts: ConfigurationErrorOptions) {\n super(opts.message ?? `gateway-matrix: ${opts.code}`);\n this.code = opts.code;\n this.detail = opts.detail;\n }\n}\n\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor() {\n super({\n code: \"sdk_not_installed\",\n message:\n 'gateway-matrix: peer-dep \"matrix-js-sdk\" not installed. Run: pnpm add matrix-js-sdk',\n detail: \"matrix-js-sdk\",\n });\n }\n}\n\nexport class EncryptedRoomError extends ConfigurationError {\n constructor(roomId: string) {\n super({\n code: \"encrypted_room_unsupported\",\n message: `gateway-matrix: room ${roomId} is end-to-end encrypted (E2EE deferred to v0.2)`,\n detail: roomId,\n });\n }\n}\n","/**\n * Matrix alias resolution + caching (D419).\n *\n * Accepts:\n * - Room id (`!abc123:server`) — pass-through.\n * - Alias (`#general:server`) — resolved via `client.getRoomIdForAlias`.\n *\n * Other shapes throw `ConfigurationError({ code: \"invalid_room_ref\" })`.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\n\n/** @knipignore — minimal Client interface `AliasCache.resolve` accepts; useful for callers building their own resolver. */\nexport interface AliasResolverClient {\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n}\n\nexport class AliasCache {\n private readonly cache = new Map<string, string>();\n\n /** Returns the room id; resolves aliases via the client + caches. */\n async resolve(client: AliasResolverClient, refOrId: string): Promise<string> {\n if (refOrId.startsWith(\"!\")) return refOrId;\n if (!refOrId.startsWith(\"#\")) {\n throw new ConfigurationError({\n code: \"invalid_room_ref\",\n message: `gateway-matrix: invalid room reference ${JSON.stringify(refOrId)} — expected '!' (room id) or '#' (alias)`,\n });\n }\n const cached = this.cache.get(refOrId);\n if (cached !== undefined) return cached;\n const { room_id } = await client.getRoomIdForAlias(refOrId);\n this.cache.set(refOrId, room_id);\n return room_id;\n }\n\n /** Drop all cached resolutions. Useful for tests + admin-rename recovery. */\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n","/**\n * Lazy `matrix-js-sdk` loader.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\nimport type { MatrixClientLike } from \"./sync.js\";\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport interface MatrixSdkClient extends MatrixClientLike {\n startClient(opts: { initialSyncLimit: number }): Promise<void>;\n stopClient(): void;\n sendTextMessage(roomId: string, text: string): Promise<{ event_id: string }>;\n getRoomIdForAlias(alias: string): Promise<{ room_id: string }>;\n getRoom(roomId: string): MatrixRoomLike | null;\n isRoomEncrypted?(roomId: string): boolean;\n /** Best-effort current user id; matrix-js-sdk returns `string | null`. */\n getUserId(): string | null;\n}\n\ninterface MatrixSdkModule {\n createClient(opts: { baseUrl: string; accessToken: string; userId: string }): MatrixSdkClient;\n}\n\nexport async function loadMatrixSdk(): Promise<MatrixSdkModule> {\n try {\n const mod = await import(\"matrix-js-sdk\");\n return mod as unknown as MatrixSdkModule;\n } catch {\n throw new SDKNotInstalledError();\n }\n}\n","/**\n * Room state helpers (D416).\n *\n * Matrix has no native \"DM\" concept — DMs are rooms with 2 members.\n * The canonical heuristic: `member_count === 2 → \"dm\"`, else `\"group\"`.\n */\n\nimport type { MatrixRoomLike } from \"./types.js\";\n\nexport function detectChannelType(room: MatrixRoomLike | undefined): \"dm\" | \"group\" {\n if (room === undefined) return \"group\";\n return room.getJoinedMemberCount() === 2 ? \"dm\" : \"group\";\n}\n","/**\n * Inbound normalization: MatrixEvent + Room → MatrixMessageEvent.\n *\n * @public\n */\n\nimport type { MatrixMessageEvent } from \"@theokit/gateway\";\n\nimport { detectChannelType } from \"./room-state.js\";\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport function matrixEventToMessageEvent(\n event: MatrixEventLike,\n room: MatrixRoomLike,\n): MatrixMessageEvent | undefined {\n const eventId = event.getId();\n const sender = event.getSender();\n if (eventId === undefined || sender === undefined) return undefined;\n const channelType = detectChannelType(room);\n const content = event.getContent();\n const body = content.body ?? \"\";\n return {\n id: eventId,\n platform: \"matrix\",\n sender: { id: sender },\n channel: {\n id: room.roomId,\n type: channelType,\n },\n text: body,\n receivedAt: event.getTs(),\n matrix: {\n roomId: room.roomId,\n eventId,\n memberCount: room.getJoinedMemberCount(),\n raw: event,\n },\n };\n}\n","/**\n * Sync timeline filter (D415, EC-3 absorbed).\n *\n * Wraps `client.on(\"Room.timeline\", listener)` with 3 filters:\n *\n * 1. Drop non-`m.room.message` events (D413).\n * 2. Drop bot's own messages (loop guard, D275 mirror).\n * 3. **EC-3**: drop events older than `freshnessWindowMs` (default 60s)\n * — initial sync from `matrix-js-sdk` delivers ~10 historical events\n * per joined room, which would otherwise trigger an LLM-call storm.\n */\n\nimport type { MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nexport interface SyncFilterOpts {\n readonly botUserId: string;\n readonly freshnessWindowMs: number;\n}\n\nexport function shouldDispatchSyncEvent(\n event: MatrixEventLike,\n opts: SyncFilterOpts,\n now = Date.now(),\n): boolean {\n if (event.getType() !== \"m.room.message\") return false;\n const sender = event.getSender();\n if (sender === opts.botUserId) return false;\n if (event.getTs() < now - opts.freshnessWindowMs) return false;\n return true;\n}\n\nexport interface TimelineSubscription {\n unsubscribe(): void;\n}\n\nexport interface MatrixClientLike {\n on(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n off(event: \"Room.timeline\", listener: (e: MatrixEventLike, r: MatrixRoomLike) => void): void;\n}\n\nexport function subscribeToTimeline(\n client: MatrixClientLike,\n handler: (event: MatrixEventLike, room: MatrixRoomLike) => void,\n opts: SyncFilterOpts,\n): TimelineSubscription {\n const wrapped = (event: MatrixEventLike, room: MatrixRoomLike): void => {\n if (!shouldDispatchSyncEvent(event, opts)) return;\n handler(event, room);\n };\n client.on(\"Room.timeline\", wrapped);\n return {\n unsubscribe(): void {\n client.off(\"Room.timeline\", wrapped);\n },\n };\n}\n","/**\n * `MatrixAdapter` — implements BasePlatformAdapter over matrix-js-sdk.\n * ADRs D413-D421.\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 { AliasCache } from \"./alias.js\";\nimport { loadMatrixSdk, type MatrixSdkClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { matrixEventToMessageEvent } from \"./normalize.js\";\nimport { subscribeToTimeline, type TimelineSubscription } from \"./sync.js\";\nimport type { MatrixAdapterOptions, MatrixEventLike, MatrixRoomLike } from \"./types.js\";\n\nconst DEFAULT_FRESHNESS_MS = 60_000;\nconst INITIAL_SYNC_LIMIT = 10;\n\nexport class MatrixAdapter extends BasePlatformAdapter {\n readonly platform = \"matrix\" as const;\n private readonly opts: MatrixAdapterOptions;\n private client: MatrixSdkClient | undefined;\n private subscription: TimelineSubscription | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private readonly aliasCache = new AliasCache();\n private connected = false;\n private readonly warnedEncrypted = new Set<string>();\n\n constructor(opts: MatrixAdapterOptions) {\n super();\n if (opts.homeserverUrl.length === 0) {\n throw new ConfigurationError({\n code: \"homeserver_url_required\",\n message: 'gateway-matrix: opts.homeserverUrl is empty (e.g. \"https://matrix.org\")',\n });\n }\n if (opts.accessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message:\n \"gateway-matrix: opts.accessToken is empty (Element → Settings → Help & About → Advanced → Access Token)\",\n });\n }\n if (opts.userId.length === 0 || !opts.userId.startsWith(\"@\")) {\n throw new ConfigurationError({\n code: \"user_id_required\",\n message: 'gateway-matrix: opts.userId must be a Matrix user id (e.g. \"@bot:matrix.org\")',\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const mod = await loadMatrixSdk();\n this.client = mod.createClient({\n baseUrl: this.opts.homeserverUrl,\n accessToken: this.opts.accessToken,\n userId: this.opts.userId,\n });\n await this.client.startClient({ initialSyncLimit: INITIAL_SYNC_LIMIT });\n this.attachSync();\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-matrix] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n this.client?.stopClient();\n this.client = undefined;\n this.connected = false;\n this.inboundHandler = undefined;\n this.aliasCache.clear();\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.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"MatrixAdapter.connect() not called\" },\n };\n }\n try {\n const roomId = await this.aliasCache.resolve(this.client, out.channel.id);\n if (this.isEncrypted(roomId)) {\n this.warnEncryptedOnce(roomId);\n return {\n ok: false,\n error: {\n code: \"encrypted_room_unsupported\",\n message: `Matrix room ${roomId} is encrypted; E2EE deferred to v0.2`,\n },\n };\n }\n const res = await this.client.sendTextMessage(roomId, out.text);\n return { ok: true, messageId: res.event_id };\n } catch (err) {\n return mapMatrixError(err);\n }\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 (D421) — caller can drive matrix-js-sdk directly for advanced features. */\n getClient(): MatrixSdkClient | undefined {\n return this.client;\n }\n\n /** Used by tests to install a mock SDK client + flip connected flag. */\n _installClient(client: MatrixSdkClient): void {\n this.client = client;\n this.connected = true;\n this.attachSync();\n }\n\n private attachSync(): void {\n if (this.client === undefined) return;\n const client = this.client;\n const opts = {\n botUserId: this.opts.userId,\n freshnessWindowMs: this.opts.freshnessWindowMs ?? DEFAULT_FRESHNESS_MS,\n };\n this.subscription = subscribeToTimeline(\n client,\n (ev: MatrixEventLike, room: MatrixRoomLike) => {\n void this.dispatchTimelineEvent(ev, room).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] dispatchTimelineEvent failed: ${m}\\n`);\n });\n },\n opts,\n );\n }\n\n private async dispatchTimelineEvent(event: MatrixEventLike, room: MatrixRoomLike): Promise<void> {\n if (this.isEncrypted(room.roomId)) {\n this.warnEncryptedOnce(room.roomId);\n return;\n }\n const normalized = matrixEventToMessageEvent(event, room);\n if (normalized === undefined) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-matrix] handler threw: ${m}\\n`);\n }\n }\n\n private isEncrypted(roomId: string): boolean {\n if (this.client === undefined) return false;\n if (this.client.isRoomEncrypted === undefined) return false;\n try {\n return this.client.isRoomEncrypted(roomId);\n } catch {\n return false;\n }\n }\n\n private warnEncryptedOnce(roomId: string): void {\n if (this.warnedEncrypted.has(roomId)) return;\n this.warnedEncrypted.add(roomId);\n process.stderr.write(\n `[gateway-matrix] room ${roomId} is end-to-end encrypted; skipping (E2EE deferred to v0.2)\\n`,\n );\n }\n}\n\ninterface MatrixRestError {\n httpStatus?: number;\n errcode?: string;\n message?: string;\n name?: string;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error mapping ladder is exhaustive — each branch maps one Matrix errcode/HTTP status to one canonical code; splitting hurts traceability.\nfunction mapMatrixError(err: unknown): SendResult {\n const e = err as MatrixRestError;\n const status = e.httpStatus ?? 0;\n if (status === 429 || e.errcode === \"M_LIMIT_EXCEEDED\") {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"Matrix rate limit\" } };\n }\n if (status === 401 || status === 403 || e.errcode === \"M_FORBIDDEN\") {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"Matrix permission error\" },\n };\n }\n if (status === 404 || e.errcode === \"M_NOT_FOUND\") {\n return {\n ok: false,\n error: { code: \"not_found\", message: e.message ?? \"Matrix resource not found\" },\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"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@theokit/gateway-matrix",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Matrix protocol platform adapter for @theokit/gateway. ADRs D413-D421.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.12.0"
|
|
9
|
+
},
|
|
10
|
+
"main": "./dist/index.cjs",
|
|
11
|
+
"module": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"import": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"require": {
|
|
20
|
+
"types": "./dist/index.d.cts",
|
|
21
|
+
"default": "./dist/index.cjs"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE",
|
|
30
|
+
"CHANGELOG.md"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsup",
|
|
34
|
+
"typecheck": "tsc --noEmit",
|
|
35
|
+
"test": "vitest run"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@theokit/gateway": "workspace:^",
|
|
39
|
+
"@theokit/sdk": "workspace:^",
|
|
40
|
+
"matrix-js-sdk": "^32.0.0"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"matrix-js-sdk": {
|
|
44
|
+
"optional": true
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@theokit/gateway": "workspace:*",
|
|
49
|
+
"@theokit/sdk": "workspace:*",
|
|
50
|
+
"tsup": "^8.5.0",
|
|
51
|
+
"typescript": "^5.8.0",
|
|
52
|
+
"vitest": "^4.1.8"
|
|
53
|
+
}
|
|
54
|
+
}
|