@huaqiu/dsh-auth 0.6.21 → 0.6.22
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/client.js +43 -37
- package/lib/client.js.map +1 -1
- package/lib/index.d.mts +18 -10
- package/lib/index.mjs +141 -36
- package/package.json +2 -2
- package/src/client/client.ts +22 -8
- package/src/client/i18n.ts +4 -10
- package/src/client/lib.ts +20 -27
- package/src/client/transport.ts +41 -14
- package/src/client/ui/sidebar-action.tsx +15 -33
- package/src/host.ts +10 -6
- package/src/routes.ts +79 -59
- package/src/service.ts +32 -8
- package/src/subscription-balances.ts +122 -0
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
import { memo, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'
|
|
31
31
|
import { createPortal } from 'react-dom'
|
|
32
32
|
import { getAuth, getAuthState, getHqEdge, setProfile, subscribeAuth } from '../auth-state.js'
|
|
33
|
-
import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type
|
|
33
|
+
import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type AiUsage, type SubscriptionQuota } from '../lib.js'
|
|
34
34
|
import { useIsDark, useLocale } from '../ui-env.js'
|
|
35
35
|
import { useT, type Translate } from '../i18n.js'
|
|
36
36
|
import { HQ_ICON } from './hq-icon.jsx'
|
|
@@ -546,36 +546,19 @@ export function quotaReading(quota: SubscriptionQuota | null, t: Translate): Met
|
|
|
546
546
|
}
|
|
547
547
|
|
|
548
548
|
/**
|
|
549
|
-
* AI
|
|
549
|
+
* AI reading from the subscription-balances AI Points group.
|
|
550
550
|
*
|
|
551
|
-
* The
|
|
552
|
-
*
|
|
553
|
-
* `
|
|
554
|
-
*
|
|
555
|
-
* `usedPoints` here made the AI card the only surface in the product that
|
|
556
|
-
* reported consumption as the balance: an account that burned 77 of its 100
|
|
557
|
-
* points read "77 / 100 pts" where the user expects "23 / 100 pts".
|
|
558
|
-
*
|
|
559
|
-
* The balance is reported as `usedPoints` + `availablePoints`, so the total is
|
|
560
|
-
* their sum — there is no separate `totalPoints` field to read. Percent keeps
|
|
561
|
-
* one decimal: a fresh account has well over 99% of its balance left, and
|
|
562
|
-
* rounding 99.6% up to "100%" would read as an exhausted account.
|
|
551
|
+
* The percentage is the upstream `quotaRemainPercent` — the REMAINING share —
|
|
552
|
+
* passed through unchanged: no local ratio and no re-rounding, so `99.68`
|
|
553
|
+
* renders as `99.68%`. A missing / `null` / non-finite value is unavailable
|
|
554
|
+
* (the card shows「—」); the bar clamps to 0–100 while the label does not.
|
|
563
555
|
*/
|
|
564
|
-
export function aiUsageReading(usage:
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
const available = Math.max(0, usage.availablePoints)
|
|
568
|
-
const total = used + available
|
|
569
|
-
const percent = total > 0
|
|
570
|
-
? Math.min(100, Math.round((available / total) * 1000) / 10)
|
|
571
|
-
: 0
|
|
572
|
-
// Headline shows the usage percent (e.g. "65%"); the exact
|
|
573
|
-
// "{available} / {total} pts" balance is preserved as the hover title.
|
|
574
|
-
const displayPercent = Math.round(percent)
|
|
556
|
+
export function aiUsageReading(usage: AiUsage | null, t: Translate): MetricReading | null {
|
|
557
|
+
const percent = usage?.quotaRemainPercent
|
|
558
|
+
if (typeof percent !== 'number' || !Number.isFinite(percent)) return null
|
|
575
559
|
return {
|
|
576
|
-
value: t('subscription.aiUsagePercent', { percent
|
|
577
|
-
|
|
578
|
-
percent,
|
|
560
|
+
value: t('subscription.aiUsagePercent', { percent }),
|
|
561
|
+
percent: Math.max(0, Math.min(100, percent)),
|
|
579
562
|
ok: true,
|
|
580
563
|
}
|
|
581
564
|
}
|
|
@@ -739,7 +722,7 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
|
|
|
739
722
|
const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null)
|
|
740
723
|
const [avatarBroken, setAvatarBroken] = useState(false)
|
|
741
724
|
const [hovered, setHovered] = useState(false)
|
|
742
|
-
const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai:
|
|
725
|
+
const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai: AiUsage | null } | null>(null)
|
|
743
726
|
const [subscribing, setSubscribing] = useState(false)
|
|
744
727
|
const triggerRef = useRef<HTMLButtonElement | null>(null)
|
|
745
728
|
const menuRef = useRef<HTMLDivElement | null>(null)
|
|
@@ -796,10 +779,9 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
|
|
|
796
779
|
|
|
797
780
|
// Live quota: EVERY time the menu opens (and every time the auth state
|
|
798
781
|
// flips to authenticated) re-fetch the active subscription for GEN and ERC
|
|
799
|
-
//
|
|
800
|
-
//
|
|
801
|
-
//
|
|
802
|
-
// three staggered ones.
|
|
782
|
+
// from the environment's subscription API, and the AI percentage from the
|
|
783
|
+
// node-proxied subscription balances. All three share one loading window
|
|
784
|
+
// instead of three staggered ones.
|
|
803
785
|
useEffect(() => {
|
|
804
786
|
if (!menuOpen || !authenticated) {
|
|
805
787
|
if (!menuOpen) setQuota(null)
|
package/src/host.ts
CHANGED
|
@@ -46,11 +46,11 @@ export interface HuaqiuAuthConfig {
|
|
|
46
46
|
/** Seconds remote token-validation results are cached. Default 60. */
|
|
47
47
|
validationTtlSeconds?: number
|
|
48
48
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* instead of calling a stale/default endpoint.
|
|
49
|
+
* Subscription balances endpoint resolved by HQ Edge from `HQ_AI_ENV`
|
|
50
|
+
* (`GET /sub-api/subscriptions/balances/current`). Absent → `/ai-usage`
|
|
51
|
+
* returns null instead of calling a stale/default endpoint.
|
|
52
52
|
*/
|
|
53
|
-
|
|
53
|
+
subscriptionBalancesUrl?: string
|
|
54
54
|
/**
|
|
55
55
|
* Subscription landing-page origin resolved by HQ Edge from the SAME
|
|
56
56
|
* `HQ_AI_ENV`. Absent → the browser half keeps its standalone PROD default.
|
|
@@ -104,7 +104,11 @@ export function resolveHostConfig(
|
|
|
104
104
|
// Resolved AI endpoints: overlay config (what HQ Edge injects) wins; explicit
|
|
105
105
|
// env URLs are the standalone escape hatch. HQ_AI_ENV itself is NOT read here
|
|
106
106
|
// — the prod/test mapping lives only in HQ Edge's central config.
|
|
107
|
-
const
|
|
107
|
+
const subscriptionBalancesUrl = (
|
|
108
|
+
config?.subscriptionBalancesUrl
|
|
109
|
+
?? env.HQ_AI_SUBSCRIPTION_BALANCES_URL
|
|
110
|
+
?? ''
|
|
111
|
+
).trim()
|
|
108
112
|
const subscriptionOrigin = (config?.subscriptionOrigin ?? env.HQ_AI_SUBSCRIPTION_ORIGIN ?? '')
|
|
109
113
|
.trim()
|
|
110
114
|
.replace(/\/+$/, '')
|
|
@@ -115,7 +119,7 @@ export function resolveHostConfig(
|
|
|
115
119
|
hostLogoutPath,
|
|
116
120
|
hostSessionTtlSeconds: ttl,
|
|
117
121
|
validationTtlSeconds,
|
|
118
|
-
|
|
122
|
+
subscriptionBalancesUrl,
|
|
119
123
|
subscriptionOrigin,
|
|
120
124
|
}
|
|
121
125
|
}
|
package/src/routes.ts
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* POST /api/v1/huaqiu/auth/session body { token, userId, nickname?, expiresAt? } → cache set
|
|
6
6
|
* POST /api/v1/huaqiu/auth/logout → cache cleared
|
|
7
7
|
* GET /api/v1/huaqiu/auth/session → { authenticated, user }
|
|
8
|
-
* GET /api/v1/huaqiu/auth/config → { hostMode }
|
|
8
|
+
* GET /api/v1/huaqiu/auth/config → { hostMode, subscriptionOrigin, subscriptionApiBaseUrl }
|
|
9
9
|
* GET /api/v1/huaqiu/auth/user-info → { userInfo } (node-side eda.cn call)
|
|
10
|
-
* GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side
|
|
10
|
+
* GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side subscription-balances call)
|
|
11
11
|
*
|
|
12
12
|
* `config` tells the browser half whether it is running under an HQ Edge host
|
|
13
13
|
* (hq-edge passes the operator credential to hq-edge itself, so the sidebar
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
20
20
|
import { getLogger, type PluginLogger } from '@huaqiu/dsh-plugin-log'
|
|
21
21
|
import type { HuaqiuAuthService, HuaqiuUserInfo } from './service.js'
|
|
22
|
+
import { aiUsageFromPayload, type AiUsage } from './subscription-balances.js'
|
|
22
23
|
|
|
23
24
|
// Lazy so test suites that `vi.mock('@deepseek-ai/dsh-home-paths', …)` before
|
|
24
25
|
// their TMP constant is initialised don't trigger `dshHomePath('logs')` at
|
|
@@ -75,82 +76,84 @@ export async function fetchEdaUserProfile(
|
|
|
75
76
|
|
|
76
77
|
export const AUTH_ROUTE_PREFIX = '/api/v1/huaqiu/auth'
|
|
77
78
|
|
|
78
|
-
// ── AI
|
|
79
|
+
// ── Subscription balances / AI usage (proxied by the node half) ──────────────
|
|
79
80
|
|
|
80
81
|
/**
|
|
81
|
-
* The
|
|
82
|
+
* The authoritative subscription-balances endpoint
|
|
83
|
+
* (`GET /sub-api/subscriptions/balances/current`).
|
|
82
84
|
*
|
|
83
|
-
* It
|
|
84
|
-
* call it: a WebView fetch is refused by App Transport Security ("the
|
|
85
|
-
* could not be loaded because the App Transport Security policy
|
|
86
|
-
* use of a secure connection") and, independently, by CORS (the
|
|
87
|
-
* no `Access-Control-Allow-Origin`). Node's fetch is subject to
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
85
|
+
* It may be served over PLAIN `http`, which is why the node half must be the one
|
|
86
|
+
* to call it: a WebView fetch is refused by App Transport Security ("the
|
|
87
|
+
* resource could not be loaded because the App Transport Security policy
|
|
88
|
+
* requires the use of a secure connection") and, independently, by CORS (the
|
|
89
|
+
* response sends no `Access-Control-Allow-Origin`). Node's fetch is subject to
|
|
90
|
+
* neither. The URL is injected as resolved config by HQ Edge (`HQ_AI_ENV`);
|
|
91
|
+
* this module has no hardcoded environment URL, and every payload is validated
|
|
92
|
+
* against the single schema in `./subscription-balances.js`.
|
|
91
93
|
*/
|
|
92
94
|
|
|
93
|
-
/**
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
* bundles.)
|
|
104
|
-
*/
|
|
105
|
-
export interface AiTokenUsage {
|
|
106
|
-
availablePoints: number
|
|
107
|
-
availableQuota: number
|
|
108
|
-
availableUsd: number
|
|
109
|
-
usedPoints: number
|
|
110
|
-
usedQuota: number
|
|
111
|
-
usedUsd: number
|
|
95
|
+
/** Upstream budget for one balances call. */
|
|
96
|
+
export const AI_USAGE_TIMEOUT_MS = 10_000
|
|
97
|
+
|
|
98
|
+
/** Host-only label for diagnostics (never log the full URL or the token). */
|
|
99
|
+
function safeHost(url: string): string {
|
|
100
|
+
try {
|
|
101
|
+
return new URL(url).host
|
|
102
|
+
} catch {
|
|
103
|
+
return '<invalid-url>'
|
|
104
|
+
}
|
|
112
105
|
}
|
|
113
106
|
|
|
114
107
|
/**
|
|
115
|
-
* Fetch
|
|
116
|
-
*
|
|
108
|
+
* Fetch and normalize AI usage for a token.
|
|
109
|
+
*
|
|
110
|
+
* `quotaRemainPercent` comes straight from the AI Points group — no local ratio
|
|
111
|
+
* is derived. `null` on any failure (invalid payload, timeout, network, non-2xx)
|
|
112
|
+
* so the UI degrades to「—」; never throws.
|
|
117
113
|
*
|
|
118
|
-
* The header is `X-Token` (capital T)
|
|
119
|
-
* subscription endpoint next door uses `x-token` + `X-User-Id`.
|
|
114
|
+
* The upstream header is `X-Token` (capital T).
|
|
120
115
|
*/
|
|
121
|
-
export async function
|
|
116
|
+
export async function fetchAiUsage(
|
|
122
117
|
token: string,
|
|
123
|
-
|
|
118
|
+
subscriptionBalancesUrl: string,
|
|
124
119
|
doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
|
|
125
|
-
|
|
120
|
+
options: { signal?: AbortSignal; timeoutMs?: number } = {},
|
|
121
|
+
): Promise<AiUsage | null> {
|
|
122
|
+
const timeoutMs = options.timeoutMs ?? AI_USAGE_TIMEOUT_MS
|
|
123
|
+
const controller = new AbortController()
|
|
124
|
+
const onAbort = () => controller.abort(options.signal?.reason)
|
|
125
|
+
if (options.signal) {
|
|
126
|
+
if (options.signal.aborted) controller.abort(options.signal.reason)
|
|
127
|
+
else options.signal.addEventListener('abort', onAbort, { once: true })
|
|
128
|
+
}
|
|
129
|
+
const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs)
|
|
130
|
+
const host = safeHost(subscriptionBalancesUrl)
|
|
126
131
|
try {
|
|
127
|
-
const res = await doFetch(
|
|
132
|
+
const res = await doFetch(subscriptionBalancesUrl, {
|
|
128
133
|
method: 'GET',
|
|
129
134
|
headers: {
|
|
130
|
-
Accept: 'application/json
|
|
131
|
-
'
|
|
135
|
+
Accept: 'application/json',
|
|
136
|
+
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
132
137
|
'X-Token': token,
|
|
133
138
|
},
|
|
139
|
+
signal: controller.signal,
|
|
134
140
|
})
|
|
135
|
-
if (!res.ok)
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const result = body.result
|
|
139
|
-
const num = (key: string): number => {
|
|
140
|
-
const v = Number(result[key])
|
|
141
|
-
return Number.isFinite(v) ? v : 0
|
|
142
|
-
}
|
|
143
|
-
return {
|
|
144
|
-
availablePoints: num('availablePoints'),
|
|
145
|
-
availableQuota: num('availableQuota'),
|
|
146
|
-
availableUsd: num('availableUsd'),
|
|
147
|
-
usedPoints: num('usedPoints'),
|
|
148
|
-
usedQuota: num('usedQuota'),
|
|
149
|
-
usedUsd: num('usedUsd'),
|
|
141
|
+
if (!res.ok) {
|
|
142
|
+
log().warn('subscription balances request failed', { host, status: res.status })
|
|
143
|
+
return null
|
|
150
144
|
}
|
|
145
|
+
const usage = aiUsageFromPayload(await res.json())
|
|
146
|
+
if (!usage) log().warn('subscription balances payload unusable', { host })
|
|
147
|
+
return usage
|
|
151
148
|
} catch (err) {
|
|
152
|
-
log().warn('
|
|
149
|
+
log().warn('subscription balances request failed', {
|
|
150
|
+
host,
|
|
151
|
+
error: String((err as Error)?.message || err),
|
|
152
|
+
})
|
|
153
153
|
return null
|
|
154
|
+
} finally {
|
|
155
|
+
clearTimeout(timer)
|
|
156
|
+
options.signal?.removeEventListener('abort', onAbort)
|
|
154
157
|
}
|
|
155
158
|
}
|
|
156
159
|
|
|
@@ -234,6 +237,9 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
|
|
|
234
237
|
sendJson(res, 200, {
|
|
235
238
|
hostMode: service.hostMode,
|
|
236
239
|
subscriptionOrigin: service.subscriptionOrigin,
|
|
240
|
+
// Origin of the resolved balances API — lets the browser build the
|
|
241
|
+
// GEN/ERC active-subscription calls without hardcoding eda.cn.
|
|
242
|
+
subscriptionApiBaseUrl: service.subscriptionApiBaseUrl,
|
|
237
243
|
})
|
|
238
244
|
return
|
|
239
245
|
}
|
|
@@ -258,11 +264,25 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
|
|
|
258
264
|
// resolved (host → pushed → persisted) — the same shape as /user-info
|
|
259
265
|
// above. The URL itself is resolved by HQ Edge; absent → no call.
|
|
260
266
|
const token = await service.auth.getAccessToken()
|
|
261
|
-
if (!token || !service.
|
|
267
|
+
if (!token || !service.subscriptionBalancesUrl) {
|
|
262
268
|
sendJson(res, 200, { usage: null })
|
|
263
269
|
return
|
|
264
270
|
}
|
|
265
|
-
|
|
271
|
+
const controller = new AbortController()
|
|
272
|
+
const onClose = () => controller.abort()
|
|
273
|
+
res.on('close', onClose)
|
|
274
|
+
let usage: AiUsage | null
|
|
275
|
+
try {
|
|
276
|
+
usage = await fetchAiUsage(
|
|
277
|
+
token,
|
|
278
|
+
service.subscriptionBalancesUrl,
|
|
279
|
+
globalThis.fetch.bind(globalThis),
|
|
280
|
+
{ signal: controller.signal },
|
|
281
|
+
)
|
|
282
|
+
} finally {
|
|
283
|
+
res.off('close', onClose)
|
|
284
|
+
}
|
|
285
|
+
sendJson(res, 200, { usage })
|
|
266
286
|
return
|
|
267
287
|
}
|
|
268
288
|
|
package/src/service.ts
CHANGED
|
@@ -96,11 +96,17 @@ export interface HuaqiuAuthService {
|
|
|
96
96
|
*/
|
|
97
97
|
readonly hostMode: boolean
|
|
98
98
|
/**
|
|
99
|
-
* Resolved
|
|
100
|
-
* or null when none was configured.
|
|
101
|
-
* hardcoded environment endpoint.
|
|
99
|
+
* Resolved subscription balances endpoint injected by HQ Edge
|
|
100
|
+
* (`config.subscriptionBalancesUrl`), or null when none was configured.
|
|
101
|
+
* `/ai-usage` never falls back to a stale hardcoded environment endpoint.
|
|
102
102
|
*/
|
|
103
|
-
readonly
|
|
103
|
+
readonly subscriptionBalancesUrl: string | null
|
|
104
|
+
/**
|
|
105
|
+
* Origin of {@link subscriptionBalancesUrl} (e.g. `https://www.eda.cn`), used
|
|
106
|
+
* by the browser half for the GEN/ERC active-subscription calls. Null when no
|
|
107
|
+
* endpoint was configured — DSH Auth never hardcodes a production host.
|
|
108
|
+
*/
|
|
109
|
+
readonly subscriptionApiBaseUrl: string | null
|
|
104
110
|
/**
|
|
105
111
|
* Resolved subscription origin injected by HQ Edge (`config.subscriptionOrigin`),
|
|
106
112
|
* or null when none was configured (standalone keeps its PROD default).
|
|
@@ -120,6 +126,15 @@ function safeHost(url: string): string {
|
|
|
120
126
|
}
|
|
121
127
|
}
|
|
122
128
|
|
|
129
|
+
/** Scheme + host origin of a URL, or null when it does not parse. */
|
|
130
|
+
function originOf(url: string): string | null {
|
|
131
|
+
try {
|
|
132
|
+
return new URL(url).origin
|
|
133
|
+
} catch {
|
|
134
|
+
return null
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
123
138
|
/**
|
|
124
139
|
* Bounded wait for the host to confirm a logout. Shorter than the login wait
|
|
125
140
|
* (which must cover a human completing the EDA dialog): logout is a host-side
|
|
@@ -222,7 +237,12 @@ export class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
|
|
|
222
237
|
fetchImpl: this.doFetch,
|
|
223
238
|
})
|
|
224
239
|
this.hostMode = this.host.enabled
|
|
225
|
-
this.
|
|
240
|
+
this.subscriptionBalancesUrl = resolved.subscriptionBalancesUrl?.length
|
|
241
|
+
? resolved.subscriptionBalancesUrl
|
|
242
|
+
: null
|
|
243
|
+
this.subscriptionApiBaseUrl = this.subscriptionBalancesUrl
|
|
244
|
+
? originOf(this.subscriptionBalancesUrl)
|
|
245
|
+
: null
|
|
226
246
|
this.subscriptionOrigin = resolved.subscriptionOrigin?.length
|
|
227
247
|
? resolved.subscriptionOrigin
|
|
228
248
|
: null
|
|
@@ -231,15 +251,19 @@ export class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
|
|
|
231
251
|
hostAuthPath: resolved.hostAuthPath,
|
|
232
252
|
hostSessionTtlSeconds: resolved.hostSessionTtlSeconds,
|
|
233
253
|
// Hosts only — never a complete URL that could carry a credential.
|
|
234
|
-
|
|
254
|
+
subscriptionBalancesHost: this.subscriptionBalancesUrl
|
|
255
|
+
? safeHost(this.subscriptionBalancesUrl)
|
|
256
|
+
: null,
|
|
235
257
|
subscriptionOrigin: this.subscriptionOrigin,
|
|
236
258
|
})
|
|
237
259
|
}
|
|
238
260
|
|
|
239
261
|
/** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
|
|
240
262
|
readonly hostMode: boolean
|
|
241
|
-
/**
|
|
242
|
-
readonly
|
|
263
|
+
/** Subscription balances endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
|
|
264
|
+
readonly subscriptionBalancesUrl: string | null
|
|
265
|
+
/** Origin used for GEN/ERC active-subscription calls; null → unavailable. */
|
|
266
|
+
readonly subscriptionApiBaseUrl: string | null
|
|
243
267
|
/** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
|
|
244
268
|
readonly subscriptionOrigin: string | null
|
|
245
269
|
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single authoritative contract for the subscription-balances API
|
|
3
|
+
* (`GET /sub-api/subscriptions/balances/current`).
|
|
4
|
+
*
|
|
5
|
+
* Both halves import these types (the browser half type-only), and the node
|
|
6
|
+
* half's parser is the ONE place an upstream payload is turned into usage data.
|
|
7
|
+
* There must be no second response shape, no second parser and no locally
|
|
8
|
+
* derived percentage: `quotaRemainPercent` is the only source of truth.
|
|
9
|
+
*
|
|
10
|
+
* This module is intentionally dependency-free so the browser bundle can import
|
|
11
|
+
* the types without pulling node modules in.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** One quota group in `result[]` (AI and non-AI groups share this shape). */
|
|
15
|
+
export interface SubscriptionBalanceGroup {
|
|
16
|
+
id: number
|
|
17
|
+
groupCode: string
|
|
18
|
+
groupName: string
|
|
19
|
+
quotaTotal: number | null
|
|
20
|
+
quotaUsed: number | null
|
|
21
|
+
quotaRemain: number | null
|
|
22
|
+
/** Remaining percentage. `null` for groups that do not report one. */
|
|
23
|
+
quotaRemainPercent: number | null
|
|
24
|
+
/** `true` ONLY for the AI Points group — the discriminator. */
|
|
25
|
+
aiPoints: boolean
|
|
26
|
+
status: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The upstream envelope. */
|
|
30
|
+
export interface SubscriptionBalancesResponse {
|
|
31
|
+
code: number
|
|
32
|
+
message: string
|
|
33
|
+
result: SubscriptionBalanceGroup[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Client-facing view: only the authoritative remaining percentage. */
|
|
37
|
+
export interface AiUsage {
|
|
38
|
+
quotaRemainPercent: number | null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The only success code accepted from the subscription balances API. */
|
|
42
|
+
export const SUBSCRIPTION_BALANCES_SUCCESS_CODE = 200000
|
|
43
|
+
|
|
44
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
45
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
46
|
+
? (value as Record<string, unknown>)
|
|
47
|
+
: null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `null`/missing/non-numeric → `null` (never a coerced 0). */
|
|
51
|
+
function numberOrNull(value: unknown): number | null {
|
|
52
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function numberOf(value: unknown): number {
|
|
56
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function stringOf(value: unknown): string {
|
|
60
|
+
return typeof value === 'string' ? value : ''
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parseGroup(raw: unknown): SubscriptionBalanceGroup | null {
|
|
64
|
+
const group = asRecord(raw)
|
|
65
|
+
if (!group) return null
|
|
66
|
+
// `aiPoints` is the ONLY AI-group discriminator. A non-boolean value makes
|
|
67
|
+
// the payload unusable: guessing would risk showing a non-AI group.
|
|
68
|
+
if (typeof group.aiPoints !== 'boolean') return null
|
|
69
|
+
return {
|
|
70
|
+
id: numberOf(group.id),
|
|
71
|
+
groupCode: stringOf(group.groupCode),
|
|
72
|
+
groupName: stringOf(group.groupName),
|
|
73
|
+
quotaTotal: numberOrNull(group.quotaTotal),
|
|
74
|
+
quotaUsed: numberOrNull(group.quotaUsed),
|
|
75
|
+
quotaRemain: numberOrNull(group.quotaRemain),
|
|
76
|
+
quotaRemainPercent: numberOrNull(group.quotaRemainPercent),
|
|
77
|
+
aiPoints: group.aiPoints,
|
|
78
|
+
status: numberOf(group.status),
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Validate an upstream payload against the authoritative schema.
|
|
84
|
+
* Returns `null` for a non-2xx-style envelope, a non-array `result`, or any
|
|
85
|
+
* malformed group — callers degrade to "unavailable" rather than guessing.
|
|
86
|
+
*/
|
|
87
|
+
export function parseSubscriptionBalancesResponse(
|
|
88
|
+
payload: unknown,
|
|
89
|
+
): SubscriptionBalancesResponse | null {
|
|
90
|
+
const body = asRecord(payload)
|
|
91
|
+
if (!body) return null
|
|
92
|
+
if (body.code !== SUBSCRIPTION_BALANCES_SUCCESS_CODE) return null
|
|
93
|
+
if (!Array.isArray(body.result)) return null
|
|
94
|
+
const result = body.result.map(parseGroup)
|
|
95
|
+
if (result.some((group) => group === null)) return null
|
|
96
|
+
return {
|
|
97
|
+
code: body.code,
|
|
98
|
+
message: typeof body.message === 'string' ? body.message : '',
|
|
99
|
+
result: result as SubscriptionBalanceGroup[],
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Select the AI Points group and read its remaining percentage.
|
|
105
|
+
*
|
|
106
|
+
* No AI group → `null`; a missing/`null`/non-finite `quotaRemainPercent` →
|
|
107
|
+
* `null` (unavailable). `0` is preserved as a valid exhausted balance.
|
|
108
|
+
*/
|
|
109
|
+
export function selectAiUsage(
|
|
110
|
+
response: SubscriptionBalancesResponse | null,
|
|
111
|
+
): AiUsage | null {
|
|
112
|
+
const group = response?.result.find((entry) => entry.aiPoints === true)
|
|
113
|
+
if (!group) return null
|
|
114
|
+
const percent = group.quotaRemainPercent
|
|
115
|
+
if (percent === null || !Number.isFinite(percent)) return null
|
|
116
|
+
return { quotaRemainPercent: percent }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Parse + select in one step — the single upstream→usage normalization. */
|
|
120
|
+
export function aiUsageFromPayload(payload: unknown): AiUsage | null {
|
|
121
|
+
return selectAiUsage(parseSubscriptionBalancesResponse(payload))
|
|
122
|
+
}
|