@im-more/dsh-slack 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 (226) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +13 -0
  3. package/lib/index.js +2659 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +66 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +165 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +49 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +54 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +126 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +396 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +61 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +196 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +27 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +35 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +14 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +14 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/modes/mrkdwn.d.ts +17 -0
  30. package/lib/types/modes/mrkdwn.d.ts.map +1 -0
  31. package/lib/types/modes/mrkdwn.js +123 -0
  32. package/lib/types/modes/mrkdwn.js.map +1 -0
  33. package/lib/types/modes/shared.d.ts +164 -0
  34. package/lib/types/modes/shared.d.ts.map +1 -0
  35. package/lib/types/modes/shared.js +411 -0
  36. package/lib/types/modes/shared.js.map +1 -0
  37. package/lib/types/mrkdwn.d.ts +41 -0
  38. package/lib/types/mrkdwn.d.ts.map +1 -0
  39. package/lib/types/mrkdwn.js +137 -0
  40. package/lib/types/mrkdwn.js.map +1 -0
  41. package/lib/types/request.d.ts +225 -0
  42. package/lib/types/request.d.ts.map +1 -0
  43. package/lib/types/request.js +330 -0
  44. package/lib/types/request.js.map +1 -0
  45. package/lib/types/send.d.ts +74 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +200 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/transport/socket.d.ts +58 -0
  50. package/lib/types/transport/socket.d.ts.map +1 -0
  51. package/lib/types/transport/socket.js +297 -0
  52. package/lib/types/transport/socket.js.map +1 -0
  53. package/lib/types/transport/webhook.d.ts +48 -0
  54. package/lib/types/transport/webhook.d.ts.map +1 -0
  55. package/lib/types/transport/webhook.js +210 -0
  56. package/lib/types/transport/webhook.js.map +1 -0
  57. package/lib/types/types/admin.d.ts +682 -0
  58. package/lib/types/types/admin.d.ts.map +1 -0
  59. package/lib/types/types/admin.js +172 -0
  60. package/lib/types/types/admin.js.map +1 -0
  61. package/lib/types/types/api.d.ts +20 -0
  62. package/lib/types/types/api.d.ts.map +1 -0
  63. package/lib/types/types/api.js +7 -0
  64. package/lib/types/types/api.js.map +1 -0
  65. package/lib/types/types/apps.d.ts +138 -0
  66. package/lib/types/types/apps.d.ts.map +1 -0
  67. package/lib/types/types/apps.js +28 -0
  68. package/lib/types/types/apps.js.map +1 -0
  69. package/lib/types/types/auth.d.ts +36 -0
  70. package/lib/types/types/auth.d.ts.map +1 -0
  71. package/lib/types/types/auth.js +10 -0
  72. package/lib/types/types/auth.js.map +1 -0
  73. package/lib/types/types/bots.d.ts +32 -0
  74. package/lib/types/types/bots.d.ts.map +1 -0
  75. package/lib/types/types/bots.js +7 -0
  76. package/lib/types/types/bots.js.map +1 -0
  77. package/lib/types/types/calls.d.ts +82 -0
  78. package/lib/types/types/calls.d.ts.map +1 -0
  79. package/lib/types/types/calls.js +22 -0
  80. package/lib/types/types/calls.js.map +1 -0
  81. package/lib/types/types/chat.d.ts +208 -0
  82. package/lib/types/types/chat.d.ts.map +1 -0
  83. package/lib/types/types/chat.js +34 -0
  84. package/lib/types/types/chat.js.map +1 -0
  85. package/lib/types/types/conversations.d.ts +266 -0
  86. package/lib/types/types/conversations.d.ts.map +1 -0
  87. package/lib/types/types/conversations.js +58 -0
  88. package/lib/types/types/conversations.js.map +1 -0
  89. package/lib/types/types/definition.d.ts +505 -0
  90. package/lib/types/types/definition.d.ts.map +1 -0
  91. package/lib/types/types/definition.js +2 -0
  92. package/lib/types/types/definition.js.map +1 -0
  93. package/lib/types/types/dialog.d.ts +20 -0
  94. package/lib/types/types/dialog.d.ts.map +1 -0
  95. package/lib/types/types/dialog.js +7 -0
  96. package/lib/types/types/dialog.js.map +1 -0
  97. package/lib/types/types/dnd.d.ts +70 -0
  98. package/lib/types/types/dnd.d.ts.map +1 -0
  99. package/lib/types/types/dnd.js +19 -0
  100. package/lib/types/types/dnd.js.map +1 -0
  101. package/lib/types/types/emoji.d.ts +18 -0
  102. package/lib/types/types/emoji.d.ts.map +1 -0
  103. package/lib/types/types/emoji.js +7 -0
  104. package/lib/types/types/emoji.js.map +1 -0
  105. package/lib/types/types/events/base-events.d.ts +235 -0
  106. package/lib/types/types/events/base-events.d.ts.map +1 -0
  107. package/lib/types/types/events/base-events.js +3 -0
  108. package/lib/types/types/events/base-events.js.map +1 -0
  109. package/lib/types/types/events/index.d.ts +97 -0
  110. package/lib/types/types/events/index.d.ts.map +1 -0
  111. package/lib/types/types/events/index.js +3 -0
  112. package/lib/types/types/events/index.js.map +1 -0
  113. package/lib/types/types/events/message-events.d.ts +215 -0
  114. package/lib/types/types/events/message-events.d.ts.map +1 -0
  115. package/lib/types/types/events/message-events.js +3 -0
  116. package/lib/types/types/events/message-events.js.map +1 -0
  117. package/lib/types/types/files.d.ts +189 -0
  118. package/lib/types/types/files.d.ts.map +1 -0
  119. package/lib/types/types/files.js +43 -0
  120. package/lib/types/types/files.js.map +1 -0
  121. package/lib/types/types/index.d.ts +82 -0
  122. package/lib/types/types/index.d.ts.map +1 -0
  123. package/lib/types/types/index.js +29 -0
  124. package/lib/types/types/index.js.map +1 -0
  125. package/lib/types/types/internal.d.ts +17 -0
  126. package/lib/types/types/internal.d.ts.map +1 -0
  127. package/lib/types/types/internal.js +60 -0
  128. package/lib/types/types/internal.js.map +1 -0
  129. package/lib/types/types/migration.d.ts +25 -0
  130. package/lib/types/types/migration.d.ts.map +1 -0
  131. package/lib/types/types/migration.js +7 -0
  132. package/lib/types/types/migration.js.map +1 -0
  133. package/lib/types/types/oauth.d.ts +50 -0
  134. package/lib/types/types/oauth.d.ts.map +1 -0
  135. package/lib/types/types/oauth.js +13 -0
  136. package/lib/types/types/oauth.js.map +1 -0
  137. package/lib/types/types/pins.d.ts +39 -0
  138. package/lib/types/types/pins.d.ts.map +1 -0
  139. package/lib/types/types/pins.js +13 -0
  140. package/lib/types/types/pins.js.map +1 -0
  141. package/lib/types/types/reactions.d.ts +75 -0
  142. package/lib/types/types/reactions.d.ts.map +1 -0
  143. package/lib/types/types/reactions.js +16 -0
  144. package/lib/types/types/reactions.js.map +1 -0
  145. package/lib/types/types/reminders.d.ts +64 -0
  146. package/lib/types/types/reminders.d.ts.map +1 -0
  147. package/lib/types/types/reminders.js +19 -0
  148. package/lib/types/types/reminders.js.map +1 -0
  149. package/lib/types/types/rtm.d.ts +30 -0
  150. package/lib/types/types/rtm.d.ts.map +1 -0
  151. package/lib/types/types/rtm.js +7 -0
  152. package/lib/types/types/rtm.js.map +1 -0
  153. package/lib/types/types/search.d.ts +24 -0
  154. package/lib/types/types/search.d.ts.map +1 -0
  155. package/lib/types/types/search.js +7 -0
  156. package/lib/types/types/search.js.map +1 -0
  157. package/lib/types/types/stars.d.ts +56 -0
  158. package/lib/types/types/stars.d.ts.map +1 -0
  159. package/lib/types/types/stars.js +13 -0
  160. package/lib/types/types/stars.js.map +1 -0
  161. package/lib/types/types/team.d.ts +98 -0
  162. package/lib/types/types/team.d.ts.map +1 -0
  163. package/lib/types/types/team.js +19 -0
  164. package/lib/types/types/team.js.map +1 -0
  165. package/lib/types/types/usergroups.d.ts +103 -0
  166. package/lib/types/types/usergroups.d.ts.map +1 -0
  167. package/lib/types/types/usergroups.js +25 -0
  168. package/lib/types/types/usergroups.js.map +1 -0
  169. package/lib/types/types/users.d.ts +169 -0
  170. package/lib/types/types/users.d.ts.map +1 -0
  171. package/lib/types/types/users.js +40 -0
  172. package/lib/types/types/users.js.map +1 -0
  173. package/lib/types/types/views.d.ts +56 -0
  174. package/lib/types/types/views.d.ts.map +1 -0
  175. package/lib/types/types/views.js +16 -0
  176. package/lib/types/types/views.js.map +1 -0
  177. package/lib/types/types/workflows.d.ts +45 -0
  178. package/lib/types/types/workflows.d.ts.map +1 -0
  179. package/lib/types/types/workflows.js +13 -0
  180. package/lib/types/types/workflows.js.map +1 -0
  181. package/package.json +65 -3
  182. package/src/bot.ts +273 -0
  183. package/src/config.ts +92 -0
  184. package/src/decode.ts +489 -0
  185. package/src/errors.ts +230 -0
  186. package/src/identity.ts +59 -0
  187. package/src/index.ts +64 -0
  188. package/src/modes/mrkdwn.ts +159 -0
  189. package/src/modes/shared.ts +515 -0
  190. package/src/mrkdwn.ts +146 -0
  191. package/src/request.ts +449 -0
  192. package/src/send.ts +300 -0
  193. package/src/transport/socket.ts +393 -0
  194. package/src/transport/webhook.ts +269 -0
  195. package/src/types/admin.ts +910 -0
  196. package/src/types/api.ts +28 -0
  197. package/src/types/apps.ts +175 -0
  198. package/src/types/auth.ts +49 -0
  199. package/src/types/bots.ts +40 -0
  200. package/src/types/calls.ts +110 -0
  201. package/src/types/chat.ts +255 -0
  202. package/src/types/conversations.ts +342 -0
  203. package/src/types/definition.ts +530 -0
  204. package/src/types/dialog.ts +28 -0
  205. package/src/types/dnd.ts +94 -0
  206. package/src/types/emoji.ts +26 -0
  207. package/src/types/events/base-events.ts +281 -0
  208. package/src/types/events/index.ts +125 -0
  209. package/src/types/events/message-events.ts +253 -0
  210. package/src/types/files.ts +245 -0
  211. package/src/types/index.ts +84 -0
  212. package/src/types/internal.ts +60 -0
  213. package/src/types/migration.ts +34 -0
  214. package/src/types/oauth.ts +66 -0
  215. package/src/types/pins.ts +55 -0
  216. package/src/types/reactions.ts +95 -0
  217. package/src/types/reminders.ts +88 -0
  218. package/src/types/rtm.ts +38 -0
  219. package/src/types/search.ts +32 -0
  220. package/src/types/stars.ts +72 -0
  221. package/src/types/team.ts +122 -0
  222. package/src/types/usergroups.ts +135 -0
  223. package/src/types/users.ts +221 -0
  224. package/src/types/views.ts +76 -0
  225. package/src/types/workflows.ts +61 -0
  226. package/README.md +0 -3
@@ -0,0 +1,515 @@
1
+ /**
2
+ * Draft model of the single `mrkdwn` mode: the node stream, the paragraph and media splitting, the 4,000-character
3
+ * split that never loses a character, and the exact request payload of one platform message.
4
+ *
5
+ * A run keeps its markup as data (`marks`) instead of embedding it in the text. That is what makes splitting exact: a
6
+ * cut closes the open markers and reopens them in the next chunk, because the markers are not part of the text being
7
+ * counted.
8
+ */
9
+
10
+ import type {
11
+ ModeTypes,
12
+ Prepared,
13
+ RenderContext,
14
+ ResourceRef,
15
+ SerializeContext,
16
+ } from '@deepseek-ai/cordis-plugin-im-core'
17
+ import { isPhrasingContainer } from '@deepseek-ai/satori-element'
18
+ import type { Element } from '@deepseek-ai/satori-element'
19
+
20
+ /** Slack's documented `text` bound: longer text is split into messages of about that size. */
21
+ export const SLACK_LIMITS = { text: 4_000 } as const
22
+
23
+ /** One markup wrapper of a run. */
24
+ export type SlackMark =
25
+ | { kind: 'bold' }
26
+ | { kind: 'italic' }
27
+ | { kind: 'strike' }
28
+ | { kind: 'code' }
29
+ | { kind: 'link'; href: string }
30
+ | { kind: 'fence'; lang: string | undefined }
31
+
32
+ /** A piece of body text under a fixed stack of marks, outermost first. */
33
+ export interface SlackRun {
34
+ /** Already escaped text. */
35
+ text: string
36
+ marks: readonly SlackMark[]
37
+ }
38
+
39
+ /** One node a mode handler produces. */
40
+ export type SlackNode =
41
+ | { type: 'text'; run: SlackRun }
42
+ /** A paragraph boundary: at most one newline, and none at the start of a message. */
43
+ | { type: 'break' }
44
+ /** An attachment, published as a message of its own. */
45
+ | { type: 'media'; ref: ResourceRef; name: string }
46
+
47
+ /** One platform message before resource resolution. */
48
+ export type SlackDraft =
49
+ | { type: 'text'; text: string }
50
+ | { type: 'file'; ref: ResourceRef; name: string }
51
+
52
+ /** Exact request data of one platform message. */
53
+ export type SlackPayload =
54
+ | {
55
+ kind: 'message'
56
+ channel: string
57
+ text: string
58
+ threadTs?: string
59
+ replyBroadcast?: boolean
60
+ }
61
+ | {
62
+ kind: 'file'
63
+ channel: string
64
+ fileId: string
65
+ name: string
66
+ threadTs?: string
67
+ }
68
+
69
+ /** Mode types of the single `mrkdwn` mode. */
70
+ export interface SlackModeTypes extends ModeTypes {
71
+ node: SlackNode
72
+ draft: SlackDraft
73
+ payload: SlackPayload
74
+ }
75
+
76
+ /** A paragraph break node. */
77
+ export const BREAK: SlackNode = { type: 'break' }
78
+
79
+ /**
80
+ * Drop the paragraph break a container put in front of its content, so a list marker is not followed by a newline.
81
+ * @param nodes - rendered children.
82
+ * @returns the children without leading break nodes.
83
+ */
84
+ export function withoutLeadingBreaks(nodes: readonly SlackNode[]): SlackNode[] {
85
+ let start = 0
86
+ while (start < nodes.length && nodes[start]!.type === 'break') start += 1
87
+ return nodes.slice(start)
88
+ }
89
+
90
+ /**
91
+ * One text node under the given marks.
92
+ * @param text - the already escaped text.
93
+ * @param marks - the marks wrapping it, outermost first.
94
+ * @returns the node.
95
+ */
96
+ export function textNode(
97
+ text: string,
98
+ marks: readonly SlackMark[] = [],
99
+ ): SlackNode {
100
+ return { type: 'text', run: { text, marks } }
101
+ }
102
+
103
+ /** Identity of one mark, for comparing two stacks. */
104
+ function markKey(mark: SlackMark): string {
105
+ switch (mark.kind) {
106
+ case 'link':
107
+ return `link:${mark.href}`
108
+ case 'fence':
109
+ return `fence:${mark.lang ?? ''}`
110
+ default:
111
+ return mark.kind
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Wrap every text run of a subtree with one mark.
117
+ *
118
+ * A run already carrying the same mark right above it is left alone, so `<b><b>x</b></b>` does not emit `**x**`.
119
+ *
120
+ * @param nodes - rendered children.
121
+ * @param mark - the mark to add.
122
+ * @returns the children with the mark added to their text runs.
123
+ */
124
+ export function withMark(
125
+ nodes: readonly SlackNode[],
126
+ mark: SlackMark,
127
+ ): SlackNode[] {
128
+ const key = markKey(mark)
129
+ return nodes.map((node) => {
130
+ if (node.type !== 'text') return node
131
+ const { marks } = node.run
132
+ const last = marks[marks.length - 1]
133
+ if (last !== undefined && markKey(last) === key) return node
134
+ return {
135
+ type: 'text',
136
+ run: { text: node.run.text, marks: [...marks, mark] },
137
+ }
138
+ })
139
+ }
140
+
141
+ /** The opening marker of one mark. */
142
+ function markOpen(mark: SlackMark): string {
143
+ switch (mark.kind) {
144
+ case 'bold':
145
+ return '*'
146
+ case 'italic':
147
+ return '_'
148
+ case 'strike':
149
+ return '~'
150
+ case 'code':
151
+ return '`'
152
+ case 'link':
153
+ return `<${mark.href}|`
154
+ case 'fence':
155
+ return `\`\`\`${mark.lang ?? ''}\n`
156
+ }
157
+ }
158
+
159
+ /** The closing marker of one mark. */
160
+ function markClose(mark: SlackMark): string {
161
+ switch (mark.kind) {
162
+ case 'link':
163
+ return '>'
164
+ case 'fence':
165
+ return '\n```'
166
+ default:
167
+ return markOpen(mark)
168
+ }
169
+ }
170
+
171
+ /** How many marks two stacks share from the outside in. */
172
+ function sharedMarks(
173
+ left: readonly SlackMark[],
174
+ right: readonly SlackMark[],
175
+ ): number {
176
+ const limit = Math.min(left.length, right.length)
177
+ for (let index = 0; index < limit; index++) {
178
+ if (markKey(left[index]!) !== markKey(right[index]!)) return index
179
+ }
180
+ return limit
181
+ }
182
+
183
+ /**
184
+ * Render a run list as one message body, closing and reopening marks only where the stack changes.
185
+ * @param runs - the runs of one message.
186
+ * @returns the message body.
187
+ */
188
+ export function renderRuns(runs: readonly SlackRun[]): string {
189
+ let body = ''
190
+ let open: readonly SlackMark[] = []
191
+ for (const run of runs) {
192
+ const shared = sharedMarks(open, run.marks)
193
+ for (let index = open.length - 1; index >= shared; index--) {
194
+ body += markClose(open[index]!)
195
+ }
196
+ for (let index = shared; index < run.marks.length; index++) {
197
+ body += markOpen(run.marks[index]!)
198
+ }
199
+ body += run.text
200
+ open = run.marks
201
+ }
202
+ for (let index = open.length - 1; index >= 0; index--) {
203
+ body += markClose(open[index]!)
204
+ }
205
+ return body
206
+ }
207
+
208
+ /** Visible characters of a run list: one per Unicode code point. */
209
+ export function visibleLength(runs: readonly SlackRun[]): number {
210
+ let length = 0
211
+ for (const run of runs) for (const _ of run.text) length += 1
212
+ return length
213
+ }
214
+
215
+ /** One code point of a message body, with the marks it sits under. */
216
+ interface Atom {
217
+ char: string
218
+ marks: readonly SlackMark[]
219
+ }
220
+
221
+ /** Canonical identity of a whole mark stack, for joining runs that render identically. */
222
+ function stackKey(marks: readonly SlackMark[]): string {
223
+ return marks.map(markKey).join('\u0000')
224
+ }
225
+
226
+ /** Fold an atom list back into runs, joining neighbours that share their whole stack. */
227
+ function runsOf(atoms: readonly Atom[]): SlackRun[] {
228
+ const runs: SlackRun[] = []
229
+ let key = ''
230
+ for (const atom of atoms) {
231
+ const atomKey = stackKey(atom.marks)
232
+ const last = runs[runs.length - 1]
233
+ if (last !== undefined && atomKey === key) {
234
+ last.text += atom.char
235
+ continue
236
+ }
237
+ runs.push({ text: atom.char, marks: atom.marks })
238
+ key = atomKey
239
+ }
240
+ return runs
241
+ }
242
+
243
+ /**
244
+ * Split a run list into chunks of at most `limit` visible characters.
245
+ *
246
+ * The cut prefers the last line break of the window, then the last space, then a hard cut; every chunk closes the
247
+ * marks it opened, so each message parses on its own. No visible character is ever dropped.
248
+ *
249
+ * @param runs - the whole message body.
250
+ * @param limit - visible characters per chunk.
251
+ * @returns the chunks, in order.
252
+ */
253
+ export function splitRuns(
254
+ runs: readonly SlackRun[],
255
+ limit: number,
256
+ ): SlackRun[][] {
257
+ if (visibleLength(runs) <= limit) return [[...runs]]
258
+ const atoms: Atom[] = []
259
+ for (const run of runs) {
260
+ for (const char of run.text) atoms.push({ char, marks: run.marks })
261
+ }
262
+ const chunks: SlackRun[][] = []
263
+ let start = 0
264
+ while (start < atoms.length) {
265
+ if (atoms.length - start <= limit) {
266
+ chunks.push(runsOf(atoms.slice(start)))
267
+ break
268
+ }
269
+ const window = start + limit
270
+ let cut = window
271
+ for (let index = window - 1; index >= start; index--) {
272
+ if (atoms[index]!.char === '\n') {
273
+ cut = index + 1
274
+ break
275
+ }
276
+ }
277
+ if (cut === window) {
278
+ for (let index = window - 1; index >= start; index--) {
279
+ if (atoms[index]!.char === ' ') {
280
+ cut = index + 1
281
+ break
282
+ }
283
+ }
284
+ }
285
+ chunks.push(runsOf(atoms.slice(start, cut)))
286
+ start = cut
287
+ }
288
+ return chunks
289
+ }
290
+
291
+ /**
292
+ * Fold the rendered node stream into platform messages.
293
+ *
294
+ * Inline nodes share one body; a media element flushes the body and becomes a message of its own, as the upstream
295
+ * encoder does. A paragraph break adds one newline and never starts a message with one, and the ends of every message
296
+ * are trimmed.
297
+ *
298
+ * @param nodes - rendered nodes in document order.
299
+ * @returns one draft per platform message; a single empty text draft when the content renders nothing.
300
+ */
301
+ export function assembleDraft(nodes: readonly SlackNode[]): SlackDraft[] {
302
+ const drafts: SlackDraft[] = []
303
+ let runs: SlackRun[] = []
304
+
305
+ /** The runs without the whitespace around the message, which no mark wraps. */
306
+ const trimmed = (input: readonly SlackRun[]): SlackRun[] => {
307
+ const copy = input.map((run) => ({ text: run.text, marks: run.marks }))
308
+ while (copy.length > 0) {
309
+ const first = copy[0]!
310
+ const text = first.text.replace(/^\s+/, '')
311
+ if (text !== '') {
312
+ first.text = text
313
+ break
314
+ }
315
+ copy.shift()
316
+ }
317
+ while (copy.length > 0) {
318
+ const last = copy[copy.length - 1]!
319
+ const text = last.text.replace(/\s+$/, '')
320
+ if (text !== '') {
321
+ last.text = text
322
+ break
323
+ }
324
+ copy.pop()
325
+ }
326
+ return copy
327
+ }
328
+
329
+ const flushText = (): void => {
330
+ if (runs.length === 0) return
331
+ for (const chunk of splitRuns(runs, SLACK_LIMITS.text)) {
332
+ const trimmedRuns = trimmed(chunk)
333
+ if (trimmedRuns.length === 0) continue
334
+ drafts.push({ type: 'text', text: renderRuns(trimmedRuns) })
335
+ }
336
+ runs = []
337
+ }
338
+
339
+ const append = (run: SlackRun): void => {
340
+ const last = runs[runs.length - 1]
341
+ if (last !== undefined && stackKey(last.marks) === stackKey(run.marks)) {
342
+ last.text += run.text
343
+ return
344
+ }
345
+ runs.push({ text: run.text, marks: run.marks })
346
+ }
347
+
348
+ const lineBreak = (): void => {
349
+ const last = runs[runs.length - 1]
350
+ if (last === undefined) return
351
+ if (last.text.endsWith('\n')) return
352
+ // The break sits outside every mark: a marked run never swallows the newline of the next paragraph, which matters
353
+ // most for a code fence, whose closing marker would otherwise move past the break.
354
+ append({ text: '\n', marks: [] })
355
+ }
356
+
357
+ for (const node of nodes) {
358
+ switch (node.type) {
359
+ case 'text':
360
+ append(node.run)
361
+ break
362
+ case 'break':
363
+ lineBreak()
364
+ break
365
+ case 'media':
366
+ flushText()
367
+ drafts.push({ type: 'file', ref: node.ref, name: node.name })
368
+ break
369
+ }
370
+ }
371
+ flushText()
372
+ if (drafts.length === 0) drafts.push({ type: 'text', text: '' })
373
+ return drafts
374
+ }
375
+
376
+ /** The file name of an outbound attachment: the declared name, else the last path segment of the source. */
377
+ export function fileName(name: string | undefined, src: string): string {
378
+ if (name !== undefined && name !== '') return name
379
+ try {
380
+ const path = new URL(src).pathname
381
+ const segment = path.slice(path.lastIndexOf('/') + 1)
382
+ if (segment !== '') return decodeURIComponent(segment)
383
+ } catch (error) {
384
+ // Not a URL: the source itself is the best name available.
385
+ error
386
+ if (src !== '' && !src.includes('/')) return src
387
+ }
388
+ return 'file'
389
+ }
390
+
391
+ /**
392
+ * The attachment node of one media element.
393
+ * @param el - one of `img`, `audio`, `video`, `file`.
394
+ * @param ctx - render context of the mode.
395
+ * @returns the node to publish after the body it was found in.
396
+ */
397
+ export function mediaNode(
398
+ el: Element<'img' | 'audio' | 'video' | 'file'>,
399
+ ctx: RenderContext<SlackModeTypes>,
400
+ ): SlackNode {
401
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
402
+ if (parent !== undefined && isPhrasingContainer(parent.type)) {
403
+ ctx.report.moved.push({
404
+ tag: el.type,
405
+ reason: 'slack-media-split',
406
+ path: ctx.stableId(el),
407
+ })
408
+ }
409
+ switch (el.type) {
410
+ case 'img':
411
+ return {
412
+ type: 'media',
413
+ ref: ctx.resource('image', el.attrs.src, {}),
414
+ name: fileName(undefined, el.attrs.src),
415
+ }
416
+ case 'audio':
417
+ return {
418
+ type: 'media',
419
+ ref: ctx.resource(
420
+ 'audio',
421
+ el.attrs.src,
422
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
423
+ ),
424
+ name: fileName(el.attrs.name, el.attrs.src),
425
+ }
426
+ case 'video':
427
+ return {
428
+ type: 'media',
429
+ ref: ctx.resource(
430
+ 'video',
431
+ el.attrs.src,
432
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
433
+ ),
434
+ name: fileName(el.attrs.name, el.attrs.src),
435
+ }
436
+ case 'file':
437
+ return {
438
+ type: 'media',
439
+ ref: ctx.resource(
440
+ 'file',
441
+ el.attrs.src,
442
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
443
+ ),
444
+ name: fileName(el.attrs.name, el.attrs.src),
445
+ }
446
+ }
447
+ }
448
+
449
+ /** The resource key `prepare` resolved for one attachment. */
450
+ function resolvedKey(prepared: Prepared<SlackDraft>, ref: ResourceRef): string {
451
+ const resolved = prepared.resolved.get(ref)
452
+ if (resolved === undefined) {
453
+ throw new Error('slack: the attachment was not prepared before serialize')
454
+ }
455
+ return resolved.key
456
+ }
457
+
458
+ /** `thread_ts` of an inbound referrer, when the target asks to follow it. */
459
+ function referrerThreadTs(referrer: unknown): string | undefined {
460
+ if (typeof referrer !== 'object' || referrer === null) return undefined
461
+ const threadTs = (referrer as { threadTs?: unknown }).threadTs
462
+ return typeof threadTs === 'string' && threadTs !== '' ? threadTs : undefined
463
+ }
464
+
465
+ /**
466
+ * The thread one part answers: an explicit thread, the referrer's thread, or — for the first part only — the quote.
467
+ *
468
+ * Slack's "reply to a message" is a thread reply, so a `<quote>` becomes `thread_ts`. Only the first part carries it,
469
+ * because the later parts of a split message would otherwise start threads of their own.
470
+ *
471
+ * @param ctx - serialize context.
472
+ * @returns the thread timestamp, when this part goes into a thread.
473
+ */
474
+ export function threadTsOf(ctx: SerializeContext): string | undefined {
475
+ if (typeof ctx.target.thread === 'string') return ctx.target.thread
476
+ if (ctx.target.thread === true) return referrerThreadTs(ctx.target.referrer)
477
+ return ctx.index === 0 ? ctx.quote : undefined
478
+ }
479
+
480
+ /**
481
+ * Build the exact request data of one draft.
482
+ *
483
+ * @param prepared - the draft with its resources resolved.
484
+ * @param ctx - serialize context (channel, thread, part index).
485
+ * @param replyBroadcast - `replyBroadcast` of the profile row.
486
+ * @returns the request data of one platform message or file message.
487
+ */
488
+ export function serializeDraft(
489
+ prepared: Prepared<SlackDraft>,
490
+ ctx: SerializeContext,
491
+ replyBroadcast: boolean,
492
+ ): SlackPayload {
493
+ const { draft } = prepared
494
+ const channel = ctx.target.chat.id
495
+ const threadTs = threadTsOf(ctx)
496
+ if (draft.type === 'file') {
497
+ return {
498
+ kind: 'file',
499
+ channel,
500
+ fileId: resolvedKey(prepared, draft.ref),
501
+ name: draft.name,
502
+ ...(threadTs === undefined ? {} : { threadTs }),
503
+ }
504
+ }
505
+ return {
506
+ kind: 'message',
507
+ channel,
508
+ // Slack accepts a zero-width joiner and shows no empty bubble; `assemble` only produces this when nothing rendered.
509
+ text: draft.text === '' ? '\u2060' : draft.text,
510
+ ...(threadTs === undefined ? {} : { threadTs }),
511
+ ...(threadTs !== undefined && replyBroadcast
512
+ ? { replyBroadcast: true }
513
+ : {}),
514
+ }
515
+ }
package/src/mrkdwn.ts ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * The `mrkdwn` escaping rules of the upstream adapter and the inbound parser of the same syntax.
3
+ *
4
+ * Slack's message text is a small markup language, not plain text: `*bold*`, `_italic_`, `~strike~`, `` `code` ``,
5
+ * `<@U…>` mentions, `<#C…>` channel links, `<url|label>` links and `:emoji:` names. Outbound, every literal character
6
+ * that would otherwise be read as markup is escaped with a zero-width space; inbound, the same markers are parsed back
7
+ * into the element vocabulary.
8
+ */
9
+
10
+ import { h } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type { Element } from '@deepseek-ai/cordis-plugin-im-core'
12
+
13
+ /** Zero-width space put in front of a markup character; it is invisible and keeps the character literal. */
14
+ const MARK_ESCAPE = '\u200B'
15
+ /** Hair space put in front of a leading `>`; a quoted block is started by `>` at the beginning of a line. */
16
+ const QUOTE_ESCAPE = '\u200A'
17
+
18
+ /**
19
+ * Escape text so Slack renders it literally.
20
+ *
21
+ * Four rules, identical to the upstream adapter's: a markup character gets a zero-width space; `@everyone`/`@here`
22
+ * are broken up so they cannot notify; a leading `>` cannot start a quoted block; and `<…>` cannot become a link or a
23
+ * mention. The result keeps every visible character and adds only invisible ones.
24
+ *
25
+ * @param text - the text of a `text` element.
26
+ * @returns the text to append to the message body.
27
+ */
28
+ export function escape(text: string): string {
29
+ return text
30
+ .replace(/(?<!\u200B)[*_~`]/g, `${MARK_ESCAPE}$&`)
31
+ .replace(/@everyone/g, () => `@${MARK_ESCAPE}everyone`)
32
+ .replace(/@here/g, () => `@${MARK_ESCAPE}here`)
33
+ .replace(/(?<!\u200B)^>/g, `${QUOTE_ESCAPE}&gt;`)
34
+ .replace(/<(.*?)>/g, '&lt;$1&gt;')
35
+ }
36
+
37
+ /**
38
+ * Undo {@link escape}: restore the markup characters, the notification words and a leading `>`.
39
+ *
40
+ * Slack hands back the text of a message as its author typed it, so a zero-width space only appears when the text was
41
+ * written by an adapter of this family; parsing it back is what keeps a relayed message identical.
42
+ *
43
+ * @param text - text of one rich-text run.
44
+ * @returns the text as it was written.
45
+ */
46
+ export function unescape(text: string): string {
47
+ return text
48
+ .replace(/\u200B([*_~`])/g, '$1')
49
+ .replace(new RegExp(`@${MARK_ESCAPE}everyone`, 'g'), () => '@everyone')
50
+ .replace(new RegExp(`@${MARK_ESCAPE}here`, 'g'), () => '@here')
51
+ .replace(new RegExp(`^${QUOTE_ESCAPE}&gt;`), '>')
52
+ }
53
+
54
+ /** A Slack control sequence between angle brackets, e.g. `<@U123>` or `<https://example.com|label>`. */
55
+ const CONTROL = /(<[^<>]*>)/
56
+
57
+ /** An emoji name between colons, e.g. `:tada:` or `:+1:`. */
58
+ const EMOJI = /(:[a-zA-Z0-9_+-]+:)/
59
+
60
+ /** The label of a mention or channel link, when Slack included one (`<@U123|alice>`). */
61
+ function labelOf(
62
+ raw: string,
63
+ prefixLength: number,
64
+ ): { id: string; name?: string } {
65
+ const body = raw.slice(prefixLength, -1)
66
+ const separator = body.indexOf('|')
67
+ if (separator < 0) return { id: body }
68
+ return {
69
+ id: body.slice(0, separator),
70
+ ...(body.slice(separator + 1) === ''
71
+ ? {}
72
+ : { name: body.slice(separator + 1) }),
73
+ }
74
+ }
75
+
76
+ /** Turn one `<…>` control sequence into elements; an unrecognized one stays as its literal text. */
77
+ function controlElement(raw: string): Element[] {
78
+ const body = raw.slice(1, -1)
79
+ if (body.startsWith('@')) {
80
+ const { id, name } = labelOf(raw, 2)
81
+ return [
82
+ h('at', { type: 'user', id, ...(name === undefined ? {} : { name }) }),
83
+ ]
84
+ }
85
+ if (body.startsWith('#')) {
86
+ const { id, name } = labelOf(raw, 2)
87
+ return [h('channel', { id, ...(name === undefined ? {} : { name }) })]
88
+ }
89
+ if (body.startsWith('!')) {
90
+ const range = body.slice(1)
91
+ if (range === 'here') return [h('at', { type: 'here' })]
92
+ if (range === 'channel' || range === 'everyone') {
93
+ return [h('at', { type: 'all' })]
94
+ }
95
+ return [h.text(raw)]
96
+ }
97
+ const separator = body.indexOf('|')
98
+ if (separator > 0) {
99
+ const href = body.slice(0, separator)
100
+ const label = body.slice(separator + 1)
101
+ return [h('a', { href }, label === '' ? href : label)]
102
+ }
103
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(body)) {
104
+ return [h('a', { href: body }, body)]
105
+ }
106
+ // A subteam mention, an unresolved id or something Slack added later: keeping it as text loses no content.
107
+ return [h.text(raw)]
108
+ }
109
+
110
+ /** Split one plain run on emoji names, keeping the text between them. */
111
+ function emojiElements(text: string): Element[] {
112
+ const parts = text.split(EMOJI)
113
+ const elements: Element[] = []
114
+ for (const part of parts) {
115
+ if (part === '') continue
116
+ if (part.length > 2 && part.startsWith(':') && part.endsWith(':')) {
117
+ const name = part.slice(1, -1)
118
+ elements.push(h('emoji', { id: name, name }))
119
+ continue
120
+ }
121
+ elements.push(h.text(unescape(part)))
122
+ }
123
+ return elements
124
+ }
125
+
126
+ /**
127
+ * Parse Slack message text into the element vocabulary.
128
+ *
129
+ * Used for the `text` field of a message (when it carries no usable `blocks`), for the `text` of a `section` block,
130
+ * and for a `rich_text_quote`/`rich_text_preformatted` body.
131
+ *
132
+ * @param text - Slack message text.
133
+ * @returns the content nodes; empty when the text is empty.
134
+ */
135
+ export function parseMrkdwn(text: string): Element[] {
136
+ const elements: Element[] = []
137
+ for (const part of text.split(CONTROL)) {
138
+ if (part === '') continue
139
+ if (part.startsWith('<') && part.endsWith('>') && part.length > 2) {
140
+ elements.push(...controlElement(part))
141
+ continue
142
+ }
143
+ elements.push(...emojiElements(part))
144
+ }
145
+ return elements
146
+ }