@im-more/dsh-matrix 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +14 -0
  3. package/lib/index.js +2401 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/as.d.ts +33 -0
  6. package/lib/types/as.d.ts.map +1 -0
  7. package/lib/types/as.js +237 -0
  8. package/lib/types/as.js.map +1 -0
  9. package/lib/types/bot.d.ts +109 -0
  10. package/lib/types/bot.d.ts.map +1 -0
  11. package/lib/types/bot.js +234 -0
  12. package/lib/types/bot.js.map +1 -0
  13. package/lib/types/config.d.ts +59 -0
  14. package/lib/types/config.d.ts.map +1 -0
  15. package/lib/types/config.js +67 -0
  16. package/lib/types/config.js.map +1 -0
  17. package/lib/types/decode.d.ts +56 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +298 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +45 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +120 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/html.d.ts +44 -0
  26. package/lib/types/html.d.ts.map +1 -0
  27. package/lib/types/html.js +286 -0
  28. package/lib/types/html.js.map +1 -0
  29. package/lib/types/identity.d.ts +20 -0
  30. package/lib/types/identity.d.ts.map +1 -0
  31. package/lib/types/identity.js +136 -0
  32. package/lib/types/identity.js.map +1 -0
  33. package/lib/types/index.d.ts +5 -0
  34. package/lib/types/index.d.ts.map +1 -0
  35. package/lib/types/index.js +5 -0
  36. package/lib/types/index.js.map +1 -0
  37. package/lib/types/media.d.ts +54 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +94 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/mentions.d.ts +58 -0
  42. package/lib/types/mentions.d.ts.map +1 -0
  43. package/lib/types/mentions.js +94 -0
  44. package/lib/types/mentions.js.map +1 -0
  45. package/lib/types/modes/html.d.ts +13 -0
  46. package/lib/types/modes/html.d.ts.map +1 -0
  47. package/lib/types/modes/html.js +242 -0
  48. package/lib/types/modes/html.js.map +1 -0
  49. package/lib/types/modes/shared.d.ts +164 -0
  50. package/lib/types/modes/shared.d.ts.map +1 -0
  51. package/lib/types/modes/shared.js +312 -0
  52. package/lib/types/modes/shared.js.map +1 -0
  53. package/lib/types/request.d.ts +82 -0
  54. package/lib/types/request.d.ts.map +1 -0
  55. package/lib/types/request.js +206 -0
  56. package/lib/types/request.js.map +1 -0
  57. package/lib/types/rooms.d.ts +83 -0
  58. package/lib/types/rooms.d.ts.map +1 -0
  59. package/lib/types/rooms.js +177 -0
  60. package/lib/types/rooms.js.map +1 -0
  61. package/lib/types/send.d.ts +76 -0
  62. package/lib/types/send.d.ts.map +1 -0
  63. package/lib/types/send.js +172 -0
  64. package/lib/types/send.js.map +1 -0
  65. package/lib/types/types.d.ts +418 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +134 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/package.json +65 -3
  70. package/src/as.ts +293 -0
  71. package/src/bot.ts +338 -0
  72. package/src/config.ts +100 -0
  73. package/src/decode.ts +392 -0
  74. package/src/errors.ts +149 -0
  75. package/src/html.ts +325 -0
  76. package/src/identity.ts +165 -0
  77. package/src/index.ts +14 -0
  78. package/src/media.ts +132 -0
  79. package/src/mentions.ts +134 -0
  80. package/src/modes/html.ts +346 -0
  81. package/src/modes/shared.ts +485 -0
  82. package/src/request.ts +295 -0
  83. package/src/rooms.ts +232 -0
  84. package/src/send.ts +275 -0
  85. package/src/types.ts +633 -0
  86. package/README.md +0 -3
package/src/html.ts ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * `formatted_body` decoding: Matrix's HTML subset becomes Satori elements.
3
+ *
4
+ * The traversal follows the upstream adapter (`html5parser` + a tag table) and keeps two one-line bug fixes from the
5
+ * migration: an unknown named character reference stays as written instead of duplicating the whole text node, and an
6
+ * image's `alt` is read from `alt` rather than from `src`. A Matrix rich reply carries a duplicated fallback block
7
+ * (`<mx-reply>`); the whole block is dropped, as the specification tells clients to strip it.
8
+ */
9
+
10
+ import { h } from '@deepseek-ai/satori-element'
11
+ import type { Element } from '@deepseek-ai/satori-element'
12
+ import { parse, SyntaxKind } from 'html5parser'
13
+ import type { INode, ITag } from 'html5parser'
14
+
15
+ /** What the traversal needs from the bot: a way to turn `mxc://` into a fetchable `satori:` source. */
16
+ export interface HtmlDecodeOptions {
17
+ /** Turn an `mxc://` URI into the bot's authenticated internal source. */
18
+ mediaSource: (mxc: string) => string
19
+ }
20
+
21
+ /** The named character references the traversal decodes (the upstream adapter's table). */
22
+ const ENTITIES: Record<string, string> = {
23
+ nbsp: ' ',
24
+ cent: '¢',
25
+ pound: '£',
26
+ yen: '¥',
27
+ euro: '€',
28
+ copy: '©',
29
+ reg: '®',
30
+ lt: '<',
31
+ gt: '>',
32
+ quot: '"',
33
+ amp: '&',
34
+ apos: "'",
35
+ }
36
+
37
+ /**
38
+ * Decode named, decimal and hexadecimal character references of one text run.
39
+ *
40
+ * A named reference outside {@link ENTITIES} is not an error: it stays as written. (Upstream returned the whole text
41
+ * node in that case, which duplicated everything around the unknown reference.)
42
+ *
43
+ * @param text - raw character data of one HTML text node.
44
+ * @returns the text with the known references decoded.
45
+ */
46
+ export function decodeHE(text: string): string {
47
+ const regex = /&(([a-z0-9]+)|(#[0-9]{1,6})|(#x[0-9a-fA-F]{1,6}));/gi
48
+ return text.replace(
49
+ regex,
50
+ (
51
+ raw: string,
52
+ _whole: string,
53
+ name?: string,
54
+ dec?: string,
55
+ hex?: string,
56
+ ) => {
57
+ if (name) return ENTITIES[name] ?? raw
58
+ if (dec) return String.fromCharCode(Number(dec.substring(1)))
59
+ if (hex) return String.fromCharCode(parseInt(hex.substring(2), 16))
60
+ return raw
61
+ },
62
+ )
63
+ }
64
+
65
+ /** One attribute of a parsed tag, as written in the source. */
66
+ function attribute(node: ITag, name: string): string | undefined {
67
+ return node.attributeMap?.[name]?.value?.value
68
+ }
69
+
70
+ /** Whether the attribute is present (an HTML boolean attribute such as `checked`). */
71
+ function hasAttribute(node: ITag, name: string): boolean {
72
+ return node.attributeMap?.[name] !== undefined
73
+ }
74
+
75
+ /** A numeric attribute, or undefined when it is absent or not a number. */
76
+ function numericAttribute(node: ITag, name: string): number | undefined {
77
+ const value = attribute(node, name)
78
+ if (value === undefined || value.trim() === '') return undefined
79
+ const parsed = Number(value)
80
+ return Number.isFinite(parsed) ? parsed : undefined
81
+ }
82
+
83
+ /** Tags whose whole subtree is not part of the message body. */
84
+ const IGNORED = new Set([
85
+ 'head',
86
+ 'script',
87
+ 'style',
88
+ 'meta',
89
+ 'title',
90
+ 'template',
91
+ ])
92
+
93
+ /** The language of a `<pre><code class="language-x">` pair, when the client wrote one. */
94
+ function languageOf(body: readonly INode[]): string | undefined {
95
+ for (const child of body) {
96
+ if (child.type !== SyntaxKind.Tag || child.name !== 'code') continue
97
+ const className = attribute(child, 'class')
98
+ if (className === undefined) continue
99
+ const match = /(?:^|\s)language-(\S+)/.exec(className)
100
+ if (match?.[1] !== undefined) return match[1]
101
+ }
102
+ return undefined
103
+ }
104
+
105
+ /** The label and destination of one `matrix.to` link, when it is one. */
106
+ const MATRIX_TO = 'https://matrix.to/#/'
107
+
108
+ /**
109
+ * Convert one HTML string into elements.
110
+ *
111
+ * @param html - the `formatted_body` of an `m.room.message`.
112
+ * @param options - how to fetch media.
113
+ * @returns the elements of the body, in document order.
114
+ */
115
+ export function htmlToElements(
116
+ html: string,
117
+ options: HtmlDecodeOptions,
118
+ ): Element[] {
119
+ const visit = (nodes: readonly INode[]): Element[] => {
120
+ const out: Element[] = []
121
+ for (const node of nodes) {
122
+ if (node.type === SyntaxKind.Text) {
123
+ const text = decodeHE(node.value)
124
+ if (text !== '') out.push(h.text(text))
125
+ continue
126
+ }
127
+ const body = node.body ?? []
128
+ switch (node.name) {
129
+ case 'mx-reply':
130
+ // The fallback repeats the replied-to message; Matrix clients strip it before rendering.
131
+ break
132
+ case 'p':
133
+ out.push(h('p', ...visit(body)))
134
+ break
135
+ case 'br':
136
+ out.push(h('br'))
137
+ break
138
+ case 'hr':
139
+ out.push(h('hr'))
140
+ break
141
+ case 'b':
142
+ case 'strong':
143
+ out.push(h('b', ...visit(body)))
144
+ break
145
+ case 'i':
146
+ case 'em':
147
+ out.push(h('i', ...visit(body)))
148
+ break
149
+ case 'u':
150
+ out.push(h('u', ...visit(body)))
151
+ break
152
+ case 's':
153
+ case 'del':
154
+ case 'strike':
155
+ out.push(h('s', ...visit(body)))
156
+ break
157
+ case 'code':
158
+ out.push(h('code', ...visit(body)))
159
+ break
160
+ case 'pre': {
161
+ const language = languageOf(body)
162
+ out.push(
163
+ h(
164
+ 'pre',
165
+ language === undefined ? {} : { lang: language },
166
+ ...visit(body),
167
+ ),
168
+ )
169
+ break
170
+ }
171
+ case 'a': {
172
+ const href = attribute(node, 'href') ?? '#'
173
+ const children = visit(body)
174
+ const plain = href.startsWith(MATRIX_TO)
175
+ ? href.slice(MATRIX_TO.length)
176
+ : undefined
177
+ if (plain?.startsWith('@')) {
178
+ out.push(h('at', { type: 'user', id: plain }, ...children))
179
+ } else if (plain?.startsWith('#') || plain?.startsWith('!')) {
180
+ out.push(h('channel', { id: plain }, ...children))
181
+ } else {
182
+ out.push(h('a', { href }, ...children))
183
+ }
184
+ break
185
+ }
186
+ case 'img': {
187
+ const src = attribute(node, 'src')
188
+ const alt = attribute(node, 'alt')
189
+ const width = numericAttribute(node, 'width')
190
+ const height = numericAttribute(node, 'height')
191
+ if (src === undefined || src === '') {
192
+ // Upstream read `alt` into `src` by mistake; an image without a source keeps its description as text.
193
+ if (alt !== undefined && alt !== '') out.push(h.text(alt))
194
+ break
195
+ }
196
+ const resolved = src.startsWith('mxc://')
197
+ ? options.mediaSource(src)
198
+ : src
199
+ out.push(
200
+ h('img', {
201
+ src: resolved,
202
+ ...(alt === undefined ? {} : { alt }),
203
+ ...(width === undefined ? {} : { width }),
204
+ ...(height === undefined ? {} : { height }),
205
+ }),
206
+ )
207
+ break
208
+ }
209
+ case 'blockquote':
210
+ out.push(h('blockquote', ...visit(body)))
211
+ break
212
+ case 'span': {
213
+ if (hasAttribute(node, 'data-mx-spoiler')) {
214
+ out.push(h('spoiler', ...visit(body)))
215
+ } else {
216
+ out.push(...visit(body))
217
+ }
218
+ break
219
+ }
220
+ case 'ul':
221
+ out.push(h('ul', ...visit(body)))
222
+ break
223
+ case 'ol': {
224
+ const start = numericAttribute(node, 'start')
225
+ out.push(
226
+ h('ol', start === undefined ? {} : { start }, ...visit(body)),
227
+ )
228
+ break
229
+ }
230
+ case 'li': {
231
+ let checked: boolean | undefined
232
+ const children: INode[] = []
233
+ for (const child of body) {
234
+ if (
235
+ child.type === SyntaxKind.Tag &&
236
+ child.name === 'input' &&
237
+ attribute(child, 'type') === 'checkbox'
238
+ ) {
239
+ checked = hasAttribute(child, 'checked')
240
+ continue
241
+ }
242
+ children.push(child)
243
+ }
244
+ out.push(
245
+ h(
246
+ 'li',
247
+ checked === undefined ? {} : { checked },
248
+ ...visit(children),
249
+ ),
250
+ )
251
+ break
252
+ }
253
+ case 'table':
254
+ out.push(h('table', ...visit(body)))
255
+ break
256
+ case 'tr':
257
+ out.push(h('tr', ...visit(body)))
258
+ break
259
+ case 'th':
260
+ case 'td': {
261
+ const align = attribute(node, 'align')
262
+ const attrs: { align?: 'left' | 'center' | 'right' } =
263
+ align === 'left' || align === 'center' || align === 'right'
264
+ ? { align }
265
+ : {}
266
+ out.push(h(node.name, attrs, ...visit(body)))
267
+ break
268
+ }
269
+ case 'details':
270
+ out.push(
271
+ h(
272
+ 'details',
273
+ hasAttribute(node, 'open') ? { open: true } : {},
274
+ ...visit(body),
275
+ ),
276
+ )
277
+ break
278
+ case 'summary':
279
+ out.push(h('summary', ...visit(body)))
280
+ break
281
+ case 'h1':
282
+ case 'h2':
283
+ case 'h3':
284
+ case 'h4':
285
+ case 'h5':
286
+ case 'h6':
287
+ out.push(h(node.name, ...visit(body)))
288
+ break
289
+ case 'sup':
290
+ case 'sub':
291
+ case 'font':
292
+ case 'div':
293
+ case 'caption':
294
+ case 'thead':
295
+ case 'tbody':
296
+ out.push(...visit(body))
297
+ break
298
+ default:
299
+ if (IGNORED.has(node.name)) break
300
+ out.push(...visit(body))
301
+ }
302
+ }
303
+ return out
304
+ }
305
+ return visit(parse(html, { setAttributeMap: true }))
306
+ }
307
+
308
+ /**
309
+ * Strip the rich-reply fallback of a plain `body`.
310
+ *
311
+ * A client that writes `format: org.matrix.custom.html` duplicates the quoted message inside `<mx-reply>`, and a plain
312
+ * body carries the same duplicate as leading `> ` lines. Only the leading block is removed, followed by the one blank
313
+ * line the fallback spec puts after it.
314
+ *
315
+ * @param body - the plain-text body of an `m.room.message`.
316
+ * @returns the body without a leading quote fallback.
317
+ */
318
+ export function stripPlainFallback(body: string): string {
319
+ const lines = body.split('\n')
320
+ let index = 0
321
+ while (index < lines.length && lines[index]!.startsWith('> ')) index++
322
+ if (index === 0) return body
323
+ if (lines[index] === '') index++
324
+ return lines.slice(index).join('\n')
325
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Application Service identity: register the virtual user with `m.login.application_service`, fall back to login when
3
+ * the homeserver reports `M_USER_IN_USE` (the normal case after the first start), check the answered `user_id`, read
4
+ * the profile and write the configured display name / avatar.
5
+ *
6
+ * The AS user has no password and no second login entry, so the returned user access token is the only credential the
7
+ * Client-Server calls carry.
8
+ */
9
+
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import type { User } from '@deepseek-ai/cordis-plugin-im-core'
12
+ import type { MatrixBot } from './bot.ts'
13
+ import type { Config } from './config.ts'
14
+ import { MatrixApiError } from './errors.ts'
15
+ import { internalMediaSource } from './media.ts'
16
+ import type { User as MatrixUser } from './types.ts'
17
+
18
+ /** The virtual user id of the configured localpart. */
19
+ export function matrixUserId(config: Config): string {
20
+ return `@${config.id}:${config.host}`
21
+ }
22
+
23
+ /** The response of a failed convenience request, recovered structurally (`ctx.http.post` throws an `HttpError`). */
24
+ function responseOf(error: unknown): Response | undefined {
25
+ if (typeof error !== 'object' || error === null || !('response' in error))
26
+ return undefined
27
+ const response = (error as { response?: unknown }).response
28
+ return response instanceof Response ? response : undefined
29
+ }
30
+
31
+ /** One JSON envelope of a failed answer. */
32
+ async function envelopeOf(
33
+ response: Response,
34
+ ): Promise<{ errcode?: string; error?: string }> {
35
+ try {
36
+ const parsed: unknown = await response.clone().json()
37
+ if (typeof parsed !== 'object' || parsed === null) return {}
38
+ const value = parsed as { errcode?: unknown; error?: unknown }
39
+ return {
40
+ ...(typeof value.errcode === 'string' ? { errcode: value.errcode } : {}),
41
+ ...(typeof value.error === 'string' ? { error: value.error } : {}),
42
+ }
43
+ } catch {
44
+ return {}
45
+ }
46
+ }
47
+
48
+ /** Convert a convenience-request failure into the adapter's own error type. */
49
+ async function apiErrorOf(
50
+ error: unknown,
51
+ method: string,
52
+ ): Promise<MatrixApiError> {
53
+ if (error instanceof MatrixApiError) return error
54
+ const failed = responseOf(error)
55
+ if (failed !== undefined) {
56
+ const body = await envelopeOf(failed)
57
+ return new MatrixApiError(
58
+ `matrix ${method} answered ${failed.status}${body.errcode === undefined ? '' : `: ${body.errcode}`}${body.error === undefined ? '' : ` ${body.error}`}`,
59
+ {
60
+ method,
61
+ status: failed.status,
62
+ ...(body.errcode === undefined ? {} : { errcode: body.errcode }),
63
+ ...(body.error === undefined ? {} : { error: body.error }),
64
+ cause: error,
65
+ },
66
+ )
67
+ }
68
+ return new MatrixApiError(`matrix ${method} request failed`, {
69
+ method,
70
+ cause: error,
71
+ })
72
+ }
73
+
74
+ /**
75
+ * Whether a failed registration means the virtual user already exists, so login is the right next step.
76
+ * @param error - the failure of `POST /register`.
77
+ * @returns true for a 400 `M_USER_IN_USE` (or a 400 without an envelope, which some homeservers send).
78
+ */
79
+ async function isUserInUse(error: unknown): Promise<boolean> {
80
+ const failed = responseOf(error)
81
+ if (failed === undefined || failed.status !== 400) return false
82
+ const body = await envelopeOf(failed)
83
+ return body.errcode === undefined || body.errcode === 'M_USER_IN_USE'
84
+ }
85
+
86
+ /** Read the avatar bytes with the platform's own content type. */
87
+ async function downloadAvatar(
88
+ ctx: Context,
89
+ url: string,
90
+ ): Promise<{ data: Uint8Array; mime: string }> {
91
+ // `get` with an identity decoder hands back the DOM response; a refused status rejects as the HTTP service's error.
92
+ const response = await ctx.http.get(url, { responseType: (raw) => raw })
93
+ const type = response.headers.get('content-type')
94
+ const data = new Uint8Array(await response.arrayBuffer())
95
+ return {
96
+ data,
97
+ mime:
98
+ type === null || type === ''
99
+ ? 'application/octet-stream'
100
+ : type.split(';')[0]!.trim(),
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Establish the bot identity and store it on the adapter.
106
+ *
107
+ * @param bot - the adapter being connected.
108
+ * @throws MatrixApiError when the credentials, the namespace or the answered identity are wrong.
109
+ */
110
+ export async function establishIdentity(bot: MatrixBot): Promise<void> {
111
+ const config = bot.config
112
+ const selfId = bot.selfId
113
+ let user: MatrixUser
114
+ try {
115
+ user = await bot.internal.register(config.id, config.asToken)
116
+ } catch (error) {
117
+ if (!(await isUserInUse(error)))
118
+ throw await apiErrorOf(error, '/client/v3/register')
119
+ try {
120
+ user = await bot.internal.login(config.id, config.asToken)
121
+ } catch (loginError) {
122
+ throw await apiErrorOf(loginError, '/client/v3/login')
123
+ }
124
+ }
125
+ if (user.user_id !== selfId) {
126
+ throw new MatrixApiError(
127
+ `matrix: the homeserver answered user_id "${user.user_id ?? ''}" instead of "${selfId}"; check the registration's users namespaces`,
128
+ { method: '/client/v3/register' },
129
+ )
130
+ }
131
+ if (user.access_token === undefined || user.access_token === '') {
132
+ throw new MatrixApiError(
133
+ 'matrix: the homeserver answered no access_token; check as_token and the registration',
134
+ {
135
+ method: '/client/v3/register',
136
+ },
137
+ )
138
+ }
139
+ bot.request.setToken(user.access_token)
140
+
141
+ if (config.name !== undefined && config.name !== null && config.name !== '') {
142
+ await bot.internal.setDisplayName(selfId, config.name)
143
+ }
144
+ if (
145
+ config.avatar !== undefined &&
146
+ config.avatar !== null &&
147
+ config.avatar !== ''
148
+ ) {
149
+ const { data, mime } = await downloadAvatar(bot.ctx, config.avatar)
150
+ await bot.internal.setAvatar(selfId, Buffer.from(data), mime)
151
+ }
152
+
153
+ const profile = await bot.internal.getProfile(selfId)
154
+ bot.user = {
155
+ id: selfId,
156
+ name: profile.displayname ?? config.name ?? config.id,
157
+ ...(profile.avatar_url === undefined || profile.avatar_url === ''
158
+ ? {}
159
+ : {
160
+ avatar:
161
+ internalMediaSource(bot, profile.avatar_url) ?? profile.avatar_url,
162
+ }),
163
+ isBot: true,
164
+ } satisfies User
165
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { MatrixBot, MatrixBot as default, type MatrixModes } from './bot.ts'
2
+ export {
3
+ Config,
4
+ configError,
5
+ routePath,
6
+ type Config as MatrixConfig,
7
+ } from './config.ts'
8
+ export {
9
+ classifyMatrixError,
10
+ isTokenFailure,
11
+ MatrixApiError,
12
+ type MatrixApiErrorInit,
13
+ } from './errors.ts'
14
+ export { MatrixClient, type MatrixRequestOptions } from './request.ts'
package/src/media.ts ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Media in both directions.
3
+ *
4
+ * Outbound: Matrix has a standalone upload endpoint, so `upload` fetches the bytes and posts them to
5
+ * `/_matrix/media/v3/upload`, returning the `mxc://` content URI as the platform key. Inbound: an `mxc://` source needs
6
+ * credentials, so decoding rewrites it to the bot's `satori:` route and the route downloads through the authenticated
7
+ * `/_matrix/client/v1/media/download` endpoint (v1.11 retired the unauthenticated form).
8
+ */
9
+
10
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type {
12
+ PrepareContext,
13
+ ResolvedResource,
14
+ ResourceRef,
15
+ } from '@deepseek-ai/cordis-plugin-im-core'
16
+ import type { MatrixClient } from './request.ts'
17
+
18
+ /** What the upload knows beyond the resource key: the platform needs a name, MIME type and size in the event. */
19
+ export interface MatrixMediaExtra {
20
+ name?: string
21
+ mime?: string
22
+ size?: number
23
+ }
24
+
25
+ /** A parsed `mxc://<server-name>/<media-id>` URI. */
26
+ export interface MxcUri {
27
+ serverName: string
28
+ mediaId: string
29
+ }
30
+
31
+ /**
32
+ * Parse one Matrix content URI.
33
+ * @param uri - an `mxc://` URI.
34
+ * @returns its server name and media id, or undefined for any other URI.
35
+ */
36
+ export function parseMxc(uri: string): MxcUri | undefined {
37
+ if (!uri.startsWith('mxc://')) return undefined
38
+ const rest = uri.slice('mxc://'.length)
39
+ const slash = rest.indexOf('/')
40
+ if (slash <= 0 || slash === rest.length - 1) return undefined
41
+ return { serverName: rest.slice(0, slash), mediaId: rest.slice(slash + 1) }
42
+ }
43
+
44
+ /** The bot surface the internal source needs (`Bot.getInternalUrl`). */
45
+ export interface InternalSourceHost {
46
+ getInternalUrl(path: string, init?: Record<string, string>): string
47
+ }
48
+
49
+ /**
50
+ * The `satori:` source of one content URI, served through the bot's `/media` route.
51
+ * @param host - the receiving bot.
52
+ * @param uri - an `mxc://` URI.
53
+ * @returns the internal source, or undefined when the URI is not a content URI.
54
+ */
55
+ export function internalMediaSource(
56
+ host: InternalSourceHost,
57
+ uri: string,
58
+ ): string | undefined {
59
+ const parsed = parseMxc(uri)
60
+ if (parsed === undefined) return undefined
61
+ return host.getInternalUrl('/media', {
62
+ mxc: `${parsed.serverName}/${parsed.mediaId}`,
63
+ })
64
+ }
65
+
66
+ /**
67
+ * Upload one resource and return its `mxc://` key.
68
+ *
69
+ * @param client - the bot's Client-Server client.
70
+ * @param ref - the resource placeholder produced by a mode handler.
71
+ * @param ctx - prepare context (fetch and cancellation).
72
+ * @returns the platform key and the name/MIME/size the event carries.
73
+ */
74
+ export async function uploadResource(
75
+ client: MatrixClient,
76
+ ref: ResourceRef,
77
+ ctx: PrepareContext,
78
+ ): Promise<ResolvedResource> {
79
+ let fetched
80
+ try {
81
+ fetched = await ctx.fetch(ref.src, ctx.signal)
82
+ } catch (error) {
83
+ // Nothing was uploaded, so nothing can have been published.
84
+ throw new PlatformError(
85
+ 'invalid',
86
+ `matrix: the resource "${ref.src}" could not be read`,
87
+ {
88
+ published: 'no',
89
+ cause: error,
90
+ },
91
+ )
92
+ }
93
+ const name = ref.meta.name ?? fetched.name ?? 'file'
94
+ const mime = ref.meta.mime ?? fetched.mime
95
+ const answer = await client.upload(name, fetched.data, mime, ctx.signal)
96
+ const contentUri = answer.content_uri
97
+ if (contentUri === undefined || contentUri === '') {
98
+ throw new PlatformError(
99
+ 'invalid',
100
+ 'matrix: the upload answered without a content_uri',
101
+ {
102
+ published: 'no',
103
+ },
104
+ )
105
+ }
106
+ return {
107
+ key: contentUri,
108
+ extra: {
109
+ name,
110
+ ...(mime === undefined ? {} : { mime }),
111
+ size: fetched.data.byteLength,
112
+ } satisfies MatrixMediaExtra,
113
+ }
114
+ }
115
+
116
+ /** Response headers a `satori:` media route mirrors from the homeserver. The length is left to the response body. */
117
+ const MIRRORED_HEADERS = ['content-type', 'content-disposition'] as const
118
+
119
+ /**
120
+ * Turn one homeserver media answer into the response the host sees.
121
+ * @param response - the authenticated download answer.
122
+ * @returns the same bytes and metadata, or `502` when the homeserver refused or lost them.
123
+ */
124
+ export function mediaResponse(response: Response): Response {
125
+ if (!response.ok) return new Response(null, { status: 502 })
126
+ const headers = new Headers()
127
+ for (const name of MIRRORED_HEADERS) {
128
+ const value = response.headers.get(name)
129
+ if (value !== null) headers.set(name, value)
130
+ }
131
+ return new Response(response.body, { status: response.status, headers })
132
+ }