dsh-wechat-access 0.0.0-stage → 0.0.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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
@@ -0,0 +1,70 @@
1
+ /**
2
+ * QQ 托管启动的失败处理。
3
+ *
4
+ * 这里只负责「失败之后做什么」,不负责拉 NapCat。把这段单独放在一个模块里,
5
+ * 是为了能单测最容易出错的分支:
6
+ * - 锁冲突发生在 manager.start() 之前:清理 runtime,但不启动 NapCat。
7
+ * - NapCat 已经启动、runtime 初始化失败:必须保留 NapCat,不能 taskkill。
8
+ */
9
+ export function shouldStopRuntime(stage) {
10
+ return stage === 'lock' || stage === 'manager-start';
11
+ }
12
+
13
+ export function shouldStopManager(stage) {
14
+ // 锁阶段 manager.start() 还没调用,不能凭空 stop 一个没启动的 manager。
15
+ return stage === 'manager-start';
16
+ }
17
+
18
+ function errorMessage(error) {
19
+ return String(error?.message ?? error ?? '未知错误');
20
+ }
21
+
22
+ export function describeStartupError(error, stage) {
23
+ let code = 'RUNTIME_INIT';
24
+ if (error?.code === 'LOCK_HELD' || stage === 'lock') code = 'LOCK_HELD';
25
+ else if (stage === 'manager-start') code = 'NAPCAT_START';
26
+ else if (stage === 'login') code = 'LOGIN_TIMEOUT';
27
+ else if (stage === 'monitor') code = 'MONITOR';
28
+ return {
29
+ code,
30
+ stage,
31
+ message: errorMessage(error),
32
+ lockOwner: error?.owner ?? null,
33
+ };
34
+ }
35
+
36
+ export async function recordManagedStartupFailure({
37
+ stage,
38
+ error,
39
+ runtime = null,
40
+ manager = null,
41
+ logger = console,
42
+ noteLog = () => {},
43
+ }) {
44
+ const info = describeStartupError(error, stage);
45
+ try {
46
+ noteLog('QQ 托管启动失败 [' + stage + ']: ' + String(error?.stack ?? error).slice(0, 4000));
47
+ } catch { /* diagnostics must never mask the real error */ }
48
+
49
+ const aborted = Boolean(runtime?.shutdown?.signal?.aborted);
50
+ if (runtime && !aborted) {
51
+ runtime.connected = false;
52
+ runtime.bootError = info.message;
53
+ runtime.bootErrorCode = info.code;
54
+ runtime.bootStage = stage;
55
+ runtime.lockOwner = info.lockOwner;
56
+ }
57
+
58
+ try { logger?.warn?.(info.message); } catch { /* logger must not break startup */ }
59
+
60
+ if (shouldStopRuntime(stage) && !aborted) {
61
+ try { await runtime?.stop?.(); }
62
+ catch (stopError) { try { noteLog('启动失败后停止 runtime 失败: ' + errorMessage(stopError)); } catch {} }
63
+ }
64
+ if (shouldStopManager(stage) && !aborted && manager) {
65
+ try { await manager.stop?.(); }
66
+ catch (stopError) { try { noteLog('启动失败后停止 NapCat 失败: ' + errorMessage(stopError)); } catch {} }
67
+ }
68
+
69
+ return { ...info, keptNapcat: !shouldStopManager(stage) && stage !== 'lock' };
70
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * QQ ↔ Steam 绑定表。
3
+ *
4
+ * 为什么需要单独一张表而不是一个 steamId 配置项:
5
+ * 一个群里可能有好几个人都开了 Steam,她得知道「问我的这个人」在玩什么,
6
+ * 而不是永远只看号主一个人。
7
+ *
8
+ * 存储形状(dataDir/steam-bindings.json):
9
+ * { "version": 1, "people": { "<QQ号>": { "steamId": "...", "nickname": "...", "source": "manual" | "code", "boundAt": 1794... } } }
10
+ *
11
+ * 写入一律走原子替换:这个文件被读的频率远高于写,但一旦写坏,
12
+ * 所有绑定信息就没了,重建只能靠人一个个重新输。
13
+ */
14
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
15
+ import { dirname, join } from 'node:path';
16
+
17
+ const VERSION = 1;
18
+ /** 一人最多能绑几个。正常只需要一个,留几个是给「小号也想知道」的情况。 */
19
+ const MAX_PER_PERSON = 3;
20
+
21
+ export class SteamBindingStore {
22
+ constructor({ dataDir, logger = console } = {}) {
23
+ this.file = join(dataDir, 'steam-bindings.json');
24
+ this.logger = logger;
25
+ // { [qq]: [{ steamId, nickname, source, boundAt }] }
26
+ this.people = {};
27
+ this.loaded = false;
28
+ this.writeChain = Promise.resolve();
29
+ }
30
+
31
+ async init() {
32
+ if (this.loaded) return this;
33
+ await mkdir(dirname(this.file), { recursive: true });
34
+ try {
35
+ const raw = JSON.parse(await readFile(this.file, 'utf8'));
36
+ if (raw?.version === VERSION && raw.people && typeof raw.people === 'object') {
37
+ this.people = raw.people;
38
+ }
39
+ } catch { /* 文件不存在或坏了就从空开始 */ }
40
+ this.loaded = true;
41
+ return this;
42
+ }
43
+
44
+ #normalize(raw) {
45
+ if (!raw || typeof raw !== 'object') return [];
46
+ // 兼容三种形态:数组、{ bindings: [...] }、以及「只有一个绑定对象」。
47
+ // 最后一种在手工编辑过的文件里出现过 —— 直接判空会把绑定关系整个丢掉。
48
+ const list = Array.isArray(raw)
49
+ ? raw
50
+ : (Array.isArray(raw.bindings) ? raw.bindings : (raw.steamId ? [raw] : []));
51
+ return list
52
+ .filter((b) => b && typeof b === 'object' && String(b.steamId ?? '').trim())
53
+ .map((b) => ({
54
+ steamId: String(b.steamId).trim(),
55
+ nickname: String(b.nickname ?? '').trim().slice(0, 60),
56
+ source: String(b.source ?? 'manual').slice(0, 20),
57
+ boundAt: Number(b.boundAt) || 0,
58
+ }))
59
+ .slice(0, MAX_PER_PERSON);
60
+ }
61
+
62
+ #save() {
63
+ this.writeChain = this.writeChain.then(async () => {
64
+ await mkdir(dirname(this.file), { recursive: true });
65
+ const tmp = this.file + '.tmp';
66
+ await writeFile(tmp, JSON.stringify({ version: VERSION, people: this.people }, null, 2) + '\n');
67
+ await rename(tmp, this.file);
68
+ }).catch((error) => this.logger.warn?.('Steam 绑定写入失败:' + error.message));
69
+ return this.writeChain;
70
+ }
71
+
72
+ /** 某个 QQ 绑定的全部 SteamID(最新的在前)。 */
73
+ list(qq) {
74
+ const key = String(qq ?? '').trim();
75
+ if (!key) return [];
76
+ const list = this.#normalize(this.people[key]);
77
+ return list.slice().sort((a, b) => b.boundAt - a.boundAt);
78
+ }
79
+
80
+ /** 优先返回最近绑定的那个;没绑定返回 null。 */
81
+ primary(qq) {
82
+ return this.list(qq)[0] ?? null;
83
+ }
84
+
85
+ /** 反查:这个 SteamID 绑在哪个 QQ 上。 */
86
+ whoIs(steamId) {
87
+ const id = String(steamId ?? '').trim();
88
+ if (!id) return '';
89
+ for (const [qq, raw] of Object.entries(this.people)) {
90
+ if (this.#normalize(raw).some((b) => b.steamId === id)) return qq;
91
+ }
92
+ return '';
93
+ }
94
+
95
+ async bind(qq, steamId, { nickname = '', source = 'manual' } = {}) {
96
+ const key = String(qq ?? '').trim();
97
+ const id = String(steamId ?? '').trim();
98
+ if (!key || !id) return { ok: false, reason: '参数为空' };
99
+ if (!/^\d{17}$/.test(id)) {
100
+ // SteamID64 固定 17 位。填成自定义 URL 名或 32 位 ID 时直接报清楚,
101
+ // 否则会变成「查不到账号」这种看不出原因的失败。
102
+ return { ok: false, reason: 'SteamID 必须是 17 位数字(SteamID64)' };
103
+ }
104
+ const list = this.list(key);
105
+ const existing = list.find((b) => b.steamId === id);
106
+ if (existing) {
107
+ // 已存在时不要直接 return:面板绑定成功后会再查一次 Steam,
108
+ // 想把真实昵称补进记录。以前这里 duplicate 直接返回,不改原记录,
109
+ // 于是第一次绑定(还没有昵称)补写永远不落盘 —— 面板当次看得到,
110
+ // 重启后再打开只剩一串数字。
111
+ const merged = { ...existing };
112
+ let changed = false;
113
+ const nextNick = String(nickname ?? '').trim().slice(0, 60);
114
+ if (nextNick && nextNick !== existing.nickname) { merged.nickname = nextNick; changed = true; }
115
+ if (source && source !== existing.source) { merged.source = source; changed = true; }
116
+ if (changed) {
117
+ this.people[key] = list.map((b) => (b.steamId === id ? merged : b));
118
+ await this.#save();
119
+ }
120
+ return { ok: true, duplicate: true, updated: changed, binding: merged };
121
+ }
122
+ if (list.length >= MAX_PER_PERSON) {
123
+ return { ok: false, reason: `一个 QQ 最多绑定 ${MAX_PER_PERSON} 个 Steam 账号` };
124
+ }
125
+ const binding = { steamId: id, nickname: String(nickname ?? '').trim().slice(0, 60), source, boundAt: Date.now() };
126
+ this.people[key] = [...list, binding];
127
+ await this.#save();
128
+ return { ok: true, binding };
129
+ }
130
+
131
+ async unbind(qq, steamId) {
132
+ const key = String(qq ?? '').trim();
133
+ const id = String(steamId ?? '').trim();
134
+ const list = this.list(key);
135
+ const next = id ? list.filter((b) => b.steamId !== id) : [];
136
+ if (next.length === list.length) return { ok: false, reason: '没有这条绑定' };
137
+ if (next.length) this.people[key] = next;
138
+ else delete this.people[key];
139
+ await this.#save();
140
+ return { ok: true, removed: list.length - next.length };
141
+ }
142
+
143
+ async flush() { await this.writeChain; }
144
+ }
package/lib/steam.mjs ADDED
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Steam 状态查询。
3
+ *
4
+ * 只做一件事:知道「对方现在在 Steam 上做什么」。
5
+ * - 在线状态(在线 / 离开 / 离线…)
6
+ * - 正在玩的游戏名(如果有)
7
+ * - 最近玩过什么、玩多久(游戏详情公开时才有)
8
+ *
9
+ * 为什么不做成「工具」而做成上下文注入:
10
+ * 模型不会无缘无故去查一个工具。你打游戏时她不会主动说「你在玩 XX 啊」,
11
+ * 除非她自己决定去调 —— 而多数时候她不会。注入是「她本来就知道」,
12
+ * 符合这里其他信息(记忆、情感、生活状态)的一贯做法。
13
+ *
14
+ * 隐私:Steam 的「游戏详情」必须是公开,否则接口返回空 response
15
+ * (不是报错!)。空 response 和「真的没玩过游戏」在协议层长得一样,
16
+ * 所以调用方必须能区分「拿不到」和「没有数据」。
17
+ */
18
+ import { checkSignal } from './util.mjs';
19
+
20
+ const API = 'https://api.steampowered.com';
21
+
22
+ /** 和风的错误码那套思路:配置问题单独提示,别让它变成一个哑巴 null。 */
23
+ /**
24
+ * 把可能含 API Key 的 URL 变成可安全打印的形式。
25
+ *
26
+ * Steam 的接口要求 Key 放在查询串里,所以任何「打印请求地址」的便利写法
27
+ * 都会把 Key 写进日志。要打就打这个。
28
+ */
29
+ export function redactSteamUrl(url) {
30
+ try {
31
+ const u = new URL(String(url));
32
+ if (u.searchParams.has('key')) u.searchParams.set('key', '***');
33
+ return u.toString();
34
+ } catch {
35
+ return '<无效地址>';
36
+ }
37
+ }
38
+
39
+ export class SteamError extends Error {
40
+ constructor(message, code = '') {
41
+ super(message);
42
+ this.name = 'SteamError';
43
+ this.code = code;
44
+ }
45
+ }
46
+
47
+ /** Steam 的 personastate 数值 → 中文。 */
48
+ const PERSONA_STATE = {
49
+ 0: '离线',
50
+ 1: '在线',
51
+ 2: '忙碌',
52
+ 3: '离开',
53
+ 4: '打盹',
54
+ 5: '想交易',
55
+ 6: '想玩游戏',
56
+ };
57
+
58
+ /**
59
+ * 把 GetPlayerSummaries 的一条记录整理成内部形状。
60
+ *
61
+ * 只留会影响「她怎么接话」的字段。头像、个人主页链接这些对聊天没用,
62
+ * 传进提示词只会稀释重点。
63
+ */
64
+ export function normalizePlayer(player) {
65
+ if (!player || typeof player !== 'object') return null;
66
+ const steamId = String(player.steamid ?? '').trim();
67
+ if (!steamId) return null;
68
+ const personaState = Number(player.personastate);
69
+ const inGame = String(player.gameextrainfo ?? '').trim();
70
+ // sinceMinutes(「这次已经玩了多久」)Steam 的 GetPlayerSummaries 不提供,
71
+ // 只有本地客户端或 Rich Presence 才有。这里不编造:字段留空,
72
+ // describeSteamStatus 里那句「已经玩了大约多久」自然不出现。
73
+ return {
74
+ steamId,
75
+ nickname: String(player.personaname ?? '').trim(),
76
+ state: PERSONA_STATE[personaState] ?? '未知',
77
+ stateCode: Number.isFinite(personaState) ? personaState : -1,
78
+ // 正在玩的游戏。离线时 Steam 不会给这个字段。
79
+ inGame: inGame || '',
80
+ gameId: String(player.gameid ?? '').trim(),
81
+ // 「正在玩」和「在线」是两回事:挂机在线但没开游戏也很常见。
82
+ lastLogoff: Number(player.lastlogoff) > 0 ? Number(player.lastlogoff) : null,
83
+ };
84
+ }
85
+
86
+ /**
87
+ * 把已拥有的游戏(含时长)整理成好读的形状。
88
+ *
89
+ * playtime_forever 单位是分钟。Steam 只在「最近两周玩过」时给 playtime_2weeks,
90
+ * 所以它是可选的。
91
+ */
92
+ export function normalizeOwnedGames(payload, { limit = 8, recentOnly = true } = {}) {
93
+ const games = Array.isArray(payload?.response?.games) ? payload.response.games : [];
94
+ const mapped = games
95
+ .map((g) => ({
96
+ appId: Number(g.appid),
97
+ name: String(g.name ?? '').trim(),
98
+ minutes: Number(g.playtime_forever) || 0,
99
+ minutes2Weeks: Number(g.playtime_2weeks) || 0,
100
+ lastPlayed: Number(g.rtime_last_played) > 0 ? Number(g.rtime_last_played) : null,
101
+ }))
102
+ .filter((g) => g.name);
103
+ // 「最近在玩」必须是最近两周真的开过的。
104
+ //
105
+ // 以前这里按「近两周时长 → 总时长」排序,两周都没玩时就用总时长兜底。
106
+ // 于是提示词里会出现「最近在玩:某游戏(几千小时)」—— 那其实是几年前玩的库存。
107
+ // 她会照着「最近」去接话,说出来的东西和时间对不上。
108
+ //
109
+ // 没有近两周记录时返回空数组,让调用方说「最近没怎么玩」,而不是编一个。
110
+ const recent = mapped.filter((g) => g.minutes2Weeks > 0);
111
+ const pool = recentOnly ? recent : mapped;
112
+ return pool
113
+ .sort((a, b) => (b.minutes2Weeks - a.minutes2Weeks) || (b.minutes - a.minutes))
114
+ .slice(0, Math.max(1, limit));
115
+ }
116
+
117
+ /** 分钟 → 「3 小时 20 分钟」。0 返回空串,别在提示词里塞「0 分钟」。 */
118
+ export function formatPlaytime(minutes) {
119
+ const m = Math.max(0, Math.round(Number(minutes) || 0));
120
+ if (!m) return '';
121
+ const h = Math.floor(m / 60);
122
+ const rest = m % 60;
123
+ if (h && rest) return `${h} 小时 ${rest} 分钟`;
124
+ if (h) return `${h} 小时`;
125
+ return `${rest} 分钟`;
126
+ }
127
+
128
+ /**
129
+ * 一条给模型看的状态描述。没有可用信息时返回空串(调用方据此跳过注入)。
130
+ *
131
+ * 刻意写得很短:这段每次回复都会进上下文,太长会挤掉真正重要的内容。
132
+ */
133
+ export function describeSteamStatus(status, { now = Date.now() } = {}) {
134
+ if (!status) return '';
135
+ const parts = [];
136
+ if (status.inGame) {
137
+ parts.push(`对方现在正在 Steam 上玩《${status.inGame}》`);
138
+ if (status.sinceMinutes && status.sinceMinutes > 0) {
139
+ parts.push(`已经玩了大约 ${formatPlaytime(status.sinceMinutes)}`);
140
+ }
141
+ } else if (status.stateCode === 0) {
142
+ const hours = status.lastLogoff ? Math.round((now - status.lastLogoff * 1000) / 3600000) : 0;
143
+ if (hours > 0 && hours < 72) parts.push(`对方 Steam 已经离线约 ${hours} 小时`);
144
+ else parts.push('对方 Steam 当前离线');
145
+ } else {
146
+ parts.push(`对方 Steam ${status.state}`);
147
+ }
148
+ // 只列近两周真的玩过的。时长也用近两周的,不能用总时长 ——
149
+ // 「最近在玩:某游戏(3000 小时)」是在说几年前的事。
150
+ const recent = (status.recentGames ?? [])
151
+ .filter((g) => g.name && g.minutes2Weeks > 0)
152
+ .slice(0, 3);
153
+ if (recent.length) {
154
+ const list = recent
155
+ .map((g) => {
156
+ const t = formatPlaytime(g.minutes2Weeks);
157
+ return t ? `${g.name}(近两周 ${t})` : g.name;
158
+ })
159
+ .join('、');
160
+ parts.push(`最近在玩:${list}`);
161
+ } else if (status.gamesUnavailable) {
162
+ // 「拿不到」不等于「没玩」:游戏详情没公开时 Steam 返回 { response: {} },
163
+ // 以前这里统一说「最近两周没有玩游戏的记录」,等于替对方编了一个结论。
164
+ if (status.stateCode !== 0 || status.inGame) {
165
+ parts.push('游戏详情没有公开,拿不到最近两周的游玩时长');
166
+ }
167
+ } else if (status.stateCode !== 0 && !status.inGame) {
168
+ // 在线但两周没开过游戏:说清楚,别让她以为对方最近在玩什么。
169
+ // 正在玩的时候不能说这句 —— 会和上一句「正在玩《X》」直接矛盾。
170
+ parts.push('最近两周没有玩游戏的记录');
171
+ }
172
+ return parts.join(';') + '。';
173
+ }
174
+
175
+ export class SteamClient {
176
+ /**
177
+ * @param {object} options
178
+ * @param {string} options.apiKey Steam Web API key(steamcommunity.com/dev/apikey 申请)
179
+ * @param {string} options.steamId 不再使用(保留形参只为兼容旧调用)
180
+ * @param {number} options.cacheTtlMs 结果缓存多久(用户可调,面板里叫「缓存时间」)
181
+ * @param {boolean} options.withGames 是否同时拉取游戏时长(需要「游戏详情」公开)
182
+ */
183
+ constructor({
184
+ apiKey = '', steamId = '', timeoutMs = 6000, cacheTtlMs = 60_000,
185
+ withGames = true, gameLimit = 8, errorCacheTtlMs = 60_000, logger = console,
186
+ } = {}) {
187
+ this.apiKey = String(apiKey ?? '').trim();
188
+ this.steamId = String(steamId ?? '').trim();
189
+ this.timeoutMs = Math.max(1000, Number(timeoutMs) || 6000);
190
+ // 0 表示不缓存。上限一天,防止有人填个天文数字之后状态永远不更新。
191
+ this.cacheTtlMs = Math.max(0, Math.min(86_400_000, Number(cacheTtlMs) || 0));
192
+ this.withGames = withGames !== false;
193
+ this.gameLimit = Math.max(1, Math.min(50, Number(gameLimit) || 8));
194
+ this.logger = logger;
195
+ // steamId → { at, status }
196
+ // 失败结果单独一个 TTL:默认 60 秒,上限同样一天。
197
+ this.errorCacheTtlMs = Math.max(0, Math.min(86_400_000, Number(errorCacheTtlMs) || 60_000));
198
+ this.cache = new Map();
199
+ }
200
+
201
+ get enabled() { return Boolean(this.apiKey); }
202
+
203
+ /** 换配置时调用,避免旧缓存继续生效。 */
204
+ reconfigure(patch = {}) {
205
+ if (patch.apiKey !== undefined) this.apiKey = String(patch.apiKey ?? '').trim();
206
+ if (patch.steamId !== undefined) this.steamId = String(patch.steamId ?? '').trim();
207
+ if (patch.cacheTtlMs !== undefined) {
208
+ this.cacheTtlMs = Math.max(0, Math.min(86_400_000, Number(patch.cacheTtlMs) || 0));
209
+ }
210
+ if (patch.withGames !== undefined) this.withGames = patch.withGames !== false;
211
+ if (patch.timeoutMs !== undefined) this.timeoutMs = Math.max(1000, Number(patch.timeoutMs) || 6000);
212
+ this.cache.clear();
213
+ }
214
+
215
+ /**
216
+ * 把一次失败记进缓存。
217
+ *
218
+ * 只记短时间:修好 Key 或网络恢复之后,不该还要等一个完整的成功缓存周期。
219
+ * 存的是 Error 对象本身,命中时原样抛出 —— 调用方拿到的错误和真实现场一致。
220
+ */
221
+ #rememberFailure(id, error) {
222
+ if (this.errorCacheTtlMs <= 0) return;
223
+ this.cache.set(id, { at: Date.now(), error });
224
+ }
225
+
226
+ async #get(path, params, signal) {
227
+ const url = new URL(API + path);
228
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v));
229
+ const timeout = AbortSignal.timeout(this.timeoutMs);
230
+ const combined = AbortSignal.any ? AbortSignal.any([signal, timeout].filter(Boolean)) : timeout;
231
+ let response;
232
+ try {
233
+ response = await fetch(url, { signal: combined, redirect: 'error' });
234
+ } catch (error) {
235
+ // 绝不把 URL 拼进错误信息。
236
+ //
237
+ // Steam 的接口把 API Key 放在查询串里(这是它规定的用法,没法改成 header)。
238
+ // 一旦某条日志顺手把完整地址打出来,Key 就永久留在 debug.log 里了。
239
+ // 这里只保留错误类型和原因,不带地址。
240
+ const reason = String(error?.name ?? 'Error') === 'TimeoutError'
241
+ ? '请求超时'
242
+ : String(error?.message ?? error);
243
+ throw new SteamError('Steam 请求中断或连接失败:' + reason, 'network');
244
+ }
245
+ if (response.status === 401 || response.status === 403) {
246
+ throw new SteamError('Steam API Key 无效或没有权限', 'auth');
247
+ }
248
+ if (response.status === 429) {
249
+ throw new SteamError('Steam 接口请求过于频繁,稍后再试', 'rate');
250
+ }
251
+ if (!response.ok) {
252
+ throw new SteamError(`Steam 返回 HTTP ${response.status}`, 'http');
253
+ }
254
+ try { return await response.json(); }
255
+ catch { throw new SteamError('Steam 返回的不是合法 JSON', 'format'); }
256
+ }
257
+
258
+ /**
259
+ * 查一个人现在的状态。
260
+ *
261
+ * steamId 为空时用构造函数里那个。缓存按 steamId 分开存 ——
262
+ * 群里不同人的绑定不能互相串。
263
+ */
264
+ async status(steamId = this.steamId, { signal, force = false } = {}) {
265
+ const id = String(steamId ?? '').trim() || this.steamId;
266
+ if (!this.apiKey) throw new SteamError('还没有配置 Steam API Key', 'config');
267
+ if (!id) throw new SteamError('还没有绑定 SteamID', 'config');
268
+ checkSignal(signal);
269
+
270
+ // 成功和失败都进缓存,但 TTL 不同。
271
+ //
272
+ // 以前只有成功才 cache.set。Key 失效或者 Steam 慢的时候,每一条私聊都要
273
+ // 先等满这一轮超时(玩家摘要 + 游戏库各最多 6 秒)才开始生成 ——
274
+ // 聊天会稳定地变慢,而且问题越持续越明显。
275
+ //
276
+ // 失败用一个很短的 TTL(最多 60 秒),既能挡住连续的等待,又不至于
277
+ // 让用户修好 Key 之后还要等很久才恢复。
278
+ const cached = this.cache.get(id);
279
+ if (!force && cached) {
280
+ const ttl = cached.error ? Math.min(this.cacheTtlMs || 60_000, this.errorCacheTtlMs) : this.cacheTtlMs;
281
+ if (ttl > 0 && Date.now() - cached.at < ttl) {
282
+ if (cached.error) throw cached.error;
283
+ return { ...cached.status, cached: true };
284
+ }
285
+ }
286
+
287
+ // 包一层:任何失败都记进缓存(带 error 标记),然后原样抛出去。
288
+ let payload;
289
+ try {
290
+ payload = await this.#get('/ISteamUser/GetPlayerSummaries/v2/', {
291
+ key: this.apiKey, steamids: id,
292
+ }, signal);
293
+ } catch (error) {
294
+ this.#rememberFailure(id, error);
295
+ throw error;
296
+ }
297
+ const player = Array.isArray(payload?.response?.players) ? payload.response.players[0] : null;
298
+ if (!player) {
299
+ // 空 players 只说明「查不到」。最常见的原因是隐私没开或 ID 写错,
300
+ // 而不是「这个人不存在」。区分不出来,所以两条可能都提一下。
301
+ const error = new SteamError('查不到这个 Steam 账号:检查 SteamID 是否正确、以及「游戏详情」是否设为公开', 'notfound');
302
+ this.#rememberFailure(id, error);
303
+ throw error;
304
+ }
305
+ const status = normalizePlayer(player);
306
+ if (!status) {
307
+ const error = new SteamError('Steam 返回的数据缺 steamid', 'format');
308
+ this.#rememberFailure(id, error);
309
+ throw error;
310
+ }
311
+
312
+ // 正在玩游戏时才有必要拉时长,而且只拉一次。
313
+ if (this.withGames) {
314
+ try {
315
+ const owned = await this.#get('/IPlayerService/GetOwnedGames/v1/', {
316
+ key: this.apiKey, steamid: id, include_appinfo: 1, include_played_free_games: 1,
317
+ }, signal);
318
+ const games = normalizeOwnedGames(owned, { limit: this.gameLimit });
319
+ if (games.length) status.recentGames = games;
320
+ // 这个接口在隐私没开时返回 { response: {} } —— 不是错误。
321
+ // 明确记下来,好让面板提示「时长拿不到」而不是让人以为没玩过游戏。
322
+ else status.gamesUnavailable = true;
323
+ } catch { /* 时长是附加信息,拿不到不影响在线状态 */ }
324
+ }
325
+
326
+ this.cache.set(id, { at: Date.now(), status });
327
+ return { ...status, cached: false };
328
+ }
329
+
330
+ /** 面板「测试连接」用:只看一眼能不能通,不写缓存。 */
331
+ async probe(steamId = this.steamId, { signal } = {}) {
332
+ return this.status(steamId, { signal, force: true });
333
+ }
334
+ }