feat(i18n): define user copy manifest contract

go
codex 2 weeks ago
parent bc86c6a961
commit 5258310c2b

@ -0,0 +1,13 @@
# 用户界面译文目录
用户界面译文采用稳定语义键、源码中文基线和管理员发布译文的模型。源码不得保存英文或其他目标语言译文。
`web/resources/user-copy/manifest.php` 是页面、scope、词条类型、中文安全基线、参数合同和安全等级的唯一源码定义。管理员草稿、发布版和历史版本属于数据库;普通用户运行时只读取管理员发布后编译的不可变目录,不能在缓存失效时回查翻译数据库。
`entries` 使用带 `key` 字段的列表,而不是以词条键作为 PHP 数组下标。这样合同校验能在加载阶段真实识别重复键,避免 PHP 解析关联数组时静默覆盖前一个同名词条。校验后的目录仍按键排序,摘要不会受源码排列顺序影响。
词条键必须是静态小写语义键,例如 `instance.settings.hostname.help`。禁止动态拼接词条键。带参数文案必须声明完整参数合同并使用 ICU 格式;支付、删除、重装、数据丢失和效果未知等高风险词条不能隐藏或留空。
覆盖扫描器当前只提供迁移报告。用户页面逐步接入目录后,最终门禁将禁止直接 Toast 文本、浏览器确认文本、固定 `zh-CN` 格式和未登记的用户可见中文。临时放行必须在同一行使用带原因的 `user-copy: allow <reason>`,最终迁移阶段会收紧放行范围。
页面内翻译预览、数据库草稿和发布目录将在后续独立提交中实现;本阶段不改变任何现有用户页面行为。

@ -0,0 +1,65 @@
<?php
namespace App\Services\UserCopy;
/** Reports source patterns that must disappear as pages join the copy catalog. */
final class UserCopyCoverageScanner
{
private const RULES = [
'direct_toast_text' => '/\btoast\s*\(\s*[\'\"]/',
'direct_confirm_text' => '/\b(?:window\.)?confirm\s*\(\s*[\'\"]/',
'hardcoded_zh_locale' =>
'/\.toLocale(?:String|DateString|TimeString)\s*\(\s*[\'\"]zh-CN[\'\"]/',
'legacy_language_branch' => '/\$language\s*={2,3}\s*[\'\"]true[\'\"]/',
'visible_chinese_literal' => '/\p{Han}/u',
];
/**
* Lines can be temporarily excluded with a documented marker while a
* migration is in progress. The final strict gate will reject markers
* without a non-empty reason.
*/
public static function scanContents(string $path, string $contents): array
{
$violations = [];
$lines = preg_split('/\R/', $contents);
if (!is_array($lines)) {
return $violations;
}
foreach ($lines as $offset => $line) {
if (preg_match('/user-copy:\s*allow\s+\S+/i', $line) === 1) {
continue;
}
foreach (self::RULES as $rule => $pattern) {
if (preg_match($pattern, $line) !== 1) {
continue;
}
$violations[] = [
'path' => $path,
'line' => $offset + 1,
'rule' => $rule,
'snippet' => trim($line),
];
}
}
return $violations;
}
public static function scanFiles(array $paths): array
{
$violations = [];
foreach ($paths as $path) {
if (!is_string($path) || !is_file($path)) {
continue;
}
$contents = file_get_contents($path);
if (!is_string($contents)) {
continue;
}
array_push($violations, ...self::scanContents($path, $contents));
}
return $violations;
}
}

@ -0,0 +1,336 @@
<?php
namespace App\Services\UserCopy;
use InvalidArgumentException;
/**
* Loads and validates the source-language contract for user-visible copy.
*
* The manifest contains stable semantic keys and a Chinese safety baseline.
* It must never contain target-locale translations; those belong to the
* administrator-managed publication ledger introduced by later stages.
*/
final class UserCopyManifest
{
private const KEY_PATTERN = '/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/D';
private const NAME_PATTERN = '/^[a-z][a-z0-9_]*$/D';
private const PAGE_PATTERN = '/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/D';
private const KINDS = [
'title', 'navigation', 'label', 'button', 'placeholder', 'help',
'description', 'status', 'empty_state', 'notice', 'warning',
'confirmation', 'toast_title', 'toast_body', 'aria_label',
'tooltip',
];
private const CRITICALITIES = ['normal', 'required', 'critical'];
private const FORMATS = ['plain_text', 'icu'];
private const PARAMETER_TYPES = [
'string', 'integer', 'number', 'date', 'time', 'datetime',
'currency', 'bytes', 'boolean',
];
private const TOAST_TONES = ['success', 'info', 'warning', 'error'];
private const ENTRY_FIELDS = [
'key', 'scope', 'page', 'kind', 'source', 'format', 'parameters',
'criticality', 'allow_hide', 'toast_tone',
];
public static function load(?string $path = null): array
{
$path = $path ?? dirname(__DIR__, 3)
. '/resources/user-copy/manifest.php';
if (!is_file($path)) {
throw new InvalidArgumentException(
'用户界面文案 Manifest 不存在:' . $path
);
}
$manifest = require $path;
if (!is_array($manifest)) {
throw new InvalidArgumentException(
'用户界面文案 Manifest 必须返回数组。'
);
}
return self::validate($manifest);
}
public static function validate(array $manifest): array
{
self::assertExactFields($manifest, ['version', 'pages', 'entries'],
'Manifest');
if (($manifest['version'] ?? null) !== 1) {
throw new InvalidArgumentException('不支持的文案 Manifest 版本。');
}
if (!is_array($manifest['pages']) || $manifest['pages'] === []) {
throw new InvalidArgumentException('文案页面目录不能为空。');
}
if (!is_array($manifest['entries'])
|| !array_is_list($manifest['entries'])) {
throw new InvalidArgumentException(
'文案词条目录必须是列表,词条键应写入 key 字段。'
);
}
$pages = [];
foreach ($manifest['pages'] as $pageKey => $page) {
if (!is_string($pageKey)
|| preg_match(self::PAGE_PATTERN, $pageKey) !== 1) {
throw new InvalidArgumentException(
'文案页面键格式无效:' . (string) $pageKey
);
}
if (!is_array($page)) {
throw new InvalidArgumentException(
'文案页面定义必须是数组:' . $pageKey
);
}
self::assertExactFields($page, ['label', 'scopes'],
'页面 ' . $pageKey);
$label = self::requiredText($page['label'] ?? null,
'页面标签 ' . $pageKey, 128);
if (!is_array($page['scopes']) || $page['scopes'] === []) {
throw new InvalidArgumentException(
'页面必须声明至少一个 scope:' . $pageKey
);
}
$scopes = [];
foreach ($page['scopes'] as $scope) {
if (!is_string($scope)
|| preg_match(self::NAME_PATTERN, $scope) !== 1) {
throw new InvalidArgumentException(
'页面 scope 格式无效:' . $pageKey
);
}
$scopes[$scope] = true;
}
$pages[$pageKey] = [
'label' => $label,
'scopes' => array_keys($scopes),
];
}
$entries = [];
foreach ($manifest['entries'] as $position => $entry) {
if (!is_array($entry)) {
throw new InvalidArgumentException(
'文案词条定义必须是数组:#' . $position
);
}
self::assertExactFields($entry, self::ENTRY_FIELDS,
'词条 #' . $position);
$copyKey = $entry['key'] ?? null;
if (!is_string($copyKey)
|| preg_match(self::KEY_PATTERN, $copyKey) !== 1) {
throw new InvalidArgumentException(
'文案词条键必须是静态语义键:' . (string) $copyKey
);
}
if (array_key_exists($copyKey, $entries)) {
throw new InvalidArgumentException(
'文案词条键重复:' . $copyKey
);
}
$scope = self::name($entry['scope'] ?? null,
'词条 scope ' . $copyKey);
$page = (string) ($entry['page'] ?? '');
if (!isset($pages[$page])) {
throw new InvalidArgumentException(
'词条引用了未声明页面:' . $copyKey
);
}
if (!in_array($scope, $pages[$page]['scopes'], true)) {
throw new InvalidArgumentException(
'词条 scope 不属于声明页面:' . $copyKey
);
}
$kind = (string) ($entry['kind'] ?? '');
if (!in_array($kind, self::KINDS, true)) {
throw new InvalidArgumentException(
'词条类型无效:' . $copyKey
);
}
$source = self::requiredText($entry['source'] ?? null,
'词条中文基线 ' . $copyKey, 4000);
$format = (string) ($entry['format'] ?? 'plain_text');
if (!in_array($format, self::FORMATS, true)) {
throw new InvalidArgumentException(
'词条格式无效:' . $copyKey
);
}
$parameters = self::parameters(
$entry['parameters'] ?? [], $copyKey
);
self::assertSourceParameters($source, $parameters, $copyKey);
if ($parameters !== [] && $format !== 'icu') {
throw new InvalidArgumentException(
'带参数词条必须使用 ICU 格式:' . $copyKey
);
}
$criticality = (string) ($entry['criticality'] ?? 'normal');
if (!in_array($criticality, self::CRITICALITIES, true)) {
throw new InvalidArgumentException(
'词条安全等级无效:' . $copyKey
);
}
if (!is_bool($entry['allow_hide'] ?? null)) {
throw new InvalidArgumentException(
'词条 allow_hide 必须是布尔值:' . $copyKey
);
}
$allowHide = $entry['allow_hide'];
if ($allowHide && $criticality !== 'normal') {
throw new InvalidArgumentException(
'必需或高风险词条不能隐藏:' . $copyKey
);
}
$toastTone = $entry['toast_tone'] ?? null;
$isToast = str_starts_with($kind, 'toast_');
if ($isToast) {
if (!is_string($toastTone)
|| !in_array($toastTone, self::TOAST_TONES, true)) {
throw new InvalidArgumentException(
'Toast 词条必须声明有效 tone:' . $copyKey
);
}
} elseif ($toastTone !== null) {
throw new InvalidArgumentException(
'非 Toast 词条不能声明 tone:' . $copyKey
);
}
$entries[$copyKey] = [
'key' => $copyKey,
'scope' => $scope,
'page' => $page,
'kind' => $kind,
'source' => $source,
'format' => $format,
'parameters' => $parameters,
'criticality' => $criticality,
'allow_hide' => $allowHide,
'toast_tone' => $toastTone,
];
}
ksort($pages, SORT_STRING);
ksort($entries, SORT_STRING);
return [
'version' => 1,
'pages' => $pages,
'entries' => array_values($entries),
];
}
public static function digest(array $manifest): string
{
$validated = self::validate($manifest);
$json = json_encode($validated,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if (!is_string($json)) {
throw new InvalidArgumentException('无法编码文案 Manifest。');
}
return hash('sha256', $json);
}
private static function parameters($value, string $copyKey): array
{
if (!is_array($value)) {
throw new InvalidArgumentException(
'词条参数合同必须是数组:' . $copyKey
);
}
$parameters = [];
foreach ($value as $name => $type) {
if (!is_string($name)
|| preg_match(self::NAME_PATTERN, $name) !== 1
|| !is_string($type)
|| !in_array($type, self::PARAMETER_TYPES, true)) {
throw new InvalidArgumentException(
'词条参数合同无效:' . $copyKey
);
}
if (isset($parameters[$name])) {
throw new InvalidArgumentException(
'词条参数重复:' . $copyKey . ':' . $name
);
}
$parameters[$name] = $type;
}
ksort($parameters, SORT_STRING);
return $parameters;
}
private static function assertSourceParameters(
string $source,
array $parameters,
string $copyKey
): void {
preg_match_all('/\{([a-z][a-z0-9_]*)\s*(?:[,}])/D', $source,
$matches);
$used = array_values(array_unique($matches[1] ?? []));
sort($used, SORT_STRING);
$declared = array_keys($parameters);
sort($declared, SORT_STRING);
if ($used !== $declared) {
throw new InvalidArgumentException(
'词条参数与中文基线不一致:' . $copyKey
);
}
}
private static function requiredText(
$value,
string $label,
int $maximumLength
): string {
if (!is_string($value) || trim($value) === '') {
throw new InvalidArgumentException($label . '不能为空。');
}
if (mb_strlen($value) > $maximumLength
|| preg_match(
'/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x{202A}-\x{202E}\x{2066}-\x{2069}]/u',
$value
)) {
throw new InvalidArgumentException($label . '包含非法内容。');
}
return $value;
}
private static function name($value, string $label): string
{
if (!is_string($value)
|| preg_match(self::NAME_PATTERN, $value) !== 1) {
throw new InvalidArgumentException($label . '格式无效。');
}
return $value;
}
private static function assertExactFields(
array $value,
array $allowed,
string $label
): void {
$unknown = array_values(array_diff(array_keys($value), $allowed));
$missing = array_values(array_diff($allowed, array_keys($value)));
if ($unknown !== []) {
throw new InvalidArgumentException(
$label . ' 包含未声明字段:' . implode(', ', $unknown)
);
}
if ($missing !== []) {
throw new InvalidArgumentException(
$label . ' 缺少字段:' . implode(', ', $missing)
);
}
}
}

@ -0,0 +1,100 @@
<?php
/**
* Source-language manifest for user-visible interface copy.
*
* Only stable keys, Chinese safety baselines and rendering metadata belong
* here. English and every other target-locale translation are maintained by
* administrators and must never be committed to this source manifest.
*/
return [
'version' => 1,
'pages' => [
'auth.login' => ['label' => '登录页', 'scopes' => ['common', 'auth']],
'auth.password' => ['label' => '重置密码页', 'scopes' => ['common', 'auth']],
'auth.register' => ['label' => '注册页', 'scopes' => ['common', 'auth']],
'cloud.backups' => ['label' => '云备份页', 'scopes' => ['common', 'backups']],
'cloud.deploy' => ['label' => '实例部署页', 'scopes' => ['common', 'deploy']],
'cloud.detail' => ['label' => '实例详情页', 'scopes' => ['common', 'instance_detail']],
'cloud.invoice_detail' => ['label' => '账单详情页', 'scopes' => ['common', 'billing']],
'cloud.invoices' => ['label' => '账单列表页', 'scopes' => ['common', 'billing']],
'cloud.instances' => ['label' => '实例列表页', 'scopes' => ['common', 'instances']],
'cloud.isos' => ['label' => 'ISO镜像页', 'scopes' => ['common', 'isos']],
'cloud.keys' => ['label' => 'SSH公钥页', 'scopes' => ['common', 'ssh_keys']],
'cloud.reinstall' => ['label' => '重装系统页', 'scopes' => ['common', 'reinstall']],
'cloud.snapshots' => ['label' => '云快照页', 'scopes' => ['common', 'snapshots']],
'cloud.traffic' => ['label' => '流量池页', 'scopes' => ['common', 'traffic']],
'cloud.vpcs' => ['label' => 'VPC私网页', 'scopes' => ['common', 'vpc']],
'legal.privacy' => ['label' => '隐私政策页', 'scopes' => ['common', 'legal']],
'legal.terms' => ['label' => '服务条款页', 'scopes' => ['common', 'legal']],
'public.home' => ['label' => '落地页', 'scopes' => ['common', 'home']],
'user.account' => ['label' => '账户设置页', 'scopes' => ['common', 'account']],
'user.announcements' => ['label' => '公告抽屉', 'scopes' => ['common', 'announcements']],
'user.invite' => ['label' => '推广页', 'scopes' => ['common', 'invite']],
'user.recharge' => ['label' => '充值页', 'scopes' => ['common', 'recharge']],
'user.tasks' => ['label' => '任务中心', 'scopes' => ['common', 'tasks']],
'user.tickets' => ['label' => '工单页', 'scopes' => ['common', 'tickets']],
],
'entries' => [
[
'key' => 'common.toast.close.aria',
'scope' => 'common',
'page' => 'cloud.instances',
'kind' => 'aria_label',
'source' => '关闭提示',
'format' => 'plain_text',
'parameters' => [],
'criticality' => 'required',
'allow_hide' => false,
'toast_tone' => null,
],
[
'key' => 'common.toast.error.title',
'scope' => 'common',
'page' => 'cloud.instances',
'kind' => 'toast_title',
'source' => '操作失败',
'format' => 'plain_text',
'parameters' => [],
'criticality' => 'required',
'allow_hide' => false,
'toast_tone' => 'error',
],
[
'key' => 'common.toast.success.body',
'scope' => 'common',
'page' => 'cloud.instances',
'kind' => 'toast_body',
'source' => '操作已完成。',
'format' => 'plain_text',
'parameters' => [],
'criticality' => 'required',
'allow_hide' => false,
'toast_tone' => 'success',
],
[
'key' => 'common.toast.success.title',
'scope' => 'common',
'page' => 'cloud.instances',
'kind' => 'toast_title',
'source' => '操作完成',
'format' => 'plain_text',
'parameters' => [],
'criticality' => 'required',
'allow_hide' => false,
'toast_tone' => 'success',
],
[
'key' => 'common.toast.warning.title',
'scope' => 'common',
'page' => 'cloud.instances',
'kind' => 'toast_title',
'source' => '请注意',
'format' => 'plain_text',
'parameters' => [],
'criticality' => 'required',
'allow_hide' => false,
'toast_tone' => 'warning',
],
],
];

@ -0,0 +1,106 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyCoverageScanner;
use App\Services\UserCopy\UserCopyManifest;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$rejects = static function (array $manifest, string $needle) use ($assert): void {
try {
UserCopyManifest::validate($manifest);
} catch (InvalidArgumentException $exception) {
$assert(str_contains($exception->getMessage(), $needle),
'Manifest rejection did not identify the expected contract: '
. $exception->getMessage());
return;
}
throw new RuntimeException('Invalid Manifest was accepted: ' . $needle);
};
$manifest = UserCopyManifest::load();
$loadedEntries = array_column($manifest['entries'], null, 'key');
$assert(($manifest['version'] ?? null) === 1
&& isset($manifest['pages']['cloud.instances'])
&& isset($loadedEntries['common.toast.success.title']),
'Source-language user-copy Manifest did not load its page and Toast contract.');
$assert(strlen(UserCopyManifest::digest($manifest)) === 64,
'User-copy Manifest digest is not a SHA-256 identity.');
$base = [
'version' => 1,
'pages' => [
'test.page' => ['label' => '测试页面', 'scopes' => ['test']],
],
'entries' => [
[
'key' => 'test.greeting',
'scope' => 'test', 'page' => 'test.page', 'kind' => 'label',
'source' => '您好,{name}', 'format' => 'icu',
'parameters' => ['name' => 'string'],
'criticality' => 'normal', 'allow_hide' => true,
'toast_tone' => null,
],
],
];
$validatedBase = UserCopyManifest::validate($base);
$validatedBaseEntries = array_column(
$validatedBase['entries'], null, 'key'
);
$assert($validatedBaseEntries['test.greeting']['source'] === '您好,{name}',
'Valid ICU source entry was not retained.');
$duplicateKey = $base;
$duplicateKey['entries'][] = $duplicateKey['entries'][0];
$rejects($duplicateKey, '词条键重复');
$invalidKey = $base;
$invalidKey['entries'][0]['key'] = 'test.{dynamic}';
$rejects($invalidKey, '静态语义键');
$invalidParameter = $base;
$invalidParameter['entries'][0]['parameters'] = [
'other' => 'string',
];
$rejects($invalidParameter, '参数与中文基线不一致');
$invalidParameterName = $base;
$invalidParameterName['entries'][0]['parameters'] = [
'user-name' => 'string',
];
$rejects($invalidParameterName, '参数合同无效');
$translationInSource = $base;
$translationInSource['entries'][0]['en'] = 'Hello';
$rejects($translationInSource, '未声明字段');
$unsafeDirection = $base;
$unsafeDirection['entries'][0]['source'] = "您好\u{202E}";
$rejects($unsafeDirection, '非法内容');
$hiddenCritical = $base;
$hiddenCritical['entries'][0]['criticality'] = 'critical';
$rejects($hiddenCritical, '高风险词条不能隐藏');
$toastWithoutTone = $base;
$toastWithoutTone['entries'][0]['kind'] = 'toast_body';
$rejects($toastWithoutTone, 'Toast 词条必须声明有效 tone');
$source = <<<'SOURCE'
toast('任务已接收。', 'success');
window.confirm('确定删除?');
date.toLocaleString('zh-CN');
// user-copy: allow fixture 中文测试数据
SOURCE;
$violations = UserCopyCoverageScanner::scanContents('fixture.js', $source);
$rules = array_count_values(array_column($violations, 'rule'));
$assert(($rules['direct_toast_text'] ?? 0) === 1
&& ($rules['direct_confirm_text'] ?? 0) === 1
&& ($rules['hardcoded_zh_locale'] ?? 0) === 1
&& ($rules['visible_chinese_literal'] ?? 0) === 2,
'Coverage scanner did not report direct user-visible copy consistently.');
echo "User-copy Manifest and coverage-scanner contract checks passed.\n";
Loading…
Cancel
Save