@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/lib/index.js ADDED
@@ -0,0 +1,2077 @@
1
+ import { Adapter, ElementRegistry, INTERACTION_DROPPED, PlatformError } from "@deepseek-ai/cordis-plugin-im-core";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
+ import { h, isPhrasingContainer, normalize } from "@deepseek-ai/satori-element";
5
+ import xml2js from "xml2js";
6
+ // \0rolldown/runtime.js
7
+ var __defProp = Object.defineProperty;
8
+ var __exportAll = (all, no_symbols) => {
9
+ let target = {};
10
+ for (var name in all) __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true
13
+ });
14
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
15
+ return target;
16
+ };
17
+ // lib/types/types.js
18
+ var types_exports = /* @__PURE__ */ __exportAll({});
19
+ // lib/types/config.js
20
+ /** Validated WeCom adapter configuration. */
21
+ const Config = z.object({
22
+ corpId: z.string().required(),
23
+ agentId: z.string().required(),
24
+ secret: z.string().role("secret").required(),
25
+ token: z.string().role("secret").required(),
26
+ aesKey: z.string().role("secret").required(),
27
+ path: z.string().default("/wecom"),
28
+ apiBaseUrl: z.string().role("url").default("https://qyapi.weixin.qq.com")
29
+ });
30
+ /** Length of an `EncodingAESKey`, which is the Base64 form of the 32-byte AES key without its padding. */
31
+ const AES_KEY_CHARS = 43;
32
+ /** Maximum length of a callback `Token` the platform accepts. */
33
+ const TOKEN_MAX_CHARS = 32;
34
+ /** The alphanumerical alphabet both callback credentials are drawn from. */
35
+ const CREDENTIAL_ALPHABET = /^[0-9A-Za-z]+$/;
36
+ /**
37
+ * Normalize a route path: absolute, no trailing slash.
38
+ *
39
+ * @param path - a configured path.
40
+ * @returns the pathname to register on the web server.
41
+ */
42
+ function routePath(path) {
43
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
44
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
45
+ }
46
+ /**
47
+ * The configuration the adapter cannot work from, as far as it can tell locally.
48
+ *
49
+ * The check runs when the bot starts, not on the first callback: the callback is the only inbound path, so a profile
50
+ * that cannot answer one has no way to receive anything.
51
+ *
52
+ * @param config - the validated configuration.
53
+ * @returns the configuration error, or undefined when the configuration is usable.
54
+ */
55
+ function configError(config) {
56
+ if (config.corpId === "") return /* @__PURE__ */ new Error("wecom: corpId is required (the enterprise id \"ww…\" of 我的企业 → 企业信息)");
57
+ if (config.agentId === "") return /* @__PURE__ */ new Error("wecom: agentId is required (the AgentID of the self-built application)");
58
+ if (!/^[1-9][0-9]*$/.test(config.agentId)) return /* @__PURE__ */ new Error(`wecom: agentId must be a positive integer string, got "${config.agentId}" (message/send takes the numeric AgentID)`);
59
+ if (config.secret === "") return /* @__PURE__ */ new Error("wecom: secret is required (the application secret, which every access_token is minted with)");
60
+ if (config.token === "") return /* @__PURE__ */ new Error("wecom: token is required (the callback Token of 接收消息 → 设置API接收)");
61
+ if (config.token.length > 32) return /* @__PURE__ */ new Error(`wecom: token must be at most 32 characters, got ${config.token.length}`);
62
+ if (config.aesKey === "") return /* @__PURE__ */ new Error("wecom: aesKey is required (the EncodingAESKey of 接收消息 → 设置API接收)");
63
+ if (config.aesKey.length !== 43 || !CREDENTIAL_ALPHABET.test(config.aesKey)) return /* @__PURE__ */ new Error(`wecom: aesKey must be exactly 43 letters or digits, got ${config.aesKey.length} characters`);
64
+ if (!config.apiBaseUrl.startsWith("https://")) return /* @__PURE__ */ new Error(`wecom: apiBaseUrl must be an https URL, got "${config.apiBaseUrl}"`);
65
+ }
66
+ // lib/types/errors.js
67
+ /**
68
+ * Platform failures of the WeCom REST surface and their mapping onto the core taxonomy.
69
+ *
70
+ * Almost every failure has one shape: HTTP 200 with `{ errcode, errmsg }`, where `errcode === 0` is success. The HTTP
71
+ * layer only fails for a transport problem or a gateway. `published: 'no'` is therefore reserved for a platform refusal
72
+ * this adapter can classify; an answer without a code, a non-JSON page and a 5xx leave the outcome open.
73
+ */
74
+ /** One failed WeCom API call. */
75
+ var WecomApiError = class extends Error {
76
+ status;
77
+ errcode;
78
+ errmsg;
79
+ bodyText;
80
+ nonJson;
81
+ constructor(message, init = {}) {
82
+ super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
83
+ this.name = "WecomApiError";
84
+ this.status = init.status;
85
+ this.errcode = init.errcode;
86
+ this.errmsg = init.errmsg;
87
+ this.bodyText = init.bodyText;
88
+ this.nonJson = init.nonJson ?? false;
89
+ }
90
+ };
91
+ const RATE_LIMIT = {
92
+ kind: "rate-limit",
93
+ published: "no"
94
+ };
95
+ const LIMIT = {
96
+ kind: "limit",
97
+ published: "no"
98
+ };
99
+ const PERMISSION = {
100
+ kind: "permission",
101
+ published: "no"
102
+ };
103
+ const NOT_FOUND = {
104
+ kind: "not-found",
105
+ published: "no"
106
+ };
107
+ const INVALID = {
108
+ kind: "invalid",
109
+ published: "no"
110
+ };
111
+ const RETRYABLE = {
112
+ kind: "retryable",
113
+ published: "unknown"
114
+ };
115
+ /**
116
+ * The codes of 全局错误码 this adapter actually meets.
117
+ *
118
+ * A refusal the platform names is a request it rejected before publishing anything, so every entry is `published: 'no'`.
119
+ */
120
+ const CODE_VERDICTS = /* @__PURE__ */ new Map([
121
+ [40001, PERMISSION],
122
+ [40013, PERMISSION],
123
+ [40014, PERMISSION],
124
+ [42001, PERMISSION],
125
+ [40003, NOT_FOUND],
126
+ [40007, INVALID],
127
+ [40008, INVALID],
128
+ [44001, INVALID],
129
+ [45002, LIMIT],
130
+ [45009, RATE_LIMIT],
131
+ [45033, RATE_LIMIT],
132
+ [48002, PERMISSION],
133
+ [60011, PERMISSION],
134
+ [81013, PERMISSION],
135
+ [82001, INVALID],
136
+ [830002, LIMIT]
137
+ ]);
138
+ /** Codes outside the documented table whose whole family has one verdict. */
139
+ const FAMILY_VERDICTS = /* @__PURE__ */ new Map([
140
+ [41001, PERMISSION],
141
+ [48004, PERMISSION],
142
+ [60020, PERMISSION],
143
+ [301002, PERMISSION]
144
+ ]);
145
+ /** Whether a code means the `access_token` was refused, so the token is re-minted and the call retried once. */
146
+ const TOKEN_FAILURE_CODES = /* @__PURE__ */ new Set([42001, 40014]);
147
+ /**
148
+ * Verdict of one business code, by the documented table and then by family.
149
+ *
150
+ * @param errcode - the `errcode` of an answer.
151
+ * @returns its classification, or undefined for a code inside no family this adapter knows.
152
+ */
153
+ function verdictOfCode(errcode) {
154
+ const exact = CODE_VERDICTS.get(errcode) ?? FAMILY_VERDICTS.get(errcode);
155
+ if (exact !== void 0) return exact;
156
+ const family = Math.trunc(errcode / 1e4);
157
+ if (family === 4) return INVALID;
158
+ if (family === 5) return RETRYABLE;
159
+ if (family === 6) return PERMISSION;
160
+ if (family === 8) return INVALID;
161
+ }
162
+ /**
163
+ * Whether an `errcode` means the `access_token` was refused.
164
+ *
165
+ * @param errcode - the code of an answer, when it carried one.
166
+ * @returns true for the two codes the platform documents as "refresh and retry".
167
+ */
168
+ function isTokenFailureCode(errcode) {
169
+ return errcode !== void 0 && TOKEN_FAILURE_CODES.has(errcode);
170
+ }
171
+ /**
172
+ * Whether a failed call means the `access_token` was refused.
173
+ *
174
+ * @param error - the caught failure.
175
+ * @returns true for the two codes the platform documents as "refresh and retry".
176
+ */
177
+ function isTokenFailure(error) {
178
+ return error instanceof WecomApiError && isTokenFailureCode(error.errcode);
179
+ }
180
+ /** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
181
+ function isAbortError(error) {
182
+ return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
183
+ }
184
+ /**
185
+ * Map any failure onto the core platform taxonomy.
186
+ *
187
+ * @param error - the caught failure.
188
+ * @returns the classified platform error.
189
+ */
190
+ function classifyWecomError(error) {
191
+ if (error instanceof PlatformError) return error;
192
+ if (error instanceof WecomApiError) {
193
+ const init = {
194
+ ...error.status === void 0 ? {} : { code: error.status },
195
+ cause: error
196
+ };
197
+ if (error.errcode !== void 0) {
198
+ const verdict = verdictOfCode(error.errcode) ?? RETRYABLE;
199
+ return new PlatformError(verdict.kind, error.message, {
200
+ ...init,
201
+ code: error.errcode,
202
+ published: verdict.published
203
+ });
204
+ }
205
+ if (error.status === 429) return new PlatformError("rate-limit", error.message, {
206
+ ...init,
207
+ published: "no"
208
+ });
209
+ if (error.status === void 0 || error.nonJson || error.status >= 500) return new PlatformError("retryable", error.message, {
210
+ ...init,
211
+ published: "unknown"
212
+ });
213
+ if (error.status !== void 0 && error.status >= 400) return new PlatformError("invalid", error.message, {
214
+ ...init,
215
+ published: "no"
216
+ });
217
+ return new PlatformError("retryable", error.message, {
218
+ ...init,
219
+ published: "unknown"
220
+ });
221
+ }
222
+ if (isAbortError(error)) return new PlatformError("fatal", error.message, {
223
+ published: "unknown",
224
+ cause: error
225
+ });
226
+ const message = error instanceof Error ? error.message : String(error);
227
+ return new PlatformError("retryable", `wecom: request failed: ${message}`, {
228
+ published: "unknown",
229
+ cause: error
230
+ });
231
+ }
232
+ // lib/types/identity.js
233
+ /** Failure to confirm the configured application identity. */
234
+ var WecomIdentityError = class extends Error {
235
+ constructor(message) {
236
+ super(message);
237
+ this.name = "WecomIdentityError";
238
+ }
239
+ };
240
+ /**
241
+ * Verify an `agent/get` answer against the configured `AgentID` and turn it into `bot.user`.
242
+ *
243
+ * `bot.id` and `selfId` are fixed at construction, so the application is identified from configuration rather than
244
+ * discovered; this call proves the credentials belong to that application. A mismatch is a configuration error that no
245
+ * retry repairs.
246
+ *
247
+ * @param agentId - the configured `AgentID`.
248
+ * @param answer - the `GET /cgi-bin/agent/get` answer.
249
+ * @returns the bot's own user, with the name and logo the platform reports.
250
+ * @throws WecomIdentityError when the answer names another application.
251
+ */
252
+ function verifyIdentity(agentId, answer) {
253
+ if (answer.agentid === void 0 || Number(answer.agentid) !== Number(agentId)) throw new WecomIdentityError(`wecom: agentId is ${agentId} but agent/get returned ${String(answer.agentid)}`);
254
+ return {
255
+ id: agentId,
256
+ ...answer.name === void 0 ? {} : { name: answer.name },
257
+ ...answer.square_logo_url === void 0 ? {} : { avatar: answer.square_logo_url },
258
+ isBot: true
259
+ };
260
+ }
261
+ // lib/types/request.js
262
+ /** Endpoints that mint a token themselves and therefore carry no `access_token`. */
263
+ const CREDENTIAL_PATHS = /* @__PURE__ */ new Set(["/cgi-bin/gettoken"]);
264
+ /** How much of a non-JSON answer is kept in the error and the log; enough to recognise a gateway page. */
265
+ const BODY_PREFIX_BYTES = 512;
266
+ /** Message of any caught value, for a log line. */
267
+ function messageOf$4(error) {
268
+ return error instanceof Error ? error.message : String(error);
269
+ }
270
+ /** Whether a failed `ctx.http` call was the caller's cancellation rather than a transport failure. */
271
+ function isCancellation(cause, signal) {
272
+ if (signal?.aborted === true) return true;
273
+ if ((cause instanceof Error || cause instanceof DOMException) && cause.name === "AbortError") return true;
274
+ return signal?.reason !== void 0 && cause === signal.reason;
275
+ }
276
+ /** A cancelled request rejects with the signal's reason, so the classifier sees the cancellation itself. */
277
+ function cancellation(cause, signal) {
278
+ return signal?.aborted === true ? signal.reason : cause;
279
+ }
280
+ /** One JSON object, when the value is a plain object. */
281
+ function asRecord(value) {
282
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
283
+ }
284
+ /**
285
+ * The absolute URL of one endpoint.
286
+ *
287
+ * @param config - the adapter configuration holding the API root.
288
+ * @param path - endpoint path under the root, e.g. `/cgi-bin/message/send`.
289
+ * @returns the absolute request URL.
290
+ */
291
+ function endpointOf(config, path) {
292
+ return `${config.apiBaseUrl.replace(/\/+$/, "")}${path}`;
293
+ }
294
+ /** The request URL with the token and the query parameters applied. */
295
+ function urlOf(endpoint, path, params, token) {
296
+ const url = new URL(endpointOf(endpoint.config, path));
297
+ if (token !== void 0) url.searchParams.set("access_token", token);
298
+ for (const [name, value] of Object.entries(params ?? {})) if (value !== void 0) url.searchParams.set(name, String(value));
299
+ return url;
300
+ }
301
+ /**
302
+ * The access token of one request, or undefined for the endpoint that mints it.
303
+ *
304
+ * @param endpoint - the adapter whose token cache the call uses.
305
+ * @param path - endpoint path.
306
+ * @returns the token to carry, if the endpoint needs one.
307
+ */
308
+ async function authorization(endpoint, path) {
309
+ if (CREDENTIAL_PATHS.has(path)) return void 0;
310
+ return await endpoint.tokens.get();
311
+ }
312
+ /** Read one answer body as text, turning a cancelled read into a cancellation. */
313
+ async function readText(response, path, signal) {
314
+ try {
315
+ return await response.text();
316
+ } catch (cause) {
317
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
318
+ throw new WecomApiError(`wecom: ${path} answered ${response.status} but its body could not be read`, {
319
+ status: response.status,
320
+ cause
321
+ });
322
+ }
323
+ }
324
+ /** Send one request and unwrap its `{ errcode, errmsg }` envelope. */
325
+ async function send(endpoint, method, path, config, token) {
326
+ let response;
327
+ try {
328
+ response = await endpoint.ctx.http(urlOf(endpoint, path, config.params, token), {
329
+ method,
330
+ ...config.data === void 0 ? {} : { data: config.data },
331
+ ...config.signal === void 0 ? {} : { signal: config.signal }
332
+ });
333
+ } catch (cause) {
334
+ if (isCancellation(cause, config.signal)) throw cancellation(cause, config.signal);
335
+ throw new WecomApiError(`wecom: ${method} ${path} request failed: ${messageOf$4(cause)}`, { cause });
336
+ }
337
+ const text = await readText(response, path, config.signal);
338
+ let body;
339
+ let nonJson = false;
340
+ if (text !== "") try {
341
+ body = JSON.parse(text);
342
+ } catch {
343
+ nonJson = true;
344
+ }
345
+ const record = asRecord(body);
346
+ const errcode = record?.errcode === void 0 ? void 0 : Number(record.errcode);
347
+ const errmsg = typeof record?.errmsg === "string" ? record.errmsg : void 0;
348
+ const suffix = (errcode === void 0 ? "" : ` (${errcode})`) + (errmsg === void 0 ? "" : `: ${errmsg}`);
349
+ const detail = {
350
+ status: response.status,
351
+ ...text === "" ? {} : { bodyText: text.slice(0, BODY_PREFIX_BYTES) },
352
+ ...errmsg === void 0 ? {} : { errmsg }
353
+ };
354
+ if (response.status < 200 || response.status >= 300 || nonJson) throw new WecomApiError(`wecom: ${method} ${path} answered ${response.status}${suffix}`, {
355
+ ...detail,
356
+ nonJson
357
+ });
358
+ if (errcode !== void 0 && errcode !== 0) throw new WecomApiError(`wecom: ${method} ${path} answered ${response.status}${suffix}`, {
359
+ ...detail,
360
+ errcode
361
+ });
362
+ return body;
363
+ }
364
+ /**
365
+ * Call one WeCom endpoint.
366
+ *
367
+ * A call refused for its `access_token` re-mints the token and is retried once; every other failure is thrown as the
368
+ * `WecomApiError` `classify` maps. A cancelled call rejects with the cancellation itself.
369
+ *
370
+ * @param endpoint - the adapter whose configuration and token cache the call uses.
371
+ * @param method - HTTP method.
372
+ * @param path - endpoint path under the API root.
373
+ * @param config - body, query parameters and cancellation of the call.
374
+ * @returns the unwrapped JSON answer.
375
+ * @throws WecomApiError when the platform refused the call or did not answer with JSON.
376
+ */
377
+ async function invoke(endpoint, method, path, config = {}) {
378
+ const token = await authorization(endpoint, path);
379
+ try {
380
+ return await send(endpoint, method, path, config, token);
381
+ } catch (error) {
382
+ if (!isTokenFailure(error) || token === void 0) throw error;
383
+ endpoint.tokens.invalidate();
384
+ return await send(endpoint, method, path, config, await authorization(endpoint, path));
385
+ }
386
+ }
387
+ /** One download attempt with one token. */
388
+ async function attempt(endpoint, path, params, signal) {
389
+ const token = await endpoint.tokens.get();
390
+ try {
391
+ return await endpoint.ctx.http(urlOf(endpoint, path, params, token), {
392
+ method: "GET",
393
+ ...signal === void 0 ? {} : { signal }
394
+ });
395
+ } catch (cause) {
396
+ if (isCancellation(cause, signal)) throw cancellation(cause, signal);
397
+ throw new WecomApiError(`wecom: GET ${path} request failed: ${messageOf$4(cause)}`, { cause });
398
+ }
399
+ }
400
+ /**
401
+ * Whether a download answer is the platform's token refusal rather than bytes.
402
+ *
403
+ * `media/get` answers the bytes on success and an `{ errcode }` JSON envelope on a refusal, still with HTTP 200, so the
404
+ * token races the same invalidation a JSON call does.
405
+ */
406
+ async function isTokenRefusal(response) {
407
+ if (!(response.headers.get("content-type") ?? "").includes("application/json")) return false;
408
+ try {
409
+ const body = asRecord(await response.clone().json());
410
+ return isTokenFailureCode(body?.errcode === void 0 ? void 0 : Number(body.errcode));
411
+ } catch {
412
+ return false;
413
+ }
414
+ }
415
+ /**
416
+ * Download the bytes of one inbound media object.
417
+ *
418
+ * `media/get` answers the bytes themselves on success and a JSON `{ errcode }` envelope on failure, so the answer is
419
+ * returned as it arrived and mapped by the caller. A refusal for the `access_token` re-mints it and retries once. A
420
+ * cancelled download rejects with the cancellation itself.
421
+ *
422
+ * @param endpoint - the adapter whose credentials the download uses.
423
+ * @param path - endpoint path under the API root.
424
+ * @param params - query parameters of the download.
425
+ * @param signal - cancellation.
426
+ * @returns the answer, status and headers included.
427
+ */
428
+ async function download(endpoint, path, params, signal) {
429
+ const response = await attempt(endpoint, path, params, signal);
430
+ if (!await isTokenRefusal(response)) return response;
431
+ endpoint.tokens.invalidate();
432
+ return await attempt(endpoint, path, params, signal);
433
+ }
434
+ // lib/types/internal.js
435
+ /**
436
+ * The mapped WeCom REST surface: one method per platform endpoint of the adapter's scope, and nothing hand-written on
437
+ * top of it.
438
+ *
439
+ * Every method goes through `request.ts`, so `access_token` injection, `errcode` unwrapping and the refresh-and-retry of
440
+ * a refused token are identical for all of them.
441
+ */
442
+ var Internal = class {
443
+ bot;
444
+ constructor(bot) {
445
+ this.bot = bot;
446
+ }
447
+ /**
448
+ * Exchange the enterprise credentials for an application `access_token`.
449
+ *
450
+ * @param input - the enterprise id and the application secret.
451
+ * @returns the token envelope, with `expires_in`.
452
+ */
453
+ async getToken(input) {
454
+ return await invoke(this.bot, "GET", "/cgi-bin/gettoken", { params: {
455
+ corpid: input.corpid,
456
+ corpsecret: input.corpsecret
457
+ } });
458
+ }
459
+ /**
460
+ * Read one application's own description.
461
+ *
462
+ * @param input - the numeric `AgentID`.
463
+ * @returns the application envelope, with `name` and `square_logo_url`.
464
+ */
465
+ async agentGet(input) {
466
+ return await invoke(this.bot, "GET", "/cgi-bin/agent/get", { params: { agentid: input.agentid } });
467
+ }
468
+ /**
469
+ * Read one member of the enterprise address book.
470
+ *
471
+ * @param input - the member userid.
472
+ * @returns the member envelope, with `name` when the application may see it.
473
+ */
474
+ async userGet(input) {
475
+ return await invoke(this.bot, "GET", "/cgi-bin/user/get", { params: { userid: input.userid } });
476
+ }
477
+ /**
478
+ * Push one application message.
479
+ *
480
+ * @param input - the exact `message/send` body.
481
+ * @returns the send envelope, with `msgid` and the invalid-recipient lists.
482
+ */
483
+ async messageSend(input) {
484
+ return await invoke(this.bot, "POST", "/cgi-bin/message/send", { data: input });
485
+ }
486
+ /**
487
+ * Upload one temporary media file.
488
+ *
489
+ * @param input - the platform media type (`image`, `voice`, `video`, `file`) and the multipart form.
490
+ * @returns the upload envelope, with `media_id` and `created_at`.
491
+ */
492
+ async mediaUpload(input, signal) {
493
+ return await invoke(this.bot, "POST", "/cgi-bin/media/upload", {
494
+ params: { type: input.type },
495
+ data: input.media,
496
+ ...signal === void 0 ? {} : { signal }
497
+ });
498
+ }
499
+ /**
500
+ * Download the bytes of one temporary media file.
501
+ *
502
+ * @param input - the `media_id` the callback carried.
503
+ * @param signal - cancellation.
504
+ * @returns the answer as it arrived: the bytes, or the platform's JSON refusal.
505
+ */
506
+ async mediaGet(input, signal) {
507
+ return await download(this.bot, "/cgi-bin/media/get", { media_id: input.media_id }, signal);
508
+ }
509
+ /**
510
+ * Recall one published application message.
511
+ *
512
+ * @param input - the `msgid` the send answer carried.
513
+ * @returns the status envelope.
514
+ */
515
+ async messageRecall(input) {
516
+ return await invoke(this.bot, "POST", "/cgi-bin/message/recall", { data: { msgid: input.msgid } });
517
+ }
518
+ /**
519
+ * Update one button-interaction card, within the platform's 72-hour, single-use window.
520
+ *
521
+ * @param input - the recipients, the card identity and the new card or button.
522
+ * @returns the status envelope.
523
+ */
524
+ async updateTemplateCard(input) {
525
+ return await invoke(this.bot, "POST", "/cgi-bin/message/update_template_card", { data: input });
526
+ }
527
+ /**
528
+ * Send one message into an application group chat.
529
+ *
530
+ * @param input - the group chat id and the message fields.
531
+ * @returns the send envelope.
532
+ */
533
+ async appchatSend(input) {
534
+ return await invoke(this.bot, "POST", "/cgi-bin/appchat/send", { data: input });
535
+ }
536
+ };
537
+ // lib/types/media.js
538
+ /**
539
+ * Media in both directions.
540
+ *
541
+ * Outbound, the platform has a real upload endpoint: the bytes are fetched, posted to `media/upload` as a multipart form
542
+ * and the returned `media_id` is what a `message/send` of type `image`/`voice`/`video`/`file` carries. The id lives three
543
+ * days, so the resolved resource carries an `expiresAt` and the core uploads the same content again after that instead of
544
+ * reusing an id the platform has already dropped.
545
+ *
546
+ * Inbound, the callback names only a `MediaId`; the bytes are read on demand from `media/get` through the bot's own
547
+ * `satori:` route.
548
+ */
549
+ /** How long a temporary `media_id` stays readable: the platform documents three days. */
550
+ const MEDIA_LIFETIME_MS = 2592e5;
551
+ /** Message of any caught value, for a log line. */
552
+ function messageOf$3(error) {
553
+ return error instanceof Error ? error.message : String(error);
554
+ }
555
+ /**
556
+ * The platform upload type of one resource kind.
557
+ *
558
+ * @param kind - the resource kind of the element.
559
+ * @returns `image`, `voice`, `video` or `file`; the platform names audio `voice`.
560
+ */
561
+ function mediaTypeOf(kind) {
562
+ switch (kind) {
563
+ case "image": return "image";
564
+ case "audio": return "voice";
565
+ case "video": return "video";
566
+ case "file": return "file";
567
+ }
568
+ }
569
+ /** File name of a source, for the multipart part of an upload. */
570
+ function fileNameOf(ref, fetchedName, mime) {
571
+ if (ref.meta.name !== void 0 && ref.meta.name !== "") return ref.meta.name;
572
+ if (fetchedName !== void 0 && fetchedName !== "") return fetchedName;
573
+ const subtype = mime?.split("/")[1]?.split(";")[0];
574
+ return `wecom-${ref.kind}${subtype === void 0 ? "" : `.${subtype}`}`;
575
+ }
576
+ /**
577
+ * Upload one outbound attachment and return the `media_id` a send references.
578
+ *
579
+ * @param bot - the adapter whose credentials the upload uses.
580
+ * @param ref - the unresolved resource.
581
+ * @param ctx - fetch context of the send pipeline.
582
+ * @returns the platform media key, with the three-day expiry the core caches against.
583
+ * @throws PlatformError with an unknown outcome when the platform accepted the upload without returning an id.
584
+ */
585
+ async function uploadMedia(bot, ref, ctx) {
586
+ const fetched = await ctx.fetch(ref.src, ctx.signal);
587
+ const mime = ref.meta.mime ?? fetched.mime;
588
+ const name = fileNameOf(ref, fetched.name, mime);
589
+ const type = mediaTypeOf(ref.kind);
590
+ const form = new FormData();
591
+ form.append("media", new Blob([fetched.data], mime === void 0 ? {} : { type: mime }), name);
592
+ const answer = await bot.internal.mediaUpload({
593
+ type,
594
+ media: form
595
+ }, ctx.signal);
596
+ if (answer.media_id === void 0 || answer.media_id === "") throw new PlatformError("invalid", "wecom: /cgi-bin/media/upload answered without a media_id", { published: "unknown" });
597
+ const createdAt = answer.created_at;
598
+ return {
599
+ key: answer.media_id,
600
+ ...typeof createdAt === "number" && Number.isFinite(createdAt) ? { expiresAt: createdAt * 1e3 + MEDIA_LIFETIME_MS } : {},
601
+ extra: {
602
+ type,
603
+ name,
604
+ ...mime === void 0 ? {} : { mime },
605
+ size: fetched.data.byteLength
606
+ }
607
+ };
608
+ }
609
+ /**
610
+ * Serve the bytes of one inbound media object.
611
+ *
612
+ * A `media_id` the platform no longer accepts (it lives three days), a file above the 20 MB the plain download serves and
613
+ * a transport failure all answer `502`: the stored element keeps its label, but its bytes are gone.
614
+ *
615
+ * @param bot - the receiving adapter.
616
+ * @param mediaId - the `MediaId` the callback carried.
617
+ * @returns the bytes with their own headers, or the refusal status.
618
+ */
619
+ async function serveMedia(bot, mediaId) {
620
+ let response;
621
+ try {
622
+ response = await bot.internal.mediaGet({ media_id: mediaId });
623
+ } catch (error) {
624
+ bot.ctx.logger.warn("wecom: media %s could not be downloaded: %s", mediaId, messageOf$3(error));
625
+ return new Response(null, { status: 502 });
626
+ }
627
+ const contentType = response.headers.get("content-type") ?? "";
628
+ if (!response.ok || contentType.includes("application/json")) {
629
+ bot.ctx.logger.warn("wecom: media %s answered %s: %s", mediaId, String(response.status), contentType.includes("application/json") ? await response.text() : contentType);
630
+ return new Response(null, { status: 502 });
631
+ }
632
+ const headers = new Headers();
633
+ if (contentType !== "") headers.set("content-type", contentType);
634
+ const disposition = response.headers.get("content-disposition");
635
+ if (disposition !== null) headers.set("content-disposition", disposition);
636
+ return new Response(response.body, {
637
+ status: response.status,
638
+ headers
639
+ });
640
+ }
641
+ // lib/types/modes/shared.js
642
+ /**
643
+ * Shared types and the draft machinery of the single `markdown` mode.
644
+ *
645
+ * A WeCom application message is one `message/send` call, and its `msgtype` decides what it can carry: `markdown` holds
646
+ * the formatted body, `image`/`voice`/`video`/`file` hold one `media_id` each, and `template_card` holds the buttons.
647
+ * A draft is therefore exactly one platform message: the body is split at the documented 2,048 bytes, every media
648
+ * element becomes a message of its own, and a message with buttons gets a card message after its body.
649
+ */
650
+ /** The platform's documented bounds, and nothing else. */
651
+ const WECOM_LIMITS = {
652
+ /** `text.content` and `markdown.content`: at most 2,048 bytes, counted as UTF-8. */
653
+ payloadBytes: 2048,
654
+ /** `message/recall` accepts a message up to 24 hours after it was sent. */
655
+ deleteWindow: 864e5,
656
+ /** `button_list` of a `button_interaction` card holds at most six buttons. */
657
+ buttonsRow: 6,
658
+ /** The card has one button row. */
659
+ buttonRows: 1
660
+ };
661
+ /** The word joiner a card title falls back to: the platform requires `main_title`, and content is never empty. */
662
+ const CARD_TITLE_FALLBACK = "⁠";
663
+ /** The process-wide random segment of every `task_id`, in base 36. */
664
+ let bootSalt = randomBytes(6).readUIntBE(0, 6).toString(36);
665
+ /** The sequence within this process; `task_id` must not repeat inside one application. */
666
+ let taskSequence = 0;
667
+ /**
668
+ * The `task_id` of one card.
669
+ *
670
+ * The platform requires the id to be unique within the application, so a counter alone would collide with the ids of the
671
+ * previous process after a restart; the random boot segment makes the pair unique across restarts.
672
+ *
673
+ * @returns an id the platform accepts: `0-9a-zA-Z_-` only, at most 128 bytes.
674
+ */
675
+ function nextTaskId() {
676
+ taskSequence += 1;
677
+ return `dsh-${bootSalt}-${taskSequence}`;
678
+ }
679
+ /**
680
+ * Report inline media that moves out of its text run into a message of its own.
681
+ *
682
+ * @param el - the media element.
683
+ * @param ctx - the render context.
684
+ */
685
+ function reportMovedMedia(el, ctx) {
686
+ const parent = ctx.ancestors[ctx.ancestors.length - 1];
687
+ if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
688
+ tag: el.type,
689
+ reason: "wecom-media-split",
690
+ path: ctx.stableId(el)
691
+ });
692
+ }
693
+ /**
694
+ * Cut one line into pieces of at most `limit` bytes, never inside a surrogate pair.
695
+ *
696
+ * @param text - the line to cut.
697
+ * @param limit - the byte bound.
698
+ * @returns the pieces, in order; concatenating them reproduces the line.
699
+ */
700
+ function hardCutBytes(text, limit) {
701
+ const pieces = [];
702
+ let piece = "";
703
+ let bytes = 0;
704
+ for (const character of text) {
705
+ const size = Buffer.byteLength(character, "utf8");
706
+ if (bytes + size > limit && piece !== "") {
707
+ pieces.push(piece);
708
+ piece = "";
709
+ bytes = 0;
710
+ }
711
+ piece += character;
712
+ bytes += size;
713
+ }
714
+ if (piece !== "") pieces.push(piece);
715
+ return pieces;
716
+ }
717
+ /**
718
+ * Cut a body into chunks the platform accepts.
719
+ *
720
+ * Lines are accumulated while they fit; a line that would overflow closes the current chunk, and a line longer than the
721
+ * bound is cut by bytes. A cut can land inside a formatting mark (`**`, `` ` ``), which the client then shows as literal
722
+ * characters: the platform documents no escape syntax that would avoid it.
723
+ *
724
+ * @param text - the body of one logical message.
725
+ * @param limit - the byte bound of one `markdown` message.
726
+ * @returns one or more chunks, in order; never empty.
727
+ */
728
+ function splitMarkdownBytes(text, limit = WECOM_LIMITS.payloadBytes) {
729
+ if (Buffer.byteLength(text, "utf8") <= limit) return [text];
730
+ const chunks = [];
731
+ let current = "";
732
+ let currentBytes = 0;
733
+ const close = () => {
734
+ if (current !== "") chunks.push(current);
735
+ current = "";
736
+ currentBytes = 0;
737
+ };
738
+ for (const line of text.split(/(?<=\n)/)) {
739
+ const lineBytes = Buffer.byteLength(line, "utf8");
740
+ if (currentBytes + lineBytes <= limit) {
741
+ current += line;
742
+ currentBytes += lineBytes;
743
+ continue;
744
+ }
745
+ close();
746
+ if (lineBytes <= limit) {
747
+ current = line;
748
+ currentBytes = lineBytes;
749
+ continue;
750
+ }
751
+ const pieces = hardCutBytes(line, limit);
752
+ for (const piece of pieces.slice(0, -1)) chunks.push(piece);
753
+ current = pieces[pieces.length - 1] ?? "";
754
+ currentBytes = Buffer.byteLength(current, "utf8");
755
+ }
756
+ close();
757
+ return chunks.length === 0 ? [""] : chunks;
758
+ }
759
+ /** Strip the newlines a paragraph puts around the content of one list item. */
760
+ function trimEdges(nodes) {
761
+ const out = [...nodes];
762
+ while (out.length > 0) {
763
+ const first = out[0];
764
+ if (first.type !== "text") break;
765
+ const stripped = first.text.replace(/^\n+/, "");
766
+ if (stripped === "") {
767
+ out.shift();
768
+ continue;
769
+ }
770
+ out[0] = {
771
+ type: "text",
772
+ text: stripped
773
+ };
774
+ break;
775
+ }
776
+ while (out.length > 0) {
777
+ const last = out[out.length - 1];
778
+ if (last.type !== "text") break;
779
+ const stripped = last.text.replace(/\n+$/, "");
780
+ if (stripped === "") {
781
+ out.pop();
782
+ continue;
783
+ }
784
+ out[out.length - 1] = {
785
+ type: "text",
786
+ text: stripped
787
+ };
788
+ break;
789
+ }
790
+ return out;
791
+ }
792
+ /** Put a list marker at the start of the item's first line, or before its first media node. */
793
+ function applyMarker(nodes, marker) {
794
+ for (let index = 0; index < nodes.length; index++) {
795
+ const node = nodes[index];
796
+ if (node.type !== "text") {
797
+ nodes.splice(index, 0, {
798
+ type: "text",
799
+ text: marker.trimEnd()
800
+ });
801
+ return;
802
+ }
803
+ const leading = /^\n*/.exec(node.text)?.[0].length ?? 0;
804
+ if (leading < node.text.length) {
805
+ nodes[index] = {
806
+ type: "text",
807
+ text: `${node.text.slice(0, leading)}${marker}${node.text.slice(leading)}`
808
+ };
809
+ return;
810
+ }
811
+ }
812
+ }
813
+ /** One list node, expanded into one line per item. */
814
+ function flattenList(node, depth) {
815
+ const out = [];
816
+ const indent = " ".repeat(depth);
817
+ let number = node.start;
818
+ node.items.forEach((item, index) => {
819
+ const marker = node.ordered ? `${indent}${number++}. ` : `${indent}- `;
820
+ const inner = trimEdges(flattenAt(item.type === "item" ? item.nodes : [item], depth + 1));
821
+ if (index > 0) out.push({
822
+ type: "text",
823
+ text: "\n"
824
+ });
825
+ if (inner.length === 0) {
826
+ out.push({
827
+ type: "text",
828
+ text: marker.trimEnd()
829
+ });
830
+ return;
831
+ }
832
+ applyMarker(inner, marker);
833
+ out.push(...inner);
834
+ });
835
+ if (out.length > 0) out.push({
836
+ type: "text",
837
+ text: "\n"
838
+ });
839
+ return out;
840
+ }
841
+ /** Expand every list and item of one node stream. */
842
+ function flattenAt(nodes, depth) {
843
+ const out = [];
844
+ for (const node of nodes) switch (node.type) {
845
+ case "text":
846
+ case "media":
847
+ case "button":
848
+ case "link-button":
849
+ out.push(node);
850
+ break;
851
+ case "item":
852
+ out.push(...flattenAt(node.nodes, depth));
853
+ break;
854
+ case "list": {
855
+ const last = out[out.length - 1];
856
+ if (last !== void 0 && !(last.type === "text" && last.text.endsWith("\n"))) out.push({
857
+ type: "text",
858
+ text: "\n"
859
+ });
860
+ out.push(...flattenList(node, depth));
861
+ break;
862
+ }
863
+ }
864
+ return out;
865
+ }
866
+ /**
867
+ * Expand list and item nodes into the flat node stream {@link assembleDraft} splits into messages.
868
+ *
869
+ * @param nodes - rendered nodes, in document order.
870
+ * @returns the same content with every list marker applied and media nodes kept in place.
871
+ */
872
+ function flattenNodes(nodes) {
873
+ return flattenAt(nodes, 0);
874
+ }
875
+ /** The media draft of one media node. */
876
+ function mediaDraftOf(node) {
877
+ return {
878
+ kind: "media",
879
+ media: node.media,
880
+ ref: node.ref,
881
+ ...node.name === void 0 ? {} : { name: node.name }
882
+ };
883
+ }
884
+ /**
885
+ * Fold a node stream into platform messages.
886
+ *
887
+ * The text buffer is split by bytes and closed before every media element; the collected buttons become one card
888
+ * message after the body, and a seventh button onwards degrades to a `[label]` line in the body. The title of the
889
+ * envelope stays in the body as a bold line and becomes the card's `main_title` when there is a card, so a title is
890
+ * never lost on a message without buttons.
891
+ *
892
+ * @param nodes - rendered nodes, in document order.
893
+ * @param envelope - the root `<title>`, if the content carried one.
894
+ * @param ctx - the render context, for the split and drop reports.
895
+ * @returns one draft per platform message, in send order; never empty.
896
+ */
897
+ function assembleDraft(nodes, envelope, ctx) {
898
+ const drafts = [];
899
+ const buttons = [];
900
+ let buffer = "";
901
+ let firstLine = "";
902
+ let split = 0;
903
+ const noteFirstLine = (text) => {
904
+ if (firstLine !== "") return;
905
+ for (const line of text.split("\n")) {
906
+ const trimmed = line.trim();
907
+ if (trimmed !== "") {
908
+ firstLine = trimmed;
909
+ return;
910
+ }
911
+ }
912
+ };
913
+ const flushText = () => {
914
+ const text = buffer.replace(/^\n+/, "").replace(/\n+$/, "");
915
+ buffer = "";
916
+ if (text === "") return;
917
+ noteFirstLine(text);
918
+ const chunks = splitMarkdownBytes(text);
919
+ split += chunks.length - 1;
920
+ for (const chunk of chunks) drafts.push({
921
+ kind: "markdown",
922
+ content: chunk
923
+ });
924
+ };
925
+ const title = envelope.title;
926
+ const titleText = title === void 0 ? "" : ctx.text(title.children).trim();
927
+ if (titleText !== "") {
928
+ buffer += `**${titleText}**`;
929
+ const subtitle = title?.attrs.subtitle;
930
+ if (subtitle !== void 0 && subtitle !== "") buffer += `\n${subtitle}`;
931
+ buffer += "\n";
932
+ }
933
+ for (const node of flattenNodes(nodes)) switch (node.type) {
934
+ case "text":
935
+ buffer += node.text;
936
+ break;
937
+ case "media":
938
+ flushText();
939
+ drafts.push(mediaDraftOf(node));
940
+ break;
941
+ case "button":
942
+ buttons.push({
943
+ text: node.text,
944
+ key: node.key
945
+ });
946
+ break;
947
+ case "link-button": buttons.push({
948
+ text: node.text,
949
+ href: node.href
950
+ });
951
+ }
952
+ if (buttons.length > WECOM_LIMITS.buttonsRow) for (const button of buttons.splice(WECOM_LIMITS.buttonsRow)) {
953
+ const label = "key" in button ? button.key : button.text;
954
+ ctx.report.dropped.push({
955
+ what: `button:${label}`,
956
+ reason: INTERACTION_DROPPED
957
+ });
958
+ buffer += `[${button.text}]\n`;
959
+ }
960
+ if (buttons.length > 0) {
961
+ flushText();
962
+ drafts.push({
963
+ kind: "card",
964
+ title: titleText !== "" ? titleText : firstLine !== "" ? firstLine : "⁠",
965
+ taskId: nextTaskId(),
966
+ buttons: [...buttons]
967
+ });
968
+ if (drafts.length > 1) split += 1;
969
+ } else flushText();
970
+ ctx.report.split += split;
971
+ if (drafts.length === 0) drafts.push({
972
+ kind: "markdown",
973
+ content: "⁠"
974
+ });
975
+ return drafts;
976
+ }
977
+ /** One resolved resource key of a prepared draft. */
978
+ function resolvedKey(prepared, ref) {
979
+ const resolved = prepared.resolved.get(ref);
980
+ if (resolved === void 0) throw new Error("wecom: media was not prepared before serialize");
981
+ return resolved.key;
982
+ }
983
+ /**
984
+ * Build the exact request body of one prepared draft.
985
+ *
986
+ * @param prepared - the draft with its resource keys resolved.
987
+ * @param ctx - the send context: the target chat names the `touser` recipient.
988
+ * @param agentId - the numeric `AgentID` every send carries.
989
+ * @returns the `message/send` body.
990
+ */
991
+ function serializeDraft(prepared, ctx, agentId) {
992
+ const touser = ctx.target.chat.id;
993
+ const draft = prepared.draft;
994
+ switch (draft.kind) {
995
+ case "markdown": return {
996
+ touser,
997
+ agentid: agentId,
998
+ msgtype: "markdown",
999
+ markdown: { content: draft.content }
1000
+ };
1001
+ case "media": {
1002
+ const mediaId = resolvedKey(prepared, draft.ref);
1003
+ switch (draft.media) {
1004
+ case "image": return {
1005
+ touser,
1006
+ agentid: agentId,
1007
+ msgtype: "image",
1008
+ image: { media_id: mediaId }
1009
+ };
1010
+ case "voice": return {
1011
+ touser,
1012
+ agentid: agentId,
1013
+ msgtype: "voice",
1014
+ voice: { media_id: mediaId }
1015
+ };
1016
+ case "file": return {
1017
+ touser,
1018
+ agentid: agentId,
1019
+ msgtype: "file",
1020
+ file: { media_id: mediaId }
1021
+ };
1022
+ case "video": return {
1023
+ touser,
1024
+ agentid: agentId,
1025
+ msgtype: "video",
1026
+ video: {
1027
+ media_id: mediaId,
1028
+ ...draft.name === void 0 ? {} : { title: draft.name }
1029
+ }
1030
+ };
1031
+ }
1032
+ throw new Error("wecom: unknown media kind");
1033
+ }
1034
+ case "card": return {
1035
+ touser,
1036
+ agentid: agentId,
1037
+ msgtype: "template_card",
1038
+ template_card: {
1039
+ card_type: "button_interaction",
1040
+ main_title: { title: draft.title },
1041
+ button_list: draft.buttons.map((button) => "key" in button ? {
1042
+ text: button.text,
1043
+ key: button.key
1044
+ } : {
1045
+ text: button.text,
1046
+ type: 1,
1047
+ url: button.href
1048
+ }),
1049
+ task_id: draft.taskId
1050
+ }
1051
+ };
1052
+ }
1053
+ }
1054
+ /**
1055
+ * Hard platform limits of one draft, checked before any request.
1056
+ *
1057
+ * Splitting already keeps the body inside the byte bound and the card inside the button bound; the checks stay as the
1058
+ * only place the adapter refuses a draft the platform would answer `45002` for.
1059
+ *
1060
+ * @param draft - the assembled draft.
1061
+ * @returns every violation the platform would refuse.
1062
+ */
1063
+ function checkDraft(draft) {
1064
+ switch (draft.kind) {
1065
+ case "markdown": {
1066
+ const bytes = Buffer.byteLength(draft.content, "utf8");
1067
+ if (bytes <= WECOM_LIMITS.payloadBytes) return [];
1068
+ return [{
1069
+ kind: "size",
1070
+ key: "limit.payload.bytes",
1071
+ limit: WECOM_LIMITS.payloadBytes,
1072
+ actual: bytes,
1073
+ message: `WeCom markdown accepts ${WECOM_LIMITS.payloadBytes} bytes, got ${bytes}`
1074
+ }];
1075
+ }
1076
+ case "card": {
1077
+ const violations = [];
1078
+ if (draft.buttons.length > WECOM_LIMITS.buttonsRow) violations.push({
1079
+ kind: "size",
1080
+ key: "limit.buttons.row",
1081
+ limit: WECOM_LIMITS.buttonsRow,
1082
+ actual: draft.buttons.length,
1083
+ message: `WeCom cards accept ${WECOM_LIMITS.buttonsRow} buttons, got ${draft.buttons.length}`
1084
+ });
1085
+ if (draft.taskId === "") violations.push({
1086
+ kind: "shape",
1087
+ message: "WeCom cards need a task_id"
1088
+ });
1089
+ return violations;
1090
+ }
1091
+ case "media": return [];
1092
+ }
1093
+ }
1094
+ // lib/types/modes/markdown.js
1095
+ /**
1096
+ * `markdown` mode: the single outbound representation of an application message.
1097
+ *
1098
+ * The body is sent verbatim — the platform documents a markdown subset but no escape syntax, so nothing is escaped and
1099
+ * a pair of `*` in the text may render as bold. Headings, bold, links, inline code, block quotes, font colours,
1100
+ * mentions, lists and media have a native form; italic, underline, strike-through, spoilers, code blocks, rules,
1101
+ * tables, panels and form controls take the core fallback, which keeps their text and records the degradation.
1102
+ * Buttons become one `template_card` message after the body.
1103
+ */
1104
+ /** How a `span[color]` value maps onto the three colours the platform paints. */
1105
+ const FONT_COLOR = {
1106
+ default: void 0,
1107
+ muted: "comment",
1108
+ info: "info",
1109
+ success: "info",
1110
+ warning: "warning",
1111
+ danger: "warning"
1112
+ };
1113
+ /** The text run of rendered children and the nodes that cannot ride inside it. */
1114
+ function textRun(nodes) {
1115
+ let text = "";
1116
+ const rest = [];
1117
+ for (const node of nodes) if (node.type === "text") text += node.text;
1118
+ else rest.push(node);
1119
+ return {
1120
+ text,
1121
+ rest
1122
+ };
1123
+ }
1124
+ /** One inline mark around the rendered children, keeping any media of the subtree outside it. */
1125
+ function marked(children, ctx, open, close = open) {
1126
+ const run = textRun(ctx.render(children));
1127
+ if (run.text === "") return run.rest;
1128
+ return [{
1129
+ type: "text",
1130
+ text: `${open}${run.text}${close}`
1131
+ }, ...run.rest];
1132
+ }
1133
+ /** One rendered line: the platform has no multiline construct, so embedded newlines become spaces. */
1134
+ function oneLine(text) {
1135
+ return text.replace(/\s*\n+\s*/g, " ").trim();
1136
+ }
1137
+ /** One media message; a media element standing in phrasing content is reported as moved, not as degraded. */
1138
+ function mediaNode(media, kind, el, ctx, src, meta) {
1139
+ reportMovedMedia(el, ctx);
1140
+ const name = meta.name !== void 0 && meta.name !== "" ? meta.name : void 0;
1141
+ return {
1142
+ type: "media",
1143
+ media,
1144
+ ref: ctx.resource(kind, src, meta),
1145
+ ...name === void 0 ? {} : { name }
1146
+ };
1147
+ }
1148
+ /** The handler of one heading level: `#` repeated, then the text on a single line. */
1149
+ function heading(level) {
1150
+ return (el, ctx) => {
1151
+ const run = textRun(ctx.render(el.children));
1152
+ const text = oneLine(run.text);
1153
+ if (text === "") return run.rest;
1154
+ return [{
1155
+ type: "text",
1156
+ text: `\n${"#".repeat(level)} ${text}`
1157
+ }, ...run.rest];
1158
+ };
1159
+ }
1160
+ /** The handler of one list: its items are collected into a list node the assembler expands into lines. */
1161
+ function list(ordered, el, ctx) {
1162
+ return {
1163
+ type: "list",
1164
+ ordered,
1165
+ start: el.type === "ol" ? el.attrs.start ?? 1 : 1,
1166
+ items: ctx.render(el.children)
1167
+ };
1168
+ }
1169
+ /**
1170
+ * Build the `markdown` mode.
1171
+ *
1172
+ * @param config - the adapter configuration; it carries the numeric `AgentID` every request body repeats.
1173
+ * @returns the single mode this adapter registers.
1174
+ */
1175
+ function createMarkdownMode(config) {
1176
+ return {
1177
+ id: "markdown",
1178
+ elements: new ElementRegistry().register("text", (el) => ({
1179
+ type: "text",
1180
+ text: el.attrs.content
1181
+ })).register("br", () => ({
1182
+ type: "text",
1183
+ text: "\n"
1184
+ })).register("p", (el, ctx) => {
1185
+ const nodes = ctx.render(el.children);
1186
+ const run = textRun(nodes);
1187
+ const out = [{
1188
+ type: "text",
1189
+ text: "\n"
1190
+ }, ...nodes];
1191
+ if (!run.text.endsWith("\n")) out.push({
1192
+ type: "text",
1193
+ text: "\n"
1194
+ });
1195
+ return out;
1196
+ }).register("h1", heading(1)).register("h2", heading(2)).register("h3", heading(3)).register("h4", heading(4)).register("h5", heading(5)).register("h6", heading(6)).register("b", (el, ctx) => marked(el.children, ctx, "**")).register("code", (el, ctx) => {
1197
+ const text = oneLine(ctx.text(el.children));
1198
+ return text === "" ? [] : [{
1199
+ type: "text",
1200
+ text: `\`${text}\``
1201
+ }];
1202
+ }).register("a", (el, ctx) => {
1203
+ const run = textRun(ctx.render(el.children));
1204
+ return [{
1205
+ type: "text",
1206
+ text: `[${run.text.trim() === "" ? el.attrs.href : run.text}](${el.attrs.href})`
1207
+ }, ...run.rest];
1208
+ }).register("span", (el, ctx) => {
1209
+ const color = FONT_COLOR[el.attrs.color ?? "default"];
1210
+ const run = textRun(ctx.render(el.children));
1211
+ if (run.text === "") return run.rest;
1212
+ if (color === void 0) return [{
1213
+ type: "text",
1214
+ text: run.text
1215
+ }, ...run.rest];
1216
+ return [{
1217
+ type: "text",
1218
+ text: `<font color="${color}">${run.text}</font>`
1219
+ }, ...run.rest];
1220
+ }, { variants: ["color"] }).register("at", (el) => ({
1221
+ type: "text",
1222
+ text: `@${el.attrs.name ?? el.attrs.id ?? ""}`
1223
+ }), { variants: ["user"] }).register("blockquote", (el, ctx) => {
1224
+ const run = textRun(ctx.render(el.children));
1225
+ const source = run.text.replace(/^\n+/, "").replace(/\n+$/, "");
1226
+ if (source === "") return run.rest;
1227
+ return [{
1228
+ type: "text",
1229
+ text: source.split("\n").map((line) => `> ${line}`).join("\n")
1230
+ }, ...run.rest];
1231
+ }).register("ul", (el, ctx) => list(false, el, ctx)).register("ol", (el, ctx) => list(true, el, ctx)).register("li", (el, ctx) => ({
1232
+ type: "item",
1233
+ nodes: ctx.render(el.children)
1234
+ })).register("img", (el, ctx) => mediaNode("image", "image", el, ctx, el.attrs.src, {}), { variants: ["inline"] }).register("audio", (el, ctx) => mediaNode("voice", "audio", el, ctx, el.attrs.src, {
1235
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
1236
+ ...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
1237
+ })).register("video", (el, ctx) => mediaNode("video", "video", el, ctx, el.attrs.src, {
1238
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
1239
+ ...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
1240
+ })).register("file", (el, ctx) => mediaNode("file", "file", el, ctx, el.attrs.src, {
1241
+ ...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
1242
+ ...el.attrs.size === void 0 ? {} : { size: el.attrs.size }
1243
+ })).register("button", (el, ctx) => {
1244
+ const text = ctx.text(el.children).trim();
1245
+ const attrs = el.attrs;
1246
+ if (attrs.type === "link") return {
1247
+ type: "link-button",
1248
+ text: text === "" ? attrs.href : text,
1249
+ href: attrs.href
1250
+ };
1251
+ if (attrs.type === "action" || attrs.type === "submit") return {
1252
+ type: "button",
1253
+ key: attrs.id,
1254
+ text: text === "" ? attrs.id : text
1255
+ };
1256
+ return {
1257
+ type: "text",
1258
+ text: `\`${attrs.text}\``
1259
+ };
1260
+ }, { variants: ["action", "link"] }).envelope("title"),
1261
+ limits: {
1262
+ "limit.payload.bytes": WECOM_LIMITS.payloadBytes,
1263
+ "limit.delete.window": WECOM_LIMITS.deleteWindow,
1264
+ "limit.buttons.row": WECOM_LIMITS.buttonsRow,
1265
+ "limit.buttons.rows": WECOM_LIMITS.buttonRows
1266
+ },
1267
+ assemble: (nodes, envelope, ctx) => assembleDraft(nodes, envelope, ctx),
1268
+ serialize: (prepared, ctx) => serializeDraft(prepared, ctx, Number(config.agentId)),
1269
+ check: (draft) => checkDraft(draft)
1270
+ };
1271
+ }
1272
+ // lib/types/send.js
1273
+ /**
1274
+ * Outbound: one `message/send` per draft, one recall per published part, and the member read of `im_members`.
1275
+ *
1276
+ * The answer is an HTTP 200 envelope whose `errcode` the transport has already checked, so what is left here is the part
1277
+ * the platform reports without failing: a recipient that does not exist (`invaliduser`), one that exists but has no
1278
+ * licence (`unlicenseduser`) and an accepted request that returned no `msgid`. Reporting any of those as a success would
1279
+ * tell the host a message was delivered when the platform dropped it.
1280
+ */
1281
+ /** One `|`-separated recipient list of a send answer, as a set of userids. */
1282
+ function listOf(value) {
1283
+ if (value === void 0) return [];
1284
+ return value.split("|").map((item) => item.trim()).filter((item) => item !== "");
1285
+ }
1286
+ /** The media id a payload carries, when the payload is a media message. */
1287
+ function mediaIdOf(payload) {
1288
+ switch (payload.msgtype) {
1289
+ case "markdown":
1290
+ case "template_card": return;
1291
+ case "image": return payload.image.media_id;
1292
+ case "voice": return payload.voice.media_id;
1293
+ case "video": return payload.video.media_id;
1294
+ case "file": return payload.file.media_id;
1295
+ }
1296
+ }
1297
+ /**
1298
+ * Send one serialized payload and report the part the platform created.
1299
+ *
1300
+ * @param deps - the adapter's API surface.
1301
+ * @param payload - one `message/send` body.
1302
+ * @param target - the chat the payload goes to; its id is the `touser` recipient as well.
1303
+ * @param ctx - core send context: `quote` is present on every part, and only part 0 records it.
1304
+ * @returns the published part.
1305
+ * @throws PlatformError when the one addressee was skipped, or when the answer carried no `msgid`.
1306
+ */
1307
+ async function sendPayload(deps, payload, target, ctx) {
1308
+ const answer = await deps.internal.messageSend(payload);
1309
+ const recipient = target.chat.id;
1310
+ if (listOf(answer.invaliduser).includes(recipient)) throw new PlatformError("not-found", `wecom: ${recipient} does not exist or is outside the application's visible range`, {
1311
+ published: "no",
1312
+ code: "invaliduser"
1313
+ });
1314
+ if (listOf(answer.unlicenseduser).includes(recipient)) throw new PlatformError("permission", `wecom: ${recipient} has no licence for the application`, {
1315
+ published: "no",
1316
+ code: "unlicenseduser"
1317
+ });
1318
+ const msgid = answer.msgid;
1319
+ if (msgid === void 0 || msgid === "") throw new PlatformError("invalid", "wecom: message/send answered without a msgid", { published: "unknown" });
1320
+ const mediaId = mediaIdOf(payload);
1321
+ return {
1322
+ id: msgid,
1323
+ kind: "message",
1324
+ time: Date.now(),
1325
+ referrer: {
1326
+ userId: recipient,
1327
+ msgId: msgid,
1328
+ ...ctx.index === 0 && ctx.quote !== void 0 ? { quotedMessageId: ctx.quote } : {}
1329
+ },
1330
+ raw: {
1331
+ msgtype: payload.msgtype,
1332
+ ...mediaId === void 0 ? {} : { mediaId },
1333
+ ...payload.msgtype === "template_card" ? { taskId: payload.template_card.task_id } : {},
1334
+ ...answer.response_code === void 0 ? {} : { responseCode: answer.response_code }
1335
+ }
1336
+ };
1337
+ }
1338
+ /**
1339
+ * Recall one published message.
1340
+ *
1341
+ * The core only calls this inside the 24-hour window of `limit.delete.window`, and logs a refusal as a warning rather
1342
+ * than failing the caller.
1343
+ *
1344
+ * @param deps - the adapter's API surface.
1345
+ * @param part - the published part, whose id is the platform `msgid`.
1346
+ * @param _handle - unused; a recall addresses the message id alone.
1347
+ */
1348
+ async function deletePart(deps, part, _handle) {
1349
+ await deps.internal.messageRecall({ msgid: part.id });
1350
+ }
1351
+ /**
1352
+ * The members of one chat.
1353
+ *
1354
+ * A direct chat is the application's only conversation kind, and its one other person is the peer the chat id already
1355
+ * names; the profile request fills in the display name the callback does not carry. A userid the application may not see
1356
+ * answers `40003`, which reaches the caller as `not-found`.
1357
+ *
1358
+ * @param deps - the adapter's API surface.
1359
+ * @param chat - the chat to list.
1360
+ * @param _cursor - unused; a direct chat is a single page.
1361
+ * @param _limit - unused; a direct chat has one member.
1362
+ * @returns one page with the peer.
1363
+ */
1364
+ async function members(deps, chat, _cursor, _limit) {
1365
+ const answer = await deps.internal.userGet({ userid: chat.id });
1366
+ return { data: [{
1367
+ id: answer.userid === void 0 || answer.userid === "" ? chat.id : answer.userid,
1368
+ ...answer.name === void 0 ? {} : { name: answer.name },
1369
+ isBot: false
1370
+ }] };
1371
+ }
1372
+ // lib/types/token.js
1373
+ /**
1374
+ * The application `access_token` every `cgi-bin` call carries.
1375
+ *
1376
+ * The platform mints one token per application with a lifetime of 7,200 seconds, refuses a client that asks too often,
1377
+ * and may invalidate a token early. The cache is therefore lazy (no background timer to clear on disconnect),
1378
+ * single-flight (concurrent callers share one request) and invalidated by the code of a refused call rather than by a
1379
+ * deadline alone.
1380
+ */
1381
+ /** Seconds shaved off the announced lifetime, so a request never races the expiry. */
1382
+ const REFRESH_MARGIN_SECONDS = 300;
1383
+ /** The application token, cached until shortly before the platform expires it. */
1384
+ var AccessTokenCache = class {
1385
+ mint;
1386
+ now;
1387
+ current;
1388
+ inflight;
1389
+ /**
1390
+ * @param mint - requests a new token from the platform.
1391
+ * @param now - clock of the expiry check; tests replace it.
1392
+ */
1393
+ constructor(mint, now = Date.now) {
1394
+ this.mint = mint;
1395
+ this.now = now;
1396
+ }
1397
+ /** The cached token, requesting one when none is cached or the cached one is near its expiry. */
1398
+ async get() {
1399
+ const current = this.current;
1400
+ if (current !== void 0 && this.now() < current.expiresAt) return current.value;
1401
+ this.inflight ??= this.mint().then((answer) => {
1402
+ if (answer.access_token === void 0 || answer.access_token === "") throw new Error(`wecom: gettoken answered without a token${answer.errmsg === void 0 ? "" : `: ${answer.errmsg}`}`);
1403
+ const expiresIn = answer.expires_in;
1404
+ if (typeof expiresIn === "number" && Number.isFinite(expiresIn)) this.current = {
1405
+ value: answer.access_token,
1406
+ expiresAt: this.now() + (expiresIn - REFRESH_MARGIN_SECONDS) * 1e3
1407
+ };
1408
+ return answer.access_token;
1409
+ }).finally(() => {
1410
+ this.inflight = void 0;
1411
+ });
1412
+ return await this.inflight;
1413
+ }
1414
+ /** Drop the cached token, so the next {@link get} asks the platform again. */
1415
+ invalidate() {
1416
+ this.current = void 0;
1417
+ }
1418
+ /** The token in the cache, when one is cached; for diagnostics only. */
1419
+ get cached() {
1420
+ return this.current?.value;
1421
+ }
1422
+ };
1423
+ // lib/types/crypto.js
1424
+ /**
1425
+ * Callback authentication and decryption, implemented on `node:crypto`.
1426
+ *
1427
+ * The platform hands every callback over in one encrypted envelope, and the adapter is the only place that can say
1428
+ * whether the bytes came from the platform:
1429
+ *
1430
+ * - `msg_signature = sha1(sort(token, timestamp, nonce, msg_encrypt).join(''))`, compared in constant time;
1431
+ * - `AES-256-CBC` keyed by `Base64_Decode(EncodingAESKey + "=")` with `IV = AESKey[0:16]` and PKCS#7 padding to
1432
+ * **32-byte** blocks (not the usual 16);
1433
+ * - the plaintext is `random(16) + msg_len(4, big endian) + msg + receiveid`, and `receiveid` must equal `corpId` for an
1434
+ * application callback.
1435
+ *
1436
+ * `tests/crypto.spec.ts` proves the three steps against the vectors the platform documents.
1437
+ */
1438
+ /** Length of the decoded AES key. */
1439
+ const AES_KEY_BYTES = 32;
1440
+ /** Length of the initialisation vector, which is the first part of the key. */
1441
+ const IV_BYTES = 16;
1442
+ /** The padding block size this platform uses: 32 bytes, not the 16 of a plain AES-CBC block. */
1443
+ const PKCS7_BLOCK_BYTES = 32;
1444
+ /** Length of the random prefix of the plaintext. */
1445
+ const RANDOM_BYTES = 16;
1446
+ /** Length of the big-endian message length between the random prefix and the message. */
1447
+ const LENGTH_BYTES = 4;
1448
+ /** One callback payload that could not be decrypted. */
1449
+ var WecomCryptoError = class extends Error {
1450
+ constructor(message, options = {}) {
1451
+ super(message, options);
1452
+ this.name = "WecomCryptoError";
1453
+ }
1454
+ };
1455
+ /**
1456
+ * Decode an `EncodingAESKey` into the AES key it stands for.
1457
+ *
1458
+ * The platform stores the Base64 key without its `=` padding, so the padding is restored before decoding.
1459
+ *
1460
+ * @param aesKey - the configured 43-character `EncodingAESKey`.
1461
+ * @returns the 32-byte AES key.
1462
+ * @throws WecomCryptoError when the decoded key is not 32 bytes.
1463
+ */
1464
+ function aesKeyOf(aesKey) {
1465
+ const key = Buffer.from(`${aesKey}=`, "base64");
1466
+ if (key.length !== AES_KEY_BYTES) throw new WecomCryptoError(`wecom: the EncodingAESKey decodes to ${key.length} bytes, expected ${AES_KEY_BYTES}`);
1467
+ return key;
1468
+ }
1469
+ /**
1470
+ * The `msg_signature` of one callback.
1471
+ *
1472
+ * The four components are sorted lexicographically as strings and concatenated without a separator, then hashed with
1473
+ * SHA-1 and printed as lowercase hex.
1474
+ *
1475
+ * @param token - the configured callback token.
1476
+ * @param timestamp - the `timestamp` the platform sent.
1477
+ * @param nonce - the `nonce` the platform sent.
1478
+ * @param encrypt - the `echostr` or outer `Encrypt` value the signature covers.
1479
+ * @returns the lowercase hexadecimal SHA-1 digest.
1480
+ */
1481
+ function signatureOf(token, timestamp, nonce, encrypt) {
1482
+ return createHash("sha1").update([
1483
+ token,
1484
+ timestamp,
1485
+ nonce,
1486
+ encrypt
1487
+ ].sort().join("")).digest("hex");
1488
+ }
1489
+ /**
1490
+ * Compare a computed signature with the one the request carried without leaking where they differ.
1491
+ *
1492
+ * @param expected - the signature computed from the request.
1493
+ * @param received - the `msg_signature` parameter, if the request carried one.
1494
+ * @returns whether the request signature matches.
1495
+ */
1496
+ function matchesSignature(expected, received) {
1497
+ if (received === void 0) return false;
1498
+ const left = Buffer.from(expected, "utf8");
1499
+ const right = Buffer.from(received, "utf8");
1500
+ if (left.length !== right.length) return false;
1501
+ return timingSafeEqual(left, right);
1502
+ }
1503
+ /**
1504
+ * Decrypt one callback payload.
1505
+ *
1506
+ * @param aesKey - the configured `EncodingAESKey`.
1507
+ * @param encrypt - the Base64 ciphertext the callback carried.
1508
+ * @returns the message and the `receiveid` it was encrypted for.
1509
+ * @throws WecomCryptoError when the ciphertext is malformed, the padding is inconsistent, or the announced length
1510
+ * exceeds the plaintext.
1511
+ */
1512
+ function decryptPayload(aesKey, encrypt) {
1513
+ const key = aesKeyOf(aesKey);
1514
+ const cipher = Buffer.from(encrypt.trim(), "base64");
1515
+ if (cipher.length === 0 || cipher.length % IV_BYTES !== 0) throw new WecomCryptoError(`wecom: the callback ciphertext is ${cipher.length} bytes, which is not a whole number of AES blocks`);
1516
+ const decipher = createDecipheriv("aes-256-cbc", key, key.subarray(0, IV_BYTES));
1517
+ decipher.setAutoPadding(false);
1518
+ let padded;
1519
+ try {
1520
+ padded = Buffer.concat([decipher.update(cipher), decipher.final()]);
1521
+ } catch (cause) {
1522
+ throw new WecomCryptoError("wecom: the callback payload could not be decrypted", { cause });
1523
+ }
1524
+ if (padded.length === 0 || padded.length % 32 !== 0) throw new WecomCryptoError(`wecom: the decrypted payload is ${padded.length} bytes, which is not padded to 32-byte blocks`);
1525
+ const padding = padded[padded.length - 1];
1526
+ if (padding < 1 || padding > 32 || padding > padded.length) throw new WecomCryptoError(`wecom: the callback padding byte is ${padding}`);
1527
+ const plaintext = padded.subarray(0, padded.length - padding);
1528
+ if (plaintext.length < 20) throw new WecomCryptoError(`wecom: the decrypted payload is ${plaintext.length} bytes, shorter than its own header`);
1529
+ const length = plaintext.readUInt32BE(RANDOM_BYTES);
1530
+ const end = 20 + length;
1531
+ if (end > plaintext.length) throw new WecomCryptoError(`wecom: the decrypted payload announces ${length} bytes of message but carries ${plaintext.length - RANDOM_BYTES - LENGTH_BYTES}`);
1532
+ return {
1533
+ message: plaintext.subarray(20, end).toString("utf8"),
1534
+ receiveId: plaintext.subarray(end).toString("utf8")
1535
+ };
1536
+ }
1537
+ // lib/types/decode.js
1538
+ /**
1539
+ * Inbound decoding: one decrypted callback becomes an intake `Session` (`message`) or a button interaction.
1540
+ *
1541
+ * An application message arrives from exactly one member in exactly one conversation — the member's direct chat with the
1542
+ * application — so `chat.type` is always `direct`, `chat.id` is the sender's userid, and there is no mention, thread or
1543
+ * quote to decode. The content of a media message is the bot's own `satori:` route, because the callback carries only a
1544
+ * `media_id` and the bytes have to be fetched with the application's credentials.
1545
+ */
1546
+ /** The chat of a callback sender: the application has only one-to-one conversations. */
1547
+ function chatOf(userId) {
1548
+ return {
1549
+ id: userId,
1550
+ type: "direct"
1551
+ };
1552
+ }
1553
+ /** The sender of a callback: the application never learns a display name without another request. */
1554
+ function senderOf(userId) {
1555
+ return {
1556
+ id: userId,
1557
+ isBot: false
1558
+ };
1559
+ }
1560
+ /**
1561
+ * The millisecond time of a callback.
1562
+ *
1563
+ * `CreateTime` is in seconds; a body without a usable value falls back to the receipt time rather than to `NaN`.
1564
+ */
1565
+ function timeOf(fields) {
1566
+ const seconds = Number(fields.CreateTime);
1567
+ return Number.isFinite(seconds) ? seconds * 1e3 : Date.now();
1568
+ }
1569
+ /**
1570
+ * The `satori:` source of one inbound media object.
1571
+ *
1572
+ * @param bot - the receiving adapter.
1573
+ * @param mediaId - the platform `MediaId`.
1574
+ * @returns the internal URL the host downloads through.
1575
+ */
1576
+ function mediaSource(bot, mediaId) {
1577
+ return bot.getInternalUrl(`/assets/${encodeURIComponent(mediaId)}`);
1578
+ }
1579
+ /**
1580
+ * The text of one location message.
1581
+ *
1582
+ * The element vocabulary has no location tag, so the place arrives as a readable line.
1583
+ *
1584
+ * @param fields - the decrypted message.
1585
+ * @returns `[位置] Label (X,Y)`, without the label when the message carries none.
1586
+ */
1587
+ function locationText(fields) {
1588
+ const label = fields.Label?.trim() ?? "";
1589
+ const x = fields.Location_X ?? "";
1590
+ const y = fields.Location_Y ?? "";
1591
+ return `[位置]${label === "" ? "" : ` ${label}`} (${x},${y})`;
1592
+ }
1593
+ /** The elements of one message, or undefined for a `MsgType` this adapter does not decode. */
1594
+ function contentOf(bot, fields, msgType) {
1595
+ switch (msgType) {
1596
+ case "text": return [fields.Content ?? ""];
1597
+ case "image": {
1598
+ const mediaId = fields.MediaId ?? "";
1599
+ return mediaId === "" ? [] : [h("img", { src: mediaSource(bot, mediaId) })];
1600
+ }
1601
+ case "voice": {
1602
+ const mediaId = fields.MediaId ?? "";
1603
+ return mediaId === "" ? [] : [h("audio", { src: mediaSource(bot, mediaId) })];
1604
+ }
1605
+ case "video": {
1606
+ const mediaId = fields.MediaId ?? "";
1607
+ return mediaId === "" ? [] : [h("video", { src: mediaSource(bot, mediaId) })];
1608
+ }
1609
+ case "location": return [h("p", locationText(fields))];
1610
+ case "link": {
1611
+ const url = fields.Url ?? "";
1612
+ if (url === "") return [];
1613
+ const title = fields.Title?.trim() ?? "";
1614
+ const description = fields.Description?.trim() ?? "";
1615
+ return [h("p", h("a", { href: url }, title === "" ? url : title), ...description === "" ? [] : ["\n", description])];
1616
+ }
1617
+ default: return;
1618
+ }
1619
+ }
1620
+ /** Decode one `template_card_event` into the button session the callback registry looks up. */
1621
+ function decodeTemplateCardEvent(bot, fields) {
1622
+ const userId = fields.FromUserName ?? "";
1623
+ const chat = chatOf(userId);
1624
+ const time = timeOf(fields);
1625
+ const referrer = {
1626
+ taskId: fields.TaskId ?? "",
1627
+ ...fields.CardType === void 0 ? {} : { cardType: fields.CardType },
1628
+ ...fields.ResponseCode === void 0 ? {} : { responseCode: fields.ResponseCode },
1629
+ userId,
1630
+ agentId: bot.config.agentId
1631
+ };
1632
+ const button = {
1633
+ bot,
1634
+ id: fields.EventKey ?? "",
1635
+ user: senderOf(userId),
1636
+ chat,
1637
+ referrer,
1638
+ time: Date.now()
1639
+ };
1640
+ return bot.session({
1641
+ type: "interaction/button",
1642
+ id: `${fields.TaskId ?? ""}:${fields.EventKey ?? ""}:${fields.CreateTime ?? ""}`,
1643
+ timestamp: time,
1644
+ button,
1645
+ raw: fields
1646
+ });
1647
+ }
1648
+ /** Decode one event message, or drop it when the contract has no consumer for it. */
1649
+ function decodeEvent(bot, fields) {
1650
+ switch (fields.Event) {
1651
+ case "template_card_event": return decodeTemplateCardEvent(bot, fields);
1652
+ default:
1653
+ bot.ctx.logger.debug("wecom: ignoring a %s event", fields.Event ?? "(none)");
1654
+ return;
1655
+ }
1656
+ }
1657
+ /**
1658
+ * Decode one decrypted callback.
1659
+ *
1660
+ * @param bot - the receiving adapter.
1661
+ * @param fields - the decrypted message fields.
1662
+ * @returns the session to publish, or undefined for a message this adapter drops.
1663
+ */
1664
+ function decodeMessage(bot, fields) {
1665
+ const msgType = fields.MsgType ?? "";
1666
+ if (msgType === "event") return decodeEvent(bot, fields);
1667
+ const nodes = contentOf(bot, fields, msgType);
1668
+ if (nodes === void 0) {
1669
+ bot.ctx.logger.debug("wecom: ignoring a message of type %s", msgType === "" ? "(none)" : msgType);
1670
+ return;
1671
+ }
1672
+ const userId = fields.FromUserName ?? "";
1673
+ const msgId = fields.MsgId ?? "";
1674
+ const time = timeOf(fields);
1675
+ const content = normalize(nodes.length > 0 ? nodes : [h("raw", {
1676
+ platform: "wecom",
1677
+ type: msgType,
1678
+ data: fields
1679
+ })]);
1680
+ const referrer = {
1681
+ corpId: bot.config.corpId,
1682
+ agentId: bot.config.agentId,
1683
+ userId,
1684
+ msgId
1685
+ };
1686
+ const message = {
1687
+ id: msgId,
1688
+ chat: chatOf(userId),
1689
+ sender: senderOf(userId),
1690
+ content,
1691
+ mentions: {
1692
+ self: false,
1693
+ all: false,
1694
+ users: []
1695
+ },
1696
+ time,
1697
+ referrer,
1698
+ raw: fields
1699
+ };
1700
+ return bot.session({
1701
+ type: "message",
1702
+ id: msgId,
1703
+ timestamp: time,
1704
+ message,
1705
+ raw: fields
1706
+ });
1707
+ }
1708
+ // lib/types/xml.js
1709
+ /**
1710
+ * XML parsing of the callback envelopes.
1711
+ *
1712
+ * Both the outer envelope (`<xml><ToUserName/><AgentID/><Encrypt/></xml>`) and the decrypted message are a flat map of
1713
+ * element name to text; `template_card_event`'s `SelectedItems` is the only nested value and no decision of this adapter
1714
+ * reads it. The platform's real input includes entities, CDATA, self-closing tags and a byte-order mark, so the parsing
1715
+ * is delegated to `xml2js` instead of a hand-written pattern.
1716
+ */
1717
+ /** One callback document that is not a well-formed `<xml>` field map. */
1718
+ var WecomXmlError = class extends Error {
1719
+ constructor(message, options = {}) {
1720
+ super(message, options);
1721
+ this.name = "WecomXmlError";
1722
+ }
1723
+ };
1724
+ /** Message of any caught value, for a log line. */
1725
+ function messageOf$2(error) {
1726
+ return error instanceof Error ? error.message : String(error);
1727
+ }
1728
+ /** One parsed field value, when the value is a scalar rather than a nested element. */
1729
+ function scalarOf(value) {
1730
+ if (typeof value === "string") return value;
1731
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1732
+ }
1733
+ /**
1734
+ * Flatten the `xml` element of a parsed document.
1735
+ *
1736
+ * @param value - the parsed document.
1737
+ * @returns its scalar fields, or undefined when the document is not an `<xml>` field map.
1738
+ */
1739
+ function fieldsOf(value) {
1740
+ if (typeof value !== "object" || value === null) return void 0;
1741
+ const root = value.xml;
1742
+ if (typeof root !== "object" || root === null) return void 0;
1743
+ const fields = {};
1744
+ for (const [name, raw] of Object.entries(root)) {
1745
+ const field = scalarOf(raw);
1746
+ if (field !== void 0) fields[name] = field;
1747
+ }
1748
+ return fields;
1749
+ }
1750
+ /**
1751
+ * Parse one callback document into its fields.
1752
+ *
1753
+ * @param text - the request body or the decrypted message.
1754
+ * @returns the scalar fields of the `<xml>` root.
1755
+ * @throws WecomXmlError when the document is not well-formed XML or carries no `<xml>` root.
1756
+ */
1757
+ async function parseXml(text) {
1758
+ let parsed;
1759
+ try {
1760
+ parsed = await xml2js.parseStringPromise(text, { explicitArray: false });
1761
+ } catch (cause) {
1762
+ throw new WecomXmlError(`wecom: the callback body is not XML: ${messageOf$2(cause)}`, { cause });
1763
+ }
1764
+ const fields = fieldsOf(parsed);
1765
+ if (fields === void 0) throw new WecomXmlError("wecom: the callback body has no <xml> root");
1766
+ return fields;
1767
+ }
1768
+ /**
1769
+ * Parse the plaintext of a decrypted message.
1770
+ *
1771
+ * The decrypted body is an `<xml>` document of its own, so it goes through the same parser as the outer envelope.
1772
+ *
1773
+ * @param message - the decrypted message.
1774
+ * @returns its scalar fields.
1775
+ * @throws WecomXmlError when the decrypted body is not XML.
1776
+ */
1777
+ async function parseMessageXml(message) {
1778
+ return await parseXml(message);
1779
+ }
1780
+ // lib/types/transport/webhook.js
1781
+ /**
1782
+ * The callback transport.
1783
+ *
1784
+ * A self-built application has exactly one inbound path: the platform POSTs an encrypted XML envelope to the URL saved
1785
+ * in 接收消息 → 设置API接收, and verifies that URL by a GET to the same address when the configuration is saved. Both
1786
+ * methods are answered by one handler because a `WebRoute` does not match on the method, and splitting them into two
1787
+ * routes of the same path would make the registration order decide which one sees the GET.
1788
+ *
1789
+ * The handler answers `200` only after `bot.receive` stored the message, so a platform that retries a timed-out delivery
1790
+ * finds the repeat deduplicated by `${bot.id}|${event.id}`; an intake failure answers `500` instead of pretending.
1791
+ */
1792
+ /** Message of any caught value, for a log line. */
1793
+ function messageOf$1(error) {
1794
+ return error instanceof Error ? error.message : String(error);
1795
+ }
1796
+ /** Read a request body to its end. The callback body is small and the platform publishes no size limit. */
1797
+ async function readBody(request) {
1798
+ const chunks = [];
1799
+ for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1800
+ return Buffer.concat(chunks).toString("utf8");
1801
+ }
1802
+ /** Write one bodiless answer. */
1803
+ function writeStatus(response, status, headers = {}) {
1804
+ response.writeHead(status, headers);
1805
+ response.end();
1806
+ }
1807
+ /**
1808
+ * Write one plain-text answer, verbatim.
1809
+ *
1810
+ * The platform requires the decrypted `echostr` back without quotes, a byte-order mark or a trailing newline.
1811
+ */
1812
+ function writeText(response, status, text) {
1813
+ response.writeHead(status, {
1814
+ "content-type": "text/plain; charset=utf-8",
1815
+ "content-length": String(Buffer.byteLength(text, "utf8"))
1816
+ });
1817
+ response.end(text);
1818
+ }
1819
+ /** The decoded query of one request. */
1820
+ function queryOf(request) {
1821
+ try {
1822
+ return new URL(request.url ?? "/", "http://localhost").searchParams;
1823
+ } catch {
1824
+ return new URLSearchParams();
1825
+ }
1826
+ }
1827
+ /** The one callback route of {@link WecomWebhook}. */
1828
+ var WecomWebhook = class {
1829
+ bot;
1830
+ webServer;
1831
+ dispose;
1832
+ constructor(bot, webServer) {
1833
+ this.bot = bot;
1834
+ this.webServer = webServer;
1835
+ }
1836
+ /** Register the route over the profile's web server. */
1837
+ start() {
1838
+ this.dispose = this.webServer.register({
1839
+ kind: "exact",
1840
+ path: routePath(this.bot.config.path),
1841
+ auth: "anonymous",
1842
+ handler: (request, response) => this.handle(request, response)
1843
+ });
1844
+ }
1845
+ /** Release the route. */
1846
+ stop() {
1847
+ this.dispose?.();
1848
+ this.dispose = void 0;
1849
+ }
1850
+ async handle(request, response) {
1851
+ try {
1852
+ switch (request.method) {
1853
+ case "GET":
1854
+ await this.handleVerify(request, response);
1855
+ return;
1856
+ case "POST":
1857
+ await this.handleCallback(request, response);
1858
+ return;
1859
+ default: writeStatus(response, 405, { allow: "GET, POST" });
1860
+ }
1861
+ } catch (error) {
1862
+ this.bot.ctx.logger.warn("wecom: callback delivery failed: %s", messageOf$1(error));
1863
+ if (!response.headersSent) writeStatus(response, 500);
1864
+ else response.end();
1865
+ }
1866
+ }
1867
+ /** The URL verification the platform sends when the callback configuration is saved. */
1868
+ async handleVerify(request, response) {
1869
+ const query = queryOf(request);
1870
+ const msgSignature = query.get("msg_signature");
1871
+ const timestamp = query.get("timestamp");
1872
+ const nonce = query.get("nonce");
1873
+ const echostr = query.get("echostr");
1874
+ if (msgSignature === null || msgSignature === "" || timestamp === null || timestamp === "" || nonce === null || nonce === "" || echostr === null || echostr === "") {
1875
+ writeStatus(response, 400);
1876
+ return;
1877
+ }
1878
+ if (!matchesSignature(signatureOf(this.bot.config.token, timestamp, nonce, echostr), msgSignature)) {
1879
+ writeStatus(response, 403);
1880
+ return;
1881
+ }
1882
+ let plaintext;
1883
+ let receiveId;
1884
+ try {
1885
+ const decrypted = decryptPayload(this.bot.config.aesKey, echostr);
1886
+ plaintext = decrypted.message;
1887
+ receiveId = decrypted.receiveId;
1888
+ } catch (error) {
1889
+ this.bot.ctx.logger.warn("wecom: verification payload could not be decrypted: %s", messageOf$1(error));
1890
+ writeStatus(response, 400);
1891
+ return;
1892
+ }
1893
+ if (receiveId !== this.bot.config.corpId) {
1894
+ this.bot.ctx.logger.warn("wecom: verification payload was encrypted for %s, not corpId %s", receiveId, this.bot.config.corpId);
1895
+ writeStatus(response, 403);
1896
+ return;
1897
+ }
1898
+ writeText(response, 200, plaintext);
1899
+ }
1900
+ /** One business callback. */
1901
+ async handleCallback(request, response) {
1902
+ const query = queryOf(request);
1903
+ const body = await readBody(request);
1904
+ let outer;
1905
+ try {
1906
+ outer = await parseXml(body);
1907
+ } catch (error) {
1908
+ if (error instanceof WecomXmlError) {
1909
+ this.bot.ctx.logger.warn("wecom: cannot parse a callback request: %s", messageOf$1(error));
1910
+ writeStatus(response, 400);
1911
+ return;
1912
+ }
1913
+ throw error;
1914
+ }
1915
+ if (outer.AgentID !== this.bot.config.agentId) {
1916
+ writeStatus(response, 403);
1917
+ return;
1918
+ }
1919
+ let fields = outer;
1920
+ const encrypt = outer.Encrypt;
1921
+ if (encrypt !== void 0 && encrypt !== "") {
1922
+ const msgSignature = query.get("msg_signature");
1923
+ const timestamp = query.get("timestamp");
1924
+ const nonce = query.get("nonce");
1925
+ if (msgSignature === null || msgSignature === "" || timestamp === null || timestamp === "" || nonce === null || nonce === "") {
1926
+ writeStatus(response, 400);
1927
+ return;
1928
+ }
1929
+ if (!matchesSignature(signatureOf(this.bot.config.token, timestamp, nonce, encrypt), msgSignature)) {
1930
+ writeStatus(response, 403);
1931
+ return;
1932
+ }
1933
+ let message;
1934
+ let receiveId;
1935
+ try {
1936
+ const decrypted = decryptPayload(this.bot.config.aesKey, encrypt);
1937
+ message = decrypted.message;
1938
+ receiveId = decrypted.receiveId;
1939
+ } catch (error) {
1940
+ this.bot.ctx.logger.warn("wecom: callback payload could not be decrypted: %s", messageOf$1(error));
1941
+ writeStatus(response, 403);
1942
+ return;
1943
+ }
1944
+ if (receiveId !== this.bot.config.corpId) {
1945
+ this.bot.ctx.logger.warn("wecom: callback was encrypted for %s, not corpId %s", receiveId, this.bot.config.corpId);
1946
+ writeStatus(response, 403);
1947
+ return;
1948
+ }
1949
+ try {
1950
+ fields = await parseMessageXml(message);
1951
+ } catch (error) {
1952
+ this.bot.ctx.logger.warn("wecom: cannot parse a decrypted callback: %s", messageOf$1(error));
1953
+ writeStatus(response, 400);
1954
+ return;
1955
+ }
1956
+ }
1957
+ const session = decodeMessage(this.bot, fields);
1958
+ if (session !== void 0) await this.bot.receive(session);
1959
+ writeText(response, 200, "success");
1960
+ }
1961
+ };
1962
+ // lib/types/bot.js
1963
+ /** Message of any caught value, for a log line. */
1964
+ function messageOf(error) {
1965
+ return error instanceof Error ? error.message : String(error);
1966
+ }
1967
+ /** One internal-route path segment back as the value it names. */
1968
+ function decodeSegment(segment) {
1969
+ try {
1970
+ return decodeURIComponent(segment);
1971
+ } catch {
1972
+ return segment;
1973
+ }
1974
+ }
1975
+ /**
1976
+ * WeCom self-built application adapter.
1977
+ *
1978
+ * The application is identified by configuration (`agentId`), confirmed with `agent/get` on connect. The encrypted XML
1979
+ * callback is the only transport, `markdown` is the only mode, and every reply is a proactive `message/send`: a passive
1980
+ * reply would have to answer inside the platform's five-second window, while a turn takes minutes. Media uploads to
1981
+ * `media/upload` and carries a three-day `media_id`; inbound media is read from the bot's own `satori:` route.
1982
+ */
1983
+ var WecomBot = class extends Adapter {
1984
+ /** The adapter needs the Satori service and the isolated `http` service. */
1985
+ static inject = ["satori", "http"];
1986
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
1987
+ static Config = Config;
1988
+ modes;
1989
+ modeOrder = ["markdown"];
1990
+ /** The mapped platform API surface. */
1991
+ internal;
1992
+ /** The application `access_token` every `cgi-bin` call carries. */
1993
+ tokens;
1994
+ webhook;
1995
+ constructor(ctx, config) {
1996
+ super(ctx, config, {
1997
+ id: `wecom:${config.agentId}`,
1998
+ platform: "wecom",
1999
+ adapter: "wecom"
2000
+ });
2001
+ this.selfId = config.agentId;
2002
+ this.internal = new Internal(this);
2003
+ this.tokens = new AccessTokenCache(async () => {
2004
+ return await this.internal.getToken({
2005
+ corpid: config.corpId,
2006
+ corpsecret: config.secret
2007
+ });
2008
+ });
2009
+ this.modes = { markdown: createMarkdownMode(config) };
2010
+ this.defineInternalRoute("/assets/:mediaId", async ({ params }) => serveMedia(this, decodeSegment(params.mediaId)));
2011
+ }
2012
+ async connect() {
2013
+ const invalid = configError(this.config);
2014
+ if (invalid !== void 0) {
2015
+ this.ctx.logger.error("wecom: connect failed: %s", invalid.message);
2016
+ throw invalid;
2017
+ }
2018
+ const webServer = this.ctx.get("webServer");
2019
+ if (webServer === void 0) {
2020
+ const error = /* @__PURE__ */ new Error("wecom: this adapter needs a profile-provided webServer; WeCom has only the callback transport, so add a webServer row to the profile and make the callback path reachable from the enterprise network");
2021
+ this.ctx.logger.error(error.message);
2022
+ throw error;
2023
+ }
2024
+ try {
2025
+ await this.tokens.get();
2026
+ const answer = await this.internal.agentGet({ agentid: Number(this.config.agentId) });
2027
+ this.user = verifyIdentity(this.config.agentId, answer);
2028
+ const webhook = new WecomWebhook(this, webServer);
2029
+ webhook.start();
2030
+ this.webhook = webhook;
2031
+ this.online();
2032
+ } catch (error) {
2033
+ this.ctx.logger.error("wecom: connect failed: %s", messageOf(error));
2034
+ throw error;
2035
+ }
2036
+ }
2037
+ async disconnect() {
2038
+ const webhook = this.webhook;
2039
+ this.webhook = void 0;
2040
+ webhook?.stop();
2041
+ }
2042
+ /**
2043
+ * Upload one outbound attachment to the platform's media endpoint.
2044
+ *
2045
+ * A `media_id` is an application-level resource, so the scope is the bot rather than the chat.
2046
+ */
2047
+ async upload(ref, _scope, ctx) {
2048
+ return await uploadMedia(this, ref, ctx);
2049
+ }
2050
+ resourceScope(_target, _kind) {
2051
+ return this.id;
2052
+ }
2053
+ async sendPayload(payload, target, ctx) {
2054
+ return await sendPayload({
2055
+ internal: this.internal,
2056
+ config: this.config
2057
+ }, payload, target, ctx);
2058
+ }
2059
+ async deletePart(part, handle) {
2060
+ await deletePart({
2061
+ internal: this.internal,
2062
+ config: this.config
2063
+ }, part, handle);
2064
+ }
2065
+ async members(chat, cursor, limit) {
2066
+ return await members({
2067
+ internal: this.internal,
2068
+ config: this.config
2069
+ }, chat, cursor, limit);
2070
+ }
2071
+ classify(error) {
2072
+ return classifyWecomError(error);
2073
+ }
2074
+ };
2075
+ export { AES_KEY_CHARS, AccessTokenCache, CARD_TITLE_FALLBACK, Config, Internal, MEDIA_LIFETIME_MS, PKCS7_BLOCK_BYTES, TOKEN_MAX_CHARS, WECOM_LIMITS, types_exports as Wecom, WecomApiError, WecomBot, WecomBot as default, WecomCryptoError, WecomIdentityError, WecomWebhook, WecomXmlError, aesKeyOf, assembleDraft, chatOf, checkDraft, classifyWecomError, configError, createMarkdownMode, decodeMessage, decodeTemplateCardEvent, decryptPayload, deletePart, download, endpointOf, fieldsOf, flattenNodes, hardCutBytes, invoke, isTokenFailure, isTokenFailureCode, locationText, matchesSignature, mediaSource, mediaTypeOf, members, nextTaskId, parseMessageXml, parseXml, reportMovedMedia, routePath, sendPayload, senderOf, serializeDraft, serveMedia, signatureOf, splitMarkdownBytes, uploadMedia, verdictOfCode, verifyIdentity };
2076
+
2077
+ //# sourceMappingURL=index.js.map