fix(i18n): 제품이 화면 언어를 자기 파일에서 선언한다

문제: 지원 locale 목록, 언어 대체, 글 방향, 문구 표, 셸의 언어
선택지가 템플릿 파일 다섯 곳에 손으로 적혀 있다. 한 언어 제품은 가짜
en-US 문구를 만들거나 템플릿 파일을 고쳐야 하고, 운영 셸 메뉴에
Pseudo·RTL 시험 locale이 보인다(0929/08-01).

고른 방법(1101 결정 (가), 템플릿이 확장 지점을 연다):
- 제품 소유 src/contracts/product-contracts.ts에 PRODUCT_LOCALES
  (기본 ko-KR, en-US)와 DEV_LOCALES(기본 en-XA, ar-EG)를 둔다.
- message-contract가 둘에서 SUPPORTED_LOCALES, 언어 대체(같은 언어의
  첫 선언 locale, 없으면 첫 제품 locale), 글 방향(RTL 언어 집합),
  DEFAULT_LOCALE을 만든다. 시험 locale은 en-US 문구를, en-US가 없으면 첫
  제품 locale 문구를 보인다.
- catalog.ts는 선언한 제품 locale마다 문구 표 하나를 둔다. en-US 표는
  en-US를 선언했을 때만 모든 키를 요구한다.
- 셸 언어 선택지는 선언에서 나오고, locale이 하나면 선택을 그리지 않는다.
  템플릿 문구에 없는 locale은 Intl.DisplayNames의 자기 이름으로 적는다.
버린 대안: 운영 환경(APP_ENV)에서 시험 locale을 자동으로 숨기기 —
presentation이 실행 환경을 읽는 포트가 없고, e2e가 production 빌드로
시험 locale을 고른다. 제품이 DEV_LOCALES를 비우는 쪽이 명시적이다.

위험·한계: ko-KR은 다른 표를 대조하는 원본이라 남겨야 한다. 템플릿에
없는 언어를 선언하면 그 문구 표가 catalog.ts에 있어야 한다(타입 오류로
알린다). 시험 locale을 빼는 것은 제품이 DEV_LOCALES를 비울 때다.

검증: desktop 결과는 PR 본문.

Refs: 0929/08-01
This commit is contained in:
DongHyeonka
2026-11-13 21:16:40 +09:00
parent 5aac37e676
commit ade1fc4a71
14 changed files with 250 additions and 68 deletions
+4 -1
View File
@@ -123,10 +123,13 @@ release admission refused for staging:
- `close`가 던지면 scope가 `FAILED`에 머물고 모든 서버 요청이 `SCOPE_FENCED`로 막힌다. 진단 `cache.operation.failed`에 `reason: PARTICIPANT_FAILED`와 `scope_participant: <label>`이 남으니 그 기록으로 원인 closer를 찾는다.
- 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다.
- 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [optional adapter recipe 「짝 백엔드 실시간 출구와의 대응」](../architecture/optional-adapter-recipes.md#짝-백엔드-실시간-출구와의-대응).
- `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때.
- `src/contracts/product-contracts.ts`: 제품 인증 프로필, 제품 런타임 설정 키, 화면 언어가 필요할 때.
- 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다.
- 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈추고, 오류 화면의 "잘못된 설정 키"에 그 키 이름(값은 아님. 중첩 키는 `CAPABILITY_OVERRIDES.AUTH_TOKEN`처럼 경로)이 나온다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다.
- FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다.
- 화면 언어도 여기서 정한다(`PRODUCT_LOCALES`, `DEV_LOCALES`). 한 언어 제품은 `PRODUCT_LOCALES`를 `["ko-KR"]`로 적는다. 그러면 기능에 en-US 문구가 없어도 타입 검사가 통과하고, 언어 선택이 셸에서 사라진다. 지원 목록·언어 대체·글 방향·문구 표·셸 선택지는 이 두 값에서 나온다.
- `DEV_LOCALES`(가짜 번역 `en-XA`, 오른쪽에서 왼쪽 `ar-EG`)는 배치 시험용이다. 제품 운영 빌드의 메뉴에서 빼려면 비운다. 템플릿은 자기 시험 때문에 둘 다 둔다.
- `ko-KR`은 남긴다. 다른 문구 표를 대조하는 원본이다. 템플릿에 없는 언어를 더하려면 그 문구 표가 있어야 한다(없으면 `src/presentation/i18n/catalog.ts`에서 타입 오류).
- `config/runtime/<profile>.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`).
- `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다.
- `config/ci/product-gates.json`: 배포 job(`deployment`)을 채우거나 제품 전용 merge 검사(`PRODUCT-GATE-NNN`)를 더할 때. 템플릿 파일 `config/ci/gates.json`은 고치지 않는다. 형식은 [`ci-quality-gates.md`](../operations/ci-quality-gates.md)에 있다.
+4 -2
View File
@@ -5,6 +5,7 @@ import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import path from "node:path";
import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts";
import { SUPPORTED_LOCALES } from "../src/presentation/i18n/message-contract.ts";
const fixtureMode = process.argv.includes("--fixture");
const failures: string[] = [];
@@ -46,7 +47,8 @@ if (!fixtureMode) {
}
}
}
if (Object.keys(EN_MESSAGES).length !== canonicalKeys.length) {
// 0929/08-01. Only a product that ships en-US needs every key in it.
if (Object.hasOwn(MESSAGE_CATALOGS, "en-US") && Object.keys(EN_MESSAGES).length !== canonicalKeys.length) {
failures.push("en-US catalog key count does not match ko-KR");
}
}
@@ -136,7 +138,7 @@ const allowedFixtureFailures = fixtureMode
const report = i18nReportArtifactSchema.parse({
schemaVersion: 1,
mode: fixtureMode ? "negative-fixture" : "source",
localeCount: Object.keys(MESSAGE_CATALOGS).length + 1,
localeCount: SUPPORTED_LOCALES.length,
messageKeyCount: Object.keys(KO_MESSAGES).length,
checkedFiles: sources.length,
failures,
+15
View File
@@ -15,6 +15,17 @@
* - `PRODUCT_REST_AUTH_PROFILES`: auth profiles installed next to the
* template's (`rest-profiles.ts`); credentials for them come from
* `src/bootstrap/product-composition.ts`.
* - `PRODUCT_LOCALES` (0929/08-01): the UI locales the product ships, in the
* order the locale menu lists them. The first one answers a browser locale
* no entry matches. The template has catalogs for `ko-KR` (the source every
* other catalog is checked against, so it stays) and `en-US`; a one-language
* product writes `["ko-KR"]` and its features need no en-US catalog. The
* template ships both.
* - `DEV_LOCALES` (0929/08-01): test locales, pseudo-localized `en-XA` and
* right-to-left `ar-EG`, listed after the product's. They show the en-US
* catalog, or the first product locale's without one. A product's own build
* empties it to keep them out of its menu; the template ships both for its
* layout tests.
*/
export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({});
@@ -22,3 +33,7 @@ export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({});
export const PRODUCT_ENV_REGISTRY = Object.freeze({});
export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({});
export const PRODUCT_LOCALES = Object.freeze(["ko-KR", "en-US"] as const);
export const DEV_LOCALES = Object.freeze(["en-XA", "ar-EG"] as const);
@@ -60,3 +60,16 @@ export const INSTALLED_MESSAGE_CATALOGS = composeInstalledMessageCatalogs(
) as {
readonly [Locale in InstalledLocale]: LocaleCatalog<Locale>;
};
/**
* 0929/08-01. One locale's composed feature catalog, typed for that locale
* whether or not an installed feature declares it: a one-language product's
* features carry no en-US catalog, and the template's en-US table still reads
* this.
*/
export function installedMessageCatalog<Locale extends string>(
locale: Locale,
): LocaleCatalog<Locale> {
const catalogs = INSTALLED_MESSAGE_CATALOGS as Readonly<Record<string, unknown>>;
return (catalogs[locale] ?? Object.freeze({})) as LocaleCatalog<Locale>;
}
+28 -5
View File
@@ -1,4 +1,8 @@
import { INSTALLED_MESSAGE_CATALOGS } from "../../features/installed-feature-messages.ts";
import {
INSTALLED_MESSAGE_CATALOGS,
installedMessageCatalog,
} from "../../features/installed-feature-messages.ts";
import { PRODUCT_LOCALES } from "../../contracts/product-contracts.ts";
import { BOOT_MESSAGES } from "./boot-messages.ts";
const PLATFORM_KO_MESSAGES = {
@@ -409,13 +413,32 @@ const PLATFORM_EN_MESSAGES = {
...BOOT_MESSAGES["en-US"],
} as const satisfies Record<keyof typeof PLATFORM_KO_MESSAGES, string>;
/**
* 0929/08-01. Complete (every key) only when the product ships en-US
* (`PRODUCT_LOCALES`): a one-language product's features carry no en-US
* catalog, and the test locales then show the first product locale.
*/
export const EN_MESSAGES = {
...PLATFORM_EN_MESSAGES,
...INSTALLED_MESSAGE_CATALOGS["en-US"],
} as const satisfies Record<MessageKey, string>;
...installedMessageCatalog("en-US"),
} as const satisfies "en-US" extends (typeof PRODUCT_LOCALES)[number]
? Record<MessageKey, string>
: Readonly<Record<string, string>>;
export const MESSAGE_CATALOGS = Object.freeze({
/** Every catalog the template has; a product locale outside it is a type error below. */
const TEMPLATE_CATALOGS = Object.freeze({
"ko-KR": KO_MESSAGES,
"en-US": EN_MESSAGES,
"ar-EG": EN_MESSAGES,
});
/**
* 0929/08-01. One complete catalog per declared product locale. The test
* locales (`DEV_LOCALES`) have none of their own (message-contract.ts).
*/
export const MESSAGE_CATALOGS = Object.freeze(
Object.fromEntries(
PRODUCT_LOCALES.map((locale) => [locale, TEMPLATE_CATALOGS[locale]]),
),
) as Readonly<
Record<(typeof PRODUCT_LOCALES)[number], Readonly<Record<MessageKey, string>>>
>;
+4
View File
@@ -2,8 +2,10 @@ export { LocaleProvider, useLocale } from "./locale-provider.tsx";
export {
catalogKeys,
fallbackMessage,
DEFAULT_LOCALE,
formatMessage,
localeDirection,
localeLabel,
MESSAGE_KEY_ALIASES,
messagePlaceholders,
normalizeLocale,
@@ -13,7 +15,9 @@ export {
export type {
MessageArguments,
MessageParameters,
DevLocale,
ParameterlessMessageKey,
ProductLocale,
SupportedLocale,
TextDirection,
} from "./message-contract.ts";
+3 -3
View File
@@ -15,6 +15,7 @@ import {
selectPlural,
} from "./formatters.ts";
import {
DEFAULT_LOCALE,
formatMessage,
localeDirection,
normalizeLocale,
@@ -54,10 +55,9 @@ type LocaleContextValue = Readonly<{
): string;
}>;
const DEFAULT_LOCALE = "ko-KR" as const;
const DEFAULT_CONTEXT: LocaleContextValue = Object.freeze({
locale: DEFAULT_LOCALE,
direction: "ltr",
direction: localeDirection(DEFAULT_LOCALE),
setLocale() {},
message: (key, ...args) => formatMessage(DEFAULT_LOCALE, key, ...args),
resolve: (key) => resolveMessage(DEFAULT_LOCALE, key),
@@ -73,7 +73,7 @@ const LocaleContext = createContext<LocaleContextValue>(DEFAULT_CONTEXT);
export function LocaleProvider({
children,
initialLocale = "ko-KR",
initialLocale = DEFAULT_LOCALE,
onLocaleChange,
}: Readonly<{
children: React.ReactNode;
+76 -20
View File
@@ -1,3 +1,7 @@
import {
DEV_LOCALES,
PRODUCT_LOCALES,
} from "../../contracts/product-contracts.ts";
import {
EN_MESSAGES,
KO_MESSAGES,
@@ -5,15 +9,26 @@ import {
type MessageKey,
} from "./catalog.ts";
export const SUPPORTED_LOCALES = Object.freeze([
"ko-KR",
"en-US",
"en-XA",
"ar-EG",
] as const);
export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number];
/**
* 0929/08-01. Every locale list below derives from the product's declaration
* (`src/contracts/product-contracts.ts`), so a one-language product changes
* that file only: no fake catalog, no template edit, no test locales in its
* menu once it empties `DEV_LOCALES`.
*/
export type ProductLocale = (typeof PRODUCT_LOCALES)[number];
export type DevLocale = (typeof DEV_LOCALES)[number];
export const SUPPORTED_LOCALES: readonly (ProductLocale | DevLocale)[] = Object.freeze([
...PRODUCT_LOCALES,
...DEV_LOCALES,
]);
export type SupportedLocale = ProductLocale | DevLocale;
export type TextDirection = "ltr" | "rtl";
/** The pseudo locale: the source catalog, accented and bracketed. */
const PSEUDO_LOCALE: string = "en-XA";
/** Languages written right to left (the template's RTL test locale is ar-EG). */
const RIGHT_TO_LEFT_LANGUAGES: ReadonlySet<string> = new Set(["ar", "fa", "he", "ur"]);
/**
* 0929/08-03. The `{name}` placeholders of a catalog string literal. The
* catalogs are `as const`, so platform and feature keys share this one rule
@@ -59,25 +74,67 @@ export type MessageArguments<Key extends MessageKey> =
: [parameters: CatalogParameters<Key>];
const PLACEHOLDER_PATTERN = /\{([a-zA-Z][a-zA-Z0-9]*)\}/g;
const FALLBACK_LOCALE = "ko-KR" as const;
const FALLBACK_LOCALE: ProductLocale = PRODUCT_LOCALES[0];
/** 0929/08-01. The locale a page starts in before a preference is read. */
export const DEFAULT_LOCALE: ProductLocale = FALLBACK_LOCALE;
/** The catalog a test locale shows: en-US when the product ships it. */
const DEV_SOURCE_LOCALE: ProductLocale =
PRODUCT_LOCALES.find((locale) => String(locale) === "en-US") ?? FALLBACK_LOCALE;
export const MESSAGE_KEY_ALIASES = Object.freeze({
"action.login": "action.reauth",
"async.pending": "common.processing",
} as const satisfies Readonly<Record<string, MessageKey>>);
function languageOf(locale: string): string {
return locale.split("-")[0]?.toLowerCase() ?? "";
}
function isProductLocale(locale: string): locale is ProductLocale {
return (PRODUCT_LOCALES as readonly string[]).includes(locale);
}
/**
* A declared locale as is, else the first product locale of its language,
* else the first product locale. A test locale is never reached by language:
* an English browser of a ko-KR-only product gets ko-KR, not pseudo text.
*/
export function normalizeLocale(locale: string): SupportedLocale {
if ((SUPPORTED_LOCALES as readonly string[]).includes(locale)) {
return locale as SupportedLocale;
}
const language = locale.split("-")[0]?.toLowerCase();
if (language === "ko") return "ko-KR";
if (language === "ar") return "ar-EG";
if (language === "en") return "en-US";
return FALLBACK_LOCALE;
const language = languageOf(locale);
return (
PRODUCT_LOCALES.find((candidate) => languageOf(candidate) === language) ??
FALLBACK_LOCALE
);
}
const LOCALE_LABEL_KEYS: Readonly<Partial<Record<string, ParameterlessMessageKey>>> = {
"ko-KR": "shell.locale.ko",
"en-US": "shell.locale.en",
[PSEUDO_LOCALE]: "shell.locale.pseudo",
"ar-EG": "shell.locale.rtl",
};
/**
* 0929/08-01. The locale menu's name for a locale: the template's catalog
* label where it has one, otherwise the locale's own name for itself.
*/
export function localeLabel(
locale: SupportedLocale,
message: (key: ParameterlessMessageKey) => string,
): string {
const key = LOCALE_LABEL_KEYS[locale];
if (key !== undefined) return message(key);
try {
return new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
} catch {
return locale;
}
}
export function localeDirection(locale: SupportedLocale): TextDirection {
return locale === "ar-EG" ? "rtl" : "ltr";
return RIGHT_TO_LEFT_LANGUAGES.has(languageOf(locale)) ? "rtl" : "ltr";
}
export function messagePlaceholders(template: string): readonly string[] {
@@ -92,8 +149,9 @@ export function resolveMessage(
parameters?: Readonly<Record<string, string | number>>,
): string {
const normalized = normalizeLocale(locale);
const sourceLocale: keyof typeof MESSAGE_CATALOGS =
normalized === "en-XA" ? "en-US" : normalized;
const sourceLocale: ProductLocale = isProductLocale(normalized)
? normalized
: DEV_SOURCE_LOCALE;
const catalog =
MESSAGE_CATALOGS[sourceLocale] ??
MESSAGE_CATALOGS[FALLBACK_LOCALE];
@@ -116,7 +174,7 @@ export function resolveMessage(
PLACEHOLDER_PATTERN,
(_, placeholder: string) => String(parameters?.[placeholder] ?? ""),
);
return normalized === "en-XA" ? pseudoLocalize(formatted) : formatted;
return normalized === PSEUDO_LOCALE ? pseudoLocalize(formatted) : formatted;
}
export function formatMessage<Key extends MessageKey>(
@@ -150,9 +208,7 @@ function pseudoLocalize(value: string): string {
return `[${expanded} ···]`;
}
export function catalogKeys(
locale: "ko-KR" | "en-US" | "ar-EG",
): MessageKey[] {
export function catalogKeys(locale: ProductLocale): MessageKey[] {
return Object.keys(MESSAGE_CATALOGS[locale]).sort() as MessageKey[];
}
+19 -15
View File
@@ -12,7 +12,9 @@ import {
Select,
} from "../design-system/index.ts";
import {
localeLabel,
normalizeLocale,
SUPPORTED_LOCALES,
useLocale,
type MessageKey,
} from "../i18n/index.ts";
@@ -75,21 +77,23 @@ export function AppShell() {
and the session status here; the menu drawer shows them (08-01). */}
<div className="app-shell__session">
<ThemePreferenceSelect className="theme-selector" id="theme-preference" />
<Select
className="locale-selector"
id="locale-preference"
label={message("shell.locale")}
options={[
{ value: "ko-KR", label: message("shell.locale.ko") },
{ value: "en-US", label: message("shell.locale.en") },
{ value: "en-XA", label: message("shell.locale.pseudo") },
{ value: "ar-EG", label: message("shell.locale.rtl") },
]}
value={locale}
onChange={(event) =>
setLocale(normalizeLocale(event.currentTarget.value))
}
/>
{/* 0929/08-01. The declared locales (src/contracts/product-contracts.ts);
a one-locale product has nothing to choose. */}
{SUPPORTED_LOCALES.length > 1 ? (
<Select
className="locale-selector"
id="locale-preference"
label={message("shell.locale")}
options={SUPPORTED_LOCALES.map((value) => ({
value,
label: localeLabel(value, message),
}))}
value={locale}
onChange={(event) =>
setLocale(normalizeLocale(event.currentTarget.value))
}
/>
) : null}
<SessionStatus />
{integrationAvailable ? (
<Button
@@ -1,6 +1,6 @@
import type { ReactNode } from "react";
import { LocaleProvider, normalizeLocale } from "../i18n/index.ts";
import { DEFAULT_LOCALE, LocaleProvider, normalizeLocale } from "../i18n/index.ts";
import { useApplicationPreferences } from "./application-provider.tsx";
import { ThemeProvider } from "./theme-provider.tsx";
@@ -14,7 +14,7 @@ export function PreferenceProviders({
const preferences = useApplicationPreferences();
return (
<LocaleProvider
initialLocale={normalizeLocale(preferences.getLocale() ?? "ko-KR")}
initialLocale={normalizeLocale(preferences.getLocale() ?? DEFAULT_LOCALE)}
onLocaleChange={preferences.setLocale}
>
<ThemeProvider>{children}</ThemeProvider>
+2 -2
View File
@@ -152,7 +152,7 @@ describe("locale provider runtime", () => {
it("reverses horizontal tab focus semantics in RTL", async () => {
const user = userEvent.setup();
render(
<LocaleProvider initialLocale="ar-EG">
<LocaleProvider initialLocale={"ar-EG" as string as SupportedLocale}>
<Tabs
activation="manual"
label="sections"
@@ -174,7 +174,7 @@ describe("locale provider runtime", () => {
it("keeps pagination semantics while direction-aware icons remain decorative", () => {
render(
<LocaleProvider initialLocale="ar-EG">
<LocaleProvider initialLocale={"ar-EG" as string as SupportedLocale}>
<Pagination
label="pages"
nextLabel="Next page"
+2 -2
View File
@@ -10,7 +10,7 @@ import { deriveAsyncState } from "../../src/application/view-models/async-state.
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx";
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { LocaleProvider, type SupportedLocale } from "../../src/presentation/i18n/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
@@ -205,7 +205,7 @@ describe("render recovery boundaries", () => {
it("renders the default fallback in the current locale", () => {
render(
<LocaleProvider initialLocale="en-US">
<LocaleProvider initialLocale={"en-US" as string as SupportedLocale}>
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<Defect />
</FeatureBoundary>
+28 -16
View File
@@ -16,6 +16,8 @@ import {
resolveMessage,
selectMessage,
selectPlural,
type ProductLocale,
type SupportedLocale,
} from "../../src/presentation/i18n/index.ts";
import {
EN_MESSAGES,
@@ -23,17 +25,27 @@ import {
MESSAGE_CATALOGS,
} from "../../src/presentation/i18n/catalog.ts";
/**
* 0929/08-01. These rows test the template's own locales. A product may
* declare others (src/contracts/product-contracts.ts), so the literals go
* through strings and the file still typechecks there.
*/
const locale = (value: string) => value as SupportedLocale;
const productLocale = (value: string) => value as ProductLocale;
describe("internationalization message contract", () => {
it("keeps every registered catalog and interpolation contract in parity", () => {
expect(catalogKeys("en-US")).toEqual(catalogKeys("ko-KR"));
expect(catalogKeys("ar-EG")).toEqual(catalogKeys("ko-KR"));
expect(catalogKeys(productLocale("en-US"))).toEqual(catalogKeys("ko-KR"));
for (const key of catalogKeys("ko-KR")) {
expect(messagePlaceholders(EN_MESSAGES[key])).toEqual(
messagePlaceholders(KO_MESSAGES[key]),
);
}
expect(MESSAGE_CATALOGS["ar-EG"]).toBe(EN_MESSAGES);
// 0929/08-01. One catalog per declared product locale; the test locales
// have none of their own and show en-US.
expect(Object.keys(MESSAGE_CATALOGS).sort()).toEqual(["en-US", "ko-KR"]);
expect(resolveMessage("ar-EG", "shell.locale")).toBe(EN_MESSAGES["shell.locale"]);
});
// 07-01/08-02. A kind without copy renders "This message is unavailable."
@@ -81,9 +93,9 @@ describe("internationalization message contract", () => {
});
it("defines direction without inferring it in components", () => {
expect(localeDirection("ko-KR")).toBe("ltr");
expect(localeDirection("en-XA")).toBe("ltr");
expect(localeDirection("ar-EG")).toBe("rtl");
expect(localeDirection(locale("ko-KR"))).toBe("ltr");
expect(localeDirection(locale("en-XA"))).toBe("ltr");
expect(localeDirection(locale("ar-EG"))).toBe("rtl");
});
});
@@ -91,25 +103,25 @@ describe("internationalization formatter contract", () => {
const instant = new Date("2026-07-26T23:30:00.000Z");
it("uses an explicit UTC default and deterministic locale formatting", () => {
expect(formatDate("en-US", instant, { dateStyle: "short" })).toBe(
expect(formatDate(locale("en-US"), instant, { dateStyle: "short" })).toBe(
"7/26/26",
);
expect(
formatDate("en-US", instant, {
formatDate(locale("en-US"), instant, {
dateStyle: "short",
timeZone: "Asia/Seoul",
}),
).toBe("7/27/26");
expect(formatNumber("en-US", 1234.5)).toBe("1,234.5");
expect(formatRelativeTime("en-US", -1, "day")).toBe("yesterday");
expect(formatList("en-US", ["one", "two", "three"])).toBe(
expect(formatNumber(locale("en-US"), 1234.5)).toBe("1,234.5");
expect(formatRelativeTime(locale("en-US"), -1, "day")).toBe("yesterday");
expect(formatList(locale("en-US"), ["one", "two", "three"])).toBe(
"one, two, and three",
);
expect(selectPlural("en-US", 1, { one: "item", other: "items" })).toBe(
expect(selectPlural(locale("en-US"), 1, { one: "item", other: "items" })).toBe(
"item",
);
expect(
selectPlural("en-US", 3, { one: "item", other: "items" }),
selectPlural(locale("en-US"), 3, { one: "item", other: "items" }),
).toBe("items");
expect(
selectMessage("pending", {
@@ -121,12 +133,12 @@ describe("internationalization formatter contract", () => {
});
it("does not throw or expose invalid formatter input", () => {
expect(formatDate("en-US", Number.NaN)).toBe(FORMAT_FALLBACK);
expect(formatNumber("en-US", Number.POSITIVE_INFINITY)).toBe(
expect(formatDate(locale("en-US"), Number.NaN)).toBe(FORMAT_FALLBACK);
expect(formatNumber(locale("en-US"), Number.POSITIVE_INFINITY)).toBe(
FORMAT_FALLBACK,
);
expect(
formatDate("en-US", instant, { timeZone: "not/a-time-zone" }),
formatDate(locale("en-US"), instant, { timeZone: "not/a-time-zone" }),
).toBe(FORMAT_FALLBACK);
});
});
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it, vi } from "vitest";
/**
* 0929/08-01. A one-language product declares its locales in its own file and
* changes nothing else: before this, the locale list, the language fallback,
* the text direction, the catalogs and the shell's menu were five copies in
* template files, so a ko-KR-only product made a fake en-US catalog or edited
* them, and its production menu offered Pseudo and RTL.
*/
vi.mock("../../src/contracts/product-contracts.ts", async (importOriginal) => ({
...(await importOriginal<typeof import("../../src/contracts/product-contracts.ts")>()),
PRODUCT_LOCALES: Object.freeze(["ko-KR"]),
DEV_LOCALES: Object.freeze([]),
}));
describe("0929/08-01 a ko-KR-only product", () => {
it("derives every locale list from its declaration", async () => {
const i18n = await import("../../src/presentation/i18n/index.ts");
const { MESSAGE_CATALOGS } = await import("../../src/presentation/i18n/catalog.ts");
expect(i18n.SUPPORTED_LOCALES).toEqual(["ko-KR"]);
expect(Object.keys(MESSAGE_CATALOGS)).toEqual(["ko-KR"]);
expect(i18n.DEFAULT_LOCALE).toBe("ko-KR");
// An English browser falls back to the product's one locale.
expect(i18n.normalizeLocale("en-US")).toBe("ko-KR");
expect(i18n.normalizeLocale("ar-EG")).toBe("ko-KR");
expect(i18n.resolveMessage("en-US", "shell.locale")).toBe(
i18n.resolveMessage("ko-KR", "shell.locale"),
);
});
});
describe("0929/08-01 test locales are chosen, not fallen into", () => {
it("sends an English browser of a ko-KR-only product with test locales to ko-KR", async () => {
vi.resetModules();
vi.doMock("../../src/contracts/product-contracts.ts", async (importOriginal) => ({
...(await importOriginal<typeof import("../../src/contracts/product-contracts.ts")>()),
PRODUCT_LOCALES: Object.freeze(["ko-KR"]),
DEV_LOCALES: Object.freeze(["en-XA", "ar-EG"]),
}));
const i18n = await import("../../src/presentation/i18n/index.ts");
expect(i18n.normalizeLocale("en-US")).toBe("ko-KR");
expect(i18n.normalizeLocale("ar-SA")).toBe("ko-KR");
// Picked by name, a test locale still works.
expect(i18n.normalizeLocale("en-XA")).toBe("en-XA");
expect(i18n.localeDirection(i18n.normalizeLocale("ar-EG"))).toBe("rtl");
vi.doUnmock("../../src/contracts/product-contracts.ts");
});
});