@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
package/src/bot.ts ADDED
@@ -0,0 +1,211 @@
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import { Adapter } from '@deepseek-ai/cordis-plugin-im-core'
3
+ import type {
4
+ Mode,
5
+ PrepareContext,
6
+ ResolvedResource,
7
+ ResourceKind,
8
+ ResourceRef,
9
+ SendContext,
10
+ SentPart,
11
+ Target,
12
+ } from '@deepseek-ai/cordis-plugin-im-core'
13
+ import { Config, configError } from './config.ts'
14
+ import { classifyDingtalkError } from './errors.ts'
15
+ import { Internal } from './internal.ts'
16
+ import { downloadUrlOf, uploadMedia } from './media.ts'
17
+ import { createMarkdownMode } from './modes/markdown.ts'
18
+ import type { DingtalkModeTypes } from './modes/shared.ts'
19
+ import { deletePart, sendPayload } from './send.ts'
20
+ import { AccessTokenCache } from './token.ts'
21
+ import { DingtalkStream } from './transport/stream.ts'
22
+ import { DingtalkWebhook } from './transport/webhook.ts'
23
+ // The migrated declarations register their typed methods on `Internal` when they are imported.
24
+ import './types/index.ts'
25
+
26
+ /** The single mode this adapter always registers. */
27
+ export interface DingtalkModes {
28
+ [mode: string]: Mode<DingtalkModeTypes>
29
+ markdown: Mode<DingtalkModeTypes>
30
+ }
31
+
32
+ /** A transport `connect` starts and `disconnect` stops. */
33
+ interface DingtalkTransport {
34
+ start(): Promise<void>
35
+ stop(): Promise<void>
36
+ }
37
+
38
+ /** Message of any caught value, for a log line. */
39
+ function messageOf(error: unknown): string {
40
+ return error instanceof Error ? error.message : String(error)
41
+ }
42
+
43
+ /**
44
+ * DingTalk robot adapter.
45
+ *
46
+ * Identity is the configured `appkey` (DingTalk exposes no robot user id to look up), Stream Mode and the HTTP callback
47
+ * are the two transports, and `markdown` is the only mode: `sampleMarkdown` is the one body template the upstream adapter
48
+ * ever produced, and an ActionCard's buttons are all jump links. Media goes out as its own message, because a DingTalk
49
+ * message carries one media item.
50
+ */
51
+ export class DingtalkBot extends Adapter<Config, DingtalkModes> {
52
+ /** The adapter needs the Satori service and the isolated `http` service. */
53
+ static override inject = ['satori', 'http']
54
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
55
+ static readonly Config = Config
56
+
57
+ readonly modes: DingtalkModes
58
+ readonly modeOrder = ['markdown'] as const
59
+
60
+ /** Full typed REST surface registered by the migrated declarations. */
61
+ override readonly internal: Internal
62
+ /** The application `accessToken` every `/v1.0/*` request carries. */
63
+ readonly tokens: AccessTokenCache
64
+
65
+ private transport: DingtalkTransport | undefined
66
+
67
+ constructor(ctx: Context, config: Config) {
68
+ super(ctx, config, {
69
+ id: `dingtalk:${config.appkey}`,
70
+ platform: 'dingtalk',
71
+ adapter: 'dingtalk',
72
+ })
73
+ this.selfId = config.appkey
74
+ this.user = { id: config.appkey, isBot: true }
75
+ this.internal = new Internal(this)
76
+ this.tokens = new AccessTokenCache(async () => {
77
+ return await this.internal.getAccessToken({
78
+ appKey: config.appkey,
79
+ appSecret: config.secret,
80
+ })
81
+ })
82
+ this.modes = { markdown: createMarkdownMode() }
83
+ this.defineInternalRoute(
84
+ '/messages/:messageId/resources/:index',
85
+ async ({ params, query }) => {
86
+ const code = query.get('code')
87
+ if (code === null || code === '') {
88
+ // Only a source this adapter wrote carries a code; a hand-written path names no readable resource.
89
+ this.ctx.logger.debug(
90
+ 'dingtalk: media %s/%s has no download code',
91
+ params.messageId,
92
+ params.index,
93
+ )
94
+ return new Response(null, { status: 404 })
95
+ }
96
+ return await this.serveMessageFile(params.messageId, params.index, code)
97
+ },
98
+ )
99
+ }
100
+
101
+ override async connect(): Promise<void> {
102
+ const invalid = configError(this.config)
103
+ if (invalid !== undefined) {
104
+ // `Bot.start` only stores a connect failure on `bot.error`, so log it here.
105
+ this.ctx.logger.error('dingtalk: connect failed: %s', invalid.message)
106
+ throw invalid
107
+ }
108
+ this.transport =
109
+ this.config.protocol === 'http'
110
+ ? new DingtalkWebhook(this)
111
+ : new DingtalkStream(this)
112
+ await this.transport.start()
113
+ }
114
+
115
+ override async disconnect(): Promise<void> {
116
+ const transport = this.transport
117
+ this.transport = undefined
118
+ await transport?.stop()
119
+ }
120
+
121
+ /**
122
+ * Upload one outbound attachment to the platform's media endpoint.
123
+ *
124
+ * `media_id` is application-wide and reusable, so the scope is the bot rather than the chat.
125
+ */
126
+ override async upload(
127
+ ref: ResourceRef,
128
+ _scope: string,
129
+ ctx: PrepareContext,
130
+ ): Promise<ResolvedResource> {
131
+ return await uploadMedia(this, ref, ctx)
132
+ }
133
+
134
+ override resourceScope(_target: Target, _kind: ResourceKind): string {
135
+ return this.id
136
+ }
137
+
138
+ override async sendPayload(
139
+ payload: unknown,
140
+ target: Target,
141
+ ctx: SendContext,
142
+ ): Promise<SentPart> {
143
+ return await sendPayload(
144
+ { internal: this.internal, config: this.config },
145
+ payload as Parameters<typeof sendPayload>[1],
146
+ target,
147
+ ctx,
148
+ )
149
+ }
150
+
151
+ override async deletePart(
152
+ part: SentPart,
153
+ handle: Parameters<typeof deletePart>[2],
154
+ ): Promise<void> {
155
+ await deletePart(
156
+ { internal: this.internal, config: this.config },
157
+ part,
158
+ handle,
159
+ )
160
+ }
161
+
162
+ override classify(error: unknown) {
163
+ return classifyDingtalkError(error)
164
+ }
165
+
166
+ /**
167
+ * Resolve one message-media route.
168
+ *
169
+ * The `downloadCode` from the query is exchanged for a signed URL per read and never cached, because the URL is
170
+ * short-lived while a stored message is not. A code or URL the platform no longer accepts answers `502`.
171
+ *
172
+ * @param messageId - platform message id, for the log line only.
173
+ * @param index - media position in the message, for the log line only.
174
+ * @param code - the platform `downloadCode` the source carried.
175
+ * @returns the bytes, or the refusal status.
176
+ */
177
+ private async serveMessageFile(
178
+ messageId: string,
179
+ index: string,
180
+ code: string,
181
+ ): Promise<Response> {
182
+ try {
183
+ const url = await downloadUrlOf(this, code)
184
+ const response = await this.ctx.http(url)
185
+ if (!response.ok) {
186
+ // The signed URL outlived its lifetime, or the file was removed: the stored element cannot be read.
187
+ this.ctx.logger.warn(
188
+ 'dingtalk: media %s/%s answered %s at its signed URL',
189
+ messageId,
190
+ index,
191
+ String(response.status),
192
+ )
193
+ return new Response(null, { status: 502 })
194
+ }
195
+ const headers = new Headers()
196
+ const mime = response.headers.get('content-type')
197
+ if (mime !== null) headers.set('content-type', mime)
198
+ return new Response(response.body, { status: response.status, headers })
199
+ } catch (error) {
200
+ this.ctx.logger.warn(
201
+ 'dingtalk: media %s/%s could not be served: %s',
202
+ messageId,
203
+ index,
204
+ messageOf(error),
205
+ )
206
+ return new Response(null, { status: 502 })
207
+ }
208
+ }
209
+ }
210
+
211
+ export default DingtalkBot
package/src/config.ts ADDED
@@ -0,0 +1,88 @@
1
+ import z from '@deepseek-ai/schemastery'
2
+
3
+ /**
4
+ * How the adapter receives bot messages: DingTalk Stream Mode (an outbound WebSocket, no public address needed) or the
5
+ * HTTP callback (`ctx.webServer` plus a public HTTPS address configured in the developer console).
6
+ */
7
+ export type DingtalkProtocol = 'ws' | 'http'
8
+
9
+ /** One DingTalk internal-application robot. */
10
+ export interface Config {
11
+ /** Client ID (formerly AppKey): `selfId`, `robotCode`, the Stream `clientId`, and one verifier of the callback signature. */
12
+ appkey: string
13
+ /** Client Secret (formerly AppSecret): the Stream `clientSecret`, the `accessToken` request, and the callback HMAC key. */
14
+ secret: string
15
+ protocol: DingtalkProtocol
16
+ /** Inbound route of `protocol: 'http'`: absolute, no trailing slash. */
17
+ path: string
18
+ /** OpenAPI root of the `/v1.0/*` endpoints; the version segment belongs to each request path. */
19
+ apiBaseUrl: string
20
+ /** Root of the legacy `oapi` endpoints, which only the media upload uses. */
21
+ oapiBaseUrl: string
22
+ ws: {
23
+ /** Fast-retry budget of the Stream Mode reconnect loop; it never gives up. */
24
+ retryTimes: number
25
+ /** Delay between dials while the fast-retry budget lasts. */
26
+ retryInterval: number
27
+ /** Delay between dials once the fast-retry budget is spent. */
28
+ retryLazy: number
29
+ }
30
+ }
31
+
32
+ /** Validated DingTalk adapter configuration. */
33
+ export const Config: z<Config> = z.object({
34
+ appkey: z.string().required(),
35
+ secret: z.string().role('secret').required(),
36
+ protocol: z.union(['ws', 'http']).required(),
37
+ path: z.string().default('/dingtalk'),
38
+ apiBaseUrl: z.string().role('url').default('https://api.dingtalk.com'),
39
+ oapiBaseUrl: z.string().role('url').default('https://oapi.dingtalk.com'),
40
+ ws: z
41
+ .object({
42
+ retryTimes: z.natural().default(6),
43
+ retryInterval: z.natural().role('ms').default(5_000),
44
+ retryLazy: z.natural().role('ms').default(60_000),
45
+ })
46
+ .default({}),
47
+ })
48
+
49
+ /**
50
+ * The configuration the adapter cannot work from, as far as it can tell locally.
51
+ *
52
+ * A profile that leaves a credential out, or that points the OpenAPI root at a non-HTTPS origin, is refused when the
53
+ * bot starts (`connect()`) rather than at the first dial or the first callback.
54
+ *
55
+ * @param config - the validated configuration.
56
+ * @returns the configuration error, or undefined when the configuration is usable.
57
+ */
58
+ export function configError(config: Config): Error | undefined {
59
+ if (config.appkey === '') {
60
+ return new Error(
61
+ 'dingtalk: appkey is required (the application Client ID, formerly AppKey)',
62
+ )
63
+ }
64
+ if (config.secret === '') {
65
+ return new Error(
66
+ 'dingtalk: secret is required (the application Client Secret, formerly AppSecret)',
67
+ )
68
+ }
69
+ for (const [name, url] of [
70
+ ['apiBaseUrl', config.apiBaseUrl],
71
+ ['oapiBaseUrl', config.oapiBaseUrl],
72
+ ] as const) {
73
+ if (!url.startsWith('https://')) {
74
+ return new Error(`dingtalk: ${name} must be an https URL, got "${url}"`)
75
+ }
76
+ }
77
+ return undefined
78
+ }
79
+
80
+ /**
81
+ * Normalize an inbound route path: absolute, no trailing slash.
82
+ * @param path - the configured `path`.
83
+ * @returns the pathname to register.
84
+ */
85
+ export function routePath(path: string): string {
86
+ const withSlash = path.startsWith('/') ? path : `/${path}`
87
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') : withSlash
88
+ }
package/src/decode.ts ADDED
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Inbound decoding: one bot-message callback body becomes an intake `Session`.
3
+ *
4
+ * DingTalk pushes six `msgtype`s to a robot (`text`, `richText`, `picture`, `file`, `audio`, `video`); all become one
5
+ * message event. Media elements name the bot's own `satori:` route rather than the platform's signed download URL, so a
6
+ * message read after the URL expired still resolves (the route exchanges the `downloadCode` per read).
7
+ */
8
+
9
+ import { h, normalize } from '@deepseek-ai/cordis-plugin-im-core'
10
+ import type {
11
+ ChatRef,
12
+ Element,
13
+ InboundMessage,
14
+ Session,
15
+ UserRef,
16
+ } from '@deepseek-ai/cordis-plugin-im-core'
17
+ import type { DingtalkBot } from './bot.ts'
18
+ import { mediaSource } from './media.ts'
19
+ import type { Message } from './types/index.ts'
20
+
21
+ /** Adapter-private context carried through `Target.referrer`. */
22
+ export interface DingtalkReferrer {
23
+ /** `conversationId` (`openConversationId` of the group send endpoint). */
24
+ conversationId: string
25
+ /** `1` single chat, `2` group chat. */
26
+ conversationType: string
27
+ /** Id of the message that carried this context. */
28
+ msgId: string
29
+ /** Encrypted id of the robot in this conversation. */
30
+ chatbotUserId: string
31
+ /** Temporary reply address of the conversation; kept for a future passive-reply path. */
32
+ sessionWebhook?: string
33
+ sessionWebhookExpiredTime?: number
34
+ }
35
+
36
+ /** The `errorCode` of a delivery failure body, which carries no message content. */
37
+ function errorCodeOf(body: object): unknown {
38
+ return 'errorCode' in body ? body.errorCode : undefined
39
+ }
40
+
41
+ /** The `errorMessage` of a delivery failure body. */
42
+ function errorMessageOf(body: object): unknown {
43
+ return 'errorMessage' in body ? body.errorMessage : undefined
44
+ }
45
+
46
+ /**
47
+ * Chat of one callback.
48
+ *
49
+ * A group message names its open conversation; a single chat has no conversation id on the send side, so the chat is
50
+ * the staff id the single-chat send endpoint addresses.
51
+ *
52
+ * @param body - the callback body.
53
+ * @param senderId - resolved sender id.
54
+ * @returns the chat reference.
55
+ */
56
+ function chatOf(body: Message, senderId: string): ChatRef {
57
+ if (body.conversationType === '1') return { id: senderId, type: 'direct' }
58
+ return {
59
+ id: body.conversationId,
60
+ type: 'group',
61
+ ...(body.conversationTitle === undefined
62
+ ? {}
63
+ : { name: body.conversationTitle }),
64
+ }
65
+ }
66
+
67
+ /** The sender of one callback: `senderStaffId` exists only for an internal chat of a published robot. */
68
+ function senderOf(body: Message): UserRef {
69
+ return {
70
+ id: body.senderStaffId || body.senderId,
71
+ ...(body.senderNick ? { name: body.senderNick } : {}),
72
+ isBot: false,
73
+ role: body.isAdmin === true ? 'admin' : 'member',
74
+ }
75
+ }
76
+
77
+ /** Mentions of one callback: a group message reaches a robot only when it mentions it. */
78
+ function mentionsOf(body: Message, chat: ChatRef): InboundMessage['mentions'] {
79
+ const users: UserRef[] = []
80
+ for (const at of body.atUsers ?? []) {
81
+ const id = at.staffId || at.dingtalkId
82
+ if (id) users.push({ id })
83
+ }
84
+ // The platform pushes a group message only when the robot is mentioned, and a single chat never needs a mention.
85
+ return { self: chat.type === 'group', all: false, users }
86
+ }
87
+
88
+ /** The `createAt` timestamp, which the platform sends as a string in the documented sample and as a number in practice. */
89
+ function timeOf(body: Message): number {
90
+ const time = Number(body.createAt)
91
+ return Number.isFinite(time) ? time : Date.now()
92
+ }
93
+
94
+ /**
95
+ * One media element of a message, with the source the host reads it through.
96
+ *
97
+ * @param bot - the receiving adapter.
98
+ * @param body - the callback body the element comes from.
99
+ * @param code - the platform `downloadCode` of this media item.
100
+ * @param index - position of the media element in the message content.
101
+ * @returns the element; its `src` carries the code, so the host can resolve it without adapter state.
102
+ */
103
+ function mediaElement(
104
+ bot: DingtalkBot,
105
+ body: Message,
106
+ code: string,
107
+ index: number,
108
+ ): Element {
109
+ const src = mediaSource(bot, body.msgId, index, code)
110
+ switch (body.msgtype) {
111
+ case 'picture':
112
+ return h('img', { src })
113
+ case 'file':
114
+ return h('file', {
115
+ src,
116
+ ...(body.content.fileName ? { name: body.content.fileName } : {}),
117
+ })
118
+ case 'audio':
119
+ return h('audio', {
120
+ src,
121
+ ...(body.content.duration === undefined
122
+ ? {}
123
+ : { duration: body.content.duration }),
124
+ })
125
+ case 'video':
126
+ return h('video', {
127
+ src,
128
+ ...(body.content.duration === undefined
129
+ ? {}
130
+ : { duration: body.content.duration }),
131
+ })
132
+ default:
133
+ return h('img', { src })
134
+ }
135
+ }
136
+
137
+ /** The content tree of one callback, never empty. */
138
+ function decodeContent(bot: DingtalkBot, body: Message): Element<'message'> {
139
+ const nodes: Element[] = []
140
+ let index = 0
141
+ switch (body.msgtype) {
142
+ case 'text':
143
+ nodes.push(h.text(body.text.content))
144
+ break
145
+ case 'richText': {
146
+ for (const item of body.content.richText) {
147
+ // A rich-text item is either a text run or a picture; the picture may arrive under either field name.
148
+ if (item.text) {
149
+ nodes.push(h.text(item.text))
150
+ continue
151
+ }
152
+ const code = item.downloadCode || item.pictureDownloadCode
153
+ if (!code) continue
154
+ nodes.push(mediaElement(bot, body, code, index))
155
+ index += 1
156
+ }
157
+ break
158
+ }
159
+ case 'picture':
160
+ case 'file':
161
+ case 'audio':
162
+ case 'video': {
163
+ if (body.content.downloadCode) {
164
+ nodes.push(mediaElement(bot, body, body.content.downloadCode, 0))
165
+ }
166
+ // A voice message carries the platform's own transcription; dropping it would lose the message's content.
167
+ if (body.msgtype === 'audio' && body.content.recognition) {
168
+ nodes.push(h.text(body.content.recognition))
169
+ }
170
+ break
171
+ }
172
+ default:
173
+ // An `msgtype` beyond the six is not decoded; `<raw>` keeps the body for diagnostics.
174
+ break
175
+ }
176
+ if (nodes.length === 0) {
177
+ nodes.push(
178
+ h(
179
+ 'raw',
180
+ { platform: 'dingtalk', type: body.msgtype, data: body },
181
+ h.text(''),
182
+ ),
183
+ )
184
+ }
185
+ return normalize(nodes)
186
+ }
187
+
188
+ /**
189
+ * Decode one delivered callback body.
190
+ *
191
+ * A quota or delivery failure carries no message content (`errorCode: 20001` after the monthly allowance is spent), so
192
+ * it is logged instead of being decoded into an empty message.
193
+ *
194
+ * @param bot - the receiving adapter (its routes and identity are used by the decoded elements).
195
+ * @param body - the callback body of either transport.
196
+ * @returns the session to publish, or undefined for a body this adapter does not turn into a message.
197
+ */
198
+ export function decodeMessage(
199
+ bot: DingtalkBot,
200
+ body: Message,
201
+ ): Session | undefined {
202
+ if (typeof body !== 'object' || body === null) return undefined
203
+ const errorCode = errorCodeOf(body)
204
+ if (errorCode !== undefined) {
205
+ bot.ctx.logger.error(
206
+ 'dingtalk quota or delivery error: %s %s',
207
+ String(errorCode),
208
+ String(errorMessageOf(body) ?? ''),
209
+ )
210
+ return undefined
211
+ }
212
+ const sender = senderOf(body)
213
+ const chat = chatOf(body, sender.id)
214
+ const content = decodeContent(bot, body)
215
+ if (body.robotCode && body.robotCode !== bot.config.appkey) {
216
+ // An authorized third-party application has a robot code of its own; v1 supports internal applications only.
217
+ bot.ctx.logger.warn(
218
+ 'dingtalk: the callback names robotCode %s, which differs from the configured appkey',
219
+ body.robotCode,
220
+ )
221
+ }
222
+ const referrer: DingtalkReferrer = {
223
+ conversationId: body.conversationId,
224
+ conversationType: body.conversationType,
225
+ msgId: body.msgId,
226
+ chatbotUserId: body.chatbotUserId,
227
+ ...(body.sessionWebhook ? { sessionWebhook: body.sessionWebhook } : {}),
228
+ ...(body.sessionWebhookExpiredTime
229
+ ? { sessionWebhookExpiredTime: body.sessionWebhookExpiredTime }
230
+ : {}),
231
+ }
232
+ const message: InboundMessage = {
233
+ id: body.msgId,
234
+ chat,
235
+ sender,
236
+ content,
237
+ mentions: mentionsOf(body, chat),
238
+ time: timeOf(body),
239
+ referrer,
240
+ raw: body,
241
+ }
242
+ return bot.session({
243
+ type: 'message',
244
+ id: body.msgId,
245
+ timestamp: message.time,
246
+ message,
247
+ referrer,
248
+ raw: body,
249
+ })
250
+ }