@zhin.js/adapter-weixin-ilink 1.1.0 → 1.1.2

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 (69) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +11 -6
  3. package/adapters/{weixin-ilink.js → weixin-ilink/index.js} +6 -6
  4. package/adapters/{weixin-ilink.ts → weixin-ilink/index.ts} +9 -9
  5. package/commands/{endpoint/add/[id].js → weixin-ilink/endpoint/add/[id]/index.js} +1 -1
  6. package/commands/weixin-ilink/endpoint/add/[id]/index.ts +3 -0
  7. package/{lib/weixin-ilink-endpoint-commands.js → commands/weixin-ilink/endpoint/definition.js} +4 -3
  8. package/{src/weixin-ilink-endpoint-commands.ts → commands/weixin-ilink/endpoint/definition.ts} +3 -3
  9. package/commands/{endpoint/list.js → weixin-ilink/endpoint/list/index.js} +1 -1
  10. package/commands/weixin-ilink/endpoint/list/index.ts +3 -0
  11. package/commands/{endpoint/remove/[id].js → weixin-ilink/endpoint/remove/[id]/index.js} +1 -1
  12. package/commands/weixin-ilink/endpoint/remove/[id]/index.ts +3 -0
  13. package/lib/client.d.ts +5 -4
  14. package/lib/client.js +33 -16
  15. package/lib/context-store.d.ts +15 -1
  16. package/lib/context-store.js +93 -1
  17. package/lib/credentials.d.ts +15 -7
  18. package/lib/credentials.js +59 -42
  19. package/lib/endpoint.d.ts +9 -4
  20. package/lib/endpoint.js +41 -27
  21. package/lib/ilink-api.d.ts +6 -5
  22. package/lib/ilink-api.js +21 -14
  23. package/lib/ilink-config-cache.d.ts +3 -7
  24. package/lib/ilink-config-cache.js +13 -14
  25. package/lib/ilink-logger.d.ts +0 -1
  26. package/lib/ilink-logger.js +11 -25
  27. package/lib/ilink-meta.d.ts +13 -7
  28. package/lib/ilink-meta.js +24 -20
  29. package/lib/ilink-session-guard.d.ts +13 -14
  30. package/lib/ilink-session-guard.js +29 -42
  31. package/lib/index.d.ts +5 -2
  32. package/lib/index.js +4 -0
  33. package/lib/login.d.ts +4 -3
  34. package/lib/login.js +24 -21
  35. package/lib/outbound-media.js +1 -1
  36. package/lib/protocol.d.ts +7 -10
  37. package/lib/protocol.js +15 -15
  38. package/lib/types.d.ts +1 -1
  39. package/lib/weixin-ilink-runtime-state.js +1 -1
  40. package/lib/weixin-inbound.d.ts +3 -49
  41. package/lib/weixin-inbound.js +20 -183
  42. package/lib/weixin-send-media.js +5 -1
  43. package/lib/weixin-send.js +2 -0
  44. package/package.json +11 -11
  45. package/plugin.js +1 -1
  46. package/schema.json +32 -4
  47. package/src/client.ts +46 -14
  48. package/src/context-store.ts +101 -10
  49. package/src/credentials.ts +68 -45
  50. package/src/endpoint.ts +59 -38
  51. package/src/ilink-api.ts +26 -20
  52. package/src/ilink-config-cache.ts +17 -13
  53. package/src/ilink-logger.ts +11 -26
  54. package/src/ilink-meta.ts +31 -21
  55. package/src/ilink-session-guard.ts +29 -46
  56. package/src/index.ts +15 -2
  57. package/src/login.ts +32 -19
  58. package/src/outbound-media.ts +1 -1
  59. package/src/protocol.ts +20 -29
  60. package/src/types.ts +0 -1
  61. package/src/upload.test.ts +11 -8
  62. package/src/weixin-ilink-runtime-state.ts +1 -1
  63. package/src/weixin-inbound.ts +23 -215
  64. package/src/weixin-send-media.ts +5 -1
  65. package/src/weixin-send.ts +2 -0
  66. package/commands/endpoint/add/[id].ts +0 -3
  67. package/commands/endpoint/list.ts +0 -3
  68. package/commands/endpoint/remove/[id].ts +0 -3
  69. package/lib/weixin-ilink-endpoint-commands.d.ts +0 -1
@@ -6,31 +6,16 @@ export type IlinkLogger = {
6
6
  withAccount: (accountId: string) => IlinkLogger;
7
7
  };
8
8
 
9
- let sink: IlinkLogger = {
10
- debug: () => {},
11
- info: () => {},
12
- warn: (msg) => console.warn(`[weixin-ilink] ${msg}`),
13
- error: (msg) => console.error(`[weixin-ilink] ${msg}`),
14
- withAccount(accountId) {
15
- const prefix = `[weixin-ilink:${accountId}]`;
16
- return {
17
- debug: (msg) => sink.debug(`${prefix} ${msg}`),
18
- info: (msg) => sink.info(`${prefix} ${msg}`),
19
- warn: (msg) => sink.warn(`${prefix} ${msg}`),
20
- error: (msg) => sink.error(`${prefix} ${msg}`),
21
- withAccount: () => this,
22
- };
23
- },
24
- };
25
-
26
- export function setIlinkLogger(next: IlinkLogger): void {
27
- sink = next;
9
+ function createIlinkLogger(prefix = '[weixin-ilink]'): IlinkLogger {
10
+ return Object.freeze({
11
+ debug: () => {},
12
+ info: () => {},
13
+ warn: (msg) => console.warn(`${prefix} ${msg}`),
14
+ error: (msg) => console.error(`${prefix} ${msg}`),
15
+ withAccount(accountId) {
16
+ return createIlinkLogger(`[weixin-ilink:${accountId}]`);
17
+ },
18
+ });
28
19
  }
29
20
 
30
- export const logger: IlinkLogger = {
31
- debug: (msg) => sink.debug(msg),
32
- info: (msg) => sink.info(msg),
33
- warn: (msg) => sink.warn(msg),
34
- error: (msg) => sink.error(msg),
35
- withAccount: (accountId) => sink.withAccount(accountId),
36
- };
21
+ export const logger: IlinkLogger = createIlinkLogger();
package/src/ilink-meta.ts CHANGED
@@ -10,9 +10,6 @@ export const DEFAULT_API_BASE_URL = "https://ilinkai.weixin.qq.com";
10
10
  const DEFAULT_BOT_AGENT = "Zhin.js";
11
11
  const BOT_AGENT_MAX_LEN = 256;
12
12
 
13
- let channelVersion = "0.0.0";
14
- let configuredBotAgent: string | undefined;
15
-
16
13
  function readPackageVersion(): string {
17
14
  try {
18
15
  const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "../package.json");
@@ -23,12 +20,7 @@ function readPackageVersion(): string {
23
20
  }
24
21
  }
25
22
 
26
- channelVersion = readPackageVersion();
27
-
28
- export function configureIlinkMeta(opts: { botAgent?: string; version?: string }): void {
29
- if (opts.botAgent) configuredBotAgent = opts.botAgent;
30
- if (opts.version) channelVersion = opts.version;
31
- }
23
+ const PACKAGE_VERSION = readPackageVersion();
32
24
 
33
25
  export function buildClientVersion(version: string): number {
34
26
  const parts = version.split(".").map((p) => parseInt(p, 10));
@@ -38,23 +30,41 @@ export function buildClientVersion(version: string): number {
38
30
  return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff);
39
31
  }
40
32
 
41
- export const ILINK_APP_CLIENT_VERSION = buildClientVersion(channelVersion);
42
-
43
- export function sanitizeBotAgent(raw: string | undefined): string {
44
- if (!raw || typeof raw !== "string") return configuredBotAgent ?? DEFAULT_BOT_AGENT;
33
+ export function sanitizeBotAgent(raw: string | undefined, fallback = DEFAULT_BOT_AGENT): string {
34
+ if (!raw || typeof raw !== "string") return fallback;
45
35
  const trimmed = raw.trim();
46
- if (!trimmed) return configuredBotAgent ?? DEFAULT_BOT_AGENT;
36
+ if (!trimmed) return fallback;
47
37
  const productRe = /^[A-Za-z0-9_.\-]{1,32}\/[A-Za-z0-9_.+\-]{1,32}$/;
48
38
  const tokens = trimmed.split(/\s+/).filter((tok) => productRe.test(tok));
49
- if (tokens.length === 0) return configuredBotAgent ?? DEFAULT_BOT_AGENT;
39
+ if (tokens.length === 0) return fallback;
50
40
  const joined = tokens.join(" ");
51
41
  if (Buffer.byteLength(joined, "utf-8") <= BOT_AGENT_MAX_LEN) return joined;
52
- return (configuredBotAgent ?? DEFAULT_BOT_AGENT);
42
+ return fallback;
43
+ }
44
+
45
+ export interface IlinkClientMetadataOptions {
46
+ readonly botAgent?: string;
47
+ readonly version?: string;
53
48
  }
54
49
 
55
- export function buildBaseInfo(): BaseInfo {
56
- return {
57
- channel_version: channelVersion,
58
- bot_agent: sanitizeBotAgent(configuredBotAgent),
59
- };
50
+ /** Immutable request identity owned by one endpoint. */
51
+ export class IlinkClientMetadata {
52
+ readonly channelVersion: string;
53
+ readonly botAgent: string;
54
+ readonly appClientVersion: number;
55
+
56
+ constructor(options: IlinkClientMetadataOptions = {}) {
57
+ this.channelVersion = options.version ?? PACKAGE_VERSION;
58
+ const defaultBotAgent = `Zhin.js/${this.channelVersion}`;
59
+ this.botAgent = sanitizeBotAgent(options.botAgent, defaultBotAgent);
60
+ this.appClientVersion = buildClientVersion(this.channelVersion);
61
+ Object.freeze(this);
62
+ }
63
+
64
+ buildBaseInfo(): BaseInfo {
65
+ return {
66
+ channel_version: this.channelVersion,
67
+ bot_agent: this.botAgent,
68
+ };
69
+ }
60
70
  }
@@ -1,58 +1,41 @@
1
- import { logger } from "./ilink-logger.js";
1
+ import { logger } from './ilink-logger.js';
2
2
 
3
- const SESSION_PAUSE_DURATION_MS = 60 * 60 * 1000;
4
-
5
- /** Error code returned by the server when the bot session has expired. */
6
3
  export const SESSION_EXPIRED_ERRCODE = -14;
4
+ export const SESSION_PAUSE_DURATION_MS = 60 * 60 * 1000;
5
+
6
+ /** Endpoint-owned cooldown state for an authenticated iLink session. */
7
+ export class IlinkSessionGuard {
8
+ #pauseUntil = 0;
9
+
10
+ constructor(
11
+ readonly accountId: string,
12
+ private readonly now: () => number = Date.now,
13
+ private readonly pauseDurationMs = SESSION_PAUSE_DURATION_MS,
14
+ ) {}
15
+
16
+ pause(): void {
17
+ this.#pauseUntil = this.now() + this.pauseDurationMs;
18
+ logger.info(
19
+ `session-guard: paused accountId=${this.accountId} until=${new Date(this.#pauseUntil).toISOString()} (${this.pauseDurationMs / 1000}s)`,
20
+ );
21
+ }
7
22
 
8
- const pauseUntilMap = new Map<string, number>();
9
-
10
- /** Pause all inbound/outbound API calls for `accountId` for one hour. */
11
- export function pauseSession(accountId: string): void {
12
- const until = Date.now() + SESSION_PAUSE_DURATION_MS;
13
- pauseUntilMap.set(accountId, until);
14
- logger.info(
15
- `session-guard: paused accountId=${accountId} until=${new Date(until).toISOString()} (${SESSION_PAUSE_DURATION_MS / 1000}s)`,
16
- );
17
- }
18
-
19
- /** Returns `true` when the bot is still within its one-hour cooldown window. */
20
- export function isSessionPaused(accountId: string): boolean {
21
- const until = pauseUntilMap.get(accountId);
22
- if (until === undefined) return false;
23
- if (Date.now() >= until) {
24
- pauseUntilMap.delete(accountId);
25
- return false;
23
+ get paused(): boolean {
24
+ return this.remainingMs > 0;
26
25
  }
27
- return true;
28
- }
29
26
 
30
- /** Milliseconds remaining until the pause expires (0 when not paused). */
31
- export function getRemainingPauseMs(accountId: string): number {
32
- const until = pauseUntilMap.get(accountId);
33
- if (until === undefined) return 0;
34
- const remaining = until - Date.now();
35
- if (remaining <= 0) {
36
- pauseUntilMap.delete(accountId);
27
+ get remainingMs(): number {
28
+ const remaining = this.#pauseUntil - this.now();
29
+ if (remaining > 0) return remaining;
30
+ this.#pauseUntil = 0;
37
31
  return 0;
38
32
  }
39
- return remaining;
40
- }
41
33
 
42
- /** Throw if the session is currently paused. Call before any API request. */
43
- export function assertSessionActive(accountId: string): void {
44
- if (isSessionPaused(accountId)) {
45
- const remainingMin = Math.ceil(getRemainingPauseMs(accountId) / 60_000);
34
+ assertActive(): void {
35
+ const remaining = this.remainingMs;
36
+ if (remaining === 0) return;
46
37
  throw new Error(
47
- `session paused for accountId=${accountId}, ${remainingMin} min remaining (errcode ${SESSION_EXPIRED_ERRCODE})`,
38
+ `session paused for accountId=${this.accountId}, ${Math.ceil(remaining / 60_000)} min remaining (errcode ${SESSION_EXPIRED_ERRCODE})`,
48
39
  );
49
40
  }
50
41
  }
51
-
52
- /**
53
- * Reset internal state — only for tests.
54
- * @internal
55
- */
56
- export function _resetForTest(): void {
57
- pauseUntilMap.clear();
58
- }
package/src/index.ts CHANGED
@@ -6,7 +6,6 @@ export {
6
6
  segmentLocalPath,
7
7
  sleep,
8
8
  type ResolvedWeixinIlinkConfig,
9
- type WeixinIlinkAdapterConfig,
10
9
  type WeixinIlinkEndpointConfig,
11
10
  type WeixinInboundMediaPaths,
12
11
  type WeixinMessageWithMedia,
@@ -14,7 +13,21 @@ export {
14
13
  } from './protocol.js';
15
14
 
16
15
  export type { WeixinMessage, MessageItem } from './ilink-types.js';
17
- export type { WeixinIlinkCredentials } from './credentials.js';
16
+ export {
17
+ WeixinIlinkStateStore,
18
+ type WeixinIlinkCredentials,
19
+ } from './credentials.js';
20
+ export {
21
+ IlinkClientMetadata,
22
+ sanitizeBotAgent,
23
+ type IlinkClientMetadataOptions,
24
+ } from './ilink-meta.js';
25
+ export { WeixinContextTokenStore } from './context-store.js';
26
+ export {
27
+ IlinkSessionGuard,
28
+ SESSION_EXPIRED_ERRCODE,
29
+ SESSION_PAUSE_DURATION_MS,
30
+ } from './ilink-session-guard.js';
18
31
 
19
32
  export {
20
33
  WeixinIlinkClient,
package/src/login.ts CHANGED
@@ -1,14 +1,13 @@
1
1
  /**
2
- * Resolve iLink bot credentials (env / config / sidecar file / QR login).
2
+ * Resolve iLink bot credentials (config / endpoint state / QR login).
3
3
  * No legacy Plugin / loginAssist dependency — QR URL is logged for manual scan.
4
4
  */
5
5
  import { apiGetFetch, apiPostFetch } from './ilink-api.js';
6
- import { buildBaseInfo, DEFAULT_API_BASE_URL } from './ilink-meta.js';
6
+ import type { IlinkClientMetadata } from './ilink-meta.js';
7
7
  import { logger } from './ilink-logger.js';
8
8
  import {
9
- loadCredentials,
10
- saveCredentials,
11
9
  type WeixinIlinkCredentials,
10
+ type WeixinIlinkStateStore,
12
11
  } from './credentials.js';
13
12
  import type { ResolvedWeixinIlinkConfig } from './protocol.js';
14
13
 
@@ -42,11 +41,19 @@ function getLocalBotTokenList(): string[] {
42
41
  return [];
43
42
  }
44
43
 
45
- async function fetchQRCode(apiBaseUrl: string, botType: string): Promise<QRCodeResponse> {
44
+ async function fetchQRCode(
45
+ apiBaseUrl: string,
46
+ botType: string,
47
+ metadata: IlinkClientMetadata,
48
+ ): Promise<QRCodeResponse> {
46
49
  const rawText = await apiPostFetch({
47
50
  baseUrl: apiBaseUrl,
51
+ metadata,
48
52
  endpoint: `ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(botType)}`,
49
- body: JSON.stringify({ local_token_list: getLocalBotTokenList(), base_info: buildBaseInfo() }),
53
+ body: JSON.stringify({
54
+ local_token_list: getLocalBotTokenList(),
55
+ base_info: metadata.buildBaseInfo(),
56
+ }),
50
57
  label: 'fetchQRCode',
51
58
  });
52
59
  return JSON.parse(rawText) as QRCodeResponse;
@@ -55,12 +62,14 @@ async function fetchQRCode(apiBaseUrl: string, botType: string): Promise<QRCodeR
55
62
  async function pollQRStatus(
56
63
  apiBaseUrl: string,
57
64
  qrcode: string,
65
+ metadata: IlinkClientMetadata,
58
66
  signal?: AbortSignal,
59
67
  ): Promise<StatusResponse> {
60
68
  try {
61
69
  const endpoint = `ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`;
62
70
  const rawText = await apiGetFetch({
63
71
  baseUrl: apiBaseUrl,
72
+ metadata,
64
73
  endpoint,
65
74
  timeoutMs: QR_LONG_POLL_TIMEOUT_MS,
66
75
  label: 'pollQRStatus',
@@ -102,36 +111,40 @@ function sleepWithAbort(ms: number, signal?: AbortSignal): Promise<void> {
102
111
 
103
112
  export async function resolveCredentials(
104
113
  config: ResolvedWeixinIlinkConfig,
114
+ metadata: IlinkClientMetadata,
115
+ state: WeixinIlinkStateStore,
105
116
  signal?: AbortSignal,
106
117
  ): Promise<WeixinIlinkCredentials> {
107
- const envToken = process.env.WEIXIN_ILINK_TOKEN?.trim() || config.botToken?.trim();
108
- if (envToken) {
109
- const stored = loadCredentials(config.id);
118
+ const configuredToken = config.botToken?.trim();
119
+ if (configuredToken) {
120
+ const stored = state.loadCredentials();
110
121
  return {
111
- botToken: envToken,
122
+ botToken: configuredToken,
112
123
  ilinkUserId: stored?.ilinkUserId,
113
124
  ilinkBotId: stored?.ilinkBotId,
114
- baseUrl: config.baseUrl ?? stored?.baseUrl ?? DEFAULT_API_BASE_URL,
125
+ baseUrl: config.baseUrl,
115
126
  };
116
127
  }
117
128
 
118
- const stored = loadCredentials(config.id);
129
+ const stored = state.loadCredentials();
119
130
  if (stored?.botToken) {
120
131
  return {
121
132
  ...stored,
122
- baseUrl: config.baseUrl ?? stored.baseUrl ?? DEFAULT_API_BASE_URL,
133
+ baseUrl: config.baseUrl,
123
134
  };
124
135
  }
125
136
 
126
- return loginWithQr(config, signal);
137
+ return loginWithQr(config, metadata, state, signal);
127
138
  }
128
139
 
129
140
  export async function loginWithQr(
130
141
  config: ResolvedWeixinIlinkConfig,
142
+ metadata: IlinkClientMetadata,
143
+ state: WeixinIlinkStateStore,
131
144
  signal?: AbortSignal,
132
145
  ): Promise<WeixinIlinkCredentials> {
133
- const apiBaseUrl = config.baseUrl ?? DEFAULT_API_BASE_URL;
134
- const qr = await fetchQRCode(apiBaseUrl, DEFAULT_ILINK_BOT_TYPE);
146
+ const apiBaseUrl = config.baseUrl;
147
+ const qr = await fetchQRCode(apiBaseUrl, DEFAULT_ILINK_BOT_TYPE, metadata);
135
148
  const qrcodeUrl = qr.qrcode_img_content || qr.qrcode;
136
149
 
137
150
  logger.info(
@@ -144,7 +157,7 @@ export async function loginWithQr(
144
157
  while (Date.now() < deadline) {
145
158
  // stop() 的 AbortSignal:不打满 8 分钟,立即退出登录循环
146
159
  if (signal?.aborted) throw abortError();
147
- const status = await pollQRStatus(currentBaseUrl, qr.qrcode, signal);
160
+ const status = await pollQRStatus(currentBaseUrl, qr.qrcode, metadata, signal);
148
161
 
149
162
  if (status.status === 'scaned_but_redirect' && status.redirect_host) {
150
163
  currentBaseUrl = status.redirect_host.startsWith('http')
@@ -157,7 +170,7 @@ export async function loginWithQr(
157
170
  throw new Error('扫码成功但未返回 bot_token');
158
171
  }
159
172
  const creds: WeixinIlinkCredentials = {
160
- botToken: status.bot_token ?? loadCredentials(config.id)?.botToken ?? '',
173
+ botToken: status.bot_token ?? state.loadCredentials()?.botToken ?? '',
161
174
  ilinkUserId: status.ilink_user_id,
162
175
  ilinkBotId: status.ilink_endpoint_id,
163
176
  baseUrl: status.baseurl ?? currentBaseUrl,
@@ -165,7 +178,7 @@ export async function loginWithQr(
165
178
  if (!creds.botToken) {
166
179
  throw new Error('binded_redirect 但本地无有效 bot_token');
167
180
  }
168
- saveCredentials(config.id, creds);
181
+ state.saveCredentials(creds);
169
182
  return creds;
170
183
  }
171
184
 
@@ -10,7 +10,7 @@
10
10
  import crypto from 'node:crypto';
11
11
  import fs from 'node:fs';
12
12
  import path from 'node:path';
13
- import { isMediaRef, type MediaRef } from '@zhin.js/core';
13
+ import { isMediaRef, type MediaRef } from '@zhin.js/im-contract';
14
14
  import { formatCompact, getLogger } from '@zhin.js/logger';
15
15
  import { downloadRemoteImageToTemp } from './upload.js';
16
16
  import { getExtensionFromMime } from './mime.js';
package/src/protocol.ts CHANGED
@@ -3,25 +3,20 @@
3
3
  * Canonicalization is owned by gateway/core before endpoint.send.
4
4
  */
5
5
 
6
- import { pickCredential } from 'zhin.js/adapter';
7
- import { isMediaRef } from '@zhin.js/core';
8
- import type { ConversationRef, Segment } from '@zhin.js/im-contract';
6
+ import { isMediaRef, type ConversationRef, type Segment } from '@zhin.js/im-contract';
9
7
  import { bodyFromItemList } from './weixin-inbound.js';
10
8
  import { DEFAULT_API_BASE_URL, DEFAULT_CDN_BASE_URL } from './ilink-meta.js';
11
9
  import type { WeixinMessage } from './ilink-types.js';
12
10
 
13
- /** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
14
- export interface WeixinIlinkAdapterConfig {
15
- readonly id?: string;
11
+ /** One expanded Weixin iLink endpoint configuration produced by AdapterIndex. */
12
+ export interface WeixinIlinkEndpointConfig {
13
+ readonly id: string;
16
14
  readonly botAgent?: string;
17
15
  readonly baseUrl?: string;
18
16
  readonly cdnBaseUrl?: string;
19
17
  readonly longPollTimeoutMs?: number;
20
18
  readonly botToken?: string;
21
- /** Transitional: legacy root `endpoints[]` with `context: weixin-ilink`. */
22
- readonly endpoints?: ReadonlyArray<Partial<ResolvedWeixinIlinkConfig> & {
23
- readonly context?: string;
24
- }>;
19
+ readonly dataDir?: string;
25
20
  }
26
21
 
27
22
  export interface ResolvedWeixinIlinkConfig {
@@ -32,10 +27,9 @@ export interface ResolvedWeixinIlinkConfig {
32
27
  readonly cdnBaseUrl: string;
33
28
  readonly longPollTimeoutMs: number;
34
29
  readonly botToken?: string;
30
+ readonly dataDir: string;
35
31
  }
36
32
 
37
- export type WeixinIlinkEndpointConfig = ResolvedWeixinIlinkConfig;
38
-
39
33
  export interface WeixinWireSegment {
40
34
  readonly type: string;
41
35
  readonly data?: Record<string, unknown>;
@@ -55,30 +49,27 @@ export type WeixinMessageWithMedia = WeixinMessage & {
55
49
  const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
56
50
 
57
51
  export function resolveWeixinIlinkConfig(
58
- config: WeixinIlinkAdapterConfig = {},
52
+ config: WeixinIlinkEndpointConfig,
59
53
  ): ResolvedWeixinIlinkConfig {
60
- const entry = config.endpoints?.find((item) => item.context === 'weixin-ilink');
61
- const id = (typeof config.id === 'string' && config.id)
62
- || (typeof entry?.id === 'string' && entry.id)
63
- || process.env.WEIXIN_ILINK_BOT_NAME
64
- || 'weixin-ilink-bot';
65
- const botToken = pickCredential(
66
- typeof config.botToken === 'string' ? config.botToken.trim() : config.botToken,
67
- typeof entry?.botToken === 'string' ? entry.botToken.trim() : entry?.botToken,
68
- process.env.WEIXIN_ILINK_TOKEN?.trim(),
69
- );
54
+ const id = typeof config.id === 'string' ? config.id.trim() : '';
55
+ if (!/^[A-Za-z0-9_.-]+$/u.test(id)) {
56
+ throw new TypeError('Weixin iLink endpoint id must use letters, numbers, dot, underscore, or hyphen');
57
+ }
58
+ const botToken = typeof config.botToken === 'string'
59
+ ? config.botToken.trim() || undefined
60
+ : undefined;
61
+ const dataDir = config.dataDir?.trim() || 'data/weixin-ilink';
70
62
  // No throw here: missing botToken is resolved later by resolveCredentials()
71
63
  // (sidecar credentials file / QR login) during endpoint.start().
72
64
  return {
73
65
  context: 'weixin-ilink',
74
66
  id,
75
- botAgent: config.botAgent ?? entry?.botAgent,
76
- baseUrl: config.baseUrl ?? entry?.baseUrl ?? DEFAULT_API_BASE_URL,
77
- cdnBaseUrl: config.cdnBaseUrl ?? entry?.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL,
78
- longPollTimeoutMs: config.longPollTimeoutMs
79
- ?? entry?.longPollTimeoutMs
80
- ?? DEFAULT_LONG_POLL_TIMEOUT_MS,
67
+ botAgent: config.botAgent,
68
+ baseUrl: config.baseUrl ?? DEFAULT_API_BASE_URL,
69
+ cdnBaseUrl: config.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL,
70
+ longPollTimeoutMs: config.longPollTimeoutMs ?? DEFAULT_LONG_POLL_TIMEOUT_MS,
81
71
  botToken,
72
+ dataDir,
82
73
  };
83
74
  }
84
75
 
package/src/types.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  export type {
2
2
  WeixinIlinkEndpointConfig,
3
- WeixinIlinkAdapterConfig,
4
3
  ResolvedWeixinIlinkConfig,
5
4
  } from './protocol.js';
6
5
 
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import fsSync from "node:fs";
4
4
  import path from "node:path";
5
5
  import os from "node:os";
6
+ import { IlinkClientMetadata } from "./ilink-meta.js";
6
7
 
7
8
  vi.mock("./ilink-logger.js", () => ({
8
9
  logger: {
@@ -30,6 +31,8 @@ const { mockFetch } = vi.hoisted(() => ({
30
31
  }));
31
32
  vi.stubGlobal("fetch", mockFetch);
32
33
 
34
+ const metadata = new IlinkClientMetadata({ version: "1.2.3" });
35
+
33
36
  function mockCdnResponse(params: {
34
37
  ok?: boolean;
35
38
  status?: number;
@@ -99,7 +102,7 @@ describe("uploadFileToWeixin", () => {
99
102
  const result = await uploadFileToWeixin({
100
103
  filePath,
101
104
  toUserId: "user1",
102
- opts: { baseUrl: "https://api.com", token: "tok" },
105
+ opts: { baseUrl: "https://api.com", metadata, token: "tok" },
103
106
  cdnBaseUrl: "https://cdn.com",
104
107
  });
105
108
 
@@ -127,7 +130,7 @@ describe("uploadFileToWeixin", () => {
127
130
  const result = await uploadFileToWeixin({
128
131
  filePath,
129
132
  toUserId: "user1",
130
- opts: { baseUrl: "https://api.com", token: "tok" },
133
+ opts: { baseUrl: "https://api.com", metadata, token: "tok" },
131
134
  cdnBaseUrl: "https://ignored-cdn.com",
132
135
  });
133
136
 
@@ -152,7 +155,7 @@ describe("uploadFileToWeixin", () => {
152
155
  uploadFileToWeixin({
153
156
  filePath,
154
157
  toUserId: "user1",
155
- opts: { baseUrl: "https://api.com" },
158
+ opts: { baseUrl: "https://api.com", metadata },
156
159
  cdnBaseUrl: "https://cdn.com",
157
160
  }),
158
161
  ).rejects.toThrow("no upload URL");
@@ -184,7 +187,7 @@ describe("uploadFileToWeixin", () => {
184
187
  const result = await uploadFileToWeixin({
185
188
  filePath,
186
189
  toUserId: "user1",
187
- opts: { baseUrl: "https://api.com" },
190
+ opts: { baseUrl: "https://api.com", metadata },
188
191
  cdnBaseUrl: "https://cdn.com",
189
192
  });
190
193
  expect(result.downloadEncryptedQueryParam).toBe("dl-retry");
@@ -214,7 +217,7 @@ describe("uploadFileToWeixin", () => {
214
217
  uploadFileToWeixin({
215
218
  filePath,
216
219
  toUserId: "user1",
217
- opts: { baseUrl: "https://api.com" },
220
+ opts: { baseUrl: "https://api.com", metadata },
218
221
  cdnBaseUrl: "https://cdn.com",
219
222
  }),
220
223
  ).rejects.toThrow("client error");
@@ -240,7 +243,7 @@ describe("uploadFileToWeixin", () => {
240
243
  uploadFileToWeixin({
241
244
  filePath,
242
245
  toUserId: "user1",
243
- opts: { baseUrl: "https://api.com" },
246
+ opts: { baseUrl: "https://api.com", metadata },
244
247
  cdnBaseUrl: "https://cdn.com",
245
248
  }),
246
249
  ).rejects.toThrow("x-encrypted-param");
@@ -265,7 +268,7 @@ describe("uploadVideoToWeixin", () => {
265
268
  const result = await uploadVideoToWeixin({
266
269
  filePath,
267
270
  toUserId: "user1",
268
- opts: { baseUrl: "https://api.com" },
271
+ opts: { baseUrl: "https://api.com", metadata },
269
272
  cdnBaseUrl: "https://cdn.com",
270
273
  });
271
274
 
@@ -293,7 +296,7 @@ describe("uploadFileAttachmentToWeixin", () => {
293
296
  filePath,
294
297
  fileName: "doc.pdf",
295
298
  toUserId: "user1",
296
- opts: { baseUrl: "https://api.com" },
299
+ opts: { baseUrl: "https://api.com", metadata },
297
300
  cdnBaseUrl: "https://cdn.com",
298
301
  });
299
302
  expect(result.filekey).toBeDefined();
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Weixin iLink 插件实例的运行时状态:adapter create() 注册的 endpoint 列表。
3
- * 由 plugin.ts setup() provide,adapter create 与 `weixin-ilink.endpoint` 命令共享(同一 owner generation)。
3
+ * 由 plugin.ts setup() provide,adapter create 与 `weixin-ilink endpoint` 命令共享(同一 owner generation)。
4
4
  */
5
5
  import { defineEndpointRuntimeStateToken } from 'zhin.js/adapter';
6
6