@im-more/dsh-dingtalk 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 (292) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +11 -0
  3. package/lib/index.js +2765 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/api/alitrip.d.ts +397 -0
  6. package/lib/types/api/alitrip.d.ts.map +1 -0
  7. package/lib/types/api/alitrip.js +21 -0
  8. package/lib/types/api/alitrip.js.map +1 -0
  9. package/lib/types/api/attendance.d.ts +63 -0
  10. package/lib/types/api/attendance.d.ts.map +1 -0
  11. package/lib/types/api/attendance.js +8 -0
  12. package/lib/types/api/attendance.js.map +1 -0
  13. package/lib/types/api/badge.d.ts +233 -0
  14. package/lib/types/api/badge.d.ts.map +1 -0
  15. package/lib/types/api/badge.js +19 -0
  16. package/lib/types/api/badge.js.map +1 -0
  17. package/lib/types/api/blackboard.d.ts +17 -0
  18. package/lib/types/api/blackboard.d.ts.map +1 -0
  19. package/lib/types/api/blackboard.js +6 -0
  20. package/lib/types/api/blackboard.js.map +1 -0
  21. package/lib/types/api/calendar.d.ts +621 -0
  22. package/lib/types/api/calendar.d.ts.map +1 -0
  23. package/lib/types/api/calendar.js +57 -0
  24. package/lib/types/api/calendar.js.map +1 -0
  25. package/lib/types/api/card.d.ts +185 -0
  26. package/lib/types/api/card.d.ts.map +1 -0
  27. package/lib/types/api/card.js +13 -0
  28. package/lib/types/api/card.js.map +1 -0
  29. package/lib/types/api/conference.d.ts +404 -0
  30. package/lib/types/api/conference.d.ts.map +1 -0
  31. package/lib/types/api/conference.js +60 -0
  32. package/lib/types/api/conference.js.map +1 -0
  33. package/lib/types/api/connector.d.ts +79 -0
  34. package/lib/types/api/connector.d.ts.map +1 -0
  35. package/lib/types/api/connector.js +8 -0
  36. package/lib/types/api/connector.js.map +1 -0
  37. package/lib/types/api/contact.d.ts +40 -0
  38. package/lib/types/api/contact.d.ts.map +1 -0
  39. package/lib/types/api/contact.js +9 -0
  40. package/lib/types/api/contact.js.map +1 -0
  41. package/lib/types/api/convFile.d.ts +135 -0
  42. package/lib/types/api/convFile.d.ts.map +1 -0
  43. package/lib/types/api/convFile.js +9 -0
  44. package/lib/types/api/convFile.js.map +1 -0
  45. package/lib/types/api/crm.d.ts +662 -0
  46. package/lib/types/api/crm.d.ts.map +1 -0
  47. package/lib/types/api/crm.js +59 -0
  48. package/lib/types/api/crm.js.map +1 -0
  49. package/lib/types/api/customerService.d.ts +128 -0
  50. package/lib/types/api/customerService.d.ts.map +1 -0
  51. package/lib/types/api/customerService.js +13 -0
  52. package/lib/types/api/customerService.js.map +1 -0
  53. package/lib/types/api/datacenter.d.ts +506 -0
  54. package/lib/types/api/datacenter.d.ts.map +1 -0
  55. package/lib/types/api/datacenter.js +61 -0
  56. package/lib/types/api/datacenter.js.map +1 -0
  57. package/lib/types/api/devicemng.d.ts +161 -0
  58. package/lib/types/api/devicemng.d.ts.map +1 -0
  59. package/lib/types/api/devicemng.js +20 -0
  60. package/lib/types/api/devicemng.js.map +1 -0
  61. package/lib/types/api/diot.d.ts +13 -0
  62. package/lib/types/api/diot.d.ts.map +1 -0
  63. package/lib/types/api/diot.js +4 -0
  64. package/lib/types/api/diot.js.map +1 -0
  65. package/lib/types/api/doc.d.ts +141 -0
  66. package/lib/types/api/doc.d.ts.map +1 -0
  67. package/lib/types/api/doc.js +27 -0
  68. package/lib/types/api/doc.js.map +1 -0
  69. package/lib/types/api/drive.d.ts +88 -0
  70. package/lib/types/api/drive.d.ts.map +1 -0
  71. package/lib/types/api/drive.js +11 -0
  72. package/lib/types/api/drive.js.map +1 -0
  73. package/lib/types/api/edu.d.ts +23 -0
  74. package/lib/types/api/edu.d.ts.map +1 -0
  75. package/lib/types/api/edu.js +4 -0
  76. package/lib/types/api/edu.js.map +1 -0
  77. package/lib/types/api/esign.d.ts +34 -0
  78. package/lib/types/api/esign.d.ts.map +1 -0
  79. package/lib/types/api/esign.js +7 -0
  80. package/lib/types/api/esign.js.map +1 -0
  81. package/lib/types/api/exclusive.d.ts +304 -0
  82. package/lib/types/api/exclusive.d.ts.map +1 -0
  83. package/lib/types/api/exclusive.js +27 -0
  84. package/lib/types/api/exclusive.js.map +1 -0
  85. package/lib/types/api/h3yun.d.ts +438 -0
  86. package/lib/types/api/h3yun.d.ts.map +1 -0
  87. package/lib/types/api/h3yun.js +33 -0
  88. package/lib/types/api/h3yun.js.map +1 -0
  89. package/lib/types/api/hrm.d.ts +215 -0
  90. package/lib/types/api/hrm.d.ts.map +1 -0
  91. package/lib/types/api/hrm.js +20 -0
  92. package/lib/types/api/hrm.js.map +1 -0
  93. package/lib/types/api/im.d.ts +773 -0
  94. package/lib/types/api/im.d.ts.map +1 -0
  95. package/lib/types/api/im.js +72 -0
  96. package/lib/types/api/im.js.map +1 -0
  97. package/lib/types/api/industry.d.ts +118 -0
  98. package/lib/types/api/industry.d.ts.map +1 -0
  99. package/lib/types/api/industry.js +14 -0
  100. package/lib/types/api/industry.js.map +1 -0
  101. package/lib/types/api/jzcrm.d.ts +255 -0
  102. package/lib/types/api/jzcrm.d.ts.map +1 -0
  103. package/lib/types/api/jzcrm.js +18 -0
  104. package/lib/types/api/jzcrm.js.map +1 -0
  105. package/lib/types/api/link.d.ts +73 -0
  106. package/lib/types/api/link.d.ts.map +1 -0
  107. package/lib/types/api/link.js +9 -0
  108. package/lib/types/api/link.js.map +1 -0
  109. package/lib/types/api/live.d.ts +132 -0
  110. package/lib/types/api/live.d.ts.map +1 -0
  111. package/lib/types/api/live.js +13 -0
  112. package/lib/types/api/live.js.map +1 -0
  113. package/lib/types/api/microApp.d.ts +240 -0
  114. package/lib/types/api/microApp.d.ts.map +1 -0
  115. package/lib/types/api/microApp.js +29 -0
  116. package/lib/types/api/microApp.js.map +1 -0
  117. package/lib/types/api/oapi.d.ts +3362 -0
  118. package/lib/types/api/oapi.d.ts.map +1 -0
  119. package/lib/types/api/oapi.js +247 -0
  120. package/lib/types/api/oapi.js.map +1 -0
  121. package/lib/types/api/oauth2.d.ts +115 -0
  122. package/lib/types/api/oauth2.d.ts.map +1 -0
  123. package/lib/types/api/oauth2.js +12 -0
  124. package/lib/types/api/oauth2.js.map +1 -0
  125. package/lib/types/api/pedia.d.ts +186 -0
  126. package/lib/types/api/pedia.d.ts.map +1 -0
  127. package/lib/types/api/pedia.js +13 -0
  128. package/lib/types/api/pedia.js.map +1 -0
  129. package/lib/types/api/project.d.ts +1119 -0
  130. package/lib/types/api/project.d.ts.map +1 -0
  131. package/lib/types/api/project.js +135 -0
  132. package/lib/types/api/project.js.map +1 -0
  133. package/lib/types/api/resident.d.ts +107 -0
  134. package/lib/types/api/resident.d.ts.map +1 -0
  135. package/lib/types/api/resident.js +10 -0
  136. package/lib/types/api/resident.js.map +1 -0
  137. package/lib/types/api/robot.d.ts +256 -0
  138. package/lib/types/api/robot.d.ts.map +1 -0
  139. package/lib/types/api/robot.js +21 -0
  140. package/lib/types/api/robot.js.map +1 -0
  141. package/lib/types/api/rooms.d.ts +256 -0
  142. package/lib/types/api/rooms.d.ts.map +1 -0
  143. package/lib/types/api/rooms.js +23 -0
  144. package/lib/types/api/rooms.js.map +1 -0
  145. package/lib/types/api/serviceGroup.d.ts +176 -0
  146. package/lib/types/api/serviceGroup.d.ts.map +1 -0
  147. package/lib/types/api/serviceGroup.js +15 -0
  148. package/lib/types/api/serviceGroup.js.map +1 -0
  149. package/lib/types/api/storage.d.ts +1241 -0
  150. package/lib/types/api/storage.d.ts.map +1 -0
  151. package/lib/types/api/storage.js +128 -0
  152. package/lib/types/api/storage.js.map +1 -0
  153. package/lib/types/api/swform.d.ts +71 -0
  154. package/lib/types/api/swform.d.ts.map +1 -0
  155. package/lib/types/api/swform.js +8 -0
  156. package/lib/types/api/swform.js.map +1 -0
  157. package/lib/types/api/todo.d.ts +169 -0
  158. package/lib/types/api/todo.d.ts.map +1 -0
  159. package/lib/types/api/todo.js +16 -0
  160. package/lib/types/api/todo.js.map +1 -0
  161. package/lib/types/api/wiki.d.ts +195 -0
  162. package/lib/types/api/wiki.d.ts.map +1 -0
  163. package/lib/types/api/wiki.js +11 -0
  164. package/lib/types/api/wiki.js.map +1 -0
  165. package/lib/types/api/workbench.d.ts +46 -0
  166. package/lib/types/api/workbench.d.ts.map +1 -0
  167. package/lib/types/api/workbench.js +14 -0
  168. package/lib/types/api/workbench.js.map +1 -0
  169. package/lib/types/api/yida.d.ts +1838 -0
  170. package/lib/types/api/yida.d.ts.map +1 -0
  171. package/lib/types/api/yida.js +103 -0
  172. package/lib/types/api/yida.js.map +1 -0
  173. package/lib/types/bot.d.ts +62 -0
  174. package/lib/types/bot.d.ts.map +1 -0
  175. package/lib/types/bot.js +134 -0
  176. package/lib/types/bot.js.map +1 -0
  177. package/lib/types/config.d.ts +47 -0
  178. package/lib/types/config.d.ts.map +1 -0
  179. package/lib/types/config.js +53 -0
  180. package/lib/types/config.js.map +1 -0
  181. package/lib/types/decode.d.ts +36 -0
  182. package/lib/types/decode.d.ts.map +1 -0
  183. package/lib/types/decode.js +200 -0
  184. package/lib/types/decode.js.map +1 -0
  185. package/lib/types/errors.d.ts +77 -0
  186. package/lib/types/errors.d.ts.map +1 -0
  187. package/lib/types/errors.js +249 -0
  188. package/lib/types/errors.js.map +1 -0
  189. package/lib/types/index.d.ts +22 -0
  190. package/lib/types/index.d.ts.map +1 -0
  191. package/lib/types/index.js +22 -0
  192. package/lib/types/index.js.map +1 -0
  193. package/lib/types/internal.d.ts +15 -0
  194. package/lib/types/internal.d.ts.map +1 -0
  195. package/lib/types/internal.js +57 -0
  196. package/lib/types/internal.js.map +1 -0
  197. package/lib/types/media.d.ts +57 -0
  198. package/lib/types/media.d.ts.map +1 -0
  199. package/lib/types/media.js +99 -0
  200. package/lib/types/media.js.map +1 -0
  201. package/lib/types/modes/markdown.d.ts +12 -0
  202. package/lib/types/modes/markdown.d.ts.map +1 -0
  203. package/lib/types/modes/markdown.js +148 -0
  204. package/lib/types/modes/markdown.js.map +1 -0
  205. package/lib/types/modes/shared.d.ts +183 -0
  206. package/lib/types/modes/shared.d.ts.map +1 -0
  207. package/lib/types/modes/shared.js +358 -0
  208. package/lib/types/modes/shared.js.map +1 -0
  209. package/lib/types/request.d.ts +63 -0
  210. package/lib/types/request.d.ts.map +1 -0
  211. package/lib/types/request.js +182 -0
  212. package/lib/types/request.js.map +1 -0
  213. package/lib/types/send.d.ts +38 -0
  214. package/lib/types/send.d.ts.map +1 -0
  215. package/lib/types/send.js +128 -0
  216. package/lib/types/send.js.map +1 -0
  217. package/lib/types/token.d.ts +32 -0
  218. package/lib/types/token.d.ts.map +1 -0
  219. package/lib/types/token.js +62 -0
  220. package/lib/types/token.js.map +1 -0
  221. package/lib/types/transport/stream.d.ts +89 -0
  222. package/lib/types/transport/stream.d.ts.map +1 -0
  223. package/lib/types/transport/stream.js +345 -0
  224. package/lib/types/transport/stream.js.map +1 -0
  225. package/lib/types/transport/webhook.d.ts +54 -0
  226. package/lib/types/transport/webhook.d.ts.map +1 -0
  227. package/lib/types/transport/webhook.js +159 -0
  228. package/lib/types/transport/webhook.js.map +1 -0
  229. package/lib/types/types/index.d.ts +150 -0
  230. package/lib/types/types/index.d.ts.map +1 -0
  231. package/lib/types/types/index.js +43 -0
  232. package/lib/types/types/index.js.map +1 -0
  233. package/package.json +61 -3
  234. package/src/api/.eslintrc.yml +2 -0
  235. package/src/api/alitrip.ts +467 -0
  236. package/src/api/attendance.ts +81 -0
  237. package/src/api/badge.ts +285 -0
  238. package/src/api/blackboard.ts +28 -0
  239. package/src/api/calendar.ts +817 -0
  240. package/src/api/card.ts +215 -0
  241. package/src/api/conference.ts +561 -0
  242. package/src/api/connector.ts +97 -0
  243. package/src/api/contact.ts +56 -0
  244. package/src/api/convFile.ts +166 -0
  245. package/src/api/crm.ts +830 -0
  246. package/src/api/customerService.ts +156 -0
  247. package/src/api/datacenter.ts +672 -0
  248. package/src/api/devicemng.ts +202 -0
  249. package/src/api/diot.ts +19 -0
  250. package/src/api/doc.ts +232 -0
  251. package/src/api/drive.ts +109 -0
  252. package/src/api/edu.ts +30 -0
  253. package/src/api/esign.ts +44 -0
  254. package/src/api/exclusive.ts +372 -0
  255. package/src/api/h3yun.ts +537 -0
  256. package/src/api/hrm.ts +272 -0
  257. package/src/api/im.ts +978 -0
  258. package/src/api/industry.ts +153 -0
  259. package/src/api/jzcrm.ts +304 -0
  260. package/src/api/link.ts +94 -0
  261. package/src/api/live.ts +162 -0
  262. package/src/api/microApp.ts +309 -0
  263. package/src/api/oapi.ts +4083 -0
  264. package/src/api/oauth2.ts +146 -0
  265. package/src/api/pedia.ts +222 -0
  266. package/src/api/project.ts +1519 -0
  267. package/src/api/resident.ts +133 -0
  268. package/src/api/robot.ts +326 -0
  269. package/src/api/rooms.ts +334 -0
  270. package/src/api/serviceGroup.ts +216 -0
  271. package/src/api/storage.ts +1701 -0
  272. package/src/api/swform.ts +94 -0
  273. package/src/api/todo.ts +220 -0
  274. package/src/api/wiki.ts +231 -0
  275. package/src/api/workbench.ts +73 -0
  276. package/src/api/yida.ts +2165 -0
  277. package/src/bot.ts +211 -0
  278. package/src/config.ts +88 -0
  279. package/src/decode.ts +250 -0
  280. package/src/errors.ts +282 -0
  281. package/src/index.ts +82 -0
  282. package/src/internal.ts +60 -0
  283. package/src/media.ts +149 -0
  284. package/src/modes/markdown.ts +173 -0
  285. package/src/modes/shared.ts +473 -0
  286. package/src/request.ts +262 -0
  287. package/src/send.ts +195 -0
  288. package/src/token.ts +72 -0
  289. package/src/transport/stream.ts +436 -0
  290. package/src/transport/webhook.ts +198 -0
  291. package/src/types/index.ts +165 -0
  292. package/README.md +0 -3
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The single `markdown` mode: DingTalk message markdown.
3
+ *
4
+ * Native tags are the ones DingTalk's markdown subset renders (text, formatting, links, mentions as plain text, headings,
5
+ * lists, quotes, code) plus the media that travels as its own message. Everything else takes the core fallback and is
6
+ * reported as degraded: an ActionCard's buttons are all jump links, so no second mode could carry more.
7
+ */
8
+
9
+ import { defineMode, ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core'
10
+ import type { Mode } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type { Element } from '@deepseek-ai/satori-element'
12
+ import {
13
+ assembleDraft,
14
+ checkDraft,
15
+ DINGTALK_LIMITS,
16
+ escape,
17
+ mediaNode,
18
+ serializeDraft,
19
+ } from './shared.ts'
20
+ import type { DingtalkModeTypes, DingtalkNode } from './shared.ts'
21
+
22
+ /** A text node. */
23
+ function text(content: string): DingtalkNode {
24
+ return { type: 'text', content }
25
+ }
26
+
27
+ /**
28
+ * Prefix every line of a subtree with the quote marker.
29
+ * @param nodes - rendered children of the quote block.
30
+ * @returns the same content with `> ` at the start of every line.
31
+ */
32
+ function quoteLines(nodes: readonly DingtalkNode[]): DingtalkNode[] {
33
+ const quoted: DingtalkNode[] = []
34
+ let atLineStart = true
35
+ for (const node of nodes) {
36
+ if (node.type === 'break') {
37
+ // A paragraph inside the quote closes its line with a break node, so the next text node starts a line.
38
+ atLineStart = true
39
+ quoted.push(node)
40
+ continue
41
+ }
42
+ if (node.type !== 'text') {
43
+ quoted.push(node)
44
+ continue
45
+ }
46
+ let content = ''
47
+ for (const char of node.content) {
48
+ if (atLineStart && char !== '\n') content += '> '
49
+ content += char
50
+ atLineStart = char === '\n'
51
+ }
52
+ quoted.push(text(content))
53
+ }
54
+ return quoted
55
+ }
56
+
57
+ /**
58
+ * The rendered children without the leading break a container may add.
59
+ * @param nodes - rendered children.
60
+ * @returns the children, with a leading break removed.
61
+ */
62
+ function withoutLeadingBreaks(nodes: readonly DingtalkNode[]): DingtalkNode[] {
63
+ return nodes[0]?.type === 'break' ? nodes.slice(1) : [...nodes]
64
+ }
65
+
66
+ /** A block element: one line start, its content, and a closing line break. */
67
+ function block(nodes: readonly DingtalkNode[]): DingtalkNode[] {
68
+ return [{ type: 'break' }, ...withoutLeadingBreaks(nodes), { type: 'break' }]
69
+ }
70
+
71
+ /** A heading line: `#` repeated for the level, then the content on one line. */
72
+ function heading(
73
+ level: number,
74
+ nodes: readonly DingtalkNode[],
75
+ ): DingtalkNode[] {
76
+ return [
77
+ { type: 'break' },
78
+ text(`${'#'.repeat(level)} `),
79
+ ...withoutLeadingBreaks(nodes),
80
+ { type: 'break' },
81
+ ]
82
+ }
83
+
84
+ /** Build the `markdown` mode. */
85
+ export function createMarkdownMode(): Mode<DingtalkModeTypes> {
86
+ const elements = new ElementRegistry<DingtalkModeTypes>()
87
+ .register('text', (el) => text(escape(el.attrs.content)))
88
+ .register('p', (el, ctx) => block(ctx.render(el.children)))
89
+ .register('br', () => text('\n'))
90
+ .register('b', (el, ctx) => [
91
+ text('**'),
92
+ ...ctx.render(el.children),
93
+ text('**'),
94
+ ])
95
+ .register('i', (el, ctx) => [
96
+ text('*'),
97
+ ...ctx.render(el.children),
98
+ text('*'),
99
+ ])
100
+ .register('a', (el, ctx) => {
101
+ const children = ctx.render(el.children)
102
+ const media = children.filter((node) => node.type === 'media')
103
+ const body = children.filter((node) => node.type === 'text')
104
+ // A link carries a label; a media element wrapped by one leaves the text run and keeps the URL as its label.
105
+ const label = body.length === 0 ? [text(escape(el.attrs.href))] : body
106
+ return [
107
+ text('['),
108
+ ...label,
109
+ text(`](${encodeURI(el.attrs.href)})`),
110
+ ...media,
111
+ ]
112
+ })
113
+ .register('at', (el) => text(`@${el.attrs.id ?? ''}`), {
114
+ variants: ['user'],
115
+ })
116
+ .register('h1', (el, ctx) => heading(1, ctx.render(el.children)))
117
+ .register('h2', (el, ctx) => heading(2, ctx.render(el.children)))
118
+ .register('h3', (el, ctx) => heading(3, ctx.render(el.children)))
119
+ .register('h4', (el, ctx) => heading(4, ctx.render(el.children)))
120
+ .register('h5', (el, ctx) => heading(5, ctx.render(el.children)))
121
+ .register('h6', (el, ctx) => heading(6, ctx.render(el.children)))
122
+ .register('ul', (el, ctx) => block(ctx.render(el.children)))
123
+ .register('ol', (el, ctx) => block(ctx.render(el.children)))
124
+ .register('li', (el, ctx) => {
125
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
126
+ // DingTalk's client numbers an ordered list itself, so every item is written as `1. ` (the upstream encoder's
127
+ // choice); an unordered item gets a dash.
128
+ const marker = parent?.type === 'ol' ? '1. ' : '- '
129
+ return [
130
+ { type: 'break' },
131
+ text(marker),
132
+ ...withoutLeadingBreaks(ctx.render(el.children)),
133
+ { type: 'break' },
134
+ ]
135
+ })
136
+ .register('blockquote', (el, ctx) =>
137
+ block(quoteLines(ctx.render(el.children))),
138
+ )
139
+ .register('code', (el, ctx) => [
140
+ // Markdown is not parsed inside code, so its text stays unescaped; a backtick would close the span early.
141
+ text(`\`${ctx.text(el.children).replaceAll('`', '\u200B')}\``),
142
+ ])
143
+ .register(
144
+ 'pre',
145
+ (el, ctx) => [
146
+ { type: 'break' },
147
+ text(`\`\`\`${el.attrs.lang ?? ''}\n`),
148
+ // As with inline code, a fenced block carries the text as written; markup escaping would show in the code.
149
+ text(ctx.text(el.children)),
150
+ text('\n```'),
151
+ { type: 'break' },
152
+ ],
153
+ { variants: ['lang'] },
154
+ )
155
+ .register('img', (el: Element<'img'>, ctx) => mediaNode(el, ctx), {
156
+ variants: ['inline'],
157
+ })
158
+ .register('audio', (el: Element<'audio'>, ctx) => mediaNode(el, ctx))
159
+ .register('video', (el: Element<'video'>, ctx) => mediaNode(el, ctx))
160
+ .register('file', (el: Element<'file'>, ctx) => mediaNode(el, ctx))
161
+
162
+ return defineMode<DingtalkModeTypes>()({
163
+ id: 'markdown',
164
+ elements,
165
+ limits: {
166
+ 'limit.payload.bytes': DINGTALK_LIMITS.payloadBytes,
167
+ 'limit.delete.window': DINGTALK_LIMITS.deleteWindowMs,
168
+ },
169
+ assemble: (nodes) => assembleDraft(nodes),
170
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx),
171
+ check: (draft) => checkDraft(draft),
172
+ })
173
+ }
@@ -0,0 +1,473 @@
1
+ /**
2
+ * Nodes, drafts, payloads and text rules of the single `markdown` mode.
3
+ *
4
+ * DingTalk renders one body per outgoing message from `msgKey` + `msgParam`, and a message carries at most one media
5
+ * item, so media leaves the text run and becomes a message of its own (as the upstream encoder did by splitting an image
6
+ * out of the markdown).
7
+ */
8
+
9
+ import type {
10
+ LimitViolation,
11
+ ModeTypes,
12
+ Prepared,
13
+ RenderContext,
14
+ ResourceKind,
15
+ ResourceRef,
16
+ SerializeContext,
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
+
21
+ /** Zero-width non-joiner: a body the platform accepts where the content is empty. */
22
+ export const ZERO_WIDTH = '\u2060'
23
+
24
+ /** Media kinds DingTalk's `sample*` templates distinguish; one per core resource kind. */
25
+ export type DingtalkMediaKind = ResourceKind
26
+
27
+ /** One media attachment lifted out of the text run. */
28
+ export interface DingtalkMedia {
29
+ kind: DingtalkMediaKind
30
+ ref: ResourceRef
31
+ /** `name` attribute of the element, for the file-name field. */
32
+ name?: string
33
+ /** `duration` attribute of the element, in milliseconds, passed through as the platform's string. */
34
+ duration?: number
35
+ }
36
+
37
+ /** One node a mode handler produces. */
38
+ export type DingtalkNode =
39
+ | { type: 'text'; content: string }
40
+ /** A line break that closes the current line; no effect when the run already ends one. */
41
+ | { type: 'break' }
42
+ | { type: 'media'; media: DingtalkMedia }
43
+
44
+ /** One platform message before resource resolution. */
45
+ export type DingtalkDraft =
46
+ { kind: 'text'; text: string } | { kind: 'media'; media: DingtalkMedia }
47
+
48
+ /**
49
+ * Exact request data of one platform message.
50
+ *
51
+ * `msgParam` is the platform's template body; the generated send layer stringifies it and puts it into `msgParam` of the
52
+ * request. It is not flattened here: the transport needs the object to measure the byte limit.
53
+ */
54
+ export type DingtalkPayload =
55
+ | {
56
+ kind: 'text'
57
+ msgKey: 'sampleMarkdown'
58
+ msgParam: { title: string; text: string }
59
+ }
60
+ | { kind: 'image'; msgKey: 'sampleImageMsg'; msgParam: { photoURL: string } }
61
+ | {
62
+ kind: 'audio'
63
+ msgKey: 'sampleAudio'
64
+ msgParam: { mediaId: string; duration: string }
65
+ }
66
+ | {
67
+ kind: 'video'
68
+ msgKey: 'sampleVideo'
69
+ msgParam: {
70
+ duration: string
71
+ videoMediaId: string
72
+ videoType: string
73
+ picMediaId?: string
74
+ }
75
+ }
76
+ | {
77
+ kind: 'file'
78
+ msgKey: 'sampleFile'
79
+ msgParam: { mediaId: string; fileName: string; fileType: string }
80
+ }
81
+
82
+ /** Mode types of the `markdown` mode. */
83
+ export interface DingtalkModeTypes extends ModeTypes {
84
+ node: DingtalkNode
85
+ draft: DingtalkDraft
86
+ payload: DingtalkPayload
87
+ }
88
+
89
+ /** The two bounds the platform documents, and nothing else. */
90
+ export const DINGTALK_LIMITS = {
91
+ /**
92
+ * `msgParam` is capped at 15000 bytes ("长度限制 15000 字节以内"). The adapter measures the UTF-8 bytes of the JSON
93
+ * body it sends; a platform that counted characters instead would only make an accepted body shorter.
94
+ */
95
+ payloadBytes: 15_000,
96
+ /** A single-chat message can be recalled within 24 hours; the group endpoint documents no other window. */
97
+ deleteWindowMs: 24 * 60 * 60 * 1_000,
98
+ } as const
99
+
100
+ /** Title length; the notification and the conversation list show it. */
101
+ const TITLE_LENGTH = 40
102
+
103
+ /**
104
+ * Escape text so DingTalk markdown renders it literally.
105
+ *
106
+ * Four rules, identical to the upstream encoder's: a markup character gets a zero-width space, markdown punctuation
107
+ * gets a backslash, a list marker after a space is broken up, and four leading spaces (a code block) are replaced.
108
+ *
109
+ * @param text - the text of a `text` element.
110
+ * @returns the text to append to the markdown body.
111
+ */
112
+ export function escape(text: string): string {
113
+ return text
114
+ .replace(/(?<!\u200B)[*_~`]/g, '\u200B$&')
115
+ .replace(/([\\`*_{}[\]\-(#!>])/g, '\\$&')
116
+ .replace(/([\-*]|\d\.) /g, '\u200B$&')
117
+ .replace(/^(\s{4})/gm, '\u200B&nbsp;&nbsp;&nbsp;&nbsp;')
118
+ }
119
+
120
+ /**
121
+ * Undo {@link escape}.
122
+ *
123
+ * DingTalk never echoes what the adapter sent, so this exists for the inbound side and to keep a round trip of the
124
+ * upstream rules testable.
125
+ *
126
+ * @param text - escaped text.
127
+ * @returns the text as it was written.
128
+ */
129
+ export function unescape(text: string): string {
130
+ return text.replace(/\u200B([*_~`])/g, '$1')
131
+ }
132
+
133
+ /** The visible text of one line of markdown, with the notation this adapter emits removed. */
134
+ function plainLine(line: string): string {
135
+ return line
136
+ .replace(/\u200B/g, '')
137
+ .replace(/\\(.)/g, '$1')
138
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
139
+ .replace(/`/g, '')
140
+ .replace(/\*\*|__/g, '')
141
+ .replace(/[*_~]/g, '')
142
+ .replace(/^#+\s*/, '')
143
+ .replace(/^\d+\.\s+/, '')
144
+ .replace(/^[-*]\s+/, '')
145
+ .replace(/^>\s?/, '')
146
+ }
147
+
148
+ /**
149
+ * The `title` the `sampleMarkdown` template requires.
150
+ *
151
+ * The error table names `miss.param.markdownTotitle`, so the field is sent even though the upstream adapter left it
152
+ * out: the first non-empty line, its markdown notation removed, cut to 40 characters.
153
+ *
154
+ * @param text - the body of the draft, before the paragraph newlines are doubled.
155
+ * @returns the title, or a zero-width body when the message has no visible text.
156
+ */
157
+ export function titleOf(text: string): string {
158
+ const line = text.split('\n').find((item) => item.trim() !== '')
159
+ if (line === undefined) return ZERO_WIDTH
160
+ const plain = plainLine(line).trim()
161
+ if (plain === '') return ZERO_WIDTH
162
+ // Code points, not UTF-16 units: a title must not end in half a surrogate pair.
163
+ return [...plain].slice(0, TITLE_LENGTH).join('')
164
+ }
165
+
166
+ /** DingTalk markdown separates paragraphs with a blank line; this is the only place newlines are doubled. */
167
+ function paragraphBreaks(text: string): string {
168
+ return text.replace(/\n/g, '\n\n')
169
+ }
170
+
171
+ /**
172
+ * Media element → the node of its own platform message.
173
+ *
174
+ * A DingTalk message carries one media item, so media never stays inside a text run. Media that stood in phrasing
175
+ * content (`<p>`, a heading, a link, an inline wrapper) is reported as `moved`: the caller sees the text plus an extra
176
+ * media message instead of one block.
177
+ *
178
+ * @param el - one of `img`/`audio`/`video`/`file`.
179
+ * @param ctx - render context of the mode.
180
+ * @returns the media node, published after the text run it was found in.
181
+ */
182
+ export function mediaNode(
183
+ el: Element<'img'> | Element<'audio'> | Element<'video'> | Element<'file'>,
184
+ ctx: RenderContext<DingtalkModeTypes>,
185
+ ): DingtalkNode {
186
+ const parent = ctx.ancestors[ctx.ancestors.length - 1]
187
+ if (parent !== undefined && isPhrasingContainer(parent.type)) {
188
+ ctx.report.moved.push({
189
+ tag: el.type,
190
+ reason: 'dingtalk-media-split',
191
+ path: ctx.stableId(el),
192
+ })
193
+ }
194
+ switch (el.type) {
195
+ case 'img':
196
+ return {
197
+ type: 'media',
198
+ media: { kind: 'image', ref: ctx.resource('image', el.attrs.src, {}) },
199
+ }
200
+ case 'audio':
201
+ return {
202
+ type: 'media',
203
+ media: audioMedia(el, ctx),
204
+ }
205
+ case 'video':
206
+ return {
207
+ type: 'media',
208
+ media: {
209
+ kind: 'video',
210
+ ref: ctx.resource('video', el.attrs.src, {
211
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
212
+ ...(el.attrs.duration === undefined
213
+ ? {}
214
+ : { duration: el.attrs.duration }),
215
+ }),
216
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
217
+ ...(el.attrs.duration === undefined
218
+ ? {}
219
+ : { duration: el.attrs.duration }),
220
+ },
221
+ }
222
+ case 'file':
223
+ return {
224
+ type: 'media',
225
+ media: {
226
+ kind: 'file',
227
+ ref: ctx.resource(
228
+ 'file',
229
+ el.attrs.src,
230
+ el.attrs.name === undefined ? {} : { name: el.attrs.name },
231
+ ),
232
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
233
+ },
234
+ }
235
+ }
236
+ }
237
+
238
+ /** Audio has the same fields as video without a poster, split out so the switch above stays readable. */
239
+ function audioMedia(
240
+ el: Element<'audio'>,
241
+ ctx: RenderContext<DingtalkModeTypes>,
242
+ ): DingtalkMedia {
243
+ return {
244
+ kind: 'audio',
245
+ ref: ctx.resource('audio', el.attrs.src, {
246
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
247
+ ...(el.attrs.duration === undefined
248
+ ? {}
249
+ : { duration: el.attrs.duration }),
250
+ }),
251
+ ...(el.attrs.name === undefined ? {} : { name: el.attrs.name }),
252
+ ...(el.attrs.duration === undefined ? {} : { duration: el.attrs.duration }),
253
+ }
254
+ }
255
+
256
+ /** One text run being accumulated, in send order. */
257
+ class Run {
258
+ private buffer = ''
259
+
260
+ /** The text so far, and the media that has to go out before the next text draft. */
261
+ readonly drafts: DingtalkDraft[] = []
262
+
263
+ /** Append text. */
264
+ push(content: string): void {
265
+ this.buffer += content
266
+ }
267
+
268
+ /** Close the current line unless it is already closed. */
269
+ breakLine(): void {
270
+ if (this.buffer === '' || this.buffer.endsWith('\n')) return
271
+ this.buffer += '\n'
272
+ }
273
+
274
+ /** Emit the accumulated text as a draft of its own, then the media. */
275
+ flush(next?: DingtalkMedia): void {
276
+ const text = this.buffer.trim()
277
+ this.buffer = ''
278
+ if (text !== '') this.drafts.push({ kind: 'text', text })
279
+ if (next !== undefined) this.drafts.push({ kind: 'media', media: next })
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Fold a node stream into platform messages: a text draft per run, and one draft per media item.
285
+ *
286
+ * DingTalk sends one media item per message, so a run of text followed by an image is two platform messages; the run is
287
+ * split rather than merged into the image, because no template carries both.
288
+ *
289
+ * @param nodes - rendered nodes, in source order.
290
+ * @returns at least one draft; empty content yields an empty text draft.
291
+ */
292
+ export function assembleDraft(nodes: readonly DingtalkNode[]): DingtalkDraft[] {
293
+ const run = new Run()
294
+ for (const node of nodes) {
295
+ switch (node.type) {
296
+ case 'text':
297
+ run.push(node.content)
298
+ break
299
+ case 'break':
300
+ run.breakLine()
301
+ break
302
+ case 'media':
303
+ run.flush(node.media)
304
+ break
305
+ }
306
+ }
307
+ run.flush()
308
+ if (run.drafts.length === 0) run.drafts.push({ kind: 'text', text: '' })
309
+ return run.drafts
310
+ }
311
+
312
+ /** One media item of a prepared draft, and the platform key `prepare` resolved for it. */
313
+ interface ResolvedMedia {
314
+ key: string
315
+ name: string | undefined
316
+ mime: string | undefined
317
+ }
318
+
319
+ /** The upload's own report of a media item (`extra`), when the adapter recorded one. */
320
+ function extraOf(value: unknown): { name?: string; mime?: string } | undefined {
321
+ if (typeof value !== 'object' || value === null) return undefined
322
+ const name =
323
+ 'name' in value && typeof value.name === 'string' ? value.name : undefined
324
+ const mime =
325
+ 'mime' in value && typeof value.mime === 'string' ? value.mime : undefined
326
+ if (name === undefined && mime === undefined) return undefined
327
+ return {
328
+ ...(name === undefined ? {} : { name }),
329
+ ...(mime === undefined ? {} : { mime }),
330
+ }
331
+ }
332
+
333
+ /** Resolve one media item of a prepared draft. */
334
+ function resolvedMedia(
335
+ prepared: Prepared<DingtalkDraft>,
336
+ media: DingtalkMedia,
337
+ ): ResolvedMedia {
338
+ const resolved = prepared.resolved.get(media.ref)
339
+ if (resolved === undefined) {
340
+ throw new Error('dingtalk: media was not prepared before serialize')
341
+ }
342
+ const extra = extraOf(resolved.extra)
343
+ return {
344
+ key: resolved.key,
345
+ name: media.name ?? extra?.name,
346
+ mime: media.ref.meta.mime ?? extra?.mime,
347
+ }
348
+ }
349
+
350
+ /** File extension of a name, without the dot. */
351
+ function extensionOf(name: string | undefined): string | undefined {
352
+ if (name === undefined) return undefined
353
+ const dot = name.lastIndexOf('.')
354
+ if (dot <= 0 || dot === name.length - 1) return undefined
355
+ return name.slice(dot + 1).toLowerCase()
356
+ }
357
+
358
+ /** Media type of a MIME type: the subtype, without any `+suffix`. */
359
+ function subtypeOf(mime: string | undefined): string | undefined {
360
+ if (mime === undefined) return undefined
361
+ const subtype = mime.split(';')[0]!.split('/')[1]
362
+ if (subtype === undefined) return undefined
363
+ return subtype.replace(/\+.*$/, '')
364
+ }
365
+
366
+ /**
367
+ * The `fileType` field of `sampleFile`.
368
+ * @param name - file name of the attachment.
369
+ * @param mime - MIME type the upload detected.
370
+ * @returns the extension of the name, else the MIME subtype, else `file`.
371
+ */
372
+ export function fileTypeOf(
373
+ name: string | undefined,
374
+ mime: string | undefined,
375
+ ): string {
376
+ return extensionOf(name) ?? subtypeOf(mime) ?? 'file'
377
+ }
378
+
379
+ /**
380
+ * Build the request payload of one draft.
381
+ *
382
+ * The paragraph newlines are doubled here and nowhere else: `assemble` keeps single newlines, so a text that already
383
+ * contains them cannot be doubled twice.
384
+ *
385
+ * @param prepared - the draft with every resource resolved.
386
+ * @param _ctx - serialize context (the adapter needs nothing from it; quotes are not rendered, see the design).
387
+ * @returns the exact `msgKey` + `msgParam` pair of the message.
388
+ */
389
+ export function serializeDraft(
390
+ prepared: Prepared<DingtalkDraft>,
391
+ _ctx: SerializeContext,
392
+ ): DingtalkPayload {
393
+ const draft = prepared.draft
394
+ if (draft.kind === 'text') {
395
+ const text = paragraphBreaks(draft.text)
396
+ return {
397
+ kind: 'text',
398
+ msgKey: 'sampleMarkdown',
399
+ msgParam: {
400
+ title: titleOf(draft.text),
401
+ text: text === '' ? ZERO_WIDTH : text,
402
+ },
403
+ }
404
+ }
405
+ const media = resolvedMedia(prepared, draft.media)
406
+ switch (draft.media.kind) {
407
+ case 'image':
408
+ return {
409
+ kind: 'image',
410
+ msgKey: 'sampleImageMsg',
411
+ msgParam: { photoURL: media.key },
412
+ }
413
+ case 'audio':
414
+ return {
415
+ kind: 'audio',
416
+ msgKey: 'sampleAudio',
417
+ msgParam: {
418
+ mediaId: media.key,
419
+ duration: String(draft.media.duration ?? 0),
420
+ },
421
+ }
422
+ case 'video':
423
+ return {
424
+ kind: 'video',
425
+ msgKey: 'sampleVideo',
426
+ msgParam: {
427
+ duration: String(draft.media.duration ?? 0),
428
+ videoMediaId: media.key,
429
+ videoType: 'mp4',
430
+ },
431
+ }
432
+ case 'file':
433
+ return {
434
+ kind: 'file',
435
+ msgKey: 'sampleFile',
436
+ msgParam: {
437
+ mediaId: media.key,
438
+ fileName: media.name ?? 'file',
439
+ fileType: fileTypeOf(media.name, media.mime),
440
+ },
441
+ }
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Hard platform limits of one draft, checked before any request.
447
+ *
448
+ * Only `msgParam` can fail: a text body over 15000 bytes is refused by the platform, and truncating it would silently
449
+ * drop model output. A media item's `msgParam` is a handful of ids and never reaches the bound.
450
+ *
451
+ * @param draft - the assembled draft.
452
+ * @returns every violation the platform would refuse.
453
+ */
454
+ export function checkDraft(draft: DingtalkDraft): LimitViolation[] {
455
+ if (draft.kind !== 'text') return []
456
+ const bytes = Buffer.byteLength(
457
+ JSON.stringify({
458
+ title: titleOf(draft.text),
459
+ text: paragraphBreaks(draft.text) || ZERO_WIDTH,
460
+ }),
461
+ 'utf8',
462
+ )
463
+ if (bytes <= DINGTALK_LIMITS.payloadBytes) return []
464
+ return [
465
+ {
466
+ kind: 'size',
467
+ key: 'limit.payload.bytes',
468
+ limit: DINGTALK_LIMITS.payloadBytes,
469
+ actual: bytes,
470
+ message: `DingTalk accepts ${DINGTALK_LIMITS.payloadBytes} bytes of msgParam, got ${bytes}`,
471
+ },
472
+ ]
473
+ }