@pinkbanana/dsh-balance 0.3.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/lib/index.js ADDED
@@ -0,0 +1,327 @@
1
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
2
+ import z from "@deepseek-ai/schemastery";
3
+ //#region src/balance.ts
4
+ const DECIMAL = /^-?\d+(?:\.\d+)?$/;
5
+ /** A safe, classified failure suitable for translation at the Host boundary. */
6
+ var BalanceQueryError = class extends Error {
7
+ code;
8
+ httpStatus;
9
+ constructor(code, message, httpStatus, options) {
10
+ super(message, options);
11
+ this.code = code;
12
+ this.httpStatus = httpStatus;
13
+ this.name = "BalanceQueryError";
14
+ }
15
+ };
16
+ function isRecord$1(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ function decimalField(row, key) {
20
+ const value = row[key];
21
+ if (typeof value !== "string" || !DECIMAL.test(value)) throw new BalanceQueryError("INVALID_RESPONSE", `DeepSeek balance response has an invalid ${key}`, 502);
22
+ return value;
23
+ }
24
+ /** Parse the documented DeepSeek payload and reject incomplete or surprising wire values. */
25
+ function parseDeepSeekBalance(value) {
26
+ if (!isRecord$1(value) || typeof value.is_available !== "boolean" || !Array.isArray(value.balance_infos)) throw new BalanceQueryError("INVALID_RESPONSE", "DeepSeek returned an invalid balance response", 502);
27
+ const balanceInfos = value.balance_infos.map((item) => {
28
+ if (!isRecord$1(item) || typeof item.currency !== "string" || item.currency.length === 0) throw new BalanceQueryError("INVALID_RESPONSE", "DeepSeek returned an invalid balance currency row", 502);
29
+ return {
30
+ currency: item.currency,
31
+ totalBalance: decimalField(item, "total_balance"),
32
+ grantedBalance: decimalField(item, "granted_balance"),
33
+ toppedUpBalance: decimalField(item, "topped_up_balance")
34
+ };
35
+ });
36
+ return {
37
+ isAvailable: value.is_available,
38
+ balanceInfos
39
+ };
40
+ }
41
+ function balanceEndpoint(baseUrl) {
42
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
43
+ return new URL("user/balance", normalized);
44
+ }
45
+ function upstreamFailure$1(status) {
46
+ if (status === 401 || status === 403) return new BalanceQueryError("INVALID_API_KEY", "DeepSeek API 密钥无效或无权查询余额", 401);
47
+ if (status === 429) return new BalanceQueryError("RATE_LIMITED", "DeepSeek API 请求过于频繁,请稍后重试", 429);
48
+ if (status >= 500) return new BalanceQueryError("UPSTREAM_UNAVAILABLE", "DeepSeek API 暂时不可用,请稍后重试", 502);
49
+ return new BalanceQueryError("UPSTREAM_ERROR", `DeepSeek API 返回了 HTTP ${status}`, 502);
50
+ }
51
+ /** Query the official endpoint with Bearer authentication and strict response validation. */
52
+ async function queryDeepSeekBalance(options) {
53
+ const fetchImpl = options.fetchImpl ?? fetch;
54
+ let response;
55
+ try {
56
+ response = await fetchImpl(balanceEndpoint(options.baseUrl), {
57
+ method: "GET",
58
+ headers: {
59
+ accept: "application/json",
60
+ authorization: `Bearer ${options.apiKey}`
61
+ },
62
+ signal: AbortSignal.timeout(options.timeoutMs)
63
+ });
64
+ } catch (error) {
65
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new BalanceQueryError("UPSTREAM_TIMEOUT", "查询 DeepSeek 余额超时", 504, { cause: error });
66
+ throw new BalanceQueryError("UPSTREAM_UNAVAILABLE", "无法连接到 DeepSeek API", 502, { cause: error });
67
+ }
68
+ if (!response.ok) throw upstreamFailure$1(response.status);
69
+ let payload;
70
+ try {
71
+ payload = await response.json();
72
+ } catch (error) {
73
+ throw new BalanceQueryError("INVALID_RESPONSE", "DeepSeek 返回了无法解析的余额响应", 502, { cause: error });
74
+ }
75
+ return parseDeepSeekBalance(payload);
76
+ }
77
+ //#endregion
78
+ //#region src/models.ts
79
+ /** A safe, classified model-list failure suitable for the Host boundary. */
80
+ var ModelQueryError = class extends Error {
81
+ code;
82
+ httpStatus;
83
+ constructor(code, message, httpStatus, options) {
84
+ super(message, options);
85
+ this.code = code;
86
+ this.httpStatus = httpStatus;
87
+ this.name = "ModelQueryError";
88
+ }
89
+ };
90
+ function isRecord(value) {
91
+ return typeof value === "object" && value !== null && !Array.isArray(value);
92
+ }
93
+ function requiredString(row, key) {
94
+ const value = row[key];
95
+ if (typeof value !== "string" || value.trim().length === 0) throw new ModelQueryError("INVALID_RESPONSE", `DeepSeek model response has an invalid ${key}`, 502);
96
+ return value;
97
+ }
98
+ /** Parse the documented `{ object: "list", data: Model[] }` response. */
99
+ function parseDeepSeekModels(value) {
100
+ if (!isRecord(value) || value.object !== "list" || !Array.isArray(value.data)) throw new ModelQueryError("INVALID_RESPONSE", "DeepSeek 返回了无效的模型列表", 502);
101
+ return { models: value.data.map((item) => {
102
+ if (!isRecord(item) || item.object !== "model") throw new ModelQueryError("INVALID_RESPONSE", "DeepSeek 返回了无效的模型条目", 502);
103
+ return {
104
+ id: requiredString(item, "id"),
105
+ ownedBy: requiredString(item, "owned_by")
106
+ };
107
+ }) };
108
+ }
109
+ function modelsEndpoint(baseUrl) {
110
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
111
+ return new URL("models", normalized);
112
+ }
113
+ function upstreamFailure(status) {
114
+ if (status === 401 || status === 403) return new ModelQueryError("INVALID_API_KEY", "DeepSeek API 密钥无效或无权查询模型", 401);
115
+ if (status === 429) return new ModelQueryError("RATE_LIMITED", "DeepSeek API 请求过于频繁,请稍后重试", 429);
116
+ if (status >= 500) return new ModelQueryError("UPSTREAM_UNAVAILABLE", "DeepSeek API 暂时不可用,请稍后重试", 502);
117
+ return new ModelQueryError("UPSTREAM_ERROR", `DeepSeek API 返回了 HTTP ${status}`, 502);
118
+ }
119
+ /** Query the official `/models` endpoint with Bearer authentication and strict validation. */
120
+ async function queryDeepSeekModels(options) {
121
+ const fetchImpl = options.fetchImpl ?? fetch;
122
+ let response;
123
+ try {
124
+ response = await fetchImpl(modelsEndpoint(options.baseUrl), {
125
+ method: "GET",
126
+ headers: {
127
+ accept: "application/json",
128
+ authorization: `Bearer ${options.apiKey}`
129
+ },
130
+ signal: AbortSignal.timeout(options.timeoutMs)
131
+ });
132
+ } catch (error) {
133
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new ModelQueryError("UPSTREAM_TIMEOUT", "查询 DeepSeek 模型列表超时", 504, { cause: error });
134
+ throw new ModelQueryError("UPSTREAM_UNAVAILABLE", "无法连接到 DeepSeek API", 502, { cause: error });
135
+ }
136
+ if (!response.ok) throw upstreamFailure(response.status);
137
+ let payload;
138
+ try {
139
+ payload = await response.json();
140
+ } catch (error) {
141
+ throw new ModelQueryError("INVALID_RESPONSE", "DeepSeek 返回了无法解析的模型列表", 502, { cause: error });
142
+ }
143
+ return parseDeepSeekModels(payload);
144
+ }
145
+ //#endregion
146
+ //#region src/types.ts
147
+ /** The same-origin endpoint exposed by the plugin's Host half. */
148
+ const BALANCE_ROUTE = "/dsh-balance/api/balance";
149
+ /** The same-origin endpoint that proxies DeepSeek's `/models` API. */
150
+ const MODELS_ROUTE = "/dsh-balance/api/models";
151
+ //#endregion
152
+ //#region src/index.ts
153
+ const name = "dsh-balance";
154
+ const inject = ["webServer", "credentials"];
155
+ const Config = z.object({
156
+ apiKeyRef: z.string().role("credential-ref").default("DEEPSEEK_API_KEY"),
157
+ baseUrl: z.string().default("https://api.deepseek.com"),
158
+ timeoutMs: z.number().step(1).min(1).max(6e4).default(1e4),
159
+ cacheMs: z.number().step(1).min(0).max(3e5).default(3e4),
160
+ allowRemote: z.boolean().default(false)
161
+ });
162
+ function validateBaseUrl(value) {
163
+ const url = new URL(value);
164
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1";
165
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) throw new Error("dsh-balance: baseUrl must use HTTPS (HTTP is accepted only for a loopback test server)");
166
+ }
167
+ function isLoopbackRequest(req) {
168
+ const host = req.headers.host;
169
+ if (host === void 0) return false;
170
+ try {
171
+ const hostname = new URL(`http://${host}`).hostname;
172
+ return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]";
173
+ } catch {
174
+ return false;
175
+ }
176
+ }
177
+ function sendJson(res, status, body) {
178
+ res.writeHead(status, {
179
+ "cache-control": "no-store",
180
+ "content-type": "application/json; charset=utf-8",
181
+ "x-content-type-options": "nosniff"
182
+ });
183
+ res.end(JSON.stringify(body));
184
+ }
185
+ /** Register the Host route that keeps credentials and upstream access out of the browser. */
186
+ function apply(ctx, config) {
187
+ validateBaseUrl(config.baseUrl);
188
+ const ref = credentialRef(config.apiKeyRef);
189
+ let cached;
190
+ let cachedModels;
191
+ const handler = async (req, res) => {
192
+ if (req.method !== "GET") {
193
+ res.setHeader("allow", "GET");
194
+ sendJson(res, 405, {
195
+ ok: false,
196
+ code: "METHOD_NOT_ALLOWED",
197
+ message: "仅支持 GET 请求"
198
+ });
199
+ return;
200
+ }
201
+ if (!config.allowRemote && !isLoopbackRequest(req)) {
202
+ sendJson(res, 403, {
203
+ ok: false,
204
+ code: "FORBIDDEN",
205
+ message: "余额查询仅允许从本机访问"
206
+ });
207
+ return;
208
+ }
209
+ if (!(new URL(req.url ?? "/dsh-balance/api/balance", "http://localhost").searchParams.get("refresh") === "1") && cached !== void 0 && cached.expiresAt > Date.now()) {
210
+ sendJson(res, 200, {
211
+ ...cached.value,
212
+ source: "cache"
213
+ });
214
+ return;
215
+ }
216
+ const credential = await ctx.credentials.resolve(ref);
217
+ if (credential === void 0) {
218
+ sendJson(res, 401, {
219
+ ok: false,
220
+ code: "MISSING_API_KEY",
221
+ message: `未配置 ${config.apiKeyRef},请先在“模型”设置中保存 DeepSeek API 密钥`
222
+ });
223
+ return;
224
+ }
225
+ try {
226
+ const result = await queryDeepSeekBalance({
227
+ apiKey: credential.value,
228
+ baseUrl: config.baseUrl,
229
+ timeoutMs: config.timeoutMs
230
+ });
231
+ const value = {
232
+ ok: true,
233
+ isAvailable: result.isAvailable,
234
+ balanceInfos: result.balanceInfos,
235
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
236
+ source: "live"
237
+ };
238
+ cached = {
239
+ expiresAt: Date.now() + config.cacheMs,
240
+ value
241
+ };
242
+ sendJson(res, 200, value);
243
+ } catch (error) {
244
+ const failure = error instanceof BalanceQueryError ? error : new BalanceQueryError("UPSTREAM_ERROR", "查询余额时发生未知错误", 502, { cause: error });
245
+ ctx.logger.warn(failure);
246
+ sendJson(res, failure.httpStatus, {
247
+ ok: false,
248
+ code: failure.code,
249
+ message: failure.message
250
+ });
251
+ }
252
+ };
253
+ const modelsHandler = async (req, res) => {
254
+ if (req.method !== "GET") {
255
+ res.setHeader("allow", "GET");
256
+ sendJson(res, 405, {
257
+ ok: false,
258
+ code: "METHOD_NOT_ALLOWED",
259
+ message: "仅支持 GET 请求"
260
+ });
261
+ return;
262
+ }
263
+ if (!config.allowRemote && !isLoopbackRequest(req)) {
264
+ sendJson(res, 403, {
265
+ ok: false,
266
+ code: "FORBIDDEN",
267
+ message: "模型查询仅允许从本机访问"
268
+ });
269
+ return;
270
+ }
271
+ if (!(new URL(req.url ?? "/dsh-balance/api/models", "http://localhost").searchParams.get("refresh") === "1") && cachedModels !== void 0 && cachedModels.expiresAt > Date.now()) {
272
+ sendJson(res, 200, {
273
+ ...cachedModels.value,
274
+ source: "cache"
275
+ });
276
+ return;
277
+ }
278
+ const credential = await ctx.credentials.resolve(ref);
279
+ if (credential === void 0) {
280
+ sendJson(res, 401, {
281
+ ok: false,
282
+ code: "MISSING_API_KEY",
283
+ message: `未配置 ${config.apiKeyRef},请先在“模型”设置中保存 DeepSeek API 密钥`
284
+ });
285
+ return;
286
+ }
287
+ try {
288
+ const value = {
289
+ ok: true,
290
+ models: (await queryDeepSeekModels({
291
+ apiKey: credential.value,
292
+ baseUrl: config.baseUrl,
293
+ timeoutMs: config.timeoutMs
294
+ })).models,
295
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
296
+ source: "live"
297
+ };
298
+ cachedModels = {
299
+ expiresAt: Date.now() + config.cacheMs,
300
+ value
301
+ };
302
+ sendJson(res, 200, value);
303
+ } catch (error) {
304
+ const failure = error instanceof ModelQueryError ? error : new ModelQueryError("UPSTREAM_ERROR", "查询模型时发生未知错误", 502, { cause: error });
305
+ ctx.logger.warn(failure);
306
+ sendJson(res, failure.httpStatus, {
307
+ ok: false,
308
+ code: failure.code,
309
+ message: failure.message
310
+ });
311
+ }
312
+ };
313
+ ctx.effect(() => ctx.webServer.register({
314
+ kind: "exact",
315
+ path: BALANCE_ROUTE,
316
+ handler
317
+ }), `dsh-balance: ${BALANCE_ROUTE}`);
318
+ ctx.effect(() => ctx.webServer.register({
319
+ kind: "exact",
320
+ path: MODELS_ROUTE,
321
+ handler: modelsHandler
322
+ }), `dsh-balance: ${MODELS_ROUTE}`);
323
+ }
324
+ //#endregion
325
+ export { BalanceQueryError, Config, ModelQueryError, apply, inject, name, parseDeepSeekBalance, parseDeepSeekModels, queryDeepSeekBalance, queryDeepSeekModels };
326
+
327
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["isRecord","upstreamFailure"],"sources":["../src/balance.ts","../src/models.ts","../src/types.ts","../src/index.ts"],"sourcesContent":["import type { BalanceErrorCode, BalanceInfo } from './types.ts'\n\nconst DECIMAL = /^-?\\d+(?:\\.\\d+)?$/\n\ninterface DeepSeekBalancePayload {\n isAvailable: boolean\n balanceInfos: BalanceInfo[]\n}\n\n/** A safe, classified failure suitable for translation at the Host boundary. */\nexport class BalanceQueryError extends Error {\n constructor(\n readonly code: BalanceErrorCode,\n message: string,\n readonly httpStatus: number,\n options?: ErrorOptions,\n ) {\n super(message, options)\n this.name = 'BalanceQueryError'\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction decimalField(row: Record<string, unknown>, key: string): string {\n const value = row[key]\n if (typeof value !== 'string' || !DECIMAL.test(value)) {\n throw new BalanceQueryError('INVALID_RESPONSE', `DeepSeek balance response has an invalid ${key}`, 502)\n }\n return value\n}\n\n/** Parse the documented DeepSeek payload and reject incomplete or surprising wire values. */\nexport function parseDeepSeekBalance(value: unknown): DeepSeekBalancePayload {\n if (!isRecord(value) || typeof value.is_available !== 'boolean' || !Array.isArray(value.balance_infos)) {\n throw new BalanceQueryError('INVALID_RESPONSE', 'DeepSeek returned an invalid balance response', 502)\n }\n\n const balanceInfos = value.balance_infos.map((item): BalanceInfo => {\n if (!isRecord(item) || typeof item.currency !== 'string' || item.currency.length === 0) {\n throw new BalanceQueryError('INVALID_RESPONSE', 'DeepSeek returned an invalid balance currency row', 502)\n }\n return {\n currency: item.currency,\n totalBalance: decimalField(item, 'total_balance'),\n grantedBalance: decimalField(item, 'granted_balance'),\n toppedUpBalance: decimalField(item, 'topped_up_balance'),\n }\n })\n\n return { isAvailable: value.is_available, balanceInfos }\n}\n\nfunction balanceEndpoint(baseUrl: string): URL {\n const normalized = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`\n return new URL('user/balance', normalized)\n}\n\nfunction upstreamFailure(status: number): BalanceQueryError {\n if (status === 401 || status === 403) {\n return new BalanceQueryError('INVALID_API_KEY', 'DeepSeek API 密钥无效或无权查询余额', 401)\n }\n if (status === 429) {\n return new BalanceQueryError('RATE_LIMITED', 'DeepSeek API 请求过于频繁,请稍后重试', 429)\n }\n if (status >= 500) {\n return new BalanceQueryError('UPSTREAM_UNAVAILABLE', 'DeepSeek API 暂时不可用,请稍后重试', 502)\n }\n return new BalanceQueryError('UPSTREAM_ERROR', `DeepSeek API 返回了 HTTP ${status}`, 502)\n}\n\nexport interface QueryBalanceOptions {\n apiKey: string\n baseUrl: string\n timeoutMs: number\n fetchImpl?: typeof fetch\n}\n\n/** Query the official endpoint with Bearer authentication and strict response validation. */\nexport async function queryDeepSeekBalance(options: QueryBalanceOptions): Promise<DeepSeekBalancePayload> {\n const fetchImpl = options.fetchImpl ?? fetch\n let response: Response\n try {\n response = await fetchImpl(balanceEndpoint(options.baseUrl), {\n method: 'GET',\n headers: {\n accept: 'application/json',\n authorization: `Bearer ${options.apiKey}`,\n },\n signal: AbortSignal.timeout(options.timeoutMs),\n })\n } catch (error) {\n if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n throw new BalanceQueryError('UPSTREAM_TIMEOUT', '查询 DeepSeek 余额超时', 504, { cause: error })\n }\n throw new BalanceQueryError('UPSTREAM_UNAVAILABLE', '无法连接到 DeepSeek API', 502, { cause: error })\n }\n\n if (!response.ok) throw upstreamFailure(response.status)\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch (error) {\n throw new BalanceQueryError('INVALID_RESPONSE', 'DeepSeek 返回了无法解析的余额响应', 502, { cause: error })\n }\n return parseDeepSeekBalance(payload)\n}\n","import type { DeepSeekApiErrorCode, ModelInfo } from './types.ts'\n\ninterface DeepSeekModelsPayload {\n models: ModelInfo[]\n}\n\n/** A safe, classified model-list failure suitable for the Host boundary. */\nexport class ModelQueryError extends Error {\n constructor(\n readonly code: DeepSeekApiErrorCode,\n message: string,\n readonly httpStatus: number,\n options?: ErrorOptions,\n ) {\n super(message, options)\n this.name = 'ModelQueryError'\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction requiredString(row: Record<string, unknown>, key: string): string {\n const value = row[key]\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ModelQueryError('INVALID_RESPONSE', `DeepSeek model response has an invalid ${key}`, 502)\n }\n return value\n}\n\n/** Parse the documented `{ object: \"list\", data: Model[] }` response. */\nexport function parseDeepSeekModels(value: unknown): DeepSeekModelsPayload {\n if (!isRecord(value) || value.object !== 'list' || !Array.isArray(value.data)) {\n throw new ModelQueryError('INVALID_RESPONSE', 'DeepSeek 返回了无效的模型列表', 502)\n }\n\n const models = value.data.map((item): ModelInfo => {\n if (!isRecord(item) || item.object !== 'model') {\n throw new ModelQueryError('INVALID_RESPONSE', 'DeepSeek 返回了无效的模型条目', 502)\n }\n return {\n id: requiredString(item, 'id'),\n ownedBy: requiredString(item, 'owned_by'),\n }\n })\n\n return { models }\n}\n\nfunction modelsEndpoint(baseUrl: string): URL {\n const normalized = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`\n return new URL('models', normalized)\n}\n\nfunction upstreamFailure(status: number): ModelQueryError {\n if (status === 401 || status === 403) {\n return new ModelQueryError('INVALID_API_KEY', 'DeepSeek API 密钥无效或无权查询模型', 401)\n }\n if (status === 429) {\n return new ModelQueryError('RATE_LIMITED', 'DeepSeek API 请求过于频繁,请稍后重试', 429)\n }\n if (status >= 500) {\n return new ModelQueryError('UPSTREAM_UNAVAILABLE', 'DeepSeek API 暂时不可用,请稍后重试', 502)\n }\n return new ModelQueryError('UPSTREAM_ERROR', `DeepSeek API 返回了 HTTP ${status}`, 502)\n}\n\nexport interface QueryModelsOptions {\n apiKey: string\n baseUrl: string\n timeoutMs: number\n fetchImpl?: typeof fetch\n}\n\n/** Query the official `/models` endpoint with Bearer authentication and strict validation. */\nexport async function queryDeepSeekModels(options: QueryModelsOptions): Promise<DeepSeekModelsPayload> {\n const fetchImpl = options.fetchImpl ?? fetch\n let response: Response\n try {\n response = await fetchImpl(modelsEndpoint(options.baseUrl), {\n method: 'GET',\n headers: {\n accept: 'application/json',\n authorization: `Bearer ${options.apiKey}`,\n },\n signal: AbortSignal.timeout(options.timeoutMs),\n })\n } catch (error) {\n if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n throw new ModelQueryError('UPSTREAM_TIMEOUT', '查询 DeepSeek 模型列表超时', 504, { cause: error })\n }\n throw new ModelQueryError('UPSTREAM_UNAVAILABLE', '无法连接到 DeepSeek API', 502, { cause: error })\n }\n\n if (!response.ok) throw upstreamFailure(response.status)\n\n let payload: unknown\n try {\n payload = await response.json()\n } catch (error) {\n throw new ModelQueryError('INVALID_RESPONSE', 'DeepSeek 返回了无法解析的模型列表', 502, { cause: error })\n }\n return parseDeepSeekModels(payload)\n}\n","/** The same-origin endpoint exposed by the plugin's Host half. */\nexport const BALANCE_ROUTE = '/dsh-balance/api/balance'\n\n/** The same-origin endpoint that proxies DeepSeek's `/models` API. */\nexport const MODELS_ROUTE = '/dsh-balance/api/models'\n\n/** One currency row returned by DeepSeek's `/user/balance` API. */\nexport interface BalanceInfo {\n currency: string\n totalBalance: string\n grantedBalance: string\n toppedUpBalance: string\n}\n\n/** A successful, browser-safe balance response. */\nexport interface BalanceSuccess {\n ok: true\n isAvailable: boolean\n balanceInfos: BalanceInfo[]\n fetchedAt: string\n source: 'live' | 'cache'\n}\n\nexport type DeepSeekApiErrorCode =\n | 'FORBIDDEN'\n | 'INVALID_API_KEY'\n | 'INVALID_RESPONSE'\n | 'METHOD_NOT_ALLOWED'\n | 'MISSING_API_KEY'\n | 'RATE_LIMITED'\n | 'UPSTREAM_ERROR'\n | 'UPSTREAM_TIMEOUT'\n | 'UPSTREAM_UNAVAILABLE'\n\n/** @deprecated Prefer the feature-neutral `DeepSeekApiErrorCode`. */\nexport type BalanceErrorCode = DeepSeekApiErrorCode\n\n/** A failed, browser-safe response. It intentionally contains no upstream body or credential. */\nexport interface BalanceFailure {\n ok: false\n code: DeepSeekApiErrorCode\n message: string\n}\n\nexport type BalanceApiResponse = BalanceSuccess | BalanceFailure\n\n/** One model returned by DeepSeek's `/models` API. */\nexport interface ModelInfo {\n id: string\n ownedBy: string\n}\n\n/** A successful, browser-safe model-list response. */\nexport interface ModelsSuccess {\n ok: true\n models: ModelInfo[]\n fetchedAt: string\n source: 'live' | 'cache'\n}\n\nexport type ModelsFailure = BalanceFailure\nexport type ModelsApiResponse = ModelsSuccess | ModelsFailure\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { credentialRef } from '@deepseek-ai/dsh-credentials'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport z from '@deepseek-ai/schemastery'\nimport { BalanceQueryError, queryDeepSeekBalance } from './balance.ts'\nimport { ModelQueryError, queryDeepSeekModels } from './models.ts'\nimport { BALANCE_ROUTE, MODELS_ROUTE } from './types.ts'\nimport type { BalanceApiResponse, BalanceSuccess, ModelsApiResponse, ModelsSuccess } from './types.ts'\n\nexport const name = 'dsh-balance'\nexport const inject = ['webServer', 'credentials']\n\nexport interface Config {\n apiKeyRef: string\n baseUrl: string\n timeoutMs: number\n cacheMs: number\n allowRemote: boolean\n}\n\nexport const Config: z<Config> = z.object({\n apiKeyRef: z.string().role('credential-ref').default('DEEPSEEK_API_KEY'),\n baseUrl: z.string().default('https://api.deepseek.com'),\n timeoutMs: z.number().step(1).min(1).max(60_000).default(10_000),\n cacheMs: z.number().step(1).min(0).max(300_000).default(30_000),\n allowRemote: z.boolean().default(false),\n})\n\nfunction validateBaseUrl(value: string): void {\n const url = new URL(value)\n const loopback = url.hostname === '127.0.0.1' || url.hostname === 'localhost' || url.hostname === '::1'\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {\n throw new Error('dsh-balance: baseUrl must use HTTPS (HTTP is accepted only for a loopback test server)')\n }\n}\n\nfunction isLoopbackRequest(req: IncomingMessage): boolean {\n const host = req.headers.host\n if (host === undefined) return false\n try {\n const hostname = new URL(`http://${host}`).hostname\n return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]'\n } catch {\n return false\n }\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: BalanceApiResponse | ModelsApiResponse): void {\n res.writeHead(status, {\n 'cache-control': 'no-store',\n 'content-type': 'application/json; charset=utf-8',\n 'x-content-type-options': 'nosniff',\n })\n res.end(JSON.stringify(body))\n}\n\n/** Register the Host route that keeps credentials and upstream access out of the browser. */\nexport function apply(ctx: Context, config: Config): void {\n validateBaseUrl(config.baseUrl)\n const ref = credentialRef(config.apiKeyRef)\n let cached: { expiresAt: number; value: BalanceSuccess } | undefined\n let cachedModels: { expiresAt: number; value: ModelsSuccess } | undefined\n\n const handler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n if (req.method !== 'GET') {\n res.setHeader('allow', 'GET')\n sendJson(res, 405, { ok: false, code: 'METHOD_NOT_ALLOWED', message: '仅支持 GET 请求' })\n return\n }\n if (!config.allowRemote && !isLoopbackRequest(req)) {\n sendJson(res, 403, { ok: false, code: 'FORBIDDEN', message: '余额查询仅允许从本机访问' })\n return\n }\n\n const requestUrl = new URL(req.url ?? BALANCE_ROUTE, 'http://localhost')\n const forceRefresh = requestUrl.searchParams.get('refresh') === '1'\n if (!forceRefresh && cached !== undefined && cached.expiresAt > Date.now()) {\n sendJson(res, 200, { ...cached.value, source: 'cache' })\n return\n }\n\n const credential = await ctx.credentials.resolve(ref)\n if (credential === undefined) {\n sendJson(res, 401, {\n ok: false,\n code: 'MISSING_API_KEY',\n message: `未配置 ${config.apiKeyRef},请先在“模型”设置中保存 DeepSeek API 密钥`,\n })\n return\n }\n\n try {\n const result = await queryDeepSeekBalance({\n apiKey: credential.value,\n baseUrl: config.baseUrl,\n timeoutMs: config.timeoutMs,\n })\n const value: BalanceSuccess = {\n ok: true,\n isAvailable: result.isAvailable,\n balanceInfos: result.balanceInfos,\n fetchedAt: new Date().toISOString(),\n source: 'live',\n }\n cached = { expiresAt: Date.now() + config.cacheMs, value }\n sendJson(res, 200, value)\n } catch (error) {\n const failure = error instanceof BalanceQueryError\n ? error\n : new BalanceQueryError('UPSTREAM_ERROR', '查询余额时发生未知错误', 502, { cause: error })\n ctx.logger.warn(failure)\n sendJson(res, failure.httpStatus, { ok: false, code: failure.code, message: failure.message })\n }\n }\n\n const modelsHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n if (req.method !== 'GET') {\n res.setHeader('allow', 'GET')\n sendJson(res, 405, { ok: false, code: 'METHOD_NOT_ALLOWED', message: '仅支持 GET 请求' })\n return\n }\n if (!config.allowRemote && !isLoopbackRequest(req)) {\n sendJson(res, 403, { ok: false, code: 'FORBIDDEN', message: '模型查询仅允许从本机访问' })\n return\n }\n\n const requestUrl = new URL(req.url ?? MODELS_ROUTE, 'http://localhost')\n const forceRefresh = requestUrl.searchParams.get('refresh') === '1'\n if (!forceRefresh && cachedModels !== undefined && cachedModels.expiresAt > Date.now()) {\n sendJson(res, 200, { ...cachedModels.value, source: 'cache' })\n return\n }\n\n const credential = await ctx.credentials.resolve(ref)\n if (credential === undefined) {\n sendJson(res, 401, {\n ok: false,\n code: 'MISSING_API_KEY',\n message: `未配置 ${config.apiKeyRef},请先在“模型”设置中保存 DeepSeek API 密钥`,\n })\n return\n }\n\n try {\n const result = await queryDeepSeekModels({\n apiKey: credential.value,\n baseUrl: config.baseUrl,\n timeoutMs: config.timeoutMs,\n })\n const value: ModelsSuccess = {\n ok: true,\n models: result.models,\n fetchedAt: new Date().toISOString(),\n source: 'live',\n }\n cachedModels = { expiresAt: Date.now() + config.cacheMs, value }\n sendJson(res, 200, value)\n } catch (error) {\n const failure = error instanceof ModelQueryError\n ? error\n : new ModelQueryError('UPSTREAM_ERROR', '查询模型时发生未知错误', 502, { cause: error })\n ctx.logger.warn(failure)\n sendJson(res, failure.httpStatus, { ok: false, code: failure.code, message: failure.message })\n }\n }\n\n ctx.effect(\n () => ctx.webServer.register({ kind: 'exact', path: BALANCE_ROUTE, handler }),\n `dsh-balance: ${BALANCE_ROUTE}`,\n )\n ctx.effect(\n () => ctx.webServer.register({ kind: 'exact', path: MODELS_ROUTE, handler: modelsHandler }),\n `dsh-balance: ${MODELS_ROUTE}`,\n )\n}\n\nexport { BalanceQueryError, parseDeepSeekBalance, queryDeepSeekBalance } from './balance.ts'\nexport { ModelQueryError, parseDeepSeekModels, queryDeepSeekModels } from './models.ts'\nexport type {\n BalanceApiResponse,\n BalanceFailure,\n BalanceInfo,\n BalanceSuccess,\n ModelInfo,\n ModelsApiResponse,\n ModelsFailure,\n ModelsSuccess,\n} from './types.ts'\n"],"mappings":";;;AAEA,MAAM,UAAU;;AAQhB,IAAa,oBAAb,cAAuC,MAAM;CAEhC;CAEA;CAHX,YACE,MACA,SACA,YACA,SAC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KAAA,GAAW;GAC5B,SAAS,KAAK,KAAK;IACjB,IAAI;IACJ,MAAM;IACN,SAAS,OAAO,OAAO,UAAU;GACnC,CAAC;GACD;EACF;EAEA,IAAI;GAMF,MAAM,QAAuB;IAC3B,IAAI;IACJ,SAAQ,MAPW,oBAAoB;KACvC,QAAQ,WAAW;KACnB,SAAS,OAAO;KAChB,WAAW,OAAO;IACpB,CAAC,EAAA,CAGgB;IACf,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;IAClC,QAAQ;GACV;GACA,eAAe;IAAE,WAAW,KAAK,IAAI,IAAI,OAAO;IAAS;GAAM;GAC/D,SAAS,KAAK,KAAK,KAAK;EAC1B,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,kBAC7B,QACA,IAAI,gBAAgB,kBAAkB,eAAe,KAAK,EAAE,OAAO,MAAM,CAAC;GAC9E,IAAI,OAAO,KAAK,OAAO;GACvB,SAAS,KAAK,QAAQ,YAAY;IAAE,IAAI;IAAO,MAAM,QAAQ;IAAM,SAAS,QAAQ;GAAQ,CAAC;EAC/F;CACF;CAEA,IAAI,aACI,IAAI,UAAU,SAAS;EAAE,MAAM;EAAS,MAAM;EAAe;CAAQ,CAAC,GAC5E,gBAAgB,eAClB;CACA,IAAI,aACI,IAAI,UAAU,SAAS;EAAE,MAAM;EAAS,MAAM;EAAc,SAAS;CAAc,CAAC,GAC1F,gBAAgB,cAClB;AACF"}
@@ -0,0 +1,22 @@
1
+ import type { BalanceErrorCode, BalanceInfo } from './types.ts';
2
+ interface DeepSeekBalancePayload {
3
+ isAvailable: boolean;
4
+ balanceInfos: BalanceInfo[];
5
+ }
6
+ /** A safe, classified failure suitable for translation at the Host boundary. */
7
+ export declare class BalanceQueryError extends Error {
8
+ readonly code: BalanceErrorCode;
9
+ readonly httpStatus: number;
10
+ constructor(code: BalanceErrorCode, message: string, httpStatus: number, options?: ErrorOptions);
11
+ }
12
+ /** Parse the documented DeepSeek payload and reject incomplete or surprising wire values. */
13
+ export declare function parseDeepSeekBalance(value: unknown): DeepSeekBalancePayload;
14
+ export interface QueryBalanceOptions {
15
+ apiKey: string;
16
+ baseUrl: string;
17
+ timeoutMs: number;
18
+ fetchImpl?: typeof fetch;
19
+ }
20
+ /** Query the official endpoint with Bearer authentication and strict response validation. */
21
+ export declare function queryDeepSeekBalance(options: QueryBalanceOptions): Promise<DeepSeekBalancePayload>;
22
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
2
+ import type { BalanceApiResponse } from '../types.ts';
3
+ import type { LOCALE_NS } from './locales.ts';
4
+ export interface BalanceTabInjected {
5
+ loadBalance: (forceRefresh: boolean, signal: AbortSignal) => Promise<BalanceApiResponse>;
6
+ }
7
+ export type BalanceTabProps = PropsRuntime<'settings.plugins.tab'> & InjectFace<BalanceTabInjected> & PropsLocale<typeof LOCALE_NS>;
8
+ export declare function BalanceTab({ loadBalance, t }: BalanceTabProps): import("react").JSX.Element;
@@ -0,0 +1,8 @@
1
+ import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
2
+ import type { ModelsApiResponse } from '../types.ts';
3
+ import type { LOCALE_NS } from './locales.ts';
4
+ export interface ModelsTabInjected {
5
+ loadModels: (forceRefresh: boolean, signal: AbortSignal) => Promise<ModelsApiResponse>;
6
+ }
7
+ export type ModelsTabProps = PropsRuntime<'settings.plugins.tab'> & InjectFace<ModelsTabInjected> & PropsLocale<typeof LOCALE_NS>;
8
+ export declare function ModelsTab({ loadModels, t }: ModelsTabProps): import("react").JSX.Element;
@@ -0,0 +1,6 @@
1
+ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
2
+ export type { BalanceTabInjected, BalanceTabProps } from './BalanceTab.tsx';
3
+ export type { ModelsTabInjected, ModelsTabProps } from './ModelsTab.tsx';
4
+ export declare const inject: string[];
5
+ /** Register one feature-owned page inside the existing Plugins settings section. */
6
+ export declare function apply(ctx: ClientContext): void;
@@ -0,0 +1,47 @@
1
+ import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
2
+ import type { DeepSeekApiErrorCode } from '../types.ts';
3
+ export declare const LOCALE_NS = "dsh-balance";
4
+ /** Simplified Chinese dictionary and source of truth for the namespace key set. */
5
+ export declare const zh: {
6
+ readonly 'locale.tag': "zh-CN";
7
+ readonly 'tab.balance': "DeepSeek 余额";
8
+ readonly 'tab.models': "DeepSeek 模型";
9
+ readonly 'action.loading': "查询中…";
10
+ readonly 'balance.title': "DeepSeek API 余额";
11
+ readonly 'balance.copy': "余额由本机 Host 使用已保存的 API 密钥查询,密钥不会发送到浏览器。";
12
+ readonly 'balance.refresh': "刷新余额";
13
+ readonly 'balance.loading': "正在查询 DeepSeek 账户余额…";
14
+ readonly 'balance.available': "当前账户有可用余额";
15
+ readonly 'balance.unavailable': "当前账户没有可用余额";
16
+ readonly 'balance.empty': "DeepSeek 未返回任何币种余额。";
17
+ readonly 'balance.toppedUp': "充值余额";
18
+ readonly 'balance.granted': "赠送余额";
19
+ readonly 'models.title': "DeepSeek 可用模型";
20
+ readonly 'models.copy': "从 DeepSeek 官方 /models 接口读取当前 API Key 可访问的模型。";
21
+ readonly 'models.refresh': "刷新模型";
22
+ readonly 'models.loading': "正在查询 DeepSeek 模型列表…";
23
+ readonly 'models.count': "当前可用 {count} 个模型";
24
+ readonly 'models.empty': "DeepSeek 未返回任何可用模型。";
25
+ readonly 'models.owner': "由 {owner} 提供";
26
+ readonly 'meta.updated': "更新于 {time}";
27
+ readonly 'meta.cached': " · 缓存";
28
+ readonly 'error.FORBIDDEN': "此查询仅允许从本机访问";
29
+ readonly 'error.INVALID_API_KEY': "DeepSeek API 密钥无效或没有查询权限";
30
+ readonly 'error.INVALID_RESPONSE': "DeepSeek 返回了无法识别的响应";
31
+ readonly 'error.METHOD_NOT_ALLOWED': "请求方法不受支持";
32
+ readonly 'error.MISSING_API_KEY': "未配置 DeepSeek API 密钥,请先在“模型”设置中保存";
33
+ readonly 'error.RATE_LIMITED': "DeepSeek API 请求过于频繁,请稍后重试";
34
+ readonly 'error.UPSTREAM_ERROR': "DeepSeek API 返回了错误";
35
+ readonly 'error.UPSTREAM_TIMEOUT': "查询 DeepSeek API 超时";
36
+ readonly 'error.UPSTREAM_UNAVAILABLE': "无法连接到 DeepSeek API";
37
+ };
38
+ export type DshBalanceLocaleKey = keyof typeof zh;
39
+ declare module '@deepseek-ai/dsh-client-ui-slots' {
40
+ interface LocaleNamespaceMap {
41
+ /** Balance and model-list settings copy owned by this plugin. */
42
+ 'dsh-balance': DshBalanceLocaleKey;
43
+ }
44
+ }
45
+ /** English dictionary, checked complete against the Chinese key set. */
46
+ export declare const en: LocaleDictOf<typeof LOCALE_NS>;
47
+ export declare function errorLocaleKey(code: DeepSeekApiErrorCode): DshBalanceLocaleKey;
@@ -0,0 +1 @@
1
+ export declare const balanceStyles = "\n.dsh-balance-tab {\n display: flex;\n flex-direction: column;\n gap: 14px;\n max-width: 760px;\n color: var(--dsw-alias-label-primary);\n}\n.dsh-balance-summary {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n}\n.dsh-balance-heading { margin: 0; font-size: 18px; font-weight: 600; }\n.dsh-balance-copy { margin: 4px 0 0; color: var(--dsw-alias-label-tertiary); font-size: 13px; line-height: 1.5; }\n.dsh-balance-refresh {\n flex: none;\n appearance: none;\n border: 1px solid var(--dsw-alias-border-l2);\n border-radius: 8px;\n padding: 6px 13px;\n background: var(--dsw-alias-bg-layer-3);\n color: var(--dsw-alias-label-primary);\n font: inherit;\n font-size: 13px;\n cursor: pointer;\n}\n.dsh-balance-refresh:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-balance-refresh:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }\n.dsh-balance-refresh:disabled { cursor: default; opacity: .55; }\n.dsh-balance-status,\n.dsh-balance-error {\n margin: 0;\n border: 1px solid var(--dsw-alias-border-l2);\n border-radius: 12px;\n padding: 18px;\n background: var(--dsw-alias-bg-layer-3);\n color: var(--dsw-alias-label-secondary);\n font-size: 13px;\n line-height: 1.6;\n}\n.dsh-balance-error { color: var(--dsw-alias-state-error-primary); }\n.dsh-balance-availability { display: flex; align-items: center; gap: 8px; font-size: 13px; }\n.dsh-balance-dot { width: 8px; height: 8px; border-radius: 999px; background: var(--dsw-alias-state-error-primary); }\n.dsh-balance-availability[data-available='true'] .dsh-balance-dot { background: var(--dsw-alias-state-success-primary); }\n.dsh-balance-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; }\n.dsh-balance-card {\n border: 1px solid var(--dsw-alias-border-l2);\n border-radius: 12px;\n padding: 16px;\n background: var(--dsw-alias-bg-layer-3);\n}\n.dsh-balance-card-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }\n.dsh-balance-currency { color: var(--dsw-alias-label-tertiary); font-size: 12px; font-weight: 600; letter-spacing: .04em; }\n.dsh-balance-total { margin: 12px 0 16px; font-size: 28px; font-weight: 650; line-height: 1.15; }\n.dsh-balance-breakdown { display: grid; grid-template-columns: 1fr auto; gap: 7px 12px; margin: 0; font-size: 12px; }\n.dsh-balance-breakdown dt { color: var(--dsw-alias-label-tertiary); }\n.dsh-balance-breakdown dd { margin: 0; color: var(--dsw-alias-label-secondary); font-variant-numeric: tabular-nums; }\n.dsh-balance-meta { margin: 0; color: var(--dsw-alias-label-tertiary); font-size: 12px; }\n.dsh-models-tab {\n display: flex;\n flex-direction: column;\n gap: 14px;\n max-width: 760px;\n color: var(--dsw-alias-label-primary);\n}\n.dsh-model-count { display: flex; align-items: center; gap: 8px; font-size: 13px; }\n.dsh-model-count .dsh-balance-dot { background: var(--dsw-alias-state-success-primary); }\n.dsh-model-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px; }\n.dsh-model-card {\n display: flex;\n flex-direction: column;\n gap: 10px;\n border: 1px solid var(--dsw-alias-border-l2);\n border-radius: 12px;\n padding: 16px;\n background: var(--dsw-alias-bg-layer-3);\n}\n.dsh-model-id {\n color: var(--dsw-alias-label-primary);\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n font-size: 15px;\n font-weight: 600;\n overflow-wrap: anywhere;\n}\n.dsh-model-owner { color: var(--dsw-alias-label-tertiary); font-size: 12px; }\n";
@@ -0,0 +1,17 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import z from '@deepseek-ai/schemastery';
3
+ export declare const name = "dsh-balance";
4
+ export declare const inject: string[];
5
+ export interface Config {
6
+ apiKeyRef: string;
7
+ baseUrl: string;
8
+ timeoutMs: number;
9
+ cacheMs: number;
10
+ allowRemote: boolean;
11
+ }
12
+ export declare const Config: z<Config>;
13
+ /** Register the Host route that keeps credentials and upstream access out of the browser. */
14
+ export declare function apply(ctx: Context, config: Config): void;
15
+ export { BalanceQueryError, parseDeepSeekBalance, queryDeepSeekBalance } from './balance.ts';
16
+ export { ModelQueryError, parseDeepSeekModels, queryDeepSeekModels } from './models.ts';
17
+ export type { BalanceApiResponse, BalanceFailure, BalanceInfo, BalanceSuccess, ModelInfo, ModelsApiResponse, ModelsFailure, ModelsSuccess, } from './types.ts';
@@ -0,0 +1,21 @@
1
+ import type { DeepSeekApiErrorCode, ModelInfo } from './types.ts';
2
+ interface DeepSeekModelsPayload {
3
+ models: ModelInfo[];
4
+ }
5
+ /** A safe, classified model-list failure suitable for the Host boundary. */
6
+ export declare class ModelQueryError extends Error {
7
+ readonly code: DeepSeekApiErrorCode;
8
+ readonly httpStatus: number;
9
+ constructor(code: DeepSeekApiErrorCode, message: string, httpStatus: number, options?: ErrorOptions);
10
+ }
11
+ /** Parse the documented `{ object: "list", data: Model[] }` response. */
12
+ export declare function parseDeepSeekModels(value: unknown): DeepSeekModelsPayload;
13
+ export interface QueryModelsOptions {
14
+ apiKey: string;
15
+ baseUrl: string;
16
+ timeoutMs: number;
17
+ fetchImpl?: typeof fetch;
18
+ }
19
+ /** Query the official `/models` endpoint with Bearer authentication and strict validation. */
20
+ export declare function queryDeepSeekModels(options: QueryModelsOptions): Promise<DeepSeekModelsPayload>;
21
+ export {};
@@ -0,0 +1,43 @@
1
+ /** The same-origin endpoint exposed by the plugin's Host half. */
2
+ export declare const BALANCE_ROUTE = "/dsh-balance/api/balance";
3
+ /** The same-origin endpoint that proxies DeepSeek's `/models` API. */
4
+ export declare const MODELS_ROUTE = "/dsh-balance/api/models";
5
+ /** One currency row returned by DeepSeek's `/user/balance` API. */
6
+ export interface BalanceInfo {
7
+ currency: string;
8
+ totalBalance: string;
9
+ grantedBalance: string;
10
+ toppedUpBalance: string;
11
+ }
12
+ /** A successful, browser-safe balance response. */
13
+ export interface BalanceSuccess {
14
+ ok: true;
15
+ isAvailable: boolean;
16
+ balanceInfos: BalanceInfo[];
17
+ fetchedAt: string;
18
+ source: 'live' | 'cache';
19
+ }
20
+ export type DeepSeekApiErrorCode = 'FORBIDDEN' | 'INVALID_API_KEY' | 'INVALID_RESPONSE' | 'METHOD_NOT_ALLOWED' | 'MISSING_API_KEY' | 'RATE_LIMITED' | 'UPSTREAM_ERROR' | 'UPSTREAM_TIMEOUT' | 'UPSTREAM_UNAVAILABLE';
21
+ /** @deprecated Prefer the feature-neutral `DeepSeekApiErrorCode`. */
22
+ export type BalanceErrorCode = DeepSeekApiErrorCode;
23
+ /** A failed, browser-safe response. It intentionally contains no upstream body or credential. */
24
+ export interface BalanceFailure {
25
+ ok: false;
26
+ code: DeepSeekApiErrorCode;
27
+ message: string;
28
+ }
29
+ export type BalanceApiResponse = BalanceSuccess | BalanceFailure;
30
+ /** One model returned by DeepSeek's `/models` API. */
31
+ export interface ModelInfo {
32
+ id: string;
33
+ ownedBy: string;
34
+ }
35
+ /** A successful, browser-safe model-list response. */
36
+ export interface ModelsSuccess {
37
+ ok: true;
38
+ models: ModelInfo[];
39
+ fetchedAt: string;
40
+ source: 'live' | 'cache';
41
+ }
42
+ export type ModelsFailure = BalanceFailure;
43
+ export type ModelsApiResponse = ModelsSuccess | ModelsFailure;