@im-more/dsh-kook 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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +12 -0
  3. package/lib/index.js +2380 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +53 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +138 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +46 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +52 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +88 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +564 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +46 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +159 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +17 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +24 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +15 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +15 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/kmarkdown.d.ts +76 -0
  30. package/lib/types/kmarkdown.d.ts.map +1 -0
  31. package/lib/types/kmarkdown.js +201 -0
  32. package/lib/types/kmarkdown.js.map +1 -0
  33. package/lib/types/modes/kmarkdown.d.ts +17 -0
  34. package/lib/types/modes/kmarkdown.d.ts.map +1 -0
  35. package/lib/types/modes/kmarkdown.js +166 -0
  36. package/lib/types/modes/kmarkdown.js.map +1 -0
  37. package/lib/types/modes/shared.d.ts +192 -0
  38. package/lib/types/modes/shared.d.ts.map +1 -0
  39. package/lib/types/modes/shared.js +371 -0
  40. package/lib/types/modes/shared.js.map +1 -0
  41. package/lib/types/request.d.ts +53 -0
  42. package/lib/types/request.d.ts.map +1 -0
  43. package/lib/types/request.js +147 -0
  44. package/lib/types/request.js.map +1 -0
  45. package/lib/types/send.d.ts +57 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +141 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/types.d.ts +807 -0
  50. package/lib/types/types.d.ts.map +1 -0
  51. package/lib/types/types.js +168 -0
  52. package/lib/types/types.js.map +1 -0
  53. package/lib/types/webhook.d.ts +35 -0
  54. package/lib/types/webhook.d.ts.map +1 -0
  55. package/lib/types/webhook.js +132 -0
  56. package/lib/types/webhook.js.map +1 -0
  57. package/lib/types/ws.d.ts +54 -0
  58. package/lib/types/ws.d.ts.map +1 -0
  59. package/lib/types/ws.js +358 -0
  60. package/lib/types/ws.js.map +1 -0
  61. package/package.json +61 -3
  62. package/src/bot.ts +217 -0
  63. package/src/config.ts +84 -0
  64. package/src/decode.ts +660 -0
  65. package/src/errors.ts +188 -0
  66. package/src/identity.ts +32 -0
  67. package/src/index.ts +80 -0
  68. package/src/kmarkdown.ts +246 -0
  69. package/src/modes/kmarkdown.ts +204 -0
  70. package/src/modes/shared.ts +498 -0
  71. package/src/request.ts +196 -0
  72. package/src/send.ts +216 -0
  73. package/src/types.ts +764 -0
  74. package/src/webhook.ts +170 -0
  75. package/src/ws.ts +431 -0
  76. package/README.md +0 -3
@@ -0,0 +1,204 @@
1
+ /**
2
+ * The single `kmarkdown` mode: KOOK message text with its KMarkdown markup, and a card when the content needs one.
3
+ *
4
+ * Native tags are the ones the upstream encoder renders (`text`, `p`, `br`, `b`, `i`, `u`, `s`, `spoiler`, `code`,
5
+ * `a`, `at`, `channel`, `emoji`) plus the block structure KMarkdown shows as text (headings, lists, quotes, fences, a
6
+ * divider) and the media and buttons that only a card module can carry. A `<button type="input">` is not declared: a
7
+ * click that sends a text as the reader has no card component, so the core fallback renders its label and command.
8
+ * Everything else takes the core fallback, which keeps its text — the platform has no second way to render it.
9
+ */
10
+
11
+ import { defineMode, ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core'
12
+ import type { Mode, RenderContext } from '@deepseek-ai/cordis-plugin-im-core'
13
+ import { isPhrasingContainer } from '@deepseek-ai/satori-element'
14
+ import type { Element } from '@deepseek-ai/satori-element'
15
+ import { escapeKMarkdown } from '../kmarkdown.ts'
16
+ import {
17
+ assembleDraft,
18
+ BREAK,
19
+ chunk,
20
+ KOOK_LIMITS,
21
+ mediaNode,
22
+ quoteLines,
23
+ serializeDraft,
24
+ textNode,
25
+ textOf,
26
+ themeOf,
27
+ withMark,
28
+ } from './shared.ts'
29
+ import type { KookButtonNode, KookModeTypes, KookNode } from './shared.ts'
30
+
31
+ /** Drop the paragraph breaks a container put in front of its content, so a list marker is not followed by a newline. */
32
+ function withoutLeadingBreaks(nodes: readonly KookNode[]): KookNode[] {
33
+ let start = 0
34
+ while (start < nodes.length && nodes[start]!.type === 'break') start += 1
35
+ return nodes.slice(start)
36
+ }
37
+
38
+ /** The nodes of a render without its text runs, for a construct that carries the text in its own markup. */
39
+ function nonText(nodes: readonly KookNode[]): KookNode[] {
40
+ return nodes.filter((node) => node.type !== 'text')
41
+ }
42
+
43
+ /** A heading: KMarkdown has no heading syntax, so a bold line stands in. */
44
+ function heading(nodes: readonly KookNode[]): KookNode[] {
45
+ return [BREAK, ...withMark(nodes, '**'), BREAK]
46
+ }
47
+
48
+ /** The action button of one `<button>` element. */
49
+ function actionButton(
50
+ el: Element<'button'>,
51
+ ctx: RenderContext<KookModeTypes>,
52
+ ): KookButtonNode {
53
+ const label = textOf(ctx.render(el.children)).trim()
54
+ if (el.attrs.type === 'link') {
55
+ return {
56
+ click: 'link',
57
+ value: el.attrs.href,
58
+ text: label === '' ? escapeKMarkdown(el.attrs.href) : label,
59
+ theme: themeOf(el.attrs.theme),
60
+ }
61
+ }
62
+ // `action` and `submit` both report their id back; the input variant never reaches a handler (not declared).
63
+ const id = el.attrs.type === 'input' ? '' : el.attrs.id
64
+ return {
65
+ click: 'return-val',
66
+ value: id,
67
+ text: label === '' ? escapeKMarkdown(id) : label,
68
+ theme: themeOf(el.attrs.theme),
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Build the `kmarkdown` mode.
74
+ * @returns the only mode of this adapter.
75
+ */
76
+ export function createKmarkdownMode(): Mode<KookModeTypes> {
77
+ const elements = new ElementRegistry<KookModeTypes>()
78
+ .register('text', (el) => textNode(escapeKMarkdown(el.attrs.content)))
79
+ .register('p', (el, ctx) => [BREAK, ...ctx.render(el.children), BREAK])
80
+ .register('br', () => textNode('\n'))
81
+ .register('b', (el, ctx) => withMark(ctx.render(el.children), '**'))
82
+ .register('i', (el, ctx) => withMark(ctx.render(el.children), '*'))
83
+ .register('u', (el, ctx) => withMark(ctx.render(el.children), '(ins)'))
84
+ .register('s', (el, ctx) => withMark(ctx.render(el.children), '~~'))
85
+ .register('spoiler', (el, ctx) =>
86
+ withMark(ctx.render(el.children), '(spl)'),
87
+ )
88
+ .register('code', (el, ctx) => textNode(`\`${ctx.text(el.children)}\``))
89
+ .register(
90
+ 'pre',
91
+ (el, ctx) => {
92
+ const language = el.attrs.lang ?? ''
93
+ return textNode(`\`\`\`${language}\n${ctx.text(el.children)}\n\`\`\``)
94
+ },
95
+ { variants: ['lang'] },
96
+ )
97
+ .register('a', (el, ctx) => {
98
+ const children = ctx.render(el.children)
99
+ const label = textOf(children).trim()
100
+ return [
101
+ textNode(
102
+ `[${label === '' ? escapeKMarkdown(el.attrs.href) : label}](${el.attrs.href})`,
103
+ ),
104
+ ...nonText(children),
105
+ ]
106
+ })
107
+ .register(
108
+ 'at',
109
+ (el) => {
110
+ switch (el.attrs.type) {
111
+ case 'user':
112
+ return el.attrs.id === undefined
113
+ ? textNode(escapeKMarkdown(`@${el.attrs.name ?? ''}`))
114
+ : textNode(`(met)${el.attrs.id}(met)`)
115
+ case 'all':
116
+ return textNode('(met)all(met)')
117
+ case 'here':
118
+ return textNode('(met)here(met)')
119
+ case 'role':
120
+ return el.attrs.id === undefined
121
+ ? textNode(escapeKMarkdown(`@${el.attrs.name ?? ''}`))
122
+ : textNode(`(rol)${el.attrs.id}(rol)`)
123
+ }
124
+ },
125
+ { variants: ['user', 'all', 'here', 'role'] },
126
+ )
127
+ .register('channel', (el) => textNode(`(chn)${el.attrs.id}(chn)`))
128
+ .register('emoji', (el) => {
129
+ const name = el.attrs.name ?? ''
130
+ // `(emj)name(emj)[id]` names the guild emoji and falls back to its short code when the id is unknown.
131
+ return el.attrs.id === '' || name === ''
132
+ ? textNode(`:${name}:`)
133
+ : textNode(`(emj)${name}(emj)[${el.attrs.id}]`)
134
+ })
135
+ .register('h1', (el, ctx) => heading(ctx.render(el.children)))
136
+ .register('h2', (el, ctx) => heading(ctx.render(el.children)))
137
+ .register('h3', (el, ctx) => heading(ctx.render(el.children)))
138
+ .register('h4', (el, ctx) => heading(ctx.render(el.children)))
139
+ .register('h5', (el, ctx) => heading(ctx.render(el.children)))
140
+ .register('h6', (el, ctx) => heading(ctx.render(el.children)))
141
+ .register('ul', (el, ctx) => [BREAK, ...ctx.render(el.children), BREAK])
142
+ .register('ol', (el, ctx) => [BREAK, ...ctx.render(el.children), BREAK])
143
+ .register('li', (el, ctx) => {
144
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
145
+ if (parent?.type !== 'ol') {
146
+ return [
147
+ textNode('• '),
148
+ ...withoutLeadingBreaks(ctx.render(el.children)),
149
+ BREAK,
150
+ ]
151
+ }
152
+ const index = Math.max(parent.children.indexOf(el), 0)
153
+ const start = parent.attrs.start ?? 1
154
+ return [
155
+ textNode(`${start + index}. `),
156
+ ...withoutLeadingBreaks(ctx.render(el.children)),
157
+ BREAK,
158
+ ]
159
+ })
160
+ .register('blockquote', (el, ctx) => quoteLines(ctx.render(el.children)))
161
+ .register('hr', () => ({ type: 'divider' }))
162
+ .register('img', (el, ctx) => mediaNode(el, ctx), { variants: ['inline'] })
163
+ .register('audio', (el, ctx) => mediaNode(el, ctx))
164
+ .register('video', (el, ctx) => mediaNode(el, ctx))
165
+ .register('file', (el, ctx) => mediaNode(el, ctx))
166
+ // `input` is deliberately not declared: the core fallback keeps the label and command text and reports the
167
+ // dropped interaction.
168
+ .register(
169
+ 'button',
170
+ (el, ctx) => {
171
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
172
+ if (parent !== undefined && isPhrasingContainer(parent.type)) {
173
+ ctx.report.moved.push({
174
+ tag: 'button',
175
+ reason: 'kook-button-lifted',
176
+ path: ctx.stableId(el),
177
+ })
178
+ }
179
+ return { type: 'buttons', buttons: [actionButton(el, ctx)] }
180
+ },
181
+ { variants: ['action', 'link', 'submit', 'theme', 'inline'] },
182
+ )
183
+ .register('button-group', (el, ctx) => {
184
+ const buttons: KookButtonNode[] = []
185
+ for (const node of ctx.render(el.children)) {
186
+ if (node.type === 'buttons') buttons.push(...node.buttons)
187
+ }
188
+ return chunk(buttons, KOOK_LIMITS.buttonsPerRow).map((group) => ({
189
+ type: 'buttons' as const,
190
+ buttons: group,
191
+ }))
192
+ })
193
+
194
+ return defineMode<KookModeTypes>()({
195
+ id: 'kmarkdown',
196
+ elements,
197
+ limits: {
198
+ 'limit.text.chars': KOOK_LIMITS.textChars,
199
+ 'limit.buttons.row': KOOK_LIMITS.buttonsPerRow,
200
+ },
201
+ assemble: (nodes, _envelope, ctx) => assembleDraft(nodes, ctx),
202
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx),
203
+ })
204
+ }
@@ -0,0 +1,498 @@
1
+ /**
2
+ * Draft model of the single `kmarkdown` mode: the node stream, the text/card buffers, the documented card budgets, and
3
+ * the exact request body of one platform message.
4
+ *
5
+ * One logical message is either kmarkdown (`type: 9`) or card JSON (`type: 10`), exactly as the upstream encoder
6
+ * flushes: text alone stays a `type: 9` message, and the first element that needs a card module (media, a button, a
7
+ * divider) turns the whole message into a card.
8
+ */
9
+
10
+ import type {
11
+ ModeTypes,
12
+ Prepared,
13
+ RenderContext,
14
+ ResourceRef,
15
+ SerializeContext,
16
+ Theme,
17
+ } from '@deepseek-ai/cordis-plugin-im-core'
18
+ import { isPhrasingContainer } from '@deepseek-ai/satori-element'
19
+ import type { Element } from '@deepseek-ai/satori-element'
20
+ import type { Card } from '../types.ts'
21
+ import { inlineKMarkdown, splitKMarkdown } from '../kmarkdown.ts'
22
+
23
+ /** KOOK's documented bounds; nothing else is a limit. */
24
+ export const KOOK_LIMITS = {
25
+ /** `content` of one message ("请不要超过 8000 字符"). */
26
+ textChars: 8_000,
27
+ /** kmarkdown text of one section/context module. */
28
+ sectionChars: 5_000,
29
+ /** Modules of one card. */
30
+ cardModules: 50,
31
+ /** Buttons of one `action-group`. */
32
+ buttonsPerRow: 4,
33
+ /** Images of one `image-group`. */
34
+ imagesPerGroup: 9,
35
+ /** `page_size` of `/guild/user-list`. */
36
+ membersPageSize: 50,
37
+ } as const
38
+
39
+ /** Button colours the platform defines; `default` becomes `primary` as the upstream encoder chooses. */
40
+ export type KookTheme = 'primary' | 'info' | 'success' | 'warning' | 'danger'
41
+
42
+ /** One button collected from `<button>` (or a `<button-group>` child). */
43
+ export interface KookButtonNode {
44
+ /** `link` opens a URL, `return-val` reports the click with `value`. */
45
+ click: 'link' | 'return-val'
46
+ /** `value` of the wire button: the href for a link, the button id for a callback. */
47
+ value: string
48
+ /** KMarkdown label. */
49
+ text: string
50
+ theme: KookTheme
51
+ }
52
+
53
+ /** One node a mode handler produces. */
54
+ export type KookNode =
55
+ | { type: 'text'; text: string }
56
+ /** A paragraph boundary: at most one newline, and none at the start of a message. */
57
+ | { type: 'break' }
58
+ | { type: 'divider' }
59
+ | { type: 'image'; ref: ResourceRef }
60
+ | {
61
+ type: 'media'
62
+ kind: 'file' | 'audio' | 'video'
63
+ ref: ResourceRef
64
+ title: string
65
+ }
66
+ | { type: 'buttons'; buttons: KookButtonNode[] }
67
+
68
+ /** One image of a card module, before `prepare` resolves its source. */
69
+ export interface KookImageDraft {
70
+ ref: ResourceRef
71
+ }
72
+
73
+ /** One module of a card draft. */
74
+ export type KookModuleDraft =
75
+ | { type: 'section'; content: string }
76
+ | { type: 'container'; image: KookImageDraft }
77
+ | { type: 'image-group'; images: KookImageDraft[] }
78
+ | { type: 'buttons'; buttons: KookButtonNode[] }
79
+ | { type: 'divider' }
80
+ | {
81
+ type: 'media'
82
+ kind: 'file' | 'audio' | 'video'
83
+ ref: ResourceRef
84
+ title: string
85
+ }
86
+
87
+ /** One platform message before resource resolution. */
88
+ export type KookDraft =
89
+ | { kind: 'text'; content: string }
90
+ | { kind: 'card'; modules: KookModuleDraft[] }
91
+
92
+ /** Exact request data of one platform message. */
93
+ export type KookPayload =
94
+ | { kind: 'text'; type: 9; content: string; quote?: string }
95
+ | { kind: 'card'; type: 10; content: string; quote?: string }
96
+
97
+ /** Mode types of the `kmarkdown` mode. */
98
+ export interface KookModeTypes extends ModeTypes {
99
+ node: KookNode
100
+ draft: KookDraft
101
+ payload: KookPayload
102
+ }
103
+
104
+ /** A paragraph break node. */
105
+ export const BREAK: KookNode = { type: 'break' }
106
+
107
+ /**
108
+ * One text node holding already encoded kmarkdown.
109
+ * @param text - kmarkdown text.
110
+ * @returns the node.
111
+ */
112
+ export function textNode(text: string): KookNode {
113
+ return { type: 'text', text }
114
+ }
115
+
116
+ /**
117
+ * Group items into runs of at most `size`.
118
+ * @param items - the items, in order.
119
+ * @param size - maximum run length.
120
+ * @returns the runs, in order.
121
+ */
122
+ export function chunk<T>(items: readonly T[], size: number): T[][] {
123
+ const runs: T[][] = []
124
+ for (let start = 0; start < items.length; start += size) {
125
+ runs.push(items.slice(start, start + size))
126
+ }
127
+ return runs
128
+ }
129
+
130
+ /**
131
+ * The card `image-group` runs of an image list (1–9 images each; DSH has no album element yet, so only a future
132
+ * caller uses this).
133
+ * @param images - the images, in order.
134
+ * @returns the groups, in order.
135
+ */
136
+ export function groupImages(
137
+ images: readonly KookImageDraft[],
138
+ ): KookImageDraft[][] {
139
+ return chunk(images, KOOK_LIMITS.imagesPerGroup)
140
+ }
141
+
142
+ /**
143
+ * The platform colour of a button theme.
144
+ * @param theme - the element's theme, when it declared one.
145
+ * @returns the KOOK button colour.
146
+ */
147
+ export function themeOf(theme: Theme | undefined): KookTheme {
148
+ switch (theme) {
149
+ case 'info':
150
+ case 'success':
151
+ case 'warning':
152
+ case 'danger':
153
+ return theme
154
+ default:
155
+ return 'primary'
156
+ }
157
+ }
158
+
159
+ /** The name of an outbound attachment: the declared name, else the last path segment of the source. */
160
+ export function fileName(name: string | undefined, src: string): string {
161
+ if (name !== undefined && name !== '') return name
162
+ try {
163
+ const segment = new URL(src).pathname.split('/').pop()
164
+ if (segment !== undefined && segment !== '')
165
+ return decodeURIComponent(segment)
166
+ } catch (error) {
167
+ // Not a URL: the source itself is the best name available.
168
+ error
169
+ if (src !== '' && !src.includes('/')) return src
170
+ }
171
+ return 'file'
172
+ }
173
+
174
+ /** The kmarkdown text of a node list (a button label, a link label). */
175
+ export function textOf(nodes: readonly KookNode[]): string {
176
+ return inlineKMarkdown(
177
+ nodes.filter(
178
+ (node): node is { type: 'text'; text: string } => node.type === 'text',
179
+ ),
180
+ )
181
+ }
182
+
183
+ /**
184
+ * Wrap every text run of a node list with one kmarkdown construct.
185
+ *
186
+ * Each contiguous text run is wrapped on its own, so a media node between two runs never leaves a marker open across
187
+ * the card module boundary. Nested marks compose (`<b><i>x</i></b>` → `***x***`), as the upstream encoder emits.
188
+ *
189
+ * @param nodes - rendered children.
190
+ * @param open - opening marker.
191
+ * @param close - closing marker, `open` when symmetric.
192
+ * @returns the children with their text runs wrapped.
193
+ */
194
+ export function withMark(
195
+ nodes: readonly KookNode[],
196
+ open: string,
197
+ close = open,
198
+ ): KookNode[] {
199
+ const out: KookNode[] = []
200
+ let run: string[] = []
201
+ const flush = (): void => {
202
+ if (run.length === 0) return
203
+ out.push(textNode(open + run.join('') + close))
204
+ run = []
205
+ }
206
+ for (const node of nodes) {
207
+ if (node.type === 'text') {
208
+ run.push(node.text)
209
+ continue
210
+ }
211
+ flush()
212
+ out.push(node)
213
+ }
214
+ flush()
215
+ return out
216
+ }
217
+
218
+ /**
219
+ * Prefix every line of a node list with the quote marker.
220
+ * @param nodes - rendered children.
221
+ * @returns the children with `> ` at the start of every line.
222
+ */
223
+ export function quoteLines(nodes: readonly KookNode[]): KookNode[] {
224
+ const out: KookNode[] = []
225
+ let atLineStart = true
226
+ for (const node of nodes) {
227
+ if (node.type === 'break') {
228
+ // A paragraph boundary starts a line; the next text node of a nested quote gets its own marker.
229
+ atLineStart = true
230
+ out.push(node)
231
+ continue
232
+ }
233
+ if (node.type !== 'text') {
234
+ out.push(node)
235
+ continue
236
+ }
237
+ let text = ''
238
+ for (const char of node.text) {
239
+ if (atLineStart && char !== '\n') text += '> '
240
+ text += char
241
+ atLineStart = char === '\n'
242
+ }
243
+ out.push(textNode(text))
244
+ }
245
+ return out
246
+ }
247
+
248
+ /**
249
+ * The media node of one attachment element, reporting a phrasing-position attachment as `moved`.
250
+ * @param el - one of `img`/`audio`/`video`/`file`.
251
+ * @param ctx - render context of the mode.
252
+ * @returns the node.
253
+ */
254
+ export function mediaNode(
255
+ el: Element<'img' | 'audio' | 'video' | 'file'>,
256
+ ctx: RenderContext<KookModeTypes>,
257
+ ): KookNode {
258
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
259
+ if (parent !== undefined && isPhrasingContainer(parent.type)) {
260
+ ctx.report.moved.push({
261
+ tag: el.type,
262
+ reason: 'kook-media-split',
263
+ path: ctx.stableId(el),
264
+ })
265
+ }
266
+ switch (el.type) {
267
+ case 'img':
268
+ return { type: 'image', ref: ctx.resource('image', el.attrs.src, {}) }
269
+ case 'audio':
270
+ return {
271
+ type: 'media',
272
+ kind: 'audio',
273
+ ref: ctx.resource(
274
+ 'audio',
275
+ el.attrs.src,
276
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
277
+ ),
278
+ title: fileName(el.attrs.name, el.attrs.src),
279
+ }
280
+ case 'video':
281
+ return {
282
+ type: 'media',
283
+ kind: 'video',
284
+ ref: ctx.resource(
285
+ 'video',
286
+ el.attrs.src,
287
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
288
+ ),
289
+ title: fileName(el.attrs.name, el.attrs.src),
290
+ }
291
+ case 'file':
292
+ return {
293
+ type: 'media',
294
+ kind: 'file',
295
+ ref: ctx.resource(
296
+ 'file',
297
+ el.attrs.src,
298
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
299
+ ),
300
+ title: fileName(el.attrs.name, el.attrs.src),
301
+ }
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Fold the rendered node stream into platform messages.
307
+ *
308
+ * Text accumulates in one buffer; the first media, button or divider element turns the message into a card and every
309
+ * text run becomes a `section`. A card holds at most 50 modules, a section at most 5,000 visible characters, and a
310
+ * kmarkdown message at most 8,000: the buffer is cut at those bounds and each extra platform message is reported as a
311
+ * split. The result is never empty.
312
+ *
313
+ * @param nodes - rendered nodes in document order.
314
+ * @param ctx - render context, for the split and moved report.
315
+ * @returns one draft per platform message.
316
+ */
317
+ export function assembleDraft(
318
+ nodes: readonly KookNode[],
319
+ ctx: RenderContext<KookModeTypes>,
320
+ ): KookDraft[] {
321
+ const drafts: KookDraft[] = []
322
+ let text = ''
323
+ let modules: KookModuleDraft[] = []
324
+ let card = false
325
+
326
+ const flushCard = (): void => {
327
+ if (modules.length === 0) return
328
+ drafts.push({ kind: 'card', modules })
329
+ modules = []
330
+ }
331
+
332
+ const pushModule = (module: KookModuleDraft): void => {
333
+ card = true
334
+ modules.push(module)
335
+ // A card accepts at most 50 modules; the next one starts another message, so a card never exceeds its budget.
336
+ if (modules.length >= KOOK_LIMITS.cardModules) flushCard()
337
+ }
338
+
339
+ const flushText = (): void => {
340
+ const content = text.trim()
341
+ text = ''
342
+ if (content === '') return
343
+ for (const section of splitKMarkdown(content, KOOK_LIMITS.sectionChars)) {
344
+ pushModule({ type: 'section', content: section })
345
+ }
346
+ }
347
+
348
+ const lineBreak = (): void => {
349
+ if (text === '') return
350
+ if (text.endsWith('\n')) return
351
+ text += '\n'
352
+ }
353
+
354
+ for (const node of nodes) {
355
+ switch (node.type) {
356
+ case 'text':
357
+ text += node.text
358
+ break
359
+ case 'break':
360
+ lineBreak()
361
+ break
362
+ case 'divider':
363
+ flushText()
364
+ pushModule({ type: 'divider' })
365
+ break
366
+ case 'image':
367
+ flushText()
368
+ pushModule({ type: 'container', image: { ref: node.ref } })
369
+ break
370
+ case 'media':
371
+ flushText()
372
+ pushModule({
373
+ type: 'media',
374
+ kind: node.kind,
375
+ ref: node.ref,
376
+ title: node.title,
377
+ })
378
+ break
379
+ case 'buttons':
380
+ flushText()
381
+ pushModule({ type: 'buttons', buttons: node.buttons })
382
+ break
383
+ }
384
+ }
385
+
386
+ if (card) {
387
+ flushText()
388
+ flushCard()
389
+ } else {
390
+ const content = text.trim()
391
+ if (content !== '') {
392
+ for (const part of splitKMarkdown(content, KOOK_LIMITS.textChars)) {
393
+ drafts.push({ kind: 'text', content: part })
394
+ }
395
+ }
396
+ }
397
+ if (drafts.length === 0) drafts.push({ kind: 'text', content: '\u2060' })
398
+ ctx.report.split += drafts.length - 1
399
+ return drafts
400
+ }
401
+
402
+ /** The resource key `prepare` resolved for one media source. */
403
+ function resolvedKey(prepared: Prepared<KookDraft>, ref: ResourceRef): string {
404
+ const resolved = prepared.resolved.get(ref)
405
+ if (resolved === undefined) {
406
+ throw new Error('kook: the media was not prepared before serialize')
407
+ }
408
+ return resolved.key
409
+ }
410
+
411
+ /** One image as a card element. */
412
+ function imageOf(
413
+ prepared: Prepared<KookDraft>,
414
+ image: KookImageDraft,
415
+ ): Card.Image {
416
+ return { type: 'image', src: resolvedKey(prepared, image.ref) }
417
+ }
418
+
419
+ /** One button as a card element. */
420
+ function buttonOf(button: KookButtonNode): Card.Button {
421
+ return {
422
+ type: 'button',
423
+ theme: button.theme,
424
+ value: button.value,
425
+ click: button.click,
426
+ text: { type: 'kmarkdown', content: button.text },
427
+ }
428
+ }
429
+
430
+ /** One draft module as the wire module(s) it produces. */
431
+ function modulesOf(
432
+ prepared: Prepared<KookDraft>,
433
+ module: KookModuleDraft,
434
+ ): Card.Module[] {
435
+ switch (module.type) {
436
+ case 'section':
437
+ return [
438
+ {
439
+ type: 'section',
440
+ text: { type: 'kmarkdown', content: module.content },
441
+ },
442
+ ]
443
+ case 'container':
444
+ return [
445
+ { type: 'container', elements: [imageOf(prepared, module.image)] },
446
+ ]
447
+ case 'image-group':
448
+ return groupImages(module.images).map((images) => ({
449
+ type: 'image-group',
450
+ elements: images.map((image) => imageOf(prepared, image)),
451
+ }))
452
+ case 'buttons':
453
+ return chunk(module.buttons, KOOK_LIMITS.buttonsPerRow).map(
454
+ (buttons) => ({
455
+ type: 'action-group',
456
+ elements: buttons.map(buttonOf),
457
+ }),
458
+ )
459
+ case 'divider':
460
+ return [{ type: 'divider' }]
461
+ case 'media':
462
+ return [
463
+ {
464
+ type: module.kind,
465
+ src: resolvedKey(prepared, module.ref),
466
+ title: module.title,
467
+ },
468
+ ]
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Build the exact request body of one draft.
474
+ *
475
+ * Only the first platform message answers the quoted one; `SerializeContext.quote` reaches every part, so the adapter
476
+ * picks the one that carries it.
477
+ *
478
+ * @param prepared - the draft with every resource resolved.
479
+ * @param ctx - serialize context (part index and quote).
480
+ * @returns the request body.
481
+ */
482
+ export function serializeDraft(
483
+ prepared: Prepared<KookDraft>,
484
+ ctx: SerializeContext,
485
+ ): KookPayload {
486
+ const quote = ctx.index === 0 ? ctx.quote : undefined
487
+ const common = quote === undefined ? {} : { quote }
488
+ if (prepared.draft.kind === 'text') {
489
+ return { kind: 'text', type: 9, content: prepared.draft.content, ...common }
490
+ }
491
+ const card: Card = {
492
+ type: 'card',
493
+ modules: prepared.draft.modules.flatMap((module) =>
494
+ modulesOf(prepared, module),
495
+ ),
496
+ }
497
+ return { kind: 'card', type: 10, content: JSON.stringify([card]), ...common }
498
+ }