dsh-sidebar-usage 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/README.zh.md +71 -0
- package/cordis.patch.yml +5 -0
- package/icon.svg +21 -0
- package/lib/accounts.js +1009 -0
- package/lib/client.js +5112 -0
- package/lib/custom.js +427 -0
- package/lib/index.js +1488 -0
- package/lib/pricing.js +420 -0
- package/lib/providers.js +183 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +68 -4
- package/screenshot.png +0 -0
- package/screenshot2.png +0 -0
- package/screenshots.json +4 -0
package/lib/custom.js
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-deepseek-usage — 自定义 provider(自定义 URL)。
|
|
3
|
+
*
|
|
4
|
+
* 能力表里没有的网关 / 中转(例如自建的 new-api、one-api、任何返回 JSON 余额的
|
|
5
|
+
* 中间层)可以用 `customProviders` 显式登记:给一个 baseUrl、一条路径、认证方式,
|
|
6
|
+
* 再用点路径(`data.limit_remaining`、`0.total_balance`)指出哪个字段是余额。
|
|
7
|
+
*
|
|
8
|
+
* 设计口径与 lib/providers.js 一致:**不猜**。地址、路径、字段名全部由用户给出;
|
|
9
|
+
* 猜出来的读数与账单无关。所以:
|
|
10
|
+
* · 没给 baseUrl → 整条丢弃并记 warning;
|
|
11
|
+
* · 没给 totalPath 且不是预设形态 → 解析失败(shape),不假装读到了 0;
|
|
12
|
+
* · 读不到剩余额度时(例如 new-api 的 `/v1/dashboard/billing/subscription`
|
|
13
|
+
* 只返回哨兵值 1e8),退回显示「已用」,币种位写 USED —— 绝不把已用当成余额。
|
|
14
|
+
*
|
|
15
|
+
* 预设三种常见形态,省掉手填路径:
|
|
16
|
+
* · json 通用 GET,一个响应里按 totalPath 取值;
|
|
17
|
+
* · deepseek-balance `GET /user/balance`(与官方同形,可指向中转);
|
|
18
|
+
* · openai-billing `/v1/dashboard/billing/{subscription,usage}` 两段式(OpenAI 口径,usage 为分);
|
|
19
|
+
* · newapi 同上,但 usage 按 new-api 的 quota 单位(默认不缩放,币种 CNY)。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** provider id 的宽松上限;只挡空白与异常长度(与 providers.js 同口径)。 */
|
|
23
|
+
const MAX_ID_LENGTH = 128;
|
|
24
|
+
|
|
25
|
+
/** 凭据引用名必须是环境变量名形态。 */
|
|
26
|
+
const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
27
|
+
|
|
28
|
+
export const CUSTOM_KINDS = ['balance', 'usage'];
|
|
29
|
+
export const CUSTOM_AUTHS = ['bearer', 'raw', 'none'];
|
|
30
|
+
export const CUSTOM_PRESETS = ['json', 'deepseek-balance', 'openai-billing', 'newapi', 'jichuanai'];
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 预设默认值。`path` 是主请求,`usagePath` 是第二段请求(可选)。
|
|
34
|
+
* `scale` 乘在解析出的数字上:OpenAI 的 usage 单位是"分",所以 0.01;
|
|
35
|
+
* new-api 实测的 total_usage 已经是"额度单位"(1 单位 = quota_per_unit),保持 1。
|
|
36
|
+
*/
|
|
37
|
+
const PRESET_DEFAULTS = {
|
|
38
|
+
json: { path: '', usagePath: '', currency: 'CNY', scale: 1 },
|
|
39
|
+
'deepseek-balance': { path: '/user/balance', usagePath: '', currency: 'CNY', scale: 1 },
|
|
40
|
+
'openai-billing': {
|
|
41
|
+
path: '/v1/dashboard/billing/subscription',
|
|
42
|
+
usagePath: '/v1/dashboard/billing/usage',
|
|
43
|
+
currency: 'USD',
|
|
44
|
+
scale: 0.01,
|
|
45
|
+
},
|
|
46
|
+
newapi: {
|
|
47
|
+
path: '/v1/dashboard/billing/subscription',
|
|
48
|
+
usagePath: '/v1/dashboard/billing/usage',
|
|
49
|
+
currency: 'CNY',
|
|
50
|
+
scale: 1,
|
|
51
|
+
},
|
|
52
|
+
// 济川AI(jc.jichuanai.com):实测 GET /api/v1/subscriptions →
|
|
53
|
+
// data[0].group.weekly_limit_usd(额度)/ weekly_usage_usd(已用)/ expires_at(到期)
|
|
54
|
+
// 余额口径:GET /api/v1/user/profile → data.balance
|
|
55
|
+
jichuanai: {
|
|
56
|
+
path: '/api/v1/subscriptions',
|
|
57
|
+
totalPath: 'data.0.group.weekly_limit_usd',
|
|
58
|
+
usedPath: 'data.0.weekly_usage_usd',
|
|
59
|
+
expiresPath: 'data.0.expires_at',
|
|
60
|
+
balancePath: '/api/v1/user/profile',
|
|
61
|
+
balanceTotalPath: 'data.balance',
|
|
62
|
+
currency: 'USD',
|
|
63
|
+
scale: 1,
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** `ASNIA` → `ASNIA_API_KEY`:与 providers.js 的派生引用同一规则。 */
|
|
68
|
+
export function derivedKeyRef(provider) {
|
|
69
|
+
return `${String(provider).toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function text(value) {
|
|
73
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 接受字符串或数字,返回有限数或 null(绝不把缺失变成 0)。 */
|
|
77
|
+
function num(value) {
|
|
78
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
|
79
|
+
if (typeof value === 'string' && value.trim() !== '') {
|
|
80
|
+
const n = Number(value);
|
|
81
|
+
return Number.isFinite(n) ? n : null;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function round2(value) {
|
|
87
|
+
return Math.round(value * 100) / 100;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** baseUrl:只接受 http(s),保留路径前缀(网关常挂在 /api 下),去掉尾部斜杠。 */
|
|
91
|
+
function normalizeBaseUrl(raw) {
|
|
92
|
+
const value = text(raw);
|
|
93
|
+
if (value === '') return null;
|
|
94
|
+
let url;
|
|
95
|
+
try {
|
|
96
|
+
url = new URL(value);
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
|
|
101
|
+
const path = url.pathname.replace(/\/+$/, '');
|
|
102
|
+
return `${url.origin}${path}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 路径:缺省用预设值;必须以 / 开头。 */
|
|
106
|
+
function normalizePath(raw, fallback) {
|
|
107
|
+
const value = text(raw);
|
|
108
|
+
const path = value === '' ? fallback : value;
|
|
109
|
+
if (path === '') return '';
|
|
110
|
+
return path.startsWith('/') ? path : `/${path}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 按点路径从 JSON 里取值:`data.limit_remaining`、`balance_infos.0.total_balance`、
|
|
115
|
+
* `items[0].total` 都支持。取不到返回 undefined(调用方据此报 empty,而不是 0)。
|
|
116
|
+
*/
|
|
117
|
+
export function readPath(body, path) {
|
|
118
|
+
const spec = text(path);
|
|
119
|
+
if (spec === '') return undefined;
|
|
120
|
+
let current = body;
|
|
121
|
+
for (const rawSegment of spec.split('.')) {
|
|
122
|
+
let segment = rawSegment.trim();
|
|
123
|
+
if (segment === '') return undefined;
|
|
124
|
+
let index = null;
|
|
125
|
+
const bracket = segment.match(/^(.*)\[(\d+)\]$/);
|
|
126
|
+
if (bracket !== null) {
|
|
127
|
+
segment = bracket[1];
|
|
128
|
+
index = Number(bracket[2]);
|
|
129
|
+
}
|
|
130
|
+
if (segment !== '') {
|
|
131
|
+
if (current === null || typeof current !== 'object') return undefined;
|
|
132
|
+
current = current[segment];
|
|
133
|
+
}
|
|
134
|
+
if (index !== null) {
|
|
135
|
+
if (!Array.isArray(current)) return undefined;
|
|
136
|
+
current = current[index];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return current;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 把配置里的 `customProviders` 整理成可查询的 Map。
|
|
144
|
+
*
|
|
145
|
+
* 接受 `[{ provider, baseUrl, … }]`;非法项整体丢弃并记一条 warning(由调用方写进
|
|
146
|
+
* 日志,避免坏配置静默生效)。重复 provider 取第一条。
|
|
147
|
+
*
|
|
148
|
+
* @param {unknown} raw `config.customProviders`
|
|
149
|
+
* @returns {{ providers: Map<string, object>, warnings: string[] }}
|
|
150
|
+
*/
|
|
151
|
+
export function normalizeCustomProviders(raw) {
|
|
152
|
+
const providers = new Map();
|
|
153
|
+
const warnings = [];
|
|
154
|
+
if (raw !== null && typeof raw === 'object' && !Array.isArray(raw) && typeof raw.get === 'function') {
|
|
155
|
+
try {
|
|
156
|
+
return normalizeCustomProviders(raw.get());
|
|
157
|
+
} catch {
|
|
158
|
+
warnings.push('customProviders 无法读取,已忽略');
|
|
159
|
+
return { providers, warnings };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (raw === undefined || raw === null) return { providers, warnings };
|
|
163
|
+
if (!Array.isArray(raw)) {
|
|
164
|
+
warnings.push('customProviders 不是数组,已忽略');
|
|
165
|
+
return { providers, warnings };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
for (const item of raw) {
|
|
169
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
|
|
170
|
+
warnings.push('忽略了一条不是对象的自定义 provider');
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const provider = text(item.provider);
|
|
174
|
+
if (provider === '' || provider.length > MAX_ID_LENGTH || /\s/.test(provider)) {
|
|
175
|
+
warnings.push('忽略了一条 provider id 非法的自定义 provider');
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const baseUrl = normalizeBaseUrl(item.baseUrl);
|
|
179
|
+
if (baseUrl === null) {
|
|
180
|
+
warnings.push(`忽略自定义 provider ${provider}:baseUrl 必须是 http(s) 地址`);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const presetRaw = text(item.preset).toLowerCase();
|
|
184
|
+
const preset = CUSTOM_PRESETS.includes(presetRaw) ? presetRaw : 'json';
|
|
185
|
+
const defaults = PRESET_DEFAULTS[preset];
|
|
186
|
+
const kindRaw = text(item.kind).toLowerCase();
|
|
187
|
+
const kind = CUSTOM_KINDS.includes(kindRaw) ? kindRaw : 'balance';
|
|
188
|
+
const authRaw = text(item.auth).toLowerCase();
|
|
189
|
+
const auth = CUSTOM_AUTHS.includes(authRaw) ? authRaw : 'bearer';
|
|
190
|
+
const currency = (text(item.currency) || defaults.currency).toUpperCase();
|
|
191
|
+
const scale = num(item.scale);
|
|
192
|
+
const quota = num(item.quota);
|
|
193
|
+
const refRaw = text(item.apiKeyRef);
|
|
194
|
+
// 引用名与明文密钥都允许:明文原样保留,交给取数层直接当 secret;
|
|
195
|
+
// 只有留空时才回退到派生引用(provider → PROVIDER_API_KEY)。
|
|
196
|
+
const ref = refRaw !== "" ? refRaw : derivedKeyRef(provider);
|
|
197
|
+
|
|
198
|
+
// 账户类型:balance = 看余额接口;subscription = 看订阅额度(含已用与到期);
|
|
199
|
+
// auto = 配了 usedPath/expiresPath 就按订阅,否则按余额。
|
|
200
|
+
const typeRaw = text(item.accountType).toLowerCase();
|
|
201
|
+
const balancePath = normalizePath(item.balancePath, defaults.balancePath ?? '');
|
|
202
|
+
const balanceTotalPath = text(item.balanceTotalPath) || (defaults.balanceTotalPath ?? '');
|
|
203
|
+
const configuredType = typeRaw === 'balance' || typeRaw === 'subscription' ? typeRaw : 'auto';
|
|
204
|
+
const looksSubscription = text(item.usedPath) !== '' || text(item.expiresPath) !== '';
|
|
205
|
+
const accountType = configuredType === 'auto'
|
|
206
|
+
? (looksSubscription ? 'subscription' : 'balance')
|
|
207
|
+
: configuredType;
|
|
208
|
+
|
|
209
|
+
const path = normalizePath(item.path, defaults.path);
|
|
210
|
+
if (path === '') {
|
|
211
|
+
warnings.push(`忽略自定义 provider ${provider}:preset=json 时必须给出 path`);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const usagePath = normalizePath(item.usagePath, defaults.usagePath);
|
|
215
|
+
|
|
216
|
+
const key = provider.toLowerCase();
|
|
217
|
+
if (providers.has(key)) {
|
|
218
|
+
warnings.push(`忽略重复的自定义 provider:${provider}`);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
// 按当前类型决定实际请求哪一组(另一组字段保留,切换时不必重填)。
|
|
222
|
+
const useSubscription = accountType === 'subscription';
|
|
223
|
+
const pickedPath = useSubscription ? path : (balancePath !== '' ? balancePath : path);
|
|
224
|
+
const subTotalPath = text(item.totalPath) || (defaults.totalPath ?? '');
|
|
225
|
+
const subUsedPath = text(item.usedPath) || (defaults.usedPath ?? '');
|
|
226
|
+
const subExpiresPath = text(item.expiresPath) || (defaults.expiresPath ?? '');
|
|
227
|
+
const pickedTotal = useSubscription ? subTotalPath : (balanceTotalPath !== '' ? balanceTotalPath : subTotalPath);
|
|
228
|
+
const pickedUsed = useSubscription ? subUsedPath : '';
|
|
229
|
+
const pickedExpires = useSubscription ? subExpiresPath : '';
|
|
230
|
+
if (pickedPath === '') {
|
|
231
|
+
warnings.push(`忽略自定义 provider ${provider}:path / balancePath 至少要给一个`);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const label = text(item.label);
|
|
236
|
+
providers.set(key, {
|
|
237
|
+
id: provider,
|
|
238
|
+
displayName: label === '' ? provider : label,
|
|
239
|
+
kind,
|
|
240
|
+
// 只有显式登记的 provider 才带 custom:accounts.js 据此走自定义取数分支。
|
|
241
|
+
custom: {
|
|
242
|
+
preset,
|
|
243
|
+
baseUrl,
|
|
244
|
+
// 生效组(按 accountType 选好)
|
|
245
|
+
path: pickedPath,
|
|
246
|
+
totalPath: pickedTotal,
|
|
247
|
+
usedPath: pickedUsed,
|
|
248
|
+
expiresPath: pickedExpires,
|
|
249
|
+
availablePath: text(item.availablePath),
|
|
250
|
+
// 两组原始值,编辑表单切换类型时用
|
|
251
|
+
accountType,
|
|
252
|
+
rawPath: path,
|
|
253
|
+
rawTotalPath: subTotalPath,
|
|
254
|
+
rawUsedPath: subUsedPath,
|
|
255
|
+
rawExpiresPath: subExpiresPath,
|
|
256
|
+
balancePath,
|
|
257
|
+
balanceTotalPath,
|
|
258
|
+
usagePath,
|
|
259
|
+
auth,
|
|
260
|
+
currency,
|
|
261
|
+
scale: scale === null || scale <= 0 ? defaults.scale : scale,
|
|
262
|
+
quota: quota === null || quota <= 0 ? 0 : quota,
|
|
263
|
+
// 原样记住,供取数层判断"引用名还是明文密钥"。
|
|
264
|
+
apiKeyRef: refRaw,
|
|
265
|
+
// 可选:借用哪家主流的单价表算「每 token 价格」。中转站自己的名字不在价格表里,
|
|
266
|
+
// 不填就只能是 known:false(卡片不显示单价)。
|
|
267
|
+
pricing: text(item.pricing).toLowerCase(),
|
|
268
|
+
},
|
|
269
|
+
refs: [ref],
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
return { providers, warnings };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 认证头:raw = 原样放进 Authorization(部分网关要求裸 key),none = 不带。 */
|
|
276
|
+
export function customHeaders(auth, secret) {
|
|
277
|
+
if (auth === 'none') return {};
|
|
278
|
+
if (auth === 'raw') return { Authorization: secret };
|
|
279
|
+
return { Authorization: `Bearer ${secret}` };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 账单类接口按自然月区间查询(当月 1 日 → 今天)。 */
|
|
283
|
+
function monthRangeQuery() {
|
|
284
|
+
const now = new Date();
|
|
285
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
286
|
+
const start = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-01`;
|
|
287
|
+
const end = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
|
288
|
+
return `?start_date=${start}&end_date=${end}`;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 这次读要打哪些请求。
|
|
293
|
+
* @returns {Array<{ key: 'main' | 'usage', url: string }>}
|
|
294
|
+
*/
|
|
295
|
+
export function customTargets(spec) {
|
|
296
|
+
const targets = [{ key: 'main', url: `${spec.baseUrl}${spec.path}` }];
|
|
297
|
+
if (spec.usagePath !== '' && spec.usagePath !== spec.path) {
|
|
298
|
+
const query = spec.preset === 'openai-billing' || spec.preset === 'newapi' ? monthRangeQuery() : '';
|
|
299
|
+
targets.push({ key: 'usage', url: `${spec.baseUrl}${spec.usagePath}${query}` });
|
|
300
|
+
}
|
|
301
|
+
return targets;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function fail(code) {
|
|
305
|
+
return { ok: false, balance: null, usage: null, code };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function okBalance(balance, usage = null, expiresAt = null) {
|
|
309
|
+
return { ok: true, balance, usage, expiresAt };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** DeepSeek 同形响应:{ is_available, balance_infos: [{ currency, total_balance }] }。 */
|
|
313
|
+
function parseDeepseekShape(spec, body) {
|
|
314
|
+
if (body?.is_available === false) return fail('unavailable');
|
|
315
|
+
const infos = Array.isArray(body?.balance_infos) ? body.balance_infos : [];
|
|
316
|
+
if (infos.length === 0) return fail('shape');
|
|
317
|
+
const withTotal = infos.filter((info) => num(info?.total_balance) !== null);
|
|
318
|
+
if (withTotal.length === 0) return fail('empty');
|
|
319
|
+
const want = spec.currency;
|
|
320
|
+
const pick = withTotal.find((info) => String(info?.currency ?? '').trim().toUpperCase() === want) ?? withTotal[0];
|
|
321
|
+
const total = num(pick.total_balance);
|
|
322
|
+
if (total === null) return fail('empty');
|
|
323
|
+
return okBalance({
|
|
324
|
+
isAvailable: true,
|
|
325
|
+
total: round2(total * spec.scale),
|
|
326
|
+
currency: want === '' ? String(pick.currency ?? '').trim().toUpperCase() || null : want,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* 两段式账单(OpenAI / new-api):
|
|
332
|
+
* subscription → hard_limit_usd(额度;new-api 实测恒为 1e8 哨兵,视为"额度未知")
|
|
333
|
+
* usage → total_usage(已用)
|
|
334
|
+
*
|
|
335
|
+
* 额度已知 → total = 额度 - 已用,币种按配置;
|
|
336
|
+
* 额度未知 → total = 已用,币种位写 USED(绝不把已用显示成余额);
|
|
337
|
+
* 配置了 quota → 以 quota 为准(用户自己知道站长给了多少)。
|
|
338
|
+
*/
|
|
339
|
+
function parseBilling(spec, subscription, usageBody) {
|
|
340
|
+
const hard = num(readPath(subscription, 'hard_limit_usd'));
|
|
341
|
+
const usedRaw = num(readPath(usageBody, 'total_usage'));
|
|
342
|
+
const used = usedRaw === null ? null : round2(usedRaw * spec.scale);
|
|
343
|
+
// 1e7 以上当哨兵:new-api 的 unlimited 占位值是 1e8。
|
|
344
|
+
const shipped = hard !== null && hard > 0 && hard < 1e7 ? hard : null;
|
|
345
|
+
const cap = spec.quota > 0 ? spec.quota : shipped;
|
|
346
|
+
|
|
347
|
+
if (cap === null && used === null) return fail('empty');
|
|
348
|
+
// 额度已知但已用读不到(字段缺失/非数字/接口改版):不能把已用当 0,
|
|
349
|
+
// 那样卡片会显示满额度,看起来像"余额自己涨回去了"。宁可报空,保留上一次读数。
|
|
350
|
+
if (cap !== null && used === null) return fail('empty');
|
|
351
|
+
const balance = { isAvailable: true, total: null, currency: spec.currency };
|
|
352
|
+
if (cap !== null) {
|
|
353
|
+
balance.total = round2(cap - used);
|
|
354
|
+
} else {
|
|
355
|
+
balance.total = used;
|
|
356
|
+
// 「已用」不是余额:币种位写成 USED,卡片会显示 "USED 17.17" 而不是 "¥ 17.17"。
|
|
357
|
+
balance.currency = 'USED';
|
|
358
|
+
}
|
|
359
|
+
const windows = [];
|
|
360
|
+
if (used !== null && cap !== null && cap > 0) {
|
|
361
|
+
windows.push({
|
|
362
|
+
key: 'cycle',
|
|
363
|
+
percent: Math.max(0, Math.min(100, (used / cap) * 100)),
|
|
364
|
+
resetsAt: null,
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
return okBalance(balance, windows.length === 0 ? null : { windows });
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** 通用 JSON:按用户给的点路径取值。 */
|
|
371
|
+
function parseJsonPreset(spec, main, usageBody) {
|
|
372
|
+
const availableRaw = spec.availablePath === '' ? undefined : readPath(main, spec.availablePath);
|
|
373
|
+
if (availableRaw === false) return fail('unavailable');
|
|
374
|
+
// 订阅到期时间(ISO 字符串或秒/毫秒时间戳都接受),仅当配置了 expiresPath。
|
|
375
|
+
let expiresAt = null;
|
|
376
|
+
if (typeof spec.expiresPath === "string" && spec.expiresPath !== "") {
|
|
377
|
+
const raw = readPath(main, spec.expiresPath);
|
|
378
|
+
if (typeof raw === "string" && raw !== "") {
|
|
379
|
+
const t = Date.parse(raw);
|
|
380
|
+
if (Number.isFinite(t)) expiresAt = t;
|
|
381
|
+
} else if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
382
|
+
expiresAt = raw > 1e12 ? raw : raw * 1000;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const totalRaw = spec.totalPath === '' ? undefined : readPath(main, spec.totalPath);
|
|
386
|
+
const usedSource = spec.usedPath === '' ? undefined : readPath(usageBody ?? main, spec.usedPath);
|
|
387
|
+
const totalNum = totalRaw === undefined ? null : num(totalRaw);
|
|
388
|
+
const usedNum = usedSource === undefined ? null : num(usedSource);
|
|
389
|
+
if (totalRaw !== undefined && totalNum === null) return fail('shape');
|
|
390
|
+
if (usedSource !== undefined && usedNum === null) return fail('shape');
|
|
391
|
+
if (totalNum === null && usedNum === null) return fail(spec.totalPath === '' ? 'shape' : 'empty');
|
|
392
|
+
|
|
393
|
+
const balance = { isAvailable: availableRaw === true ? true : null, total: null, currency: spec.currency };
|
|
394
|
+
if (totalNum !== null && usedNum !== null) {
|
|
395
|
+
// 给了"额度 + 已用"两段(例如订阅卡:weekly_limit_usd / weekly_usage_usd)时,
|
|
396
|
+
// totalPath 表示**额度**而不是剩余,这里算成剩余额度,百分比另由 windows 给出。
|
|
397
|
+
balance.total = round2((totalNum - usedNum) * spec.scale);
|
|
398
|
+
} else if (totalNum !== null) {
|
|
399
|
+
balance.total = round2(totalNum * spec.scale);
|
|
400
|
+
} else {
|
|
401
|
+
balance.total = round2(usedNum * spec.scale);
|
|
402
|
+
balance.currency = 'USED';
|
|
403
|
+
}
|
|
404
|
+
const windows = [];
|
|
405
|
+
if (totalNum !== null && usedNum !== null && totalNum > 0) {
|
|
406
|
+
windows.push({ key: 'cycle', percent: Math.max(0, Math.min(100, (usedNum / totalNum) * 100)), resetsAt: null });
|
|
407
|
+
}
|
|
408
|
+
return okBalance(balance, windows.length === 0 ? null : { windows }, expiresAt);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* 解析自定义 provider 的响应体。
|
|
413
|
+
*
|
|
414
|
+
* @param entry 归一后的自定义 entry(含 `custom` 规格)
|
|
415
|
+
* @param payloads 按 customTargets 的 key 收集到的 JSON 体:{ main, usage? }
|
|
416
|
+
*/
|
|
417
|
+
export function parseCustomPayload(entry, payloads) {
|
|
418
|
+
const spec = entry?.custom;
|
|
419
|
+
if (spec === undefined || spec === null) return fail('shape');
|
|
420
|
+
const main = payloads?.main;
|
|
421
|
+
const usageBody = payloads?.usage;
|
|
422
|
+
if (spec.preset === 'deepseek-balance') return parseDeepseekShape(spec, main);
|
|
423
|
+
if (spec.preset === 'openai-billing' || spec.preset === 'newapi') {
|
|
424
|
+
return parseBilling(spec, main, usageBody);
|
|
425
|
+
}
|
|
426
|
+
return parseJsonPreset(spec, main, usageBody);
|
|
427
|
+
}
|