diff --git a/.changeset/i18n-cli-guide-caller-facing.md b/.changeset/i18n-cli-guide-caller-facing.md new file mode 100644 index 0000000000000..2a5ae61c49bdf --- /dev/null +++ b/.changeset/i18n-cli-guide-caller-facing.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[docs] The i18n, RTL and testing guide keeps to what holds for a caller: `useTranslator()` resolves every `@astryx.*` key; how a core component reads its strings moves to the contributing guide. + +@vjeux diff --git a/.changeset/i18n-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md new file mode 100644 index 0000000000000..ea7ae90473e61 --- /dev/null +++ b/.changeset/i18n-en-namespace-slices.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': minor +--- + +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `useLocale`, `useDirection` and `useCollator`, nor the components that read the locale or direction through them (the date, date-time, date-range and number inputs, Calendar, Chat, PowerSearch, Table sorting and filtering, Timestamp). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. Migration: mount `InternationalizationProvider`; its `locale`, `messages` and `overrides` take the value's fields of the same name, and its `dir` takes the value's `direction`. The provider has no `translate` input: an app that supplied its own `translate` expresses those strings as `messages` (a catalog per locale) or `overrides` (sparse, per locale) and the provider resolves them in the documented order. Run `astryx upgrade`: its `migrate-internationalization-context` transform rewrites a variable value to the provider's `locale`, `dir` and `messages` with a TODO for its `overrides` and `translate`, and an inline object literal key by key with a TODO for `translate`; any other value, and any element that spreads props, is left as written behind a TODO saying why. The provider now writes an internal runtime context that those hooks read. Reading the public context is unchanged, so a component that reads it with `useContext` and re-mounts `InternationalizationProvider` with a derived value keeps working: `locale`, `direction`, `messages`, `overrides` and `translate`, which still resolves every `@astryx.*` key against the whole shipped English catalog, with or without a provider; `useTranslator()` is unchanged. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. + +@vjeux diff --git a/.changeset/vite-locale-alias-one-segment.md b/.changeset/vite-locale-alias-one-segment.md new file mode 100644 index 0000000000000..e9a415831e49f --- /dev/null +++ b/.changeset/vite-locale-alias-one-segment.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/build': patch +--- + +[fix] `astryxStylex()`'s alias for `@astryxdesign/core/locales/.generated.js` takes one path segment, so the per-namespace English slices under `locales/en/` — which the package's exports map keeps out of reach — no longer resolve through the source tree in a Vite app either. + +@vjeux diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 70749bdd90594..13ed565e0927d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -291,24 +291,39 @@ export * from './MyComponent'; ### User-facing strings and text direction -Components read user-facing strings with `useTranslator()` rather than -hardcoding them: +Components read user-facing strings with `useComponentTranslator()` +rather than hardcoding them. The slice is the component's own namespace of the +English catalog, generated under `src/i18n/generated-locales/en/`, so an app +that neither mounts `InternationalizationProvider`, calls `useTranslator()` nor +imports `InternationalizationContext` (each carries the whole catalog) bundles +only the strings of the components it renders: ```tsx -import {useTranslator} from '@astryxdesign/core/i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import saveButtonMessages from '../i18n/generated-locales/en/saveButton.generated'; function SaveButton() { - const t = useTranslator(); - return ; + const t = useComponentTranslator(saveButtonMessages); + return ; } ``` -Astryx's own strings live in `packages/core/locales/en.json`. The -`@astryx/no-hardcoded-i18n-string` ESLint rule rejects a hardcoded one. For a -prop whose default is a translated string, alias the prop and resolve it in the -body: destructure `label: labelFromProps`, then +A file that reads several namespaces merges their slices once at module level +(`const messages = {...aMessages, ...bMessages}`) and passes that. Astryx's own +strings live in `packages/core/locales/en.json`, keyed +`@astryx..`; `pnpm generate:i18n-runtime` emits the slices, and +`pnpm check:i18n-catalog` gains a slice-coverage rule with the component +sweep, failing a key read outside the file's slice. The +`@astryx/no-hardcoded-i18n-string` ESLint rule rejects a hardcoded string. For +a prop whose default is a translated string, alias the prop and resolve it in +the body: destructure `label: labelFromProps`, then `const label = labelFromProps ?? t('@astryx..')`. +`useTranslator()` from `@astryxdesign/core/i18n` is the consumer-facing hook: +it carries the whole English catalog, so a component inside `packages/core` +renders with its slice instead; packages that depend on core (`lab`, +`richtext`) use `useTranslator()`. + A component that responds to text direction resolves it from the DOM, not from a render-time JavaScript read. Reach for the lightest tool that works, in this order: @@ -346,8 +361,8 @@ order: flip for free; don't pass them a direction flag. 4. **`useDirection()` context, as a last resort.** Use it only when you need the direction value during render and nothing above fits. It is SSR-safe - and returns `'ltr'` outside a provider (like `useTranslator`'s silent - fallback), but it is the one path that can mismatch on hydration when the + and returns `'ltr'` outside a provider (like a translator's silent + English fallback), but it is the one path that can mismatch on hydration when the provider's direction disagrees with ``. No Astryx component reads direction from context at render time. diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js index 3df9f81b8b208..a9a3efc8a45d2 100644 --- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js +++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js @@ -247,21 +247,21 @@ const rule = { type: 'problem', docs: { description: - 'Disallow hardcoded user-facing strings; route through useTranslator() instead', + 'Disallow hardcoded user-facing strings; route through a translator (useComponentTranslator() in core, useTranslator() elsewhere) instead', category: 'Best Practices', recommended: true, }, messages: { hardcodedString: 'Hardcoded user-facing string {{value}} in `{{name}}`. ' + - 'Route through `t(\'..\')` via `useTranslator()` so it can be localized.', + 'Route through `t(\'..\')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) so it can be localized.', hardcodedDefault: 'Hardcoded default {{value}} for prop `{{name}}`. ' + 'Use the alias-and-resolve pattern: `{{name}}: {{name}}FromProps` in the destructure, then ' + '`const {{name}} = {{name}}FromProps ?? t(\'..\');` inside the body.', hardcodedCallArg: 'Hardcoded user-facing string {{value}} passed to `{{name}}()`. ' + - 'Route through `t(\'..\')` via `useTranslator()` so it can be localized.', + 'Route through `t(\'..\')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) so it can be localized.', }, schema: [ { diff --git a/packages/build/src/vite.test.ts b/packages/build/src/vite.test.ts index 8f618832c8a34..1fcdc5b52ca46 100644 --- a/packages/build/src/vite.test.ts +++ b/packages/build/src/vite.test.ts @@ -176,6 +176,27 @@ describe('astryxStylex locale aliases', () => { path.join(corePackage, 'src/Button'), ); }); + + it('does not route a per-namespace English slice to its source file', () => { + // `locales/en/.generated.js` is the package's own: the exports + // map gives it a `null` target, and the alias for whole catalogs takes a + // single path segment, so the slice specifier never reaches + // `src/i18n/generated-locales/en/`. + const rootDir = path.join(tmpdir(), 'astryx-vite-alias'); + const aliases = getInjectedConfig(rootDir).resolve.alias; + const corePackage = path.join(rootDir, 'node_modules/@astryxdesign/core'); + const resolved = applyAlias( + aliases, + '@astryxdesign/core/locales/en/button.generated.js', + ); + expect(resolved).not.toContain('generated-locales'); + expect(resolved).not.toBe( + path.join( + corePackage, + 'src/i18n/generated-locales/en/button.generated.ts', + ), + ); + }); }); describe('astryxStylex optimizeDeps package discovery', () => { diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.ts index 0581b58675edb..07f4a3d6c0b86 100644 --- a/packages/build/src/vite.ts +++ b/packages/build/src/vite.ts @@ -225,7 +225,12 @@ export function astryxStylex( resolve: { alias: [ { - find: /^@astryxdesign\/core\/locales\/(.+)\.generated\.js$/, + // A whole catalog, `locales/.generated.js`. The capture + // takes one path segment only: the per-namespace English slices + // under `locales/en/.generated.js` are the package's + // own (the exports map gives them a `null` target), and this + // alias must not reach them either. + find: /^@astryxdesign\/core\/locales\/([^/]+)\.generated\.js$/, replacement: path.join( coreSourceDir, 'i18n/generated-locales/$1.generated.ts', diff --git a/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs b/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs index 7b55923254e5b..711d0a0950c8c 100644 --- a/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs +++ b/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs @@ -122,7 +122,7 @@ import pseudo from '@astryxdesign/core/locales/pseudo.generated.js'; }, { type: 'prose', - text: 'Astryx component authors read strings with `useTranslator()` rather than hardcoding user-facing text.', + text: "Astryx components read their strings from the English catalog rather than hardcoding them. Your own code reads any `@astryx.*` key with `useTranslator()`:", }, { type: 'code', @@ -137,7 +137,7 @@ function SaveButton() { }, { type: 'prose', - text: "Astryx's own strings live in `packages/core/locales/en.json`. New user-facing strings must go through `useTranslator`; this is enforced by the `@astryx/no-hardcoded-i18n-string` ESLint rule. See the AI contribution guide for the alias-and-resolve pattern used when adding new keys.", + text: "Astryx's own strings live in `packages/core/locales/en.json`, keyed `@astryx..`. The contributing guide covers how a core component reads its strings, the `@astryx/no-hardcoded-i18n-string` ESLint rule and the alias-and-resolve pattern used when adding new keys.", }, { type: 'prose', diff --git a/packages/core/package.json b/packages/core/package.json index 8f02333465c35..76e4d83136b43 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -169,6 +169,7 @@ "types": "./dist/i18n/generated-locales/*.generated.d.ts", "default": "./dist/i18n/generated-locales/*.generated.js" }, + "./locales/en/*": null, "./AlertDialog": { "source": "./src/AlertDialog/index.ts", "types": "./dist/AlertDialog/index.d.ts", diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.ts index 80ebf11dc5ebe..43de892de8bd1 100644 --- a/packages/core/src/i18n/InternationalizationContext.ts +++ b/packages/core/src/i18n/InternationalizationContext.ts @@ -4,9 +4,17 @@ /** * @file InternationalizationContext.ts - * @input React createContext, i18n types + * @input React createContext, i18n types, the whole shipped English catalog * @output Exports InternationalizationContext and InternationalizationContextValue - * @position Context definition for client-side locale + messages + * @position Context definition for client-side locale + messages: the public + * context a consumer reads. Its `translate` resolves every `@astryx.*` key, + * falling back to the shipped English catalog, so this module carries that + * catalog; the locale hooks inside this package read + * TranslationRuntimeContext instead, and a component moves to it (carrying + * only its own slice) as it adopts useComponentTranslator. Both contexts + * are written by InternationalizationProvider, which is how an app + * configures Astryx: a value rendered straight into this context reaches + * consumers of this context and nothing that reads the runtime context. * * Separated from InternationalizationProvider.tsx so components can consume * the context without pulling in the full provider implementation. @@ -14,35 +22,44 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/i18n/InternationalizationProvider.tsx - * - /packages/core/src/i18n/t.client.ts - * - /packages/core/src/i18n/useDirection.ts - * - /packages/core/src/i18n/useLocale.ts - * - /packages/core/src/i18n/useCollator.ts - * - /packages/core/src/i18n/getLocaleDirection.ts - * - /packages/core/src/i18n/index.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts + * - /packages/core/src/i18n/useTranslator.ts */ import {createContext} from 'react'; -import {getResolve} from './resolve'; +import enCatalog from './generated-locales/en.generated'; import type {Locale, MessagesByLocale, Overrides} from './types'; +import type {MessageResolver} from './TranslationRuntimeContext'; +import {getResolve} from './resolve'; + +/** A translator over the whole shipped catalog: `translate(key, values?)`. */ +export type Translate = ( + key: string, + values?: Record, +) => string; export interface InternationalizationContextValue { locale: Locale; direction: 'ltr' | 'rtl'; messages: MessagesByLocale; overrides?: Overrides; - translate: ReturnType; + /** + * Resolves a key against the provider's catalogs and overrides, then the + * whole shipped English catalog. + */ + translate: Translate; +} + +/** Bind the whole English catalog as a resolver's fallback. */ +export function translateWithCatalog(resolve: MessageResolver): Translate { + return (key, values) => resolve(key, values, enCatalog); } -/** - * Default value falls through to the shipped en catalog in resolve(). - * A consumer that doesn't render a provider still gets English defaults. - */ export const InternationalizationContext = createContext({ locale: 'en', direction: 'ltr', messages: {}, - translate: getResolve('en', {}), + translate: translateWithCatalog(getResolve('en', {})), }); InternationalizationContext.displayName = 'InternationalizationContext'; diff --git a/packages/core/src/i18n/InternationalizationProvider.tsx b/packages/core/src/i18n/InternationalizationProvider.tsx index 84f2f91fc9f91..9fb78ed4a32fa 100644 --- a/packages/core/src/i18n/InternationalizationProvider.tsx +++ b/packages/core/src/i18n/InternationalizationProvider.tsx @@ -4,7 +4,7 @@ /** * @file InternationalizationProvider.tsx - * @input React, InternationalizationContext, i18n types + * @input React, InternationalizationContext, TranslationRuntimeContext, i18n types * @output Exports InternationalizationProvider component and props type * @position Provider component for astryx i18n locale + messages * @@ -20,7 +20,11 @@ */ import {useMemo, type ReactNode} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import { + InternationalizationContext, + translateWithCatalog, +} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; import {getLocaleDirection} from './getLocaleDirection'; import type { Locale, @@ -115,20 +119,34 @@ export function InternationalizationProvider({ children, }: InternationalizationProviderProps) { const direction = dir ?? getLocaleDirection(locale); - const value = useMemo(() => { + // One resolver, two readers: the components inside this package pass their + // own English slice to it; the public context binds the whole catalog. + const runtime = useMemo(() => { const providedMessages = messages ?? {}; return { locale, direction, messages: normalizeMessages(providedMessages), overrides, - translate: getResolve(locale, providedMessages, overrides), + resolve: getResolve(locale, providedMessages, overrides), }; }, [locale, direction, messages, overrides]); + const value = useMemo( + () => ({ + locale: runtime.locale, + direction: runtime.direction, + messages: runtime.messages, + overrides: runtime.overrides, + translate: translateWithCatalog(runtime.resolve), + }), + [runtime], + ); return ( - - {children} - + + + {children} + + ); } diff --git a/packages/core/src/i18n/TranslationRuntimeContext.ts b/packages/core/src/i18n/TranslationRuntimeContext.ts new file mode 100644 index 0000000000000..615b8721dee3c --- /dev/null +++ b/packages/core/src/i18n/TranslationRuntimeContext.ts @@ -0,0 +1,46 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file TranslationRuntimeContext.ts + * @input React createContext; getResolve + * @output Exports TranslationRuntimeContext — the locale, direction, catalogs + * and the message resolver that the components inside this package read — + * and its value type + * @position Internal to the i18n runtime. The public InternationalizationContext + * is this value plus a `translate` bound to the whole English catalog; the + * provider writes both. This module imports no catalog, so a component that + * reads it (useComponentTranslator, useLocale, useDirection, useCollator) + * bundles none; the whole catalog rides only with the public context, the + * provider and useTranslator. + * + * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/InternationalizationProvider.tsx + * - /packages/core/src/i18n/useComponentTranslator.ts + */ + +import {createContext} from 'react'; +import {getResolve} from './resolve'; +import type {Locale, MessagesByLocale, Overrides} from './types'; + +/** Resolves a key against the provider's catalogs, then the caller's English. */ +export type MessageResolver = ReturnType; + +export interface TranslationRuntimeContextValue { + locale: Locale; + direction: 'ltr' | 'rtl'; + messages: MessagesByLocale; + overrides?: Overrides; + resolve: MessageResolver; +} + +export const TranslationRuntimeContext = + createContext({ + locale: 'en', + direction: 'ltr', + messages: {}, + resolve: getResolve('en', {}), + }); +TranslationRuntimeContext.displayName = 'TranslationRuntimeContext'; diff --git a/packages/core/src/i18n/__tests__/i18n.source-build.test.mjs b/packages/core/src/i18n/__tests__/i18n.source-build.test.mjs new file mode 100644 index 0000000000000..bdef983f62212 --- /dev/null +++ b/packages/core/src/i18n/__tests__/i18n.source-build.test.mjs @@ -0,0 +1,71 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file i18n.source-build.test.mjs + * @input Uses Babel, the core build config, and the i18n runtime and a + * component source + * @output Verifies the shipped i18n runtime the components read imports no + * English catalog: the whole catalog rides only with the public context, + * the provider and useTranslator, and a component carries its own slice + * @position Regression test for the import graph of the shipped i18n modules + */ + +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {parseAsync, transformAsync} from '@babel/core'; +import {describe, expect, it} from 'vitest'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const CORE_ROOT = path.resolve(__dirname, '../../..'); +const SRC_ROOT = path.join(CORE_ROOT, 'src'); + +/** The relative specifiers a compiled module imports statically. */ +async function compiledStaticImportsOf(relativeFile) { + const file = path.join(SRC_ROOT, relativeFile); + const source = await fs.readFile(file, 'utf8'); + const result = await transformAsync(source, { + babelrc: false, + configFile: path.join(CORE_ROOT, 'babel.config.json'), + filename: file, + }); + const ast = await parseAsync(result.code, { + babelrc: false, + configFile: false, + filename: `${file}.js`, + sourceType: 'module', + }); + return ast.program.body + .filter(node => node.type === 'ImportDeclaration') + .map(node => node.source.value); +} + +const WHOLE_CATALOG = /generated-locales\/en\.generated\.js$/; + +describe('the shipped i18n runtime and the English catalog', () => { + it('the runtime a component reads imports no catalog', async () => { + for (const file of [ + 'i18n/resolve.ts', + 'i18n/TranslationRuntimeContext.ts', + 'i18n/useComponentTranslator.ts', + 'i18n/useLocale.ts', + 'i18n/useDirection.ts', + 'i18n/useCollator.ts', + ]) { + const imports = await compiledStaticImportsOf(file); + expect(imports, file).not.toContainEqual( + expect.stringMatching(/generated-locales/), + ); + expect(imports, file).not.toContain('./InternationalizationContext.js'); + } + }); + + it('the public context carries the whole catalog, and useTranslator reads it', async () => { + expect( + await compiledStaticImportsOf('i18n/InternationalizationContext.ts'), + ).toContainEqual(expect.stringMatching(WHOLE_CATALOG)); + expect(await compiledStaticImportsOf('i18n/useTranslator.ts')).toContain( + './InternationalizationContext.js', + ); + }); +}); diff --git a/packages/core/src/i18n/__tests__/locale-exports.test.mjs b/packages/core/src/i18n/__tests__/locale-exports.test.mjs new file mode 100644 index 0000000000000..430b23e2871e7 --- /dev/null +++ b/packages/core/src/i18n/__tests__/locale-exports.test.mjs @@ -0,0 +1,78 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file locale-exports.test.mjs + * @input The package's exports map, read through Node's own package + * resolution: the package's self-reference, which applies the same map a + * consumer's import does + * @output Verifies the public locale surface: every whole catalog under + * `@astryxdesign/core/locales/.generated.js` resolves, and the + * per-namespace English slices under `locales/en/` do not — they are the + * package's own, rendered through the internal useComponentTranslator + * @position Regression test for the `./locales/en/*` null export + */ + +import {spawnSync} from 'node:child_process'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {describe, expect, it} from 'vitest'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const CORE_ROOT = path.resolve(__dirname, '../../..'); + +/** + * Resolve a specifier the way a consumer's bundler or Node would: through + * the package's exports map. The package's own directory resolves its name + * through that same map (a self-reference), so no other package is involved: + * the docsite's server routes trace this package's files, and a path from + * here into another directory would make them ship that whole directory. + * `import.meta.resolve` consults the map only and + * never reads the target, so a built `dist/` is not needed: a matching + * pattern yields its target path, and a `null` target or no match is + * ERR_PACKAGE_PATH_NOT_EXPORTED. Run in a fresh process so the test's own + * module loader plays no part. + */ +function resolveFromConsumer(specifier) { + const script = ` + try { + console.log(JSON.stringify({ok: import.meta.resolve(${JSON.stringify(specifier)})})); + } catch (error) { + console.log(JSON.stringify({code: error.code})); + } + `; + const result = spawnSync( + process.execPath, + ['--input-type=module', '--eval', script], + { + cwd: CORE_ROOT, + encoding: 'utf8', + }, + ); + if (result.status !== 0) { + throw new Error( + `node exited ${result.status} (${result.signal ?? 'no signal'}): ${result.stderr}`, + ); + } + return JSON.parse(result.stdout.trim()); +} + +describe('the public locale surface of @astryxdesign/core', () => { + it('resolves a whole catalog by locale', () => { + expect( + resolveFromConsumer('@astryxdesign/core/locales/en.generated.js').ok, + ).toMatch(/\/dist\/i18n\/generated-locales\/en\.generated\.js$/); + expect( + resolveFromConsumer('@astryxdesign/core/locales/fr-FR.generated.js').ok, + ).toMatch(/\/dist\/i18n\/generated-locales\/fr-FR\.generated\.js$/); + }); + + it('does not resolve a per-namespace English slice', () => { + for (const namespace of ['button', 'pagination']) { + expect( + resolveFromConsumer( + `@astryxdesign/core/locales/en/${namespace}.generated.js`, + ), + ).toEqual({code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'}); + } + }); +}); diff --git a/packages/core/src/i18n/__tests__/resolve.test.ts b/packages/core/src/i18n/__tests__/resolve.test.ts index 88b0e7efb9682..8433db2bd2e9b 100644 --- a/packages/core/src/i18n/__tests__/resolve.test.ts +++ b/packages/core/src/i18n/__tests__/resolve.test.ts @@ -10,19 +10,27 @@ import {describe, expect, test, beforeEach, vi} from 'vitest'; import {__resetForTests, getResolve, resolveLocaleChain} from '../resolve'; +import enCatalog from '../generated-locales/en.generated'; +import paginationMessages from '../generated-locales/en/pagination.generated'; import type { Catalog, MessagesByLocale, Overrides, ProviderMessagesByLocale, + RuntimeCatalog, } from '../types'; +// The English fallback is the caller's (a component's slice, or the whole +// catalog through useTranslator); these cases resolve against the whole +// catalog, as useTranslator does, unless a case passes its own. const resolve = ( - ...[key, values, locale, messages, overrides]: [ - ...Parameters>, - ...Parameters, - ] -) => getResolve(locale, messages, overrides)(key, values); + key: string, + values: Record | undefined, + locale: Parameters[0], + messages: Parameters[1], + overrides: Parameters[2], + fallback: RuntimeCatalog | undefined = enCatalog, +) => getResolve(locale, messages, overrides)(key, values, fallback); // Reset caches between tests so warn-once and formatter cache don't bleed. beforeEach(() => { @@ -61,9 +69,7 @@ describe('resolveLocaleChain', () => { }); describe('resolve — basic lookup', () => { - test('falls back to shipped en catalog when locale is en and no messages passed', () => { - // The compact shipped English catalog is loaded at module initialization; - // Pagination keys should resolve. This asserts the module wiring end-to-end. + test('falls back to the shipped en catalog when locale is en and no messages passed', () => { const out = resolve( '@astryx.pagination.next', undefined, @@ -74,6 +80,43 @@ describe('resolve — basic lookup', () => { expect(out).toBe('Go to next page'); }); + test("resolves from a component's own namespace slice, and no further", () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect( + resolve( + '@astryx.pagination.next', + undefined, + 'en', + {}, + undefined, + paginationMessages, + ), + ).toBe('Go to next page'); + // A key of another namespace is not in the slice: the key comes back and + // the one-time warning fires, which is what check:i18n-catalog's + // slice-coverage rule (landing with the component sweep) prevents. + expect( + resolve( + '@astryx.button.loading', + undefined, + 'en', + {}, + undefined, + paginationMessages, + ), + ).toBe('@astryx.button.loading'); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('missing key')); + warn.mockRestore(); + }); + + test('carries no English catalog of its own: with no fallback the key comes back', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect(getResolve('en', {})('@astryx.pagination.next', undefined)).toBe( + '@astryx.pagination.next', + ); + warn.mockRestore(); + }); + test('returns the key itself and warns for unknown key', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); const out = resolve( diff --git a/packages/core/src/i18n/resolve.ts b/packages/core/src/i18n/resolve.ts index 120551ef7d198..568f9496628d7 100644 --- a/packages/core/src/i18n/resolve.ts +++ b/packages/core/src/i18n/resolve.ts @@ -11,17 +11,25 @@ * 2. Per-locale override for a parent locale (pt-BR → pt) * 3. Shipped catalog entry for the exact locale * 4. Shipped catalog entry for a parent locale (pt-BR → pt) - * 5. Shipped en catalog (the source of truth, always present) + * 5. The caller's English fallback (the source of truth): a component's own + * namespace slice through useComponentTranslator, or the whole shipped en + * catalog through useTranslator. This module imports no catalog itself, + * so a bundle carries only the slices of the components it renders. * 6. The key itself (dev-visible fallback, warns once) * * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/i18n/useComponentTranslator.ts * - /packages/core/src/i18n/useTranslator.ts * - /packages/core/src/i18n/__tests__/resolve.test.ts */ import IntlMessageFormat from 'intl-messageformat'; -import type {Locale, Overrides, ProviderMessagesByLocale} from './types'; -import enCatalog from './generated-locales/en.generated'; +import type { + Locale, + Overrides, + ProviderMessagesByLocale, + RuntimeCatalog, +} from './types'; import {warnOnce, __resetDevWarnings} from '../utils/devWarning'; /** @@ -112,11 +120,18 @@ export function getResolve( ) { const lookup = getLookup(locale, messages, overrides); - return (key: string, values: Record | undefined) => { - const result = lookup[key] ?? enCatalog[key]; + return ( + key: string, + values: Record | undefined, + fallback?: RuntimeCatalog, + ) => { + const result = lookup[key] ?? fallback?.[key]; if (result === undefined) { // Fires ONLY when a key is missing from every source including the - // shipped `en` catalog — a real bug (typo, stale catalog, deleted key). + // caller's English fallback — a real bug (typo, stale catalog, deleted + // key, or a component reading a key outside its own namespace slice; + // `check:i18n-catalog`'s slice-coverage rule, which lands with the + // component sweep, catches the last one before it ships). // Fallback to `en` from a non-en locale is expected and stays silent, // matching the FormatJS / i18next default. warnOnce( diff --git a/packages/core/src/i18n/useCollator.ts b/packages/core/src/i18n/useCollator.ts index 57cfbbe5de6c1..149c777a06728 100644 --- a/packages/core/src/i18n/useCollator.ts +++ b/packages/core/src/i18n/useCollator.ts @@ -4,7 +4,7 @@ /** * @file useCollator.ts - * @input InternationalizationContext (via use()), optional Intl.CollatorOptions + * @input TranslationRuntimeContext (via use()), optional Intl.CollatorOptions * @output A memoized Intl.Collator bound to the active locale * @position Public provider-aware string-comparison hook. Exported from the * i18n barrel for components, sibling packages, and consumers that need @@ -15,7 +15,7 @@ * useTranslator/useDirection/useLocale fallback. * * SYNC: When modified, update: - * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts * - /packages/core/src/i18n/useLocale.ts * - /packages/core/src/i18n/useCollator.doc.mjs * - /packages/core/src/i18n/index.ts @@ -23,7 +23,7 @@ */ import {use, useMemo} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; /** * Returns an `Intl.Collator` for the active provider locale, memoized across @@ -36,7 +36,7 @@ import {InternationalizationContext} from './InternationalizationContext'; * ``` */ export function useCollator(options?: Intl.CollatorOptions): Intl.Collator { - const ctx = use(InternationalizationContext); + const ctx = use(TranslationRuntimeContext); return useMemo( () => new Intl.Collator(ctx.locale, options), [ctx.locale, options], diff --git a/packages/core/src/i18n/useComponentTranslator.test.tsx b/packages/core/src/i18n/useComponentTranslator.test.tsx new file mode 100644 index 0000000000000..2ab8b2db4cdd1 --- /dev/null +++ b/packages/core/src/i18n/useComponentTranslator.test.tsx @@ -0,0 +1,147 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useComponentTranslator.test.tsx + * @input Uses vitest, @testing-library/react, useComponentTranslator, the + * i18n provider and two English namespace slices + * @output Verifies a component's translator resolves its own slice, the + * provider's catalog and overrides ahead of it, nothing outside it, and + * stays stable across renders + * @position Testing; validates useComponentTranslator.ts. Resolution order + * itself is covered by resolve.test.ts. + */ + +import {use} from 'react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {renderHook} from '@testing-library/react'; +import {useComponentTranslator} from './useComponentTranslator'; +import {useTranslator} from './useTranslator'; +import {InternationalizationContext} from './InternationalizationContext'; +import {InternationalizationProvider} from './InternationalizationProvider'; +import {__resetForTests} from './resolve'; +import enCatalog from './generated-locales/en.generated'; +import buttonMessages from './generated-locales/en/button.generated'; +import paginationMessages from './generated-locales/en/pagination.generated'; +import enSource from '../../locales/en.json'; +import type {MessagesByLocale, Overrides} from './types'; + +const FR_MESSAGES: MessagesByLocale = { + fr: {'@astryx.button.loading': {defaultMessage: 'Chargement'}}, +}; +const FR_OVERRIDES: Overrides = { + fr: {'@astryx.button.loading': 'Patientez'}, +}; + +beforeEach(() => { + __resetForTests(); +}); + +describe('useComponentTranslator', () => { + it("resolves the component's own keys from its slice with no provider", () => { + const {result} = renderHook(() => useComponentTranslator(buttonMessages)); + expect(result.current('@astryx.button.loading')).toBe('Loading'); + }); + + it('formats ICU values from the slice', () => { + const {result} = renderHook(() => + useComponentTranslator(paginationMessages), + ); + expect( + result.current('@astryx.pagination.pageAnnounce', {current: 3}), + ).toContain('3'); + }); + + it("returns a key outside the slice as the key, and warns once: the slice is the component's whole English", () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const {result} = renderHook(() => useComponentTranslator(buttonMessages)); + expect(result.current('@astryx.pagination.next')).toBe( + '@astryx.pagination.next', + ); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('missing key')); + warn.mockRestore(); + }); + + it("lets the provider's catalog beat the slice", () => { + const {result} = renderHook(() => useComponentTranslator(buttonMessages), { + wrapper: ({children}) => ( + + {children} + + ), + }); + expect(result.current('@astryx.button.loading')).toBe('Chargement'); + }); + + it("lets a provider override beat the provider's catalog and the slice", () => { + const {result} = renderHook(() => useComponentTranslator(buttonMessages), { + wrapper: ({children}) => ( + + {children} + + ), + }); + expect(result.current('@astryx.button.loading')).toBe('Patientez'); + }); + + it('hands back the same function across renders while the slice and provider hold', () => { + const {result, rerender} = renderHook(() => + useComponentTranslator(buttonMessages), + ); + const first = result.current; + rerender(); + expect(result.current).toBe(first); + }); + + it('useTranslator with no argument still resolves every shipped key', () => { + const {result} = renderHook(() => useTranslator()); + expect(result.current('@astryx.button.loading')).toBe('Loading'); + expect(result.current('@astryx.pagination.next')).toBe('Go to next page'); + }); +}); + +describe('the whole English catalog', () => { + it('carries every authored key and message, and agrees with the slices', () => { + const authored = Object.keys(enSource).sort(); + expect(Object.keys(enCatalog).sort()).toEqual(authored); + for (const key of authored) { + expect(enCatalog[key]).toBe( + (enSource as Record)[key] + .defaultMessage, + ); + } + expect(enCatalog['@astryx.button.loading']).toBe( + buttonMessages['@astryx.button.loading'], + ); + }); +}); + +describe('the public InternationalizationContext boundary', () => { + it('its translate falls back to the whole shipped English catalog with no provider, as it always has', () => { + const {result} = renderHook(() => use(InternationalizationContext)); + expect(result.current.locale).toBe('en'); + expect(result.current.translate('@astryx.pagination.next', undefined)).toBe( + 'Go to next page', + ); + expect(result.current.translate('@astryx.button.loading')).toBe('Loading'); + }); + + it('its translate falls back to English under a provider whose catalog lacks the key', () => { + const {result} = renderHook(() => use(InternationalizationContext), { + wrapper: ({children}) => ( + + {children} + + ), + }); + expect(result.current.locale).toBe('fr'); + expect(result.current.translate('@astryx.button.loading')).toBe( + 'Chargement', + ); + expect(result.current.translate('@astryx.pagination.next')).toBe( + 'Go to next page', + ); + }); +}); diff --git a/packages/core/src/i18n/useComponentTranslator.ts b/packages/core/src/i18n/useComponentTranslator.ts new file mode 100644 index 0000000000000..475571f4f8ed3 --- /dev/null +++ b/packages/core/src/i18n/useComponentTranslator.ts @@ -0,0 +1,57 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useComponentTranslator.ts + * @input TranslationRuntimeContext (via use()); the component's own English + * namespace slice from ./generated-locales/en/.generated + * @output Exports useComponentTranslator — the translator a core component + * renders with — and the TranslatorFn type + * @position The i18n hook for components inside this package. A component + * passes the slice of the English catalog that holds its own keys, so a + * bundle carries the strings of the components it renders and nothing of + * the other hundred. Consumers use useTranslator, which carries the whole + * catalog; this hook imports none. + * + * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/i18n/useTranslator.ts + * - /packages/core/src/i18n/resolve.ts + * - /scripts/check-i18n-catalog.mjs (its slice-coverage rule lands with the + * component sweep) + */ + +import {use, useMemo} from 'react'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; +import type {RuntimeCatalog} from './types'; + +export type TranslatorFn = ( + key: string, + values?: Record, +) => string; + +/** + * Returns a translator bound to the current provider's locale whose English + * fallback is `messages`: the component's own namespace slice, or a + * module-level merge of the slices it reads. Stable while the provider and + * the slice are, so it is safe in memo dependencies, event handlers and + * effects. + * + * @example + * ``` + * import buttonMessages from '../i18n/generated-locales/en/button.generated'; + * + * function Button() { + * const t = useComponentTranslator(buttonMessages); + * return {t('@astryx.button.loading')}; + * } + * ``` + */ +export function useComponentTranslator(messages: RuntimeCatalog): TranslatorFn { + const {resolve: resolveMessage} = use(TranslationRuntimeContext); + return useMemo( + () => (key: string, values?: Record) => + resolveMessage(key, values, messages), + [messages, resolveMessage], + ); +} diff --git a/packages/core/src/i18n/useDirection.ts b/packages/core/src/i18n/useDirection.ts index a8184b98ed49b..bc4177740b341 100644 --- a/packages/core/src/i18n/useDirection.ts +++ b/packages/core/src/i18n/useDirection.ts @@ -4,7 +4,7 @@ /** * @file useDirection.ts - * @input InternationalizationContext (via use()) + * @input TranslationRuntimeContext (via use()) * @output 'ltr' | 'rtl' * @position Client hook for reading the ambient text direction. Returns 'ltr' * when called outside a provider (matches the silent-en-fallback pattern of @@ -18,15 +18,15 @@ * the provider's direction disagrees with the actual ``. * * SYNC: When modified, update these files to stay in sync: - * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts * - /packages/core/src/i18n/getLocaleDirection.ts (server-safe counterpart) * - /packages/core/src/i18n/index.ts */ import {use} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; export function useDirection(): 'ltr' | 'rtl' { - const ctx = use(InternationalizationContext); + const ctx = use(TranslationRuntimeContext); return ctx.direction; } diff --git a/packages/core/src/i18n/useLocale.ts b/packages/core/src/i18n/useLocale.ts index a5dda8a01c880..07f91a211262e 100644 --- a/packages/core/src/i18n/useLocale.ts +++ b/packages/core/src/i18n/useLocale.ts @@ -4,7 +4,7 @@ /** * @file useLocale.ts - * @input InternationalizationContext (via use()) + * @input TranslationRuntimeContext (via use()) * @output The active BCP 47 locale tag * @position Public provider-aware locale accessor. Exported from the i18n * barrel for components, sibling packages, and consumers that must thread @@ -18,17 +18,17 @@ * provider-backed contract. * * SYNC: When modified, update: - * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts * - /packages/core/src/i18n/useLocale.doc.mjs * - /packages/core/src/i18n/index.ts * - /packages/core/src/i18n/__tests__/useLocale.test.tsx */ import {use} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; import type {Locale} from './types'; export function useLocale(): Locale { - const ctx = use(InternationalizationContext); + const ctx = use(TranslationRuntimeContext); return ctx.locale; } diff --git a/packages/core/src/i18n/useTranslator.ts b/packages/core/src/i18n/useTranslator.ts index c7abd5dc450a6..e3948b7005596 100644 --- a/packages/core/src/i18n/useTranslator.ts +++ b/packages/core/src/i18n/useTranslator.ts @@ -8,7 +8,10 @@ * @output Exports useTranslator hook returning a stable translator function * @position Client-side hook for translating outside of render (event handlers, * effects, non-component code) while still resolving against the current - * provider's locale. + * provider's locale. The consumer-facing translator: it resolves every + * `@astryx.*` key, so it carries the whole English catalog. A component + * inside this package uses useComponentTranslator with its own slice + * instead, so an app bundles only the strings of the components it renders. * * Prefer `t()` for translations at the callsite during render. When you need * to translate inside an event handler or effect, capture a translator during @@ -16,20 +19,19 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/i18n/index.ts - * - /packages/core/src/i18n/t.client.ts + * - /packages/core/src/i18n/useComponentTranslator.ts */ import {use} from 'react'; import {InternationalizationContext} from './InternationalizationContext'; +import type {TranslatorFn} from './useComponentTranslator'; -export type TranslatorFn = ( - key: string, - values?: Record, -) => string; +export type {TranslatorFn}; /** * Returns a translator function bound to the current provider's locale. - * Safe to call from event handlers and effects. + * Safe to call from event handlers and effects. Its English fallback is the + * whole shipped catalog, so any `@astryx.*` key resolves. * * @example * ``` diff --git a/scripts/generate-i18n-runtime.mjs b/scripts/generate-i18n-runtime.mjs index 11727db9635f6..477e9577568eb 100644 --- a/scripts/generate-i18n-runtime.mjs +++ b/scripts/generate-i18n-runtime.mjs @@ -7,6 +7,11 @@ * packages/core/locales/*.json remain the canonical Crowdin sources and keep * translator descriptions. Each generated module exports only the * key-to-defaultMessage map used at runtime. + * + * The English catalog is emitted one namespace at a time, under + * `generated-locales/en/.generated.ts`: a component carries its own + * slice through `useComponentTranslator`, so an app bundles the strings of the + * components it renders rather than the whole library's. */ import {spawn} from 'node:child_process'; @@ -28,6 +33,13 @@ const GENERATED_LOCALES_DIR = path.join( ); const EN_FILE = 'en.json'; const PSEUDO_FILE = 'pseudo.json'; +/** + * Where the per-namespace English slices live, under GENERATED_LOCALES_DIR. + * The package's exports map gives `./locales/en/*` a `null` target, so the + * slices are the package's own and never a consumer import path. + */ +const EN_SLICES_DIR = 'en'; +const KEY_PREFIX = '@astryx.'; function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); @@ -69,6 +81,42 @@ export function createRuntimeCatalogs(sourceCatalogs) { return runtimeCatalogs; } +/** + * The namespace of a catalog key: `@astryx.button.loading` belongs to + * `button`. Every key names one, which is also the slice module's name. + */ +export function namespaceOf(key) { + const [namespace, ...rest] = key.slice(KEY_PREFIX.length).split('.'); + if (!key.startsWith(KEY_PREFIX) || !namespace || rest.length === 0) { + throw new Error( + `${key}: a catalog key is "${KEY_PREFIX}."`, + ); + } + return namespace; +} + +/** Split a runtime catalog into one map per namespace, keys in source order. */ +export function createNamespaceSlices(runtimeCatalog) { + const slices = {}; + for (const [key, message] of Object.entries(runtimeCatalog)) { + const namespace = namespaceOf(key); + (slices[namespace] ??= {})[key] = message; + } + return slices; +} + +export function getSliceModuleName(namespace) { + return `${namespace}.generated.ts`; +} + +function getSliceModulePath(namespace) { + return path.join( + GENERATED_LOCALES_DIR, + EN_SLICES_DIR, + getSliceModuleName(namespace), + ); +} + export function getGeneratedModuleName(sourceFile) { if (!sourceFile.endsWith('.json')) { throw new Error(`Expected a JSON locale filename: ${sourceFile}`); @@ -80,16 +128,31 @@ function getGeneratedModulePath(sourceFile) { return path.join(GENERATED_LOCALES_DIR, getGeneratedModuleName(sourceFile)); } -export async function renderRuntimeCatalogModule(runtimeCatalog, sourceFile) { +async function renderCatalogModule(runtimeCatalog, outputFile, description) { const {format, resolveConfig} = await import('prettier'); - const outputFile = getGeneratedModulePath(sourceFile); + const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-i18n-runtime.mjs from ${description}.\n * Translator descriptions remain in the authored JSON catalogs and must not be copied here.\n * Do not edit by hand. Run \`pnpm generate:i18n-runtime\` instead.\n */\n\nconst runtimeCatalog: Readonly> = ${JSON.stringify(runtimeCatalog)};\n\nexport default runtimeCatalog;\n`; + const prettierConfig = await resolveConfig(outputFile); + return format(source, {...prettierConfig, filepath: outputFile}); +} + +export async function renderRuntimeCatalogModule(runtimeCatalog, sourceFile) { const sourceDescription = sourceFile === PSEUDO_FILE ? 'the pseudo-localization projection of packages/core/locales/en.json' : `packages/core/locales/${sourceFile}`; - const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-i18n-runtime.mjs from ${sourceDescription}.\n * Translator descriptions remain in the authored JSON catalogs and must not be copied here.\n * Do not edit by hand. Run \`pnpm generate:i18n-runtime\` instead.\n */\n\nconst runtimeCatalog: Readonly> = ${JSON.stringify(runtimeCatalog)};\n\nexport default runtimeCatalog;\n`; - const prettierConfig = await resolveConfig(outputFile); - return format(source, {...prettierConfig, filepath: outputFile}); + return renderCatalogModule( + runtimeCatalog, + getGeneratedModulePath(sourceFile), + sourceDescription, + ); +} + +export async function renderNamespaceSliceModule(slice, namespace) { + return renderCatalogModule( + slice, + getSliceModulePath(namespace), + `the \`${namespace}\` keys of packages/core/locales/${EN_FILE}`, + ); } function readSourceCatalogs() { @@ -118,18 +181,16 @@ function writeIfChanged(file, content) { return true; } -function removeStaleModules(expectedFiles) { - if (!fs.existsSync(GENERATED_LOCALES_DIR)) return 0; +function removeStaleModules(directory, expectedFiles) { + if (!fs.existsSync(directory)) return 0; let removed = 0; - for (const entry of fs.readdirSync(GENERATED_LOCALES_DIR, { - withFileTypes: true, - })) { + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { if ( entry.isFile() && entry.name.endsWith('.generated.ts') && !expectedFiles.has(entry.name) ) { - fs.rmSync(path.join(GENERATED_LOCALES_DIR, entry.name)); + fs.rmSync(path.join(directory, entry.name)); removed += 1; } } @@ -152,19 +213,31 @@ export async function generateRuntimeCatalogs({check = false} = {}) { return; } - fs.mkdirSync(GENERATED_LOCALES_DIR, {recursive: true}); + const slicesDir = path.join(GENERATED_LOCALES_DIR, EN_SLICES_DIR); + fs.mkdirSync(slicesDir, {recursive: true}); const expectedFiles = new Set( Object.keys(runtimeCatalogs).map(getGeneratedModuleName), ); - const removed = removeStaleModules(expectedFiles); + const slices = createNamespaceSlices(runtimeCatalogs[EN_FILE]); + const expectedSliceFiles = new Set( + Object.keys(slices).map(getSliceModuleName), + ); + const removed = + removeStaleModules(GENERATED_LOCALES_DIR, expectedFiles) + + removeStaleModules(slicesDir, expectedSliceFiles); let changed = 0; for (const [file, catalog] of Object.entries(runtimeCatalogs)) { const output = await renderRuntimeCatalogModule(catalog, file); if (writeIfChanged(getGeneratedModulePath(file), output)) changed += 1; } + for (const [namespace, slice] of Object.entries(slices)) { + const output = await renderNamespaceSliceModule(slice, namespace); + if (writeIfChanged(getSliceModulePath(namespace), output)) changed += 1; + } console.log( `Generated ${Object.keys(runtimeCatalogs).length} runtime locale modules ` + + `and ${Object.keys(slices).length} English namespace slices ` + `(${changed} changed, ${removed} stale removed)`, ); } diff --git a/scripts/generate-i18n-runtime.test.mjs b/scripts/generate-i18n-runtime.test.mjs index 97756420f922d..e6b576e6d66e2 100644 --- a/scripts/generate-i18n-runtime.test.mjs +++ b/scripts/generate-i18n-runtime.test.mjs @@ -8,11 +8,15 @@ import path from 'node:path'; import {fileURLToPath} from 'node:url'; import {describe, expect, it} from 'vitest'; import { + createNamespaceSlices, createRuntimeCatalog, createRuntimeCatalogs, createSpawnInvocation, getGeneratedModuleName, + getSliceModuleName, isSourceLocaleFile, + namespaceOf, + renderNamespaceSliceModule, renderRuntimeCatalogModule, } from './generate-i18n-runtime.mjs'; @@ -122,6 +126,49 @@ describe('createRuntimeCatalogs', () => { }); }); +describe('English namespace slices', () => { + it('names the namespace of a key', () => { + expect(namespaceOf('@astryx.button.loading')).toBe('button'); + expect(namespaceOf('@astryx.dateTimeInput.time.hour')).toBe( + 'dateTimeInput', + ); + }); + + it('rejects a key that names no namespace', () => { + expect(() => namespaceOf('@astryx.loading')).toThrow('.'); + expect(() => namespaceOf('loading')).toThrow('.'); + }); + + it('splits a runtime catalog into one map per namespace, every key kept once', () => { + const slices = createNamespaceSlices({ + '@astryx.button.loading': 'Loading', + '@astryx.pagination.next': 'Go to next page', + '@astryx.pagination.previous': 'Go to previous page', + }); + expect(slices).toEqual({ + button: {'@astryx.button.loading': 'Loading'}, + pagination: { + '@astryx.pagination.next': 'Go to next page', + '@astryx.pagination.previous': 'Go to previous page', + }, + }); + expect(Object.values(slices).flatMap(Object.keys)).toHaveLength(3); + }); + + it('renders a slice as the same string-map module shape, named after the namespace', async () => { + expect(getSliceModuleName('button')).toBe('button.generated.ts'); + const output = await renderNamespaceSliceModule( + {'@astryx.button.loading': 'Loading'}, + 'button', + ); + expect(output).toContain('from the `button` keys of'); + expect(output).toContain( + "const runtimeCatalog: Readonly> = {\n '@astryx.button.loading': 'Loading',\n};", + ); + expect(output).toContain('export default runtimeCatalog;'); + }); +}); + describe('generated module names', () => { it('places generated modules beside the i18n runtime with an explicit suffix', () => { expect(getGeneratedModuleName('fr-FR.json')).toBe('fr-FR.generated.ts'); diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js index ddc98d5f035c4..90412cff6883e 100644 --- a/scripts/sync-exports.js +++ b/scripts/sync-exports.js @@ -188,6 +188,12 @@ const STATIC_EXPORTS = { types: './dist/i18n/generated-locales/*.generated.d.ts', default: './dist/i18n/generated-locales/*.generated.js', }, + // The per-namespace English slices under generated-locales/en/ are the + // package's own: a core component renders with its slice through the + // internal useComponentTranslator. The longer pattern wins the match, so + // this keeps them off the public surface while `./locales/en.generated.js` + // and the other whole catalogs stay importable. + './locales/en/*': null, }; /**