@im-more/dsh-wecom 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.
- package/LICENSE +21 -0
- package/cordis.patch.yml +13 -0
- package/lib/index.js +2077 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +50 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +126 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +48 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +68 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/crypto.d.ts +69 -0
- package/lib/types/crypto.d.ts.map +1 -0
- package/lib/types/crypto.js +129 -0
- package/lib/types/crypto.js.map +1 -0
- package/lib/types/decode.d.ts +58 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +182 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +67 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +170 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +20 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +34 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +19 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +18 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/internal.d.ts +154 -0
- package/lib/types/internal.d.ts.map +1 -0
- package/lib/types/internal.js +115 -0
- package/lib/types/internal.js.map +1 -0
- package/lib/types/media.d.ts +44 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +116 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/markdown.d.ts +20 -0
- package/lib/types/modes/markdown.d.ts.map +1 -0
- package/lib/types/modes/markdown.js +205 -0
- package/lib/types/modes/markdown.js.map +1 -0
- package/lib/types/modes/shared.d.ts +227 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +487 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +55 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +202 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +54 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +124 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/token.d.ts +34 -0
- package/lib/types/token.d.ts.map +1 -0
- package/lib/types/token.js +61 -0
- package/lib/types/token.js.map +1 -0
- package/lib/types/transport/webhook.d.ts +41 -0
- package/lib/types/transport/webhook.d.ts.map +1 -0
- package/lib/types/transport/webhook.js +216 -0
- package/lib/types/transport/webhook.js.map +1 -0
- package/lib/types/types.d.ts +58 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +2 -0
- package/lib/types/types.js.map +1 -0
- package/lib/types/xml.d.ts +40 -0
- package/lib/types/xml.d.ts.map +1 -0
- package/lib/types/xml.js +82 -0
- package/lib/types/xml.js.map +1 -0
- package/package.json +65 -3
- package/src/bot.ts +195 -0
- package/src/config.ts +117 -0
- package/src/crypto.ts +172 -0
- package/src/decode.ts +238 -0
- package/src/errors.ts +199 -0
- package/src/identity.ts +41 -0
- package/src/index.ts +101 -0
- package/src/internal.ts +237 -0
- package/src/media.ts +157 -0
- package/src/modes/markdown.ts +263 -0
- package/src/modes/shared.ts +618 -0
- package/src/request.ts +291 -0
- package/src/send.ts +172 -0
- package/src/token.ts +75 -0
- package/src/transport/webhook.ts +292 -0
- package/src/types.ts +74 -0
- package/src/xml.ts +89 -0
- package/README.md +0 -3
package/src/decode.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbound decoding: one decrypted callback becomes an intake `Session` (`message`) or a button interaction.
|
|
3
|
+
*
|
|
4
|
+
* An application message arrives from exactly one member in exactly one conversation — the member's direct chat with the
|
|
5
|
+
* application — so `chat.type` is always `direct`, `chat.id` is the sender's userid, and there is no mention, thread or
|
|
6
|
+
* quote to decode. The content of a media message is the bot's own `satori:` route, because the callback carries only a
|
|
7
|
+
* `media_id` and the bytes have to be fetched with the application's credentials.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type {
|
|
11
|
+
ButtonEvent,
|
|
12
|
+
ChatRef,
|
|
13
|
+
InboundMessage,
|
|
14
|
+
Session,
|
|
15
|
+
UserRef,
|
|
16
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
17
|
+
import { h, normalize } from '@deepseek-ai/satori-element'
|
|
18
|
+
import type { Child } from '@deepseek-ai/satori-element'
|
|
19
|
+
import type { WecomBot } from './bot.ts'
|
|
20
|
+
import type { XmlFields } from './xml.ts'
|
|
21
|
+
|
|
22
|
+
/** Adapter-private context of a decoded message, carried through `Target.referrer`. */
|
|
23
|
+
export interface WecomReferrer {
|
|
24
|
+
corpId: string
|
|
25
|
+
agentId: string
|
|
26
|
+
userId: string
|
|
27
|
+
msgId: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Adapter-private context of a card click, carried through the button's referrer. */
|
|
31
|
+
export interface WecomCardReferrer {
|
|
32
|
+
taskId: string
|
|
33
|
+
cardType?: string
|
|
34
|
+
responseCode?: string
|
|
35
|
+
userId: string
|
|
36
|
+
agentId: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The chat of a callback sender: the application has only one-to-one conversations. */
|
|
40
|
+
export function chatOf(userId: string): ChatRef {
|
|
41
|
+
return { id: userId, type: 'direct' }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The sender of a callback: the application never learns a display name without another request. */
|
|
45
|
+
export function senderOf(userId: string): UserRef {
|
|
46
|
+
return { id: userId, isBot: false }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The millisecond time of a callback.
|
|
51
|
+
*
|
|
52
|
+
* `CreateTime` is in seconds; a body without a usable value falls back to the receipt time rather than to `NaN`.
|
|
53
|
+
*/
|
|
54
|
+
function timeOf(fields: XmlFields): number {
|
|
55
|
+
const seconds = Number(fields.CreateTime)
|
|
56
|
+
return Number.isFinite(seconds) ? seconds * 1000 : Date.now()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The `satori:` source of one inbound media object.
|
|
61
|
+
*
|
|
62
|
+
* @param bot - the receiving adapter.
|
|
63
|
+
* @param mediaId - the platform `MediaId`.
|
|
64
|
+
* @returns the internal URL the host downloads through.
|
|
65
|
+
*/
|
|
66
|
+
export function mediaSource(bot: WecomBot, mediaId: string): string {
|
|
67
|
+
return bot.getInternalUrl(`/assets/${encodeURIComponent(mediaId)}`)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The text of one location message.
|
|
72
|
+
*
|
|
73
|
+
* The element vocabulary has no location tag, so the place arrives as a readable line.
|
|
74
|
+
*
|
|
75
|
+
* @param fields - the decrypted message.
|
|
76
|
+
* @returns `[位置] Label (X,Y)`, without the label when the message carries none.
|
|
77
|
+
*/
|
|
78
|
+
export function locationText(fields: XmlFields): string {
|
|
79
|
+
const label = fields.Label?.trim() ?? ''
|
|
80
|
+
const x = fields.Location_X ?? ''
|
|
81
|
+
const y = fields.Location_Y ?? ''
|
|
82
|
+
return `[位置]${label === '' ? '' : ` ${label}`} (${x},${y})`
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The elements of one message, or undefined for a `MsgType` this adapter does not decode. */
|
|
86
|
+
function contentOf(
|
|
87
|
+
bot: WecomBot,
|
|
88
|
+
fields: XmlFields,
|
|
89
|
+
msgType: string,
|
|
90
|
+
): Child[] | undefined {
|
|
91
|
+
switch (msgType) {
|
|
92
|
+
case 'text':
|
|
93
|
+
return [fields.Content ?? '']
|
|
94
|
+
case 'image': {
|
|
95
|
+
const mediaId = fields.MediaId ?? ''
|
|
96
|
+
return mediaId === ''
|
|
97
|
+
? []
|
|
98
|
+
: [h('img', { src: mediaSource(bot, mediaId) })]
|
|
99
|
+
}
|
|
100
|
+
case 'voice': {
|
|
101
|
+
const mediaId = fields.MediaId ?? ''
|
|
102
|
+
return mediaId === ''
|
|
103
|
+
? []
|
|
104
|
+
: [h('audio', { src: mediaSource(bot, mediaId) })]
|
|
105
|
+
}
|
|
106
|
+
case 'video': {
|
|
107
|
+
const mediaId = fields.MediaId ?? ''
|
|
108
|
+
return mediaId === ''
|
|
109
|
+
? []
|
|
110
|
+
: [h('video', { src: mediaSource(bot, mediaId) })]
|
|
111
|
+
}
|
|
112
|
+
case 'location':
|
|
113
|
+
return [h('p', locationText(fields))]
|
|
114
|
+
case 'link': {
|
|
115
|
+
const url = fields.Url ?? ''
|
|
116
|
+
if (url === '') return []
|
|
117
|
+
const title = fields.Title?.trim() ?? ''
|
|
118
|
+
const description = fields.Description?.trim() ?? ''
|
|
119
|
+
return [
|
|
120
|
+
h(
|
|
121
|
+
'p',
|
|
122
|
+
h('a', { href: url }, title === '' ? url : title),
|
|
123
|
+
...(description === '' ? [] : ['\n', description]),
|
|
124
|
+
),
|
|
125
|
+
]
|
|
126
|
+
}
|
|
127
|
+
default:
|
|
128
|
+
return undefined
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Decode one `template_card_event` into the button session the callback registry looks up. */
|
|
133
|
+
export function decodeTemplateCardEvent(
|
|
134
|
+
bot: WecomBot,
|
|
135
|
+
fields: XmlFields,
|
|
136
|
+
): Session {
|
|
137
|
+
const userId = fields.FromUserName ?? ''
|
|
138
|
+
const chat = chatOf(userId)
|
|
139
|
+
const time = timeOf(fields)
|
|
140
|
+
const referrer: WecomCardReferrer = {
|
|
141
|
+
taskId: fields.TaskId ?? '',
|
|
142
|
+
...(fields.CardType === undefined ? {} : { cardType: fields.CardType }),
|
|
143
|
+
...(fields.ResponseCode === undefined
|
|
144
|
+
? {}
|
|
145
|
+
: { responseCode: fields.ResponseCode }),
|
|
146
|
+
userId,
|
|
147
|
+
agentId: bot.config.agentId,
|
|
148
|
+
}
|
|
149
|
+
const button: ButtonEvent = {
|
|
150
|
+
bot,
|
|
151
|
+
id: fields.EventKey ?? '',
|
|
152
|
+
user: senderOf(userId),
|
|
153
|
+
chat,
|
|
154
|
+
referrer,
|
|
155
|
+
// The click has no platform time of its own beyond the envelope, and the platform answers nothing back here.
|
|
156
|
+
time: Date.now(),
|
|
157
|
+
}
|
|
158
|
+
return bot.session({
|
|
159
|
+
type: 'interaction/button',
|
|
160
|
+
// A click carries no `MsgId`, so the dedupe id is composed of the card, the button and the callback time.
|
|
161
|
+
id: `${fields.TaskId ?? ''}:${fields.EventKey ?? ''}:${fields.CreateTime ?? ''}`,
|
|
162
|
+
timestamp: time,
|
|
163
|
+
button,
|
|
164
|
+
raw: fields,
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Decode one event message, or drop it when the contract has no consumer for it. */
|
|
169
|
+
function decodeEvent(bot: WecomBot, fields: XmlFields): Session | undefined {
|
|
170
|
+
switch (fields.Event) {
|
|
171
|
+
case 'template_card_event':
|
|
172
|
+
return decodeTemplateCardEvent(bot, fields)
|
|
173
|
+
default:
|
|
174
|
+
// Lifecycle events (`subscribe`, `unsubscribe`, `enter_agent`), menu events, `taskcard_click` and
|
|
175
|
+
// `template_card_menu_event` all arrive here: the IM contract has no "someone opened the application" or "a menu
|
|
176
|
+
// was used" event, and mapping them onto `interaction/button` would produce ids nothing registered.
|
|
177
|
+
bot.ctx.logger.debug(
|
|
178
|
+
'wecom: ignoring a %s event',
|
|
179
|
+
fields.Event ?? '(none)',
|
|
180
|
+
)
|
|
181
|
+
return undefined
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Decode one decrypted callback.
|
|
187
|
+
*
|
|
188
|
+
* @param bot - the receiving adapter.
|
|
189
|
+
* @param fields - the decrypted message fields.
|
|
190
|
+
* @returns the session to publish, or undefined for a message this adapter drops.
|
|
191
|
+
*/
|
|
192
|
+
export function decodeMessage(
|
|
193
|
+
bot: WecomBot,
|
|
194
|
+
fields: XmlFields,
|
|
195
|
+
): Session | undefined {
|
|
196
|
+
const msgType = fields.MsgType ?? ''
|
|
197
|
+
if (msgType === 'event') return decodeEvent(bot, fields)
|
|
198
|
+
const nodes = contentOf(bot, fields, msgType)
|
|
199
|
+
if (nodes === undefined) {
|
|
200
|
+
bot.ctx.logger.debug(
|
|
201
|
+
'wecom: ignoring a message of type %s',
|
|
202
|
+
msgType === '' ? '(none)' : msgType,
|
|
203
|
+
)
|
|
204
|
+
return undefined
|
|
205
|
+
}
|
|
206
|
+
const userId = fields.FromUserName ?? ''
|
|
207
|
+
const msgId = fields.MsgId ?? ''
|
|
208
|
+
const time = timeOf(fields)
|
|
209
|
+
const content = normalize(
|
|
210
|
+
nodes.length > 0
|
|
211
|
+
? nodes
|
|
212
|
+
: [h('raw', { platform: 'wecom', type: msgType, data: fields })],
|
|
213
|
+
)
|
|
214
|
+
const referrer: WecomReferrer = {
|
|
215
|
+
corpId: bot.config.corpId,
|
|
216
|
+
agentId: bot.config.agentId,
|
|
217
|
+
userId,
|
|
218
|
+
msgId,
|
|
219
|
+
}
|
|
220
|
+
const message: InboundMessage = {
|
|
221
|
+
id: msgId,
|
|
222
|
+
chat: chatOf(userId),
|
|
223
|
+
sender: senderOf(userId),
|
|
224
|
+
content,
|
|
225
|
+
// An application message has no mention mechanism: there is no group and no `@` in a one-to-one conversation.
|
|
226
|
+
mentions: { self: false, all: false, users: [] },
|
|
227
|
+
time,
|
|
228
|
+
referrer,
|
|
229
|
+
raw: fields,
|
|
230
|
+
}
|
|
231
|
+
return bot.session({
|
|
232
|
+
type: 'message',
|
|
233
|
+
id: msgId,
|
|
234
|
+
timestamp: time,
|
|
235
|
+
message,
|
|
236
|
+
raw: fields,
|
|
237
|
+
})
|
|
238
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Platform failures of the WeCom REST surface and their mapping onto the core taxonomy.
|
|
3
|
+
*
|
|
4
|
+
* Almost every failure has one shape: HTTP 200 with `{ errcode, errmsg }`, where `errcode === 0` is success. The HTTP
|
|
5
|
+
* layer only fails for a transport problem or a gateway. `published: 'no'` is therefore reserved for a platform refusal
|
|
6
|
+
* this adapter can classify; an answer without a code, a non-JSON page and a 5xx leave the outcome open.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
|
|
10
|
+
import type { PlatformErrorKind } from '@deepseek-ai/cordis-plugin-im-core'
|
|
11
|
+
|
|
12
|
+
/** Fields one failed WeCom call carries for classification and logs. */
|
|
13
|
+
export interface WecomApiErrorInit {
|
|
14
|
+
/** HTTP status of the answer, absent when the request never produced one. */
|
|
15
|
+
status?: number
|
|
16
|
+
/** The business code of an HTTP 200 answer; `0` never reaches this class. */
|
|
17
|
+
errcode?: number
|
|
18
|
+
/** The platform's own message for the code. */
|
|
19
|
+
errmsg?: string
|
|
20
|
+
/** How much of the answer body is kept for diagnostics. */
|
|
21
|
+
bodyText?: string
|
|
22
|
+
/** The answer was not JSON (a gateway page, a truncated answer). */
|
|
23
|
+
nonJson?: boolean
|
|
24
|
+
cause?: unknown
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** One failed WeCom API call. */
|
|
28
|
+
export class WecomApiError extends Error {
|
|
29
|
+
readonly status: number | undefined
|
|
30
|
+
readonly errcode: number | undefined
|
|
31
|
+
readonly errmsg: string | undefined
|
|
32
|
+
readonly bodyText: string | undefined
|
|
33
|
+
readonly nonJson: boolean
|
|
34
|
+
|
|
35
|
+
constructor(message: string, init: WecomApiErrorInit = {}) {
|
|
36
|
+
super(message, init.cause === undefined ? undefined : { cause: init.cause })
|
|
37
|
+
this.name = 'WecomApiError'
|
|
38
|
+
this.status = init.status
|
|
39
|
+
this.errcode = init.errcode
|
|
40
|
+
this.errmsg = init.errmsg
|
|
41
|
+
this.bodyText = init.bodyText
|
|
42
|
+
this.nonJson = init.nonJson ?? false
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** One classification of a platform code or status. */
|
|
47
|
+
interface Verdict {
|
|
48
|
+
kind: PlatformErrorKind
|
|
49
|
+
published: 'no' | 'unknown'
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const RATE_LIMIT: Verdict = { kind: 'rate-limit', published: 'no' }
|
|
53
|
+
const LIMIT: Verdict = { kind: 'limit', published: 'no' }
|
|
54
|
+
const PERMISSION: Verdict = { kind: 'permission', published: 'no' }
|
|
55
|
+
const NOT_FOUND: Verdict = { kind: 'not-found', published: 'no' }
|
|
56
|
+
const INVALID: Verdict = { kind: 'invalid', published: 'no' }
|
|
57
|
+
const RETRYABLE: Verdict = { kind: 'retryable', published: 'unknown' }
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The codes of 全局错误码 this adapter actually meets.
|
|
61
|
+
*
|
|
62
|
+
* A refusal the platform names is a request it rejected before publishing anything, so every entry is `published: 'no'`.
|
|
63
|
+
*/
|
|
64
|
+
const CODE_VERDICTS: ReadonlyMap<number, Verdict> = new Map<number, Verdict>([
|
|
65
|
+
[40001, PERMISSION], // invalid secret
|
|
66
|
+
[40013, PERMISSION], // invalid corpId
|
|
67
|
+
[40014, PERMISSION], // invalid access_token
|
|
68
|
+
[42001, PERMISSION], // access_token expired
|
|
69
|
+
[40003, NOT_FOUND], // invalid userid
|
|
70
|
+
[40007, INVALID], // invalid media_id
|
|
71
|
+
[40008, INVALID], // invalid msgtype
|
|
72
|
+
[44001, INVALID], // empty media file
|
|
73
|
+
[45002, LIMIT], // message content over the limit
|
|
74
|
+
[45009, RATE_LIMIT], // API call rate limit
|
|
75
|
+
[45033, RATE_LIMIT], // API concurrency limit
|
|
76
|
+
[48002, PERMISSION], // API not enabled for the application
|
|
77
|
+
[60011, PERMISSION], // no permission for the member/department/tag
|
|
78
|
+
[81013, PERMISSION], // every userid/department/tag was invalid
|
|
79
|
+
[82001, INVALID], // touser/toparty/totag all empty
|
|
80
|
+
[830002, LIMIT], // downloaded file too large
|
|
81
|
+
])
|
|
82
|
+
|
|
83
|
+
/** Codes outside the documented table whose whole family has one verdict. */
|
|
84
|
+
const FAMILY_VERDICTS: ReadonlyMap<number, Verdict> = new Map<number, Verdict>([
|
|
85
|
+
[41001, PERMISSION], // access_token missing
|
|
86
|
+
[48004, PERMISSION], // API forbidden
|
|
87
|
+
[60020, PERMISSION], // IP not in the trust list
|
|
88
|
+
[301002, PERMISSION], // no privilege for this API
|
|
89
|
+
])
|
|
90
|
+
|
|
91
|
+
/** Whether a code means the `access_token` was refused, so the token is re-minted and the call retried once. */
|
|
92
|
+
const TOKEN_FAILURE_CODES: ReadonlySet<number> = new Set([42001, 40014])
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Verdict of one business code, by the documented table and then by family.
|
|
96
|
+
*
|
|
97
|
+
* @param errcode - the `errcode` of an answer.
|
|
98
|
+
* @returns its classification, or undefined for a code inside no family this adapter knows.
|
|
99
|
+
*/
|
|
100
|
+
export function verdictOfCode(errcode: number): Verdict | undefined {
|
|
101
|
+
const exact = CODE_VERDICTS.get(errcode) ?? FAMILY_VERDICTS.get(errcode)
|
|
102
|
+
if (exact !== undefined) return exact
|
|
103
|
+
// `4xxxx` are parameter refusals, `5xxxx` gateway and retry classes, `6xxxx` authorization and `8xxxx` member and
|
|
104
|
+
// media refusals; the platform documents each family as one behaviour.
|
|
105
|
+
const family = Math.trunc(errcode / 10_000)
|
|
106
|
+
if (family === 4) return INVALID
|
|
107
|
+
if (family === 5) return RETRYABLE
|
|
108
|
+
if (family === 6) return PERMISSION
|
|
109
|
+
if (family === 8) return INVALID
|
|
110
|
+
return undefined
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Whether an `errcode` means the `access_token` was refused.
|
|
115
|
+
*
|
|
116
|
+
* @param errcode - the code of an answer, when it carried one.
|
|
117
|
+
* @returns true for the two codes the platform documents as "refresh and retry".
|
|
118
|
+
*/
|
|
119
|
+
export function isTokenFailureCode(errcode: number | undefined): boolean {
|
|
120
|
+
return errcode !== undefined && TOKEN_FAILURE_CODES.has(errcode)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Whether a failed call means the `access_token` was refused.
|
|
125
|
+
*
|
|
126
|
+
* @param error - the caught failure.
|
|
127
|
+
* @returns true for the two codes the platform documents as "refresh and retry".
|
|
128
|
+
*/
|
|
129
|
+
export function isTokenFailure(error: unknown): boolean {
|
|
130
|
+
return error instanceof WecomApiError && isTokenFailureCode(error.errcode)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
|
|
134
|
+
function isAbortError(error: unknown): error is Error | DOMException {
|
|
135
|
+
return (
|
|
136
|
+
(error instanceof Error || error instanceof DOMException) &&
|
|
137
|
+
error.name === 'AbortError'
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Map any failure onto the core platform taxonomy.
|
|
143
|
+
*
|
|
144
|
+
* @param error - the caught failure.
|
|
145
|
+
* @returns the classified platform error.
|
|
146
|
+
*/
|
|
147
|
+
export function classifyWecomError(error: unknown): PlatformError {
|
|
148
|
+
if (error instanceof PlatformError) return error
|
|
149
|
+
if (error instanceof WecomApiError) {
|
|
150
|
+
const init = {
|
|
151
|
+
...(error.status === undefined ? {} : { code: error.status }),
|
|
152
|
+
cause: error,
|
|
153
|
+
}
|
|
154
|
+
if (error.errcode !== undefined) {
|
|
155
|
+
const verdict = verdictOfCode(error.errcode) ?? RETRYABLE
|
|
156
|
+
return new PlatformError(verdict.kind, error.message, {
|
|
157
|
+
...init,
|
|
158
|
+
code: error.errcode,
|
|
159
|
+
published: verdict.published,
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
if (error.status === 429) {
|
|
163
|
+
// A rate limit refused the request; the platform publishes no retry delay, so none is invented.
|
|
164
|
+
return new PlatformError('rate-limit', error.message, {
|
|
165
|
+
...init,
|
|
166
|
+
published: 'no',
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
// A body that is not JSON came from something in front of the API (a gateway page, a cut-off answer), and a 5xx or
|
|
170
|
+
// a transport failure may still have reached the platform.
|
|
171
|
+
if (error.status === undefined || error.nonJson || error.status >= 500) {
|
|
172
|
+
return new PlatformError('retryable', error.message, {
|
|
173
|
+
...init,
|
|
174
|
+
published: 'unknown',
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
if (error.status !== undefined && error.status >= 400) {
|
|
178
|
+
return new PlatformError('invalid', error.message, {
|
|
179
|
+
...init,
|
|
180
|
+
published: 'no',
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
return new PlatformError('retryable', error.message, {
|
|
184
|
+
...init,
|
|
185
|
+
published: 'unknown',
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
if (isAbortError(error)) {
|
|
189
|
+
return new PlatformError('fatal', error.message, {
|
|
190
|
+
published: 'unknown',
|
|
191
|
+
cause: error,
|
|
192
|
+
})
|
|
193
|
+
}
|
|
194
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
195
|
+
return new PlatformError('retryable', `wecom: request failed: ${message}`, {
|
|
196
|
+
published: 'unknown',
|
|
197
|
+
cause: error,
|
|
198
|
+
})
|
|
199
|
+
}
|
package/src/identity.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { User } from '@deepseek-ai/cordis-plugin-im-core'
|
|
2
|
+
import type { AgentGetAnswer } from './internal.ts'
|
|
3
|
+
|
|
4
|
+
/** Failure to confirm the configured application identity. */
|
|
5
|
+
export class WecomIdentityError extends Error {
|
|
6
|
+
constructor(message: string) {
|
|
7
|
+
super(message)
|
|
8
|
+
this.name = 'WecomIdentityError'
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Verify an `agent/get` answer against the configured `AgentID` and turn it into `bot.user`.
|
|
14
|
+
*
|
|
15
|
+
* `bot.id` and `selfId` are fixed at construction, so the application is identified from configuration rather than
|
|
16
|
+
* discovered; this call proves the credentials belong to that application. A mismatch is a configuration error that no
|
|
17
|
+
* retry repairs.
|
|
18
|
+
*
|
|
19
|
+
* @param agentId - the configured `AgentID`.
|
|
20
|
+
* @param answer - the `GET /cgi-bin/agent/get` answer.
|
|
21
|
+
* @returns the bot's own user, with the name and logo the platform reports.
|
|
22
|
+
* @throws WecomIdentityError when the answer names another application.
|
|
23
|
+
*/
|
|
24
|
+
export function verifyIdentity(agentId: string, answer: AgentGetAnswer): User {
|
|
25
|
+
if (
|
|
26
|
+
answer.agentid === undefined ||
|
|
27
|
+
Number(answer.agentid) !== Number(agentId)
|
|
28
|
+
) {
|
|
29
|
+
throw new WecomIdentityError(
|
|
30
|
+
`wecom: agentId is ${agentId} but agent/get returned ${String(answer.agentid)}`,
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
id: agentId,
|
|
35
|
+
...(answer.name === undefined ? {} : { name: answer.name }),
|
|
36
|
+
...(answer.square_logo_url === undefined
|
|
37
|
+
? {}
|
|
38
|
+
: { avatar: answer.square_logo_url }),
|
|
39
|
+
isBot: true,
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import * as Wecom from './types.ts'
|
|
2
|
+
|
|
3
|
+
export { WecomBot, WecomBot as default, type WecomModes } from './bot.ts'
|
|
4
|
+
export {
|
|
5
|
+
AES_KEY_CHARS,
|
|
6
|
+
Config,
|
|
7
|
+
configError,
|
|
8
|
+
routePath,
|
|
9
|
+
TOKEN_MAX_CHARS,
|
|
10
|
+
type Config as WecomConfig,
|
|
11
|
+
} from './config.ts'
|
|
12
|
+
export {
|
|
13
|
+
aesKeyOf,
|
|
14
|
+
decryptPayload,
|
|
15
|
+
matchesSignature,
|
|
16
|
+
PKCS7_BLOCK_BYTES,
|
|
17
|
+
signatureOf,
|
|
18
|
+
WecomCryptoError,
|
|
19
|
+
type DecryptedPayload,
|
|
20
|
+
} from './crypto.ts'
|
|
21
|
+
export {
|
|
22
|
+
chatOf,
|
|
23
|
+
decodeMessage,
|
|
24
|
+
decodeTemplateCardEvent,
|
|
25
|
+
locationText,
|
|
26
|
+
mediaSource,
|
|
27
|
+
senderOf,
|
|
28
|
+
type WecomCardReferrer,
|
|
29
|
+
type WecomReferrer,
|
|
30
|
+
} from './decode.ts'
|
|
31
|
+
export {
|
|
32
|
+
classifyWecomError,
|
|
33
|
+
isTokenFailure,
|
|
34
|
+
isTokenFailureCode,
|
|
35
|
+
verdictOfCode,
|
|
36
|
+
WecomApiError,
|
|
37
|
+
type WecomApiErrorInit,
|
|
38
|
+
} from './errors.ts'
|
|
39
|
+
export { verifyIdentity, WecomIdentityError } from './identity.ts'
|
|
40
|
+
export {
|
|
41
|
+
Internal,
|
|
42
|
+
type AgentGetAnswer,
|
|
43
|
+
type AppchatSendInput,
|
|
44
|
+
type MediaUploadAnswer,
|
|
45
|
+
type MessageSendAnswer,
|
|
46
|
+
type UpdateTemplateCardInput,
|
|
47
|
+
type UserGetAnswer,
|
|
48
|
+
type WecomStatusAnswer,
|
|
49
|
+
type WecomTokenAnswer,
|
|
50
|
+
} from './internal.ts'
|
|
51
|
+
export {
|
|
52
|
+
MEDIA_LIFETIME_MS,
|
|
53
|
+
mediaTypeOf,
|
|
54
|
+
serveMedia,
|
|
55
|
+
uploadMedia,
|
|
56
|
+
} from './media.ts'
|
|
57
|
+
export type {
|
|
58
|
+
TemplateCard,
|
|
59
|
+
TemplateCardButton,
|
|
60
|
+
WecomCardButton,
|
|
61
|
+
WecomDraft,
|
|
62
|
+
WecomMediaKind,
|
|
63
|
+
WecomModeTypes,
|
|
64
|
+
WecomNode,
|
|
65
|
+
WecomPayload,
|
|
66
|
+
} from './modes/shared.ts'
|
|
67
|
+
export {
|
|
68
|
+
assembleDraft,
|
|
69
|
+
CARD_TITLE_FALLBACK,
|
|
70
|
+
checkDraft,
|
|
71
|
+
flattenNodes,
|
|
72
|
+
hardCutBytes,
|
|
73
|
+
nextTaskId,
|
|
74
|
+
reportMovedMedia,
|
|
75
|
+
serializeDraft,
|
|
76
|
+
splitMarkdownBytes,
|
|
77
|
+
WECOM_LIMITS,
|
|
78
|
+
} from './modes/shared.ts'
|
|
79
|
+
export { createMarkdownMode } from './modes/markdown.ts'
|
|
80
|
+
export {
|
|
81
|
+
download,
|
|
82
|
+
endpointOf,
|
|
83
|
+
invoke,
|
|
84
|
+
type WecomRequestConfig,
|
|
85
|
+
type WecomRequestEndpoint,
|
|
86
|
+
} from './request.ts'
|
|
87
|
+
export { deletePart, members, sendPayload, type WecomSendDeps } from './send.ts'
|
|
88
|
+
export { AccessTokenCache } from './token.ts'
|
|
89
|
+
export {
|
|
90
|
+
WecomWebhook,
|
|
91
|
+
type WebHandlerRoute,
|
|
92
|
+
type WebServerLike,
|
|
93
|
+
} from './transport/webhook.ts'
|
|
94
|
+
export {
|
|
95
|
+
fieldsOf,
|
|
96
|
+
parseMessageXml,
|
|
97
|
+
parseXml,
|
|
98
|
+
WecomXmlError,
|
|
99
|
+
type XmlFields,
|
|
100
|
+
} from './xml.ts'
|
|
101
|
+
export { Wecom }
|