@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.
- package/LICENSE +21 -0
- package/cordis.patch.yml +14 -0
- package/lib/index.js +2401 -0
- package/lib/index.js.map +1 -0
- package/lib/types/as.d.ts +33 -0
- package/lib/types/as.d.ts.map +1 -0
- package/lib/types/as.js +237 -0
- package/lib/types/as.js.map +1 -0
- package/lib/types/bot.d.ts +109 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +234 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +59 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +67 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +56 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +298 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +45 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +120 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/html.d.ts +44 -0
- package/lib/types/html.d.ts.map +1 -0
- package/lib/types/html.js +286 -0
- package/lib/types/html.js.map +1 -0
- package/lib/types/identity.d.ts +20 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +136 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +5 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +5 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/media.d.ts +54 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +94 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/mentions.d.ts +58 -0
- package/lib/types/mentions.d.ts.map +1 -0
- package/lib/types/mentions.js +94 -0
- package/lib/types/mentions.js.map +1 -0
- package/lib/types/modes/html.d.ts +13 -0
- package/lib/types/modes/html.d.ts.map +1 -0
- package/lib/types/modes/html.js +242 -0
- package/lib/types/modes/html.js.map +1 -0
- package/lib/types/modes/shared.d.ts +164 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +312 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +82 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +206 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/rooms.d.ts +83 -0
- package/lib/types/rooms.d.ts.map +1 -0
- package/lib/types/rooms.js +177 -0
- package/lib/types/rooms.js.map +1 -0
- package/lib/types/send.d.ts +76 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +172 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/types.d.ts +418 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +134 -0
- package/lib/types/types.js.map +1 -0
- package/package.json +65 -3
- package/src/as.ts +293 -0
- package/src/bot.ts +338 -0
- package/src/config.ts +100 -0
- package/src/decode.ts +392 -0
- package/src/errors.ts +149 -0
- package/src/html.ts +325 -0
- package/src/identity.ts +165 -0
- package/src/index.ts +14 -0
- package/src/media.ts +132 -0
- package/src/mentions.ts +134 -0
- package/src/modes/html.ts +346 -0
- package/src/modes/shared.ts +485 -0
- package/src/request.ts +295 -0
- package/src/rooms.ts +232 -0
- package/src/send.ts +275 -0
- package/src/types.ts +633 -0
- package/README.md +0 -3
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["messageOf","h"],"sources":["types/config.js","types/as.js","types/html.js","types/media.js","types/mentions.js","types/decode.js","types/errors.js","types/identity.js","types/request.js","types/rooms.js","types/send.js","types/modes/shared.js","types/modes/html.js","types/types.js","types/bot.js"],"sourcesContent":["/**\n * The Application Service configuration: the registration credentials, the virtual user, the inbound route and the\n * media request defaults. There is no transport switch — the homeserver's transaction push is the only intake.\n *\n * `endpoint` defaults to `https://<host>`; trailing slashes are removed so the client can append `/_matrix` once.\n */\nimport z from '@deepseek-ai/schemastery';\n/** A schema-required field, narrowed from the transform's nullable view of an object schema. */\nfunction required(value, field) {\n if (value === undefined || value === null || value === '') {\n throw new Error(`matrix: ${field} is required`);\n }\n return value;\n}\n/** Validated Matrix adapter configuration; `endpoint` is always resolved. */\nexport const Config = z.transform(z.object({\n endpoint: z.string().role('url'),\n host: z.string().required(),\n id: z.string().required(),\n asToken: z.string().role('secret').required(),\n hsToken: z.string().role('secret').required(),\n path: z.string().default('/matrix'),\n name: z.string(),\n avatar: z.string(),\n autoJoin: z.boolean().default(true),\n}), (value) => ({\n ...value,\n endpoint: (value.endpoint ?? `https://${required(value.host, 'host')}`).replace(/\\/+$/, ''),\n host: required(value.host, 'host'),\n id: required(value.id, 'id'),\n asToken: required(value.asToken, 'asToken'),\n hsToken: required(value.hsToken, 'hsToken'),\n path: value.path ?? '/matrix',\n autoJoin: value.autoJoin ?? true,\n}));\n/**\n * The endpoint the adapter refuses to start with.\n *\n * The schema marks `endpoint` as a URL for profile renderers, but only this check makes a malformed root fail before\n * the first request instead of on every call.\n *\n * @param config - the validated configuration.\n * @returns the configuration error, or undefined when the endpoint is usable.\n */\nexport function configError(config) {\n let url;\n try {\n url = new URL(config.endpoint);\n }\n catch {\n return new Error('matrix: endpoint must be an absolute http(s) URL');\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return new Error('matrix: endpoint must be an absolute http(s) URL');\n }\n return undefined;\n}\n/**\n * Normalize an inbound route path: absolute, no trailing slash.\n * @param path - the configured `path`.\n * @returns the pathname to register.\n */\nexport function routePath(path) {\n const withSlash = path.startsWith('/') ? path : `/${path}`;\n return withSlash.length > 1 ? withSlash.replace(/\\/+$/, '') : withSlash;\n}\n//# sourceMappingURL=config.js.map","/**\n * The Application Service inbound transport.\n *\n * The profile's `webServer` owns the listener, so this transport registers one anonymous prefix route at the configured\n * path and implements the Application Service API under it: transaction pushes (current and legacy path forms), the\n * `users` query, the `rooms` query (always unknown) and the v1.7 `ping`. Every request is authenticated by `hs_token`,\n * with the legacy `?access_token=` form accepted and refused when it contradicts a Bearer header.\n *\n * A transaction is confirmed only after every event reached intake: a failed event answers `500`, so the homeserver\n * redelivers the batch with the same transaction id and the host's event-id deduplication removes the copies it already\n * stored. That is the opposite of the upstream adapter's confirm-first order, which loses an event whose store failed.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { routePath } from \"./config.js\";\n/** The prefixes a transaction push uses: the current Application Service path and the legacy one. */\nconst TRANSACTION_PREFIXES = ['/_matrix/app/v1/transactions/', '/transactions/'];\n/** The route families whose methods are fixed. */\nconst PING_PATH = '/_matrix/app/v1/ping';\nconst USERS_PREFIX = '/_matrix/app/v1/users/';\nconst ROOMS_PREFIX = '/_matrix/app/v1/rooms/';\n/** Compare two secrets without leaking where they differ. */\nfunction secretMatches(expected, received) {\n const left = Buffer.from(expected, 'utf8');\n const right = Buffer.from(received, 'utf8');\n if (left.length !== right.length)\n return false;\n return timingSafeEqual(left, right);\n}\n/** The Bearer token of a request, when it used the current scheme. */\nfunction bearerOf(request) {\n const header = request.headers.authorization;\n if (typeof header !== 'string')\n return undefined;\n const match = /^Bearer\\s+(.+)$/i.exec(header);\n return match?.[1];\n}\n/** Read a request body to its end. The adapter imposes no size limit of its own. */\nasync function readBody(request) {\n const chunks = [];\n for await (const chunk of request) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n/** Write one bodiless answer. */\nfunction writeStatus(response, status, headers = {}) {\n if (response.headersSent) {\n response.end();\n return;\n }\n response.writeHead(status, headers);\n response.end();\n}\n/** Write one JSON answer. */\nfunction writeJson(response, status, body) {\n if (response.headersSent) {\n response.end();\n return;\n }\n response.writeHead(status, { 'content-type': 'application/json' });\n response.end(JSON.stringify(body));\n}\n/** The `M_UNRECOGNIZED` answer the specification asks unknown routes to use. */\nfunction writeUnrecognized(response) {\n writeJson(response, 404, {\n errcode: 'M_UNRECOGNIZED',\n error: 'Unrecognized request',\n });\n}\n/** Message of any caught value, for a log line. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n/** The transaction id of one subpath, when the subpath is a transaction route. */\nfunction transactionIdOf(sub) {\n for (const prefix of TRANSACTION_PREFIXES) {\n if (!sub.startsWith(prefix))\n continue;\n const id = sub.slice(prefix.length);\n return id === '' ? undefined : id;\n }\n return undefined;\n}\n/** The Application Service transport of one bot. */\nexport class MatrixAppService {\n bot;\n dispose;\n constructor(bot) {\n this.bot = bot;\n }\n /** Register the prefix route; a profile without a web server fails with an actionable message. */\n async start() {\n const webServer = this.bot.ctx.get('webServer');\n if (webServer === undefined) {\n throw this.fail('matrix: the Application Service needs a profile-provided webServer; ' +\n \"the homeserver must reach the route named by the registration's url\");\n }\n this.dispose = webServer.register({\n kind: 'prefix',\n path: routePath(this.bot.config.path),\n auth: 'anonymous',\n handler: (request, response) => this.handle(request, response),\n });\n }\n /** Release the route. */\n async stop() {\n this.dispose?.();\n this.dispose = undefined;\n }\n /** Log a fatal start failure before the caller throws it (`Bot.start` only stores a connect failure). */\n fail(message) {\n this.bot.ctx.logger.error(message);\n return new Error(message);\n }\n async handle(request, response) {\n try {\n const base = routePath(this.bot.config.path);\n const url = new URL(request.url ?? '/', 'http://matrix.invalid');\n const inside = base === '/' ||\n url.pathname === base ||\n url.pathname.startsWith(`${base}/`);\n if (!inside) {\n writeUnrecognized(response);\n return;\n }\n if (!this.authorized(request, url.searchParams)) {\n writeStatus(response, 403);\n return;\n }\n const sub = base === '/' ? url.pathname : url.pathname.slice(base.length);\n const txnId = transactionIdOf(sub);\n if (txnId !== undefined) {\n if (request.method !== 'PUT') {\n writeStatus(response, 405, { allow: 'PUT' });\n return;\n }\n await this.transaction(request, response, txnId);\n return;\n }\n if (sub === PING_PATH) {\n if (request.method !== 'POST') {\n writeStatus(response, 405, { allow: 'POST' });\n return;\n }\n writeJson(response, 200, {});\n return;\n }\n if (sub.startsWith(USERS_PREFIX)) {\n if (request.method !== 'GET') {\n writeStatus(response, 405, { allow: 'GET' });\n return;\n }\n this.users(response, sub.slice(USERS_PREFIX.length));\n return;\n }\n if (sub.startsWith(ROOMS_PREFIX)) {\n if (request.method !== 'GET') {\n writeStatus(response, 405, { allow: 'GET' });\n return;\n }\n writeUnrecognized(response);\n return;\n }\n writeUnrecognized(response);\n }\n catch (error) {\n // A route must never leave the listener without an answer.\n this.bot.ctx.logger.warn('matrix: Application Service request failed: %s', messageOf(error));\n writeStatus(response, 500);\n }\n }\n /** Whether one request carries the registration's `hs_token` in exactly one consistent form. */\n authorized(request, query) {\n const bearer = bearerOf(request);\n const legacy = query.get('access_token') ?? undefined;\n if (bearer !== undefined && legacy !== undefined && bearer !== legacy)\n return false;\n const token = bearer ?? legacy;\n if (token === undefined)\n return false;\n return secretMatches(this.bot.config.hsToken, token);\n }\n /** Read and process one transaction; the answer is `200 {}` only after every event reached intake. */\n async transaction(request, response, txnId) {\n const body = await readBody(request);\n let parsed;\n try {\n parsed = JSON.parse(body);\n }\n catch (error) {\n this.bot.ctx.logger.warn('matrix: cannot parse transaction %s: %s', txnId, messageOf(error));\n writeStatus(response, 400);\n return;\n }\n if (typeof parsed !== 'object' || parsed === null) {\n writeStatus(response, 400);\n return;\n }\n const events = parsed.events;\n if (!Array.isArray(events)) {\n writeStatus(response, 400);\n return;\n }\n try {\n for (const raw of events) {\n if (typeof raw !== 'object' || raw === null)\n continue;\n const session = await this.bot.decode(raw);\n if (session !== undefined)\n await this.bot.receive(session);\n }\n }\n catch (error) {\n this.bot.noteRuntimeError(error);\n this.bot.ctx.logger.warn('matrix: transaction %s failed; the homeserver redelivers it: %s', txnId, messageOf(error));\n writeStatus(response, 500);\n return;\n }\n writeJson(response, 200, {});\n }\n /** Answer the `users` query: only the AS virtual user exists. */\n users(response, encoded) {\n let userId = encoded;\n try {\n userId = decodeURIComponent(encoded);\n }\n catch {\n // A malformed escape is simply not a user this service owns.\n }\n if (userId !== this.bot.selfId) {\n writeUnrecognized(response);\n return;\n }\n writeJson(response, 200, {});\n }\n}\n//# sourceMappingURL=as.js.map","/**\n * `formatted_body` decoding: Matrix's HTML subset becomes Satori elements.\n *\n * The traversal follows the upstream adapter (`html5parser` + a tag table) and keeps two one-line bug fixes from the\n * migration: an unknown named character reference stays as written instead of duplicating the whole text node, and an\n * image's `alt` is read from `alt` rather than from `src`. A Matrix rich reply carries a duplicated fallback block\n * (`<mx-reply>`); the whole block is dropped, as the specification tells clients to strip it.\n */\nimport { h } from '@deepseek-ai/satori-element';\nimport { parse, SyntaxKind } from 'html5parser';\n/** The named character references the traversal decodes (the upstream adapter's table). */\nconst ENTITIES = {\n nbsp: ' ',\n cent: '¢',\n pound: '£',\n yen: '¥',\n euro: '€',\n copy: '©',\n reg: '®',\n lt: '<',\n gt: '>',\n quot: '\"',\n amp: '&',\n apos: \"'\",\n};\n/**\n * Decode named, decimal and hexadecimal character references of one text run.\n *\n * A named reference outside {@link ENTITIES} is not an error: it stays as written. (Upstream returned the whole text\n * node in that case, which duplicated everything around the unknown reference.)\n *\n * @param text - raw character data of one HTML text node.\n * @returns the text with the known references decoded.\n */\nexport function decodeHE(text) {\n const regex = /&(([a-z0-9]+)|(#[0-9]{1,6})|(#x[0-9a-fA-F]{1,6}));/gi;\n return text.replace(regex, (raw, _whole, name, dec, hex) => {\n if (name)\n return ENTITIES[name] ?? raw;\n if (dec)\n return String.fromCharCode(Number(dec.substring(1)));\n if (hex)\n return String.fromCharCode(parseInt(hex.substring(2), 16));\n return raw;\n });\n}\n/** One attribute of a parsed tag, as written in the source. */\nfunction attribute(node, name) {\n return node.attributeMap?.[name]?.value?.value;\n}\n/** Whether the attribute is present (an HTML boolean attribute such as `checked`). */\nfunction hasAttribute(node, name) {\n return node.attributeMap?.[name] !== undefined;\n}\n/** A numeric attribute, or undefined when it is absent or not a number. */\nfunction numericAttribute(node, name) {\n const value = attribute(node, name);\n if (value === undefined || value.trim() === '')\n return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n/** Tags whose whole subtree is not part of the message body. */\nconst IGNORED = new Set([\n 'head',\n 'script',\n 'style',\n 'meta',\n 'title',\n 'template',\n]);\n/** The language of a `<pre><code class=\"language-x\">` pair, when the client wrote one. */\nfunction languageOf(body) {\n for (const child of body) {\n if (child.type !== SyntaxKind.Tag || child.name !== 'code')\n continue;\n const className = attribute(child, 'class');\n if (className === undefined)\n continue;\n const match = /(?:^|\\s)language-(\\S+)/.exec(className);\n if (match?.[1] !== undefined)\n return match[1];\n }\n return undefined;\n}\n/** The label and destination of one `matrix.to` link, when it is one. */\nconst MATRIX_TO = 'https://matrix.to/#/';\n/**\n * Convert one HTML string into elements.\n *\n * @param html - the `formatted_body` of an `m.room.message`.\n * @param options - how to fetch media.\n * @returns the elements of the body, in document order.\n */\nexport function htmlToElements(html, options) {\n const visit = (nodes) => {\n const out = [];\n for (const node of nodes) {\n if (node.type === SyntaxKind.Text) {\n const text = decodeHE(node.value);\n if (text !== '')\n out.push(h.text(text));\n continue;\n }\n const body = node.body ?? [];\n switch (node.name) {\n case 'mx-reply':\n // The fallback repeats the replied-to message; Matrix clients strip it before rendering.\n break;\n case 'p':\n out.push(h('p', ...visit(body)));\n break;\n case 'br':\n out.push(h('br'));\n break;\n case 'hr':\n out.push(h('hr'));\n break;\n case 'b':\n case 'strong':\n out.push(h('b', ...visit(body)));\n break;\n case 'i':\n case 'em':\n out.push(h('i', ...visit(body)));\n break;\n case 'u':\n out.push(h('u', ...visit(body)));\n break;\n case 's':\n case 'del':\n case 'strike':\n out.push(h('s', ...visit(body)));\n break;\n case 'code':\n out.push(h('code', ...visit(body)));\n break;\n case 'pre': {\n const language = languageOf(body);\n out.push(h('pre', language === undefined ? {} : { lang: language }, ...visit(body)));\n break;\n }\n case 'a': {\n const href = attribute(node, 'href') ?? '#';\n const children = visit(body);\n const plain = href.startsWith(MATRIX_TO)\n ? href.slice(MATRIX_TO.length)\n : undefined;\n if (plain?.startsWith('@')) {\n out.push(h('at', { type: 'user', id: plain }, ...children));\n }\n else if (plain?.startsWith('#') || plain?.startsWith('!')) {\n out.push(h('channel', { id: plain }, ...children));\n }\n else {\n out.push(h('a', { href }, ...children));\n }\n break;\n }\n case 'img': {\n const src = attribute(node, 'src');\n const alt = attribute(node, 'alt');\n const width = numericAttribute(node, 'width');\n const height = numericAttribute(node, 'height');\n if (src === undefined || src === '') {\n // Upstream read `alt` into `src` by mistake; an image without a source keeps its description as text.\n if (alt !== undefined && alt !== '')\n out.push(h.text(alt));\n break;\n }\n const resolved = src.startsWith('mxc://')\n ? options.mediaSource(src)\n : src;\n out.push(h('img', {\n src: resolved,\n ...(alt === undefined ? {} : { alt }),\n ...(width === undefined ? {} : { width }),\n ...(height === undefined ? {} : { height }),\n }));\n break;\n }\n case 'blockquote':\n out.push(h('blockquote', ...visit(body)));\n break;\n case 'span': {\n if (hasAttribute(node, 'data-mx-spoiler')) {\n out.push(h('spoiler', ...visit(body)));\n }\n else {\n out.push(...visit(body));\n }\n break;\n }\n case 'ul':\n out.push(h('ul', ...visit(body)));\n break;\n case 'ol': {\n const start = numericAttribute(node, 'start');\n out.push(h('ol', start === undefined ? {} : { start }, ...visit(body)));\n break;\n }\n case 'li': {\n let checked;\n const children = [];\n for (const child of body) {\n if (child.type === SyntaxKind.Tag &&\n child.name === 'input' &&\n attribute(child, 'type') === 'checkbox') {\n checked = hasAttribute(child, 'checked');\n continue;\n }\n children.push(child);\n }\n out.push(h('li', checked === undefined ? {} : { checked }, ...visit(children)));\n break;\n }\n case 'table':\n out.push(h('table', ...visit(body)));\n break;\n case 'tr':\n out.push(h('tr', ...visit(body)));\n break;\n case 'th':\n case 'td': {\n const align = attribute(node, 'align');\n const attrs = align === 'left' || align === 'center' || align === 'right'\n ? { align }\n : {};\n out.push(h(node.name, attrs, ...visit(body)));\n break;\n }\n case 'details':\n out.push(h('details', hasAttribute(node, 'open') ? { open: true } : {}, ...visit(body)));\n break;\n case 'summary':\n out.push(h('summary', ...visit(body)));\n break;\n case 'h1':\n case 'h2':\n case 'h3':\n case 'h4':\n case 'h5':\n case 'h6':\n out.push(h(node.name, ...visit(body)));\n break;\n case 'sup':\n case 'sub':\n case 'font':\n case 'div':\n case 'caption':\n case 'thead':\n case 'tbody':\n out.push(...visit(body));\n break;\n default:\n if (IGNORED.has(node.name))\n break;\n out.push(...visit(body));\n }\n }\n return out;\n };\n return visit(parse(html, { setAttributeMap: true }));\n}\n/**\n * Strip the rich-reply fallback of a plain `body`.\n *\n * A client that writes `format: org.matrix.custom.html` duplicates the quoted message inside `<mx-reply>`, and a plain\n * body carries the same duplicate as leading `> ` lines. Only the leading block is removed, followed by the one blank\n * line the fallback spec puts after it.\n *\n * @param body - the plain-text body of an `m.room.message`.\n * @returns the body without a leading quote fallback.\n */\nexport function stripPlainFallback(body) {\n const lines = body.split('\\n');\n let index = 0;\n while (index < lines.length && lines[index].startsWith('> '))\n index++;\n if (index === 0)\n return body;\n if (lines[index] === '')\n index++;\n return lines.slice(index).join('\\n');\n}\n//# sourceMappingURL=html.js.map","/**\n * Media in both directions.\n *\n * Outbound: Matrix has a standalone upload endpoint, so `upload` fetches the bytes and posts them to\n * `/_matrix/media/v3/upload`, returning the `mxc://` content URI as the platform key. Inbound: an `mxc://` source needs\n * credentials, so decoding rewrites it to the bot's `satori:` route and the route downloads through the authenticated\n * `/_matrix/client/v1/media/download` endpoint (v1.11 retired the unauthenticated form).\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\n/**\n * Parse one Matrix content URI.\n * @param uri - an `mxc://` URI.\n * @returns its server name and media id, or undefined for any other URI.\n */\nexport function parseMxc(uri) {\n if (!uri.startsWith('mxc://'))\n return undefined;\n const rest = uri.slice('mxc://'.length);\n const slash = rest.indexOf('/');\n if (slash <= 0 || slash === rest.length - 1)\n return undefined;\n return { serverName: rest.slice(0, slash), mediaId: rest.slice(slash + 1) };\n}\n/**\n * The `satori:` source of one content URI, served through the bot's `/media` route.\n * @param host - the receiving bot.\n * @param uri - an `mxc://` URI.\n * @returns the internal source, or undefined when the URI is not a content URI.\n */\nexport function internalMediaSource(host, uri) {\n const parsed = parseMxc(uri);\n if (parsed === undefined)\n return undefined;\n return host.getInternalUrl('/media', {\n mxc: `${parsed.serverName}/${parsed.mediaId}`,\n });\n}\n/**\n * Upload one resource and return its `mxc://` key.\n *\n * @param client - the bot's Client-Server client.\n * @param ref - the resource placeholder produced by a mode handler.\n * @param ctx - prepare context (fetch and cancellation).\n * @returns the platform key and the name/MIME/size the event carries.\n */\nexport async function uploadResource(client, ref, ctx) {\n let fetched;\n try {\n fetched = await ctx.fetch(ref.src, ctx.signal);\n }\n catch (error) {\n // Nothing was uploaded, so nothing can have been published.\n throw new PlatformError('invalid', `matrix: the resource \"${ref.src}\" could not be read`, {\n published: 'no',\n cause: error,\n });\n }\n const name = ref.meta.name ?? fetched.name ?? 'file';\n const mime = ref.meta.mime ?? fetched.mime;\n const answer = await client.upload(name, fetched.data, mime, ctx.signal);\n const contentUri = answer.content_uri;\n if (contentUri === undefined || contentUri === '') {\n throw new PlatformError('invalid', 'matrix: the upload answered without a content_uri', {\n published: 'no',\n });\n }\n return {\n key: contentUri,\n extra: {\n name,\n ...(mime === undefined ? {} : { mime }),\n size: fetched.data.byteLength,\n },\n };\n}\n/** Response headers a `satori:` media route mirrors from the homeserver. The length is left to the response body. */\nconst MIRRORED_HEADERS = ['content-type', 'content-disposition'];\n/**\n * Turn one homeserver media answer into the response the host sees.\n * @param response - the authenticated download answer.\n * @returns the same bytes and metadata, or `502` when the homeserver refused or lost them.\n */\nexport function mediaResponse(response) {\n if (!response.ok)\n return new Response(null, { status: 502 });\n const headers = new Headers();\n for (const name of MIRRORED_HEADERS) {\n const value = response.headers.get(name);\n if (value !== null)\n headers.set(name, value);\n }\n return new Response(response.body, { status: response.status, headers });\n}\n//# sourceMappingURL=media.js.map","/**\n * Mentions in both directions.\n *\n * Inbound, `m.mentions` is authoritative for `self`/`all`, because guessing from a display name is what the\n * specification warns against; a `matrix.to` link decoded into an `at` element covers older clients that did not write\n * the field, and a bare `@room` in the body covers the pre-v1.7 room mention. Outbound, `at` elements collect into\n * `m.mentions` (one object per draft, always present) and render as `matrix.to` links.\n */\n/** A new empty collection. */\nexport function createMentionSet() {\n return { users: [], room: false };\n}\n/**\n * Add one handler's mention to a draft's collection.\n * @param set - the draft's collection.\n * @param mention - the mention; a user id or a room mention.\n */\nexport function addMention(set, mention) {\n if (mention === undefined)\n return;\n if (mention.user !== undefined && !set.users.includes(mention.user))\n set.users.push(mention.user);\n if (mention.room === true)\n set.room = true;\n}\n/** The wire object of one collection; `{}` when it mentions nobody. */\nexport function mentionWire(set) {\n return {\n ...(set.users.length === 0 ? {} : { user_ids: [...set.users] }),\n ...(set.room ? { room: true } : {}),\n };\n}\n/** Whether the plain body carries the old standalone `@room` form. */\nfunction bodyMentionsRoom(body) {\n if (body === undefined)\n return false;\n return /(^|\\s)@room(?=\\s|$)/.test(body);\n}\n/** Every `at[type=user]` of a decoded tree, in document order. */\nfunction atElements(elements) {\n const out = [];\n const walk = (nodes) => {\n for (const node of nodes) {\n if (node.type === 'at') {\n if (node.attrs.type === 'user')\n out.push(node);\n continue;\n }\n walk(node.children);\n }\n };\n walk(elements);\n return out;\n}\n/**\n * Decode the mention facts of one inbound event.\n *\n * @param content - the event content, whose `m.mentions` is authoritative when present.\n * @param body - the plain body, for the legacy `@room` form.\n * @param elements - the decoded content tree, for `matrix.to` links and mention labels.\n * @param selfId - the bot's Matrix user id.\n * @returns `self`/`all` flags and the users the message mentions.\n */\nexport function decodeMentions(content, body, elements, selfId) {\n const declared = content['m.mentions'];\n const declaredIds = Array.isArray(declared?.user_ids)\n ? declared.user_ids.filter((id) => typeof id === 'string')\n : [];\n const users = [];\n const seen = new Set();\n for (const element of atElements(elements)) {\n const id = element.attrs.id;\n if (id === undefined || seen.has(id))\n continue;\n seen.add(id);\n users.push({\n id,\n ...(element.attrs.name === undefined ? {} : { name: element.attrs.name }),\n });\n }\n for (const id of declaredIds) {\n if (seen.has(id))\n continue;\n seen.add(id);\n users.push({ id });\n }\n const selfByElement = users.some((user) => user.id === selfId);\n return {\n self: selfId !== '' && (declaredIds.includes(selfId) || selfByElement),\n all: declared?.room === true || bodyMentionsRoom(body),\n users,\n };\n}\n//# sourceMappingURL=mentions.js.map","/**\n * Inbound decoding: one Application Service event becomes one `Session`.\n *\n * `m.room.message` becomes a message (text/emote/notice through `formatted_body` or the plain body, media through the\n * authenticated `satori:` route); `m.reaction` becomes `reaction-added`; `m.room.redaction` becomes\n * `message-deleted` (room v11 moved the target into `content.redacts`). Membership and room-name events only update\n * the room cache, and an invitation of the bot itself is joined when `autoJoin` is on. Everything else is dropped;\n * `m.room.encrypted` is the visible consequence of the no-E2EE decision.\n */\nimport { h } from '@deepseek-ai/cordis-plugin-im-core';\nimport { htmlToElements, stripPlainFallback } from \"./html.js\";\nimport { internalMediaSource } from \"./media.js\";\nimport { decodeMentions } from \"./mentions.js\";\n/** Rooms whose first `m.room.encrypted` event has already been logged. */\nconst encryptedLogged = new WeakMap();\n/** The message types this adapter decodes; every other `msgtype` is dropped whole. */\nexport const MESSAGE_TYPES = new Set([\n 'm.text',\n 'm.emote',\n 'm.notice',\n 'm.image',\n 'm.file',\n 'm.audio',\n 'm.video',\n]);\n/** The chat of one room, from the cache. */\nfunction chatOf(host, roomId) {\n const name = host.rooms.nameOf(roomId);\n return {\n id: roomId,\n type: host.rooms.isDirect(roomId, host.selfId) ? 'direct' : 'group',\n ...(name === undefined ? {} : { name }),\n };\n}\n/** The `satori:` source of one `mxc://` URI, or the raw address when it is not one. */\nfunction mediaSource(host, uri) {\n if (uri === undefined || uri === '')\n return undefined;\n return internalMediaSource(host, uri) ?? uri;\n}\n/** The sender of one event, with the display name the room cache knows. */\nfunction senderOf(host, event) {\n const name = host.rooms.displayNameOf(event.room_id, event.sender);\n return {\n id: event.sender,\n ...(name === undefined ? {} : { name }),\n isBot: false,\n };\n}\n/** The elements of one `m.room.message` content, or undefined for a msgtype this adapter drops. */\nfunction messageElements(host, event) {\n const content = event.content;\n switch (content.msgtype) {\n case 'm.text':\n case 'm.emote':\n case 'm.notice': {\n const formatted = content;\n if (formatted.format === 'org.matrix.custom.html' &&\n typeof formatted.formatted_body === 'string' &&\n formatted.formatted_body !== '') {\n return htmlToElements(formatted.formatted_body, {\n mediaSource: (mxc) => mediaSource(host, mxc) ?? mxc,\n });\n }\n return [h.text(stripPlainFallback(content.body ?? ''))];\n }\n case 'm.image': {\n const image = content;\n const src = mediaSource(host, image.url);\n if (src === undefined)\n return undefined;\n return [\n h('img', {\n src,\n ...(image.body === '' ? {} : { alt: image.body }),\n ...(image.info?.w === undefined ? {} : { width: image.info.w }),\n ...(image.info?.h === undefined ? {} : { height: image.info.h }),\n }),\n ];\n }\n case 'm.file': {\n const file = content;\n const src = mediaSource(host, file.url);\n if (src === undefined)\n return undefined;\n const name = file.filename ?? file.body;\n return [h('file', { src, ...(name === '' ? {} : { name }) })];\n }\n case 'm.audio': {\n const audio = content;\n const src = mediaSource(host, audio.url);\n if (src === undefined)\n return undefined;\n const name = audio.filename ?? audio.body;\n return [\n h('audio', {\n src,\n ...(name === '' ? {} : { name }),\n ...(audio.info?.duration === undefined\n ? {}\n : { duration: audio.info.duration }),\n }),\n ];\n }\n case 'm.video': {\n const video = content;\n const src = mediaSource(host, video.url);\n if (src === undefined)\n return undefined;\n const name = video.body;\n return [\n h('video', {\n src,\n ...(name === '' ? {} : { name }),\n ...(video.info?.duration === undefined\n ? {}\n : { duration: video.info.duration }),\n }),\n ];\n }\n default:\n return undefined;\n }\n}\n/**\n * Decode one `m.room.message` event.\n *\n * @param host - the receiving adapter.\n * @param event - one message event.\n * @param chat - the chat to report, when the caller already knows it (`getMessage` uses the requested one).\n * @returns the decoded message, whose content is never empty.\n */\nexport function decodeMessage(host, event, chat) {\n const content = event.content;\n const elements = messageElements(host, event);\n if (elements === undefined) {\n host.log(`matrix: ignored msgtype \"${content.msgtype ?? 'unknown'}\"`);\n }\n // A body of \"\" or a formatted body that only contained a fallback decodes to nothing usable.\n const usable = (elements ?? []).filter((element) => element.type !== 'text' || element.attrs.content !== '');\n const children = usable.length > 0\n ? usable\n : [\n h('raw', { platform: 'matrix', type: 'm.room.message', data: event.content }, h.text('')),\n ];\n const message = h('message', {}, ...children);\n const relates = content['m.relates_to'];\n const threadRoot = relates?.rel_type === 'm.thread' ? relates.event_id : undefined;\n const quoteId = relates?.['m.in_reply_to']?.event_id;\n const referrer = {\n roomId: event.room_id,\n eventId: event.event_id,\n sender: event.sender,\n ...(threadRoot === undefined ? {} : { threadRoot }),\n };\n return {\n id: event.event_id,\n chat: chat ?? chatOf(host, event.room_id),\n ...(threadRoot === undefined\n ? {}\n : { thread: { id: threadRoot, root: threadRoot } }),\n sender: senderOf(host, event),\n content: message,\n ...(quoteId === undefined ? {} : { quote: { id: quoteId } }),\n mentions: decodeMentions(content, content.body, message.children, host.selfId),\n time: event.origin_server_ts,\n referrer,\n raw: event,\n };\n}\n/** Decode one received event.\n *\n * @param host - the receiving adapter.\n * @param event - one event of an Application Service transaction.\n * @returns the session to publish, or undefined for an event this adapter does not carry.\n */\nexport async function decodeEvent(host, event) {\n // The homeserver echoes the bot's own events; the host also skips them, but not worth a `receive` round-trip.\n if (event.sender === host.selfId)\n return undefined;\n const timestamp = event.origin_server_ts;\n switch (event.type) {\n case 'm.room.message': {\n const content = event.content;\n if (content['m.new_content'] !== undefined) {\n host.log('matrix: ignored an edited message (m.new_content)');\n return undefined;\n }\n if (!MESSAGE_TYPES.has(content.msgtype)) {\n host.log(`matrix: ignored msgtype \"${content.msgtype ?? 'unknown'}\"`);\n return undefined;\n }\n const message = decodeMessage(host, event);\n return host.session({\n type: 'message',\n id: event.event_id,\n timestamp,\n message,\n raw: event,\n });\n }\n case 'm.reaction': {\n const relation = event.content['m.relates_to'];\n if (relation?.rel_type !== 'm.annotation') {\n host.log('matrix: ignored a reaction without an m.annotation relation');\n return undefined;\n }\n if (relation.event_id === undefined || relation.key === undefined) {\n host.log('matrix: ignored a reaction without an event id or key');\n return undefined;\n }\n return host.session({\n type: 'reaction-added',\n id: event.event_id,\n timestamp,\n reaction: {\n message: { id: relation.event_id, chat: chatOf(host, event.room_id) },\n emoji: relation.key,\n user: { id: event.sender },\n },\n raw: event,\n });\n }\n case 'm.room.redaction': {\n // Room version 11 moved the target into `content.redacts`; older rooms keep it on the event.\n const content = event.content;\n const target = event.redacts ?? content.redacts;\n if (target === undefined)\n return undefined;\n return host.session({\n type: 'message-deleted',\n id: event.event_id,\n timestamp,\n deleted: { id: target, chat: chatOf(host, event.room_id) },\n raw: event,\n });\n }\n case 'm.room.member': {\n const member = event.content;\n const stateKey = event.state_key;\n if (stateKey === undefined)\n return undefined;\n host.rooms.applyMember(event.room_id, stateKey, member.membership, member.displayname);\n if (stateKey !== host.selfId)\n return undefined;\n if (member.membership === 'invite') {\n if (!host.autoJoin) {\n host.log(`matrix: invited to ${event.room_id}; autoJoin is off, so it is not joined`);\n return undefined;\n }\n try {\n await host.joinRoom(event.room_id);\n }\n catch (error) {\n host.warn(`matrix: could not join ${event.room_id}: ${error instanceof Error ? error.message : String(error)}`);\n }\n return undefined;\n }\n if (member.membership === 'join') {\n // A new room's name/members/summary are not in the push; refresh the cache once.\n try {\n await host.refreshRooms();\n }\n catch (error) {\n host.warn(`matrix: could not refresh rooms after joining ${event.room_id}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return undefined;\n }\n case 'm.room.name': {\n const content = event.content;\n if (typeof content.name === 'string')\n host.rooms.setName(event.room_id, content.name);\n return undefined;\n }\n case 'm.room.encryption':\n if (host.rooms.markEncrypted(event.room_id)) {\n host.warn(`matrix: room ${event.room_id} enabled end-to-end encryption; this adapter cannot decrypt its messages`);\n }\n return undefined;\n case 'm.room.encrypted': {\n let logged = encryptedLogged.get(host.rooms);\n if (logged === undefined) {\n logged = new Set();\n encryptedLogged.set(host.rooms, logged);\n }\n if (!logged.has(event.room_id)) {\n logged.add(event.room_id);\n host.log(`matrix: dropped an encrypted message in ${event.room_id} (E2EE is not supported)`);\n }\n return undefined;\n }\n default:\n host.log(`matrix: ignored ${event.type} event`);\n return undefined;\n }\n}\n//# sourceMappingURL=decode.js.map","/**\n * Matrix failures and their mapping onto the core platform taxonomy.\n *\n * Matrix answers with one JSON envelope (`errcode`, `error`) and asks clients to decide from `errcode`, falling back\n * to the HTTP status only for `M_UNKNOWN`. A refused write is atomic, so every 4xx means nothing was published;\n * transport failures and 5xx answers leave the outcome unknown. The token-failure codes also mark the bot offline at\n * the transport layer, because the AS-issued user token has no refresh path.\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\n/** One failed Matrix API call, with the fields `classify` reads. */\nexport class MatrixApiError extends Error {\n method;\n path;\n status;\n errcode;\n error;\n retryAfterMs;\n constructor(message, init = {}) {\n super(message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = 'MatrixApiError';\n this.method = init.method;\n this.path = init.path;\n this.status = init.status;\n this.errcode = init.errcode;\n this.error = init.error;\n this.retryAfterMs = init.retryAfterMs;\n }\n}\n/** Whether a failure means the user token is gone; the bot has to be re-logged in from scratch. */\nexport function isTokenFailure(error) {\n if (error instanceof MatrixApiError) {\n if (error.errcode === 'M_UNKNOWN_TOKEN' ||\n error.errcode === 'M_MISSING_TOKEN')\n return true;\n return error.errcode === undefined && error.status === 401;\n }\n return false;\n}\n/** The kind and publish state implied by one `errcode`. */\nfunction byErrcode(errcode) {\n switch (errcode) {\n case 'M_LIMIT_EXCEEDED':\n return { kind: 'rate-limit', published: 'no' };\n case 'M_UNKNOWN_TOKEN':\n case 'M_MISSING_TOKEN':\n case 'M_FORBIDDEN':\n case 'M_EXCLUSIVE':\n case 'M_USER_DEACTIVATED':\n case 'M_CONSENT_NOT_GIVEN':\n return { kind: 'permission', published: 'no' };\n case 'M_RESOURCE_LIMIT_EXCEEDED':\n return { kind: 'retryable', published: 'no' };\n case 'M_NOT_FOUND':\n return { kind: 'not-found', published: 'no' };\n case 'M_BAD_JSON':\n case 'M_NOT_JSON':\n case 'M_MISSING_PARAM':\n case 'M_INVALID_PARAM':\n return { kind: 'invalid', published: 'no' };\n case 'M_TOO_LARGE':\n return { kind: 'limit', published: 'no' };\n default:\n return undefined;\n }\n}\n/** The kind and publish state implied by a status when no `errcode` decides it. */\nfunction byStatus(status) {\n if (status === 429)\n return { kind: 'rate-limit', published: 'no' };\n if (status !== undefined && status >= 500)\n return { kind: 'retryable', published: 'unknown' };\n // A 2xx answer this client could not read may still have published the event; only a refusal is certainly unpublished.\n if (status !== undefined && status >= 200 && status < 300)\n return { kind: 'retryable', published: 'unknown' };\n if (status !== undefined)\n return { kind: 'invalid', published: 'no' };\n return { kind: 'retryable', published: 'unknown' };\n}\n/**\n * Map any failure onto the core platform taxonomy.\n *\n * @param error - the caught failure.\n * @returns the classified platform error, with `retryAfterMs` when the platform named a delay.\n */\nexport function classifyMatrixError(error) {\n if (error instanceof PlatformError)\n return error;\n if (error instanceof MatrixApiError) {\n const { kind, published } = (error.errcode === undefined || error.errcode === 'M_UNKNOWN'\n ? undefined\n : byErrcode(error.errcode)) ?? byStatus(error.status);\n const code = error.errcode ?? error.status;\n return new PlatformError(kind, error.message, {\n ...(code === undefined ? {} : { code }),\n ...(error.retryAfterMs === undefined\n ? {}\n : { retryAfterMs: error.retryAfterMs }),\n published,\n cause: error,\n });\n }\n if (error instanceof Error && error.name === 'AbortError') {\n return new PlatformError('fatal', error.message, {\n published: 'unknown',\n cause: error,\n });\n }\n if (error instanceof DOMException && error.name === 'AbortError') {\n return new PlatformError('fatal', error.message, {\n published: 'unknown',\n cause: error,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new PlatformError('retryable', `matrix request failed: ${message}`, {\n published: 'unknown',\n cause: error,\n });\n}\n//# sourceMappingURL=errors.js.map","/**\n * Application Service identity: register the virtual user with `m.login.application_service`, fall back to login when\n * the homeserver reports `M_USER_IN_USE` (the normal case after the first start), check the answered `user_id`, read\n * the profile and write the configured display name / avatar.\n *\n * The AS user has no password and no second login entry, so the returned user access token is the only credential the\n * Client-Server calls carry.\n */\nimport { MatrixApiError } from \"./errors.js\";\nimport { internalMediaSource } from \"./media.js\";\n/** The virtual user id of the configured localpart. */\nexport function matrixUserId(config) {\n return `@${config.id}:${config.host}`;\n}\n/** The response of a failed convenience request, recovered structurally (`ctx.http.post` throws an `HttpError`). */\nfunction responseOf(error) {\n if (typeof error !== 'object' || error === null || !('response' in error))\n return undefined;\n const response = error.response;\n return response instanceof Response ? response : undefined;\n}\n/** One JSON envelope of a failed answer. */\nasync function envelopeOf(response) {\n try {\n const parsed = await response.clone().json();\n if (typeof parsed !== 'object' || parsed === null)\n return {};\n const value = parsed;\n return {\n ...(typeof value.errcode === 'string' ? { errcode: value.errcode } : {}),\n ...(typeof value.error === 'string' ? { error: value.error } : {}),\n };\n }\n catch {\n return {};\n }\n}\n/** Convert a convenience-request failure into the adapter's own error type. */\nasync function apiErrorOf(error, method) {\n if (error instanceof MatrixApiError)\n return error;\n const failed = responseOf(error);\n if (failed !== undefined) {\n const body = await envelopeOf(failed);\n return new MatrixApiError(`matrix ${method} answered ${failed.status}${body.errcode === undefined ? '' : `: ${body.errcode}`}${body.error === undefined ? '' : ` ${body.error}`}`, {\n method,\n status: failed.status,\n ...(body.errcode === undefined ? {} : { errcode: body.errcode }),\n ...(body.error === undefined ? {} : { error: body.error }),\n cause: error,\n });\n }\n return new MatrixApiError(`matrix ${method} request failed`, {\n method,\n cause: error,\n });\n}\n/**\n * Whether a failed registration means the virtual user already exists, so login is the right next step.\n * @param error - the failure of `POST /register`.\n * @returns true for a 400 `M_USER_IN_USE` (or a 400 without an envelope, which some homeservers send).\n */\nasync function isUserInUse(error) {\n const failed = responseOf(error);\n if (failed === undefined || failed.status !== 400)\n return false;\n const body = await envelopeOf(failed);\n return body.errcode === undefined || body.errcode === 'M_USER_IN_USE';\n}\n/** Read the avatar bytes with the platform's own content type. */\nasync function downloadAvatar(ctx, url) {\n // `get` with an identity decoder hands back the DOM response; a refused status rejects as the HTTP service's error.\n const response = await ctx.http.get(url, { responseType: (raw) => raw });\n const type = response.headers.get('content-type');\n const data = new Uint8Array(await response.arrayBuffer());\n return {\n data,\n mime: type === null || type === ''\n ? 'application/octet-stream'\n : type.split(';')[0].trim(),\n };\n}\n/**\n * Establish the bot identity and store it on the adapter.\n *\n * @param bot - the adapter being connected.\n * @throws MatrixApiError when the credentials, the namespace or the answered identity are wrong.\n */\nexport async function establishIdentity(bot) {\n const config = bot.config;\n const selfId = bot.selfId;\n let user;\n try {\n user = await bot.internal.register(config.id, config.asToken);\n }\n catch (error) {\n if (!(await isUserInUse(error)))\n throw await apiErrorOf(error, '/client/v3/register');\n try {\n user = await bot.internal.login(config.id, config.asToken);\n }\n catch (loginError) {\n throw await apiErrorOf(loginError, '/client/v3/login');\n }\n }\n if (user.user_id !== selfId) {\n throw new MatrixApiError(`matrix: the homeserver answered user_id \"${user.user_id ?? ''}\" instead of \"${selfId}\"; check the registration's users namespaces`, { method: '/client/v3/register' });\n }\n if (user.access_token === undefined || user.access_token === '') {\n throw new MatrixApiError('matrix: the homeserver answered no access_token; check as_token and the registration', {\n method: '/client/v3/register',\n });\n }\n bot.request.setToken(user.access_token);\n if (config.name !== undefined && config.name !== null && config.name !== '') {\n await bot.internal.setDisplayName(selfId, config.name);\n }\n if (config.avatar !== undefined &&\n config.avatar !== null &&\n config.avatar !== '') {\n const { data, mime } = await downloadAvatar(bot.ctx, config.avatar);\n await bot.internal.setAvatar(selfId, Buffer.from(data), mime);\n }\n const profile = await bot.internal.getProfile(selfId);\n bot.user = {\n id: selfId,\n name: profile.displayname ?? config.name ?? config.id,\n ...(profile.avatar_url === undefined || profile.avatar_url === ''\n ? {}\n : {\n avatar: internalMediaSource(bot, profile.avatar_url) ?? profile.avatar_url,\n }),\n isBot: true,\n };\n}\n//# sourceMappingURL=identity.js.map","/**\n * Matrix Client-Server transport: one HTTP path for every endpoint the adapter calls, the standard error envelope\n * (`errcode` / `error`), rate-limit fields, upload bytes and authenticated media download.\n *\n * `Internal` (the migrated upstream client) keeps its upstream method bodies and calls this class through\n * `bot.http`; the adapter's own send/media paths call it directly, so both cannot diverge on base URL or auth.\n */\nimport { MatrixApiError } from \"./errors.js\";\n/** Delay asked for by a `Retry-After` response header (seconds or HTTP-date). */\nfunction retryAfterHeader(response) {\n const header = response.headers.get('retry-after');\n if (header === null)\n return undefined;\n const seconds = Number(header);\n if (Number.isFinite(seconds) && seconds >= 0)\n return seconds * 1_000;\n const date = Date.parse(header);\n if (!Number.isNaN(date))\n return Math.max(0, date - Date.now());\n return undefined;\n}\n/** The retry delay of one failed answer: the body field first, then the standard header. */\nfunction retryAfterOf(body, response) {\n const bodyDelay = body?.retry_after_ms;\n if (typeof bodyDelay === 'number' &&\n Number.isFinite(bodyDelay) &&\n bodyDelay >= 0)\n return bodyDelay;\n return retryAfterHeader(response);\n}\n/** Whether a caught value is an abort error, including the `DOMException` a signal produces. */\nfunction isAbortError(value) {\n return ((value instanceof Error || value instanceof DOMException) &&\n value.name === 'AbortError');\n}\n/** The abort reason carried by a failure, unwrapping a transport error's `cause` chain. */\nfunction abortReasonOf(error) {\n if (isAbortError(error))\n return error;\n if (typeof error === 'object' && error !== null && 'cause' in error) {\n return abortReasonOf(error.cause);\n }\n return undefined;\n}\n/** A message for a failed call, naming status and the server's own error text when it sent one. */\nfunction failureMessage(method, path, status, body) {\n const code = typeof body?.errcode === 'string' ? body.errcode : undefined;\n const detail = typeof body?.error === 'string' ? body.error : undefined;\n const suffix = code === undefined && detail === undefined\n ? ''\n : `: ${[code, detail].filter((part) => part !== undefined).join(' ')}`;\n return `matrix ${method} ${path} answered ${status}${suffix}`;\n}\n/**\n * The Client-Server client of one bot.\n *\n * Requests are relative to the homeserver root with `/_matrix` already appended. The access token is set after\n * `register`/`login`; `register`/`login` themselves go through `ctx.http` with the application service token.\n */\nexport class MatrixClient {\n ctx;\n endpoint;\n /** The user access token every Client-Server call carries; empty until `connect` logged in. */\n token;\n /** @param ctx - context whose `http` service performs requests. @param endpoint - homeserver root plus `/_matrix`. */\n constructor(ctx, endpoint) {\n this.ctx = ctx;\n this.endpoint = endpoint;\n }\n /** Set the user access token minted by `m.login.application_service`. */\n setToken(token) {\n this.token = token;\n }\n /** The absolute URL of one endpoint path. */\n url(path) {\n return `${this.endpoint}${path.startsWith('/') ? path : `/${path}`}`;\n }\n /**\n * Call one GET endpoint.\n * @param path - endpoint below the Matrix root.\n * @param options - query parameters, headers and cancellation.\n * @returns the parsed JSON answer.\n */\n async get(path, options = {}) {\n return await this.decode(await this.send('GET', path, undefined, options), 'GET', path);\n }\n /**\n * Call one PUT endpoint.\n * @param path - endpoint below the Matrix root.\n * @param data - JSON body (`t.rn` events, profile writes).\n * @param options - query parameters, headers and cancellation.\n * @returns the parsed JSON answer.\n */\n async put(path, data, options = {}) {\n return await this.decode(await this.send('PUT', path, data, options), 'PUT', path);\n }\n /**\n * Call one POST endpoint.\n * @param path - endpoint below the Matrix root.\n * @param data - JSON body or raw bytes (upload).\n * @param options - query parameters, headers and cancellation.\n * @returns the parsed JSON answer.\n */\n async post(path, data, options = {}) {\n return await this.decode(await this.send('POST', path, data, options), 'POST', path);\n }\n /**\n * Upload bytes to the media repository.\n * @param name - file name sent as the `filename` query parameter.\n * @param data - the bytes.\n * @param mimetype - `content-type` of the bytes, when known.\n * @param signal - cancellation.\n * @returns the upload answer (`content_uri` on success).\n */\n async upload(name, data, mimetype, signal) {\n return await this.post(`/media/v3/upload?filename=${encodeURIComponent(name)}`, data, {\n ...(mimetype === undefined\n ? {}\n : { headers: { 'content-type': mimetype } }),\n ...(signal === undefined ? {} : { signal }),\n });\n }\n /**\n * Download one media item through the authenticated endpoint (v1.11's recommended path).\n * @param serverName - the server name of the `mxc://` URI.\n * @param mediaId - the media id of the `mxc://` URI.\n * @param fileName - optional file name path segment.\n * @param signal - cancellation.\n * @returns the platform's answer, body included.\n */\n async download(serverName, mediaId, fileName, signal) {\n const suffix = fileName === undefined ? '' : `/${fileName}`;\n return await this.send('GET', `/client/v1/media/download/${serverName}/${mediaId}${suffix}`, undefined, signal === undefined ? {} : { signal });\n }\n /** Perform one request and return the raw answer; transport failures become `MatrixApiError`s. */\n async send(method, path, data, options) {\n const headers = { ...options.headers };\n if (this.token !== undefined)\n headers.authorization = `Bearer ${this.token}`;\n let response;\n try {\n response = await this.ctx.http(this.url(path), {\n method,\n ...(data === undefined ? {} : { data }),\n ...(options.params === undefined ? {} : { params: options.params }),\n headers,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n });\n }\n catch (cause) {\n if (options.signal?.aborted === true)\n throw options.signal.reason;\n const abort = abortReasonOf(cause);\n if (abort !== undefined)\n throw abort;\n throw new MatrixApiError(`matrix ${method} ${path} request failed`, {\n method,\n path,\n cause,\n });\n }\n if (options.signal?.aborted === true)\n throw options.signal.reason;\n return response;\n }\n /** Decode one answer: JSON object on success, `MatrixApiError` for every refusal. */\n async decode(response, method, path) {\n const status = response.status;\n let text;\n try {\n text = await response.text();\n }\n catch (cause) {\n throw new MatrixApiError('matrix answered without a readable body', {\n status,\n cause,\n });\n }\n let parsed;\n if (text !== '') {\n try {\n parsed = JSON.parse(text);\n }\n catch {\n parsed = undefined;\n }\n }\n const body = typeof parsed === 'object' && parsed !== null\n ? parsed\n : undefined;\n if (status >= 400) {\n const retryAfterMs = retryAfterOf(body, response);\n throw new MatrixApiError(failureMessage(method, path, status, body), {\n status,\n ...(typeof body?.errcode === 'string' ? { errcode: body.errcode } : {}),\n ...(typeof body?.error === 'string' ? { error: body.error } : {}),\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n }\n if (parsed === undefined) {\n throw new MatrixApiError(`matrix answered ${status} without a JSON body`, { status });\n }\n return parsed;\n }\n}\n//# sourceMappingURL=request.js.map","/**\n * The room cache and the one-shot full-state `/sync` that fills it.\n *\n * Application Service pushes carry events only: no room list, name, member set or summary. `connect` therefore asks the\n * homeserver for one full-state sync (`full_state=true` makes the answer immediate, so it is a query, not a poll),\n * uses the joined rooms for names/members/summaries/`m.direct`/encryption markers, and joins the invited rooms when\n * `autoJoin` is on. The same query runs once more after the bot joins a room on its own.\n *\n * A room is reported as direct when the bot's own `m.direct` names it, else when the summary says two joined members,\n * else when the observed joined members are exactly the bot and one other user. Everything else is a group.\n */\n/** The rooms the bot's own `m.direct` account data names. */\nfunction directRoomIds(sync) {\n const out = [];\n for (const event of sync.account_data?.events ?? []) {\n if (event.type !== 'm.direct')\n continue;\n const content = event.content;\n for (const value of Object.values(content)) {\n if (!Array.isArray(value))\n continue;\n for (const roomId of value) {\n if (typeof roomId === 'string')\n out.push(roomId);\n }\n }\n }\n return out;\n}\n/** In-memory room state shared by decode, enumeration and member reads. */\nexport class RoomCache {\n rooms = new Map();\n directRooms = new Set();\n /** The cached state of one room, created on first use. */\n room(roomId) {\n let room = this.rooms.get(roomId);\n if (room === undefined) {\n room = { members: new Map(), encrypted: false };\n this.rooms.set(roomId, room);\n }\n return room;\n }\n /** The room name last seen, if any. */\n nameOf(roomId) {\n return this.rooms.get(roomId)?.name;\n }\n /** The display name last seen for one member of a room. */\n displayNameOf(roomId, userId) {\n return this.rooms.get(roomId)?.members.get(userId)?.displayname;\n }\n /** Whether a room's state says it enabled end-to-end encryption. */\n isEncrypted(roomId) {\n return this.rooms.get(roomId)?.encrypted === true;\n }\n /**\n * Record that a room is encrypted.\n * @param roomId - the room.\n * @returns true when this is the first observation, so the caller logs its warning once.\n */\n markEncrypted(roomId) {\n const room = this.room(roomId);\n if (room.encrypted)\n return false;\n room.encrypted = true;\n return true;\n }\n /** Record one `m.room.name` event. */\n setName(roomId, name) {\n this.room(roomId).name = name;\n }\n /** Record one `m.room.member` event. */\n applyMember(roomId, userId, membership, displayname) {\n const room = this.room(roomId);\n const member = room.members.get(userId) ?? { joined: false };\n member.joined = membership === 'join';\n if (displayname !== undefined)\n member.displayname = displayname;\n room.members.set(userId, member);\n }\n /** The joined members of one room, in insertion order. */\n joinedMembers(roomId) {\n const room = this.rooms.get(roomId);\n if (room === undefined)\n return [];\n return [...room.members]\n .filter(([, member]) => member.joined)\n .map(([userId]) => userId);\n }\n /**\n * Whether a room is a direct chat.\n * @param roomId - the room.\n * @param selfId - the bot's Matrix user id.\n * @returns true for a room the judgement chain reports as direct.\n */\n isDirect(roomId, selfId) {\n if (this.directRooms.has(roomId))\n return true;\n const room = this.rooms.get(roomId);\n if (room === undefined)\n return false;\n if (room.joinedMemberCount === 2)\n return true;\n const joined = [...room.members.values()].filter((member) => member.joined);\n return joined.length === 2 && room.members.get(selfId)?.joined === true;\n }\n /** Record one state event that arrived by push. */\n applyStateEvent(roomId, type, stateKey, content) {\n switch (type) {\n case 'm.room.name':\n if (typeof content.name === 'string')\n this.setName(roomId, content.name);\n return;\n case 'm.room.member':\n if (stateKey !== undefined) {\n this.applyMember(roomId, stateKey, typeof content.membership === 'string'\n ? content.membership\n : undefined, typeof content.displayname === 'string'\n ? content.displayname\n : undefined);\n }\n return;\n case 'm.room.encryption':\n this.markEncrypted(roomId);\n return;\n }\n }\n /**\n * Apply one full-state sync answer.\n * @param sync - the answer of `GET /client/v3/sync?full_state=true`.\n * @param selfId - the bot's Matrix user id.\n * @returns the rooms that invited the bot, in answer order.\n */\n applySync(sync, selfId) {\n for (const roomId of directRoomIds(sync))\n this.directRooms.add(roomId);\n for (const [roomId, joined] of Object.entries(sync.rooms?.join ?? {})) {\n const room = this.room(roomId);\n for (const event of joined.state?.events ?? []) {\n this.applyStateEvent(roomId, event.type, event.state_key, event.content);\n }\n const count = joined.summary?.['m.joined_member_count'];\n if (typeof count === 'number')\n room.joinedMemberCount = count;\n }\n const invites = [];\n for (const [roomId, invited] of Object.entries(sync.rooms?.invite ?? {})) {\n let invitedSelf = false;\n for (const event of invited.invite_state?.events ?? []) {\n this.applyStateEvent(roomId, event.type, event.state_key, event.content);\n if (event.type === 'm.room.member' &&\n event.state_key === selfId &&\n event.content.membership === 'invite') {\n invitedSelf = true;\n }\n }\n if (invitedSelf)\n invites.push(roomId);\n }\n return invites;\n }\n}\n/**\n * Run the one-shot full-state sync and apply it.\n *\n * The response's `next_batch` is deliberately dropped: an Application Service has no cursor, and the timeline of this\n * query is history that the host's store already owns.\n *\n * @param internal - the room enumerator (the migrated `Internal`).\n * @param cache - the room cache to fill.\n * @param selfId - the bot's Matrix user id.\n * @returns the rooms that invited the bot.\n */\nexport async function enumerateRooms(internal, cache, selfId) {\n const sync = await internal.sync(true);\n return cache.applySync(sync, selfId);\n}\n//# sourceMappingURL=rooms.js.map","/**\n * Outbound hooks: send, delete, reaction, members and message reads.\n *\n * Every write is one `PUT /rooms/{roomId}/send|redact/...` with a transaction id; `txtId` is derived from the caller's\n * idempotency key when there is one (Matrix deduplicates a retransmission with the same id), else from a per-process\n * random base plus a counter. Matrix returns only an `event_id`, so a published part carries no platform timestamp.\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\nimport { createHash } from 'node:crypto';\nimport { MESSAGE_TYPES } from \"./decode.js\";\n/** The transaction id of one request: idempotency key first, counter otherwise. */\nexport function txnIdOf(deps, ctx) {\n const key = ctx.options.idempotencyKey;\n if (key !== undefined) {\n return createHash('sha256')\n .update(`${key}#${ctx.index}`)\n .digest('hex')\n .slice(0, 32);\n }\n return String(deps.nextTxn());\n}\n/**\n * Whether a retry of one send is deduplicated by Matrix. Only a call with an idempotency key is: the spec returns the\n * first answer for a retransmission of the same `(endpoint, txnId)` pair.\n */\nexport function idempotentSend(_target, ctx) {\n return ctx.options.idempotencyKey !== undefined;\n}\n/** The event content of one serialized payload. */\nfunction eventContent(payload) {\n const relates = payload.relates;\n const common = {\n 'm.mentions': payload.mentions,\n ...(relates === undefined ? {} : { 'm.relates_to': relates }),\n };\n if (payload.kind === 'text') {\n return {\n msgtype: 'm.text',\n body: payload.body,\n ...(payload.html === undefined\n ? {}\n : { format: 'org.matrix.custom.html', formatted_body: payload.html }),\n ...common,\n };\n }\n return {\n msgtype: payload.msgtype,\n body: payload.body,\n filename: payload.body,\n url: payload.url,\n ...(payload.info === undefined ? {} : { info: payload.info }),\n ...common,\n };\n}\n/** The published part of one accepted event. */\nfunction partOf(deps, payload, eventId) {\n if (typeof eventId !== 'string' || eventId === '') {\n // The request reached the homeserver, so an answer without an id is a published outcome, not a refusal.\n throw new PlatformError('invalid', 'matrix: the homeserver answered without an event_id', { published: 'unknown' });\n }\n const thread = payload.thread;\n const referrer = {\n roomId: payload.roomId,\n eventId,\n sender: deps.selfId,\n ...(thread === undefined ? {} : { threadRoot: thread.root }),\n };\n return {\n id: eventId,\n kind: 'message',\n time: Date.now(),\n ...(thread === undefined\n ? {}\n : { thread: { id: thread.root, root: thread.root } }),\n referrer,\n };\n}\n/**\n * Send one serialized payload.\n * @param deps - adapter services.\n * @param payload - the serialized payload.\n * @param _target - the chat being published to (the payload already names it).\n * @param ctx - core send context (signal, part index, idempotency key).\n * @returns the published part.\n */\nexport async function sendPayload(deps, payload, _target, ctx) {\n const txn = txnIdOf(deps, ctx);\n const path = `/client/v3/rooms/${payload.roomId}/send/m.room.message/${txn}`;\n const answer = await deps.client.put(path, eventContent(payload), ctx.options.signal === undefined ? {} : { signal: ctx.options.signal });\n return partOf(deps, payload, answer.event_id);\n}\n/**\n * Redact one published event.\n * @param deps - adapter services.\n * @param part - the part to delete.\n * @param handle - the message the part belongs to (its target names the room).\n */\nexport async function deletePart(deps, part, handle) {\n if (part.id === '') {\n throw new PlatformError('invalid', 'matrix: an empty event id cannot be redacted', { published: 'no' });\n }\n await deps.client.put(`/client/v3/rooms/${handle.target.chat.id}/redact/${part.id}/${deps.nextTxn()}`, {});\n}\n/**\n * Add an annotation (`m.reaction`) to one message.\n * @param deps - adapter services.\n * @param message - the message to react to.\n * @param emoji - the annotation key, passed through as written (`:shortcode:` included).\n */\nexport async function createReaction(deps, message, emoji) {\n await deps.client.put(`/client/v3/rooms/${message.chat.id}/send/m.reaction/${deps.nextTxn()}`, {\n 'm.relates_to': {\n rel_type: 'm.annotation',\n event_id: message.id,\n key: emoji,\n },\n });\n}\n/**\n * List the joined members of a room.\n *\n * The room state endpoint returns the whole member set at once, so there is no cursor; `limit` truncates the page.\n *\n * @param deps - adapter services.\n * @param chat - the room.\n * @param _cursor - ignored; the state read is one full page.\n * @param limit - page size bound.\n * @returns the joined members, each with the display name its membership event carried.\n */\nexport async function members(deps, chat, _cursor, limit) {\n const state = await deps.client.get(`/client/v3/rooms/${chat.id}/state`);\n const data = [];\n for (const event of state) {\n if (event.type !== 'm.room.member' || event.state_key === undefined)\n continue;\n const content = event.content;\n if (content.membership !== 'join')\n continue;\n if (content.displayname !== undefined) {\n deps.rooms.applyMember(chat.id, event.state_key, 'join', content.displayname);\n }\n data.push({\n id: event.state_key,\n ...(content.displayname === undefined\n ? {}\n : { name: content.displayname }),\n isBot: deps.isBot(event.state_key),\n });\n }\n const page = limit === undefined ? data : data.slice(0, Math.max(0, limit));\n return { data: page };\n}\n/**\n * Read one message by id.\n * @param deps - adapter services.\n * @param chat - the chat the caller asked about; the decoded message reports it unchanged.\n * @param id - the event id.\n * @returns the decoded message.\n */\nexport async function getMessage(deps, chat, id) {\n const event = await deps.client.get(`/client/v3/rooms/${chat.id}/event/${id}`);\n if (event.type !== 'm.room.message') {\n throw new PlatformError('not-found', `matrix: event ${id} in ${chat.id} is not a message`, { published: 'no' });\n }\n const content = event.content;\n if (content.msgtype === undefined || !MESSAGE_TYPES.has(content.msgtype)) {\n // A redacted event keeps an empty content object; an unsupported msgtype has no inbound representation.\n throw new PlatformError('not-found', `matrix: event ${id} in ${chat.id} is not a readable message`, { published: 'no' });\n }\n return deps.decode(chat, event);\n}\n//# sourceMappingURL=send.js.map","/**\n * The single `html` mode's node, draft and payload types, HTML escaping, media promotion, reply/thread relations and\n * payload assembly.\n *\n * A Matrix message is either one `m.text` event with `body` + `formatted_body`, or one media event per media element.\n * Every handler therefore returns an HTML fragment and its plain-text projection from the same traversal, so the two\n * sides cannot drift; `assemble` flushes a text draft around each media element.\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\nimport { isPhrasingContainer } from '@deepseek-ai/satori-element';\nimport { addMention, createMentionSet, mentionWire } from \"../mentions.js\";\n/** Escape character data of `formatted_body`. */\nexport function escapeHtml(text) {\n return text\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>');\n}\n/** Escape one HTML attribute value (double-quoted). */\nexport function escapeAttribute(text) {\n return escapeHtml(text).replaceAll('\"', '"');\n}\n/** One inline node. */\nexport function htmlNode(html, text, mentions) {\n return {\n type: 'html',\n html,\n text,\n ...(mentions === undefined || mentions.length === 0 ? {} : { mentions }),\n };\n}\n/** One mention node per collected user and one for the room mention. */\nexport function mentionNodes(set) {\n return [\n ...set.users.map((user) => ({ user })),\n ...(set.room ? [{ room: true }] : []),\n ];\n}\n/**\n * Split rendered children into one inline run and the media nodes that follow it.\n * @param nodes - rendered children.\n * @returns the concatenated HTML/text, the collected mentions and the media nodes, in source order.\n */\nexport function inlineRun(nodes) {\n let html = '';\n let text = '';\n const mentions = createMentionSet();\n const rest = [];\n for (const node of nodes) {\n if (node.type === 'media') {\n rest.push(node);\n continue;\n }\n html += node.html;\n text += node.text;\n for (const mention of node.mentions ?? [])\n addMention(mentions, mention);\n }\n return { html, text, mentions, rest };\n}\n/**\n * Wrap the inline text of rendered children in one HTML tag; media of the subtree follows the wrapper.\n * @param tag - the HTML tag name.\n * @param nodes - rendered children.\n * @param textSuffix - plain-text separator this block adds after its inline text.\n * @returns the wrapper (when it has text) and the media nodes.\n */\nexport function inlineWrapper(tag, nodes, textSuffix = '') {\n const { html, text, mentions, rest } = inlineRun(nodes);\n const out = [];\n if (html !== '') {\n out.push(htmlNode(`<${tag}>${html}</${tag}>`, text + textSuffix, mentionNodes(mentions)));\n }\n out.push(...rest);\n return out;\n}\n/**\n * Turn one media element into its node.\n *\n * Matrix clients render inline `mxc:` images inconsistently and a media message is the standard presentation, so every\n * media element becomes its own event. Media standing in phrasing content is reported as `moved`: nothing is lost,\n * only repositioned.\n *\n * @param el - one of `img`/`audio`/`video`/`file`.\n * @param ctx - render context of the mode.\n * @returns the media node, to be published after the text run it was found in.\n */\nexport function mediaNode(el, ctx) {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (parent !== undefined && isPhrasingContainer(parent.type)) {\n ctx.report.moved.push({\n tag: el.type,\n reason: 'matrix-media-split',\n path: ctx.stableId(el),\n });\n }\n switch (el.type) {\n case 'img':\n return {\n type: 'media',\n tag: 'img',\n ref: ctx.resource('image', el.attrs.src, {\n ...(el.attrs.alt === undefined ? {} : { name: el.attrs.alt }),\n ...(el.attrs.width === undefined ? {} : { width: el.attrs.width }),\n ...(el.attrs.height === undefined ? {} : { height: el.attrs.height }),\n }),\n ...(el.attrs.alt === undefined ? {} : { name: el.attrs.alt }),\n ...(el.attrs.width === undefined ? {} : { width: el.attrs.width }),\n ...(el.attrs.height === undefined ? {} : { height: el.attrs.height }),\n };\n case 'audio':\n return {\n type: 'media',\n tag: 'audio',\n ref: ctx.resource('audio', el.attrs.src, {\n ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n ...(el.attrs.duration === undefined\n ? {}\n : { duration: el.attrs.duration }),\n }),\n ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n ...(el.attrs.duration === undefined\n ? {}\n : { duration: el.attrs.duration }),\n };\n case 'video':\n return {\n type: 'media',\n tag: 'video',\n ref: ctx.resource('video', el.attrs.src, {\n ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n ...(el.attrs.duration === undefined\n ? {}\n : { duration: el.attrs.duration }),\n }),\n ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n ...(el.attrs.duration === undefined\n ? {}\n : { duration: el.attrs.duration }),\n };\n case 'file':\n return {\n type: 'media',\n tag: 'file',\n ref: ctx.resource('file', el.attrs.src, el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n };\n }\n}\n/** The Matrix `msgtype` of one media tag. */\nexport function msgtypeOf(tag) {\n switch (tag) {\n case 'img':\n return 'm.image';\n case 'audio':\n return 'm.audio';\n case 'video':\n return 'm.video';\n case 'file':\n return 'm.file';\n }\n}\n/**\n * Fold a node stream into platform events: a text run around each media node.\n * @param nodes - rendered nodes, in source order.\n * @returns the drafts to publish, at least one for any content a handler produced.\n */\nexport function assembleDrafts(nodes) {\n const drafts = [];\n let html = '';\n let text = '';\n let mentions = createMentionSet();\n const flush = () => {\n if (html.trim() === '' && text.trim() === '') {\n html = '';\n text = '';\n mentions = createMentionSet();\n return;\n }\n drafts.push({ kind: 'text', html, text, mentions: mentionWire(mentions) });\n html = '';\n text = '';\n mentions = createMentionSet();\n };\n for (const node of nodes) {\n if (node.type === 'media') {\n flush();\n drafts.push({\n kind: 'media',\n tag: node.tag,\n ref: node.ref,\n ...(node.name === undefined ? {} : { name: node.name }),\n ...(node.width === undefined ? {} : { width: node.width }),\n ...(node.height === undefined ? {} : { height: node.height }),\n ...(node.duration === undefined ? {} : { duration: node.duration }),\n mentions: {},\n });\n continue;\n }\n html += node.html;\n text += node.text;\n for (const mention of node.mentions ?? [])\n addMention(mentions, mention);\n }\n flush();\n return drafts;\n}\n/** The adapter-private reply context of a publication, when the target carries one. */\nfunction referrerOf(target) {\n const referrer = target.referrer;\n if (typeof referrer !== 'object' || referrer === null)\n return undefined;\n return referrer;\n}\n/** The thread root a target names: an explicit id, else the referrer's root for `thread: true`. */\nfunction threadRootOf(target) {\n if (typeof target.thread === 'string')\n return target.thread;\n if (target.thread !== true)\n return undefined;\n return referrerOf(target)?.threadRoot;\n}\n/**\n * Build the `m.relates_to` object of one event.\n *\n * A reply names only the quoted event id: the fallback body needs the quoted text, which this adapter does not fetch.\n * A thread carries its root, and — because the specification requires an unthreaded-client fallback — an\n * `m.in_reply_to` naming the latest known event (`is_falling_back: true`).\n */\nfunction relationOf(ctx) {\n const referrer = referrerOf(ctx.target);\n const threadRoot = threadRootOf(ctx.target);\n const quote = ctx.index === 0 ? ctx.quote : undefined;\n if (threadRoot === undefined) {\n return quote === undefined\n ? undefined\n : { 'm.in_reply_to': { event_id: quote } };\n }\n const reply = quote ?? referrer?.eventId;\n return {\n rel_type: 'm.thread',\n event_id: threadRoot,\n ...(reply === undefined\n ? {}\n : { is_falling_back: true, 'm.in_reply_to': { event_id: reply } }),\n };\n}\n/** One media key resolved by `prepare`. */\nfunction resolvedKey(prepared, ref) {\n const resolved = prepared.resolved.get(ref);\n if (resolved === undefined) {\n throw new PlatformError('invalid', 'matrix: media was not prepared before serialize', { published: 'no' });\n }\n return resolved.key;\n}\n/** The extra fields `upload` recorded for one prepared media key. */\nfunction extraOf(prepared, ref) {\n const resolved = prepared.resolved.get(ref);\n if (resolved === undefined)\n return {};\n const extra = resolved.extra;\n if (typeof extra !== 'object' || extra === null)\n return {};\n return extra;\n}\n/**\n * Build the request payload of one draft.\n *\n * @param prepared - one assembled draft with its resolved media.\n * @param ctx - serialize context (target, part index, quote).\n * @returns the exact request data `sendPayload` posts.\n */\nexport function serializeDraft(prepared, ctx) {\n const draft = prepared.draft;\n const relates = relationOf(ctx);\n const thread = threadRootOf(ctx.target);\n const common = {\n roomId: ctx.target.chat.id,\n mentions: draft.mentions,\n ...(relates === undefined ? {} : { relates }),\n ...(thread === undefined ? {} : { thread: { root: thread } }),\n };\n if (draft.kind === 'text') {\n const body = draft.text.trim();\n const html = draft.html.trim();\n return {\n kind: 'text',\n ...common,\n // Matrix requires a plain `body`; the media path is the only draft that may carry no text.\n body: body === '' ? ' ' : body,\n ...(html === '' ? {} : { html }),\n };\n }\n const extra = extraOf(prepared, draft.ref);\n const body = draft.name ?? extra.name ?? 'file';\n const info = {\n ...(draft.width === undefined ? {} : { w: draft.width }),\n ...(draft.height === undefined ? {} : { h: draft.height }),\n ...(draft.duration === undefined ? {} : { duration: draft.duration }),\n ...(extra.mime === undefined ? {} : { mimetype: extra.mime }),\n ...(extra.size === undefined ? {} : { size: extra.size }),\n };\n return {\n kind: 'media',\n ...common,\n msgtype: msgtypeOf(draft.tag),\n url: resolvedKey(prepared, draft.ref),\n body,\n ...(Object.keys(info).length === 0 ? {} : { info }),\n };\n}\n//# sourceMappingURL=shared.js.map","/**\n * `html` mode: Matrix's `org.matrix.custom.html` rich text, with the plain `body` produced from the same traversal.\n *\n * Native tags are the specification's allowed subset (`b`/`i`/`u`/`s`/`del`/`code`/`pre`/`a`/`p`/`blockquote`/lists/\n * headings/table/details/spoiler); everything else takes the core fallback and is reported as degraded. A user mention\n * renders as a `matrix.to` link and collects into `m.mentions`; `@room` is the room mention. Media never stays inline:\n * each media element becomes its own event and is reported as moved when it stood in phrasing content.\n */\nimport { ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core';\nimport { addMention, createMentionSet } from \"../mentions.js\";\nimport { assembleDrafts, escapeAttribute, escapeHtml, htmlNode, inlineRun, inlineWrapper, mediaNode, mentionNodes, serializeDraft, } from \"./shared.js\";\n/** The `matrix.to` prefix of a room or user link. */\nconst MATRIX_LINK = 'https://matrix.to/#/';\n/** Wrap the inline text of `children` in one tag, letting media of the subtree follow it. */\nfunction wrap(tag, ctx, children, textSuffix = '') {\n return inlineWrapper(tag, ctx.render(children), textSuffix);\n}\n/** Prefix every line of a blockquote text projection with `> `. */\nfunction quoteText(text) {\n const body = text.replace(/\\n+$/, '');\n if (body === '')\n return '\\n\\n';\n return `${body\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n')}\\n\\n`;\n}\n/** The text of one table cell, with block children separated by a space. */\nfunction cellText(ctx, cell) {\n return cell.children\n .map((child) => ctx.text([child]))\n .filter((part) => part.trim() !== '')\n .join(' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n/** The `- ` / `1. ` marker of one list item, plus its task-list box. */\nfunction listMarker(el, ctx) {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n let marker = '- ';\n if (parent?.type === 'ol') {\n const start = typeof parent.attrs.start === 'number' ? parent.attrs.start : 1;\n const index = parent.children.indexOf(el);\n marker = `${start + Math.max(0, index)}. `;\n }\n if (el.attrs.checked === true)\n marker += '[x] ';\n else if (el.attrs.checked === false)\n marker += '[ ] ';\n return marker;\n}\n/** Build the `html` mode. */\nexport function createHtmlMode() {\n const elements = new ElementRegistry()\n .register('text', (el) => htmlNode(escapeHtml(el.attrs.content), el.attrs.content))\n .register('br', () => htmlNode('<br/>', '\\n'))\n .register('p', (el, ctx) => wrap('p', ctx, el.children, '\\n\\n'))\n .register('b', (el, ctx) => wrap('strong', ctx, el.children))\n .register('i', (el, ctx) => wrap('em', ctx, el.children))\n .register('u', (el, ctx) => wrap('u', ctx, el.children))\n .register('s', (el, ctx) => wrap('del', ctx, el.children))\n .register('spoiler', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n // The hidden text reaches `formatted_body` only: `body` must not repeat what the spoiler hides.\n return [\n htmlNode(`<span data-mx-spoiler>${run.html}</span>`, '[剧透]', mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('code', (el, ctx) => {\n const content = ctx.text(el.children);\n return htmlNode(`<code>${escapeHtml(content)}</code>`, content);\n })\n .register('pre', (el, ctx) => {\n const content = ctx.text(el.children);\n const language = el.attrs.lang;\n const html = language === undefined || language === ''\n ? `<pre>${escapeHtml(content)}</pre>`\n : `<pre><code class=\"language-${escapeAttribute(language)}\">${escapeHtml(content)}</code></pre>`;\n return htmlNode(html, `${content}\\n\\n`);\n }, { variants: ['lang'] })\n .register('a', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n const href = el.attrs.href;\n const label = run.html === '' ? escapeHtml(href) : run.html;\n const plain = run.text === '' ? href : run.text;\n return [\n htmlNode(`<a href=\"${escapeAttribute(href)}\">${label}</a>`, plain === href ? href : `${plain} (${href})`, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('at', (el) => {\n if (el.attrs.type === 'all')\n return htmlNode('@room', '@room', [{ room: true }]);\n if (el.attrs.type === 'user' && el.attrs.id !== undefined) {\n const id = el.attrs.id;\n const label = escapeHtml(el.attrs.name ?? id);\n return htmlNode(`<a href=\"${MATRIX_LINK}${escapeAttribute(id)}\">${label}</a>`, el.attrs.name ?? id, [{ user: id }]);\n }\n return htmlNode(escapeHtml(el.attrs.name ?? el.attrs.id ?? el.attrs.type), el.attrs.name ?? el.attrs.id ?? '');\n }, { variants: ['user', 'all'] })\n .register('channel', (el) => {\n const id = el.attrs.id;\n const label = escapeHtml(el.attrs.name ?? id);\n return htmlNode(`<a href=\"${MATRIX_LINK}${escapeAttribute(id)}\">${label}</a>`, el.attrs.name ?? id);\n })\n .register('emoji', (el) => {\n const label = `:${el.attrs.name ?? el.attrs.id}:`;\n return htmlNode(escapeHtml(label), label);\n })\n .register('h1', (el, ctx) => wrap('h1', ctx, el.children, '\\n\\n'))\n .register('h2', (el, ctx) => wrap('h2', ctx, el.children, '\\n\\n'))\n .register('h3', (el, ctx) => wrap('h3', ctx, el.children, '\\n\\n'))\n .register('h4', (el, ctx) => wrap('h4', ctx, el.children, '\\n\\n'))\n .register('h5', (el, ctx) => wrap('h5', ctx, el.children, '\\n\\n'))\n .register('h6', (el, ctx) => wrap('h6', ctx, el.children, '\\n\\n'))\n .register('blockquote', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n return [\n htmlNode(`<blockquote>${run.html}</blockquote>`, quoteText(run.text), mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('ul', (el, ctx) => wrap('ul', ctx, el.children))\n .register('ol', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n const start = typeof el.attrs.start === 'number' ? ` start=\"${el.attrs.start}\"` : '';\n return [\n htmlNode(`<ol${start}>${run.html}</ol>`, run.text, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('li', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n const box = el.attrs.checked === true\n ? '[x] '\n : el.attrs.checked === false\n ? '[ ] '\n : '';\n return [\n htmlNode(`<li>${box}${run.html}</li>`, `${listMarker(el, ctx)}${run.text}\\n`, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n }, { variants: ['checked', 'nested'] })\n .register('hr', () => htmlNode('<hr/>', '\\n---\\n'))\n .register('table', (el, ctx) => {\n const rows = el.children.filter((child) => child.type === 'tr');\n const first = rows[0];\n const header = first !== undefined &&\n first.children.length > 0 &&\n first.children.every((cell) => cell.type === 'th')\n ? first\n : undefined;\n const bodyRows = header === undefined ? rows : rows.slice(1);\n const renderedRow = (row) => inlineRun(ctx.render([row]));\n const headerRun = header === undefined ? undefined : renderedRow(header);\n const bodyRuns = bodyRows.map(renderedRow);\n const html = [\n '<table>',\n headerRun === undefined ? '' : `<thead>${headerRun.html}</thead>`,\n `<tbody>${bodyRuns.map((run) => run.html).join('')}</tbody>`,\n '</table>',\n ].join('');\n const headerCells = header === undefined\n ? []\n : header.children\n .filter((cell) => cell.type === 'th' || cell.type === 'td')\n .map((cell) => cellText(ctx, cell));\n const lines = bodyRows.map((row) => row.children\n .filter((cell) => cell.type === 'th' || cell.type === 'td')\n .map((cell, index) => {\n const value = cellText(ctx, cell);\n const head = headerCells[index];\n return head === undefined || head === ''\n ? value\n : `${head}: ${value}`;\n })\n .join(' | '));\n const mentions = createMentionSet();\n for (const run of [headerRun, ...bodyRuns]) {\n if (run === undefined)\n continue;\n for (const mention of mentionNodes(run.mentions))\n addMention(mentions, mention);\n }\n const text = lines.join('\\n');\n return [\n htmlNode(html, text === '' ? '' : `${text}\\n`, mentionNodes(mentions)),\n ...(headerRun?.rest ?? []),\n ...bodyRuns.flatMap((run) => run.rest),\n ];\n }, { variants: ['align'] })\n .register('tr', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n return [\n htmlNode(`<tr>${run.html}</tr>`, run.text, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('th', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n const align = el.attrs.align === undefined\n ? ''\n : ` align=\"${escapeAttribute(el.attrs.align)}\"`;\n return [\n htmlNode(`<th${align}>${run.html}</th>`, run.text, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('td', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n const align = el.attrs.align === undefined\n ? ''\n : ` align=\"${escapeAttribute(el.attrs.align)}\"`;\n return [\n htmlNode(`<td${align}>${run.html}</td>`, run.text, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n }, { variants: ['block'] })\n .register('details', (el, ctx) => {\n const run = inlineRun(ctx.render(el.children));\n const open = el.attrs.open === true ? ' open' : '';\n return [\n htmlNode(`<details${open}>${run.html}</details>`, `▸ ${run.text}`, mentionNodes(run.mentions)),\n ...run.rest,\n ];\n })\n .register('summary', (el, ctx) => wrap('summary', ctx, el.children, '\\n'))\n .register('small', (el, ctx) => ctx.render(el.children))\n .register('img', (el, ctx) => mediaNode(el, ctx), { variants: ['inline'] })\n .register('audio', (el, ctx) => mediaNode(el, ctx))\n .register('video', (el, ctx) => mediaNode(el, ctx))\n .register('file', (el, ctx) => mediaNode(el, ctx));\n return {\n id: 'html',\n elements,\n limits: {},\n assemble: (nodes) => assembleDrafts(nodes),\n serialize: (prepared, ctx) => serializeDraft(prepared, ctx),\n };\n}\n//# sourceMappingURL=html.js.map","import imageSize from 'image-size';\nexport class Internal {\n bot;\n txnId = Math.round(Math.random() * 1000);\n constructor(bot) {\n this.bot = bot;\n }\n async uploadFile(filename, buffer, mimetype) {\n const headers = {};\n if (mimetype)\n headers['content-type'] = mimetype;\n return (await this.bot.http.post(`/media/v3/upload?filename=${filename}`, buffer, { headers })).content_uri;\n }\n async sendTextMessage(roomId, content, reply) {\n const eventContent = {\n msgtype: 'm.text',\n body: content,\n };\n if (reply)\n eventContent['m.relates_to'] = { 'm.in_reply_to': { 'event_id': reply } };\n const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.room.message/${this.txnId++}`, eventContent);\n return response.event_id;\n }\n async sendMediaMessage(roomId, type, buffer, reply, mimetype, filename = 'file') {\n const uri = await this.uploadFile(filename, buffer, mimetype);\n let info;\n if (type === 'image') {\n const { width, height } = imageSize(buffer);\n info = {\n size: buffer.byteLength,\n h: height,\n w: width,\n ...(mimetype === undefined ? {} : { mimetype }),\n };\n }\n const eventContent = {\n msgtype: `m.${type}`,\n body: filename,\n url: uri,\n ...(info === undefined ? {} : { info }),\n };\n if (reply)\n eventContent['m.relates_to'] = { 'm.in_reply_to': { 'event_id': reply } };\n const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.room.message/${this.txnId++}`, eventContent);\n return response.event_id;\n }\n async sendReaction(roomId, messageId, key) {\n const eventContent = {\n 'm.relates_to': {\n rel_type: 'm.annotation',\n event_id: messageId,\n key,\n },\n };\n const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.reaction/${this.txnId++}`, eventContent);\n return response.event_id;\n }\n async getEvent(roomId, eventId) {\n return await this.bot.http.get(`/client/v3/rooms/${roomId}/event/${eventId}`);\n }\n async redactEvent(roomId, eventId, reason) {\n const event = await this.bot.http.put(`/client/v3/rooms/${roomId}/redact/${eventId}/${this.txnId++}`, { reason });\n return event.event_id;\n }\n async getProfile(userId) {\n return await this.bot.http.get(`/client/v3/profile/${userId}`);\n }\n async setDisplayName(userId, displayname) {\n await this.bot.http.put(`/client/v3/profile/${userId}/displayname`, { displayname });\n }\n async setAvatar(userId, buffer, mimetype) {\n const uri = await this.uploadFile('avatar', buffer, mimetype);\n await this.bot.http.put(`/client/v3/profile/${userId}/avatar_url`, { avatar_url: uri });\n }\n async createRoom(creation) {\n const response = await this.bot.http.post('/client/v3/createRoom', creation);\n return response.room_id;\n }\n async joinRoom(roomId, reason) {\n const response = await this.bot.http.post(`/client/v3/join/${roomId}`, { reason });\n return response.room_id;\n }\n async leaveRoom(roomId, reason) {\n const response = await this.bot.http.post(`/client/v3/rooms/${roomId}/leave`, { reason });\n return response.room_id;\n }\n async invite(roomId, userId, reason) {\n await this.bot.http.post(`/client/v3/rooms/${roomId}/invite`, { user_id: userId, reason });\n }\n async sync(fullSstate = false) {\n return await this.bot.http.get('/client/v3/sync', {\n params: { full_state: fullSstate },\n });\n }\n async getState(roomId) {\n return await this.bot.http.get(`/client/v3/rooms/${roomId}/state`);\n }\n async setState(roomId, eventType, event, state) {\n const statePath = state ? `/${state}` : '';\n const response = await this.bot.http.put(`/client/v3/rooms/${roomId}/state/${eventType}${statePath}`, event);\n return response.event_id;\n }\n async getJoinedRooms() {\n return await this.bot.http.get('/client/v3/joined_rooms');\n }\n async register(username, asToken) {\n return await this.bot.ctx.http.post(this.bot.endpoint + '/client/v3/register', {\n type: 'm.login.application_service',\n username,\n }, {\n headers: {\n 'Authorization': `Bearer ${asToken}`,\n },\n });\n }\n async login(username, asToken) {\n return await this.bot.ctx.http.post(this.bot.endpoint + '/client/v3/login', {\n type: 'm.login.application_service',\n identifier: {\n type: 'm.id.user',\n user: username,\n },\n }, {\n headers: {\n 'Authorization': `Bearer ${asToken}`,\n },\n });\n }\n getAssetUrl(mxc) {\n // mxc://\n return `${this.bot.endpoint}/client/v1/media/download/${mxc.substring(6)}`;\n }\n}\n//# sourceMappingURL=types.js.map","/**\n * Matrix Application Service adapter.\n *\n * The only transport is the homeserver's transaction push into a profile-provided `webServer`; the bot first registers\n * its virtual user (`m.login.application_service`), then runs one full-state sync to learn its rooms, then registers\n * the transaction route and goes online. There is no `/sync` message loop and no end-to-end encryption: encrypted\n * rooms are unusable, and `m.room.encrypted` events are dropped.\n *\n * The mode is `html` only: Matrix's rich text is `org.matrix.custom.html` plus a plain `body`, and a plain-only mode\n * would be the same payload without the two format fields. Media is uploaded to the media repository; inbound `mxc:`\n * URIs are served through the authenticated download endpoint behind the bot's own `satori:` route.\n */\nimport { Adapter } from '@deepseek-ai/cordis-plugin-im-core';\nimport { MatrixAppService } from \"./as.js\";\nimport { Config, configError } from \"./config.js\";\nimport { decodeEvent, decodeMessage } from \"./decode.js\";\nimport { classifyMatrixError, isTokenFailure } from \"./errors.js\";\nimport { establishIdentity, matrixUserId } from \"./identity.js\";\nimport { mediaResponse, parseMxc, uploadResource } from \"./media.js\";\nimport { MatrixClient } from \"./request.js\";\nimport { enumerateRooms, RoomCache } from \"./rooms.js\";\nimport { createReaction, deletePart, getMessage, idempotentSend, members, sendPayload, } from \"./send.js\";\nimport { createHtmlMode } from \"./modes/html.js\";\nimport { Internal } from \"./types.js\";\n/** Message of any caught value, for a log line. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n/**\n * Matrix Application Service adapter.\n *\n * Identity is the configured virtual user (`@<id>:<host>`), registered or logged in on connect; the inbound route is\n * the Application Service API below `path`; the room cache is filled by the one-shot full-state sync.\n */\nexport class MatrixBot extends Adapter {\n /** The adapter needs the Satori service and the isolated `http` service. */\n static inject = ['satori', 'http'];\n /** The Loader applies this schema to a profile row's `config` before the constructor runs. */\n static Config = Config;\n modes = { html: createHtmlMode() };\n modeOrder = ['html'];\n /** Homeserver root plus `/_matrix`, without a trailing slash. */\n endpoint;\n /** Client-Server transport shared by `Internal` and the adapter's own calls. */\n request;\n /** The same client under the name the migrated upstream `Internal` uses (`bot.http`). */\n http;\n /** Full typed Client-Server / Application Service surface (the migrated upstream client). */\n internal;\n /** Names, members, summaries, direct markers and encryption markers per room. */\n rooms = new RoomCache();\n /** Random process base of transaction ids, so a restart cannot collide with an old id. */\n txnBase = Math.round(Math.random() * 1_000);\n /** Monotonic transaction id counter. */\n txnCounter = 0;\n appService;\n /** Whether an invitation of the bot itself is joined automatically. */\n get autoJoin() {\n return this.config.autoJoin;\n }\n constructor(ctx, config) {\n const invalid = configError(config);\n if (invalid !== undefined)\n throw invalid;\n const selfId = matrixUserId(config);\n super(ctx, config, {\n id: `matrix:${selfId}`,\n platform: 'matrix',\n adapter: 'matrix',\n });\n this.selfId = selfId;\n this.user = { id: selfId, name: config.name ?? config.id, isBot: true };\n this.endpoint = `${config.endpoint}/_matrix`;\n this.request = new MatrixClient(ctx, this.endpoint);\n this.http = this.request;\n this.internal = new Internal(this);\n this.defineInternalRoute('/media', (request) => this.serveMedia(request));\n }\n async connect() {\n try {\n await establishIdentity(this);\n await this.refreshRooms();\n const appService = new MatrixAppService(this);\n await appService.start();\n this.appService = appService;\n this.online();\n }\n catch (error) {\n // `Bot.start` only stores a connect failure on `bot.error`; the log line names the failure for the operator.\n this.ctx.logger.error('matrix: connect failed: %s', messageOf(error));\n await this.appService?.stop();\n this.appService = undefined;\n throw error;\n }\n }\n async disconnect() {\n const appService = this.appService;\n this.appService = undefined;\n await appService?.stop();\n }\n async upload(ref, _scope, ctx) {\n return await this.withApi(() => uploadResource(this.request, ref, ctx));\n }\n resourceScope(_target, _kind) {\n // An uploaded media item belongs to the bot user and is valid in every room it sends to.\n return this.id;\n }\n async sendPayload(payload, target, ctx) {\n try {\n return await this.withApi(() => sendPayload(this.sendDeps(), payload, target, ctx));\n }\n catch (error) {\n // The upload already succeeded; a later failure leaves the media in the repository with no event referencing it.\n const value = payload;\n if (value.kind === 'media') {\n this.ctx.logger.warn('matrix: a send attempt for uploaded media %s failed: %s', value.url, messageOf(error));\n }\n throw error;\n }\n }\n idempotentSend(target, ctx) {\n return idempotentSend(target, ctx);\n }\n async deletePart(part, handle) {\n await this.withApi(() => deletePart(this.sendDeps(), part, handle));\n }\n async createReaction(message, emoji) {\n await this.withApi(() => createReaction(this.sendDeps(), message, emoji));\n }\n async members(chat, cursor, limit) {\n return await this.withApi(() => members(this.sendDeps(), chat, cursor, limit));\n }\n async getMessage(chat, id) {\n return await this.withApi(() => getMessage(this.sendDeps(), chat, id));\n }\n classify(error) {\n return classifyMatrixError(error);\n }\n /** Decode one Application Service event into the session the transport publishes. */\n async decode(event) {\n return await decodeEvent(this, event);\n }\n /** Debug log of one dropped inbound event. */\n log(message) {\n this.ctx.logger.debug(message);\n }\n /** Warning log of an unreadable room or a failed state refresh. */\n warn(message) {\n this.ctx.logger.warn(message);\n }\n /** Join one room without refreshing; the self-join event triggers the refresh. */\n async joinRoom(roomId) {\n await this.internal.joinRoom(roomId);\n }\n /**\n * Run the one-shot full-state sync and apply it, joining the rooms the bot was invited into when `autoJoin` is on.\n *\n * The sync's timeline is history the host store already owns, so it is only read for state. A successful join runs\n * the same query once more, which is what puts the new room's name, members and summary in the cache.\n */\n async refreshRooms() {\n const invites = await enumerateRooms(this.internal, this.rooms, this.selfId);\n if (invites.length === 0)\n return;\n if (!this.config.autoJoin) {\n for (const roomId of invites)\n this.ctx.logger.info(`matrix: invited to ${roomId}; autoJoin is off, so it is not joined`);\n return;\n }\n let joined = false;\n for (const roomId of invites) {\n try {\n await this.internal.joinRoom(roomId);\n joined = true;\n }\n catch (error) {\n // The invitation stays in force, so a later connect retries it; one unjoinable room must not fail the rest.\n this.ctx.logger.warn(`matrix: could not join invited room ${roomId}: ${messageOf(error)}`);\n }\n }\n if (joined)\n await enumerateRooms(this.internal, this.rooms, this.selfId);\n }\n /**\n * Take the bot offline when a Client-Server call reports that its token is gone.\n * @param error - the caught failure of an outbound call or an inbound event handler.\n */\n noteRuntimeError(error) {\n if (!isTokenFailure(error))\n return;\n this.ctx.logger.error('matrix: the user access token was rejected (%s); replace the registration credentials and restart', messageOf(error));\n this.offline(error);\n }\n /** Adapt one authenticated media download into the host's response. */\n async serveMedia(request) {\n const value = request.query.get('mxc');\n if (value === null)\n return new Response(null, { status: 400 });\n const parsed = parseMxc(value.startsWith('mxc://') ? value : `mxc://${value}`);\n if (parsed === undefined)\n return new Response(null, { status: 400 });\n try {\n return mediaResponse(await this.request.download(parsed.serverName, parsed.mediaId));\n }\n catch (error) {\n this.noteRuntimeError(error);\n this.ctx.logger.warn('matrix: media %s/%s could not be served: %s', parsed.serverName, parsed.mediaId, messageOf(error));\n return new Response(null, { status: 502 });\n }\n }\n /** Run one outbound call, marking the bot offline when the failure is a dead token. */\n async withApi(run) {\n try {\n return await run();\n }\n catch (error) {\n this.noteRuntimeError(error);\n throw error;\n }\n }\n sendDeps() {\n return {\n client: this.request,\n selfId: this.selfId,\n nextTxn: () => this.txnBase + this.txnCounter++,\n rooms: this.rooms,\n isBot: (userId) => this.ctx.bots.some((bot) => bot.platform === 'matrix' && bot.selfId === userId),\n decode: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AI,CAAC;EAC7C;CACJ;;CAEA,MAAM,QAAQ,KAAK;EACf,IAAI;GACA,OAAO,MAAM,IAAI;EACrB,SACO,OAAO;GACV,KAAK,iBAAiB,KAAK;GAC3B,MAAM;EACV;CACJ;CACA,WAAW;EACP,OAAO;GACH,QAAQ,KAAK;GACb,QAAQ,KAAK;GACb,eAAe,KAAK,UAAU,KAAK;GACnC,OAAO,KAAK;GACZ,QAAQ,WAAW,KAAK,IAAI,KAAK,MAAM,QAAQ,IAAI,aAAa,YAAY,IAAI,WAAW,MAAM;GACjG,SAAS,MAAM,UAAU,cAAc,MAAM,OAAO,IAAI;EAC5D;CACJ;AACJ"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Application Service inbound transport.
|
|
3
|
+
*
|
|
4
|
+
* The profile's `webServer` owns the listener, so this transport registers one anonymous prefix route at the configured
|
|
5
|
+
* path and implements the Application Service API under it: transaction pushes (current and legacy path forms), the
|
|
6
|
+
* `users` query, the `rooms` query (always unknown) and the v1.7 `ping`. Every request is authenticated by `hs_token`,
|
|
7
|
+
* with the legacy `?access_token=` form accepted and refused when it contradicts a Bearer header.
|
|
8
|
+
*
|
|
9
|
+
* A transaction is confirmed only after every event reached intake: a failed event answers `500`, so the homeserver
|
|
10
|
+
* redelivers the batch with the same transaction id and the host's event-id deduplication removes the copies it already
|
|
11
|
+
* stored. That is the opposite of the upstream adapter's confirm-first order, which loses an event whose store failed.
|
|
12
|
+
*/
|
|
13
|
+
import type { MatrixBot } from './bot.ts';
|
|
14
|
+
/** The Application Service transport of one bot. */
|
|
15
|
+
export declare class MatrixAppService {
|
|
16
|
+
private readonly bot;
|
|
17
|
+
private dispose;
|
|
18
|
+
constructor(bot: MatrixBot);
|
|
19
|
+
/** Register the prefix route; a profile without a web server fails with an actionable message. */
|
|
20
|
+
start(): Promise<void>;
|
|
21
|
+
/** Release the route. */
|
|
22
|
+
stop(): Promise<void>;
|
|
23
|
+
/** Log a fatal start failure before the caller throws it (`Bot.start` only stores a connect failure). */
|
|
24
|
+
private fail;
|
|
25
|
+
private handle;
|
|
26
|
+
/** Whether one request carries the registration's `hs_token` in exactly one consistent form. */
|
|
27
|
+
private authorized;
|
|
28
|
+
/** Read and process one transaction; the answer is `200 {}` only after every event reached intake. */
|
|
29
|
+
private transaction;
|
|
30
|
+
/** Answer the `users` query: only the AS virtual user exists. */
|
|
31
|
+
private users;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=as.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"as.d.ts","sourceRoot":"","sources":["../../src/as.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AAuGzC,oDAAoD;AACpD,qBAAa,gBAAgB;IAGf,OAAO,CAAC,QAAQ,CAAC,GAAG;IAFhC,OAAO,CAAC,OAAO,CAA0B;gBAEZ,GAAG,EAAE,SAAS;IAE3C,kGAAkG;IAC5F,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgB5B,yBAAyB;IACnB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAK3B,yGAAyG;IACzG,OAAO,CAAC,IAAI;YAKE,MAAM;IAgEpB,gGAAgG;IAChG,OAAO,CAAC,UAAU;IAalB,sGAAsG;YACxF,WAAW;IA8CzB,iEAAiE;IACjE,OAAO,CAAC,KAAK;CAad"}
|