chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
import type { Composer } from 'vue-i18n'
import type { FlatKeyBagPath } from './auditActionRegistry.ts'
/**
* Resolve a dot-namespaced audit action to its localized label.
*
* Uses `tm(root)` + flat key lookup because action strings such as
* `rbac.member_added` must not be passed to `t()` — vue-i18n would split on
* every dot and expect a nested object tree.
*/
export function auditActionLabel(
i18n: Pick<Composer, 'tm'>,
root: FlatKeyBagPath,
action: string,
): string {
const bag = i18n.tm(root) as unknown
if (bag !== null && typeof bag === 'object' && typeof (bag as Record<string, string>)[action] === 'string') {
return (bag as Record<string, string>)[action]
}
return action
}
@@ -0,0 +1,147 @@
import {
AUDIT_ACTION_I18N_ROOTS,
KB_ACTIVITY_DETAIL_VALUES,
KB_ACTIVITY_I18N_ROOTS,
KB_ACTIVITY_OUTCOMES,
REGISTERED_AUDIT_ACTION_ENTRIES,
} from './auditActionRegistry.ts'
/**
* Canonical English labels for audit / KB-activity runtime keys.
* Used when locale files or git history lack a registered key during prune/regenerate.
*/
const TENANT_MEMBER_AUDIT_ACTION_LABELS_EN: Record<string, string> = {
'rbac.member_added': 'Member added',
'rbac.member_removed': 'Member removed',
'rbac.member_role_changed': 'Role changed',
'rbac.member_left': 'Member left',
'rbac.access_denied': 'Access denied',
'rbac.invitation_sent': 'Invitation sent',
'rbac.invitation_accepted': 'Invitation accepted',
'rbac.invitation_declined': 'Invitation declined',
'rbac.invitation_revoked': 'Invitation revoked',
'rbac.invitation_expired': 'Invitation expired',
}
const SYSTEM_GLOBAL_AUDIT_ACTION_LABELS_EN: Record<string, string> = {
'system.setting_changed': 'System setting changed',
'system.admin_promoted': 'System admin granted',
'system.api_key_created': 'Platform API key created',
'system.api_key_revoked': 'Platform API key revoked',
'system.admin_revoked': 'System admin revoked',
'system.user_password_reset': 'User password reset',
'system.user_created': 'User created',
'system.queue_task_retried': 'Failed task run again',
'system.queue_task_deleted': 'Failed task record cleared',
'system.queue_task_run_now': 'Queue task run now',
'system.queue_task_cancelled': 'Queue task cancelled',
'system.queue_archived_purged': 'All failed tasks cleared',
}
const KB_ACTIVITY_ACTION_LABELS_EN: Record<string, string> = {
'kb.created': 'Knowledge base created',
'kb.updated': 'Knowledge base updated',
'kb.deleted': 'Knowledge base deleted',
'kb.duplicated': 'Knowledge base duplicated',
'kb.clone_started': 'Clone started',
'kb.clone_completed': 'Clone completed',
'kb.clone_failed': 'Clone failed',
'knowledge.created': 'Knowledge added',
'knowledge.updated': 'Knowledge updated',
'knowledge.deleted': 'Knowledge deleted',
'knowledge.batch_deleted': 'Knowledge batch deleted',
'knowledge.reparse_started': 'Reparse started',
'knowledge.parse_canceled': 'Parsing canceled',
'knowledge.move_started': 'Knowledge move started',
'knowledge.move_completed': 'Knowledge move completed',
'knowledge.move_failed': 'Knowledge move failed',
'tag.created': 'Tag created',
'tag.updated': 'Tag updated',
'tag.deleted': 'Tag deleted',
'datasource.created': 'Data source created',
'datasource.updated': 'Data source updated',
'datasource.deleted': 'Data source deleted',
'datasource.sync_started': 'Data source sync started',
'datasource.sync_completed': 'Data source sync completed',
'datasource.sync_failed': 'Data source sync failed',
'datasource.paused': 'Data source paused',
'datasource.resumed': 'Data source resumed',
'kb.share_added': 'Share added',
'kb.share_permission_changed': 'Share permission changed',
'kb.share_removed': 'Share removed',
'wiki.content_changed': 'Wiki content changed',
'faq.import_started': 'FAQ import started',
'faq.import_completed': 'FAQ import completed',
'faq.import_failed': 'FAQ import failed',
}
const KB_ACTIVITY_OUTCOME_LABELS_EN: Record<string, string> = {
accepted: 'Accepted',
success: 'Success',
failed: 'Failed',
partial: 'Partial',
canceled: 'Canceled',
denied: 'Denied',
}
const KB_ACTIVITY_DETAIL_VALUE_LABELS_EN: Record<string, string> = {
user: 'User initiated',
manual: 'Manual',
schedule: 'Scheduled',
system: 'System',
pending: 'Pending',
completed: 'Completed',
partial: 'Partially completed',
canceled: 'Canceled',
failed: 'Failed',
enqueue: 'Task submission',
reuse_vectors: 'Reuse vectors',
reparse: 'Reparse',
viewer: 'Read-only',
editor: 'Can edit',
admin: 'Manage',
append: 'Append',
replace: 'Replace',
}
function flattenBag(root: string, labels: Record<string, string>): Record<string, string> {
const flat: Record<string, string> = {}
for (const [key, value] of Object.entries(labels)) {
flat[`${root}.${key}`] = value
}
return flat
}
export const AUDIT_ACTION_LOCALE_DEFAULTS: Readonly<Record<string, string>> = {
...flattenBag(AUDIT_ACTION_I18N_ROOTS.tenantMember, TENANT_MEMBER_AUDIT_ACTION_LABELS_EN),
...flattenBag(AUDIT_ACTION_I18N_ROOTS.systemGlobal, SYSTEM_GLOBAL_AUDIT_ACTION_LABELS_EN),
...flattenBag(AUDIT_ACTION_I18N_ROOTS.kbActivity, KB_ACTIVITY_ACTION_LABELS_EN),
...flattenBag(KB_ACTIVITY_I18N_ROOTS.outcomes, KB_ACTIVITY_OUTCOME_LABELS_EN),
...flattenBag(KB_ACTIVITY_I18N_ROOTS.detailValues, KB_ACTIVITY_DETAIL_VALUE_LABELS_EN),
}
export function getAuditActionLocaleDefault(path: string): string | undefined {
return AUDIT_ACTION_LOCALE_DEFAULTS[path]
}
/** Verify registry lists and baked-in English defaults stay aligned. */
export function findAuditActionDefaultRegistryMismatches(): string[] {
const failures: string[] = []
for (const { root, actions } of REGISTERED_AUDIT_ACTION_ENTRIES) {
for (const action of actions) {
const path = `${root}.${action}`
if (!AUDIT_ACTION_LOCALE_DEFAULTS[path]) failures.push(`missing default for ${path}`)
}
}
for (const outcome of KB_ACTIVITY_OUTCOMES) {
const path = `${KB_ACTIVITY_I18N_ROOTS.outcomes}.${outcome}`
if (!AUDIT_ACTION_LOCALE_DEFAULTS[path]) failures.push(`missing default for ${path}`)
}
for (const value of KB_ACTIVITY_DETAIL_VALUES) {
const path = `${KB_ACTIVITY_I18N_ROOTS.detailValues}.${value}`
if (!AUDIT_ACTION_LOCALE_DEFAULTS[path]) failures.push(`missing default for ${path}`)
}
return failures
}
+138
View File
@@ -0,0 +1,138 @@
/**
* Canonical audit / KB-activity action strings and their i18n message roots.
*
* Action values mirror `internal/types/audit_log.go` (dot-namespaced, e.g.
* `kb.created`, `rbac.member_added`). Locale bags under each root must expose
* those strings as **flat object keys** (not nested paths) because vue-i18n's
* `t('root.kb.created')` would traverse nested objects, while the runtime
* value from the API is the literal string `kb.created`.
*
* Keep this list in sync when adding new AuditAction constants in Go.
*/
export const AUDIT_ACTION_I18N_ROOTS = {
tenantMember: 'tenantMember.audit.action',
systemGlobal: 'system.globalSettings.audit.action',
kbActivity: 'knowledgeEditor.activity.actions',
} as const
/** Workspace membership / invitation audit events (tenantMember drawer). */
export const TENANT_MEMBER_AUDIT_ACTIONS = [
'rbac.member_added',
'rbac.member_removed',
'rbac.member_role_changed',
'rbac.member_left',
'rbac.access_denied',
'rbac.invitation_sent',
'rbac.invitation_accepted',
'rbac.invitation_declined',
'rbac.invitation_revoked',
'rbac.invitation_expired',
] as const
/** Platform control-plane audit events (system settings → audit tab). */
export const SYSTEM_GLOBAL_AUDIT_ACTIONS = [
'system.setting_changed',
'system.admin_promoted',
'system.api_key_created',
'system.api_key_revoked',
'system.admin_revoked',
'system.user_password_reset',
'system.user_created',
'system.queue_task_retried',
'system.queue_task_deleted',
'system.queue_task_run_now',
'system.queue_task_cancelled',
'system.queue_archived_purged',
] as const
/** Knowledge-base activity feed (KB settings → activity). */
export const KB_ACTIVITY_ACTIONS = [
'kb.created',
'kb.updated',
'kb.deleted',
'kb.duplicated',
'kb.clone_started',
'kb.clone_completed',
'kb.clone_failed',
'knowledge.created',
'knowledge.updated',
'knowledge.deleted',
'knowledge.batch_deleted',
'knowledge.reparse_started',
'knowledge.parse_canceled',
'knowledge.move_started',
'knowledge.move_completed',
'knowledge.move_failed',
'tag.created',
'tag.updated',
'tag.deleted',
'datasource.created',
'datasource.updated',
'datasource.deleted',
'datasource.sync_started',
'datasource.sync_completed',
'datasource.sync_failed',
'datasource.paused',
'datasource.resumed',
'kb.share_added',
'kb.share_permission_changed',
'kb.share_removed',
'wiki.content_changed',
'faq.import_started',
'faq.import_completed',
'faq.import_failed',
] as const
/** KB activity outcome column / filter values (`AuditOutcome` subset used in activity UI). */
export const KB_ACTIVITY_OUTCOMES = [
'accepted',
'success',
'failed',
'partial',
'canceled',
'denied',
] as const
/** Enum-like detail payload values shown in the activity task drawer. */
export const KB_ACTIVITY_DETAIL_VALUES = [
'user',
'manual',
'schedule',
'system',
'pending',
'completed',
'partial',
'canceled',
'failed',
'enqueue',
'reuse_vectors',
'reparse',
'viewer',
'editor',
'admin',
'append',
'replace',
] as const
export const KB_ACTIVITY_I18N_ROOTS = {
outcomes: 'knowledgeEditor.activity.outcomes',
detailValues: 'knowledgeEditor.activity.detailValues',
} as const
/** Locale object paths whose children use flat keys containing dots. */
export const FLAT_KEY_BAG_PATHS = [
AUDIT_ACTION_I18N_ROOTS.tenantMember,
AUDIT_ACTION_I18N_ROOTS.systemGlobal,
AUDIT_ACTION_I18N_ROOTS.kbActivity,
] as const
export type FlatKeyBagPath = (typeof FLAT_KEY_BAG_PATHS)[number]
export const REGISTERED_AUDIT_ACTION_ENTRIES: ReadonlyArray<{
root: FlatKeyBagPath
actions: readonly string[]
}> = [
{ root: AUDIT_ACTION_I18N_ROOTS.tenantMember, actions: TENANT_MEMBER_AUDIT_ACTIONS },
{ root: AUDIT_ACTION_I18N_ROOTS.systemGlobal, actions: SYSTEM_GLOBAL_AUDIT_ACTIONS },
{ root: AUDIT_ACTION_I18N_ROOTS.kbActivity, actions: KB_ACTIVITY_ACTIONS },
]
File diff suppressed because it is too large. Load diff
+171
View File
@@ -0,0 +1,171 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
EMBED_MESSAGES,
normalizeEmbedLocale,
SUPPORTED_LOCALES,
} from './embed.ts'
const EXPECTED_CONVERSATION_TIME_KEYS = [
'today',
'yesterday',
'thisYear',
'otherYear',
] as const
const EXPECTED_REFERENCES_DRAWER_KEYS = [
'referencesDrawerTitle',
'referencesDrawerTitleWeb',
'referencesDrawerTitleDocs',
'referencesDrawerTitleTools',
'referencesDrawerTitleMixed',
'referencesDrawerWebSection',
'referencesDrawerDocsSection',
'referencesDrawerToolsSection',
'referencesDrawerEmpty',
] as const
test('supported embed locales include zh-CN, zh-TW, en-US, ko-KR, ja-JP, ru-RU', () => {
assert.deepEqual([...SUPPORTED_LOCALES].sort(), ['en-US', 'ja-JP', 'ko-KR', 'ru-RU', 'zh-CN', 'zh-TW'].sort())
})
test('every supported locale defines conversationTime and referencesDrawer in chat', () => {
for (const locale of SUPPORTED_LOCALES) {
const bundle = EMBED_MESSAGES[locale] as {
chat?: Record<string, unknown>
common?: Record<string, unknown>
}
assert.ok(bundle, `Locale bundle for ${locale} must exist`)
assert.ok(bundle.chat, `Locale bundle for ${locale} must have chat section`)
// conversationTime checks
const conversationTime = bundle.chat.conversationTime as Record<string, string> | undefined
assert.ok(
conversationTime && typeof conversationTime === 'object',
`Locale ${locale} is missing chat.conversationTime`,
)
for (const key of EXPECTED_CONVERSATION_TIME_KEYS) {
assert.equal(
typeof conversationTime[key],
'string',
`Locale ${locale} is missing chat.conversationTime.${key}`,
)
assert.ok(
conversationTime[key].trim().length > 0,
`chat.conversationTime.${key} in ${locale} should not be empty`,
)
assert.ok(
conversationTime[key].includes('{time}'),
`chat.conversationTime.${key} in ${locale} must include {time} placeholder`,
)
}
// referencesDrawer checks
const chatBag = bundle.chat as Record<string, unknown>
for (const key of EXPECTED_REFERENCES_DRAWER_KEYS) {
const val: unknown = chatBag[key]
assert.equal(
typeof val,
'string',
`Locale ${locale} is missing chat.${key}`,
)
assert.ok(
(val as string).trim().length > 0,
`chat.${key} in ${locale} should not be empty`,
)
}
// common.close check
assert.ok(bundle.common, `Locale bundle for ${locale} must have common section`)
assert.equal(
typeof bundle.common.close,
'string',
`Locale ${locale} is missing common.close`,
)
assert.ok(
(bundle.common.close as string).trim().length > 0,
`common.close in ${locale} should not be empty`,
)
}
})
test('locale-specific translations match expected strings for missing keys', () => {
// zh-CN
const zhChat = EMBED_MESSAGES['zh-CN'].chat as Record<string, any>
const zhCommon = EMBED_MESSAGES['zh-CN'].common as Record<string, any>
assert.equal(zhChat.conversationTime.today, '今天 {time}')
assert.equal(zhChat.conversationTime.yesterday, '昨天 {time}')
assert.equal(zhChat.conversationTime.thisYear, '{month}月{day}日 {time}')
assert.equal(zhChat.conversationTime.otherYear, '{year}年{month}月{day}日 {time}')
assert.equal(zhChat.referencesDrawerTitleDocs, '文档来源')
assert.equal(zhChat.referencesDrawerEmpty, '暂无参考来源')
assert.equal(zhCommon.close, '关闭')
// en-US
const enChat = EMBED_MESSAGES['en-US'].chat as Record<string, any>
const enCommon = EMBED_MESSAGES['en-US'].common as Record<string, any>
assert.equal(enChat.conversationTime.today, 'Today {time}')
assert.equal(enChat.conversationTime.yesterday, 'Yesterday {time}')
assert.equal(enChat.conversationTime.thisYear, '{month}/{day} {time}')
assert.equal(enChat.conversationTime.otherYear, '{month}/{day}/{year} {time}')
assert.equal(enChat.referencesDrawerTitleDocs, 'Document sources')
assert.equal(enChat.referencesDrawerEmpty, 'No sources available')
assert.equal(enCommon.close, 'Close')
// ja-JP
const jaChat = EMBED_MESSAGES['ja-JP'].chat as Record<string, any>
const jaCommon = EMBED_MESSAGES['ja-JP'].common as Record<string, any>
assert.equal(jaChat.conversationTime.today, '今日{time}')
assert.equal(jaChat.conversationTime.yesterday, '昨日{time}')
assert.equal(jaChat.referencesDrawerTitleDocs, 'ドキュメントの出典')
assert.equal(jaChat.referencesDrawerEmpty, '出典はありません')
assert.equal(jaCommon.close, '閉じる')
// ko-KR
const koChat = EMBED_MESSAGES['ko-KR'].chat as Record<string, any>
const koCommon = EMBED_MESSAGES['ko-KR'].common as Record<string, any>
assert.equal(koChat.conversationTime.today, '오늘 {time}')
assert.equal(koChat.conversationTime.yesterday, '어제 {time}')
assert.equal(koChat.conversationTime.thisYear, '{month}월 {day}일 {time}')
assert.equal(koChat.conversationTime.otherYear, '{year}년 {month}월 {day}일 {time}')
assert.equal(koChat.referencesDrawerTitleDocs, '문서 출처')
assert.equal(koChat.referencesDrawerEmpty, '참고 출처가 없습니다')
assert.equal(koCommon.close, '닫기')
// ru-RU
const ruChat = EMBED_MESSAGES['ru-RU'].chat as Record<string, any>
const ruCommon = EMBED_MESSAGES['ru-RU'].common as Record<string, any>
assert.equal(ruChat.conversationTime.today, 'Сегодня {time}')
assert.equal(ruChat.conversationTime.yesterday, 'Вчера {time}')
assert.equal(ruChat.conversationTime.thisYear, '{day}.{month} {time}')
assert.equal(ruChat.conversationTime.otherYear, '{day}.{month}.{year} {time}')
assert.equal(ruChat.referencesDrawerTitleDocs, 'Документы')
assert.equal(ruChat.referencesDrawerEmpty, 'Источники отсутствуют')
assert.equal(ruCommon.close, 'Закрыть')
})
test('normalizeEmbedLocale maps tags accurately with fallback to zh-CN', () => {
assert.equal(normalizeEmbedLocale('zh-CN'), 'zh-CN')
assert.equal(normalizeEmbedLocale('zh'), 'zh-CN')
assert.equal(normalizeEmbedLocale('ZH-cn'), 'zh-CN')
// 繁中變體不得被通用 'zh' 規則吞掉
assert.equal(normalizeEmbedLocale('zh-TW'), 'zh-TW')
assert.equal(normalizeEmbedLocale('zh-tw'), 'zh-TW')
assert.equal(normalizeEmbedLocale('ZH-TW'), 'zh-TW')
assert.equal(normalizeEmbedLocale('zh-Hant'), 'zh-TW')
assert.equal(normalizeEmbedLocale('zh-Hant-TW'), 'zh-TW')
assert.equal(normalizeEmbedLocale('zh-HK'), 'zh-TW')
assert.equal(normalizeEmbedLocale('zh-MO'), 'zh-TW')
assert.equal(normalizeEmbedLocale('en-US'), 'en-US')
assert.equal(normalizeEmbedLocale('en'), 'en-US')
assert.equal(normalizeEmbedLocale('EN-gb'), 'en-US')
assert.equal(normalizeEmbedLocale('ja-JP'), 'ja-JP')
assert.equal(normalizeEmbedLocale('ja'), 'ja-JP')
assert.equal(normalizeEmbedLocale('ko-KR'), 'ko-KR')
assert.equal(normalizeEmbedLocale('ko'), 'ko-KR')
assert.equal(normalizeEmbedLocale('ru-RU'), 'ru-RU')
assert.equal(normalizeEmbedLocale('ru'), 'ru-RU')
assert.equal(normalizeEmbedLocale('unknown-locale'), 'zh-CN')
assert.equal(normalizeEmbedLocale(' '), 'zh-CN')
})
+39
View File
@@ -0,0 +1,39 @@
import { createI18n } from 'vue-i18n'
import zhCN from './locales/zh-CN.ts'
import ruRU from './locales/ru-RU.ts'
import enUS from './locales/en-US.ts'
import koKR from './locales/ko-KR.ts'
import jaJP from './locales/ja-JP.ts'
import zhTW from './locales/zh-TW.ts'
import { BUILT_IN_DEFAULT, resolveDefaultLocale } from './resolveDefaultLocale.ts'
import { pluralRules } from './pluralizationRules.ts'
const messages = {
'zh-CN': zhCN,
'zh-TW': zhTW,
'en-US': enUS,
'ru-RU': ruRU,
'ko-KR': koKR,
'ja-JP': jaJP
}
// User's explicit past choice wins; otherwise use the deployment default.
const savedLocale = localStorage.getItem('locale') || resolveDefaultLocale(
window.__RUNTIME_CONFIG__?.DEFAULT_LOCALE,
import.meta.env.VITE_DEFAULT_LOCALE,
)
const i18n = createI18n({
legacy: false,
locale: savedLocale,
fallbackLocale: BUILT_IN_DEFAULT,
globalInjection: true,
pluralRules,
// Some translations intentionally embed `<strong>` markup (e.g. agent step summaries).
// We render them via v-html with our own sanitization, so silence vue-i18n's HTML warning
// to avoid flooding the console and slowing renders during history loads.
warnHtmlMessage: false,
messages
})
export default i18n
+239
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)}`,
)
}
+338
View File
@@ -0,0 +1,338 @@
import assert from 'node:assert/strict'
import { before, test } from 'node:test'
import { findAuditActionDefaultRegistryMismatches } from './auditActionLocaleDefaults.ts'
import { REGISTERED_AUDIT_ACTION_ENTRIES, KB_ACTIVITY_DETAIL_VALUES, KB_ACTIVITY_I18N_ROOTS, KB_ACTIVITY_OUTCOMES } from './auditActionRegistry.ts'
import {
CRITICAL_LOCALE_KEYS,
LOCALE_BUNDLES,
alignLocaleBundleToReferenceKeys,
collectI18nUsageFromSources,
collectLocaleKeys,
collectReferencedLocaleKeys,
diffLocaleKeys,
findAllLocaleMessageCompileErrors,
findUsedKeysMissingInLocales,
getLocaleValueAtPath,
rebuildPrunedLocales,
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('operation labels remain referenced when pruning locale bundles', () => {
const keys = [...localeKeysByName[REFERENCE_LOCALE]].filter((key) => key.startsWith('agentStream.operations.names.'))
assert.ok(keys.length > 0)
assert.deepEqual(keys.filter((key) => !referencedKeys.has(key)), [])
})
test('installer command progress messages resolve in the settings namespace', () => {
for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) {
for (const name of ['installCommandRunning', 'installCommandWaiting']) {
const key = `settings.sandbox.${name}`
assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`)
}
}
})
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',
'academycloud',
'markitdown',
'opendataloader',
] as const
/** Worker pools / queues use dynamic te() paths in RuntimeQueues.vue; keep in sync with internal/types/task.go. */
const RUNTIME_WORKER_POOL_NAMES = [
'core',
'postprocess',
'enrichment',
'maintenance',
'shared',
'wiki',
] as const
const RUNTIME_QUEUE_NAMES = [
'default',
'chat_attachment',
'postprocess',
'summary',
'sync',
'low',
'multimodal',
'graph',
'question',
'wiki',
] as const
const RUNTIME_TASK_TYPE_KEYS = [
'documentProcess',
'manualProcess',
'temporaryDocumentProcess',
'postProcess',
'summary',
'tableSummary',
'question',
'multimodal',
'graph',
'sync',
'faqImport',
'batchReparse',
'batchDelete',
'move',
'indexDelete',
'kbClone',
'kbDelete',
'wikiIngest',
'wikiFinalize',
] as const
test('registered audit action labels exist as flat keys in every locale', () => {
const failures: string[] = []
for (const { root, actions } of REGISTERED_AUDIT_ACTION_ENTRIES) {
for (const action of actions) {
const dottedPath = `${root}.${action}`
for (const [localeName, bundle] of Object.entries(LOCALE_BUNDLES) as Array<[LocaleName, unknown]>) {
const bag = getLocaleValueAtPath(bundle, root)
const label =
bag !== null && typeof bag === 'object'
? (bag as Record<string, string>)[action]
: undefined
if (typeof label !== 'string' || !label) {
failures.push(`${localeName}: missing flat ${dottedPath}`)
}
}
}
}
assert.deepEqual(failures, [], failures.slice(0, 20).join('\n'))
})
test('locale alignment preserves flat audit action keys (regenerate safety)', () => {
const referenceKeys = collectLocaleKeys(LOCALE_BUNDLES[REFERENCE_LOCALE])
const aligned = alignLocaleBundleToReferenceKeys(referenceKeys, LOCALE_BUNDLES['zh-CN'], LOCALE_BUNDLES['en-US'])
const failures: string[] = []
for (const { root, actions } of REGISTERED_AUDIT_ACTION_ENTRIES) {
const bag = getLocaleValueAtPath(aligned, root)
if (bag == null || typeof bag !== 'object') {
failures.push(`zh-CN aligned: missing bag ${root}`)
continue
}
for (const action of actions) {
if (typeof (bag as Record<string, unknown>)[action] !== 'string') {
failures.push(`zh-CN aligned: missing flat ${root}.${action}`)
}
const nestedArea = action.split('.')[0]
if (
nestedArea &&
(bag as Record<string, unknown>)[nestedArea] != null &&
typeof (bag as Record<string, unknown>)[nestedArea] === 'object'
) {
failures.push(`zh-CN aligned: nested corruption under ${root}.${nestedArea}`)
}
}
}
assert.deepEqual(failures, [], failures.join('\n'))
})
test('KB activity outcomes and detail values exist in every locale', () => {
const failures: string[] = []
for (const outcome of KB_ACTIVITY_OUTCOMES) {
const path = `${KB_ACTIVITY_I18N_ROOTS.outcomes}.${outcome}`
for (const [localeName, bundle] of Object.entries(LOCALE_BUNDLES) as Array<[LocaleName, unknown]>) {
const label = getLocaleValueAtPath(bundle, path)
if (typeof label !== 'string' || !label) failures.push(`${localeName}: missing ${path}`)
}
}
for (const value of KB_ACTIVITY_DETAIL_VALUES) {
const path = `${KB_ACTIVITY_I18N_ROOTS.detailValues}.${value}`
for (const [localeName, bundle] of Object.entries(LOCALE_BUNDLES) as Array<[LocaleName, unknown]>) {
const label = getLocaleValueAtPath(bundle, path)
if (typeof label !== 'string' || !label) failures.push(`${localeName}: missing ${path}`)
}
}
assert.deepEqual(failures, [], failures.slice(0, 20).join('\n'))
})
test('audit action locale defaults cover the registry', () => {
const failures = findAuditActionDefaultRegistryMismatches()
assert.deepEqual(failures, [], failures.join('\n'))
})
test('prune rebuild restores registered audit keys from baked-in English defaults', () => {
const usage = collectI18nUsageFromSources()
const emptyBundles = {
'en-US': {},
'zh-CN': {},
'zh-TW': {},
'ko-KR': {},
'ja-JP': {},
'ru-RU': {},
} as Record<LocaleName, Record<string, unknown>>
const rebuilt = rebuildPrunedLocales(emptyBundles, usage)
const en = rebuilt['en-US'] as Record<string, unknown>
const failures: string[] = []
for (const { root, actions } of REGISTERED_AUDIT_ACTION_ENTRIES) {
const bag = getLocaleValueAtPath(en, root)
for (const action of actions) {
if (
bag == null ||
typeof bag !== 'object' ||
typeof (bag as Record<string, string>)[action] !== 'string'
) {
failures.push(`en-US rebuild: missing ${root}.${action}`)
}
}
}
assert.deepEqual(failures, [], failures.join('\n'))
assert.equal(
getLocaleValueAtPath(en, `${KB_ACTIVITY_I18N_ROOTS.outcomes}.success`),
'Success',
)
})
test('runtime queue worker pool and queue labels exist in every locale', () => {
const failures: string[] = []
for (const pool of RUNTIME_WORKER_POOL_NAMES) {
for (const [localeName, keys] of Object.entries(localeKeysByName) as Array<[LocaleName, Set<string>]>) {
if (!keys.has(`system.globalSettings.runtime.pools.${pool}`)) {
failures.push(`${localeName}: missing system.globalSettings.runtime.pools.${pool}`)
}
if (!keys.has(`system.globalSettings.runtime.poolDescriptions.${pool}`)) {
failures.push(`${localeName}: missing system.globalSettings.runtime.poolDescriptions.${pool}`)
}
}
}
for (const queue of RUNTIME_QUEUE_NAMES) {
for (const [localeName, keys] of Object.entries(localeKeysByName) as Array<[LocaleName, Set<string>]>) {
if (!keys.has(`system.globalSettings.runtime.queueNames.${queue}`)) {
failures.push(`${localeName}: missing system.globalSettings.runtime.queueNames.${queue}`)
}
if (!keys.has(`system.globalSettings.runtime.queueDescriptions.${queue}`)) {
failures.push(`${localeName}: missing system.globalSettings.runtime.queueDescriptions.${queue}`)
}
}
}
for (const taskType of RUNTIME_TASK_TYPE_KEYS) {
for (const [localeName, keys] of Object.entries(localeKeysByName) as Array<[LocaleName, Set<string>]>) {
if (!keys.has(`system.globalSettings.runtime.tasks.taskTypes.${taskType}`)) {
failures.push(`${localeName}: missing system.globalSettings.runtime.tasks.taskTypes.${taskType}`)
}
}
}
assert.deepEqual(failures, [], failures.slice(0, 20).join('\n'))
})
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'))
})
test('Seafile picker texts and sync error codes remain localized after pruning', () => {
const seafileErrors = [
'permission_denied', 'not_found', 'file_too_large', 'empty_file',
'source_changed', 'invalid_response', 'ssrf_blocked', 'fetch_failed',
]
const keys = [
'connector.seafile', 'connectorDesc.seafile',
'seafile.baseUrl', 'seafile.apiToken', 'seafile.apiTokenHint',
'seafile.singleLibraryOnly', 'seafile.selectionRequired',
'resourceType.library', 'noResourcesDesc_seafile',
...[1, 2, 3].map(step => `guideStep${step}_seafile`),
...seafileErrors.map(code => `syncError.seafile_${code}`),
].map(key => `datasource.${key}`)
keys.push('knowledgeBase.channelSeafile')
for (const key of keys) {
assert.ok(referencedKeys.has(key), `pruning would remove ${key}`)
for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) {
assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`)
}
}
})
test('DingTalk configuration and sync failures remain localized after pruning', () => {
const keys = [
'connector.dingtalk', 'connectorDesc.dingtalk',
'field.clientId', 'field.clientSecret', 'field.operatorId', 'field.operatorIdHint',
'prereqBarText_dingtalk', 'prereqOpenConsole_dingtalk',
...[1, 2, 3].flatMap(step => [`prereqStep${step}Brief_dingtalk`, `prereqStep${step}Desc_dingtalk`]),
'syncError.dingtalk_document_failed', 'syncError.dingtalk_resource_failed',
].map(key => `datasource.${key}`)
for (const key of keys) {
assert.ok(referencedKeys.has(key), `pruning would remove ${key}`)
for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) {
assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`)
}
}
})
+759
View File
@@ -0,0 +1,759 @@
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 {
FLAT_KEY_BAG_PATHS,
KB_ACTIVITY_DETAIL_VALUES,
KB_ACTIVITY_I18N_ROOTS,
KB_ACTIVITY_OUTCOMES,
REGISTERED_AUDIT_ACTION_ENTRIES,
} from './auditActionRegistry.ts'
import { AUDIT_ACTION_LOCALE_DEFAULTS, getAuditActionLocaleDefault } from './auditActionLocaleDefaults.ts'
import { writeLocaleModule } from './localeSerialize.ts'
import enUS from './locales/en-US.ts'
import jaJP from './locales/ja-JP.ts'
import koKR from './locales/ko-KR.ts'
import ruRU from './locales/ru-RU.ts'
import zhCN from './locales/zh-CN.ts'
import zhTW from './locales/zh-TW.ts'
export const LOCALE_BUNDLES = {
'en-US': enUS,
'zh-CN': zhCN,
'zh-TW': zhTW,
'ko-KR': koKR,
'ja-JP': jaJP,
'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 = [
// Operation labels use IDs supplied by the backend catalog at runtime.
'agentStream.operations.names.',
'system.globalSettings.listConfirm.',
'system.globalSettings.keyLabels.',
'system.globalSettings.keyDescriptions.',
'system.globalSettings.enumLabels.',
'system.globalSettings.audit.action.',
'system.globalSettings.audit.actorRole.',
'knowledgeEditor.activity.detailFields.',
'knowledgeEditor.activity.detailValues.',
'knowledgeEditor.activity.outcomes.',
'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.',
'datasource.syncError.',
'kbSettings.parser.engines.',
'model.editor.description.',
'integrations.tabs.',
'integrations.mcpserver.tools.',
'integrations.mcpserver.groups.',
'knowledgeStages.stage.',
'knowledgeStages.status.',
'system.globalSettings.runtime.pools.',
'system.globalSettings.runtime.poolDescriptions.',
'system.globalSettings.runtime.queueNames.',
'system.globalSettings.runtime.queueDescriptions.',
'system.globalSettings.runtime.tasks.taskTypes.',
'organization.role.',
'inviteRegister.',
'modelSettings.builtinModels.',
// Image-attribute display text is keyed by the backend attribute registry
// (imageAttr.contain_text.label …), built from the schema response at runtime,
// so it is registered as a whole prefix: a new backend attribute must keep
// being translated without touching the audit.
'imageAttr.',
// Image-pipeline panel text is keyed by the registry response too
// (imagePipeline.smartocr.label …), likewise runtime-built: a
// pipeline or field added in the backend must keep being translated without
// touching the audit. The panel's own wording is literal and lives in the
// locale files under knowledgeEditor.advanced.multimodal.imagePipeline*.
'imagePipeline.',
// Gallery attribute labels are keyed by the namespaced attribute id from
// the gallery contract, likewise runtime-built; static labels for the few
// builtin attributes ship in the locale files as
// knowledgeEditor.wikiBrowser.gallery.attr.builtin_caption …, and
// everything else falls back to the contract wording.
'knowledgeEditor.wikiBrowser.gallery.attr.',
] 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', 'zh-TW', 'ko-KR', 'ru-RU', 'ja-JP']
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
if (setLocaleFlatBagValueIfApplicable(root, path, value)) return
setLocaleValueAtPathParts(root, path.split('.'), value)
}
/** Write flat keys (e.g. `kb.created`) under audit action bags without nesting. */
function setLocaleFlatBagValueIfApplicable(root: LocaleTree, path: string, value: string): boolean {
for (const bagPath of FLAT_KEY_BAG_PATHS) {
const prefix = `${bagPath}.`
if (!path.startsWith(prefix)) continue
const actionKey = path.slice(prefix.length)
if (!actionKey) return false
const bagParts = bagPath.split('.')
let node: Record<string, unknown> = root
for (const part of bagParts) {
let child = node[part]
if (child == null || typeof child !== 'object' || Array.isArray(child)) {
child = {}
node[part] = child
}
node = child as Record<string, unknown>
}
node[actionKey] = value
return true
}
return false
}
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) ??
getAuditActionLocaleDefault(key) ??
AUDIT_ACTION_LOCALE_DEFAULTS[key]
if (typeof value === 'string') setLocaleValueAtPath(target, key, value)
}
}
export function collectRequiredLocaleKeys(usage: I18nUsage, referenceBundle: unknown): Set<string> {
const required = new Set([
...collectReferencedLocaleKeys(referenceBundle, usage),
...usage.staticKeys,
...CRITICAL_LOCALE_KEYS,
])
for (const { root, actions } of REGISTERED_AUDIT_ACTION_ENTRIES) {
for (const action of actions) required.add(`${root}.${action}`)
}
for (const outcome of KB_ACTIVITY_OUTCOMES) {
required.add(`${KB_ACTIVITY_I18N_ROOTS.outcomes}.${outcome}`)
}
for (const value of KB_ACTIVITY_DETAIL_VALUES) {
required.add(`${KB_ACTIVITY_I18N_ROOTS.detailValues}.${value}`)
}
return required
}
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)
const enTree: LocaleTree =
enPruned && typeof enPruned === 'object' && !Array.isArray(enPruned)
? (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 loadLocaleBundlesFromDisk(
localesDir = LOCALES_DIR,
): Promise<Record<LocaleName, LocaleTree>> {
const bundles = {} as Record<LocaleName, LocaleTree>
for (const localeName of LOCALE_ORDER) {
const filePath = join(localesDir, `${localeName}.ts`)
const mod = await import(`${pathToFileURL(filePath).href}?disk=${Date.now()}`)
bundles[localeName] = structuredClone(mod.default) as LocaleTree
}
return bundles
}
export async function loadFullLocaleBundlesFromGit(
ref = 'HEAD',
): Promise<Record<LocaleName, LocaleTree>> {
const tempDir = mkdtempSync(join(tmpdir(), 'academy-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 loadLocaleBundlesFromDisk(localesDir)
const before = collectLocaleKeys(sourceBundles['en-US']).size
const rebuilt = rebuildPrunedLocales(sourceBundles, usage)
writePrunedLocaleFiles(rebuilt, localesDir)
return {
before,
after: collectLocaleKeys(rebuilt['en-US']).size,
}
}
+40
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')
}
+18
View File
@@ -0,0 +1,18 @@
/**
* Embed i18n entry point.
*
* - Visitor UI strings: `frontend/src/i18n/embed.ts` (loaded by embed-main.ts)
* - Admin `embedPublish` strings: `frontend/src/i18n/locales/*.ts`
*
* Re-export locale helpers so feature code can import from one path.
*/
export {
applyEmbedLocale,
EMBED_LOCALE_STORAGE_KEY,
EMBED_MESSAGES,
normalizeEmbedLocale,
readEmbedLocaleFromUrl,
SUPPORTED_LOCALES,
syncEmbedLocaleFromUrl,
type EmbedLocale,
} from '@/i18n/embed'
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
@@ -0,0 +1,57 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import enUS from './en-US.ts'
import jaJP from './ja-JP.ts'
import koKR from './ko-KR.ts'
import ruRU from './ru-RU.ts'
import zhCN from './zh-CN.ts'
import zhTW from './zh-TW.ts'
type LocaleValue = string | Record<string, unknown> | unknown[]
function collectStrings(value: LocaleValue, path = ''): Array<{ path: string; value: string }> {
if (typeof value === 'string') return [{ path, value }]
if (Array.isArray(value)) {
return value.flatMap((item, index) =>
collectStrings(item as LocaleValue, `${path}[${index}]`),
)
}
if (value && typeof value === 'object') {
return Object.entries(value).flatMap(([key, item]) =>
collectStrings(item as LocaleValue, path ? `${path}.${key}` : key),
)
}
return []
}
function withoutTechnicalTenantTokens(value: string): string {
return value
.replace(/\{tenant(?:Id)?\}/g, '')
.replace(/\btenant_id\b/gi, '')
.replace(/\btenantless\b/gi, '')
.replace(/\bX-Tenant-ID\b/g, '')
}
const localeChecks = [
{ name: 'zh-CN', locale: zhCN, forbidden: /租户/ },
{ name: 'zh-TW', locale: zhTW, forbidden: /租戶/ },
{ name: 'en-US', locale: enUS, forbidden: /\btenants?\b/i },
{ name: 'ko-KR', locale: koKR, forbidden: /테넌트/ },
{ name: 'ja-JP', locale: jaJP, forbidden: /テナント/ },
{ name: 'ru-RU', locale: ruRU, forbidden: /(?:тенант|арендатор)/i },
]
test('user-facing locale values use workspace terminology', () => {
for (const check of localeChecks) {
const legacyValues = collectStrings(check.locale)
.filter(({ value }) => check.forbidden.test(withoutTechnicalTenantTokens(value)))
.map(({ path, value }) => `${check.name}:${path}=${value}`)
assert.deepEqual(
legacyValues,
[],
`${check.name} still contains user-facing tenant terminology`,
)
}
})
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { test } from 'node:test'
import { LOCALE_BUNDLES, collectLocaleKeys, type LocaleName } from './localeKeyAudit.ts'
// The repository-wide audit compares locales against each other: it catches a
// key present in en-US but missing in ko-KR. It cannot catch a key that is
// referenced in code and missing from *every* locale, because it starts from
// the keys that already exist.
//
// That gap is not hypothetical — the memory settings shipped a reference to
// `memoryWorkspaceSettings.instructionsLabel` while it existed in no locale,
// and every check stayed green while the UI would have rendered the raw key.
//
// This guards the memory namespaces specifically. There are pre-existing
// violations elsewhere in the app; widening this check means fixing those
// first, which is a separate change.
const GUARDED_PREFIXES = ['memorySettings.', 'memoryWorkspaceSettings.', 'chat.memory']
const STATIC_KEY_PATTERN = /\$?\bt\(\s*['"]([a-zA-Z][\w]*(?:\.[\w]+)+)['"]/g
function collectStaticKeys(dir: string, found = new Set<string>()): Set<string> {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const target = path.join(dir, entry.name)
if (entry.isDirectory()) {
collectStaticKeys(target, found)
continue
}
if (!/\.(vue|ts)$/.test(entry.name) || entry.name.endsWith('.test.ts')) continue
for (const match of fs.readFileSync(target, 'utf8').matchAll(STATIC_KEY_PATTERN)) {
found.add(match[1])
}
}
return found
}
test('memory i18n keys referenced in code exist in every locale', () => {
const referenced = [...collectStaticKeys(path.join(import.meta.dirname, '..'))].filter((key) =>
GUARDED_PREFIXES.some((prefix) => key.startsWith(prefix)),
)
assert.ok(referenced.length > 0, 'no memory i18n keys were found; has the scan pattern drifted?')
const failures: string[] = []
for (const [localeName, bundle] of Object.entries(LOCALE_BUNDLES) as Array<[LocaleName, unknown]>) {
const keys = collectLocaleKeys(bundle)
for (const key of referenced) {
if (!keys.has(key)) failures.push(`${localeName}: missing ${key}`)
}
}
assert.deepEqual(failures, [], failures.slice(0, 20).join('\n'))
})
// Kind and origin labels are looked up dynamically, so the scan above cannot
// see them and a renamed kind would silently render a raw key in the chat.
test('dynamic memory kind and origin labels exist in every locale', () => {
const dynamic = [
...['profile', 'preference', 'fact', 'task'].map((kind) => `memorySettings.kinds.${kind}`),
...['explicit', 'extracted', 'manual'].map((origin) => `memorySettings.origins.${origin}`),
]
const failures: string[] = []
for (const [localeName, bundle] of Object.entries(LOCALE_BUNDLES) as Array<[LocaleName, unknown]>) {
const keys = collectLocaleKeys(bundle)
for (const key of dynamic) {
if (!keys.has(key)) failures.push(`${localeName}: missing ${key}`)
}
}
assert.deepEqual(failures, [], failures.join('\n'))
})
+18
View File
@@ -0,0 +1,18 @@
/**
* vue-i18n's built-in plural rule only distinguishes "one" and "other". Russian
* has three forms (one / few / many), so messages written with three pipes need
* a selector that follows the CLDR rules. Only locales listed here are affected;
* everything else keeps the default rule.
*/
export const pluralRules: Record<string, (choice: number, choicesLength: number) => number> = {
ru: russianPluralRule,
'ru-RU': russianPluralRule,
}
function russianPluralRule(choice: number, choicesLength: number): number {
if (choicesLength < 3) return Math.abs(choice) === 1 ? 0 : 1
const value = Math.abs(choice)
if (value % 10 === 1 && value % 100 !== 11) return 0
if (value % 10 >= 2 && value % 10 <= 4 && (value % 100 < 10 || value % 100 >= 20)) return 1
return 2
}
@@ -0,0 +1,4 @@
import { regeneratePrunedLocaleFiles } from './localeKeyAudit.ts'
const { before, after } = await regeneratePrunedLocaleFiles()
console.log(`Pruned locale keys: ${before} -> ${after} (en-US reference)`)
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { BUILT_IN_DEFAULT, resolveDefaultLocale } from './resolveDefaultLocale.ts'
test('resolveDefaultLocale prefers runtime over build-time default', () => {
assert.equal(resolveDefaultLocale('en-US', 'ru-RU'), 'en-US')
})
test('resolveDefaultLocale falls back to build-time then built-in default', () => {
assert.equal(resolveDefaultLocale('', 'ko-KR'), 'ko-KR')
assert.equal(resolveDefaultLocale('', 'ja-JP'), 'ja-JP')
assert.equal(resolveDefaultLocale(undefined, undefined), BUILT_IN_DEFAULT)
})
test('resolveDefaultLocale trims whitespace around supported tags', () => {
assert.equal(resolveDefaultLocale(' en-US '), 'en-US')
})
test('resolveDefaultLocale rejects unknown values', () => {
assert.equal(resolveDefaultLocale('fr-FR'), BUILT_IN_DEFAULT)
assert.equal(resolveDefaultLocale('en-US"};alert(1);//'), BUILT_IN_DEFAULT)
assert.equal(resolveDefaultLocale(' '), BUILT_IN_DEFAULT)
})
+18
View File
@@ -0,0 +1,18 @@
export const SUPPORTED_LOCALES = ['zh-CN', 'zh-TW', 'en-US', 'ru-RU', 'ko-KR', 'ja-JP'] as const
export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number]
export const BUILT_IN_DEFAULT: SupportedLocale = 'zh-CN'
function isSupportedLocale(value: string): value is SupportedLocale {
return (SUPPORTED_LOCALES as readonly string[]).includes(value)
}
/** Resolve deployment default locale before any user preference is applied. */
export function resolveDefaultLocale(
runtimeLocale?: string | null,
buildTimeLocale?: string | null,
): SupportedLocale {
const raw = runtimeLocale || buildTimeLocale || BUILT_IN_DEFAULT
const candidate = typeof raw === 'string' ? raw.trim() : BUILT_IN_DEFAULT
return isSupportedLocale(candidate) ? candidate : BUILT_IN_DEFAULT
}