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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +14 -0
  3. package/lib/index.js +2401 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/as.d.ts +33 -0
  6. package/lib/types/as.d.ts.map +1 -0
  7. package/lib/types/as.js +237 -0
  8. package/lib/types/as.js.map +1 -0
  9. package/lib/types/bot.d.ts +109 -0
  10. package/lib/types/bot.d.ts.map +1 -0
  11. package/lib/types/bot.js +234 -0
  12. package/lib/types/bot.js.map +1 -0
  13. package/lib/types/config.d.ts +59 -0
  14. package/lib/types/config.d.ts.map +1 -0
  15. package/lib/types/config.js +67 -0
  16. package/lib/types/config.js.map +1 -0
  17. package/lib/types/decode.d.ts +56 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +298 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +45 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +120 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/html.d.ts +44 -0
  26. package/lib/types/html.d.ts.map +1 -0
  27. package/lib/types/html.js +286 -0
  28. package/lib/types/html.js.map +1 -0
  29. package/lib/types/identity.d.ts +20 -0
  30. package/lib/types/identity.d.ts.map +1 -0
  31. package/lib/types/identity.js +136 -0
  32. package/lib/types/identity.js.map +1 -0
  33. package/lib/types/index.d.ts +5 -0
  34. package/lib/types/index.d.ts.map +1 -0
  35. package/lib/types/index.js +5 -0
  36. package/lib/types/index.js.map +1 -0
  37. package/lib/types/media.d.ts +54 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +94 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/mentions.d.ts +58 -0
  42. package/lib/types/mentions.d.ts.map +1 -0
  43. package/lib/types/mentions.js +94 -0
  44. package/lib/types/mentions.js.map +1 -0
  45. package/lib/types/modes/html.d.ts +13 -0
  46. package/lib/types/modes/html.d.ts.map +1 -0
  47. package/lib/types/modes/html.js +242 -0
  48. package/lib/types/modes/html.js.map +1 -0
  49. package/lib/types/modes/shared.d.ts +164 -0
  50. package/lib/types/modes/shared.d.ts.map +1 -0
  51. package/lib/types/modes/shared.js +312 -0
  52. package/lib/types/modes/shared.js.map +1 -0
  53. package/lib/types/request.d.ts +82 -0
  54. package/lib/types/request.d.ts.map +1 -0
  55. package/lib/types/request.js +206 -0
  56. package/lib/types/request.js.map +1 -0
  57. package/lib/types/rooms.d.ts +83 -0
  58. package/lib/types/rooms.d.ts.map +1 -0
  59. package/lib/types/rooms.js +177 -0
  60. package/lib/types/rooms.js.map +1 -0
  61. package/lib/types/send.d.ts +76 -0
  62. package/lib/types/send.d.ts.map +1 -0
  63. package/lib/types/send.js +172 -0
  64. package/lib/types/send.js.map +1 -0
  65. package/lib/types/types.d.ts +418 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +134 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/package.json +65 -3
  70. package/src/as.ts +293 -0
  71. package/src/bot.ts +338 -0
  72. package/src/config.ts +100 -0
  73. package/src/decode.ts +392 -0
  74. package/src/errors.ts +149 -0
  75. package/src/html.ts +325 -0
  76. package/src/identity.ts +165 -0
  77. package/src/index.ts +14 -0
  78. package/src/media.ts +132 -0
  79. package/src/mentions.ts +134 -0
  80. package/src/modes/html.ts +346 -0
  81. package/src/modes/shared.ts +485 -0
  82. package/src/request.ts +295 -0
  83. package/src/rooms.ts +232 -0
  84. package/src/send.ts +275 -0
  85. package/src/types.ts +633 -0
  86. package/README.md +0 -3
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Mentions in both directions.
3
+ *
4
+ * Inbound, `m.mentions` is authoritative for `self`/`all`, because guessing from a display name is what the
5
+ * specification warns against; a `matrix.to` link decoded into an `at` element covers older clients that did not write
6
+ * the field, and a bare `@room` in the body covers the pre-v1.7 room mention. Outbound, `at` elements collect into
7
+ * `m.mentions` (one object per draft, always present) and render as `matrix.to` links.
8
+ */
9
+
10
+ import type { Element, UserRef } from '@deepseek-ai/cordis-plugin-im-core'
11
+
12
+ /** The `m.mentions` content object (always written, empty when nothing is mentioned). */
13
+ export interface MatrixMentionWire {
14
+ user_ids?: string[]
15
+ room?: boolean
16
+ }
17
+
18
+ /** The `m.mentions` field as an event carries it. */
19
+ export interface MatrixMentionContent {
20
+ user_ids?: string[]
21
+ room?: boolean
22
+ }
23
+
24
+ /** Decoded mention facts of one inbound event. */
25
+ export interface MatrixMentions {
26
+ self: boolean
27
+ all: boolean
28
+ users: UserRef[]
29
+ }
30
+
31
+ /** Mutable collection used while assembling one draft. */
32
+ export interface MentionSet {
33
+ readonly users: string[]
34
+ room: boolean
35
+ }
36
+
37
+ /** One mention a mode handler found while rendering. */
38
+ export interface MentionNode {
39
+ user?: string
40
+ room?: boolean
41
+ }
42
+
43
+ /** A new empty collection. */
44
+ export function createMentionSet(): MentionSet {
45
+ return { users: [], room: false }
46
+ }
47
+
48
+ /**
49
+ * Add one handler's mention to a draft's collection.
50
+ * @param set - the draft's collection.
51
+ * @param mention - the mention; a user id or a room mention.
52
+ */
53
+ export function addMention(
54
+ set: MentionSet,
55
+ mention: MentionNode | undefined,
56
+ ): void {
57
+ if (mention === undefined) return
58
+ if (mention.user !== undefined && !set.users.includes(mention.user))
59
+ set.users.push(mention.user)
60
+ if (mention.room === true) set.room = true
61
+ }
62
+
63
+ /** The wire object of one collection; `{}` when it mentions nobody. */
64
+ export function mentionWire(set: MentionSet): MatrixMentionWire {
65
+ return {
66
+ ...(set.users.length === 0 ? {} : { user_ids: [...set.users] }),
67
+ ...(set.room ? { room: true } : {}),
68
+ }
69
+ }
70
+
71
+ /** Whether the plain body carries the old standalone `@room` form. */
72
+ function bodyMentionsRoom(body: string | undefined): boolean {
73
+ if (body === undefined) return false
74
+ return /(^|\s)@room(?=\s|$)/.test(body)
75
+ }
76
+
77
+ /** Every `at[type=user]` of a decoded tree, in document order. */
78
+ function atElements(elements: readonly Element[]): Element<'at'>[] {
79
+ const out: Element<'at'>[] = []
80
+ const walk = (nodes: readonly Element[]) => {
81
+ for (const node of nodes) {
82
+ if (node.type === 'at') {
83
+ if (node.attrs.type === 'user') out.push(node)
84
+ continue
85
+ }
86
+ walk(node.children)
87
+ }
88
+ }
89
+ walk(elements)
90
+ return out
91
+ }
92
+
93
+ /**
94
+ * Decode the mention facts of one inbound event.
95
+ *
96
+ * @param content - the event content, whose `m.mentions` is authoritative when present.
97
+ * @param body - the plain body, for the legacy `@room` form.
98
+ * @param elements - the decoded content tree, for `matrix.to` links and mention labels.
99
+ * @param selfId - the bot's Matrix user id.
100
+ * @returns `self`/`all` flags and the users the message mentions.
101
+ */
102
+ export function decodeMentions(
103
+ content: { 'm.mentions'?: MatrixMentionContent },
104
+ body: string | undefined,
105
+ elements: readonly Element[],
106
+ selfId: string,
107
+ ): MatrixMentions {
108
+ const declared = content['m.mentions']
109
+ const declaredIds = Array.isArray(declared?.user_ids)
110
+ ? declared.user_ids.filter((id): id is string => typeof id === 'string')
111
+ : []
112
+ const users: UserRef[] = []
113
+ const seen = new Set<string>()
114
+ for (const element of atElements(elements)) {
115
+ const id = element.attrs.id
116
+ if (id === undefined || seen.has(id)) continue
117
+ seen.add(id)
118
+ users.push({
119
+ id,
120
+ ...(element.attrs.name === undefined ? {} : { name: element.attrs.name }),
121
+ })
122
+ }
123
+ for (const id of declaredIds) {
124
+ if (seen.has(id)) continue
125
+ seen.add(id)
126
+ users.push({ id })
127
+ }
128
+ const selfByElement = users.some((user) => user.id === selfId)
129
+ return {
130
+ self: selfId !== '' && (declaredIds.includes(selfId) || selfByElement),
131
+ all: declared?.room === true || bodyMentionsRoom(body),
132
+ users,
133
+ }
134
+ }
@@ -0,0 +1,346 @@
1
+ /**
2
+ * `html` mode: Matrix's `org.matrix.custom.html` rich text, with the plain `body` produced from the same traversal.
3
+ *
4
+ * Native tags are the specification's allowed subset (`b`/`i`/`u`/`s`/`del`/`code`/`pre`/`a`/`p`/`blockquote`/lists/
5
+ * headings/table/details/spoiler); everything else takes the core fallback and is reported as degraded. A user mention
6
+ * renders as a `matrix.to` link and collects into `m.mentions`; `@room` is the room mention. Media never stays inline:
7
+ * each media element becomes its own event and is reported as moved when it stood in phrasing content.
8
+ */
9
+
10
+ import { ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type { Mode, RenderContext } from '@deepseek-ai/cordis-plugin-im-core'
12
+ import type { Element } from '@deepseek-ai/satori-element'
13
+ import { addMention, createMentionSet } from '../mentions.ts'
14
+ import {
15
+ assembleDrafts,
16
+ escapeAttribute,
17
+ escapeHtml,
18
+ htmlNode,
19
+ inlineRun,
20
+ inlineWrapper,
21
+ mediaNode,
22
+ mentionNodes,
23
+ serializeDraft,
24
+ } from './shared.ts'
25
+ import type { MatrixModeTypes, MatrixNode } from './shared.ts'
26
+
27
+ /** The `matrix.to` prefix of a room or user link. */
28
+ const MATRIX_LINK = 'https://matrix.to/#/'
29
+
30
+ /** Wrap the inline text of `children` in one tag, letting media of the subtree follow it. */
31
+ function wrap(
32
+ tag: string,
33
+ ctx: RenderContext<MatrixModeTypes>,
34
+ children: readonly Element[],
35
+ textSuffix = '',
36
+ ): MatrixNode[] {
37
+ return inlineWrapper(tag, ctx.render(children), textSuffix)
38
+ }
39
+
40
+ /** Prefix every line of a blockquote text projection with `> `. */
41
+ function quoteText(text: string): string {
42
+ const body = text.replace(/\n+$/, '')
43
+ if (body === '') return '\n\n'
44
+ return `${body
45
+ .split('\n')
46
+ .map((line) => `> ${line}`)
47
+ .join('\n')}\n\n`
48
+ }
49
+
50
+ /** The text of one table cell, with block children separated by a space. */
51
+ function cellText(ctx: RenderContext<MatrixModeTypes>, cell: Element): string {
52
+ return cell.children
53
+ .map((child) => ctx.text([child]))
54
+ .filter((part) => part.trim() !== '')
55
+ .join(' ')
56
+ .replace(/\s+/g, ' ')
57
+ .trim()
58
+ }
59
+
60
+ /** The `- ` / `1. ` marker of one list item, plus its task-list box. */
61
+ function listMarker(
62
+ el: Element<'li'>,
63
+ ctx: RenderContext<MatrixModeTypes>,
64
+ ): string {
65
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
66
+ let marker = '- '
67
+ if (parent?.type === 'ol') {
68
+ const start =
69
+ typeof parent.attrs.start === 'number' ? parent.attrs.start : 1
70
+ const index = parent.children.indexOf(el)
71
+ marker = `${start + Math.max(0, index)}. `
72
+ }
73
+ if (el.attrs.checked === true) marker += '[x] '
74
+ else if (el.attrs.checked === false) marker += '[ ] '
75
+ return marker
76
+ }
77
+
78
+ /** Build the `html` mode. */
79
+ export function createHtmlMode(): Mode<MatrixModeTypes> {
80
+ const elements = new ElementRegistry<MatrixModeTypes>()
81
+ .register('text', (el) =>
82
+ htmlNode(escapeHtml(el.attrs.content), el.attrs.content),
83
+ )
84
+ .register('br', () => htmlNode('<br/>', '\n'))
85
+ .register('p', (el, ctx) => wrap('p', ctx, el.children, '\n\n'))
86
+ .register('b', (el, ctx) => wrap('strong', ctx, el.children))
87
+ .register('i', (el, ctx) => wrap('em', ctx, el.children))
88
+ .register('u', (el, ctx) => wrap('u', ctx, el.children))
89
+ .register('s', (el, ctx) => wrap('del', ctx, el.children))
90
+ .register('spoiler', (el, ctx) => {
91
+ const run = inlineRun(ctx.render(el.children))
92
+ // The hidden text reaches `formatted_body` only: `body` must not repeat what the spoiler hides.
93
+ return [
94
+ htmlNode(
95
+ `<span data-mx-spoiler>${run.html}</span>`,
96
+ '[剧透]',
97
+ mentionNodes(run.mentions),
98
+ ),
99
+ ...run.rest,
100
+ ]
101
+ })
102
+ .register('code', (el, ctx) => {
103
+ const content = ctx.text(el.children)
104
+ return htmlNode(`<code>${escapeHtml(content)}</code>`, content)
105
+ })
106
+ .register(
107
+ 'pre',
108
+ (el, ctx) => {
109
+ const content = ctx.text(el.children)
110
+ const language = el.attrs.lang
111
+ const html =
112
+ language === undefined || language === ''
113
+ ? `<pre>${escapeHtml(content)}</pre>`
114
+ : `<pre><code class="language-${escapeAttribute(language)}">${escapeHtml(content)}</code></pre>`
115
+ return htmlNode(html, `${content}\n\n`)
116
+ },
117
+ { variants: ['lang'] },
118
+ )
119
+ .register('a', (el, ctx) => {
120
+ const run = inlineRun(ctx.render(el.children))
121
+ const href = el.attrs.href
122
+ const label = run.html === '' ? escapeHtml(href) : run.html
123
+ const plain = run.text === '' ? href : run.text
124
+ return [
125
+ htmlNode(
126
+ `<a href="${escapeAttribute(href)}">${label}</a>`,
127
+ plain === href ? href : `${plain} (${href})`,
128
+ mentionNodes(run.mentions),
129
+ ),
130
+ ...run.rest,
131
+ ]
132
+ })
133
+ .register(
134
+ 'at',
135
+ (el) => {
136
+ if (el.attrs.type === 'all')
137
+ return htmlNode('@room', '@room', [{ room: true }])
138
+ if (el.attrs.type === 'user' && el.attrs.id !== undefined) {
139
+ const id = el.attrs.id
140
+ const label = escapeHtml(el.attrs.name ?? id)
141
+ return htmlNode(
142
+ `<a href="${MATRIX_LINK}${escapeAttribute(id)}">${label}</a>`,
143
+ el.attrs.name ?? id,
144
+ [{ user: id }],
145
+ )
146
+ }
147
+ return htmlNode(
148
+ escapeHtml(el.attrs.name ?? el.attrs.id ?? el.attrs.type),
149
+ el.attrs.name ?? el.attrs.id ?? '',
150
+ )
151
+ },
152
+ { variants: ['user', 'all'] },
153
+ )
154
+ .register('channel', (el) => {
155
+ const id = el.attrs.id
156
+ const label = escapeHtml(el.attrs.name ?? id)
157
+ return htmlNode(
158
+ `<a href="${MATRIX_LINK}${escapeAttribute(id)}">${label}</a>`,
159
+ el.attrs.name ?? id,
160
+ )
161
+ })
162
+ .register('emoji', (el) => {
163
+ const label = `:${el.attrs.name ?? el.attrs.id}:`
164
+ return htmlNode(escapeHtml(label), label)
165
+ })
166
+ .register('h1', (el, ctx) => wrap('h1', ctx, el.children, '\n\n'))
167
+ .register('h2', (el, ctx) => wrap('h2', ctx, el.children, '\n\n'))
168
+ .register('h3', (el, ctx) => wrap('h3', ctx, el.children, '\n\n'))
169
+ .register('h4', (el, ctx) => wrap('h4', ctx, el.children, '\n\n'))
170
+ .register('h5', (el, ctx) => wrap('h5', ctx, el.children, '\n\n'))
171
+ .register('h6', (el, ctx) => wrap('h6', ctx, el.children, '\n\n'))
172
+ .register('blockquote', (el, ctx) => {
173
+ const run = inlineRun(ctx.render(el.children))
174
+ return [
175
+ htmlNode(
176
+ `<blockquote>${run.html}</blockquote>`,
177
+ quoteText(run.text),
178
+ mentionNodes(run.mentions),
179
+ ),
180
+ ...run.rest,
181
+ ]
182
+ })
183
+ .register('ul', (el, ctx) => wrap('ul', ctx, el.children))
184
+ .register('ol', (el, ctx) => {
185
+ const run = inlineRun(ctx.render(el.children))
186
+ const start =
187
+ typeof el.attrs.start === 'number' ? ` start="${el.attrs.start}"` : ''
188
+ return [
189
+ htmlNode(
190
+ `<ol${start}>${run.html}</ol>`,
191
+ run.text,
192
+ mentionNodes(run.mentions),
193
+ ),
194
+ ...run.rest,
195
+ ]
196
+ })
197
+ .register(
198
+ 'li',
199
+ (el, ctx) => {
200
+ const run = inlineRun(ctx.render(el.children))
201
+ const box =
202
+ el.attrs.checked === true
203
+ ? '[x] '
204
+ : el.attrs.checked === false
205
+ ? '[ ] '
206
+ : ''
207
+ return [
208
+ htmlNode(
209
+ `<li>${box}${run.html}</li>`,
210
+ `${listMarker(el, ctx)}${run.text}\n`,
211
+ mentionNodes(run.mentions),
212
+ ),
213
+ ...run.rest,
214
+ ]
215
+ },
216
+ { variants: ['checked', 'nested'] },
217
+ )
218
+ .register('hr', () => htmlNode('<hr/>', '\n---\n'))
219
+ .register(
220
+ 'table',
221
+ (el, ctx) => {
222
+ const rows = el.children.filter(
223
+ (child): child is Element<'tr'> => child.type === 'tr',
224
+ )
225
+ const first = rows[0]
226
+ const header =
227
+ first !== undefined &&
228
+ first.children.length > 0 &&
229
+ first.children.every((cell) => cell.type === 'th')
230
+ ? first
231
+ : undefined
232
+ const bodyRows = header === undefined ? rows : rows.slice(1)
233
+ const renderedRow = (row: Element<'tr'>) => inlineRun(ctx.render([row]))
234
+ const headerRun = header === undefined ? undefined : renderedRow(header)
235
+ const bodyRuns = bodyRows.map(renderedRow)
236
+ const html = [
237
+ '<table>',
238
+ headerRun === undefined ? '' : `<thead>${headerRun.html}</thead>`,
239
+ `<tbody>${bodyRuns.map((run) => run.html).join('')}</tbody>`,
240
+ '</table>',
241
+ ].join('')
242
+ const headerCells =
243
+ header === undefined
244
+ ? []
245
+ : header.children
246
+ .filter((cell) => cell.type === 'th' || cell.type === 'td')
247
+ .map((cell) => cellText(ctx, cell))
248
+ const lines = bodyRows.map((row) =>
249
+ row.children
250
+ .filter((cell) => cell.type === 'th' || cell.type === 'td')
251
+ .map((cell, index) => {
252
+ const value = cellText(ctx, cell)
253
+ const head = headerCells[index]
254
+ return head === undefined || head === ''
255
+ ? value
256
+ : `${head}: ${value}`
257
+ })
258
+ .join(' | '),
259
+ )
260
+ const mentions = createMentionSet()
261
+ for (const run of [headerRun, ...bodyRuns]) {
262
+ if (run === undefined) continue
263
+ for (const mention of mentionNodes(run.mentions))
264
+ addMention(mentions, mention)
265
+ }
266
+ const text = lines.join('\n')
267
+ return [
268
+ htmlNode(
269
+ html,
270
+ text === '' ? '' : `${text}\n`,
271
+ mentionNodes(mentions),
272
+ ),
273
+ ...(headerRun?.rest ?? []),
274
+ ...bodyRuns.flatMap((run) => run.rest),
275
+ ]
276
+ },
277
+ { variants: ['align'] },
278
+ )
279
+ .register('tr', (el, ctx) => {
280
+ const run = inlineRun(ctx.render(el.children))
281
+ return [
282
+ htmlNode(`<tr>${run.html}</tr>`, run.text, mentionNodes(run.mentions)),
283
+ ...run.rest,
284
+ ]
285
+ })
286
+ .register('th', (el, ctx) => {
287
+ const run = inlineRun(ctx.render(el.children))
288
+ const align =
289
+ el.attrs.align === undefined
290
+ ? ''
291
+ : ` align="${escapeAttribute(el.attrs.align)}"`
292
+ return [
293
+ htmlNode(
294
+ `<th${align}>${run.html}</th>`,
295
+ run.text,
296
+ mentionNodes(run.mentions),
297
+ ),
298
+ ...run.rest,
299
+ ]
300
+ })
301
+ .register(
302
+ 'td',
303
+ (el, ctx) => {
304
+ const run = inlineRun(ctx.render(el.children))
305
+ const align =
306
+ el.attrs.align === undefined
307
+ ? ''
308
+ : ` align="${escapeAttribute(el.attrs.align)}"`
309
+ return [
310
+ htmlNode(
311
+ `<td${align}>${run.html}</td>`,
312
+ run.text,
313
+ mentionNodes(run.mentions),
314
+ ),
315
+ ...run.rest,
316
+ ]
317
+ },
318
+ { variants: ['block'] },
319
+ )
320
+ .register('details', (el, ctx) => {
321
+ const run = inlineRun(ctx.render(el.children))
322
+ const open = el.attrs.open === true ? ' open' : ''
323
+ return [
324
+ htmlNode(
325
+ `<details${open}>${run.html}</details>`,
326
+ `▸ ${run.text}`,
327
+ mentionNodes(run.mentions),
328
+ ),
329
+ ...run.rest,
330
+ ]
331
+ })
332
+ .register('summary', (el, ctx) => wrap('summary', ctx, el.children, '\n'))
333
+ .register('small', (el, ctx) => ctx.render(el.children))
334
+ .register('img', (el, ctx) => mediaNode(el, ctx), { variants: ['inline'] })
335
+ .register('audio', (el, ctx) => mediaNode(el, ctx))
336
+ .register('video', (el, ctx) => mediaNode(el, ctx))
337
+ .register('file', (el, ctx) => mediaNode(el, ctx))
338
+
339
+ return {
340
+ id: 'html',
341
+ elements,
342
+ limits: {},
343
+ assemble: (nodes) => assembleDrafts(nodes),
344
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx),
345
+ }
346
+ }