@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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +13 -0
  3. package/lib/index.js +2077 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +50 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +126 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +48 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +68 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/crypto.d.ts +69 -0
  14. package/lib/types/crypto.d.ts.map +1 -0
  15. package/lib/types/crypto.js +129 -0
  16. package/lib/types/crypto.js.map +1 -0
  17. package/lib/types/decode.d.ts +58 -0
  18. package/lib/types/decode.d.ts.map +1 -0
  19. package/lib/types/decode.js +182 -0
  20. package/lib/types/decode.js.map +1 -0
  21. package/lib/types/errors.d.ts +67 -0
  22. package/lib/types/errors.d.ts.map +1 -0
  23. package/lib/types/errors.js +170 -0
  24. package/lib/types/errors.js.map +1 -0
  25. package/lib/types/identity.d.ts +20 -0
  26. package/lib/types/identity.d.ts.map +1 -0
  27. package/lib/types/identity.js +34 -0
  28. package/lib/types/identity.js.map +1 -0
  29. package/lib/types/index.d.ts +19 -0
  30. package/lib/types/index.d.ts.map +1 -0
  31. package/lib/types/index.js +18 -0
  32. package/lib/types/index.js.map +1 -0
  33. package/lib/types/internal.d.ts +154 -0
  34. package/lib/types/internal.d.ts.map +1 -0
  35. package/lib/types/internal.js +115 -0
  36. package/lib/types/internal.js.map +1 -0
  37. package/lib/types/media.d.ts +44 -0
  38. package/lib/types/media.d.ts.map +1 -0
  39. package/lib/types/media.js +116 -0
  40. package/lib/types/media.js.map +1 -0
  41. package/lib/types/modes/markdown.d.ts +20 -0
  42. package/lib/types/modes/markdown.d.ts.map +1 -0
  43. package/lib/types/modes/markdown.js +205 -0
  44. package/lib/types/modes/markdown.js.map +1 -0
  45. package/lib/types/modes/shared.d.ts +227 -0
  46. package/lib/types/modes/shared.d.ts.map +1 -0
  47. package/lib/types/modes/shared.js +487 -0
  48. package/lib/types/modes/shared.js.map +1 -0
  49. package/lib/types/request.d.ts +55 -0
  50. package/lib/types/request.d.ts.map +1 -0
  51. package/lib/types/request.js +202 -0
  52. package/lib/types/request.js.map +1 -0
  53. package/lib/types/send.d.ts +54 -0
  54. package/lib/types/send.d.ts.map +1 -0
  55. package/lib/types/send.js +124 -0
  56. package/lib/types/send.js.map +1 -0
  57. package/lib/types/token.d.ts +34 -0
  58. package/lib/types/token.d.ts.map +1 -0
  59. package/lib/types/token.js +61 -0
  60. package/lib/types/token.js.map +1 -0
  61. package/lib/types/transport/webhook.d.ts +41 -0
  62. package/lib/types/transport/webhook.d.ts.map +1 -0
  63. package/lib/types/transport/webhook.js +216 -0
  64. package/lib/types/transport/webhook.js.map +1 -0
  65. package/lib/types/types.d.ts +58 -0
  66. package/lib/types/types.d.ts.map +1 -0
  67. package/lib/types/types.js +2 -0
  68. package/lib/types/types.js.map +1 -0
  69. package/lib/types/xml.d.ts +40 -0
  70. package/lib/types/xml.d.ts.map +1 -0
  71. package/lib/types/xml.js +82 -0
  72. package/lib/types/xml.js.map +1 -0
  73. package/package.json +65 -3
  74. package/src/bot.ts +195 -0
  75. package/src/config.ts +117 -0
  76. package/src/crypto.ts +172 -0
  77. package/src/decode.ts +238 -0
  78. package/src/errors.ts +199 -0
  79. package/src/identity.ts +41 -0
  80. package/src/index.ts +101 -0
  81. package/src/internal.ts +237 -0
  82. package/src/media.ts +157 -0
  83. package/src/modes/markdown.ts +263 -0
  84. package/src/modes/shared.ts +618 -0
  85. package/src/request.ts +291 -0
  86. package/src/send.ts +172 -0
  87. package/src/token.ts +75 -0
  88. package/src/transport/webhook.ts +292 -0
  89. package/src/types.ts +74 -0
  90. package/src/xml.ts +89 -0
  91. package/README.md +0 -3
package/src/request.ts ADDED
@@ -0,0 +1,291 @@
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import type {} from '@deepseek-ai/cordis-plugin-http'
3
+ import type { Config } from './config.ts'
4
+ import { isTokenFailure, isTokenFailureCode, WecomApiError } from './errors.ts'
5
+
6
+ /** Endpoints that mint a token themselves and therefore carry no `access_token`. */
7
+ const CREDENTIAL_PATHS: ReadonlySet<string> = new Set(['/cgi-bin/gettoken'])
8
+
9
+ /** How much of a non-JSON answer is kept in the error and the log; enough to recognise a gateway page. */
10
+ const BODY_PREFIX_BYTES = 512
11
+
12
+ /** One request body, query and cancellation. */
13
+ export interface WecomRequestConfig {
14
+ /** A JSON body, or the multipart form of the media upload. */
15
+ data?: object | FormData
16
+ params?: Record<string, string | number | undefined>
17
+ signal?: AbortSignal | undefined
18
+ }
19
+
20
+ /** What one call needs from the adapter. */
21
+ export interface WecomRequestEndpoint {
22
+ readonly ctx: Context
23
+ readonly config: Config
24
+ readonly tokens: {
25
+ get(): Promise<string>
26
+ invalidate(): void
27
+ }
28
+ }
29
+
30
+ /** Message of any caught value, for a log line. */
31
+ function messageOf(error: unknown): string {
32
+ return error instanceof Error ? error.message : String(error)
33
+ }
34
+
35
+ /** Whether a failed `ctx.http` call was the caller's cancellation rather than a transport failure. */
36
+ function isCancellation(
37
+ cause: unknown,
38
+ signal: AbortSignal | undefined,
39
+ ): boolean {
40
+ if (signal?.aborted === true) return true
41
+ if (
42
+ (cause instanceof Error || cause instanceof DOMException) &&
43
+ cause.name === 'AbortError'
44
+ ) {
45
+ return true
46
+ }
47
+ return signal?.reason !== undefined && cause === signal.reason
48
+ }
49
+
50
+ /** A cancelled request rejects with the signal's reason, so the classifier sees the cancellation itself. */
51
+ function cancellation(
52
+ cause: unknown,
53
+ signal: AbortSignal | undefined,
54
+ ): unknown {
55
+ return signal?.aborted === true ? signal.reason : cause
56
+ }
57
+
58
+ /** One JSON object, when the value is a plain object. */
59
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
60
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
61
+ ? (value as Record<string, unknown>)
62
+ : undefined
63
+ }
64
+
65
+ /**
66
+ * The absolute URL of one endpoint.
67
+ *
68
+ * @param config - the adapter configuration holding the API root.
69
+ * @param path - endpoint path under the root, e.g. `/cgi-bin/message/send`.
70
+ * @returns the absolute request URL.
71
+ */
72
+ export function endpointOf(config: Config, path: string): string {
73
+ return `${config.apiBaseUrl.replace(/\/+$/, '')}${path}`
74
+ }
75
+
76
+ /** The request URL with the token and the query parameters applied. */
77
+ function urlOf(
78
+ endpoint: WecomRequestEndpoint,
79
+ path: string,
80
+ params: Record<string, string | number | undefined> | undefined,
81
+ token: string | undefined,
82
+ ): URL {
83
+ const url = new URL(endpointOf(endpoint.config, path))
84
+ if (token !== undefined) url.searchParams.set('access_token', token)
85
+ for (const [name, value] of Object.entries(params ?? {})) {
86
+ if (value !== undefined) url.searchParams.set(name, String(value))
87
+ }
88
+ return url
89
+ }
90
+
91
+ /**
92
+ * The access token of one request, or undefined for the endpoint that mints it.
93
+ *
94
+ * @param endpoint - the adapter whose token cache the call uses.
95
+ * @param path - endpoint path.
96
+ * @returns the token to carry, if the endpoint needs one.
97
+ */
98
+ async function authorization(
99
+ endpoint: WecomRequestEndpoint,
100
+ path: string,
101
+ ): Promise<string | undefined> {
102
+ if (CREDENTIAL_PATHS.has(path)) return undefined
103
+ return await endpoint.tokens.get()
104
+ }
105
+
106
+ /** Read one answer body as text, turning a cancelled read into a cancellation. */
107
+ async function readText(
108
+ response: Response,
109
+ path: string,
110
+ signal: AbortSignal | undefined,
111
+ ): Promise<string> {
112
+ try {
113
+ return await response.text()
114
+ } catch (cause) {
115
+ // Reading the body fails when the caller cancelled mid-answer; that is still a cancellation.
116
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal)
117
+ throw new WecomApiError(
118
+ `wecom: ${path} answered ${response.status} but its body could not be read`,
119
+ { status: response.status, cause },
120
+ )
121
+ }
122
+ }
123
+
124
+ /** Send one request and unwrap its `{ errcode, errmsg }` envelope. */
125
+ async function send<T>(
126
+ endpoint: WecomRequestEndpoint,
127
+ method: string,
128
+ path: string,
129
+ config: WecomRequestConfig,
130
+ token: string | undefined,
131
+ ): Promise<T> {
132
+ let response: Response
133
+ try {
134
+ response = await endpoint.ctx.http(
135
+ urlOf(endpoint, path, config.params, token),
136
+ {
137
+ method,
138
+ ...(config.data === undefined ? {} : { data: config.data }),
139
+ ...(config.signal === undefined ? {} : { signal: config.signal }),
140
+ },
141
+ )
142
+ } catch (cause) {
143
+ if (isCancellation(cause, config.signal)) {
144
+ throw cancellation(cause, config.signal)
145
+ }
146
+ throw new WecomApiError(
147
+ `wecom: ${method} ${path} request failed: ${messageOf(cause)}`,
148
+ { cause },
149
+ )
150
+ }
151
+
152
+ const text = await readText(response, path, config.signal)
153
+ let body: unknown
154
+ let nonJson = false
155
+ if (text !== '') {
156
+ try {
157
+ body = JSON.parse(text)
158
+ } catch {
159
+ nonJson = true
160
+ }
161
+ }
162
+ const record = asRecord(body)
163
+ const errcode =
164
+ record?.errcode === undefined ? undefined : Number(record.errcode)
165
+ const errmsg = typeof record?.errmsg === 'string' ? record.errmsg : undefined
166
+ const suffix =
167
+ (errcode === undefined ? '' : ` (${errcode})`) +
168
+ (errmsg === undefined ? '' : `: ${errmsg}`)
169
+ const detail = {
170
+ status: response.status,
171
+ ...(text === '' ? {} : { bodyText: text.slice(0, BODY_PREFIX_BYTES) }),
172
+ ...(errmsg === undefined ? {} : { errmsg }),
173
+ }
174
+ if (response.status < 200 || response.status >= 300 || nonJson) {
175
+ throw new WecomApiError(
176
+ `wecom: ${method} ${path} answered ${response.status}${suffix}`,
177
+ { ...detail, nonJson },
178
+ )
179
+ }
180
+ if (errcode !== undefined && errcode !== 0) {
181
+ // A business refusal arrives as HTTP 200; reading that as a success would lose the refusal.
182
+ throw new WecomApiError(
183
+ `wecom: ${method} ${path} answered ${response.status}${suffix}`,
184
+ { ...detail, errcode },
185
+ )
186
+ }
187
+ return body as T
188
+ }
189
+
190
+ /**
191
+ * Call one WeCom endpoint.
192
+ *
193
+ * A call refused for its `access_token` re-mints the token and is retried once; every other failure is thrown as the
194
+ * `WecomApiError` `classify` maps. A cancelled call rejects with the cancellation itself.
195
+ *
196
+ * @param endpoint - the adapter whose configuration and token cache the call uses.
197
+ * @param method - HTTP method.
198
+ * @param path - endpoint path under the API root.
199
+ * @param config - body, query parameters and cancellation of the call.
200
+ * @returns the unwrapped JSON answer.
201
+ * @throws WecomApiError when the platform refused the call or did not answer with JSON.
202
+ */
203
+ export async function invoke<T>(
204
+ endpoint: WecomRequestEndpoint,
205
+ method: string,
206
+ path: string,
207
+ config: WecomRequestConfig = {},
208
+ ): Promise<T> {
209
+ const token = await authorization(endpoint, path)
210
+ try {
211
+ return await send<T>(endpoint, method, path, config, token)
212
+ } catch (error) {
213
+ // The platform documents that a token may be invalidated early, so a refused call is retried once with a fresh one.
214
+ if (!isTokenFailure(error) || token === undefined) throw error
215
+ endpoint.tokens.invalidate()
216
+ return await send<T>(
217
+ endpoint,
218
+ method,
219
+ path,
220
+ config,
221
+ await authorization(endpoint, path),
222
+ )
223
+ }
224
+ }
225
+
226
+ /** One download attempt with one token. */
227
+ async function attempt(
228
+ endpoint: WecomRequestEndpoint,
229
+ path: string,
230
+ params: Record<string, string | number | undefined>,
231
+ signal: AbortSignal | undefined,
232
+ ): Promise<Response> {
233
+ const token = await endpoint.tokens.get()
234
+ try {
235
+ return await endpoint.ctx.http(urlOf(endpoint, path, params, token), {
236
+ method: 'GET',
237
+ ...(signal === undefined ? {} : { signal }),
238
+ })
239
+ } catch (cause) {
240
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal)
241
+ throw new WecomApiError(
242
+ `wecom: GET ${path} request failed: ${messageOf(cause)}`,
243
+ { cause },
244
+ )
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Whether a download answer is the platform's token refusal rather than bytes.
250
+ *
251
+ * `media/get` answers the bytes on success and an `{ errcode }` JSON envelope on a refusal, still with HTTP 200, so the
252
+ * token races the same invalidation a JSON call does.
253
+ */
254
+ async function isTokenRefusal(response: Response): Promise<boolean> {
255
+ const type = response.headers.get('content-type') ?? ''
256
+ if (!type.includes('application/json')) return false
257
+ try {
258
+ const body = asRecord(await response.clone().json())
259
+ const errcode =
260
+ body?.errcode === undefined ? undefined : Number(body.errcode)
261
+ return isTokenFailureCode(errcode)
262
+ } catch {
263
+ // An unreadable answer is not a token refusal; the caller maps it as a failed download.
264
+ return false
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Download the bytes of one inbound media object.
270
+ *
271
+ * `media/get` answers the bytes themselves on success and a JSON `{ errcode }` envelope on failure, so the answer is
272
+ * returned as it arrived and mapped by the caller. A refusal for the `access_token` re-mints it and retries once. A
273
+ * cancelled download rejects with the cancellation itself.
274
+ *
275
+ * @param endpoint - the adapter whose credentials the download uses.
276
+ * @param path - endpoint path under the API root.
277
+ * @param params - query parameters of the download.
278
+ * @param signal - cancellation.
279
+ * @returns the answer, status and headers included.
280
+ */
281
+ export async function download(
282
+ endpoint: WecomRequestEndpoint,
283
+ path: string,
284
+ params: Record<string, string | number | undefined>,
285
+ signal?: AbortSignal,
286
+ ): Promise<Response> {
287
+ const response = await attempt(endpoint, path, params, signal)
288
+ if (!(await isTokenRefusal(response))) return response
289
+ endpoint.tokens.invalidate()
290
+ return await attempt(endpoint, path, params, signal)
291
+ }
package/src/send.ts ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Outbound: one `message/send` per draft, one recall per published part, and the member read of `im_members`.
3
+ *
4
+ * The answer is an HTTP 200 envelope whose `errcode` the transport has already checked, so what is left here is the part
5
+ * the platform reports without failing: a recipient that does not exist (`invaliduser`), one that exists but has no
6
+ * licence (`unlicenseduser`) and an accepted request that returned no `msgid`. Reporting any of those as a success would
7
+ * tell the host a message was delivered when the platform dropped it.
8
+ */
9
+
10
+ import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
11
+ import type {
12
+ ChatRef,
13
+ MembersPage,
14
+ SendContext,
15
+ SentPart,
16
+ Target,
17
+ MessageHandle,
18
+ } from '@deepseek-ai/cordis-plugin-im-core'
19
+ import type { Config } from './config.ts'
20
+ import type { Internal } from './internal.ts'
21
+ import type { WecomPayload } from './modes/shared.ts'
22
+
23
+ /** Everything `sendPayload`, `deletePart` and `members` need from the adapter. */
24
+ export interface WecomSendDeps {
25
+ readonly internal: Internal
26
+ readonly config: Config
27
+ }
28
+
29
+ /** One `|`-separated recipient list of a send answer, as a set of userids. */
30
+ function listOf(value: string | undefined): string[] {
31
+ if (value === undefined) return []
32
+ return value
33
+ .split('|')
34
+ .map((item) => item.trim())
35
+ .filter((item) => item !== '')
36
+ }
37
+
38
+ /** The media id a payload carries, when the payload is a media message. */
39
+ function mediaIdOf(payload: WecomPayload): string | undefined {
40
+ switch (payload.msgtype) {
41
+ case 'markdown':
42
+ case 'template_card':
43
+ return undefined
44
+ case 'image':
45
+ return payload.image.media_id
46
+ case 'voice':
47
+ return payload.voice.media_id
48
+ case 'video':
49
+ return payload.video.media_id
50
+ case 'file':
51
+ return payload.file.media_id
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Send one serialized payload and report the part the platform created.
57
+ *
58
+ * @param deps - the adapter's API surface.
59
+ * @param payload - one `message/send` body.
60
+ * @param target - the chat the payload goes to; its id is the `touser` recipient as well.
61
+ * @param ctx - core send context: `quote` is present on every part, and only part 0 records it.
62
+ * @returns the published part.
63
+ * @throws PlatformError when the one addressee was skipped, or when the answer carried no `msgid`.
64
+ */
65
+ export async function sendPayload(
66
+ deps: WecomSendDeps,
67
+ payload: WecomPayload,
68
+ target: Target,
69
+ ctx: SendContext,
70
+ ): Promise<SentPart> {
71
+ const answer = await deps.internal.messageSend(payload)
72
+ const recipient = target.chat.id
73
+ if (listOf(answer.invaliduser).includes(recipient)) {
74
+ // `errcode` was 0 and the message went to nobody: the one addressee is not in the application's visible range.
75
+ throw new PlatformError(
76
+ 'not-found',
77
+ `wecom: ${recipient} does not exist or is outside the application's visible range`,
78
+ { published: 'no', code: 'invaliduser' },
79
+ )
80
+ }
81
+ if (listOf(answer.unlicenseduser).includes(recipient)) {
82
+ throw new PlatformError(
83
+ 'permission',
84
+ `wecom: ${recipient} has no licence for the application`,
85
+ { published: 'no', code: 'unlicenseduser' },
86
+ )
87
+ }
88
+ const msgid = answer.msgid
89
+ if (msgid === undefined || msgid === '') {
90
+ // The platform accepted the request but returned no id: the message may be there, with nothing left to recall it by.
91
+ throw new PlatformError(
92
+ 'invalid',
93
+ 'wecom: message/send answered without a msgid',
94
+ { published: 'unknown' },
95
+ )
96
+ }
97
+ const mediaId = mediaIdOf(payload)
98
+ return {
99
+ id: msgid,
100
+ kind: 'message',
101
+ time: Date.now(),
102
+ referrer: {
103
+ userId: recipient,
104
+ msgId: msgid,
105
+ ...(ctx.index === 0 && ctx.quote !== undefined
106
+ ? { quotedMessageId: ctx.quote }
107
+ : {}),
108
+ },
109
+ raw: {
110
+ msgtype: payload.msgtype,
111
+ ...(mediaId === undefined ? {} : { mediaId }),
112
+ ...(payload.msgtype === 'template_card'
113
+ ? { taskId: payload.template_card.task_id }
114
+ : {}),
115
+ ...(answer.response_code === undefined
116
+ ? {}
117
+ : { responseCode: answer.response_code }),
118
+ },
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Recall one published message.
124
+ *
125
+ * The core only calls this inside the 24-hour window of `limit.delete.window`, and logs a refusal as a warning rather
126
+ * than failing the caller.
127
+ *
128
+ * @param deps - the adapter's API surface.
129
+ * @param part - the published part, whose id is the platform `msgid`.
130
+ * @param _handle - unused; a recall addresses the message id alone.
131
+ */
132
+ export async function deletePart(
133
+ deps: WecomSendDeps,
134
+ part: SentPart,
135
+ _handle: MessageHandle,
136
+ ): Promise<void> {
137
+ await deps.internal.messageRecall({ msgid: part.id })
138
+ }
139
+
140
+ /**
141
+ * The members of one chat.
142
+ *
143
+ * A direct chat is the application's only conversation kind, and its one other person is the peer the chat id already
144
+ * names; the profile request fills in the display name the callback does not carry. A userid the application may not see
145
+ * answers `40003`, which reaches the caller as `not-found`.
146
+ *
147
+ * @param deps - the adapter's API surface.
148
+ * @param chat - the chat to list.
149
+ * @param _cursor - unused; a direct chat is a single page.
150
+ * @param _limit - unused; a direct chat has one member.
151
+ * @returns one page with the peer.
152
+ */
153
+ export async function members(
154
+ deps: WecomSendDeps,
155
+ chat: ChatRef,
156
+ _cursor?: string,
157
+ _limit?: number,
158
+ ): Promise<MembersPage> {
159
+ const answer = await deps.internal.userGet({ userid: chat.id })
160
+ return {
161
+ data: [
162
+ {
163
+ id:
164
+ answer.userid === undefined || answer.userid === ''
165
+ ? chat.id
166
+ : answer.userid,
167
+ ...(answer.name === undefined ? {} : { name: answer.name }),
168
+ isBot: false,
169
+ },
170
+ ],
171
+ }
172
+ }
package/src/token.ts ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The application `access_token` every `cgi-bin` call carries.
3
+ *
4
+ * The platform mints one token per application with a lifetime of 7,200 seconds, refuses a client that asks too often,
5
+ * and may invalidate a token early. The cache is therefore lazy (no background timer to clear on disconnect),
6
+ * single-flight (concurrent callers share one request) and invalidated by the code of a refused call rather than by a
7
+ * deadline alone.
8
+ */
9
+
10
+ /** One answer of `GET /cgi-bin/gettoken`. */
11
+ export interface WecomTokenAnswer {
12
+ errcode?: number
13
+ errmsg?: string
14
+ access_token?: string
15
+ expires_in?: number
16
+ }
17
+
18
+ /** Seconds shaved off the announced lifetime, so a request never races the expiry. */
19
+ const REFRESH_MARGIN_SECONDS = 300
20
+
21
+ /** The application token, cached until shortly before the platform expires it. */
22
+ export class AccessTokenCache {
23
+ private current: { value: string; expiresAt: number } | undefined
24
+ private inflight: Promise<string> | undefined
25
+
26
+ /**
27
+ * @param mint - requests a new token from the platform.
28
+ * @param now - clock of the expiry check; tests replace it.
29
+ */
30
+ constructor(
31
+ private readonly mint: () => Promise<WecomTokenAnswer>,
32
+ private readonly now: () => number = Date.now,
33
+ ) {}
34
+
35
+ /** The cached token, requesting one when none is cached or the cached one is near its expiry. */
36
+ async get(): Promise<string> {
37
+ const current = this.current
38
+ if (current !== undefined && this.now() < current.expiresAt)
39
+ return current.value
40
+ this.inflight ??= this.mint()
41
+ .then((answer) => {
42
+ if (answer.access_token === undefined || answer.access_token === '') {
43
+ // A refusal must not leave the adapter sending `access_token=` on every later call.
44
+ throw new Error(
45
+ `wecom: gettoken answered without a token${answer.errmsg === undefined ? '' : `: ${answer.errmsg}`}`,
46
+ )
47
+ }
48
+ const expiresIn = answer.expires_in
49
+ // Without a usable lifetime the token still answers this round of callers but is not cached: a `NaN` deadline
50
+ // would silently re-request on every call.
51
+ if (typeof expiresIn === 'number' && Number.isFinite(expiresIn)) {
52
+ this.current = {
53
+ value: answer.access_token,
54
+ expiresAt:
55
+ this.now() + (expiresIn - REFRESH_MARGIN_SECONDS) * 1_000,
56
+ }
57
+ }
58
+ return answer.access_token
59
+ })
60
+ .finally(() => {
61
+ this.inflight = undefined
62
+ })
63
+ return await this.inflight
64
+ }
65
+
66
+ /** Drop the cached token, so the next {@link get} asks the platform again. */
67
+ invalidate(): void {
68
+ this.current = undefined
69
+ }
70
+
71
+ /** The token in the cache, when one is cached; for diagnostics only. */
72
+ get cached(): string | undefined {
73
+ return this.current?.value
74
+ }
75
+ }