@atian25/zzz-stats-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 atian25
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/api.mjs ADDED
@@ -0,0 +1,227 @@
1
+ import { SdkError, abortable, throwIfAborted } from './errors.mjs';
2
+
3
+ const REGIONS = new Set(['prod_gf_cn', 'prod_gf_jp', 'prod_gf_us', 'prod_gf_eu', 'prod_gf_sg']);
4
+ const DEFAULT_CHANNELS = [
5
+ ['2', 'GACHA_TYPE_CHARACTER_UP', '独家频段'],
6
+ ['102', 'GACHA_TYPE_CHARACTER_RETURN', '独家重映'],
7
+ ['3', 'GACHA_TYPE_WEAPON_UP', '音擎频段'],
8
+ ['103', 'GACHA_TYPE_WEAPON_RETURN', '音擎回响'],
9
+ ['1', 'GACHA_TYPE_PERMANENT', '常驻频段'],
10
+ ['5', 'GACHA_TYPE_BANGBOO', '邦布频段'],
11
+ ].map(([id, enumName, label]) => Object.freeze({ id, enum: enumName, label }));
12
+ const sessions = new WeakMap();
13
+ const invalid = message => { throw new SdkError('INVALID_ARGUMENT', message); };
14
+ const object = (value, label) => {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value)) invalid(`${label} 必须是对象`);
16
+ return value;
17
+ };
18
+ const keys = (value, allowed, label) => {
19
+ object(value, label);
20
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) invalid(`${label} 不支持参数 ${key}`);
21
+ };
22
+ const COMMON = ['region', 'signal', 'onProgress', 'log', 'dependencies'];
23
+ const LOGIN = ['channel', 'login', 'browser', 'endpoints'];
24
+
25
+ function common(options, stage = 'collect') {
26
+ const deps = options.dependencies ?? {};
27
+ keys(deps, ['fetch', 'sleep', 'now', 'encodeQr'], 'dependencies');
28
+ for (const [key, value] of Object.entries(deps)) if (typeof value !== 'function') invalid(`dependencies.${key} 必须是函数`);
29
+ for (const key of ['onProgress', 'log']) if (options[key] !== undefined && typeof options[key] !== 'function') invalid(`${key} 必须是函数`);
30
+ const signal = options.signal;
31
+ if (signal !== undefined && !(signal instanceof AbortSignal)) invalid('signal 必须是 AbortSignal');
32
+ throwIfAborted(signal);
33
+ const sleep = deps.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms)));
34
+ return {
35
+ log: options.log ?? (() => {}),
36
+ now: deps.now ?? Date.now,
37
+ signal,
38
+ progress: (status, data = {}) => callback(options.onProgress, { stage, status, ...data }, signal),
39
+ sleep: ms => abortable(() => sleep(ms), signal),
40
+ fetchImpl: async (url, init) => {
41
+ try {
42
+ const response = await abortable(() => (deps.fetch ?? fetch)(url, { ...init, signal }), signal);
43
+ return new Proxy(response, { get(target, key) {
44
+ const value = Reflect.get(target, key, target);
45
+ if (typeof value !== 'function') return value;
46
+ return (...args) => abortable(() => value.apply(target, args), signal);
47
+ } });
48
+ }
49
+ catch (cause) {
50
+ if (cause instanceof SdkError) throw cause;
51
+ throwIfAborted(signal);
52
+ throw new SdkError('NETWORK_ERROR', '网络请求失败', { stage, cause });
53
+ }
54
+ },
55
+ encodeQr: deps.encodeQr && (text => abortable(() => deps.encodeQr(text), signal)),
56
+ };
57
+ }
58
+
59
+ async function callback(fn, payload, signal) {
60
+ if (!fn) return;
61
+ try { return await abortable(() => fn(payload), signal); }
62
+ catch (cause) {
63
+ if (cause instanceof SdkError && cause.code === 'ABORTED') throw cause;
64
+ throw new SdkError('CALLBACK_FAILED', '调用方回调失败', { stage: 'callback', cause });
65
+ }
66
+ }
67
+
68
+ function channelsOf(channels = DEFAULT_CHANNELS) {
69
+ if (!Array.isArray(channels) || !channels.length) invalid('channels 必须是非空频道数组');
70
+ const ids = new Set(), enums = new Set();
71
+ return channels.map(ch => {
72
+ object(ch, '频道');
73
+ const known = DEFAULT_CHANNELS.find(v => v.id === ch.id && v.enum === ch.enum);
74
+ if (!known || typeof ch.label !== 'string' || !ch.label || ids.has(ch.id) || enums.has(ch.enum)) invalid('频道 id/enum 必须受支持且唯一,label 必须非空');
75
+ ids.add(ch.id); enums.add(ch.enum);
76
+ return { id: ch.id, enum: ch.enum, label: ch.label };
77
+ });
78
+ }
79
+
80
+ function loginOptions(options) {
81
+ const channel = options.channel ?? 'node';
82
+ const config = options.login ?? {};
83
+ object(config, 'login');
84
+ const method = config.method ?? 'qr';
85
+ if (!['node', 'browser'].includes(channel)) invalid('channel 只支持 node/browser');
86
+ if (!['qr', 'sms'].includes(method)) invalid('login.method 只支持 qr/sms');
87
+ if (channel === 'node' && method === 'sms') invalid('node 通道不支持 sms');
88
+ if (channel === 'node' && typeof config.onQr !== 'function') invalid('node 通道必须传 login.onQr');
89
+ keys(config, ['method', 'onQr', 'input', 'pollMs', 'maxWaitMs', 'maxRefresh', 'minRefreshGapMs'], 'login');
90
+ if (config.onQr !== undefined && typeof config.onQr !== 'function') invalid('login.onQr 必须是函数');
91
+ for (const key of ['pollMs', 'maxWaitMs', 'minRefreshGapMs']) {
92
+ if (config[key] !== undefined && (!Number.isFinite(config[key]) || config[key] <= 0)) invalid(`login.${key} 必须是正数`);
93
+ }
94
+ if (config.maxRefresh !== undefined && (!Number.isInteger(config.maxRefresh) || config.maxRefresh < 0)) invalid('login.maxRefresh 必须是非负整数');
95
+ const input = config.input ?? {};
96
+ keys(input, ['requestPhone', 'requestCode', 'takeRefreshRequest', 'subscribeRefresh', 'requestManualAction'], 'login.input');
97
+ for (const [key, value] of Object.entries(input)) if (typeof value !== 'function') invalid(`login.input.${key} 必须是函数`);
98
+ if (channel === 'node' && (config.maxRefresh !== undefined || config.minRefreshGapMs !== undefined || Object.keys(input).length)) invalid('node 通道当前不支持输入/刷新参数');
99
+ const region = options.region ?? 'prod_gf_cn';
100
+ if (!REGIONS.has(region)) invalid('未知 region');
101
+ if (channel === 'node' && region !== 'prod_gf_cn') throw new SdkError('UNSUPPORTED_REGION', 'node 通道只支持国服', { stage: 'validate' });
102
+ if (method === 'sms' && region !== 'prod_gf_cn') invalid('sms 当前仅支持国服 +86');
103
+ if (channel === 'browser') {
104
+ keys(options.browser ?? {}, ['driver'], 'browser');
105
+ object(options.browser?.driver, 'browser.driver');
106
+ } else if (options.browser !== undefined) invalid('node 通道不接受 browser 参数');
107
+ keys(options.endpoints ?? {}, ['api', 'page'], 'endpoints');
108
+ for (const value of Object.values(options.endpoints ?? {})) {
109
+ try { if (!['http:', 'https:'].includes(new URL(value).protocol)) invalid('endpoint 必须是 HTTP URL'); }
110
+ catch { invalid('endpoint 必须是 HTTP URL'); }
111
+ }
112
+ return { channel, method, region, config, input };
113
+ }
114
+
115
+ function makeSession(fields, drv, owned) {
116
+ let closing;
117
+ const state = { closed: false, drv };
118
+ const session = {
119
+ ...fields,
120
+ async close() {
121
+ if (!closing) {
122
+ state.closed = true;
123
+ if (session.channel === 'node') session.cookieHeader = '';
124
+ closing = Promise.resolve().then(() => owned ? drv?.close?.() : undefined);
125
+ }
126
+ await closing;
127
+ },
128
+ };
129
+ for (const key of ['channel', 'gameUid', 'region']) {
130
+ Object.defineProperty(session, key, { value: fields[key], enumerable: true, writable: false, configurable: false });
131
+ }
132
+ sessions.set(session, state);
133
+ return session;
134
+ }
135
+
136
+ /** 分步登录;方式与执行通道是两个独立参数维度。 */
137
+ export async function login(options = {}) {
138
+ keys(options, [...COMMON, ...LOGIN], 'login options');
139
+ const { channel, method, region, config, input } = loginOptions(options);
140
+ const deps = common(options, 'login');
141
+ await callback(options.onProgress, { stage: 'login', status: 'started', message: '申请登录' }, options.signal);
142
+ const onQr = config.onQr && (qr => callback(config.onQr, { dataUrl: qr.dataUrl }, options.signal));
143
+ if (channel === 'node') {
144
+ const { loginByQrNode } = await import('./login-node.mjs');
145
+ const result = await loginByQrNode({ ...deps, onQr, region, pollMs: config.pollMs, maxWaitMs: config.maxWaitMs });
146
+ return makeSession({ channel, accountId: result.uid || null, gameUid: result.gameUid,
147
+ nickname: result.nickname, region, cookieHeader: result.cookieHeader });
148
+ }
149
+ const { loginByQrBrowser } = await import('./login-browser.mjs');
150
+ const host = region === 'prod_gf_cn' ? 'act.mihoyo.com' : 'act.hoyolab.com';
151
+ const result = await loginByQrBrowser({
152
+ ...deps, driver: options.browser.driver, region,
153
+ pageUrl: options.endpoints?.page ?? `https://${host}/zzz/event/gacha-record/index.html`,
154
+ loginMode: method, onQr,
155
+ input: {
156
+ ...input,
157
+ requestPhone: input.requestPhone && (() => callback(input.requestPhone, { signal: options.signal }, options.signal)),
158
+ requestCode: input.requestCode && (() => callback(input.requestCode, { signal: options.signal }, options.signal)),
159
+ requestManualAction: input.requestManualAction && (context => callback(input.requestManualAction, context, options.signal)),
160
+ takeRefreshRequest: input.takeRefreshRequest && (() => callback(input.takeRefreshRequest, undefined, options.signal)),
161
+ subscribeRefresh: input.subscribeRefresh && (() => {
162
+ throwIfAborted(options.signal);
163
+ let unsubscribe;
164
+ try { unsubscribe = input.subscribeRefresh(); } catch (cause) { throw new SdkError('CALLBACK_FAILED', '订阅刷新失败', { stage: 'callback', cause }); }
165
+ if (typeof unsubscribe !== 'function') invalid('subscribeRefresh 必须同步返回退订函数');
166
+ return () => { try { unsubscribe(); } catch (cause) { throw new SdkError('CALLBACK_FAILED', '退订刷新失败', { stage: 'callback', cause }); } };
167
+ }),
168
+ },
169
+ pollMs: config.pollMs, maxWaitMs: config.maxWaitMs,
170
+ maxRefresh: config.maxRefresh, minGapMs: config.minRefreshGapMs,
171
+ });
172
+ return makeSession({ channel, accountId: null, gameUid: result.uid, nickname: result.nickname, region }, result.drv, result.owned);
173
+ }
174
+
175
+ /** 已有会话取数;不关闭借入 session。 */
176
+ export async function collect(options = {}) {
177
+ keys(options, [...COMMON, 'session', 'channels', 'endpoints'], 'collect options');
178
+ const session = object(options.session, 'session');
179
+ if (!['node', 'browser'].includes(session.channel) || typeof session.gameUid !== 'string' || !/^\d+$/.test(session.gameUid) || typeof session.close !== 'function') invalid('session 缺少有效 channel/gameUid/close');
180
+ if (!REGIONS.has(session.region) || (options.region !== undefined && options.region !== session.region)) invalid('region 必须与 session.region 一致');
181
+ // 自建 Node session 不在 WeakMap;调用方负责 close 后清空 Cookie 或拒绝复用。
182
+ const state = sessions.get(session);
183
+ if (state?.closed) invalid('session 已关闭');
184
+ if (session.channel === 'node' && !session.cookieHeader) invalid('node session 需要 cookieHeader');
185
+ if (session.channel === 'node' && session.region !== 'prod_gf_cn') throw new SdkError('UNSUPPORTED_REGION', 'node 通道只支持国服');
186
+ if (session.channel === 'browser' && !state?.drv) invalid('browser session 必须由 login 返回');
187
+ const channels = channelsOf(options.channels);
188
+ keys(options.endpoints ?? {}, ['api'], 'endpoints');
189
+ const deps = common(options);
190
+ const { ACT_API } = await import('./transport-node.mjs');
191
+ const api = options.endpoints?.api ?? (session.region === 'prod_gf_cn' ? ACT_API.cn : ACT_API.os);
192
+ try { if (!['http:', 'https:'].includes(new URL(api).protocol)) invalid('api 必须是 HTTP URL'); }
193
+ catch { invalid('api 必须是 HTTP URL'); }
194
+ await callback(options.onProgress, { stage: 'collect', status: 'started', message: '开始取数' }, options.signal);
195
+ const args = { ...deps, uid: session.gameUid, nickname: session.nickname,
196
+ region: session.region, channels, api, fetchedAt: new Date(deps.now()).toISOString() };
197
+ let result;
198
+ if (session.channel === 'node') {
199
+ const { collectViaNode } = await import('./login-node.mjs');
200
+ result = await collectViaNode({ ...args, cookieHeader: session.cookieHeader });
201
+ } else {
202
+ const { collectViaBrowser } = await import('./login-browser.mjs');
203
+ result = await collectViaBrowser({ ...args, drv: state.drv });
204
+ }
205
+ throwIfAborted(options.signal);
206
+ await deps.progress('completed');
207
+ const files = new Map(result.files);
208
+ files.delete('meta.json');
209
+ return { gameUid: session.gameUid, nickname: session.nickname ?? null, region: session.region,
210
+ files, summary: result.summary, meta: result.meta };
211
+ }
212
+
213
+ /** 完整流程;不接 cfg 或已有 session。 */
214
+ export async function collectData(options = {}) {
215
+ keys(options, [...COMMON, ...LOGIN, 'channels'], 'collectData options');
216
+ loginOptions(options);
217
+ channelsOf(options.channels);
218
+ const { channels, endpoints, ...loginArgs } = options;
219
+ const session = await login({ ...loginArgs, endpoints });
220
+ try {
221
+ const result = await collect({ session, channels, endpoints: endpoints?.api ? { api: endpoints.api } : undefined,
222
+ region: options.region, signal: options.signal, dependencies: options.dependencies,
223
+ onProgress: options.onProgress, log: options.log });
224
+ await callback(options.onProgress, { stage: 'done', status: 'completed', message: '采集完成' }, options.signal);
225
+ return result;
226
+ } finally { await session.close(); }
227
+ }
package/collect.mjs ADDED
@@ -0,0 +1,143 @@
1
+ /** 登录后采集内核:只返回 13 个响应键与独立 meta,不读消费者配置。 */
2
+
3
+ import { throwIfAborted, SdkError } from './errors.mjs';
4
+
5
+ /** 单次 hist_pool_stat 最多带 10 个版本(接口上限,超了报 -400005)。 */
6
+ export const MAX_VERS = 10;
7
+ /** 请求间隔。沿用改前实测值:太快会被限流,350ms 稳。 */
8
+ export const REQUEST_GAP_MS = 350;
9
+
10
+ /** 版本号降序。与改前 `sortVersionsDesc` 一字不差。 */
11
+ export function sortVersionsDesc(list) {
12
+ return [...list].sort((a, b) => {
13
+ const pa = String(a).split('.').map(Number);
14
+ const pb = String(b).split('.').map(Number);
15
+ return pb[0] - pa[0] || (pb[1] ?? 0) - (pa[1] ?? 0);
16
+ });
17
+ }
18
+
19
+ /** 按 n 分片。与改前 `chunk` 一字不差。 */
20
+ export function chunk(list, n) {
21
+ const out = [];
22
+ for (let i = 0; i < list.length; i += n) out.push(list.slice(i, i + n));
23
+ return out;
24
+ }
25
+
26
+ /**
27
+ * 按频道取数,产出 13 个键的 Map(不含 meta.json —— 那个要昵称,由外层补)。
28
+ *
29
+ * 这段是改前 `collectAll()` 的原样搬迁(含「先 index 再逐频道」「每频道 cur + hist」
30
+ * 「hist 按版本分片并去重」的顺序)。**顺序不能改**:产物里的键序、
31
+ * 以及「缺某个频道时 hist 用空 list 兜底」的行为都依赖它。
32
+ *
33
+ * @param {object} args
34
+ * @param {{fetchJson: Function, kind: string}} args.transport
35
+ * @param {Array<{id: string|number, enum: string, label: string}>} args.channels
36
+ * @param {(msg: string) => void} [args.log]
37
+ * @param {(ms: number) => Promise<void>} [args.sleep]
38
+ */
39
+ export async function collectFiles({ transport, channels, log = () => {}, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), signal, progress = async () => {} }) {
40
+ throwIfAborted(signal);
41
+ const index = await transport.fetchJson('/index');
42
+ if (!index?.data || !Array.isArray(index.data.type_stats)) throw new SdkError('INVALID_RESPONSE', 'index 缺少 type_stats', { stage: 'collect', endpoint: '/index' });
43
+ const byEnum = new Map((index.data.type_stats ?? []).map((t) => [t.gacha_type, t]));
44
+
45
+ const files = new Map();
46
+ files.set('index.json', index);
47
+ const summary = {};
48
+
49
+ for (const ch of channels) {
50
+ throwIfAborted(signal);
51
+ await progress('channel-start', { channelId: ch.id });
52
+ const stat = byEnum.get(ch.enum);
53
+
54
+ await sleep(REQUEST_GAP_MS);
55
+ let cur;
56
+ try {
57
+ cur = await transport.fetchJson('/cur_pool_stat', `gacha_type=${ch.id}`);
58
+ } catch (e) {
59
+ /*
60
+ * 单频道 cur 失败不致命:音擎回响这类频道常常一条记录都没有,
61
+ * 接口会报错或返回空。用空 list 兜底,让该频道在报表里正常显示「没有金」。
62
+ */
63
+ log(`⚠️ ${ch.label} cur_pool_stat 失败:${e.message}`);
64
+ cur = { retcode: 0, data: { list: [] } };
65
+ }
66
+ throwIfAborted(signal);
67
+ files.set(`cur_pool_stat_${ch.id}.json`, cur);
68
+
69
+ // 历史卡池:必须用本频道自己的 has_data_vers,且单次最多 10 个
70
+ const vers = sortVersionsDesc(stat?.has_data_vers ?? []);
71
+ const pools = [];
72
+ for (const slice of chunk(vers, MAX_VERS)) {
73
+ await sleep(REQUEST_GAP_MS);
74
+ try {
75
+ const hist = await transport.fetchJson('/hist_pool_stat', `gacha_type=${ch.id}&vers=${slice.join(',')}`);
76
+ pools.push(...(hist.data?.list ?? []));
77
+ } catch (e) {
78
+ if (e.retcode === -400005) throw new SdkError('UPSTREAM_ERROR', `${ch.label}: vers 分片仍报参数错误`, { stage: 'collect', retcode: e.retcode, endpoint: '/hist_pool_stat', cause: e });
79
+ throw e;
80
+ }
81
+ }
82
+ /*
83
+ * 分片之间可能有重叠(同一版本可能出现在多个分片的返回里),按四元组去重。
84
+ * 改前就是这么做的,**判据别动**:只看 gacha_type|version|start_ts|end_ts,
85
+ * 不看记录内容 —— 同一卡池的不同版本属于不同条目,本来就该都在。
86
+ */
87
+ const seen = new Set();
88
+ const merged = pools.filter((p) => {
89
+ const key = `${p.gacha_type}|${p.version}|${p.start_ts}|${p.end_ts}`;
90
+ if (seen.has(key)) return false;
91
+ seen.add(key);
92
+ return true;
93
+ });
94
+ files.set(`hist_pool_stat_${ch.id}.json`, {
95
+ retcode: 0,
96
+ message: 'OK',
97
+ data: { cur_ver: index.data.cur_ver, list: merged },
98
+ });
99
+
100
+ const countGold = (list) => list.reduce((s, p) => s + (p.cur_records?.length ?? 0), 0);
101
+ const golds = countGold(merged) + countGold(cur.data?.list ?? []);
102
+ summary[ch.id] = { label: ch.label, pulls: Number(stat?.total_count ?? 0), sCount: Number(stat?.s_count ?? 0), golds };
103
+ await progress('channel-done', { channelId: ch.id });
104
+ log(`${ch.label}: ${summary[ch.id].pulls} 抽 / 官方 S ${summary[ch.id].sCount} / 取到金 ${golds} / 版本 ${vers.length}`);
105
+ }
106
+
107
+ return { files, summary, index };
108
+ }
109
+
110
+ /**
111
+ * 由 index + 登录阶段信息拼出 meta.json 的内容。
112
+ *
113
+ * **字段顺序与改前完全一致**(`JSON.stringify(meta, null, 2)` 落盘,键序会影响字节):
114
+ * 改前在 `scripts/collect.mjs` 的 main 里手写这个对象,这里原样搬过来。
115
+ *
116
+ * @param {object} args
117
+ * @param {object} args.index `/index` 的原始响应
118
+ * @param {string} args.uid
119
+ * @param {string|null} args.nickname
120
+ * @param {string} args.region
121
+ * @param {string} args.api
122
+ * @param {Record<string, object>} args.summary
123
+ * @param {string} [args.fetchedAt] 采集时间(ISO),默认 now
124
+ * @param {boolean} [args.isCn]
125
+ */
126
+ export function buildMeta({ index, uid, nickname, region, api, summary, fetchedAt, isCn }) {
127
+ const versions = (index.data.type_stats ?? []).flatMap((t) => t.has_data_vers ?? []);
128
+ const uniq = sortVersionsDesc([...new Set(versions)]);
129
+ return {
130
+ schema: 'zzz-stats/v1',
131
+ server: (isCn ?? /^prod_gf_cn$/i.test(region)) ? 'cn' : 'os',
132
+ uid,
133
+ region,
134
+ nickname: nickname ?? null,
135
+ fetched_at: fetchedAt ?? new Date().toISOString(),
136
+ versions: uniq.length ? `${uniq[uniq.length - 1]} → ${uniq[0]}` : null,
137
+ source: api,
138
+ channels: summary,
139
+ total_gacha_count: Number(index.data.total_gacha_count ?? 0),
140
+ total_s_count: Number(index.data.total_s_count ?? 0),
141
+ total_counts_exclude_bangboo: true,
142
+ };
143
+ }