fix(i18n): use English runtime text and localize system UI

This commit is contained in:
Arthur Koba
2026-10-25 19:44:15 +03:00
parent ada0550571
commit 65a96670d5
289 changed files with 8092 additions and 3426 deletions
+21 -14
View File
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
/**
* Cap PoW (Proof-of-Work) 人机验证前端实现
* 与后端 pkg/cap 算法完全对应
@@ -78,7 +79,7 @@ async function solvePuzzle(token, index, size, difficulty) {
for (let nonce = 0; nonce < 10_000_000; nonce++) {
if ((await sha256Hex(salt + nonce)).startsWith(target)) return nonce;
}
throw new Error('无法在合理范围内求解第 ' + (index + 1) + ' 个难题');
throw new Error('Could not solve puzzle ' + (index + 1) + ' within the allowed search range');
}
// Entry point — receive task from main thread
@@ -124,7 +125,11 @@ function solveInWorker(
worker.onerror = (err) => {
URL.revokeObjectURL(url);
worker.terminate();
reject(new Error(err.message || 'Worker 执行失败'));
reject(
new Error(
err.message || runtimeText('worker_execution_failed_1877e35b'),
),
);
};
worker.postMessage({ token, count, size, difficulty });
@@ -142,14 +147,14 @@ export async function getCapToken(scope = 'login'): Promise<string> {
});
const challenge = await readApiData<ChallengeResponse>(
challengeRes,
'获取人机验证难题失败',
runtimeText('failed_to_fetch_the_verification_challenge_95553133'),
);
const { c: count, s: size, d: difficulty } = challenge.challenge;
console.groupCollapsed('[Cap] 人机验证 PoW 求解开始');
console.log(` 难题数量 (count) : ${count}`);
console.log(` 验证难度 (difficulty): ${difficulty}`);
console.log(` 盐值长度 (size) : ${size}`);
console.groupCollapsed('[Cap] Starting verification PoW solver');
console.log(` Challenge count: ${count}`);
console.log(` Difficulty: ${difficulty}`);
console.log(` Salt size: ${size}`);
console.groupEnd();
// 2. 在 Worker 中求解(不阻塞主线程)
@@ -162,11 +167,11 @@ export async function getCapToken(scope = 'login'): Promise<string> {
);
const wallTime = ((performance.now() - t0) / 1000).toFixed(3);
console.groupCollapsed('[Cap] 人机验证 PoW 求解完成');
console.log(` 难题数量 (count) : ${count}`);
console.log(` 验证难度 (difficulty): ${difficulty}`);
console.log(` Worker 耗时 : ${elapsed}s`);
console.log(` 总耗时(含通信) : ${wallTime}s`);
console.groupCollapsed('[Cap] Verification PoW solver completed');
console.log(` Challenge count: ${count}`);
console.log(` Difficulty: ${difficulty}`);
console.log(` Worker duration: ${elapsed}s`);
console.log(` Total duration (including communication): ${wallTime}s`);
console.log(` Solutions :`, solutions);
console.groupEnd();
@@ -178,10 +183,12 @@ export async function getCapToken(scope = 'login'): Promise<string> {
});
const redeemData = await readApiData<RedeemResponse>(
redeemRes,
'人机验证失败',
runtimeText('verification_failed_d3925ab2'),
);
if (!redeemData.success || !redeemData.token) {
throw new Error(redeemData.error || '人机验证失败');
throw new Error(
redeemData.error || runtimeText('verification_failed_d3925ab2'),
);
}
return redeemData.token;
@@ -1,170 +1,7 @@
import { runtimeText } from '@/i18n/runtime';
/** 内置离线页模板:baohaus */
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>离线页 | OpenFlare</title>
<style>
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
export default function getOfflineHTML() {
const html = runtimeText.raw('doctype_html_html_lang_en_head_meta_3e4f5ecb');
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: #f4f3ef;
color: #121212;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 48px 24px;
-webkit-font-smoothing: antialiased;
}
.bauhaus-card {
width: 100%;
max-width: 580px;
background: #ffffff;
border: 3px solid #121212;
box-shadow: 8px 8px 0px #121212;
display: flex;
flex-direction: column;
overflow: hidden;
}
.card-accent-bar {
height: 12px;
display: flex;
}
.accent-red { flex: 2; background-color: #e63946; }
.accent-blue { flex: 3; background-color: #1d3557; }
.accent-yellow { flex: 1; background-color: #f1faee; }
.card-body {
padding: 40px 32px;
display: flex;
flex-direction: column;
gap: 24px;
}
.tag {
align-self: flex-start;
background-color: #121212;
color: #ffffff;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
padding: 4px 10px;
}
.title {
font-size: 28px;
font-weight: 800;
line-height: 1.2;
letter-spacing: -0.02em;
}
.message {
font-size: 15px;
line-height: 1.6;
color: #4a4a4a;
}
.contact-box {
border: 2px solid #121212;
background-color: #f9f8f3;
padding: 20px;
display: flex;
flex-direction: column;
gap: 12px;
}
.contact-line {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
font-weight: 600;
}
.contact-line a {
color: #e63946;
text-decoration: none;
font-weight: 700;
}
.contact-line a:hover {
text-decoration: underline;
}
.card-footer {
border-top: 2px solid #121212;
padding: 16px 32px;
background-color: #faf9f6;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.05em;
}
.brand {
display: flex;
align-items: center;
gap: 6px;
}
.brand-icon {
width: 16px;
height: 16px;
fill: currentColor;
}
</style>
</head>
<body>
<div class="bauhaus-card">
<div class="card-accent-bar">
<div class="accent-red"></div>
<div class="accent-blue"></div>
<div class="accent-yellow"></div>
</div>
<div class="card-body">
<div class="tag">OFFLINE FALLBACK</div>
<h1 class="title">离线联系站长</h1>
<p class="message">
源站网络临时不可达。离线 Service Worker 已拦截请求,您可以使用下方联系方式取得支持。
</p>
<div class="contact-box">
<div class="contact-line">
<span>站长邮箱</span>
<a href="mailto:admin@example.com">admin@example.com</a>
</div>
<div class="contact-line">
<span>服务监控</span>
<a href="https://status.example.com" target="_blank" rel="noopener">status.example.com</a>
</div>
</div>
</div>
<div class="card-footer">
<div class="brand">
<svg class="brand-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M13 2L3 14H12L11 22L21 10H12L13 2Z" />
</svg>
<span>OpenFlare Service Worker</span>
</div>
<span>OFFLINE MODE</span>
</div>
</div>
</body>
</html>
`;
export default html;
return html;
}
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
/**
* 内置离线页 HTML 模板目录。
*/
@@ -17,29 +18,40 @@ export type OfflinePageTemplate = {
export const OFFLINE_PAGE_TEMPLATES: OfflinePageTemplate[] = [
{
id: 'minimalist',
name: '极简白底',
html: minimalistHtml,
get name() {
return runtimeText('minimal_white_5636e8a9');
},
get html() {
return minimalistHtml();
},
},
{
id: 'line-style',
name: '线框拓扑',
html: lineStyleHtml,
get name() {
return runtimeText('line_topology_22ad450c');
},
get html() {
return lineStyleHtml();
},
},
{
id: 'baohaus',
name: '包豪斯',
html: baohausHtml,
get name() {
return runtimeText('bauhaus_5cc69781');
},
get html() {
return baohausHtml();
},
},
];
/** 默认预制模板 */
export const DEFAULT_OFFLINE_PAGE_TEMPLATE_ID = 'minimalist';
export const DEFAULT_OFFLINE_PAGE_HTML =
getOfflinePageTemplate(DEFAULT_OFFLINE_PAGE_TEMPLATE_ID)?.html ?? '';
export function effectiveOfflinePageHTML(html: string): string {
return html.trim() === '' ? DEFAULT_OFFLINE_PAGE_HTML : html;
return html.trim() === ''
? (getOfflinePageTemplate(DEFAULT_OFFLINE_PAGE_TEMPLATE_ID)?.html ?? '')
: html;
}
export function getOfflinePageTemplate(
@@ -1,193 +1,7 @@
import { runtimeText } from '@/i18n/runtime';
/** 内置离线页模板:line-style */
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>离线页 | OpenFlare</title>
<style>
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
export default function getOfflineHTML() {
const html = runtimeText.raw('doctype_html_html_lang_en_head_meta_42a4f2da');
:root {
--color-bg: #fcfcfc;
--color-line: #e0e0e0;
--color-line-hover: #1a1a1a;
--color-text-main: #1a1a1a;
--color-text-sub: #666666;
--color-text-muted: #999999;
--color-accent: #d4d4d4;
--font-geo: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
}
body {
font-family: var(--font-geo);
background-color: var(--color-bg);
background-image: radial-gradient(circle, var(--color-accent) 0.8px, transparent 0.8px);
background-size: 24px 24px;
color: var(--color-text-main);
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 48px 24px;
-webkit-font-smoothing: antialiased;
letter-spacing: 0.01em;
}
.main-container {
width: 100%;
max-width: 640px;
display: flex;
flex-direction: column;
gap: 32px;
}
.line-box {
border: 1px solid var(--color-line);
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(4px);
padding: 32px;
transition: all var(--transition-fast);
position: relative;
}
.line-box:hover {
border-color: var(--color-line-hover);
box-shadow: 0 0 0 1px var(--color-line-hover);
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.15em;
text-transform: uppercase;
color: var(--color-text-sub);
margin-bottom: 12px;
}
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #f59e0b;
}
.title {
font-size: 24px;
font-weight: 700;
letter-spacing: -0.02em;
margin-bottom: 12px;
}
.description {
font-size: 14px;
line-height: 1.6;
color: var(--color-text-sub);
margin-bottom: 24px;
}
.contact-list {
display: flex;
flex-direction: column;
gap: 12px;
border-top: 1px dashed var(--color-line);
padding-top: 20px;
}
.contact-row {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 13px;
}
.contact-label {
color: var(--color-text-muted);
font-size: 12px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.contact-value a {
color: var(--color-text-main);
font-weight: 600;
text-decoration: none;
border-bottom: 1px solid var(--color-line);
transition: border-color var(--transition-fast);
}
.contact-value a:hover {
border-color: var(--color-text-main);
}
.footer-bar {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 11px;
color: var(--color-text-muted);
letter-spacing: 0.05em;
}
.brand {
display: flex;
align-items: center;
gap: 6px;
font-weight: 600;
color: var(--color-text-main);
}
.brand-icon {
width: 14px;
height: 14px;
fill: currentColor;
}
</style>
</head>
<body>
<div class="main-container">
<div class="line-box">
<div class="status-badge">
<span class="status-dot"></span>
SERVICE WORKER OFFLINE CACHE
</div>
<h1 class="title">网络中断或源站不可达</h1>
<p class="description">
系统已自动启用 Service Worker 兜底保护。如需紧急联系站长,请通过以下渠道:
</p>
<div class="contact-list">
<div class="contact-row">
<span class="contact-label">Email Support</span>
<span class="contact-value"><a href="mailto:admin@example.com">admin@example.com</a></span>
</div>
<div class="contact-row">
<span class="contact-label">Status Page</span>
<span class="contact-value"><a href="https://status.example.com" target="_blank" rel="noopener">status.example.com</a></span>
</div>
</div>
</div>
<div class="footer-bar">
<div class="brand">
<svg class="brand-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M13 2L3 14H12L11 22L21 10H12L13 2Z" />
</svg>
<span>OpenFlare Edge</span>
</div>
<span>FALLBACK ACTIVE</span>
</div>
</div>
</body>
</html>
`;
export default html;
return html;
}
@@ -1,128 +1,7 @@
import { runtimeText } from '@/i18n/runtime';
/** 内置离线页模板:minimalist(默认) */
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>离线页 | OpenFlare</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: #ffffff;
color: #333333;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
padding: 48px 24px;
}
.container {
max-width: 560px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
gap: 24px;
}
.badge {
display: inline-flex;
align-items: center;
padding: 4px 12px;
border-radius: 9999px;
background-color: #f3f4f6;
color: #4b5563;
font-size: 12px;
font-weight: 500;
letter-spacing: 0.05em;
}
.title {
font-size: 32px;
font-weight: 700;
color: #111827;
line-height: 1.25;
}
.description {
font-size: 15px;
line-height: 1.6;
color: #6b7280;
max-width: 480px;
}
.contact-card {
width: 100%;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 24px;
display: flex;
flex-direction: column;
gap: 16px;
text-align: left;
}
.contact-item {
display: flex;
align-items: center;
gap: 12px;
font-size: 14px;
color: #374151;
}
.contact-item svg {
width: 18px;
height: 18px;
color: #6b7280;
flex-shrink: 0;
}
.contact-item a {
color: #2563eb;
text-decoration: none;
}
.contact-item a:hover {
text-decoration: underline;
}
.footer {
margin-top: 32px;
display: flex;
align-items: center;
gap: 8px;
color: #9ca3af;
font-size: 13px;
}
.brand-icon {
width: 20px;
height: 20px;
fill: currentColor;
}
</style>
</head>
<body>
<div class="container">
<div class="badge">OFFLINE CONTACT</div>
<h1 class="title">站点暂不可用,联系站长</h1>
<p class="description">
当前无法连接至源站。页面已开启 Service Worker 离线保护,您可以通过以下方式与站长取得联系。
</p>
<div class="contact-card">
<div class="contact-item">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
<span>联系邮箱:<a href="mailto:admin@example.com">admin@example.com</a></span>
</div>
<div class="contact-item">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
<span>服务状态页:<a href="https://status.example.com" target="_blank" rel="noopener">status.example.com</a></span>
</div>
</div>
<div class="footer">
<svg class="brand-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M13 2L3 14H12L11 22L21 10H12L13 2Z" />
</svg>
<span>OpenFlare Protection</span>
</div>
</div>
</body>
</html>
`;
export default function getOfflineHTML() {
const html = runtimeText.raw('doctype_html_html_lang_en_head_meta_505c1308');
export default html;
return html;
}
@@ -1,7 +1,7 @@
/** 内置错误页模板:baohaus(包豪斯风格) */
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
/**
* 内置源站错误页 HTML 模板目录。
* 每个模板对应本目录下一个独立 `.ts` 模块(export default 完整 HTML 字符串)。
@@ -21,17 +22,23 @@ export type OriginErrorPageTemplate = {
export const ORIGIN_ERROR_PAGE_TEMPLATES: OriginErrorPageTemplate[] = [
{
id: 'minimalist',
name: '极简白底',
get name() {
return runtimeText('minimal_white_5636e8a9');
},
html: minimalistHtml,
},
{
id: 'line-style',
name: '线框拓扑',
get name() {
return runtimeText('line_topology_22ad450c');
},
html: lineStyleHtml,
},
{
id: 'baohaus',
name: '包豪斯',
get name() {
return runtimeText('bauhaus_5cc69781');
},
html: baohausHtml,
},
];
@@ -1,7 +1,7 @@
/** 内置错误页模板:line-style */
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -1,7 +1,7 @@
/** 内置错误页模板:minimalist(默认) */
const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
+27 -8
View File
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
/** Matches pkg/render/openresty StatusCodeMin / StatusCodeMax. */
export const STATUS_CODE_MIN = 400;
export const STATUS_CODE_MAX = 599;
@@ -14,7 +15,7 @@ export function parseStatusCodeTag(tag: string): {
} {
const trimmed = tag.trim();
if (!trimmed) {
throw new Error('状态码标签不能为空');
throw new Error(runtimeText('status_code_tag_must_not_be_empty_21235ebf'));
}
let lo: number;
@@ -25,22 +26,36 @@ export function parseStatusCodeTag(tag: string): {
lo = Number.parseInt(trimmed.slice(0, dash), 10);
hi = Number.parseInt(trimmed.slice(dash + 1), 10);
if (Number.isNaN(lo) || Number.isNaN(hi)) {
throw new Error(`无效状态码区间: ${trimmed}`);
throw new Error(
runtimeText('invalid_status_code_range_value0_8983e96e', {
value0: trimmed,
}),
);
}
} else {
lo = Number.parseInt(trimmed, 10);
if (Number.isNaN(lo)) {
throw new Error(`无效状态码: ${trimmed}`);
throw new Error(
runtimeText('invalid_status_code_value0_0f206e48', { value0: trimmed }),
);
}
hi = lo;
}
if (lo > hi) {
throw new Error(`状态码区间左右端点反序: ${trimmed}`);
throw new Error(
runtimeText('status_code_range_endpoints_are_reversed_value0_d92c2784', {
value0: trimmed,
}),
);
}
if (lo < STATUS_CODE_MIN || hi > STATUS_CODE_MAX) {
throw new Error(
`状态码须在 ${STATUS_CODE_MIN}–${STATUS_CODE_MAX}: ${trimmed}`,
runtimeText('status_code_must_be_between_value0_value1_c5b04822', {
value0: STATUS_CODE_MIN,
value1: STATUS_CODE_MAX,
value2: trimmed,
}),
);
}
@@ -65,18 +80,22 @@ export function validateStatusCodeTagMessage(tag: string): string | null {
parseStatusCodeTag(tag);
return null;
} catch (error) {
return error instanceof Error ? error.message : '无效状态码标签';
return error instanceof Error
? error.message
: runtimeText('invalid_status_code_tag_d16e85d7');
}
}
/** Validate a full tag list before save (must be non-empty and expand cleanly). */
export function validateStatusCodeTags(tags: string[]): void {
if (tags.length === 0) {
throw new Error('请至少添加一个状态码标签');
throw new Error(runtimeText('add_at_least_one_status_code_tag_b81b2696'));
}
const codes = expandStatusCodeTags(tags);
if (codes.length === 0) {
throw new Error('状态码展开结果为空');
throw new Error(
runtimeText('the_expanded_status_code_list_is_empty_47245f34'),
);
}
}
+32 -11
View File
@@ -1,3 +1,5 @@
import { runtimeText } from '@/i18n/runtime';
import { resolveClientLocale } from '@/i18n/client';
import axios, {
AxiosError,
AxiosResponse,
@@ -95,6 +97,7 @@ apiClient.interceptors.request.use(
config.baseURL = getApiBaseUrl();
}
config.url = normalizeApiPath(config.url);
config.headers['Accept-Language'] ??= resolveClientLocale();
const requestKey = getRequestKey(config);
const source = axios.CancelToken.source();
@@ -152,7 +155,7 @@ apiClient.interceptors.response.use(
/* 请求被取消时静默处理 */
if (axios.isCancel(error)) {
const cancelError = new Error(
error.message || '请求已被取消',
error.message || runtimeText('request_canceled_5892f9b1'),
) as Error & { __CANCEL__?: boolean };
cancelError.__CANCEL__ = true;
return Promise.reject(cancelError);
@@ -167,7 +170,10 @@ apiClient.interceptors.response.use(
if (error.response?.status === 403) {
return Promise.reject(
new ForbiddenError(
error.response.data?.error_msg || '权限不足,请过盾后重试',
error.response.data?.error_msg ||
runtimeText(
'insufficient_permissions_complete_verification_and_try_again_73719073',
),
error.response.data?.error_code,
error.response.data?.details,
),
@@ -177,7 +183,10 @@ apiClient.interceptors.response.use(
/* 404 资源未找到错误 */
if (error.response?.status === 404) {
return Promise.reject(
new NotFoundError(error.response.data?.error_msg || '请求的资源不存在'),
new NotFoundError(
error.response.data?.error_msg ||
runtimeText('the_requested_resource_was_not_found_aecc0681'),
),
);
}
@@ -185,7 +194,8 @@ apiClient.interceptors.response.use(
if (error.response?.status === 400) {
return Promise.reject(
new ValidationError(
error.response.data?.error_msg || '请求参数验证失败',
error.response.data?.error_msg ||
runtimeText('request_parameter_validation_failed_60ef7c51'),
error.response.data?.details,
),
);
@@ -196,9 +206,13 @@ apiClient.interceptors.response.use(
const retryAfter = error.response.headers?.['retry-after'];
const message =
error.response.data?.error_msg ||
`请求过于频繁,请 ${retryAfter || '稍后'} 秒后重试`;
(retryAfter
? runtimeText('too_many_requests_retry_in_value0_seconds_ab5e78f1', {
value0: retryAfter,
})
: runtimeText('rate_limit_retry_later'));
toast.error('请求频率限制', {
toast.error(runtimeText('request_rate_limit_ad4f0f8b'), {
description: message,
id: 'rate-limit-error',
});
@@ -210,7 +224,8 @@ apiClient.interceptors.response.use(
if (error.response && error.response.status >= 500) {
return Promise.reject(
new ServerError(
error.response.data?.error_msg || '服务器内部错误,请稍后重试',
error.response.data?.error_msg ||
runtimeText('internal_server_error_try_again_later_4f0dd7e9'),
error.response.status,
),
);
@@ -230,7 +245,9 @@ apiClient.interceptors.response.use(
error.message?.includes('Failed to fetch')
) {
return Promise.reject(
new NetworkError('无法连接到服务器,请确认后端服务已启动'),
new NetworkError(
runtimeText('cannot_connect_to_the_server_check_that_5551f4fc'),
),
);
}
@@ -247,7 +264,11 @@ apiClient.interceptors.response.use(
}
/* 兜底错误 */
return Promise.reject(new ApiErrorBase(error.message || '网络请求失败'));
return Promise.reject(
new ApiErrorBase(
error.message || runtimeText('network_request_failed_8407ceab'),
),
);
},
);
@@ -260,7 +281,7 @@ export function cancelRequest(method: string, url: string): void {
const requestKey = `${method.toUpperCase()}_${url}`;
const source = cancelTokens.get(requestKey);
if (source) {
source.cancel('请求已被手动取消');
source.cancel(runtimeText('request_canceled_manually_7ba622e6'));
cancelTokens.delete(requestKey);
}
}
@@ -270,7 +291,7 @@ export function cancelRequest(method: string, url: string): void {
*/
export function cancelAllRequests(): void {
cancelTokens.forEach((source) => {
source.cancel('所有请求已被取消');
source.cancel(runtimeText('all_requests_canceled_72f8fa9a'));
});
cancelTokens.clear();
}
+31 -8
View File
@@ -1,3 +1,4 @@
import { getRuntimeTranslator, runtimeText } from '@/i18n/runtime';
/**
* API 错误类型定义
*/
@@ -22,7 +23,11 @@ export class ApiErrorBase extends Error {
* 网络错误
*/
export class NetworkError extends ApiErrorBase {
constructor(message = '网络连接失败,请检查您的网络') {
constructor(
message = runtimeText(
'network_connection_failed_check_your_network_cbf47b07',
),
) {
super(message);
this.name = 'NetworkError';
Object.setPrototypeOf(this, NetworkError.prototype);
@@ -33,7 +38,9 @@ export class NetworkError extends ApiErrorBase {
* 超时错误
*/
export class TimeoutError extends ApiErrorBase {
constructor(message = '请求超时,请稍后重试') {
constructor(
message = runtimeText('request_timed_out_try_again_later_6c3465f6'),
) {
super(message);
this.name = 'TimeoutError';
Object.setPrototypeOf(this, TimeoutError.prototype);
@@ -44,7 +51,7 @@ export class TimeoutError extends ApiErrorBase {
* 未授权错误 (401)
*/
export class UnauthorizedError extends ApiErrorBase {
constructor(message = '未授权,请先登录') {
constructor(message = runtimeText('unauthorized_sign_in_first_466879f5')) {
super(message, 'UNAUTHORIZED', 401);
this.name = 'UnauthorizedError';
Object.setPrototypeOf(this, UnauthorizedError.prototype);
@@ -55,7 +62,11 @@ export class UnauthorizedError extends ApiErrorBase {
* 权限不足错误 (403)
*/
export class ForbiddenError extends ApiErrorBase {
constructor(message = '权限不足', code = 'FORBIDDEN', details?: unknown) {
constructor(
message = runtimeText('insufficient_permissions_5e3c8a26'),
code = 'FORBIDDEN',
details?: unknown,
) {
super(message, code, 403, details);
this.name = 'ForbiddenError';
Object.setPrototypeOf(this, ForbiddenError.prototype);
@@ -66,7 +77,9 @@ export class ForbiddenError extends ApiErrorBase {
* 资源未找到错误 (404)
*/
export class NotFoundError extends ApiErrorBase {
constructor(message = '请求的资源不存在') {
constructor(
message = runtimeText('the_requested_resource_was_not_found_aecc0681'),
) {
super(message, 'NOT_FOUND', 404);
this.name = 'NotFoundError';
Object.setPrototypeOf(this, NotFoundError.prototype);
@@ -77,7 +90,10 @@ export class NotFoundError extends ApiErrorBase {
* 服务器错误 (5xx)
*/
export class ServerError extends ApiErrorBase {
constructor(message = '服务器内部错误,请稍后重试', statusCode = 500) {
constructor(
message = runtimeText('internal_server_error_try_again_later_4f0dd7e9'),
statusCode = 500,
) {
super(message, 'SERVER_ERROR', statusCode);
this.name = 'ServerError';
Object.setPrototypeOf(this, ServerError.prototype);
@@ -88,7 +104,10 @@ export class ServerError extends ApiErrorBase {
* 验证错误 (400)
*/
export class ValidationError extends ApiErrorBase {
constructor(message = '请求参数验证失败', details?: unknown) {
constructor(
message = runtimeText('request_parameter_validation_failed_60ef7c51'),
details?: unknown,
) {
super(message, 'VALIDATION_ERROR', 400, details);
this.name = 'ValidationError';
Object.setPrototypeOf(this, ValidationError.prototype);
@@ -107,6 +126,10 @@ export function isCancelError(error: unknown): boolean {
(('__CANCEL__' in error &&
(error as { __CANCEL__?: boolean }).__CANCEL__ === true) ||
('message' in error &&
(error as { message?: string }).message === '请求已被取消'))
(['en', 'zh-CN'] as const).some(
(locale) =>
(error as { message?: string }).message ===
getRuntimeTranslator(locale)('request_canceled_5892f9b1'),
)))
);
}
+19 -3
View File
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
/**
* task-param-utils.ts
*
@@ -46,7 +47,12 @@ function coerceParamValue(
}
const num = Number(trimmed);
if (Number.isNaN(num)) {
return { error: `「${param.label}」必须是有效的数字`, ok: false };
return {
error: runtimeText('value0_must_be_a_valid_number_1d79f887', {
value0: param.label,
}),
ok: false,
};
}
return { value: num, ok: true };
}
@@ -61,7 +67,12 @@ function coerceParamValue(
} else if (val === 'false') {
return { value: false, ok: true };
}
return { error: `「${param.label}」必须是 true 或 false`, ok: false };
return {
error: runtimeText('value0_must_be_true_or_false_23cce68e', {
value0: param.label,
}),
ok: false,
};
}
case 'string':
case 'text':
@@ -96,7 +107,12 @@ export function buildTaskPayload(
// 必填项空值检查
if (param.required && raw.trim() === '') {
return { payload: null, error: `「${param.label}」不能为空` };
return {
payload: null,
error: runtimeText('value0_must_not_be_empty_8bf3a929', {
value0: param.label,
}),
};
}
const result = coerceParamValue(param, raw);
+6 -2
View File
@@ -1,3 +1,5 @@
import { getFormattingLocale } from '@/i18n/format';
import { runtimeText } from '@/i18n/runtime';
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
@@ -8,7 +10,7 @@ export function cn(...inputs: ClassValue[]) {
export function formatDateTime(dateStr: string | Date) {
try {
const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr;
return new Intl.DateTimeFormat('zh-CN', {
return new Intl.DateTimeFormat(getFormattingLocale(), {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
@@ -61,7 +63,9 @@ export function encodeBase64(value: string): string {
return bufferConstructor.from(value, 'utf-8').toString('base64');
}
throw new Error('当前环境不支持 Base64 编码');
throw new Error(
runtimeText('base64_encoding_is_not_supported_in_this_7642d848'),
);
}
/**
+9 -3
View File
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
import { isCancelError } from '@/lib/services/core';
import { toast } from 'sonner';
@@ -9,6 +10,7 @@ interface HandleContextErrorOptions {
showToast?: boolean;
/** 是否在控制台记录错误 */
logError?: boolean;
logMessage?: string;
}
/**
@@ -37,11 +39,15 @@ export function handleContextError(
defaultMessage: string,
options: HandleContextErrorOptions = {},
): Error {
const { showToast = false, logError = true } = options;
const {
showToast = false,
logError = true,
logMessage = 'Context operation failed',
} = options;
// 取消的请求不算错误
if (isCancelError(error)) {
return new Error('请求已取消');
return new Error(runtimeText('request_canceled_282c4cfb'));
}
const errorMessage = error instanceof Error ? error.message : defaultMessage;
@@ -49,7 +55,7 @@ export function handleContextError(
error instanceof Error ? error : new Error(defaultMessage);
if (logError) {
console.error(defaultMessage, error);
console.error(logMessage, error);
}
if (showToast) {
+14 -5
View File
@@ -1,6 +1,15 @@
const compactNumberFormatter = new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: 1,
});
import { getFormattingLocale } from '@/i18n/format';
const compactNumberFormatters = new Map<string, Intl.NumberFormat>();
function compactNumberFormatter() {
const locale = getFormattingLocale();
let formatter = compactNumberFormatters.get(locale);
if (!formatter) {
formatter = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 });
compactNumberFormatters.set(locale, formatter);
}
return formatter;
}
type FormatBytesOptions = {
emptyText?: string;
@@ -11,7 +20,7 @@ export function formatCompactNumber(value?: number | null) {
if (value === undefined || value === null || Number.isNaN(value)) {
return '—';
}
return compactNumberFormatter.format(value);
return compactNumberFormatter().format(value);
}
export function formatPercent(value?: number | null) {
@@ -43,7 +52,7 @@ export function formatBytes(
}
const digits = current >= 100 || index === 0 ? 0 : 1;
return `${new Intl.NumberFormat('zh-CN', {
return `${new Intl.NumberFormat(getFormattingLocale(), {
maximumFractionDigits: digits,
minimumFractionDigits: 0,
}).format(current)} ${units[index]}`;
+33 -98
View File
@@ -35,11 +35,12 @@ export interface SearchItemSource {
descriptionKey: string;
url: string;
category: 'page' | 'feature' | 'setting' | 'admin';
keywords: string[];
keywordKey: string;
icon?: string;
}
export interface SearchItem extends SearchItemSource {
export interface SearchItem extends Omit<SearchItemSource, 'keywordKey'> {
keywords: string[];
title: string;
description: string;
matchRange?: [number, number];
@@ -57,7 +58,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.homeDesc',
url: '/',
category: 'page',
keywords: ['home', '主页', '首页', 'dashboard', '总览'],
keywordKey: 'search.keywords.home',
},
// ==================== 文档库 ====================
@@ -67,7 +68,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.usageDocsDesc',
url: 'https://openflare.fyrn.link/',
category: 'page',
keywords: ['docs', '文档', '使用', 'how to', 'tutorial', '教程', 'help'],
keywordKey: 'search.keywords.docs-how-to-use',
},
// ==================== 业务控制台 ====================
@@ -77,15 +78,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.nodesDesc',
url: '/nodes',
category: 'page',
keywords: [
'node',
'节点',
'边缘节点',
'中继',
'内网穿透',
'tunnel',
'服务器',
],
keywordKey: 'search.keywords.console-nodes',
},
{
id: 'console-proxy-routes',
@@ -93,7 +86,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.proxyRoutesDesc',
url: '/proxy-routes',
category: 'page',
keywords: ['route', '规则', '路由', '代理', '反向代理', 'proxy'],
keywordKey: 'search.keywords.console-proxy-routes',
},
{
id: 'console-websites',
@@ -101,7 +94,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.websitesDesc',
url: '/websites',
category: 'page',
keywords: ['website', 'domain', '网站', '域名', '站点'],
keywordKey: 'search.keywords.console-websites',
},
{
id: 'console-certificates',
@@ -109,7 +102,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.certificatesDesc',
url: '/certificates',
category: 'page',
keywords: ['certificate', 'ssl', 'tls', '证书', 'https', '加密'],
keywordKey: 'search.keywords.console-certificates',
},
{
id: 'console-dns-accounts',
@@ -117,15 +110,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.dnsAccountsDesc',
url: '/dns-accounts',
category: 'page',
keywords: [
'dns',
'dns account',
'账号',
'域名解析',
'cloudflare',
'aliyun',
'tencent',
],
keywordKey: 'search.keywords.console-dns-accounts',
},
{
id: 'console-origins',
@@ -133,7 +118,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.originsDesc',
url: '/origins',
category: 'page',
keywords: ['origin', '源站', '后端', 'backend', '服务器', '负载均衡'],
keywordKey: 'search.keywords.console-origins',
},
{
id: 'console-responses',
@@ -141,18 +126,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.responsesDesc',
url: '/responses',
category: 'page',
keywords: [
'响应页面',
'错误页',
'联系页',
'源站',
'502',
'503',
'5xx',
'Service Worker',
'离线兜底',
'error page',
],
keywordKey: 'search.keywords.console-responses',
},
{
id: 'console-waf',
@@ -160,7 +134,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.wafDesc',
url: '/waf',
category: 'page',
keywords: ['waf', '防火墙', '安全', 'security', '拦截', '规则'],
keywordKey: 'search.keywords.console-waf',
},
{
id: 'console-ip-groups',
@@ -168,7 +142,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.ipGroupsDesc',
url: '/ip-groups',
category: 'page',
keywords: ['ip', 'ip group', 'ip组', '黑名单', '白名单', '访问控制'],
keywordKey: 'search.keywords.console-ip-groups',
},
{
id: 'console-rate-limits',
@@ -176,14 +150,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.rateLimitsDesc',
url: '/rate-limits',
category: 'page',
keywords: [
'限流',
'rate limit',
'limit_conn',
'limit_rate',
'并发',
'带宽',
],
keywordKey: 'search.keywords.console-rate-limits',
},
{
id: 'console-pages',
@@ -191,7 +158,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.pagesDesc',
url: '/pages',
category: 'page',
keywords: ['pages', '静态托管', 'cdn', '网站', '部署', 'static'],
keywordKey: 'search.keywords.console-pages',
},
{
id: 'console-config-versions',
@@ -199,7 +166,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.configVersionsDesc',
url: '/config-versions',
category: 'page',
keywords: ['version', 'config', '版本', '发布', '回滚', '对比', '部署'],
keywordKey: 'search.keywords.console-config-versions',
},
{
id: 'console-access-logs',
@@ -207,7 +174,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.accessLogsDesc',
url: '/access-logs',
category: 'page',
keywords: ['log', 'logs', '访问日志', '分析', '流量', '请求'],
keywordKey: 'search.keywords.console-access-logs',
},
{
id: 'console-apply-logs',
@@ -215,15 +182,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.applyLogsDesc',
url: '/apply-logs',
category: 'page',
keywords: [
'apply',
'log',
'logs',
'应用记录',
'配置下发',
'同步',
'部署历史',
],
keywordKey: 'search.keywords.console-apply-logs',
},
{
id: 'console-performance',
@@ -231,7 +190,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.performanceDesc',
url: '/performance',
category: 'page',
keywords: ['performance', '性能', '调优', '优化', '参数', '连接', '超时'],
keywordKey: 'search.keywords.console-performance',
},
// ==================== 个人设置 ====================
@@ -241,7 +200,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.settingsDesc',
url: '/settings',
category: 'setting',
keywords: ['settings', '设置', '偏好', 'preferences'],
keywordKey: 'search.keywords.settings',
},
{
id: 'settings-profile',
@@ -249,7 +208,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.profileDesc',
url: '/settings/profile',
category: 'setting',
keywords: ['profile', '资料', '个人', '我的', '信息', 'avatar'],
keywordKey: 'search.keywords.settings-profile',
},
{
id: 'settings-appearance',
@@ -257,7 +216,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.appearanceDesc',
url: '/settings/appearance',
category: 'setting',
keywords: ['appearance', '外观', '主题', 'theme', 'dark', 'light'],
keywordKey: 'search.keywords.settings-appearance',
},
{
id: 'admin-settings',
@@ -265,15 +224,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.adminSettingsDesc',
url: '/admin/settings',
category: 'admin',
keywords: [
'admin',
'管理员',
'系统设置',
'安全',
'security',
'oidc',
'login',
],
keywordKey: 'search.keywords.admin-settings',
},
{
id: 'admin-system',
@@ -281,7 +232,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.systemDesc',
url: '/admin/system',
category: 'admin',
keywords: ['admin', '管理员', '系统', '配置', 'system', 'configurations'],
keywordKey: 'search.keywords.admin-system',
},
{
id: 'admin-users',
@@ -289,7 +240,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.usersDesc',
url: '/admin/users',
category: 'admin',
keywords: ['admin', '管理员', '用户', '管理', 'users', 'status'],
keywordKey: 'search.keywords.admin-users',
},
{
id: 'admin-tasks',
@@ -297,15 +248,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.tasksDesc',
url: '/admin/tasks',
category: 'admin',
keywords: [
'admin',
'管理员',
'任务',
'异步',
'tasks',
'scheduler',
'worker',
],
keywordKey: 'search.keywords.admin-tasks',
},
{
id: 'admin-files',
@@ -313,7 +256,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.storageDesc',
url: '/admin/files',
category: 'admin',
keywords: ['admin', '管理员', '存储', '文件', 'files', 'upload', 's3'],
keywordKey: 'search.keywords.admin-files',
},
{
id: 'admin-database',
@@ -321,7 +264,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.databaseDesc',
url: '/admin/database',
category: 'admin',
keywords: ['admin', '管理员', '数据库', 'database', 'sql', 'query', 'gorm'],
keywordKey: 'search.keywords.admin-database',
},
{
id: 'admin-push',
@@ -329,16 +272,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.pushDesc',
url: '/admin/push',
category: 'admin',
keywords: [
'admin',
'管理员',
'推送',
'通知',
'push',
'mail',
'telegram',
'lark',
],
keywordKey: 'search.keywords.admin-push',
},
{
id: 'admin-logs',
@@ -346,7 +280,7 @@ export const searchData: SearchItemSource[] = [
descriptionKey: 'search.items.logsDesc',
url: '/admin/logs',
category: 'admin',
keywords: ['admin', '管理员', '日志', 'logs', 'system log', 'terminal'],
keywordKey: 'search.keywords.admin-logs',
},
];
@@ -369,10 +303,11 @@ export function searchItems(
? searchData
: searchData.filter((item) => item.category !== 'admin');
const resolved = filteredData.map((item) => ({
const resolved: SearchItem[] = filteredData.map((item) => ({
...item,
title: t(item.titleKey),
description: t(item.descriptionKey),
keywords: t(item.keywordKey).split('|'),
}));
if (!trimmedQuery) {