阶段二:迁移登录账号与风控接口到生成契约

This commit is contained in:
Christ committed 2026-08-20 00:16:40 +08:00
1 parent fba0915fd3
commit 5fc32239f6
33 files changed
+939 -145

No files matched your search

+92 -26
View File
@@ -14,7 +14,8 @@ NotificationEventType,
OperationResponse,
QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
} from '../../../shared/api-contract/accounts';
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/accounts';
@@ -27,7 +28,10 @@ export type QRLoginStatusResult = Pick<
// Accounts
// addAccount 新增账号。
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
return post('/api/v1/accounts', { id, value, login_method: loginMethod });
return runContractRequest(/* signal 是本次账号创建请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/accounts', {
body: { id, value, login_method: loginMethod },
signal,
}));
};
// accountAvatarURL 生成账号头像地址。
@@ -51,7 +55,7 @@ const accountAvatarURL = (item: AccountSummaryResponse, version: string): string
// getAccountDetails 读取账号详情。
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => {
// data 数据,用于当前 API 处理流程。
const response = await get<unknown>('/api/v1/accounts/details', undefined, options);
const response = await runContractRequest(/* signal 是本次账号详情读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
// data 是兼容数组、null 和历史 data 包裹后的账号摘要列表。
const data = collectionFrom<AccountSummaryResponse>(response, ['data', 'accounts', 'details']);
// avatarVersion 头像缓存版本,用于当前 API 处理流程。
@@ -105,21 +109,29 @@ export interface AccountRuntimeStatus {
// getAccountRuntimeStatuses 读取账号运行状态。
export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise<Record<string, AccountRuntimeStatus>> => {
const response = await get<unknown>('/api/v1/accounts/runtime-status', undefined, options);
// statuses 是兼容直接映射、statuses 包裹和 null 的运行状态索引。
const statuses = objectFrom<Record<string, AccountRuntimeStatus>>(response, ['statuses', 'data', 'result']);
return statuses || {};
// response 是按账号 ID 索引的非敏感运行状态快照。
const response = await runContractRequest(
/* signal 是本次账号运行状态读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/runtime-status', { signal }),
options,
);
return response;
};
// generateQRLogin 生成二维码登录会话。
export const generateQRLogin = async (options?: RequestControlOptions): Promise<QRLoginGenerateResponse> => {
// 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。
return post('/api/v1/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 });
return runContractRequest(
/* signal 是本次二维码生成请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/qr-login/generate', { signal }),
{ ...options, timeoutMs: options?.timeoutMs ?? 130_000 },
);
};
// checkQRLoginStatus 查询二维码登录状态。
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<QRLoginStatusResponse> => {
return get(`/api/v1/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
return runContractRequest(
/* requestSignal 是本次二维码轮询请求的超时与取消控制信号。 */ requestSignal => contractClient.GET('/api/v1/qr-login/check/{session_id}', { params: { path: { session_id: sessionId } }, signal: requestSignal }),
{ signal, timeoutMs: 10_000 },
);
};
// completeQRVerification 完成二维码登录验证。
@@ -127,9 +139,11 @@ export const completeQRVerification = async (
sessionId: string,
targetAccountId?: string,
): Promise<QRLoginVerificationResponse> => {
return post(`/api/v1/qr-login/complete-verification/${sessionId}`, {
target_account_id: targetAccountId || '',
});
return runContractRequest(/* requestSignal 是本次风控完成请求的超时与取消控制信号。 */ requestSignal => contractClient.POST('/api/v1/qr-login/complete-verification/{session_id}', {
params: { path: { session_id: sessionId } },
body: { target_account_id: targetAccountId || '' },
signal: requestSignal,
}));
};
@@ -139,32 +153,55 @@ export const completeQRVerification = async (
// updateAccountStatus 更新账号状态。
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/status`, { enabled });
return runContractRequest(/* signal 是本次账号状态更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/status', {
params: { path: { cid: id } },
body: { enabled },
signal,
}));
};
// deleteAccount 删除账号。
export const deleteAccount = async (id: string): Promise<OperationResponse> => {
return del(`/api/v1/accounts/${id}`);
return runContractRequest(/* signal 是本次账号删除请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/accounts/{cid}', {
params: { path: { cid: id } },
signal,
}));
};
// updateAccountRemark 更新账号备注。
export const updateAccountRemark = async (id: string, remark: string): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/remark`, { remark });
return runContractRequest(/* signal 是本次账号备注更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/remark', {
params: { path: { cid: id } },
body: { remark },
signal,
}));
};
// updateAccountAutoConfirm 更新账号自动确认设置。
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
return runContractRequest(/* signal 是本次账号自动确认更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/auto-confirm', {
params: { path: { cid: id } },
body: { auto_confirm: autoConfirm },
signal,
}));
};
// updateAccountPauseDuration 更新账号暂停时长。
export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options);
return runContractRequest(/* signal 是本次账号暂停时长更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/pause-duration', {
params: { path: { cid: id } },
body: { pause_duration: pauseDuration },
signal,
}), options);
};
// updateAccountCookie 更新账号登录凭证。
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}`, { id, value, login_method: loginMethod });
return runContractRequest(/* signal 是本次账号凭据更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}', {
params: { path: { cid: id } },
body: { id, value, login_method: loginMethod },
signal,
}));
};
export interface AccountSettingsUpdate {
@@ -181,7 +218,11 @@ export interface AccountSettingsUpdate {
// updateAccountSettings 更新账号设置。
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/settings`, data, options);
return runContractRequest(/* signal 是本次账号聚合设置更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/settings', {
params: { path: { cid: id } },
body: data,
signal,
}), options);
};
export interface LongLoginSettings {
@@ -191,12 +232,19 @@ export interface LongLoginSettings {
// getLongLoginSettings 读取长期登录设置。
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
return runContractRequest(/* signal 是本次长期登录设置读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/{cid}/long-login', {
params: { path: { cid: id } },
signal,
}), options);
};
// setLongLoginSettings 设置长期登录开关。
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
return runContractRequest(/* signal 是本次长期登录设置更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/long-login', {
params: { path: { cid: id } },
body: { enabled },
signal,
}), options);
};
export interface PasswordLoginStartResponse {
@@ -226,22 +274,36 @@ export const passwordLogin = async (data: {
/** password 表示密码。 */ password: string;
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
return post('/api/v1/password-login', data, options);
return runContractRequest(/* signal 是永久关闭的密码登录请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/password-login', {
body: data,
signal,
}), options);
};
// checkPasswordLoginStatus 查询密码登录状态。
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
// result 是永久关闭 operation 的理论成功类型;真实服务端恒定返回 password_login_disabled 错误。
const result = runContractRequest(/* requestSignal 是永久关闭的密码登录查询请求的超时与取消控制信号。 */ requestSignal => contractClient.GET('/api/v1/password-login/check/{session_id}', {
params: { path: { session_id: sessionId } },
signal: requestSignal,
}), { signal, timeoutMs: 10_000 });
return result as unknown as Promise<PasswordLoginStatusResponse>;
};
// cancelPasswordLogin 取消密码登录。
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<OperationResponse> => {
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
return runContractRequest(/* signal 是永久关闭的密码登录取消请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/password-login/cancel/{session_id}', {
params: { path: { session_id: sessionId } },
signal,
}), options);
};
// refreshAccountProfile 刷新账号资料。
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
return post(`/api/v1/accounts/${id}/refresh-profile`, {});
return runContractRequest(/* signal 是本次账号资料刷新请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/accounts/{cid}/refresh-profile', {
params: { path: { cid: id } },
signal,
}));
};
// updateAccountLoginInfo 更新账号登录信息。
@@ -251,7 +313,11 @@ export const updateAccountLoginInfo = async (id: string, data: {
/** clear_password 表示是否清理登录密码。 */ clear_password?: boolean;
/** show_browser 表示是否显示浏览器。 */ show_browser?: boolean;
}): Promise<OperationResponse> => {
return put(`/api/v1/accounts/${id}/login-info`, data);
return runContractRequest(/* signal 是本次账号登录信息更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/accounts/{cid}/login-info', {
params: { path: { cid: id } },
body: data,
signal,
}));
};
// getAllAISettings 读取全部人工智能设置。
+24 -5
View File
@@ -1,5 +1,5 @@
import type { OperationResponse,SessionResponse } from '../../../shared/api-contract/session';
import { get,post,type RequestControlOptions } from '../../../shared/http/client';
import { contractClient, runContractRequest, type ContractRequestOptions } from '../../../shared/api-contract/client';
export type * from '../../../shared/api-contract/session';
/** 会话状态接口返回的只读传输契约。 */
@@ -29,13 +29,32 @@ export interface LoginRequest {
}
/** 以用户名密码或邮箱验证码建立管理会话。 */
export const login = async (data: LoginRequest): Promise<SessionResponse> => post('/api/v1/session/login', data, { skipAuthLogout: true });
export const login = async (data: LoginRequest): Promise<SessionResponse> => {
// response 是生成契约校验后的登录成功响应。
const response = await runContractRequest(
/* signal 是本次登录请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/login', { body: data, signal }),
{ skipAuthLogout: true },
);
return { ...response, token: response.token ?? undefined };
};
/** 用首次设置的管理员密码完成系统初始化并建立会话。 */
export const initializeAdmin = async (password: string): Promise<SessionResponse> => post('/api/v1/session/initialize', { password }, { skipAuthLogout: true });
export const initializeAdmin = async (password: string): Promise<SessionResponse> => {
// response 是生成契约校验后的首次初始化成功响应。
const response = await runContractRequest(
/* signal 是本次初始化请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/initialize', { body: { password }, signal }),
{ skipAuthLogout: true },
);
return { ...response, token: response.token ?? undefined };
};
/** 读取当前浏览器的认证与初始化状态,调用者可取消页面卸载前的请求。 */
export const verifySession = async (options?: RequestControlOptions): Promise<SessionStatusResponse> => get('/api/v1/session', undefined, options);
export const verifySession = async (options?: ContractRequestOptions): Promise<SessionStatusResponse> =>
runContractRequest(/* signal 是本次会话校验请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/session', { signal }), options);
/** 结束当前浏览器会话。 */
export const logout = async (): Promise<OperationResponse> => post('/api/v1/session/logout', {});
export const logout = async (): Promise<OperationResponse> => {
// response 是注销接口仅返回的用户可见提示。
const response = await runContractRequest(/* signal 是本次注销请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/logout', { body: {}, signal }));
return { success: true, message: response.message };
};
+26 -17
View File
@@ -1,5 +1,6 @@
import type { AIModelsResponse,OperationResponse,SystemSettings } from '../../../shared/api-contract/settings';
import { get,post,put,type RequestControlOptions } from '../../../shared/http/client';
import type { OperationResponse,SystemSettings } from '../../../shared/api-contract/settings';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { type RequestControlOptions } from '../../../shared/http/client';
export type * from '../../../shared/api-contract/settings';
/** 设置页面使用的会话状态传输契约,避免跨 feature 依赖。 */
@@ -27,7 +28,7 @@ export type SensitiveSettingChange = {
/** 系统设置更新请求,将普通配置与敏感命令分开传输。 */
export type SystemSettingsUpdate = {
/** 非敏感配置字段。 */
values?: Record<string, unknown>;
values?: Record<string, string | number | boolean>;
/** 由服务端解释的敏感值变更命令。 */
secrets?: Record<string, SensitiveSettingChange>;
};
@@ -36,10 +37,10 @@ export type SystemSettingsUpdate = {
const SENSITIVE_SYSTEM_SETTING_KEYS = new Set(['ai_api_key', 'smtp_password', 'qq_reply_secret_key', 'captcha.remote_secret_key']);
/** 将历史设置草稿转换为服务端要求的普通值与敏感命令结构。 */
const normalizeSystemSettingsUpdate = (settings: Partial<SystemSettings> | SystemSettingsUpdate): Record<string, unknown> => {
if ('values' in settings || 'secrets' in settings) return settings;
const normalizeSystemSettingsUpdate = (settings: Partial<SystemSettings> | SystemSettingsUpdate): SystemSettingsUpdate => {
if ('values' in settings || 'secrets' in settings) return settings as SystemSettingsUpdate;
// values 保存普通设置,永不容纳秘密文本。
const values: Record<string, unknown> = {};
const values: Record<string, string | number | boolean> = {};
// secrets 保存服务端需要独立处理的敏感设置命令。
const secrets: Record<string, SensitiveSettingChange> = {};
for (const /* key、value 是当前待分流的设置键和值。 */ [key, value] of Object.entries(settings)) {
@@ -48,7 +49,7 @@ const normalizeSystemSettingsUpdate = (settings: Partial<SystemSettings> | Syste
secrets[key] = value === '' ? { action: 'clear' } : { action: 'replace', value: String(value) };
continue;
}
values[key] = value;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') values[key] = value;
}
return Object.keys(secrets).length > 0 ? { values, secrets } : values;
};
@@ -72,29 +73,37 @@ const normalizeSettings = (settings: Record<string, unknown>): SystemSettings =>
};
/** 修改当前管理员的密码。 */
export const changePassword = async (currentPassword: string, newPassword: string): Promise<OperationResponse> => post('/api/v1/session/password', { current_password: currentPassword, new_password: newPassword });
export const changePassword = async (currentPassword: string, newPassword: string): Promise<OperationResponse> =>
runContractRequest(/* signal 是本次管理员密码更新请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/session/password', { body: { current_password: currentPassword, new_password: newPassword }, signal }));
/** 修改当前管理员的登录名称与可选密码。 */
export const updateLoginCredentials = async (data: { /** 当前密码用于服务端重新验证身份。 */ current_password: string; /** 新的管理员名称。 */ new_username: string; /** 可选的新密码。 */ new_password?: string }, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/session/credentials', data, options);
export const updateLoginCredentials = async (data: { /** 当前密码用于服务端重新验证身份。 */ current_password: string; /** 新的管理员名称。 */ new_username: string; /** 可选的新密码。 */ new_password?: string }, options?: RequestControlOptions): Promise<OperationResponse> =>
runContractRequest(/* signal 是本次管理员凭据更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/session/credentials', { body: data, signal }), options);
/** 获取系统设置;仅保留敏感值是否已配置的状态,不接收敏感明文。 */
export const getSystemSettings = async (options?: RequestControlOptions): Promise<SystemSettings> => {
// response 是服务端可能包裹在 data 中的设置响应。
const response = await get<{ /** settings 是当前系统配置对象。 */ data?: Record<string, unknown>; /** settings 是未包裹的兼容设置对象。 */ settings?: Record<string, unknown> } & Record<string, unknown>>('/api/v1/settings/system', undefined, options);
// settings 是去除 transport 包裹后的配置对象。
const settings = response.data || response.settings || response;
return normalizeSettings(settings);
// response 是 OpenAPI 约束的脱敏系统设置键值对象。
const response = await runContractRequest(/* signal 是本次系统设置读取请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/settings/system', { signal }), options);
return normalizeSettings(response);
};
/** 保存普通系统配置和敏感设置命令。 */
export const updateSystemSettings = async (settings: Partial<SystemSettings> | SystemSettingsUpdate, options?: RequestControlOptions): Promise<OperationResponse> => put('/api/v1/settings/system', normalizeSystemSettingsUpdate(settings), options);
export const updateSystemSettings = async (settings: Partial<SystemSettings> | SystemSettingsUpdate, options?: RequestControlOptions): Promise<OperationResponse> =>
runContractRequest(/* signal 是本次系统设置更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/settings/system', {
body: normalizeSystemSettingsUpdate(settings),
signal,
}), options);
/** 向服务端请求指定人工智能服务的可用模型列表。 */
export const fetchAIModels = async (baseURL: string, apiKey = '', options?: RequestControlOptions): Promise<string[]> => {
// response 是模型发现接口的具名响应。
const response = await post<AIModelsResponse>('/api/v1/settings/ai-models', { base_url: baseURL, api_key: apiKey }, options);
const response = await runContractRequest(/* signal 是本次模型发现请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/settings/ai-models', {
body: { base_url: baseURL, api_key: apiKey },
signal,
}), options);
return Array.isArray(response.models) ? response.models : [];
};
/** 在保存登录凭据前读取当前会话状态。 */
export const verifySession = async (options?: RequestControlOptions): Promise<SettingsSessionStatusResponse> => get('/api/v1/session', undefined, options);
export const verifySession = async (options?: RequestControlOptions): Promise<SettingsSessionStatusResponse> =>
runContractRequest(/* signal 是本次设置页会话校验请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/session', { signal }), options);
+1 -1
View File
@@ -102,7 +102,7 @@ describe('React feature dependency boundaries', () => {
test('production React code does not call fetch or axios outside the request boundary', () => {
// violations 保存页面或组件中直接发起网络请求的源码路径。
const violations = productionSources()
.filter(file => file.relativePath !== 'shared/http/client.ts' && /\bfetch\s*\(|\baxios\b/.test(file.source) /* file 是当前待审计直接网络调用的生产模块。 */)
.filter(file => !['shared/http/client.ts', 'shared/api-contract/client.ts'].includes(file.relativePath) && /\bfetch\s*\(|\baxios\b/.test(file.source) /* file 是当前待审计直接网络调用的生产模块。 */)
.map(file => file.relativePath /* 输出越过 HTTP 客户端的模块路径。 */);
expect(violations).toEqual([]);
+81
View File
@@ -0,0 +1,81 @@
import createClient from 'openapi-fetch';
import { ApiError, controlledSignal, notifyAuthExpired, type RequestControlOptions } from '../http/client';
import type { paths } from './generated/schema';
// contractRequestTimeoutMs 是非上传契约请求沿用的默认超时,保持旧 HTTP client 的用户体验。
const contractRequestTimeoutMs = 30_000;
// ContractRequestOptions 是类型化 operation 运行时使用的取消、超时与登录态控制参数。
export type ContractRequestOptions = RequestControlOptions & {
// skipAuthLogout 防止登录和首次初始化失败时错误清理现有页面状态。
skipAuthLogout?: boolean;
};
// ContractResult 是 openapi-fetch 对单个 operation 的成功数据、错误数据和原始响应封装。
type ContractResult<T> = {
// data 是成功状态码且符合 OpenAPI 响应类型时解析出的数据。
data?: T;
// error 是非成功状态码解析出的统一错误 envelope 或未知载荷。
error?: unknown;
// response 是保留状态码和响应头的底层响应对象。
response: Response;
};
// contractFetch 为 openapi-fetch 注入现有浏览器 Cookie 与请求地址兼容语义。
const contractFetch: typeof fetch = async (input, init) => {
// response 是使用既有 Cookie 策略发出的 HTTP 响应。
// requestURL 是 openapi-fetch 根据 baseUrl 生成的绝对地址;测试环境需还原为相对路径以复用既有 fetch fixture。
const requestURL = new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url);
// request 是合并 openapi-fetch 已构造请求与可选 init 后的完整请求对象。
const request = input instanceof Request ? input : new Request(input, init);
// body 是恢复为文本的 JSON 请求载荷;GET/HEAD 不能携带请求体。
const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.clone().text();
// fetchInput 是测试环境还原后的相对 API 地址,浏览器环境继续保留绝对 origin。
const fetchInput = requestURL.origin === 'http://localhost' ? `${requestURL.pathname}${requestURL.search}` : input;
// response 是使用旧 client 等价方法、请求体、取消信号和 Cookie 策略发出的 HTTP 响应。
const response = await fetch(fetchInput, {
method: request.method,
headers: request.headers,
body,
signal: request.signal,
credentials: 'include',
});
return response;
};
// contractClient 是唯一持有生成 paths 类型并执行版本化 HTTP operation 的共享实例。
// contractBaseUrl 是浏览器生产环境的当前 origin;Node 测试使用可被 fetch fixture 还原的占位 origin。
const contractBaseUrl = typeof location === 'undefined' ? 'http://localhost' : location.origin;
export const contractClient = createClient<paths>({ baseUrl: contractBaseUrl, fetch: contractFetch });
// runContractRequest 执行类型化 operation,并恢复旧 client 的超时、取消和 ApiError 行为。
export async function runContractRequest<T>(
execute: (signal: AbortSignal) => Promise<ContractResult<T>>,
options: ContractRequestOptions = {},
): Promise<T> {
// control 统一管理外部 AbortSignal 与默认请求超时。
const control = controlledSignal(options.signal, options.timeoutMs ?? contractRequestTimeoutMs);
try {
// result 是 openapi-fetch 返回的成功或错误响应封装。
const result = await execute(control.signal);
if (result.response.status === 401 && !options.skipAuthLogout) notifyAuthExpired();
if (result.error !== undefined) {
throw new ApiError(result.response.status, result.error);
}
if (result.data === undefined) {
throw new ApiError(result.response.status, undefined);
}
return result.data;
} catch (error /* error 是底层 fetch、响应解析或 ApiError 抛出的原始失败原因。 */) {
// error 是底层 fetch、响应解析或 ApiError 抛出的原始失败原因。
if (control.signal.aborted) {
throw new Error(options.signal?.aborted ? '请求已取消' : '请求超时,请稍后重试');
}
throw error;
} finally {
control.cleanup();
}
}
+143 -22
View File
@@ -1893,6 +1893,95 @@ export interface components {
AccountStatusRequest: {
enabled: boolean;
};
AccountSettingsUpdateRequest: {
cookie?: string;
remark?: string;
auto_confirm?: boolean;
pause_duration?: number;
username?: string;
login_password?: string;
clear_password?: boolean;
show_browser?: boolean;
channel_ids?: number[];
};
AccountLoginInfoRequest: {
username?: string;
login_password?: string;
clear_password?: boolean;
show_browser?: boolean;
};
LongLoginSettingsRequest: {
enabled: boolean;
};
LongLoginResponse: {
can_open_long_login: boolean;
enabled: boolean;
};
AutoConfirmRequest: {
auto_confirm: boolean;
};
AutoConfirmResponse: {
auto_confirm: boolean;
};
AccountRemarkRequest: {
remark: string;
};
PauseDurationRequest: {
pause_duration: number;
};
PauseDurationResponse: {
pause_duration: number;
paused_until: number;
paused: boolean;
};
CookieSettingsResponse: {
success: boolean;
paused_until: number;
paused: boolean;
};
CookieProfileResponse: {
success: boolean;
id: string;
nickname: string;
avatar_url: string;
profile_error: string;
};
RuntimeStatus: {
/** @enum {string} */
state: "starting" | "connecting" | "online" | "reconnecting" | "auth_expired" | "verification_required" | "runtime_conflict" | "error" | "stopped" | "disabled";
message?: string;
connected: boolean;
failures: number;
/** Format: date-time */
updated_at: string;
};
RuntimeStatusMap: {
[key: string]: components["schemas"]["RuntimeStatus"];
};
AIModelsRequest: {
base_url: string;
api_key?: string;
};
AIModelsResponse: {
models: string[];
};
SecretSettingChange: {
/** @enum {string} */
action: "retain" | "replace" | "clear";
value?: string;
};
SystemSettingValueMap: {
[key: string]: string | number | boolean;
};
SystemSettingsUpdateRequest: {
values?: components["schemas"]["SystemSettingValueMap"];
secrets?: {
[key: string]: components["schemas"]["SecretSettingChange"];
};
};
SystemSettingsResponse: {
[key: string]: string | number | boolean;
};
SessionStatusResponse: {
authenticated: boolean;
initialized: boolean;
@@ -2571,7 +2660,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AutoConfirmResponse"];
};
};
/** @description 统一错误响应 */
@@ -2630,7 +2719,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AutoConfirmRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -2638,7 +2731,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["OperationResponse"];
};
};
/** @description 统一错误响应 */
@@ -2697,7 +2790,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AccountLoginInfoRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -2705,7 +2802,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["OperationResponse"];
};
};
/** @description 统一错误响应 */
@@ -2772,7 +2869,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["LongLoginResponse"];
};
};
/** @description 统一错误响应 */
@@ -2831,7 +2928,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["LongLoginSettingsRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -2839,7 +2940,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["LongLoginResponse"];
};
};
/** @description 统一错误响应 */
@@ -2906,7 +3007,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["PauseDurationResponse"];
};
};
/** @description 统一错误响应 */
@@ -2965,7 +3066,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["PauseDurationRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -2973,7 +3078,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CookieSettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -3040,7 +3145,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CookieProfileResponse"];
};
};
/** @description 统一错误响应 */
@@ -3099,7 +3204,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AccountRemarkRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -3107,7 +3216,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["OperationResponse"];
};
};
/** @description 统一错误响应 */
@@ -3166,7 +3275,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AccountSettingsUpdateRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -3174,7 +3287,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CookieSettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -3375,7 +3488,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["RuntimeStatusMap"];
};
};
/** @description 统一错误响应 */
@@ -10301,7 +10414,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AIModelsRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -10309,7 +10426,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AIModelsResponse"];
};
};
/** @description 统一错误响应 */
@@ -10573,7 +10690,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["SystemSettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -10630,7 +10747,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["SystemSettingsUpdateRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -10638,7 +10759,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["OperationResponse"];
};
};
/** @description 统一错误响应 */
+5 -3
View File
@@ -55,14 +55,15 @@ export class ApiError extends Error {
}
}
const notifyAuthExpired = () => {
// notifyAuthExpired 合并同一批未授权响应,避免多个并发请求反复触发会话清理。
export const notifyAuthExpired = () => {
if (authLogoutPending || typeof window === 'undefined') return;
authLogoutPending = true;
window.dispatchEvent(new Event('auth:logout'));
queueMicrotask(() => {
authLogoutPending = false;
} /* 微任务结束后允许下一次未授权响应重新触发登出通知。 */);
}; /* notifyAuthExpired 合并同一批 401 响应,避免重复触发会话清理。 */
};
const buildQueryString = (params?: QueryParams): string => {
if (!params) return '';
@@ -154,7 +155,8 @@ export const postForm = async <T>(url: string, body: FormData, options: RequestC
return payload as T;
}; /* postForm 表示postForm。 */
const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number) => {
// controlledSignal 组合外部取消与内部超时,调用方必须在请求结束后执行 cleanup。
export const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number) => {
const controller = new AbortController(); /* controller 表示controller。 */
const abortFromExternal = () => controller.abort(external?.reason); /* abortFromExternal 表示abortFromExternal。 */
if (external?.aborted) abortFromExternal();