mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): add Antigravity host UI localization and language packs
- Add standalone host-i18n language pack manager with GitHub/jsDelivr download, SHA-256 integrity checks, offline light/deep tier switching, and lossless DOM translation over the CDP window bridge - Add Settings -> General host interface language controls, untranslated UI string collector, and loopback-only /api/host-i18n endpoints - Include zh-CN layered language pack assets and source/audit/build scripts under host-i18n/ while keeping the Release ZIP runtime whitelist isolated
This commit is contained in:
@@ -66,12 +66,19 @@ import {
|
||||
triggerDesktopHostRelaunch,
|
||||
} from './desktop-launcher-config.mjs';
|
||||
import {
|
||||
collectHostI18nUntranslatedFromActiveTargets,
|
||||
ensureIdeRemoteDebuggingArgv,
|
||||
getDefaultWindowBridgeStatus,
|
||||
notifyHostI18nChanged,
|
||||
notifyModelContextWindowsChanged,
|
||||
notifyWindowOverlaySetting,
|
||||
resolveDevToolsPortCandidates,
|
||||
startDefaultWindowBridge,
|
||||
} from './window-bridge.mjs';
|
||||
import {
|
||||
handleHostI18nGetRequest,
|
||||
handleHostI18nPostAction,
|
||||
} from './host-i18n/index.mjs';
|
||||
import { getQuotaReservationLogSnapshot } from './quota-reservation.mjs';
|
||||
import { getSessionMigrationCatalog, migrateSessions } from './session-migrator.mjs';
|
||||
import {
|
||||
@@ -867,6 +874,37 @@ export function executeQuotaReservationLogAction() {
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeHostI18nGetAction(opts = {}) {
|
||||
const result = await handleHostI18nGetRequest({
|
||||
bridgeStatus: getDefaultWindowBridgeStatus(),
|
||||
...(opts?.hostI18nManager ? { manager: opts.hostI18nManager } : {}),
|
||||
});
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(result),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeHostI18nPostAction(data = {}, opts = {}) {
|
||||
const out = await handleHostI18nPostAction(isPlainObject(data) ? data : {}, {
|
||||
bridgeStatus: getDefaultWindowBridgeStatus(),
|
||||
onChanged: typeof opts?.onHostI18nChanged === 'function' ? opts.onHostI18nChanged : notifyHostI18nChanged,
|
||||
collectFromTargets:
|
||||
typeof opts?.collectHostI18nUntranslated === 'function'
|
||||
? opts.collectHostI18nUntranslated
|
||||
: collectHostI18nUntranslatedFromActiveTargets,
|
||||
...(opts?.hostI18nManager ? { manager: opts.hostI18nManager } : {}),
|
||||
});
|
||||
return {
|
||||
status: Number(out?.status || 200),
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(out?.payload || { ok: false, error: 'Invalid host-i18n response' }),
|
||||
};
|
||||
}
|
||||
|
||||
export function executeRevealFileAction(data, opts = {}) {
|
||||
const result = revealLocalExportFile(data?.filePath, {
|
||||
...(opts?.platform ? { platform: opts.platform } : {}),
|
||||
@@ -911,6 +949,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
|
||||
if (isPlainObject(data) && data.__quotaReservationAction === 'log') {
|
||||
return executeQuotaReservationLogAction();
|
||||
}
|
||||
if (isPlainObject(data) && typeof data.__hostI18nAction === 'string') {
|
||||
if (data.__hostI18nAction === 'get') {
|
||||
return executeHostI18nGetAction(opts);
|
||||
}
|
||||
return executeHostI18nPostAction(
|
||||
{ ...(isPlainObject(data.payload) ? data.payload : {}), action: data.__hostI18nAction },
|
||||
opts
|
||||
);
|
||||
}
|
||||
return executeSettingsAction(data);
|
||||
case 'accounts_get':
|
||||
return executeAccountCredentialAction(undefined, opts);
|
||||
@@ -938,6 +985,10 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
|
||||
return executeRevealFileAction(data, opts);
|
||||
case 'quota_reservation_log':
|
||||
return executeQuotaReservationLogAction();
|
||||
case 'host_i18n_get':
|
||||
return executeHostI18nGetAction(opts);
|
||||
case 'host_i18n_action':
|
||||
return executeHostI18nPostAction(data, opts);
|
||||
default:
|
||||
return {
|
||||
status: 404,
|
||||
|
||||
@@ -382,7 +382,7 @@ export function computeRuntimeCodeVersion(options = {}) {
|
||||
join(HERE, 'trajectory-metrics.mjs'),
|
||||
LOCAL_CATALOG_FILE,
|
||||
];
|
||||
for (const subDir of ['shared', 'backend']) {
|
||||
for (const subDir of ['shared', 'backend', join('backend', 'host-i18n')]) {
|
||||
const absDir = join(HERE, subDir);
|
||||
try {
|
||||
if (existsSync(absDir)) {
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* @fileoverview 受控的 Antigravity 宿主语言包 HTTPS 拉取器。
|
||||
*
|
||||
* - 严格限制仅允许官方白名单域名(`raw.githubusercontent.com` / `cdn.jsdelivr.net`);
|
||||
* - 复用 `cloudcode-proxy.mjs` 的系统 HTTPS 代理检测与 CONNECT 隧道,兼容代理环境;
|
||||
* - 主源超时或 5xx/网络失败时自动回退至 jsDelivr CDN 镜像;
|
||||
* - 响应体严格限制大小上限,避免异常大载荷撑爆内存。
|
||||
*/
|
||||
|
||||
import { detectSystemHttpsProxy, openCcProxyTunnelSocket } from '../cloudcode-proxy.mjs';
|
||||
|
||||
export const HOST_I18N_ALLOWED_HOSTS = Object.freeze([
|
||||
'raw.githubusercontent.com',
|
||||
'cdn.jsdelivr.net',
|
||||
]);
|
||||
export const HOST_I18N_MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
|
||||
export const HOST_I18N_DEFAULT_TIMEOUT_MS = 8_000;
|
||||
const HOST_I18N_MAX_REDIRECTS = 3;
|
||||
|
||||
let hostI18nNetModulesPromise = null;
|
||||
|
||||
async function loadHostI18nNetModules() {
|
||||
if (!hostI18nNetModulesPromise) {
|
||||
hostI18nNetModulesPromise = Promise.all([
|
||||
import('node:http'),
|
||||
import('node:https'),
|
||||
import('node:net'),
|
||||
import('node:tls'),
|
||||
]).then(([httpMod, httpsMod, netMod, tlsMod]) => ({
|
||||
http: httpMod.default || httpMod,
|
||||
https: httpsMod.default || httpsMod,
|
||||
net: netMod.default || netMod,
|
||||
tls: tlsMod.default || tlsMod,
|
||||
}));
|
||||
}
|
||||
return hostI18nNetModulesPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验下载 URL 是否属于允许的 HTTPS 白名单源。
|
||||
*
|
||||
* @param {string} rawUrl
|
||||
* @returns {URL}
|
||||
*/
|
||||
export function assertAllowedHostI18nUrl(rawUrl) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(String(rawUrl || '').trim());
|
||||
} catch {
|
||||
throw new Error('Invalid host-i18n download URL');
|
||||
}
|
||||
if (parsed.protocol !== 'https:') {
|
||||
throw new Error(`Unsupported host-i18n protocol: ${parsed.protocol}`);
|
||||
}
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
if (!HOST_I18N_ALLOWED_HOSTS.includes(host)) {
|
||||
throw new Error(`Disallowed host-i18n host: ${host}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过原生 `https` + 系统 HTTPS 代理隧道拉取单个白名单 URL 的 UTF-8 文本。
|
||||
*
|
||||
* @param {string} rawUrl
|
||||
* @param {{ timeoutMs?: number, maxBytes?: number, redirectCount?: number }} [options]
|
||||
* @returns {Promise<{ ok: boolean, status: number, text: string, url: string }>}
|
||||
*/
|
||||
async function fetchAllowedUrlViaNodeHttps(
|
||||
rawUrl,
|
||||
{
|
||||
timeoutMs = HOST_I18N_DEFAULT_TIMEOUT_MS,
|
||||
maxBytes = HOST_I18N_MAX_RESPONSE_BYTES,
|
||||
redirectCount = 0,
|
||||
} = {}
|
||||
) {
|
||||
const target = assertAllowedHostI18nUrl(rawUrl);
|
||||
const mods = await loadHostI18nNetModules();
|
||||
const { http, https, net, tls } = mods;
|
||||
|
||||
const proxy = await detectSystemHttpsProxy(target.hostname).catch(() => null);
|
||||
const socket = proxy
|
||||
? await openCcProxyTunnelSocket(
|
||||
{ http, https, net, tls },
|
||||
target.hostname,
|
||||
Number(target.port || 443),
|
||||
proxy,
|
||||
{ timeoutMs: Math.min(timeoutMs, 5_000) }
|
||||
)
|
||||
: null;
|
||||
|
||||
let socketConsumed = false;
|
||||
const agent = socket ? new https.Agent({ keepAlive: false }) : null;
|
||||
if (agent) {
|
||||
agent.createConnection = () => {
|
||||
socketConsumed = true;
|
||||
return socket;
|
||||
};
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (ok, value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (!socketConsumed) {
|
||||
try {
|
||||
socket?.destroy();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
try {
|
||||
agent?.destroy();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
if (ok) resolve(value);
|
||||
else reject(value);
|
||||
};
|
||||
|
||||
const req = https.request(
|
||||
target,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json, text/plain;q=0.9',
|
||||
'Cache-Control': 'no-cache',
|
||||
'User-Agent': 'antigravity-usage-monitor-host-i18n/1.0',
|
||||
},
|
||||
...(agent ? { agent } : {}),
|
||||
},
|
||||
(res) => {
|
||||
const status = Number(res.statusCode || 0);
|
||||
if (
|
||||
(status === 301 || status === 302 || status === 307 || status === 308) &&
|
||||
res.headers?.location &&
|
||||
redirectCount < HOST_I18N_MAX_REDIRECTS
|
||||
) {
|
||||
res.resume();
|
||||
let nextUrl = '';
|
||||
try {
|
||||
nextUrl = new URL(String(res.headers.location), target).href;
|
||||
assertAllowedHostI18nUrl(nextUrl);
|
||||
} catch (err) {
|
||||
finish(false, err);
|
||||
return;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
fetchAllowedUrlViaNodeHttps(nextUrl, {
|
||||
timeoutMs,
|
||||
maxBytes,
|
||||
redirectCount: redirectCount + 1,
|
||||
}).then(
|
||||
(val) => finish(true, val),
|
||||
(err) => finish(false, err)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks = [];
|
||||
let totalBytes = 0;
|
||||
res.on('data', (chunk) => {
|
||||
totalBytes += chunk.length;
|
||||
if (totalBytes > maxBytes) {
|
||||
req.destroy(new Error(`host-i18n response exceeds ${maxBytes} bytes`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on('error', (err) => finish(false, err));
|
||||
res.on('end', () => {
|
||||
const text = Buffer.concat(chunks).toString('utf8');
|
||||
finish(true, {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
text,
|
||||
url: target.href,
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
req.destroy(new Error(`host-i18n request timeout after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
|
||||
req.on('error', (err) => finish(false, err));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 依次尝试多个白名单候选 URL(主源 GitHub Raw -> 备用 jsDelivr CDN),返回首个成功的文本响应。
|
||||
*
|
||||
* @param {string[]} urls
|
||||
* @param {{
|
||||
* timeoutMs?: number,
|
||||
* maxBytes?: number,
|
||||
* fetchImpl?: ((url: string, init?: object) => Promise<{ ok: boolean, status?: number, text: () => Promise<string> }>)|null,
|
||||
* }} [options]
|
||||
* @returns {Promise<{ text: string, url: string, status: number }>}
|
||||
*/
|
||||
export async function fetchHostI18nTextWithFallback(
|
||||
urls,
|
||||
{
|
||||
timeoutMs = HOST_I18N_DEFAULT_TIMEOUT_MS,
|
||||
maxBytes = HOST_I18N_MAX_RESPONSE_BYTES,
|
||||
fetchImpl = null,
|
||||
} = {}
|
||||
) {
|
||||
const list = Array.isArray(urls) ? urls.filter(Boolean) : [];
|
||||
if (list.length === 0) {
|
||||
throw new Error('No host-i18n candidate URLs configured');
|
||||
}
|
||||
|
||||
const errors = [];
|
||||
for (const rawUrl of list) {
|
||||
const validated = assertAllowedHostI18nUrl(rawUrl);
|
||||
try {
|
||||
if (typeof fetchImpl === 'function') {
|
||||
const res = await fetchImpl(validated.href, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json', 'Cache-Control': 'no-cache' },
|
||||
signal:
|
||||
typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
|
||||
? AbortSignal.timeout(timeoutMs)
|
||||
: undefined,
|
||||
});
|
||||
const status = Number(res?.status || (res?.ok ? 200 : 500));
|
||||
if (!res?.ok) {
|
||||
throw new Error(`HTTP ${status}`);
|
||||
}
|
||||
const text = await res.text();
|
||||
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
|
||||
throw new Error(`host-i18n response exceeds ${maxBytes} bytes`);
|
||||
}
|
||||
return { text, url: validated.href, status };
|
||||
}
|
||||
|
||||
const res = await fetchAllowedUrlViaNodeHttps(validated.href, { timeoutMs, maxBytes });
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
return { text: res.text, url: res.url, status: res.status };
|
||||
} catch (err) {
|
||||
errors.push(`${validated.hostname}: ${err?.message || 'request failed'}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed to fetch host-i18n asset (${errors.join('; ')})`);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* @fileoverview Antigravity 宿主多语言子系统统一门面 (`backend/host-i18n/index.mjs`)。
|
||||
*
|
||||
* 主程序其余模块(`window-bridge.mjs`、`api-actions.mjs`)仅通过本门面与宿主翻译子系统交互,
|
||||
* 保持极薄的集成边界与完整可剥离性。
|
||||
*/
|
||||
|
||||
import {
|
||||
HOST_I18N_DEFAULT_DEPTH,
|
||||
HOST_I18N_OFF_LOCALE,
|
||||
normalizeHostI18nDepth,
|
||||
normalizeHostI18nLocale,
|
||||
} from '../../shared/host-i18n-protocol.mjs';
|
||||
import { createHostI18nPackManager } from './pack-manager.mjs';
|
||||
import {
|
||||
createHostI18nApplyExpression,
|
||||
createHostI18nCollectExpression,
|
||||
createHostI18nDisposeExpression,
|
||||
createHostI18nHeartbeatExpression,
|
||||
} from './runtime-translator.mjs';
|
||||
|
||||
export {
|
||||
HOST_I18N_DEFAULT_DEPTH,
|
||||
HOST_I18N_OFF_LOCALE,
|
||||
createHostI18nApplyExpression,
|
||||
createHostI18nCollectExpression,
|
||||
createHostI18nDisposeExpression,
|
||||
createHostI18nHeartbeatExpression,
|
||||
createHostI18nPackManager,
|
||||
normalizeHostI18nDepth,
|
||||
normalizeHostI18nLocale,
|
||||
};
|
||||
|
||||
let defaultHostI18nManager = null;
|
||||
|
||||
/**
|
||||
* 获取进程级默认宿主语言包管理器单例。
|
||||
*/
|
||||
export function getDefaultHostI18nManager() {
|
||||
if (!defaultHostI18nManager) {
|
||||
defaultHostI18nManager = createHostI18nPackManager();
|
||||
}
|
||||
return defaultHostI18nManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 供 `window-bridge.mjs` 读取当前宿主翻译是否激活及按需下发描述。
|
||||
*/
|
||||
export function getHostI18nBridgeDescriptor() {
|
||||
return getDefaultHostI18nManager().getActiveBridgeDescriptor();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断宿主语言翻译当前是否处于激活状态(用于独立保活 CDP 调试端口)。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isHostI18nActiveForBridge() {
|
||||
return Boolean(getHostI18nBridgeDescriptor()?.active);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 `GET /api/host-i18n`:返回当前状态、已安装包与远端语言清单(必要时静默拉取缓存清单)。
|
||||
*
|
||||
* @param {{ bridgeStatus?: object|null, manager?: ReturnType<typeof createHostI18nPackManager> }} [options]
|
||||
*/
|
||||
export async function handleHostI18nGetRequest({ bridgeStatus = null, manager = null } = {}) {
|
||||
const mgr = manager || getDefaultHostI18nManager();
|
||||
const manifestResult = await mgr.refreshManifest({ force: false });
|
||||
return {
|
||||
ok: true,
|
||||
...mgr.getStatusSnapshot({ manifestResult, bridgeStatus }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 `POST /api/host-i18n` 控制指令:
|
||||
* - `refresh_manifest`:强制刷新仓库语言包清单
|
||||
* - `select`:选择语言(未下载时自动拉取并校验 SHA-256 后生效,传 `'off'` 即关闭并还原)
|
||||
* - `set_depth`:在 `'light'` / `'deep'` 间零网络热切换
|
||||
* - `install` / `update`:显式下载或更新指定语言包
|
||||
* - `remove`:删除指定语言的本地缓存包
|
||||
* - `collect_untranslated`:按需采集当前打开宿主页面中未翻译的英文 UI 短语
|
||||
*
|
||||
* @param {object} body
|
||||
* @param {{
|
||||
* bridgeStatus?: object|null,
|
||||
* onChanged?: (() => Promise<any>|any)|null,
|
||||
* collectFromTargets?: (() => Promise<{ targets: number, items: Array<{ text: string, kind: string, count: number }> }>)|null,
|
||||
* manager?: ReturnType<typeof createHostI18nPackManager>|null,
|
||||
* }} [options]
|
||||
*/
|
||||
export async function handleHostI18nPostAction(
|
||||
body = {},
|
||||
{ bridgeStatus = null, onChanged = null, collectFromTargets = null, manager = null } = {}
|
||||
) {
|
||||
const mgr = manager || getDefaultHostI18nManager();
|
||||
const action = String(body?.action || '').trim().toLowerCase();
|
||||
|
||||
try {
|
||||
if (action === 'refresh_manifest') {
|
||||
const manifestResult = await mgr.refreshManifest({ force: true });
|
||||
return {
|
||||
status: 200,
|
||||
payload: {
|
||||
ok: manifestResult.ok,
|
||||
...(manifestResult.error ? { error: manifestResult.error } : {}),
|
||||
...mgr.getStatusSnapshot({ manifestResult, bridgeStatus }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (action === 'select') {
|
||||
const res = await mgr.selectLanguage({
|
||||
locale: body?.locale,
|
||||
depth: body?.depth,
|
||||
});
|
||||
await Promise.resolve(onChanged?.()).catch(() => {});
|
||||
return {
|
||||
status: 200,
|
||||
payload: {
|
||||
ok: true,
|
||||
downloaded: Boolean(res.downloaded),
|
||||
...mgr.getStatusSnapshot({ bridgeStatus }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (action === 'set_depth') {
|
||||
mgr.setDepth(body?.depth);
|
||||
await Promise.resolve(onChanged?.()).catch(() => {});
|
||||
return {
|
||||
status: 200,
|
||||
payload: {
|
||||
ok: true,
|
||||
...mgr.getStatusSnapshot({ bridgeStatus }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (action === 'install' || action === 'update') {
|
||||
const res = await mgr.installPack(body?.locale, { forceManifestRefresh: true });
|
||||
const cur = mgr.loadState();
|
||||
if (cur.locale === res.locale) {
|
||||
await Promise.resolve(onChanged?.()).catch(() => {});
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
payload: {
|
||||
ok: true,
|
||||
installed: res,
|
||||
...mgr.getStatusSnapshot({ bridgeStatus }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (action === 'remove') {
|
||||
const res = mgr.removePack(body?.locale);
|
||||
await Promise.resolve(onChanged?.()).catch(() => {});
|
||||
return {
|
||||
status: res.ok ? 200 : 400,
|
||||
payload: {
|
||||
ok: res.ok,
|
||||
...(res.error ? { error: res.error } : {}),
|
||||
...mgr.getStatusSnapshot({ bridgeStatus }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (action === 'collect_untranslated') {
|
||||
if (typeof collectFromTargets !== 'function') {
|
||||
return {
|
||||
status: 400,
|
||||
payload: { ok: false, error: 'collector_unavailable', count: 0, items: [], template: { base: {} } },
|
||||
};
|
||||
}
|
||||
const collected = await collectFromTargets();
|
||||
const items = Array.isArray(collected?.items) ? collected.items : [];
|
||||
const templateBase = {};
|
||||
for (const item of items) {
|
||||
if (item?.text) templateBase[item.text] = '';
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
payload: {
|
||||
ok: true,
|
||||
targets: Number(collected?.targets || 0),
|
||||
count: items.length,
|
||||
items,
|
||||
template: { base: templateBase },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 400,
|
||||
payload: { ok: false, error: `Unknown host-i18n action: ${action || '(empty)'}` },
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
status: 500,
|
||||
payload: {
|
||||
ok: false,
|
||||
error: err?.message || 'Host I18n action failed',
|
||||
...mgr.getStatusSnapshot({ bridgeStatus }),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,799 @@
|
||||
/**
|
||||
* @fileoverview 独立解耦的 Antigravity 宿主语言包状态、远端清单同步、SHA-256 校验与本地缓存管理器。
|
||||
*
|
||||
* 持久化边界:
|
||||
* 全部落盘在 `DATA_DIR/host-i18n/` 下,与主插件 `settings.json` 及监控遥测状态完全隔离:
|
||||
* - `state.json` :当前选中的 `locale`(`'off'` 或 BCP-47)与 `depth`(`'light' | 'deep'`)
|
||||
* - `manifest-cache.json` :远端仓库可用语言包清单缓存
|
||||
* - `installed-meta.json` :已下载语言包元信息索引
|
||||
* - `packs/<locale>.json` :通过 SHA-256 校验后的单语言分层语言包本体
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
HOST_I18N_DEFAULT_DEPTH,
|
||||
HOST_I18N_OFF_LOCALE,
|
||||
HOST_I18N_SCHEMA_VERSION,
|
||||
normalizeHostI18nDepth,
|
||||
normalizeHostI18nLocale,
|
||||
} from '../../shared/host-i18n-protocol.mjs';
|
||||
import { DATA_DIR, OFFICIAL_GITHUB_REPO, detectCustomGitForkRepo } from '../config.mjs';
|
||||
import { writeJsonAtomicSync, writeTextFileAtomicSync } from '../fs-atomic.mjs';
|
||||
import { isPlainObject } from '../http-helpers.mjs';
|
||||
import { fetchHostI18nTextWithFallback } from './http-fetch.mjs';
|
||||
|
||||
export const DEFAULT_HOST_I18N_REF = 'main';
|
||||
export const HOST_I18N_MANIFEST_TTL_MS = 6 * 3600 * 1000;
|
||||
const HOST_I18N_SHA256_RE = /^[a-f0-9]{64}$/i;
|
||||
const HOST_I18N_ALLOWED_REGEX_FLAGS_RE = /^[i]?$/;
|
||||
const HOST_I18N_UNSAFE_REGEX_RE = /\([^)]*[+*][^)]*\)[+*{]/;
|
||||
|
||||
function hostI18nSha256(text) {
|
||||
return createHash('sha256').update(String(text || ''), 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
function hostI18nResolveStoragePaths(baseDataDir = DATA_DIR) {
|
||||
const rootDir = join(baseDataDir, 'host-i18n');
|
||||
return {
|
||||
rootDir,
|
||||
stateFile: join(rootDir, 'state.json'),
|
||||
manifestCacheFile: join(rootDir, 'manifest-cache.json'),
|
||||
installedMetaFile: join(rootDir, 'installed-meta.json'),
|
||||
packsDir: join(rootDir, 'packs'),
|
||||
};
|
||||
}
|
||||
|
||||
function hostI18nResolveRepoAndRef(options = {}) {
|
||||
const envRepo = String(process?.env?.USAGE_MONITOR_HOST_I18N_REPO || '').trim();
|
||||
const repo =
|
||||
String(options?.repo || '').trim() ||
|
||||
envRepo ||
|
||||
detectCustomGitForkRepo() ||
|
||||
OFFICIAL_GITHUB_REPO;
|
||||
const envRef = String(process?.env?.USAGE_MONITOR_HOST_I18N_REF || '').trim();
|
||||
const ref = String(options?.ref || '').trim() || envRef || DEFAULT_HOST_I18N_REF;
|
||||
const localDir =
|
||||
String(options?.localSourceDir || '').trim() ||
|
||||
String(process?.env?.USAGE_MONITOR_HOST_I18N_LOCAL_DIR || '').trim();
|
||||
return { repo, ref, localDir };
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建仓库内语言包文件的主/备下载 URL(GitHub Raw 主源 + jsDelivr 镜像兜底)。
|
||||
*
|
||||
* @param {string} relPath 如 `'manifest.json'` 或 `'packs/zh-CN.json'`
|
||||
* @param {{ repo?: string, ref?: string }} [options]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function buildHostI18nAssetUrls(relPath, options = {}) {
|
||||
const cleanRel = String(relPath || '')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^\/+/, '');
|
||||
if (!cleanRel || cleanRel.includes('..')) {
|
||||
throw new Error(`Invalid host-i18n relative asset path: ${relPath}`);
|
||||
}
|
||||
const { repo, ref } = hostI18nResolveRepoAndRef(options);
|
||||
return [
|
||||
`https://raw.githubusercontent.com/${repo}/${ref}/host-i18n/dist/${cleanRel}`,
|
||||
`https://cdn.jsdelivr.net/gh/${repo}@${ref}/host-i18n/dist/${cleanRel}`,
|
||||
];
|
||||
}
|
||||
|
||||
function sanitizeHostI18nExactMap(rawMap) {
|
||||
const out = {};
|
||||
if (!isPlainObject(rawMap)) return out;
|
||||
for (const [k, v] of Object.entries(rawMap)) {
|
||||
const key = String(k || '').replace(/\r\n/g, '\n').trim();
|
||||
const val = typeof v === 'string' ? v.replace(/\r\n/g, '\n').trim() : '';
|
||||
if (!key || !val || key.length > 1000 || val.length > 1500) continue;
|
||||
out[key] = val;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sanitizeHostI18nPatterns(rawList) {
|
||||
const out = [];
|
||||
if (!Array.isArray(rawList)) return out;
|
||||
for (const item of rawList) {
|
||||
if (!isPlainObject(item)) continue;
|
||||
const source = typeof item.source === 'string' ? item.source : '';
|
||||
const flags = typeof item.flags === 'string' ? item.flags : '';
|
||||
const replace = typeof item.replace === 'string' ? item.replace : '';
|
||||
const hint = typeof item.hint === 'string' ? item.hint.trim() : '';
|
||||
if (!source || source.length > 360 || !source.startsWith('^') || !source.endsWith('$')) {
|
||||
continue;
|
||||
}
|
||||
if (!HOST_I18N_ALLOWED_REGEX_FLAGS_RE.test(flags) || HOST_I18N_UNSAFE_REGEX_RE.test(source)) {
|
||||
continue;
|
||||
}
|
||||
if (!replace || replace.length > 800) continue;
|
||||
try {
|
||||
// 校验正则可合法编译
|
||||
// eslint-disable-next-line no-new
|
||||
new RegExp(source, flags);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
out.push(hint ? { source, flags, replace, hint } : { source, flags, replace });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范化远端或本地的 `manifest.json` 载荷。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {{ schemaVersion: number, packs: Array<object> }}
|
||||
*/
|
||||
export function sanitizeHostI18nManifest(raw) {
|
||||
if (!isPlainObject(raw)) {
|
||||
throw new Error('Invalid host-i18n manifest payload');
|
||||
}
|
||||
const schemaVersion = Number(raw.schemaVersion || 0);
|
||||
if (schemaVersion !== HOST_I18N_SCHEMA_VERSION) {
|
||||
throw new Error(`Unsupported host-i18n manifest schemaVersion: ${schemaVersion}`);
|
||||
}
|
||||
const rawPacks = Array.isArray(raw.packs) ? raw.packs : [];
|
||||
const packs = [];
|
||||
const seen = new Set();
|
||||
for (const item of rawPacks) {
|
||||
if (!isPlainObject(item)) continue;
|
||||
const locale = normalizeHostI18nLocale(item.locale);
|
||||
if (locale === HOST_I18N_OFF_LOCALE || seen.has(locale)) continue;
|
||||
const sha256 = String(item.sha256 || '').trim().toLowerCase();
|
||||
const version = String(item.version || '').trim();
|
||||
const file = String(item.file || `packs/${locale}.json`)
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^\/+/, '');
|
||||
if (!HOST_I18N_SHA256_RE.test(sha256) || !version || file.includes('..') || !file.endsWith('.json')) {
|
||||
continue;
|
||||
}
|
||||
seen.add(locale);
|
||||
packs.push({
|
||||
locale,
|
||||
name: String(item.name || locale).trim(),
|
||||
nativeName: String(item.nativeName || item.name || locale).trim(),
|
||||
version,
|
||||
file,
|
||||
sha256,
|
||||
bytes: Math.max(0, Number(item.bytes || 0) || 0),
|
||||
depths: Array.isArray(item.depths)
|
||||
? item.depths.map((d) => normalizeHostI18nDepth(d)).filter((v, i, a) => a.indexOf(v) === i)
|
||||
: ['light', 'deep'],
|
||||
stats: isPlainObject(item.stats)
|
||||
? {
|
||||
baseExact: Number(item.stats.baseExact || 0) || 0,
|
||||
lightExact: Number(item.stats.lightExact || 0) || 0,
|
||||
deepExact: Number(item.stats.deepExact || 0) || 0,
|
||||
basePatterns: Number(item.stats.basePatterns || 0) || 0,
|
||||
lightPatterns: Number(item.stats.lightPatterns || 0) || 0,
|
||||
deepPatterns: Number(item.stats.deepPatterns || 0) || 0,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
}
|
||||
return { schemaVersion, packs };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范化单个语言包 JSON 内容。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @param {string} expectedLocale
|
||||
*/
|
||||
export function sanitizeHostI18nPack(raw, expectedLocale = '') {
|
||||
if (!isPlainObject(raw)) {
|
||||
throw new Error('Invalid host-i18n pack payload');
|
||||
}
|
||||
const schemaVersion = Number(raw.schemaVersion || 0);
|
||||
if (schemaVersion !== HOST_I18N_SCHEMA_VERSION) {
|
||||
throw new Error(`Unsupported host-i18n pack schemaVersion: ${schemaVersion}`);
|
||||
}
|
||||
const locale = normalizeHostI18nLocale(raw.locale);
|
||||
if (locale === HOST_I18N_OFF_LOCALE) {
|
||||
throw new Error('Invalid locale in host-i18n pack');
|
||||
}
|
||||
if (expectedLocale && locale !== normalizeHostI18nLocale(expectedLocale)) {
|
||||
throw new Error(`Pack locale mismatch: expected ${expectedLocale}, got ${locale}`);
|
||||
}
|
||||
const version = String(raw.version || '').trim();
|
||||
if (!version) {
|
||||
throw new Error('Missing version in host-i18n pack');
|
||||
}
|
||||
const baseExact = sanitizeHostI18nExactMap(raw.base?.exact);
|
||||
const basePatterns = sanitizeHostI18nPatterns(raw.base?.patterns);
|
||||
const lightExact = sanitizeHostI18nExactMap(raw.modes?.light?.exact);
|
||||
const lightPatterns = sanitizeHostI18nPatterns(raw.modes?.light?.patterns);
|
||||
const deepExact = sanitizeHostI18nExactMap(raw.modes?.deep?.exact);
|
||||
const deepPatterns = sanitizeHostI18nPatterns(raw.modes?.deep?.patterns);
|
||||
|
||||
return {
|
||||
schemaVersion,
|
||||
locale,
|
||||
name: String(raw.name || locale).trim(),
|
||||
nativeName: String(raw.nativeName || raw.name || locale).trim(),
|
||||
version,
|
||||
base: { exact: baseExact, patterns: basePatterns },
|
||||
modes: {
|
||||
light: { exact: lightExact, patterns: lightPatterns },
|
||||
deep: { exact: deepExact, patterns: deepPatterns },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function hostI18nPatternSpecificityScore(source) {
|
||||
const s = String(source || '');
|
||||
let literalChars = 0;
|
||||
let parenDepth = 0;
|
||||
let inCharClass = false;
|
||||
for (let i = 0; i < s.length; i += 1) {
|
||||
const ch = s[i];
|
||||
if (ch === '\\' && i + 1 < s.length) {
|
||||
const next = s[i + 1];
|
||||
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
|
||||
literalChars += 1;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '[' && !inCharClass) {
|
||||
inCharClass = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === ']' && inCharClass) {
|
||||
inCharClass = false;
|
||||
continue;
|
||||
}
|
||||
if (inCharClass) continue;
|
||||
if (ch === '(') {
|
||||
parenDepth += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === ')') {
|
||||
if (parenDepth > 0) parenDepth -= 1;
|
||||
continue;
|
||||
}
|
||||
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
|
||||
literalChars += 1;
|
||||
}
|
||||
}
|
||||
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
|
||||
const typedCaptures = (s.match(/\\d\+/g) || []).length;
|
||||
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据语言包与深/浅档位合成运行期单层查找载荷。
|
||||
*
|
||||
* @param {object} pack
|
||||
* @param {'light'|'deep'} depth
|
||||
* @param {string} sha256
|
||||
*/
|
||||
export function compileHostI18nRuntimePayload(pack, depth, sha256 = '') {
|
||||
const safeDepth = normalizeHostI18nDepth(depth);
|
||||
const modeBucket = safeDepth === 'deep' ? pack?.modes?.deep : pack?.modes?.light;
|
||||
const exact = {
|
||||
...(pack?.base?.exact || {}),
|
||||
...(modeBucket?.exact || {}),
|
||||
};
|
||||
const taggedPatterns = [
|
||||
...(Array.isArray(pack?.base?.patterns)
|
||||
? pack.base.patterns.map((rule) => ({ rule, tierRank: 0 }))
|
||||
: []),
|
||||
...(Array.isArray(modeBucket?.patterns)
|
||||
? modeBucket.patterns.map((rule) => ({ rule, tierRank: 1 }))
|
||||
: []),
|
||||
];
|
||||
taggedPatterns.sort((a, b) => {
|
||||
const scoreDiff =
|
||||
hostI18nPatternSpecificityScore(b.rule?.source) -
|
||||
hostI18nPatternSpecificityScore(a.rule?.source);
|
||||
if (scoreDiff !== 0) return scoreDiff;
|
||||
if (b.tierRank !== a.tierRank) return b.tierRank - a.tierRank;
|
||||
return String(b.rule?.source || '').length - String(a.rule?.source || '').length;
|
||||
});
|
||||
const patterns = taggedPatterns.map((entry) => entry.rule);
|
||||
const hashTag = String(sha256 || hostI18nSha256(JSON.stringify(exact))).slice(0, 12);
|
||||
return {
|
||||
locale: pack.locale,
|
||||
depth: safeDepth,
|
||||
version: pack.version,
|
||||
revision: `${pack.locale}:${safeDepth}:${pack.version}:${hashTag}`,
|
||||
exact,
|
||||
patterns,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建独立的 Host I18n 包与状态管理器实例(可注入 `dataDir` / `fetchImpl` 便于隔离测试)。
|
||||
*
|
||||
* @param {{
|
||||
* dataDir?: string,
|
||||
* repo?: string,
|
||||
* ref?: string,
|
||||
* localSourceDir?: string,
|
||||
* fetchImpl?: Function|null,
|
||||
* timeoutMs?: number,
|
||||
* }} [options]
|
||||
*/
|
||||
export function createHostI18nPackManager(options = {}) {
|
||||
const paths = hostI18nResolveStoragePaths(options.dataDir || DATA_DIR);
|
||||
const inFlightDownloads = new Map();
|
||||
let inFlightManifest = null;
|
||||
|
||||
let cachedState = null;
|
||||
let cachedStateMtimeMs = -1;
|
||||
let cachedInstalledMeta = null;
|
||||
let cachedInstalledMetaMtimeMs = -1;
|
||||
const cachedPacks = new Map(); // locale -> { mtimeMs, sha256, pack }
|
||||
let cachedCompiledRuntime = null; // { revision, payload }
|
||||
|
||||
function readMtimeMs(filePath) {
|
||||
try {
|
||||
const st = statSync(filePath, { throwIfNoEntry: false });
|
||||
return st ? Number(st.mtimeMs || 0) : -1;
|
||||
} catch {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
function readJsonFileSafe(filePath, fallback) {
|
||||
if (!existsSync(filePath)) return fallback;
|
||||
try {
|
||||
return JSON.parse(readFileSync(filePath, 'utf8'));
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function loadState() {
|
||||
const mtimeMs = readMtimeMs(paths.stateFile);
|
||||
if (mtimeMs < 0) {
|
||||
cachedState = {
|
||||
schemaVersion: HOST_I18N_SCHEMA_VERSION,
|
||||
locale: HOST_I18N_OFF_LOCALE,
|
||||
depth: HOST_I18N_DEFAULT_DEPTH,
|
||||
updatedAtMs: 0,
|
||||
};
|
||||
cachedStateMtimeMs = -1;
|
||||
return { ...cachedState };
|
||||
}
|
||||
if (cachedState && cachedStateMtimeMs === mtimeMs) {
|
||||
return { ...cachedState };
|
||||
}
|
||||
const raw = readJsonFileSafe(paths.stateFile, {});
|
||||
cachedState = {
|
||||
schemaVersion: HOST_I18N_SCHEMA_VERSION,
|
||||
locale: normalizeHostI18nLocale(raw?.locale),
|
||||
depth: normalizeHostI18nDepth(raw?.depth),
|
||||
updatedAtMs: Number(raw?.updatedAtMs || 0) || 0,
|
||||
};
|
||||
cachedStateMtimeMs = mtimeMs;
|
||||
return { ...cachedState };
|
||||
}
|
||||
|
||||
function saveState(nextPartial) {
|
||||
const prev = loadState();
|
||||
const next = {
|
||||
schemaVersion: HOST_I18N_SCHEMA_VERSION,
|
||||
locale:
|
||||
nextPartial?.locale !== undefined
|
||||
? normalizeHostI18nLocale(nextPartial.locale)
|
||||
: prev.locale,
|
||||
depth:
|
||||
nextPartial?.depth !== undefined
|
||||
? normalizeHostI18nDepth(nextPartial.depth)
|
||||
: prev.depth,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
mkdirSync(paths.rootDir, { recursive: true });
|
||||
writeJsonAtomicSync(paths.stateFile, next);
|
||||
cachedState = next;
|
||||
cachedStateMtimeMs = readMtimeMs(paths.stateFile);
|
||||
return { ...next };
|
||||
}
|
||||
|
||||
function loadInstalledMeta() {
|
||||
const mtimeMs = readMtimeMs(paths.installedMetaFile);
|
||||
if (mtimeMs < 0) {
|
||||
cachedInstalledMeta = {};
|
||||
cachedInstalledMetaMtimeMs = -1;
|
||||
return {};
|
||||
}
|
||||
if (cachedInstalledMeta && cachedInstalledMetaMtimeMs === mtimeMs) {
|
||||
return { ...cachedInstalledMeta };
|
||||
}
|
||||
const raw = readJsonFileSafe(paths.installedMetaFile, {});
|
||||
const clean = {};
|
||||
if (isPlainObject(raw)) {
|
||||
for (const [k, v] of Object.entries(raw)) {
|
||||
const loc = normalizeHostI18nLocale(k);
|
||||
if (loc === HOST_I18N_OFF_LOCALE || !isPlainObject(v)) continue;
|
||||
clean[loc] = {
|
||||
locale: loc,
|
||||
name: String(v.name || loc),
|
||||
nativeName: String(v.nativeName || v.name || loc),
|
||||
version: String(v.version || ''),
|
||||
sha256: String(v.sha256 || '').toLowerCase(),
|
||||
bytes: Number(v.bytes || 0) || 0,
|
||||
downloadedAtMs: Number(v.downloadedAtMs || 0) || 0,
|
||||
source: String(v.source || ''),
|
||||
};
|
||||
}
|
||||
}
|
||||
cachedInstalledMeta = clean;
|
||||
cachedInstalledMetaMtimeMs = mtimeMs;
|
||||
return { ...clean };
|
||||
}
|
||||
|
||||
function saveInstalledMeta(metaObj) {
|
||||
mkdirSync(paths.rootDir, { recursive: true });
|
||||
writeJsonAtomicSync(paths.installedMetaFile, metaObj);
|
||||
cachedInstalledMeta = { ...metaObj };
|
||||
cachedInstalledMetaMtimeMs = readMtimeMs(paths.installedMetaFile);
|
||||
}
|
||||
|
||||
function getPackFilePath(locale) {
|
||||
const clean = normalizeHostI18nLocale(locale);
|
||||
if (clean === HOST_I18N_OFF_LOCALE) return '';
|
||||
return join(paths.packsDir, `${clean}.json`);
|
||||
}
|
||||
|
||||
function loadInstalledPack(locale) {
|
||||
const clean = normalizeHostI18nLocale(locale);
|
||||
if (clean === HOST_I18N_OFF_LOCALE) return null;
|
||||
const filePath = getPackFilePath(clean);
|
||||
const mtimeMs = readMtimeMs(filePath);
|
||||
if (mtimeMs < 0) {
|
||||
cachedPacks.delete(clean);
|
||||
return null;
|
||||
}
|
||||
const memo = cachedPacks.get(clean);
|
||||
if (memo && memo.mtimeMs === mtimeMs) {
|
||||
return memo;
|
||||
}
|
||||
try {
|
||||
const rawText = readFileSync(filePath, 'utf8');
|
||||
const sha256 = hostI18nSha256(rawText);
|
||||
const pack = sanitizeHostI18nPack(JSON.parse(rawText), clean);
|
||||
const rec = { mtimeMs, sha256, pack, bytes: Buffer.byteLength(rawText, 'utf8') };
|
||||
cachedPacks.set(clean, rec);
|
||||
return rec;
|
||||
} catch {
|
||||
cachedPacks.delete(clean);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function loadCachedManifest() {
|
||||
const raw = readJsonFileSafe(paths.manifestCacheFile, null);
|
||||
if (!isPlainObject(raw)) return null;
|
||||
try {
|
||||
const clean = sanitizeHostI18nManifest(raw.manifest || raw);
|
||||
return {
|
||||
manifest: clean,
|
||||
fetchedAtMs: Number(raw.fetchedAtMs || 0) || 0,
|
||||
source: String(raw.source || ''),
|
||||
lastError: raw.lastError ? String(raw.lastError) : null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAssetText(relPath) {
|
||||
const resolved = hostI18nResolveRepoAndRef(options);
|
||||
if (resolved.localDir) {
|
||||
const localPath = join(resolved.localDir, relPath);
|
||||
if (!existsSync(localPath)) {
|
||||
throw new Error(`Local host-i18n file not found: ${localPath}`);
|
||||
}
|
||||
return {
|
||||
text: readFileSync(localPath, 'utf8'),
|
||||
url: `local:${localPath}`,
|
||||
status: 200,
|
||||
};
|
||||
}
|
||||
if (!options.fetchImpl && String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid') {
|
||||
throw new Error('Remote host-i18n fetch disabled in test.invalid environment');
|
||||
}
|
||||
const urls = buildHostI18nAssetUrls(relPath, resolved);
|
||||
return fetchHostI18nTextWithFallback(urls, {
|
||||
fetchImpl: options.fetchImpl || null,
|
||||
timeoutMs: options.timeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshManifest({ force = false } = {}) {
|
||||
const cached = loadCachedManifest();
|
||||
const now = Date.now();
|
||||
if (!force && cached && now - cached.fetchedAtMs < HOST_I18N_MANIFEST_TTL_MS) {
|
||||
return { ok: true, fromCache: true, ...cached };
|
||||
}
|
||||
if (inFlightManifest) return inFlightManifest;
|
||||
|
||||
inFlightManifest = (async () => {
|
||||
try {
|
||||
const res = await fetchAssetText('manifest.json');
|
||||
const manifest = sanitizeHostI18nManifest(JSON.parse(res.text));
|
||||
const record = {
|
||||
manifest,
|
||||
fetchedAtMs: Date.now(),
|
||||
source: res.url,
|
||||
lastError: null,
|
||||
};
|
||||
mkdirSync(paths.rootDir, { recursive: true });
|
||||
writeJsonAtomicSync(paths.manifestCacheFile, record);
|
||||
return { ok: true, fromCache: false, ...record };
|
||||
} catch (err) {
|
||||
const message = err?.message || 'Failed to fetch host-i18n manifest';
|
||||
return {
|
||||
ok: false,
|
||||
fromCache: Boolean(cached),
|
||||
manifest: cached?.manifest || { schemaVersion: HOST_I18N_SCHEMA_VERSION, packs: [] },
|
||||
fetchedAtMs: cached?.fetchedAtMs || 0,
|
||||
source: cached?.source || '',
|
||||
error: message,
|
||||
};
|
||||
}
|
||||
})().finally(() => {
|
||||
inFlightManifest = null;
|
||||
});
|
||||
|
||||
return inFlightManifest;
|
||||
}
|
||||
|
||||
async function installPack(rawLocale, { forceManifestRefresh = false } = {}) {
|
||||
const locale = normalizeHostI18nLocale(rawLocale);
|
||||
if (locale === HOST_I18N_OFF_LOCALE) {
|
||||
throw new Error('Cannot install pack for "off" locale');
|
||||
}
|
||||
if (inFlightDownloads.has(locale)) {
|
||||
return inFlightDownloads.get(locale);
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
const manifestRes = await refreshManifest({ force: forceManifestRefresh });
|
||||
let entry = manifestRes.manifest?.packs?.find((p) => p.locale === locale) || null;
|
||||
if (!entry && !forceManifestRefresh) {
|
||||
const refreshed = await refreshManifest({ force: true });
|
||||
entry = refreshed.manifest?.packs?.find((p) => p.locale === locale) || null;
|
||||
}
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
manifestRes.error
|
||||
? `Language pack "${locale}" unavailable: ${manifestRes.error}`
|
||||
: `Language pack "${locale}" not found in repository manifest`
|
||||
);
|
||||
}
|
||||
|
||||
const res = await fetchAssetText(entry.file);
|
||||
const actualHash = hostI18nSha256(res.text);
|
||||
if (actualHash !== entry.sha256) {
|
||||
throw new Error(
|
||||
`Integrity check failed for "${locale}" (expected ${entry.sha256.slice(0, 12)}, got ${actualHash.slice(0, 12)})`
|
||||
);
|
||||
}
|
||||
|
||||
const pack = sanitizeHostI18nPack(JSON.parse(res.text), locale);
|
||||
mkdirSync(paths.packsDir, { recursive: true });
|
||||
const targetPath = getPackFilePath(locale);
|
||||
writeTextFileAtomicSync(targetPath, res.text);
|
||||
|
||||
const meta = loadInstalledMeta();
|
||||
meta[locale] = {
|
||||
locale,
|
||||
name: pack.name,
|
||||
nativeName: pack.nativeName,
|
||||
version: pack.version,
|
||||
sha256: actualHash,
|
||||
bytes: Buffer.byteLength(res.text, 'utf8'),
|
||||
downloadedAtMs: Date.now(),
|
||||
source: res.url,
|
||||
};
|
||||
saveInstalledMeta(meta);
|
||||
cachedPacks.delete(locale);
|
||||
if (cachedCompiledRuntime?.payload?.locale === locale) {
|
||||
cachedCompiledRuntime = null;
|
||||
}
|
||||
const loaded = loadInstalledPack(locale);
|
||||
return {
|
||||
ok: true,
|
||||
locale,
|
||||
version: pack.version,
|
||||
sha256: actualHash,
|
||||
bytes: loaded?.bytes || meta[locale].bytes,
|
||||
source: res.url,
|
||||
};
|
||||
})().finally(() => {
|
||||
inFlightDownloads.delete(locale);
|
||||
});
|
||||
|
||||
inFlightDownloads.set(locale, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
async function selectLanguage({ locale: rawLocale, depth: rawDepth } = {}) {
|
||||
const locale = normalizeHostI18nLocale(rawLocale);
|
||||
const current = loadState();
|
||||
const depth =
|
||||
rawDepth !== undefined ? normalizeHostI18nDepth(rawDepth) : current.depth;
|
||||
|
||||
if (locale === HOST_I18N_OFF_LOCALE) {
|
||||
const nextState = saveState({ locale: HOST_I18N_OFF_LOCALE, depth });
|
||||
return { ok: true, downloaded: false, state: nextState };
|
||||
}
|
||||
|
||||
let downloaded = false;
|
||||
let loaded = loadInstalledPack(locale);
|
||||
if (!loaded) {
|
||||
await installPack(locale, { forceManifestRefresh: false });
|
||||
downloaded = true;
|
||||
loaded = loadInstalledPack(locale);
|
||||
}
|
||||
if (!loaded) {
|
||||
throw new Error(`Language pack "${locale}" failed to load after installation`);
|
||||
}
|
||||
|
||||
const nextState = saveState({ locale, depth });
|
||||
return {
|
||||
ok: true,
|
||||
downloaded,
|
||||
state: nextState,
|
||||
packVersion: loaded.pack.version,
|
||||
};
|
||||
}
|
||||
|
||||
function setDepth(rawDepth) {
|
||||
const depth = normalizeHostI18nDepth(rawDepth);
|
||||
const nextState = saveState({ depth });
|
||||
return { ok: true, state: nextState };
|
||||
}
|
||||
|
||||
function removePack(rawLocale) {
|
||||
const locale = normalizeHostI18nLocale(rawLocale);
|
||||
if (locale === HOST_I18N_OFF_LOCALE) {
|
||||
return { ok: false, error: 'Invalid locale' };
|
||||
}
|
||||
const targetPath = getPackFilePath(locale);
|
||||
if (targetPath && existsSync(targetPath)) {
|
||||
rmSync(targetPath, { force: true });
|
||||
}
|
||||
cachedPacks.delete(locale);
|
||||
if (cachedCompiledRuntime?.payload?.locale === locale) {
|
||||
cachedCompiledRuntime = null;
|
||||
}
|
||||
const meta = loadInstalledMeta();
|
||||
delete meta[locale];
|
||||
saveInstalledMeta(meta);
|
||||
|
||||
const cur = loadState();
|
||||
let nextState = cur;
|
||||
if (cur.locale === locale) {
|
||||
nextState = saveState({ locale: HOST_I18N_OFF_LOCALE });
|
||||
}
|
||||
return { ok: true, removedLocale: locale, state: nextState };
|
||||
}
|
||||
|
||||
function getActiveBridgeDescriptor() {
|
||||
const st = loadState();
|
||||
if (st.locale === HOST_I18N_OFF_LOCALE) {
|
||||
return { active: false, locale: HOST_I18N_OFF_LOCALE, depth: st.depth, revision: '', getPayload: null };
|
||||
}
|
||||
const loaded = loadInstalledPack(st.locale);
|
||||
if (!loaded) {
|
||||
return { active: false, locale: st.locale, depth: st.depth, revision: '', getPayload: null };
|
||||
}
|
||||
const revision = `${loaded.pack.locale}:${st.depth}:${loaded.pack.version}:${loaded.sha256.slice(0, 12)}`;
|
||||
return {
|
||||
active: true,
|
||||
locale: loaded.pack.locale,
|
||||
depth: st.depth,
|
||||
version: loaded.pack.version,
|
||||
revision,
|
||||
getPayload: () => {
|
||||
if (cachedCompiledRuntime && cachedCompiledRuntime.revision === revision) {
|
||||
return cachedCompiledRuntime.payload;
|
||||
}
|
||||
const payload = compileHostI18nRuntimePayload(loaded.pack, st.depth, loaded.sha256);
|
||||
cachedCompiledRuntime = { revision, payload };
|
||||
return payload;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getStatusSnapshot({ manifestResult = null, bridgeStatus = null } = {}) {
|
||||
const state = loadState();
|
||||
const installedMeta = loadInstalledMeta();
|
||||
const cachedManifest = manifestResult || loadCachedManifest();
|
||||
const remotePacks = Array.isArray(cachedManifest?.manifest?.packs)
|
||||
? cachedManifest.manifest.packs
|
||||
: [];
|
||||
|
||||
const byLocale = new Map();
|
||||
for (const remote of remotePacks) {
|
||||
const localPack = loadInstalledPack(remote.locale);
|
||||
const localInfo = installedMeta[remote.locale] || null;
|
||||
const installed = Boolean(localPack);
|
||||
const installedSha = localPack?.sha256 || localInfo?.sha256 || '';
|
||||
const installedVersion = localPack?.pack?.version || localInfo?.version || '';
|
||||
byLocale.set(remote.locale, {
|
||||
locale: remote.locale,
|
||||
name: remote.name,
|
||||
nativeName: remote.nativeName,
|
||||
remoteVersion: remote.version,
|
||||
remoteSha256: remote.sha256,
|
||||
remoteBytes: remote.bytes,
|
||||
depths: remote.depths || ['light', 'deep'],
|
||||
stats: remote.stats || null,
|
||||
installed,
|
||||
installedVersion,
|
||||
installedBytes: localPack?.bytes || localInfo?.bytes || 0,
|
||||
downloadedAtMs: localInfo?.downloadedAtMs || 0,
|
||||
updateAvailable: Boolean(installed && installedSha && installedSha !== remote.sha256),
|
||||
});
|
||||
}
|
||||
|
||||
// 保留仅在本地存在(离线/自定义)的已安装包条目
|
||||
for (const [loc, localInfo] of Object.entries(installedMeta)) {
|
||||
if (byLocale.has(loc)) continue;
|
||||
const localPack = loadInstalledPack(loc);
|
||||
if (!localPack) continue;
|
||||
byLocale.set(loc, {
|
||||
locale: loc,
|
||||
name: localPack.pack.name,
|
||||
nativeName: localPack.pack.nativeName,
|
||||
remoteVersion: '',
|
||||
remoteSha256: '',
|
||||
remoteBytes: 0,
|
||||
depths: ['light', 'deep'],
|
||||
stats: {
|
||||
baseExact: Object.keys(localPack.pack.base.exact).length,
|
||||
lightExact: Object.keys(localPack.pack.modes.light.exact).length,
|
||||
deepExact: Object.keys(localPack.pack.modes.deep.exact).length,
|
||||
basePatterns: localPack.pack.base.patterns.length,
|
||||
lightPatterns: localPack.pack.modes.light.patterns.length,
|
||||
deepPatterns: localPack.pack.modes.deep.patterns.length,
|
||||
},
|
||||
installed: true,
|
||||
installedVersion: localPack.pack.version,
|
||||
installedBytes: localPack.bytes,
|
||||
downloadedAtMs: localInfo.downloadedAtMs || 0,
|
||||
updateAvailable: false,
|
||||
});
|
||||
}
|
||||
|
||||
const activeDesc = getActiveBridgeDescriptor();
|
||||
const resolvedRepo = hostI18nResolveRepoAndRef(options);
|
||||
return {
|
||||
schemaVersion: HOST_I18N_SCHEMA_VERSION,
|
||||
locale: state.locale,
|
||||
depth: state.depth,
|
||||
active: activeDesc.active,
|
||||
activeRevision: activeDesc.revision,
|
||||
updatedAtMs: state.updatedAtMs,
|
||||
manifestFetchedAtMs: Number(cachedManifest?.fetchedAtMs || 0) || 0,
|
||||
manifestError: cachedManifest?.error || null,
|
||||
repo: resolvedRepo.repo,
|
||||
ref: resolvedRepo.ref,
|
||||
packs: Array.from(byLocale.values()),
|
||||
...(bridgeStatus ? { bridgeStatus } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
paths,
|
||||
loadState,
|
||||
saveState,
|
||||
loadInstalledPack,
|
||||
refreshManifest,
|
||||
installPack,
|
||||
selectLanguage,
|
||||
setDepth,
|
||||
removePack,
|
||||
getActiveBridgeDescriptor,
|
||||
getStatusSnapshot,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,914 @@
|
||||
/**
|
||||
* @fileoverview 注入到 Antigravity 渲染进程的无损运行时 DOM 翻译引擎与按需词条采集器。
|
||||
*
|
||||
* 工程底线:
|
||||
* 1. 绝不替换、拆裂或增删 React 托管的任何 DOM 元素,仅原地改写 `Text.nodeValue` 及
|
||||
* `placeholder` / `title` / `aria-label` / `aria-description` / `aria-placeholder` 属性;
|
||||
* 2. 通过 `WeakMap` 精确记录每个被改写节点/属性的原文与译文,既支持 `light ↔ deep` /
|
||||
* `关闭` 秒级无损还原,也能自动识别 React 原地更新的新英文文案并重新翻译;
|
||||
* 3. 对齐 Antigravity 真实 DOM 结构,严格豁免用户消息正文(`user-message-content`)、
|
||||
* 代码块、Diff 行、编辑器、终端、可编辑区以及本插件双 Shadow Host,不误伤工具栏按钮;
|
||||
* 4. 针对数千条精确词条 + 数百条动态模板做 O(1) 精确查表 + 首词桶索引,并经
|
||||
* `requestAnimationFrame` 分帧合批,杜绝流式输出掉帧。
|
||||
*/
|
||||
|
||||
import { HOST_I18N_GLOBAL_KEY } from '../../shared/host-i18n-protocol.mjs';
|
||||
|
||||
/**
|
||||
* 在宿主页面执行:安装或热更新无损 DOM 翻译器,并续期 18 秒看门狗。
|
||||
*
|
||||
* @param {object} payload `{ locale, depth, revision, exact, patterns }`
|
||||
* @param {string} bootId
|
||||
* @param {string} [globalKey]
|
||||
*/
|
||||
export function applyHostI18nInPage(payload, bootId, globalKey = '__AGUsageMonitorHostI18n') {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
||||
return { applied: false, reason: 'no_dom' };
|
||||
}
|
||||
const root = document.body || document.documentElement;
|
||||
if (!root) {
|
||||
return { applied: false, reason: 'no_root' };
|
||||
}
|
||||
|
||||
const WATCHDOG_MS = 18_000;
|
||||
const FRAME_NODE_BUDGET = 450;
|
||||
const INITIAL_SCAN_BUDGET = 4000;
|
||||
const MAX_PENDING_NODES = 4096;
|
||||
const MAX_MISS_CACHE = 1024;
|
||||
const MAX_EXACT_LEN = 1000;
|
||||
const MAX_PATTERN_LEN = 360;
|
||||
const TRANSLATABLE_ATTRS = [
|
||||
'placeholder',
|
||||
'title',
|
||||
'aria-label',
|
||||
'aria-description',
|
||||
'aria-placeholder',
|
||||
];
|
||||
const SKIP_TAGS = new Set([
|
||||
'SCRIPT',
|
||||
'STYLE',
|
||||
'NOSCRIPT',
|
||||
'CODE',
|
||||
'PRE',
|
||||
'TEXTAREA',
|
||||
'SVG',
|
||||
'MATH',
|
||||
'KBD',
|
||||
'SAMP',
|
||||
'VAR',
|
||||
'CANVAS',
|
||||
'VIDEO',
|
||||
'AUDIO',
|
||||
'IFRAME',
|
||||
]);
|
||||
const SKIP_TESTIDS = new Set([
|
||||
'user-message-content',
|
||||
'markdown-code-block-preview',
|
||||
'markdown-frontmatter',
|
||||
'automation-instructions-markdown',
|
||||
'code-gutter',
|
||||
'code-gutter-diff',
|
||||
'diff-gutter-strip',
|
||||
'artifact-pdf-view',
|
||||
]);
|
||||
const SKIP_CLASSES = new Set([
|
||||
'monaco-editor',
|
||||
'xterm',
|
||||
'cm-editor',
|
||||
'ProseMirror',
|
||||
'markdown-body',
|
||||
'prose',
|
||||
'diff-line',
|
||||
'view-lines',
|
||||
]);
|
||||
|
||||
function isSkippedSelf(el) {
|
||||
if (!el || el.nodeType !== 1) return false;
|
||||
if (SKIP_TAGS.has(el.tagName)) return true;
|
||||
if (el.isContentEditable === true) return true;
|
||||
const id = el.id;
|
||||
if (id === 'ag-usage-monitor-capsule' || id === 'ag-usage-monitor-portal') return true;
|
||||
if (typeof el.hasAttribute === 'function' && el.hasAttribute('data-ag-i18n-ignore')) return true;
|
||||
if (typeof el.getAttribute === 'function') {
|
||||
if (el.getAttribute('contenteditable') === 'true') return true;
|
||||
const tid = el.getAttribute('data-testid');
|
||||
if (tid && SKIP_TESTIDS.has(tid)) return true;
|
||||
}
|
||||
const cls = el.className;
|
||||
if (typeof cls === 'string' && cls) {
|
||||
if (cls.indexOf(' ') === -1) {
|
||||
if (SKIP_CLASSES.has(cls)) return true;
|
||||
} else {
|
||||
const parts = cls.split(/\s+/);
|
||||
for (let i = 0; i < parts.length; i += 1) {
|
||||
if (SKIP_CLASSES.has(parts[i])) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isSkippedElement(el) {
|
||||
let cur = el;
|
||||
while (cur && cur.nodeType === 1) {
|
||||
if (isSkippedSelf(cur)) return true;
|
||||
cur = cur.parentElement || (cur.parentNode && cur.parentNode.nodeType === 1 ? cur.parentNode : null);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasAsciiLetter(str) {
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
const code = str.charCodeAt(i);
|
||||
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAsciiLetterCode(code) {
|
||||
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
}
|
||||
|
||||
function extractFirstWordLower(str) {
|
||||
const m = str.match(/^[A-Za-z][A-Za-z0-9'-]*/);
|
||||
return m ? m[0].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function extractLastWordLower(str) {
|
||||
const m = str.match(/([A-Za-z]{2,})[.)?!'"\u201d\u2019…]*$/);
|
||||
return m ? m[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function extractPatternLeadingWordLower(source) {
|
||||
// 匹配以 `^Word` 开头的锚定模板(忽略反转义前的普通字母首词)
|
||||
const m = String(source || '').match(/^\^([A-Za-z]{2,})/);
|
||||
return m ? m[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function isNumericStartPattern(source) {
|
||||
return /^\^(?:\\d|\(\\d|\\\(|\\\+|, \\\+)/.test(String(source || ''));
|
||||
}
|
||||
|
||||
function extractPatternTrailingWordsLower(source) {
|
||||
const s = String(source || '');
|
||||
// 跳过结尾是通配捕获或字符集的模板,仅索引以固定英文词结尾的模板(兼容可选复数 s?)
|
||||
const plural = s.match(/([A-Za-z]{2,})s\?(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
|
||||
if (plural) {
|
||||
const base = plural[1].toLowerCase();
|
||||
return [base, `${base}s`];
|
||||
}
|
||||
const exact = s.match(/(?:^|[\s(\\/-])([A-Za-z]{2,})(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
|
||||
if (exact) {
|
||||
return [exact[1].toLowerCase()];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function computePatternSpecificity(source) {
|
||||
const s = String(source || '');
|
||||
let literalChars = 0;
|
||||
let parenDepth = 0;
|
||||
let inCharClass = false;
|
||||
for (let i = 0; i < s.length; i += 1) {
|
||||
const ch = s[i];
|
||||
if (ch === '\\' && i + 1 < s.length) {
|
||||
const next = s[i + 1];
|
||||
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
|
||||
literalChars += 1;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '[' && !inCharClass) {
|
||||
inCharClass = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === ']' && inCharClass) {
|
||||
inCharClass = false;
|
||||
continue;
|
||||
}
|
||||
if (inCharClass) continue;
|
||||
if (ch === '(') {
|
||||
parenDepth += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === ')') {
|
||||
if (parenDepth > 0) parenDepth -= 1;
|
||||
continue;
|
||||
}
|
||||
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
|
||||
literalChars += 1;
|
||||
}
|
||||
}
|
||||
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
|
||||
const typedCaptures = (s.match(/\\d\+/g) || []).length;
|
||||
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
|
||||
}
|
||||
|
||||
function compileMatchers(rawPayload) {
|
||||
const exactMap = new Map();
|
||||
const exactLowerMap = new Map();
|
||||
const rawExact = rawPayload?.exact;
|
||||
if (rawExact && typeof rawExact === 'object') {
|
||||
for (const [k, v] of Object.entries(rawExact)) {
|
||||
if (typeof v !== 'string' || !v) continue;
|
||||
exactMap.set(k, v);
|
||||
if (k.length <= 80) {
|
||||
const lowerK = k.toLowerCase();
|
||||
if (!exactLowerMap.has(lowerK)) {
|
||||
exactLowerMap.set(lowerK, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const prefixBuckets = new Map();
|
||||
const suffixBuckets = new Map();
|
||||
const numericFallbacks = [];
|
||||
const fallbackPatterns = [];
|
||||
const rawPatterns = Array.isArray(rawPayload?.patterns) ? rawPayload.patterns : [];
|
||||
for (let i = 0; i < rawPatterns.length; i += 1) {
|
||||
const item = rawPatterns[i];
|
||||
if (!item || typeof item.source !== 'string' || typeof item.replace !== 'string') continue;
|
||||
try {
|
||||
const compiled = {
|
||||
re: new RegExp(item.source, typeof item.flags === 'string' ? item.flags : ''),
|
||||
replace: item.replace,
|
||||
hintLower: typeof item.hint === 'string' ? item.hint.toLowerCase() : '',
|
||||
specificity: computePatternSpecificity(item.source),
|
||||
sourceLen: item.source.length,
|
||||
order: i,
|
||||
};
|
||||
const leadWord = extractPatternLeadingWordLower(item.source);
|
||||
if (leadWord) {
|
||||
let bucket = prefixBuckets.get(leadWord);
|
||||
if (!bucket) {
|
||||
bucket = [];
|
||||
prefixBuckets.set(leadWord, bucket);
|
||||
}
|
||||
bucket.push(compiled);
|
||||
} else if (isNumericStartPattern(item.source)) {
|
||||
numericFallbacks.push(compiled);
|
||||
} else {
|
||||
const tailWords = extractPatternTrailingWordsLower(item.source);
|
||||
if (tailWords.length > 0) {
|
||||
for (let t = 0; t < tailWords.length; t += 1) {
|
||||
const tw = tailWords[t];
|
||||
let sBucket = suffixBuckets.get(tw);
|
||||
if (!sBucket) {
|
||||
sBucket = [];
|
||||
suffixBuckets.set(tw, sBucket);
|
||||
}
|
||||
sBucket.push(compiled);
|
||||
}
|
||||
} else {
|
||||
fallbackPatterns.push(compiled);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略单条非法正则
|
||||
}
|
||||
}
|
||||
const sortBySpecificity = (a, b) =>
|
||||
b.specificity - a.specificity || b.sourceLen - a.sourceLen || a.order - b.order;
|
||||
for (const bucket of prefixBuckets.values()) {
|
||||
if (bucket.length > 1) bucket.sort(sortBySpecificity);
|
||||
}
|
||||
for (const bucket of suffixBuckets.values()) {
|
||||
if (bucket.length > 1) bucket.sort(sortBySpecificity);
|
||||
}
|
||||
if (numericFallbacks.length > 1) numericFallbacks.sort(sortBySpecificity);
|
||||
if (fallbackPatterns.length > 1) fallbackPatterns.sort(sortBySpecificity);
|
||||
return {
|
||||
exactMap,
|
||||
exactLowerMap,
|
||||
prefixBuckets,
|
||||
suffixBuckets,
|
||||
numericFallbacks,
|
||||
fallbackPatterns,
|
||||
missCache: new Set(),
|
||||
};
|
||||
}
|
||||
|
||||
function runPatternList(trimmed, lowerRef, list) {
|
||||
if (!list || list.length === 0) return undefined;
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
const pat = list[i];
|
||||
if (pat.hintLower) {
|
||||
if (lowerRef.value === null) lowerRef.value = trimmed.toLowerCase();
|
||||
if (!lowerRef.value.includes(pat.hintLower)) continue;
|
||||
}
|
||||
if (pat.re.test(trimmed)) {
|
||||
const next = trimmed.replace(pat.re, pat.replace);
|
||||
if (next && next !== trimmed) return next;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function translateTextWithMatchers(rawText, matchers) {
|
||||
if (typeof rawText !== 'string' || !rawText || rawText.length > MAX_EXACT_LEN) return null;
|
||||
const normalizedRaw = rawText.includes('\r') ? rawText.replace(/\r\n/g, '\n') : rawText;
|
||||
const trimmed = normalizedRaw.trim();
|
||||
if (!trimmed || trimmed.length > MAX_EXACT_LEN) return null;
|
||||
if (trimmed.length <= 160 && matchers.missCache.has(trimmed)) return null;
|
||||
|
||||
let translatedCore = matchers.exactMap.get(trimmed);
|
||||
const hasLetter = translatedCore === undefined ? hasAsciiLetter(trimmed) : false;
|
||||
let lowerRef = { value: null };
|
||||
|
||||
if (translatedCore === undefined && trimmed.length <= 80 && hasLetter) {
|
||||
lowerRef.value = trimmed.toLowerCase();
|
||||
translatedCore = matchers.exactLowerMap.get(lowerRef.value);
|
||||
}
|
||||
if (
|
||||
translatedCore === undefined &&
|
||||
trimmed.length <= MAX_PATTERN_LEN &&
|
||||
!trimmed.includes('\n') &&
|
||||
hasLetter
|
||||
) {
|
||||
const firstCode = trimmed.charCodeAt(0);
|
||||
if (isAsciiLetterCode(firstCode)) {
|
||||
const leadWord = extractFirstWordLower(trimmed);
|
||||
if (leadWord) {
|
||||
translatedCore = runPatternList(trimmed, lowerRef, matchers.prefixBuckets.get(leadWord));
|
||||
}
|
||||
} else if (matchers.numericFallbacks.length > 0) {
|
||||
translatedCore = runPatternList(trimmed, lowerRef, matchers.numericFallbacks);
|
||||
}
|
||||
if (translatedCore === undefined) {
|
||||
const tailWord = extractLastWordLower(trimmed);
|
||||
if (tailWord) {
|
||||
translatedCore = runPatternList(trimmed, lowerRef, matchers.suffixBuckets.get(tailWord));
|
||||
}
|
||||
}
|
||||
if (translatedCore === undefined && matchers.fallbackPatterns.length > 0) {
|
||||
translatedCore = runPatternList(trimmed, lowerRef, matchers.fallbackPatterns);
|
||||
}
|
||||
}
|
||||
if (translatedCore === undefined || translatedCore === trimmed) {
|
||||
if (trimmed.length <= 160) {
|
||||
if (matchers.missCache.size >= MAX_MISS_CACHE) {
|
||||
matchers.missCache.clear();
|
||||
}
|
||||
matchers.missCache.add(trimmed);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const startIdx = normalizedRaw.indexOf(trimmed);
|
||||
const leading = startIdx > 0 ? normalizedRaw.slice(0, startIdx) : '';
|
||||
const trailing =
|
||||
startIdx + trimmed.length < normalizedRaw.length
|
||||
? normalizedRaw.slice(startIdx + trimmed.length)
|
||||
: '';
|
||||
return leading + translatedCore + trailing;
|
||||
}
|
||||
|
||||
let state = window[globalKey];
|
||||
|
||||
function restoreSubtree(scanRoot, targetState) {
|
||||
if (!scanRoot) return;
|
||||
if (typeof document.createTreeWalker === 'function') {
|
||||
const textWalker = document.createTreeWalker(scanRoot, 4);
|
||||
let node = textWalker.nextNode();
|
||||
while (node) {
|
||||
const rec = targetState.textRecords.get(node);
|
||||
if (rec) {
|
||||
if (node.nodeValue === rec.translated) {
|
||||
node.nodeValue = rec.orig;
|
||||
}
|
||||
targetState.textRecords.delete(node);
|
||||
}
|
||||
node = textWalker.nextNode();
|
||||
}
|
||||
|
||||
const elWalker = document.createTreeWalker(scanRoot, 1);
|
||||
let el = elWalker.nextNode();
|
||||
while (el) {
|
||||
const attrMap = targetState.attrRecords.get(el);
|
||||
if (attrMap) {
|
||||
for (const [attrName, rec] of attrMap.entries()) {
|
||||
if (el.getAttribute(attrName) === rec.translated) {
|
||||
el.setAttribute(attrName, rec.orig);
|
||||
}
|
||||
}
|
||||
targetState.attrRecords.delete(el);
|
||||
}
|
||||
if (el.shadowRoot && el.id !== 'ag-usage-monitor-capsule' && el.id !== 'ag-usage-monitor-portal') {
|
||||
restoreSubtree(el.shadowRoot, targetState);
|
||||
}
|
||||
el = elWalker.nextNode();
|
||||
}
|
||||
} else {
|
||||
const walkFallback = (cur) => {
|
||||
if (!cur) return;
|
||||
if (cur.nodeType === 3) {
|
||||
const rec = targetState.textRecords.get(cur);
|
||||
if (rec) {
|
||||
if (cur.nodeValue === rec.translated) cur.nodeValue = rec.orig;
|
||||
targetState.textRecords.delete(cur);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (cur.nodeType === 1 || cur.nodeType === 11) {
|
||||
if (cur.nodeType === 1) {
|
||||
const attrMap = targetState.attrRecords.get(cur);
|
||||
if (attrMap) {
|
||||
for (const [attrName, rec] of attrMap.entries()) {
|
||||
if (cur.getAttribute?.(attrName) === rec.translated) {
|
||||
cur.setAttribute(attrName, rec.orig);
|
||||
}
|
||||
}
|
||||
targetState.attrRecords.delete(cur);
|
||||
}
|
||||
if (cur.shadowRoot && cur.id !== 'ag-usage-monitor-capsule' && cur.id !== 'ag-usage-monitor-portal') {
|
||||
walkFallback(cur.shadowRoot);
|
||||
}
|
||||
}
|
||||
const children = cur.childNodes || [];
|
||||
for (let i = 0; i < children.length; i += 1) {
|
||||
walkFallback(children[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
walkFallback(scanRoot);
|
||||
}
|
||||
}
|
||||
|
||||
function restoreAllTracked(targetState) {
|
||||
if (!targetState) return;
|
||||
targetState.isMutating = true;
|
||||
try {
|
||||
const scanRoot = document.body || document.documentElement;
|
||||
restoreSubtree(scanRoot, targetState);
|
||||
} finally {
|
||||
targetState.isMutating = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (state && state.bootId !== bootId) {
|
||||
state.dispose?.();
|
||||
state = null;
|
||||
}
|
||||
|
||||
if (!state) {
|
||||
const scheduleFrame =
|
||||
typeof window.requestAnimationFrame === 'function'
|
||||
? (cb) => ({ kind: 'raf', id: window.requestAnimationFrame(cb) })
|
||||
: (cb) => ({ kind: 'timer', id: setTimeout(cb, 16) });
|
||||
const cancelFrame = (handle) => {
|
||||
if (!handle) return;
|
||||
if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function') {
|
||||
window.cancelAnimationFrame(handle.id);
|
||||
} else {
|
||||
clearTimeout(handle.id);
|
||||
}
|
||||
};
|
||||
|
||||
state = {
|
||||
bootId,
|
||||
revision: '',
|
||||
locale: '',
|
||||
depth: '',
|
||||
matchers: {
|
||||
exactMap: new Map(),
|
||||
exactLowerMap: new Map(),
|
||||
prefixBuckets: new Map(),
|
||||
suffixBuckets: new Map(),
|
||||
numericFallbacks: [],
|
||||
fallbackPatterns: [],
|
||||
missCache: new Set(),
|
||||
},
|
||||
textRecords: new WeakMap(),
|
||||
attrRecords: new WeakMap(),
|
||||
pendingNodes: new Set(),
|
||||
fullRescanPending: false,
|
||||
frameHandle: null,
|
||||
watchdogTimer: null,
|
||||
observer: null,
|
||||
isMutating: false,
|
||||
translatedCount: 0,
|
||||
applyTextNode(node, parentVerifiedSafe = false) {
|
||||
if (!node || node.nodeType !== 3) return;
|
||||
if (!parentVerifiedSafe) {
|
||||
const parent = node.parentElement || node.parentNode;
|
||||
if (parent && isSkippedElement(parent)) return;
|
||||
}
|
||||
const curVal = node.nodeValue;
|
||||
if (typeof curVal !== 'string' || !curVal) return;
|
||||
|
||||
const existing = state.textRecords.get(node);
|
||||
let origVal = curVal;
|
||||
if (existing) {
|
||||
if (curVal === existing.translated) {
|
||||
return;
|
||||
}
|
||||
origVal = curVal;
|
||||
state.textRecords.delete(node);
|
||||
}
|
||||
|
||||
const nextVal = translateTextWithMatchers(origVal, state.matchers);
|
||||
if (nextVal !== null && nextVal !== origVal) {
|
||||
state.textRecords.set(node, { orig: origVal, translated: nextVal });
|
||||
state.isMutating = true;
|
||||
try {
|
||||
node.nodeValue = nextVal;
|
||||
state.translatedCount += 1;
|
||||
} finally {
|
||||
state.isMutating = false;
|
||||
}
|
||||
}
|
||||
},
|
||||
applyElementAttrs(el, selfVerifiedSafe = false) {
|
||||
if (!el || el.nodeType !== 1) return;
|
||||
if (!selfVerifiedSafe && isSkippedElement(el)) return;
|
||||
if (typeof el.getAttribute !== 'function' || typeof el.setAttribute !== 'function') return;
|
||||
for (let i = 0; i < TRANSLATABLE_ATTRS.length; i += 1) {
|
||||
const attrName = TRANSLATABLE_ATTRS[i];
|
||||
const curVal = el.getAttribute(attrName);
|
||||
if (!curVal) continue;
|
||||
let attrMap = state.attrRecords.get(el);
|
||||
const existing = attrMap?.get(attrName);
|
||||
let origVal = curVal;
|
||||
if (existing) {
|
||||
if (curVal === existing.translated) continue;
|
||||
origVal = curVal;
|
||||
attrMap.delete(attrName);
|
||||
}
|
||||
const nextVal = translateTextWithMatchers(origVal, state.matchers);
|
||||
if (nextVal !== null && nextVal !== origVal) {
|
||||
if (!attrMap) {
|
||||
attrMap = new Map();
|
||||
state.attrRecords.set(el, attrMap);
|
||||
}
|
||||
attrMap.set(attrName, { orig: origVal, translated: nextVal });
|
||||
state.isMutating = true;
|
||||
try {
|
||||
el.setAttribute(attrName, nextVal);
|
||||
state.translatedCount += 1;
|
||||
} finally {
|
||||
state.isMutating = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
walkSubtree(node, budgetRef, ancestorsVerifiedSafe = false) {
|
||||
if (!node || budgetRef.remaining <= 0) return false;
|
||||
if (node.nodeType === 3) {
|
||||
budgetRef.remaining -= 1;
|
||||
state.applyTextNode(node, ancestorsVerifiedSafe);
|
||||
return true;
|
||||
}
|
||||
if (node.nodeType !== 1 && node.nodeType !== 11) return true;
|
||||
if (node.nodeType === 1) {
|
||||
if (ancestorsVerifiedSafe ? isSkippedSelf(node) : isSkippedElement(node)) return true;
|
||||
budgetRef.remaining -= 1;
|
||||
state.applyElementAttrs(node, true);
|
||||
if (node.shadowRoot && node.id !== 'ag-usage-monitor-capsule' && node.id !== 'ag-usage-monitor-portal') {
|
||||
state.walkSubtree(node.shadowRoot, budgetRef, true);
|
||||
}
|
||||
}
|
||||
const children = node.childNodes || [];
|
||||
for (let i = 0; i < children.length; i += 1) {
|
||||
if (budgetRef.remaining <= 0) {
|
||||
state.pendingNodes.add(children[i]);
|
||||
return false;
|
||||
}
|
||||
if (!state.walkSubtree(children[i], budgetRef, true)) {
|
||||
for (let j = i + 1; j < children.length; j += 1) {
|
||||
state.pendingNodes.add(children[j]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
flushPending() {
|
||||
state.frameHandle = null;
|
||||
if (state.fullRescanPending) {
|
||||
state.fullRescanPending = false;
|
||||
state.pendingNodes.clear();
|
||||
const scanRoot = document.body || document.documentElement;
|
||||
if (scanRoot) state.pendingNodes.add(scanRoot);
|
||||
}
|
||||
const budgetRef = { remaining: FRAME_NODE_BUDGET };
|
||||
const batch = Array.from(state.pendingNodes);
|
||||
state.pendingNodes.clear();
|
||||
for (let i = 0; i < batch.length; i += 1) {
|
||||
if (budgetRef.remaining <= 0) {
|
||||
for (let j = i; j < batch.length; j += 1) {
|
||||
state.pendingNodes.add(batch[j]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
state.walkSubtree(batch[i], budgetRef, false);
|
||||
}
|
||||
if (state.pendingNodes.size > 0 || state.fullRescanPending) {
|
||||
state.scheduleFlush();
|
||||
}
|
||||
},
|
||||
scheduleFlush() {
|
||||
if (state.frameHandle) return;
|
||||
state.frameHandle = scheduleFrame(() => state.flushPending());
|
||||
},
|
||||
enqueue(node) {
|
||||
if (!node) return;
|
||||
if (state.pendingNodes.size >= MAX_PENDING_NODES) {
|
||||
state.fullRescanPending = true;
|
||||
state.pendingNodes.clear();
|
||||
} else {
|
||||
state.pendingNodes.add(node);
|
||||
}
|
||||
state.scheduleFlush();
|
||||
},
|
||||
scanAllNow() {
|
||||
const scanRoot = document.body || document.documentElement;
|
||||
if (!scanRoot) return;
|
||||
const budgetRef = { remaining: INITIAL_SCAN_BUDGET };
|
||||
state.walkSubtree(scanRoot, budgetRef, true);
|
||||
if (state.pendingNodes.size > 0) {
|
||||
state.scheduleFlush();
|
||||
}
|
||||
},
|
||||
touchWatchdog() {
|
||||
clearTimeout(state.watchdogTimer);
|
||||
state.watchdogTimer = setTimeout(() => {
|
||||
state.dispose();
|
||||
}, WATCHDOG_MS);
|
||||
},
|
||||
dispose() {
|
||||
clearTimeout(state.watchdogTimer);
|
||||
state.watchdogTimer = null;
|
||||
cancelFrame(state.frameHandle);
|
||||
state.frameHandle = null;
|
||||
try {
|
||||
state.observer?.disconnect?.();
|
||||
} catch {
|
||||
// 忽略断开异常
|
||||
}
|
||||
state.observer = null;
|
||||
state.pendingNodes.clear();
|
||||
state.fullRescanPending = false;
|
||||
restoreAllTracked(state);
|
||||
state.matchers.exactMap.clear();
|
||||
state.matchers.exactLowerMap.clear();
|
||||
state.matchers.prefixBuckets.clear();
|
||||
state.matchers.suffixBuckets.clear();
|
||||
state.matchers.numericFallbacks.length = 0;
|
||||
state.matchers.fallbackPatterns.length = 0;
|
||||
state.matchers.missCache.clear();
|
||||
if (window[globalKey] === state) {
|
||||
delete window[globalKey];
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if (typeof window.MutationObserver === 'function') {
|
||||
state.observer = new window.MutationObserver((mutations) => {
|
||||
if (state.isMutating) return;
|
||||
for (let i = 0; i < mutations.length; i += 1) {
|
||||
const m = mutations[i];
|
||||
if (m.type === 'characterData' || m.type === 'attributes') {
|
||||
state.enqueue(m.target);
|
||||
} else if (m.type === 'childList') {
|
||||
const added = m.addedNodes || [];
|
||||
for (let j = 0; j < added.length; j += 1) {
|
||||
state.enqueue(added[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
state.observer.observe(root, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
characterData: true,
|
||||
attributes: true,
|
||||
attributeFilter: TRANSLATABLE_ATTRS,
|
||||
});
|
||||
}
|
||||
|
||||
window[globalKey] = state;
|
||||
}
|
||||
|
||||
state.touchWatchdog();
|
||||
|
||||
const nextRevision = String(payload?.revision || '');
|
||||
if (state.revision !== nextRevision) {
|
||||
if (state.revision) {
|
||||
restoreAllTracked(state);
|
||||
}
|
||||
state.revision = nextRevision;
|
||||
state.locale = String(payload?.locale || '');
|
||||
state.depth = String(payload?.depth || '');
|
||||
state.matchers = compileMatchers(payload);
|
||||
state.translatedCount = 0;
|
||||
state.scanAllNow();
|
||||
}
|
||||
|
||||
return {
|
||||
applied: true,
|
||||
revision: state.revision,
|
||||
locale: state.locale,
|
||||
depth: state.depth,
|
||||
translatedCount: state.translatedCount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 轻量心跳表达式:若当前页面已加载同一 `bootId` 且同 `revision`,直接续期看门狗,无需重传大词表。
|
||||
*/
|
||||
export function createHostI18nHeartbeatExpression(bootId, revision) {
|
||||
return `(() => {
|
||||
try {
|
||||
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
|
||||
if (!st || st.bootId !== ${JSON.stringify(bootId)} || st.revision !== ${JSON.stringify(revision)}) {
|
||||
return { alive: false, needsApply: true };
|
||||
}
|
||||
st.touchWatchdog?.();
|
||||
return { alive: true, needsApply: false, revision: st.revision, translatedCount: Number(st.translatedCount || 0) };
|
||||
} catch {
|
||||
return { alive: false, needsApply: true };
|
||||
}
|
||||
})()`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成完整注入/切换词表表达式。
|
||||
*/
|
||||
export function createHostI18nApplyExpression(payload, bootId) {
|
||||
return `(${applyHostI18nInPage.toString()})(${JSON.stringify(payload)}, ${JSON.stringify(bootId)}, ${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成停止翻译并无损还原原文的清理表达式。
|
||||
*/
|
||||
export function createHostI18nDisposeExpression() {
|
||||
return `(() => {
|
||||
try {
|
||||
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
|
||||
if (!st) return { disposed: false };
|
||||
st.dispose?.();
|
||||
return { disposed: true };
|
||||
} catch {
|
||||
return { disposed: false };
|
||||
}
|
||||
})()`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在宿主页面按需执行:只读采集当前可见 UI 控件与说明中尚未翻译的英文短语
|
||||
* (严格排除聊天用户正文、代码块、Diff、编辑器与隐私路径)。
|
||||
*/
|
||||
export function collectUntranslatedHostUiInPage(globalKey = '__AGUsageMonitorHostI18n') {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
||||
return { count: 0, items: [] };
|
||||
}
|
||||
const root = document.body || document.documentElement;
|
||||
if (!root) return { count: 0, items: [] };
|
||||
|
||||
const activeState = window[globalKey] || null;
|
||||
const SKIP_TAGS = new Set([
|
||||
'SCRIPT',
|
||||
'STYLE',
|
||||
'NOSCRIPT',
|
||||
'CODE',
|
||||
'PRE',
|
||||
'TEXTAREA',
|
||||
'SVG',
|
||||
'MATH',
|
||||
'KBD',
|
||||
'SAMP',
|
||||
'VAR',
|
||||
'CANVAS',
|
||||
'VIDEO',
|
||||
'AUDIO',
|
||||
'IFRAME',
|
||||
]);
|
||||
const SKIP_SELECTOR = [
|
||||
'#ag-usage-monitor-capsule',
|
||||
'#ag-usage-monitor-portal',
|
||||
'[data-ag-i18n-ignore]',
|
||||
'[contenteditable="true"]',
|
||||
'.monaco-editor',
|
||||
'.xterm',
|
||||
'.cm-editor',
|
||||
'.ProseMirror',
|
||||
'.markdown-body',
|
||||
'.prose',
|
||||
'[data-testid="user-message-content"]',
|
||||
'[data-testid="markdown-code-block-preview"]',
|
||||
'[data-testid="markdown-frontmatter"]',
|
||||
'[data-testid="automation-instructions-markdown"]',
|
||||
'[data-testid="code-gutter"]',
|
||||
'[data-testid="code-gutter-diff"]',
|
||||
'[data-testid="diff-gutter-strip"]',
|
||||
'[data-testid="artifact-pdf-view"]',
|
||||
'.diff-line',
|
||||
'.view-lines',
|
||||
].join(',');
|
||||
const UI_CONTROL_SELECTOR = [
|
||||
'button',
|
||||
'[role="button"]',
|
||||
'[role="menuitem"]',
|
||||
'[role="tab"]',
|
||||
'[role="option"]',
|
||||
'[role="switch"]',
|
||||
'[role="checkbox"]',
|
||||
'[role="radio"]',
|
||||
'[role="heading"]',
|
||||
'[role="tooltip"]',
|
||||
'[role="status"]',
|
||||
'label',
|
||||
'legend',
|
||||
'caption',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'th',
|
||||
'dt',
|
||||
'dd',
|
||||
'p',
|
||||
'span',
|
||||
'nav a',
|
||||
'[placeholder]',
|
||||
'[title]',
|
||||
'[aria-label]',
|
||||
'[aria-description]',
|
||||
].join(',');
|
||||
const NON_LATIN_RE = /[\u3000-\u9fff\uac00-\ud7af\u0400-\u04ff]/;
|
||||
const NOISE_RE =
|
||||
/^(?:https?:\/\/|file:\/\/|\/|~\.|[A-Za-z]:\\|[\w.+-]+@[\w.-]+\.[a-z]{2,}$|[0-9a-f]{8}-[0-9a-f]{4}-|v?\d+(?:\.\d+)+$|\/[a-z0-9_-]+$|(?:gemini|claude|gpt|o[134])\b)/i;
|
||||
|
||||
function isSkipped(el) {
|
||||
if (!el || el.nodeType !== 1) return false;
|
||||
if (SKIP_TAGS.has(el.tagName)) return true;
|
||||
if (el.isContentEditable === true) return true;
|
||||
if (el.id === 'ag-usage-monitor-capsule' || el.id === 'ag-usage-monitor-portal') return true;
|
||||
if (typeof el.closest === 'function') {
|
||||
try {
|
||||
if (el.closest(SKIP_SELECTOR)) return true;
|
||||
} catch {
|
||||
// 忽略选择器异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const counts = new Map();
|
||||
const kinds = new Map();
|
||||
|
||||
function recordCandidate(raw, kind) {
|
||||
if (typeof raw !== 'string') return;
|
||||
if (raw.includes('\n') || raw.includes('\r')) return;
|
||||
const text = raw.trim();
|
||||
if (text.length < 2 || text.length > 260) return;
|
||||
if (!/[A-Za-z]{2,}/.test(text)) return;
|
||||
if (NON_LATIN_RE.test(text)) return;
|
||||
if (NOISE_RE.test(text)) return;
|
||||
if (/^[0-9.,:%$+\-*/\s()[\]]+$/.test(text)) return;
|
||||
if (activeState?.matchers?.exactMap?.has(text)) return;
|
||||
if (text.length <= 80 && activeState?.matchers?.exactLowerMap?.has(text.toLowerCase())) return;
|
||||
counts.set(text, (counts.get(text) || 0) + 1);
|
||||
if (!kinds.has(text)) kinds.set(text, kind);
|
||||
}
|
||||
|
||||
const elements =
|
||||
typeof root.querySelectorAll === 'function' ? root.querySelectorAll(UI_CONTROL_SELECTOR) : [];
|
||||
for (let i = 0; i < elements.length; i += 1) {
|
||||
const el = elements[i];
|
||||
if (isSkipped(el)) continue;
|
||||
for (const attrName of ['placeholder', 'title', 'aria-label', 'aria-description']) {
|
||||
const val = el.getAttribute?.(attrName);
|
||||
const attrMap = activeState?.attrRecords?.get(el);
|
||||
if (val && !(attrMap && attrMap.has(attrName))) {
|
||||
recordCandidate(val, attrName);
|
||||
}
|
||||
}
|
||||
const children = el.childNodes || [];
|
||||
for (let j = 0; j < children.length; j += 1) {
|
||||
const ch = children[j];
|
||||
if (ch && ch.nodeType === 3) {
|
||||
if (activeState?.textRecords?.has(ch)) continue;
|
||||
recordCandidate(ch.nodeValue, 'text');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const items = Array.from(counts.entries())
|
||||
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
||||
.slice(0, 500)
|
||||
.map(([text, count]) => ({ text, kind: kinds.get(text) || 'text', count }));
|
||||
|
||||
return { count: items.length, items };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成按需采集未命中 UI 词条的只读 CDP 表达式。
|
||||
*/
|
||||
export function createHostI18nCollectExpression() {
|
||||
return `(${collectUntranslatedHostUiInPage.toString()})(${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
|
||||
}
|
||||
@@ -538,6 +538,24 @@ export function createStandaloneWebServer(options = {}) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const remoteAddr = String(req.socket?.remoteAddress || '').trim();
|
||||
const isLoopbackClient =
|
||||
!remoteAddr ||
|
||||
remoteAddr === '127.0.0.1' ||
|
||||
remoteAddr === '::1' ||
|
||||
remoteAddr === '::ffff:127.0.0.1';
|
||||
if (pathname === '/api/host-i18n' && method === 'POST' && !isLoopbackClient) {
|
||||
sendResponse(
|
||||
res,
|
||||
403,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
error: 'Host I18n mutations are only allowed from loopback clients',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
let data = undefined;
|
||||
if (method === 'GET') {
|
||||
data = Object.fromEntries(urlObj.searchParams.entries());
|
||||
@@ -559,6 +577,25 @@ export function createStandaloneWebServer(options = {}) {
|
||||
} else {
|
||||
data = {};
|
||||
}
|
||||
if (
|
||||
pathname === '/api/settings' &&
|
||||
data &&
|
||||
typeof data === 'object' &&
|
||||
typeof data.__hostI18nAction === 'string' &&
|
||||
data.__hostI18nAction !== 'get' &&
|
||||
!isLoopbackClient
|
||||
) {
|
||||
sendResponse(
|
||||
res,
|
||||
403,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
error: 'Host I18n mutations are only allowed from loopback clients',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
pathname === '/api/settings' &&
|
||||
data &&
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
WINDOW_OVERLAY_KEY,
|
||||
WINDOW_OVERLAY_METHODS,
|
||||
} from '../shared/window-bridge-protocol.mjs';
|
||||
import { HOST_I18N_GLOBAL_KEY } from '../shared/host-i18n-protocol.mjs';
|
||||
import {
|
||||
DATA_DIR,
|
||||
computeRuntimeCodeVersion,
|
||||
@@ -45,6 +46,13 @@ import {
|
||||
getContextWindowModels,
|
||||
resolveContextWindowRules,
|
||||
} from './context-windows.mjs';
|
||||
import {
|
||||
createHostI18nApplyExpression,
|
||||
createHostI18nCollectExpression,
|
||||
createHostI18nDisposeExpression,
|
||||
createHostI18nHeartbeatExpression,
|
||||
getHostI18nBridgeDescriptor,
|
||||
} from './host-i18n/index.mjs';
|
||||
import {
|
||||
ensureDesktopLaunchEntriesConfigured,
|
||||
resolveDesktopHostExecutable,
|
||||
@@ -64,6 +72,7 @@ import { getDefaultCloudCodeProxy } from './cloudcode-proxy.mjs';
|
||||
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
||||
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
|
||||
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
|
||||
const windowHostI18nRef = `window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}]`;
|
||||
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
|
||||
const windowBridgeEndpointKey = JSON.stringify(WINDOW_BRIDGE_ENDPOINT_KEY);
|
||||
const overlayMethods = Object.fromEntries(
|
||||
@@ -1150,6 +1159,10 @@ export function createWindowBridgeController(options) {
|
||||
cloudCodeProxy = null,
|
||||
manageCloudCodeProxy = false,
|
||||
resolveLocalContextRulesFn = null,
|
||||
getHostI18nDescriptorFn =
|
||||
options?.env === undefined && options?.homeDir === undefined
|
||||
? getHostI18nBridgeDescriptor
|
||||
: () => ({ active: false, revision: '', getPayload: null }),
|
||||
} = options || {};
|
||||
|
||||
const activeCloudCodeProxy =
|
||||
@@ -1210,6 +1223,10 @@ export function createWindowBridgeController(options) {
|
||||
};
|
||||
let hadContextWindows = false;
|
||||
let contextWindowBootId = `${process.pid}:${Date.now()}`;
|
||||
let hadHostI18n = false;
|
||||
let hostI18nBootId = `hi18n:${process.pid}:${Date.now()}`;
|
||||
let lastHostI18nAppliedCount = 0;
|
||||
let cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
|
||||
const cachedBackendCtxModelsByEndpoint = new Map();
|
||||
const targetClassifyCache = new Map();
|
||||
let nodeDepsPromise = null;
|
||||
@@ -1879,10 +1896,21 @@ export function createWindowBridgeController(options) {
|
||||
const needsMainCdpContext = hasContextWindows && ctxMainEnabled;
|
||||
const needsCloudCodeProxy = hasContextWindows && ctxSwarmEnabled;
|
||||
const needsAnyCdpContext = hasContextWindows && (ctxMainEnabled || ctxSwarmEnabled);
|
||||
const hostI18nDesc =
|
||||
typeof getHostI18nDescriptorFn === 'function' ? getHostI18nDescriptorFn() : null;
|
||||
const needsHostI18n = Boolean(
|
||||
hostI18nDesc?.active &&
|
||||
hostI18nDesc?.revision &&
|
||||
typeof hostI18nDesc?.getPayload === 'function'
|
||||
);
|
||||
|
||||
let leasedBySelf = false;
|
||||
let currentLease = null;
|
||||
if ((enabled || needsAnyCdpContext || needsCloudCodeProxy) && leaseFilePath && !forceReinject) {
|
||||
if (
|
||||
(enabled || needsAnyCdpContext || needsCloudCodeProxy || needsHostI18n) &&
|
||||
leaseFilePath &&
|
||||
!forceReinject
|
||||
) {
|
||||
const lease = loadJson(leaseFilePath, null);
|
||||
currentLease = lease;
|
||||
const leasePid = Number(lease?.pid || 0);
|
||||
@@ -1951,7 +1979,7 @@ export function createWindowBridgeController(options) {
|
||||
}
|
||||
|
||||
const shouldCheckLaunchers =
|
||||
(enabled || needsMainCdpContext) &&
|
||||
(enabled || needsMainCdpContext || needsHostI18n) &&
|
||||
autoConfigureIdeArgv &&
|
||||
(lastLauncherProvisionAtMs === 0 ||
|
||||
Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs);
|
||||
@@ -1966,12 +1994,15 @@ export function createWindowBridgeController(options) {
|
||||
if (provPending) {
|
||||
await provPending.catch(() => {});
|
||||
}
|
||||
updateBridgeStatus(enabled || needsMainCdpContext ? 'no_devtools_port' : 'disabled', {
|
||||
enabled,
|
||||
leasedBySelf,
|
||||
bundleVersion,
|
||||
prevLease: currentLease,
|
||||
});
|
||||
updateBridgeStatus(
|
||||
enabled || needsMainCdpContext || needsHostI18n ? 'no_devtools_port' : 'disabled',
|
||||
{
|
||||
enabled,
|
||||
leasedBySelf,
|
||||
bundleVersion,
|
||||
prevLease: currentLease,
|
||||
}
|
||||
);
|
||||
return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 };
|
||||
}
|
||||
|
||||
@@ -1984,12 +2015,15 @@ export function createWindowBridgeController(options) {
|
||||
if (provPending) {
|
||||
await provPending.catch(() => {});
|
||||
}
|
||||
updateBridgeStatus(enabled || needsMainCdpContext ? 'cdp_unreachable' : 'disabled', {
|
||||
enabled,
|
||||
leasedBySelf,
|
||||
bundleVersion,
|
||||
prevLease: currentLease,
|
||||
});
|
||||
updateBridgeStatus(
|
||||
enabled || needsMainCdpContext || needsHostI18n ? 'cdp_unreachable' : 'disabled',
|
||||
{
|
||||
enabled,
|
||||
leasedBySelf,
|
||||
bundleVersion,
|
||||
prevLease: currentLease,
|
||||
}
|
||||
);
|
||||
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
|
||||
}
|
||||
|
||||
@@ -2012,6 +2046,8 @@ export function createWindowBridgeController(options) {
|
||||
!enabled &&
|
||||
!needsAnyCdpContext &&
|
||||
!hadContextWindows &&
|
||||
!needsHostI18n &&
|
||||
!hadHostI18n &&
|
||||
!hadInjectedTargets &&
|
||||
!hadInjectedChatFrames &&
|
||||
!forceReinject
|
||||
@@ -2251,6 +2287,66 @@ export function createWindowBridgeController(options) {
|
||||
hadContextWindows = needsAnyCdpContext;
|
||||
}
|
||||
|
||||
if (needsHostI18n || hadHostI18n) {
|
||||
const hostI18nWsUrls = new Set();
|
||||
for (const target of targets) {
|
||||
if (target.isIdeWorkbench) continue;
|
||||
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
|
||||
if (wsUrl) hostI18nWsUrls.add(wsUrl);
|
||||
}
|
||||
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
|
||||
if (chatUrl) hostI18nWsUrls.add(chatUrl);
|
||||
}
|
||||
|
||||
if (!needsHostI18n) {
|
||||
const disposeHostI18nExpr = createHostI18nDisposeExpression();
|
||||
await Promise.allSettled(
|
||||
Array.from(hostI18nWsUrls).map((wsUrl) => evaluateOnTarget(wsUrl, disposeHostI18nExpr))
|
||||
);
|
||||
hadHostI18n = false;
|
||||
lastHostI18nAppliedCount = 0;
|
||||
cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
|
||||
} else {
|
||||
const heartbeatExpr = createHostI18nHeartbeatExpression(
|
||||
hostI18nBootId,
|
||||
hostI18nDesc.revision
|
||||
);
|
||||
let appliedTargets = 0;
|
||||
await Promise.allSettled(
|
||||
Array.from(hostI18nWsUrls).map(async (wsUrl) => {
|
||||
try {
|
||||
const hbRes = await evaluateOnTarget(wsUrl, heartbeatExpr, 1800);
|
||||
const hbVal = hbRes?.result?.result?.value;
|
||||
if (hbVal?.alive === true && hbVal?.needsApply === false) {
|
||||
appliedTargets += 1;
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 心跳异常时回退完整注入
|
||||
}
|
||||
if (
|
||||
!cachedHostI18nApply.expr ||
|
||||
cachedHostI18nApply.revision !== hostI18nDesc.revision ||
|
||||
cachedHostI18nApply.bootId !== hostI18nBootId
|
||||
) {
|
||||
const payload = hostI18nDesc.getPayload();
|
||||
cachedHostI18nApply = {
|
||||
revision: hostI18nDesc.revision,
|
||||
bootId: hostI18nBootId,
|
||||
expr: createHostI18nApplyExpression(payload, hostI18nBootId),
|
||||
};
|
||||
}
|
||||
const applyRes = await evaluateOnTarget(wsUrl, cachedHostI18nApply.expr, 8000);
|
||||
if (applyRes?.result?.result?.value?.applied) {
|
||||
appliedTargets += 1;
|
||||
}
|
||||
})
|
||||
);
|
||||
hadHostI18n = true;
|
||||
lastHostI18nAppliedCount = appliedTargets;
|
||||
}
|
||||
}
|
||||
|
||||
const disposeExpr = `(() => {
|
||||
try {
|
||||
const existed = Boolean(${windowOverlayRef} || ${windowBridgeRef});
|
||||
@@ -2784,7 +2880,10 @@ export function createWindowBridgeController(options) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
if (disposeWindows && (hadInjectedTargets || hadInjectedChatFrames || hadContextWindows)) {
|
||||
if (
|
||||
disposeWindows &&
|
||||
(hadInjectedTargets || hadInjectedChatFrames || hadContextWindows || hadHostI18n)
|
||||
) {
|
||||
const prevStopped = stopped;
|
||||
stopped = false;
|
||||
try {
|
||||
@@ -2795,6 +2894,7 @@ export function createWindowBridgeController(options) {
|
||||
}));
|
||||
const disposeExpr = `(() => {
|
||||
try {
|
||||
${windowHostI18nRef}?.dispose?.();
|
||||
${windowContextWindowsRef}?.dispose?.();
|
||||
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
|
||||
delete ${windowOverlayRef};
|
||||
@@ -2820,6 +2920,9 @@ export function createWindowBridgeController(options) {
|
||||
hadInjectedTargets = false;
|
||||
hadInjectedChatFrames = false;
|
||||
hadContextWindows = false;
|
||||
hadHostI18n = false;
|
||||
lastHostI18nAppliedCount = 0;
|
||||
cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
|
||||
if (activeCloudCodeProxy) {
|
||||
await activeCloudCodeProxy.stop().catch(() => {});
|
||||
}
|
||||
@@ -2842,7 +2945,10 @@ export function createWindowBridgeController(options) {
|
||||
const hasCtx =
|
||||
Object.keys(cur.modelContextWindows || {}).length > 0 &&
|
||||
cur.contextWindowMainEnabled !== false;
|
||||
if (!hasCtx && autoConfigureIdeArgv) {
|
||||
const hasHostI18n = Boolean(
|
||||
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
|
||||
);
|
||||
if (!hasCtx && !hasHostI18n && autoConfigureIdeArgv) {
|
||||
launcherConfigured = false;
|
||||
hasReadOnlyShortcuts = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
@@ -2870,9 +2976,12 @@ export function createWindowBridgeController(options) {
|
||||
const hasCtx =
|
||||
Object.keys(cur.modelContextWindows || {}).length > 0 &&
|
||||
cur.contextWindowMainEnabled !== false;
|
||||
const hasHostI18n = Boolean(
|
||||
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
|
||||
);
|
||||
if (hasCtx) {
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
} else if (!overlayOn && autoConfigureIdeArgv) {
|
||||
} else if (!overlayOn && !hasHostI18n && autoConfigureIdeArgv) {
|
||||
launcherConfigured = false;
|
||||
hasReadOnlyShortcuts = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
@@ -2889,16 +2998,97 @@ export function createWindowBridgeController(options) {
|
||||
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
||||
}
|
||||
|
||||
function notifyHostI18nChanged() {
|
||||
const cur = getSettingsFn() || {};
|
||||
const mountMode = normalizeWindowMountMode(cur.windowMountMode, cur.enableWindowOverlay);
|
||||
const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||
const hasCtx =
|
||||
Object.keys(cur.modelContextWindows || {}).length > 0 &&
|
||||
cur.contextWindowMainEnabled !== false;
|
||||
const hasHostI18n = Boolean(
|
||||
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
|
||||
);
|
||||
if (hasHostI18n) {
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
} else {
|
||||
hadHostI18n = true;
|
||||
if (!overlayOn && !hasCtx && autoConfigureIdeArgv) {
|
||||
launcherConfigured = false;
|
||||
hasReadOnlyShortcuts = false;
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
void ensureDesktopLaunchEntriesConfigured({
|
||||
enabled: false,
|
||||
env,
|
||||
platform,
|
||||
homeDir,
|
||||
execFileFn: launcherExecFileFn,
|
||||
fsOps: launcherFsOps,
|
||||
allowInTest: allowDesktopLauncherInTest,
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
||||
}
|
||||
|
||||
async function collectHostI18nUntranslatedFromTargets() {
|
||||
const cdpPorts = findActiveDevToolsPorts();
|
||||
if (!cdpPorts.length) {
|
||||
return { targets: 0, items: [] };
|
||||
}
|
||||
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({ targets: [] }));
|
||||
const wsUrls = new Set();
|
||||
for (const target of targets) {
|
||||
if (target.isIdeWorkbench) continue;
|
||||
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
|
||||
if (wsUrl) wsUrls.add(wsUrl);
|
||||
}
|
||||
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
|
||||
if (chatUrl) wsUrls.add(chatUrl);
|
||||
}
|
||||
if (wsUrls.size === 0) {
|
||||
return { targets: 0, items: [] };
|
||||
}
|
||||
const collectExpr = createHostI18nCollectExpression();
|
||||
const settled = await Promise.allSettled(
|
||||
Array.from(wsUrls).map((wsUrl) => evaluateOnTarget(wsUrl, collectExpr, 3500))
|
||||
);
|
||||
const mergedCounts = new Map();
|
||||
const mergedKinds = new Map();
|
||||
let scannedTargets = 0;
|
||||
for (const res of settled) {
|
||||
if (res.status !== 'fulfilled') continue;
|
||||
const val = res.value?.result?.result?.value;
|
||||
if (!val || !Array.isArray(val.items)) continue;
|
||||
scannedTargets += 1;
|
||||
for (const item of val.items) {
|
||||
const text = String(item?.text || '').trim();
|
||||
if (!text) continue;
|
||||
mergedCounts.set(text, (mergedCounts.get(text) || 0) + (Number(item?.count || 1) || 1));
|
||||
if (!mergedKinds.has(text)) mergedKinds.set(text, String(item?.kind || 'text'));
|
||||
}
|
||||
}
|
||||
const items = Array.from(mergedCounts.entries())
|
||||
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
||||
.slice(0, 200)
|
||||
.map(([text, count]) => ({ text, kind: mergedKinds.get(text) || 'text', count }));
|
||||
return { targets: scannedTargets, items };
|
||||
}
|
||||
|
||||
return {
|
||||
ensureBridgeServer,
|
||||
syncAllWindows,
|
||||
invokeRemoteWindowRpc,
|
||||
notifySettingChanged,
|
||||
notifyContextWindowsChanged,
|
||||
notifyHostI18nChanged,
|
||||
collectHostI18nUntranslatedFromTargets,
|
||||
start,
|
||||
stop,
|
||||
getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }),
|
||||
getBridgeStatus: () => ({ ...lastBridgeStatus }),
|
||||
getBridgeStatus: () => ({
|
||||
...lastBridgeStatus,
|
||||
hostI18nAppliedCount: lastHostI18nAppliedCount,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2957,3 +3147,15 @@ export function notifyModelContextWindowsChanged() {
|
||||
if (!defaultBridgeController) return Promise.resolve({ ok: false });
|
||||
return defaultBridgeController.notifyContextWindowsChanged();
|
||||
}
|
||||
|
||||
export function notifyHostI18nChanged() {
|
||||
if (!defaultBridgeController) return Promise.resolve({ ok: false });
|
||||
return defaultBridgeController.notifyHostI18nChanged();
|
||||
}
|
||||
|
||||
export function collectHostI18nUntranslatedFromActiveTargets() {
|
||||
if (!defaultBridgeController) {
|
||||
return Promise.resolve({ targets: 0, items: [] });
|
||||
}
|
||||
return defaultBridgeController.collectHostI18nUntranslatedFromTargets();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user