fix(frontend): prune i18n locales, add audit tooling, and fix UI warnings

Regenerate four locale bundles from static usage analysis (6024 -> 4592 keys),
align translations across locales, escape vue-i18n @ syntax, and add check-i18n
plus gap-scan tooling. Also fix TDesign drawer/textarea teardown warnings and
add missing tenantOthers section labels.
main
wizardchen 2026-07-30 20:45:01 +08:00 committed by lyingbug
parent 59cbe58330
commit 25f3751138
15 changed files with 18403 additions and 22934 deletions

View File

@ -10,7 +10,10 @@
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"test": "tsx --test"
"test": "tsx --test",
"check-i18n": "tsx --test src/i18n/localeKeyAudit.test.ts",
"scan-i18n-gaps": "tsx src/i18n/localeGapScan.ts",
"regenerate-i18n-locales": "tsx src/i18n/regeneratePrunedLocales.ts"
},
"dependencies": {
"@microsoft/fetch-event-source": "^2.0.1",

View File

@ -192,7 +192,7 @@
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { computed, ref, watch, onBeforeUnmount } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
@ -455,6 +455,12 @@ const copyResult = async () => {
MessagePlugin.error(t('common.copyFailed'))
}
}
onBeforeUnmount(() => {
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
})
</script>
<style scoped lang="less">

View File

@ -9,7 +9,7 @@
</teleport>
<t-drawer v-model:visible="drawerVisible" v-bind="drawerPassthroughAttrs" :size="effectiveWidth" :z-index="2500" placement="right"
attach="body" destroy-on-close :footer="!hideFooter"
:class="drawerClass">
:class="drawerClass" @before-close="blurActiveElementBeforeClose">
<!--
Custom header. We replace TDesign's default header so we can put a leading
icon badge and an optional subtitle (description) right next to the title,
@ -239,8 +239,18 @@ onUnmounted(() => {
cleanupResize()
})
function blurActiveElementBeforeClose() {
// TDesign textarea autosize calls getComputedStyle on blur/resize; if the
// drawer is already tearing down (destroy-on-close), that node may no longer
// be an Element and the promise rejects uncaught.
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
}
const handleConfirm = () => emit('confirm')
const handleCancel = () => {
blurActiveElementBeforeClose()
emit('cancel')
emit('update:visible', false)
}

View File

@ -0,0 +1,239 @@
import { readdirSync, readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
LOCALE_BUNDLES,
collectI18nUsageFromSources,
collectLocaleKeys,
collectReferencedLocaleKeys,
collectStaticI18nKeysFromSources,
} from './localeKeyAudit.ts'
const SOURCE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
const EXT = /\.(vue|ts|js|mjs)$/
const SKIP = /\/i18n\/locales\/|localeGapScan\.ts$|\.test\.(ts|mjs|js)$/
function walk(dir: string, out: string[] = []): string[] {
for (const ent of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, ent.name)
if (ent.isDirectory()) walk(p, out)
else if (EXT.test(ent.name) && !SKIP.test(p)) out.push(p)
}
return out
}
function flattenMessages(root: unknown, path = ''): Set<string> {
const keys = new Set<string>()
if (typeof root === 'string') {
if (path) keys.add(path)
return keys
}
if (!root || typeof root !== 'object') return keys
for (const [key, value] of Object.entries(root as Record<string, unknown>)) {
const nextPath = path ? `${path}.${key}` : key
if (typeof value === 'string') keys.add(nextPath)
else for (const child of flattenMessages(value, nextPath)) keys.add(child)
}
return keys
}
const TEMPLATE_RE = /(?:\$t|(?<![.\w])t|i18n\.global\.t|globalSettingsText)\(\s*`([^`]+)`/g
const CONCAT_RE = /(?:\$t|(?<![.\w])t)\(\s*['"]([a-zA-Z][\w.]*\.)['"]\s*\+/g
const TM_ROOT_RE = /tm\(\s*['"]([^'"]+)['"]\s*\)/g
const templatePrefixes = new Map<string, Set<string>>()
const concatPrefixes = new Map<string, Set<string>>()
const tmRoots = new Map<string, Set<string>>()
for (const file of walk(SOURCE_ROOT)) {
const rel = file.replace(SOURCE_ROOT + '/', '')
const content = readFileSync(file, 'utf8')
let match: RegExpExecArray | null
TEMPLATE_RE.lastIndex = 0
while ((match = TEMPLATE_RE.exec(content))) {
const tpl = match[1]
const idx = tpl.indexOf('${')
const prefix = idx === -1 ? tpl : tpl.slice(0, idx)
const bucket = templatePrefixes.get(prefix) ?? new Set()
bucket.add(rel)
templatePrefixes.set(prefix, bucket)
}
CONCAT_RE.lastIndex = 0
while ((match = CONCAT_RE.exec(content))) {
const prefix = match[1]
const bucket = concatPrefixes.get(prefix) ?? new Set()
bucket.add(rel)
concatPrefixes.set(prefix, bucket)
}
TM_ROOT_RE.lastIndex = 0
while ((match = TM_ROOT_RE.exec(content))) {
const root = match[1]
const bucket = tmRoots.get(root) ?? new Set()
bucket.add(rel)
tmRoots.set(root, bucket)
}
}
const usage = collectI18nUsageFromSources()
const enKeys = collectLocaleKeys(LOCALE_BUNDLES['en-US'])
const referenced = collectReferencedLocaleKeys(LOCALE_BUNDLES['en-US'], usage)
function prefixMatchesConfigured(prefix: string): boolean {
const normalized = prefix.endsWith('.') ? prefix : `${prefix}.`
for (const configured of usage.prefixes) {
if (normalized.startsWith(configured) || configured.startsWith(normalized)) return true
}
return false
}
function keysUnderPrefix(prefix: string): string[] {
const normalized = prefix.endsWith('.') ? prefix : `${prefix}.`
return [...enKeys].filter((key) => key.startsWith(normalized))
}
function missingUnderPrefix(prefix: string): string[] {
return keysUnderPrefix(prefix).filter((key) => !referenced.has(key))
}
type Gap = {
kind: 'template' | 'concat' | 'tm'
prefix: string
files: string[]
localeKeys: number
missingKeys: string[]
configured: boolean
}
const gaps: Gap[] = []
for (const [prefix, files] of templatePrefixes) {
if (!prefix.includes('.') && !prefix.includes('${')) continue
const missing = missingUnderPrefix(prefix)
const configured = prefixMatchesConfigured(prefix)
if (!configured || missing.length > 0) {
gaps.push({
kind: 'template',
prefix,
files: [...files],
localeKeys: keysUnderPrefix(prefix).length,
missingKeys: missing.slice(0, 5),
configured,
})
}
}
for (const [prefix, files] of concatPrefixes) {
const missing = missingUnderPrefix(prefix)
const configured = prefixMatchesConfigured(prefix)
if (!configured || missing.length > 0) {
gaps.push({
kind: 'concat',
prefix,
files: [...files],
localeKeys: keysUnderPrefix(prefix).length,
missingKeys: missing.slice(0, 5),
configured,
})
}
}
for (const [root, files] of tmRoots) {
const missing = missingUnderPrefix(root)
const configured = prefixMatchesConfigured(root)
if (!configured || missing.length > 0) {
gaps.push({
kind: 'tm',
prefix: root,
files: [...files],
localeKeys: keysUnderPrefix(root).length,
missingKeys: missing.slice(0, 5),
configured,
})
}
}
// embed bundle audit
const embedFile = join(dirname(fileURLToPath(import.meta.url)), 'embed.ts')
const embedSource = readFileSync(embedFile, 'utf8')
const embedMessagesMatch = embedSource.match(/const messages = (\{[\s\S]*?\n\}) as const/)
const embedMessages = embedMessagesMatch
? (Function(`"use strict"; return (${embedMessagesMatch[1]});`)() as Record<string, unknown>)
: {}
const embedKeysByLocale = Object.fromEntries(
Object.entries(embedMessages).map(([locale, bundle]) => [locale, flattenMessages(bundle)]),
) as Record<string, Set<string>>
const embedStaticKeys = new Set<string>()
const EMBED_STATIC_RE = /(?:\$t|(?<![.\w])t)\(\s*['"]([^'"]+)['"]/g
for (const file of walk(join(SOURCE_ROOT, 'views/embed'))) {
const content = readFileSync(file, 'utf8')
let match: RegExpExecArray | null
EMBED_STATIC_RE.lastIndex = 0
while ((match = EMBED_STATIC_RE.exec(content))) embedStaticKeys.add(match[1])
}
const embedReference = embedKeysByLocale['en-US'] ?? new Set<string>()
const embedMissing: string[] = []
for (const key of embedStaticKeys) {
for (const [locale, keys] of Object.entries(embedKeysByLocale)) {
if (!keys.has(key)) embedMissing.push(`${key} -> missing in embed ${locale}`)
}
}
const embedDrift: string[] = []
for (const [locale, keys] of Object.entries(embedKeysByLocale)) {
if (locale === 'en-US') continue
for (const key of embedReference) {
if (!keys.has(key)) embedDrift.push(`${locale}: missing ${key}`)
}
for (const key of keys) {
if (!embedReference.has(key)) embedDrift.push(`${locale}: extra ${key}`)
}
}
console.log('=== Main app: dynamic prefix gaps ===')
console.log(`Template literal prefixes: ${templatePrefixes.size}`)
console.log(`String concat prefixes: ${concatPrefixes.size}`)
console.log(`tm() roots: ${tmRoots.size}`)
console.log(`Potential gaps: ${gaps.length}`)
for (const gap of gaps.sort((a, b) => a.prefix.localeCompare(b.prefix))) {
console.log(`\n[${gap.kind}] ${gap.prefix}`)
console.log(` configured: ${gap.configured}, locale keys: ${gap.localeKeys}, missing referenced: ${gap.missingKeys.length}`)
if (gap.missingKeys.length) console.log(` sample missing: ${gap.missingKeys.join(', ')}`)
console.log(` files: ${gap.files.slice(0, 3).join(', ')}${gap.files.length > 3 ? '...' : ''}`)
}
console.log('\n=== Embed bundle (src/i18n/embed.ts) ===')
for (const [locale, keys] of Object.entries(embedKeysByLocale)) {
console.log(`${locale}: ${keys.size} keys`)
}
console.log(`Embed static keys used in views/embed: ${embedStaticKeys.size}`)
console.log(`Embed key parity issues: ${embedDrift.length}`)
console.log(`Embed missing used keys: ${embedMissing.length}`)
if (embedMissing.length) console.log(embedMissing.slice(0, 10).join('\n'))
if (embedDrift.length) console.log(embedDrift.slice(0, 10).join('\n'))
console.log('\n=== Main locale uncovered keys (in bundle, not referenced) ===')
const uncovered = [...enKeys].filter((key) => !referenced.has(key))
console.log(`Count: ${uncovered.length}`)
console.log('\n=== Indirect i18n keys (computed / inline ternary) ===')
const staticKeys = collectStaticI18nKeysFromSources()
const indirectCandidates = [
'knowledgeList.sections.tenantOthers',
'knowledgeList.sections.tenantReadonly',
'agent.sections.tenantOthers',
'agent.sections.tenantReadonly',
'modelSettings.builtinModels.descriptionAdmin',
'modelSettings.builtinModels.description',
]
for (const key of indirectCandidates) {
console.log(
`${key}: tracked=${staticKeys.has(key)} locale=${enKeys.has(key)} referenced=${referenced.has(key)}`,
)
}

View File

@ -0,0 +1,87 @@
import assert from 'node:assert/strict'
import { before, test } from 'node:test'
import {
CRITICAL_LOCALE_KEYS,
LOCALE_BUNDLES,
collectI18nUsageFromSources,
collectLocaleKeys,
collectReferencedLocaleKeys,
diffLocaleKeys,
findAllLocaleMessageCompileErrors,
findUsedKeysMissingInLocales,
type LocaleName,
} from './localeKeyAudit.ts'
const REFERENCE_LOCALE: LocaleName = 'en-US'
let localeKeysByName: Record<LocaleName, Set<string>>
let referencedKeys: Set<string>
before(() => {
const usage = collectI18nUsageFromSources()
localeKeysByName = Object.fromEntries(
Object.entries(LOCALE_BUNDLES).map(([name, bundle]) => [name, collectLocaleKeys(bundle)]),
) as Record<LocaleName, Set<string>>
referencedKeys = collectReferencedLocaleKeys(LOCALE_BUNDLES[REFERENCE_LOCALE], usage)
})
test('locale bundles expose the same translation keys', () => {
const referenceKeys = localeKeysByName[REFERENCE_LOCALE]
const mismatches: string[] = []
for (const [localeName, keys] of Object.entries(localeKeysByName) as Array<[LocaleName, Set<string>]>) {
if (localeName === REFERENCE_LOCALE) continue
const { missing, extra } = diffLocaleKeys(referenceKeys, keys)
for (const key of missing) mismatches.push(`${localeName}: missing ${key}`)
for (const key of extra) mismatches.push(`${localeName}: extra ${key}`)
}
assert.deepEqual(mismatches, [], mismatches.slice(0, 20).join('\n'))
})
test('critical runtime i18n trees are present', () => {
const en = localeKeysByName['en-US']
const missing = CRITICAL_LOCALE_KEYS.filter((key) => !en.has(key))
assert.deepEqual(missing, [], missing.join('\n'))
})
test('referenced i18n keys used in app code exist in every locale', () => {
const failures = findUsedKeysMissingInLocales(referencedKeys, localeKeysByName)
assert.deepEqual(failures, [], failures.slice(0, 20).join('\n'))
})
const PARSER_ENGINE_NAMES = [
'builtin',
'simple',
'mineru',
'mineru_cloud',
'paddleocr_vl',
'paddleocr_vl_cloud',
'weknoracloud',
'markitdown',
'opendataloader',
] as const
test('parser engine display keys exist in every locale', () => {
const failures: string[] = []
for (const engineName of PARSER_ENGINE_NAMES) {
for (const [localeName, keys] of Object.entries(localeKeysByName) as Array<[LocaleName, Set<string>]>) {
for (const suffix of ['name', 'desc'] as const) {
const key = `kbSettings.parser.engines.${engineName}.${suffix}`
if (!keys.has(key)) failures.push(`${localeName}: missing ${key}`)
}
}
}
assert.deepEqual(failures, [], failures.join('\n'))
})
test('locale messages compile with vue-i18n syntax rules', () => {
const failures = findAllLocaleMessageCompileErrors(LOCALE_BUNDLES)
const summary = failures.map(
(failure) => `${failure.path}: ${failure.message}\n ${failure.value}`,
)
assert.deepEqual(summary, [], summary.slice(0, 20).join('\n'))
})

View File

@ -0,0 +1,666 @@
import { execSync } from 'node:child_process'
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { compile, type CompileError } from '@intlify/core-base'
import { writeLocaleModule } from './localeSerialize.ts'
import enUS from './locales/en-US.ts'
import koKR from './locales/ko-KR.ts'
import ruRU from './locales/ru-RU.ts'
import zhCN from './locales/zh-CN.ts'
export const LOCALE_BUNDLES = {
'en-US': enUS,
'zh-CN': zhCN,
'ko-KR': koKR,
'ru-RU': ruRU,
} as const
export type LocaleName = keyof typeof LOCALE_BUNDLES
const SOURCE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
const SOURCE_EXTENSIONS = /\.(vue|ts|js|mjs)$/
const TEST_FILE_PATTERN = /\.test\.(ts|mjs|js)$/
const I18N_SOURCE_HINTS = ['$t(', 'i18n.global.t(', "t('", 't("', ".t('", '.t("'] as const
const STATIC_KEY_PATTERNS = [
/\$t\(\s*['"]([^'"]+)['"]/g,
/i18n\.global\.t\(\s*['"]([^'"]+)['"]/g,
/(?<![.\w])t\(\s*['"]([^'"]+)['"]/g,
/(?<![.\w])te\(\s*['"]([^'"]+)['"]/g,
] as const
const CONCAT_KEY_PATTERNS = [
/\$t\(\s*['"]([^'"]+)['"]\s*\+/g,
/i18n\.global\.t\(\s*['"]([^'"]+)['"]\s*\+/g,
/(?<![.\w])t\(\s*['"]([^'"]+)['"]\s*\+/g,
] as const
const TEMPLATE_KEY_PATTERNS = [
/\$t\(\s*`([^`]+)`/g,
/i18n\.global\.t\(\s*`([^`]+)`/g,
/(?<![.\w])t\(\s*`([^`]+)`/g,
/(?<![.\w])te\(\s*`([^`]+)`/g,
/globalSettingsText\(\s*`([^`]+)`/g,
] as const
const METADATA_KEY_PATTERNS = [
/\b(?:labelKey|hintKey|titleKey|i18nKey)\s*:\s*['"]([^'"]+)['"]/g,
/\bstepI18nPrefix\s*:\s*['"]([^'"]+)['"]/g,
] as const
const STEP_PREFIX_PATTERNS = [
/step-i18n-prefix=["']([^"']+)["']/g,
] as const
const TM_KEY_PATTERNS = [
/(?<![.\w])tm\(\s*['"]([^'"]+)['"]/g,
] as const
const EXTRA_PREFIXES = [
'system.globalSettings.listConfirm.',
'system.globalSettings.admins.confirm.',
'system.globalSettings.keyLabels.',
'system.globalSettings.keyDescriptions.',
'system.globalSettings.enumLabels.',
'system.globalSettings.audit.action.',
'system.globalSettings.audit.actorRole.',
'knowledgeEditor.activity.detailFields.',
'knowledgeEditor.activity.actions.',
'knowledgeEditor.activity.targets.',
'tenantMember.audit.action.',
'newUserGuide.steps.',
'contextualGuide.kbList.steps.',
'contextualGuide.kbCreate.steps.',
'contextualGuide.tenantModels.steps.',
'contextualGuide.tenantModels.stepsAgent.',
'contextualGuide.kbDetail.steps.',
'contextualGuide.chat.steps.',
'contextualGuide.agentList.steps.',
'contextualGuide.agentCreate.steps.',
'kbSettings.parser.engines.',
'model.editor.description.',
'integrations.tabs.',
'knowledgeStages.stage.',
'knowledgeStages.status.',
'organization.role.',
'inviteRegister.',
'modelSettings.builtinModels.',
] as const
/** Keys that must survive pruning even when static analysis misses them. */
export const CRITICAL_LOCALE_KEYS = [
'newUserGuide.steps.welcome.title',
'contextualGuide.kbList.steps.create.title',
'tenantMember.audit.action.rbac.member_added',
'system.globalSettings.audit.action.system.setting_changed',
'knowledgeEditor.activity.targets.knowledge_base',
'modelSettings.builtinModels.descriptionAdmin',
'model.editor.description.chat',
'model.editor.description.asr',
'inviteRegister.emailPlaceholder',
'knowledgeList.sections.tenantOthers',
'agent.sections.tenantOthers',
] as const
function addPrefix(usage: I18nUsage, prefix: string): void {
if (!prefix) return
usage.prefixes.add(prefix.endsWith('.') ? prefix : `${prefix}.`)
}
function buildI18nLiteralPattern(): RegExp {
const namespaces = Object.keys(enUS as Record<string, unknown>)
.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
// Only match object-literal values (e.g. labelKey: 'foo.bar'), not Vue bindings like :name="agent.name".
return new RegExp(`(?:[:,(]\\s*)['"]((?:${namespaces})\\.[^'"]+)['"]`, 'g')
}
export type I18nUsage = {
staticKeys: Set<string>
prefixes: Set<string>
segmentPatterns: string[][]
}
/** Flatten a locale object into dot-path keys without recursive flatMap allocations. */
export function collectLocaleKeys(root: unknown): Set<string> {
const keys = new Set<string>()
const stack: Array<{ value: unknown; path: string }> = [{ value: root, path: '' }]
while (stack.length > 0) {
const current = stack.pop()!
const { value, path } = current
if (typeof value === 'string') {
if (path) keys.add(path)
continue
}
if (Array.isArray(value)) {
for (let index = value.length - 1; index >= 0; index -= 1) {
stack.push({ value: value[index], path: `${path}[${index}]` })
}
continue
}
if (!value || typeof value !== 'object') continue
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
const nextPath = path ? `${path}.${key}` : key
if (typeof child === 'string') keys.add(nextPath)
else stack.push({ value: child, path: nextPath })
}
}
return keys
}
function isAuditableSourceFile(path: string): boolean {
if (!SOURCE_EXTENSIONS.test(path)) return false
if (path.includes('/i18n/locales/')) return false
if (TEST_FILE_PATTERN.test(path)) return false
return true
}
function listSourceFiles(dir: string, results: string[] = []): string[] {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name)
if (entry.isDirectory()) {
if (entry.name !== 'node_modules') listSourceFiles(path, results)
continue
}
if (isAuditableSourceFile(path)) results.push(path)
}
return results
}
function isStaticTranslationKey(key: string): boolean {
if (!key || key.endsWith('.')) return false
return /^[\w.-]+$/.test(key)
}
const KNOWN_LOCALE_NAMESPACES = new Set(Object.keys(enUS as Record<string, unknown>))
const INDIRECT_TERNARY_IN_T_RE = /\$t\(\s*[\s\S]*?\? ['"]([^'"]+)['"]\s*:\s*['"]([^'"]+)['"]/g
const INDIRECT_VAR_T_RE = /\$t\(([a-zA-Z_][\w]*)\)/g
function addIndirectTranslationKeys(content: string, usage: I18nUsage): void {
INDIRECT_TERNARY_IN_T_RE.lastIndex = 0
let match: RegExpExecArray | null
while ((match = INDIRECT_TERNARY_IN_T_RE.exec(content)) !== null) {
for (const key of [match[1], match[2]]) {
if (KNOWN_LOCALE_NAMESPACES.has(key.split('.')[0]) && isStaticTranslationKey(key)) {
usage.staticKeys.add(key)
}
}
}
const variableNames = new Set<string>()
INDIRECT_VAR_T_RE.lastIndex = 0
while ((match = INDIRECT_VAR_T_RE.exec(content)) !== null) {
variableNames.add(match[1])
}
for (const variableName of variableNames) {
const computedPattern = new RegExp(
`${escapeRegExp(variableName)}\\s*=\\s*computed\\(\\(\\)\\s*=>[\\s\\S]*?\\n\\)`,
'm',
)
const block = content.match(computedPattern)?.[0]
if (!block) continue
const ternaryPattern = /\? ['"]([^'"]+)['"]\s*:\s*['"]([^'"]+)['"]/g
ternaryPattern.lastIndex = 0
while ((match = ternaryPattern.exec(block)) !== null) {
for (const key of [match[1], match[2]]) {
if (KNOWN_LOCALE_NAMESPACES.has(key.split('.')[0]) && isStaticTranslationKey(key)) {
usage.staticKeys.add(key)
}
}
}
}
}
let cachedSourceFiles: string[] | undefined
function getSourceFiles(rootDir = SOURCE_ROOT): string[] {
if (!cachedSourceFiles) cachedSourceFiles = listSourceFiles(rootDir)
return cachedSourceFiles
}
/** Collect literal i18n keys from app source (excludes locale bundles and tests). */
export function collectStaticI18nKeysFromSources(rootDir = SOURCE_ROOT): Set<string> {
return collectI18nUsageFromSources(rootDir).staticKeys
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function addTemplatePattern(usage: I18nUsage, template: string): void {
const trimmed = template.trim()
if (!trimmed || !trimmed.includes('${')) return
const parts = trimmed.split(/\$\{[^}]+\}/)
if (parts.length === 1) {
usage.prefixes.add(parts[0])
return
}
if (parts.length === 2 && parts[1] === '') {
usage.prefixes.add(parts[0])
return
}
usage.segmentPatterns.push(parts)
}
export function collectI18nUsageFromSources(rootDir = SOURCE_ROOT): I18nUsage {
const usage: I18nUsage = {
staticKeys: new Set<string>(),
prefixes: new Set<string>(EXTRA_PREFIXES),
segmentPatterns: [],
}
const i18nLiteralPattern = buildI18nLiteralPattern()
for (const file of getSourceFiles(rootDir)) {
const content = readFileSync(file, 'utf8')
for (const pattern of STATIC_KEY_PATTERNS) {
pattern.lastIndex = 0
let match: RegExpExecArray | null
while ((match = pattern.exec(content)) !== null) {
const key = match[1]
if (isStaticTranslationKey(key)) usage.staticKeys.add(key)
}
}
for (const pattern of METADATA_KEY_PATTERNS) {
pattern.lastIndex = 0
let match: RegExpExecArray | null
while ((match = pattern.exec(content)) !== null) {
const key = match[1]
if (key.includes('.steps')) addPrefix(usage, key)
else if (isStaticTranslationKey(key)) usage.staticKeys.add(key)
}
}
for (const pattern of STEP_PREFIX_PATTERNS) {
pattern.lastIndex = 0
let match: RegExpExecArray | null
while ((match = pattern.exec(content)) !== null) {
addPrefix(usage, match[1])
}
}
for (const pattern of TM_KEY_PATTERNS) {
pattern.lastIndex = 0
let match: RegExpExecArray | null
while ((match = pattern.exec(content)) !== null) {
addPrefix(usage, match[1])
}
}
i18nLiteralPattern.lastIndex = 0
let literalMatch: RegExpExecArray | null
while ((literalMatch = i18nLiteralPattern.exec(content)) !== null) {
const key = literalMatch[1]
if (isStaticTranslationKey(key)) usage.staticKeys.add(key)
}
for (const pattern of CONCAT_KEY_PATTERNS) {
pattern.lastIndex = 0
let match: RegExpExecArray | null
while ((match = pattern.exec(content)) !== null) {
const prefix = match[1]
if (prefix) usage.prefixes.add(prefix)
}
}
for (const pattern of TEMPLATE_KEY_PATTERNS) {
pattern.lastIndex = 0
let match: RegExpExecArray | null
while ((match = pattern.exec(content)) !== null) {
addTemplatePattern(usage, match[1])
}
}
addIndirectTranslationKeys(content, usage)
}
return usage
}
export function isLocaleKeyUsed(key: string, usage: I18nUsage): boolean {
if (usage.staticKeys.has(key)) return true
for (const prefix of usage.prefixes) {
if (key.startsWith(prefix)) return true
}
for (const parts of usage.segmentPatterns) {
let pattern = '^'
for (let index = 0; index < parts.length; index += 1) {
pattern += escapeRegExp(parts[index])
if (index < parts.length - 1) pattern += '[^.]+'
}
pattern += '$'
if (new RegExp(pattern).test(key)) return true
}
return false
}
export function collectReferencedLocaleKeys(root: unknown, usage: I18nUsage): Set<string> {
const referenced = new Set<string>()
for (const key of collectLocaleKeys(root)) {
if (isLocaleKeyUsed(key, usage)) referenced.add(key)
}
return referenced
}
export function pruneLocaleTree(root: unknown, usage: I18nUsage, path = ''): unknown {
if (typeof root === 'string') {
return path && isLocaleKeyUsed(path, usage) ? root : undefined
}
if (Array.isArray(root)) {
const pruned = root
.map((item, index) => pruneLocaleTree(item, usage, `${path}[${index}]`))
.filter((item) => item !== undefined)
return pruned.length > 0 ? pruned : undefined
}
if (!root || typeof root !== 'object') return undefined
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(root as Record<string, unknown>)) {
const nextPath = path ? `${path}.${key}` : key
const pruned = pruneLocaleTree(value, usage, nextPath)
if (pruned !== undefined) result[key] = pruned
}
return Object.keys(result).length > 0 ? result : undefined
}
export function diffLocaleKeys(reference: Set<string>, target: Set<string>): {
missing: string[]
extra: string[]
} {
const missing: string[] = []
const extra: string[] = []
for (const key of reference) {
if (!target.has(key)) missing.push(key)
}
for (const key of target) {
if (!reference.has(key)) extra.push(key)
}
missing.sort()
extra.sort()
return { missing, extra }
}
export function findUsedKeysMissingInLocales(
usedKeys: Iterable<string>,
localeKeysByName: Record<LocaleName, Set<string>>,
): string[] {
const failures: string[] = []
for (const key of usedKeys) {
const missingIn = (Object.keys(localeKeysByName) as LocaleName[]).filter(
(localeName) => !localeKeysByName[localeName].has(key),
)
if (missingIn.length > 0) failures.push(`${key} -> missing in ${missingIn.join(', ')}`)
}
failures.sort()
return failures
}
export type LocaleMessageEntry = {
path: string
value: string
}
export type LocaleMessageCompileError = {
path: string
value: string
message: string
}
const LOCALE_MESSAGE_COMPILE_OPTIONS = {
warnHtmlMessage: false,
} as const
/** Flatten a locale object into dot-path message entries. */
export function collectLocaleMessages(root: unknown, path = ''): LocaleMessageEntry[] {
if (typeof root === 'string') {
return path ? [{ path, value: root }] : []
}
if (Array.isArray(root)) {
return root.flatMap((item, index) => collectLocaleMessages(item, `${path}[${index}]`))
}
if (!root || typeof root !== 'object') return []
return Object.entries(root as Record<string, unknown>).flatMap(([key, value]) => {
const nextPath = path ? `${path}.${key}` : key
return collectLocaleMessages(value, nextPath)
})
}
/** Compile a locale message with the same vue-i18n rules used at runtime. */
export function compileLocaleMessage(
value: string,
context: { key: string; locale: string } = { key: 'audit', locale: 'en-US' },
): void {
compile(value, {
...LOCALE_MESSAGE_COMPILE_OPTIONS,
key: context.key,
locale: context.locale,
onError: (error: CompileError) => {
throw error
},
})
}
export function findLocaleMessageCompileErrors(
root: unknown,
localeName = 'locale',
): LocaleMessageCompileError[] {
const failures: LocaleMessageCompileError[] = []
for (const { path, value } of collectLocaleMessages(root)) {
try {
compileLocaleMessage(value, { key: path, locale: localeName })
} catch (error) {
failures.push({
path: `${localeName}:${path}`,
value,
message: error instanceof Error ? error.message : String(error),
})
}
}
failures.sort((left, right) => left.path.localeCompare(right.path))
return failures
}
export function findAllLocaleMessageCompileErrors(
bundles: Record<string, unknown>,
): LocaleMessageCompileError[] {
return Object.entries(bundles).flatMap(([localeName, bundle]) =>
findLocaleMessageCompileErrors(bundle, localeName),
)
}
type LocaleTree = Record<string, unknown>
const LOCALE_ORDER: LocaleName[] = ['en-US', 'zh-CN', 'ko-KR', 'ru-RU']
const LOCALES_DIR = join(dirname(fileURLToPath(import.meta.url)), 'locales')
function getLocaleValueAtPathParts(current: unknown, parts: string[]): unknown {
if (parts.length === 0) return current
if (current == null || typeof current !== 'object' || Array.isArray(current)) return undefined
const object = current as Record<string, unknown>
for (let length = parts.length; length >= 1; length -= 1) {
const key = parts.slice(0, length).join('.')
if (!Object.prototype.hasOwnProperty.call(object, key)) continue
const next = object[key]
if (length === parts.length) return next
return getLocaleValueAtPathParts(next, parts.slice(length))
}
return undefined
}
function setLocaleValueAtPathParts(current: unknown, parts: string[], value: string): void {
if (parts.length === 0) return
const object = current as Record<string, unknown>
for (let length = parts.length; length >= 1; length -= 1) {
const key = parts.slice(0, length).join('.')
if (!Object.prototype.hasOwnProperty.call(object, key) && length > 1) continue
if (length === parts.length) {
object[key] = value
return
}
let child = object[key]
if (child == null || typeof child !== 'object' || Array.isArray(child)) {
child = {}
object[key] = child
}
setLocaleValueAtPathParts(child, parts.slice(length), value)
return
}
const [head, ...tail] = parts
let child = object[head]
if (child == null || typeof child !== 'object' || Array.isArray(child)) {
child = {}
object[head] = child
}
setLocaleValueAtPathParts(child, tail, value)
}
export function getLocaleValueAtPath(root: unknown, path: string): unknown {
return getLocaleValueAtPathParts(root, path.split('.'))
}
export function setLocaleValueAtPath(root: LocaleTree, path: string, value: string): void {
if (!path) return
setLocaleValueAtPathParts(root, path.split('.'), value)
}
export function mergeLocaleKeysFromSource(
target: LocaleTree,
source: unknown,
keys: Iterable<string>,
): void {
for (const key of keys) {
if (collectLocaleKeys(target).has(key)) continue
const value = getLocaleValueAtPath(source, key)
if (typeof value === 'string') setLocaleValueAtPath(target, key, value)
}
}
export function collectRequiredLocaleKeys(usage: I18nUsage, referenceBundle: unknown): Set<string> {
return new Set([
...collectReferencedLocaleKeys(referenceBundle, usage),
...usage.staticKeys,
...CRITICAL_LOCALE_KEYS,
])
}
export function alignLocaleBundleToReferenceKeys(
referenceKeys: Set<string>,
localeFull: LocaleTree,
fallbackFull: LocaleTree,
): LocaleTree {
const aligned: LocaleTree = {}
for (const key of referenceKeys) {
const value = getLocaleValueAtPath(localeFull, key) ?? getLocaleValueAtPath(fallbackFull, key)
if (typeof value === 'string') setLocaleValueAtPath(aligned, key, value)
}
return aligned
}
export function rebuildPrunedLocales(
fullBundles: Record<LocaleName, LocaleTree>,
usage = collectI18nUsageFromSources(),
): Record<LocaleName, LocaleTree> {
const requiredKeys = collectRequiredLocaleKeys(usage, fullBundles['en-US'])
const enFull = structuredClone(fullBundles['en-US'])
const enPruned = pruneLocaleTree(enFull, usage)
if (!enPruned || typeof enPruned !== 'object' || Array.isArray(enPruned)) {
throw new Error('prune removed entire en-US locale bundle')
}
const enTree = enPruned as LocaleTree
mergeLocaleKeysFromSource(enTree, fullBundles['en-US'], requiredKeys)
const referenceKeys = collectLocaleKeys(enTree)
const rebuilt = { 'en-US': enTree } as Record<LocaleName, LocaleTree>
for (const localeName of LOCALE_ORDER) {
if (localeName === 'en-US') continue
rebuilt[localeName] = alignLocaleBundleToReferenceKeys(
referenceKeys,
fullBundles[localeName],
fullBundles['en-US'],
)
}
return rebuilt
}
export function writePrunedLocaleFiles(
bundles: Record<LocaleName, LocaleTree>,
localesDir = LOCALES_DIR,
): void {
for (const localeName of LOCALE_ORDER) {
writeLocaleModule(join(localesDir, `${localeName}.ts`), bundles[localeName])
}
}
const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '../../..')
export async function loadFullLocaleBundlesFromGit(
ref = 'HEAD',
): Promise<Record<LocaleName, LocaleTree>> {
const tempDir = mkdtempSync(join(tmpdir(), 'weknora-locales-'))
try {
const bundles = {} as Record<LocaleName, LocaleTree>
for (const localeName of LOCALE_ORDER) {
const relativePath = `frontend/src/i18n/locales/${localeName}.ts`
const content = execSync(`git show ${ref}:${relativePath}`, {
cwd: REPO_ROOT,
encoding: 'utf8',
})
const filePath = join(tempDir, `${localeName}.ts`)
writeFileSync(filePath, content, 'utf8')
const mod = await import(pathToFileURL(filePath).href)
bundles[localeName] = structuredClone(mod.default) as LocaleTree
}
return bundles
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
}
export async function regeneratePrunedLocaleFiles(localesDir = LOCALES_DIR): Promise<{
before: number
after: number
}> {
const usage = collectI18nUsageFromSources()
const sourceBundles = await loadFullLocaleBundlesFromGit()
const before = collectLocaleKeys(sourceBundles['en-US']).size
const rebuilt = rebuildPrunedLocales(sourceBundles, usage)
writePrunedLocaleFiles(rebuilt, localesDir)
return {
before,
after: collectLocaleKeys(rebuilt['en-US']).size,
}
}

View File

@ -0,0 +1,40 @@
import { writeFileSync } from 'node:fs'
export function escapeLocaleString(value: string): string {
return `'${value
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')}'`
}
export function quoteLocaleKey(key: string): string {
if (/^[A-Za-z_][\w]*$/.test(key)) return key
return escapeLocaleString(key)
}
export function serializeLocaleValue(value: unknown, indent = 0): string {
const pad = ' '.repeat(indent)
if (typeof value === 'string') return escapeLocaleString(value)
if (Array.isArray(value)) {
const items = value.map((item) => `${pad} ${serializeLocaleValue(item, indent + 1)}`)
return `[\n${items.join(',\n')}\n${pad}]`
}
if (!value || typeof value !== 'object') return 'null'
const entries = Object.entries(value as Record<string, unknown>).map(([key, child]) => {
const serialized = serializeLocaleValue(child, indent + 1)
return `${pad} ${quoteLocaleKey(key)}: ${serialized}`
})
return `{\n${entries.join(',\n')}\n${pad}}`
}
export function writeLocaleModule(file: string, tree: unknown): void {
writeFileSync(file, `export default ${serializeLocaleValue(tree, 0)}\n`, 'utf8')
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,4 @@
import { regeneratePrunedLocaleFiles } from './localeKeyAudit.ts'
const { before, after } = await regeneratePrunedLocaleFiles()
console.log(`Pruned locale keys: ${before} -> ${after} (en-US reference)`)

View File

@ -124,7 +124,7 @@
<!-- Graph page detail drawer -->
<t-drawer v-model:visible="graphDrawerVisible" :header="graphDrawerPage?.title || ''" size="480px"
:footer="false" placement="right" :attach="false" :show-overlay="false" :close-btn="true" destroy-on-close
:footer="false" placement="right" :show-overlay="false" :close-btn="true" destroy-on-close
class="wiki-graph-drawer">
<template v-if="graphDrawerPage">
<div class="wiki-reader-meta" style="margin-bottom: 8px;">

View File

@ -464,6 +464,10 @@ const visible = computed(() => {
// 关闭弹窗
const handleClose = () => {
// Blur before unmount so TDesign textarea autosize won't run on a detached node.
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
uiStore.closeSettings()
// 如果当前路由是设置页,返回上一页
if (route.path === '/platform/settings') {
@ -550,6 +554,12 @@ onMounted(() => {
window.addEventListener('settings-nav', handleSettingsNav as EventListener)
})
watch(currentSection, () => {
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
})
onUnmounted(() => {
window.removeEventListener('keydown', handleEscape)
window.removeEventListener('settings-nav', handleSettingsNav as EventListener)

View File

@ -444,7 +444,7 @@
<t-form-item :label="t('system.globalSettings.passwordReset.emailLabel')" name="email">
<t-input
v-model="passwordResetForm.email"
type="email"
type="text"
clearable
autocomplete="off"
:disabled="passwordResetSubmitting"