From c534930af939cbfe76a419a5254e03f7340a4928 Mon Sep 17 00:00:00 2001 From: Krish Goradia Date: Mon, 16 Nov 2026 03:26:48 +0530 Subject: [PATCH] fix(i18n): Select plural forms by key instead of position Plurals were serialized with `Object.values(...).join(' | ')`, but the runtime picks a form by position, so `{ 0, n }` returned the zero form for a count of 1, and `{ 1, 2, n }` was read as `{ 0, 1, n }`. Objects with only numeric keys, like `{ 404: ..., 500: ... }`, were also collapsed into one plural message instead of nested messages. - Serialize plurals as `one | n` or `zero | one | n`, falling back to `n` for a missing form. Output for `{ n }`, `{ 1, n }` and `{ 0, 1, n }` is unchanged. - Only treat objects with an `n` key as plurals. - Throw a clear error for plural keys other than 0, 1 and n. Refs #2747 Co-Authored-By: Claude Opus 5.5 --- packages/i18n/src/__tests__/build.test.ts | 37 +++++++++++ packages/i18n/src/__tests__/plural.test.ts | 74 ++++++++++++++++++++++ packages/i18n/src/build.ts | 43 ++++++++++++- 3 files changed, 151 insertions(+), 3 deletions(-) create mode 100644 packages/i18n/src/__tests__/plural.test.ts diff --git a/packages/i18n/src/__tests__/build.test.ts b/packages/i18n/src/__tests__/build.test.ts index 1a20b0402..04025e96e 100644 --- a/packages/i18n/src/__tests__/build.test.ts +++ b/packages/i18n/src/__tests__/build.test.ts @@ -11,8 +11,11 @@ import { describe, it, expect, vi } from 'vitest'; import { parseMessagesFile, + parseMessagesObject, + generateChromeMessages, generateChromeMessagesFile, generateTypeFile, + generateTypeText, } from '../build'; vi.mock('node:fs/promises'); @@ -198,4 +201,38 @@ describe('Built Tools', () => { 'Messages file should not contain `null` (found at "invalidField")', ); }); + + it('should keep each plural form on its own count when only 0 and n are defined', () => { + const messages = parseMessagesObject({ + items: { 0: 'No items', n: '$1 items' }, + }); + + expect(generateChromeMessages(messages).items).toEqual({ + message: 'No items | $1 items | $1 items', + }); + }); + + it('should treat numeric keys without an n form as nested messages', () => { + const messages = parseMessagesObject({ + errors: { 404: 'Not found', 500: 'Server error' }, + }); + + expect(generateChromeMessages(messages)).toMatchObject({ + errors_404: { message: 'Not found' }, + errors_500: { message: 'Server error' }, + }); + expect(generateTypeText(messages)).toContain( + '"errors.404": { substitutions: 0, plural: false };', + ); + }); + + it('should throw an error for unsupported plural keys', () => { + expect(() => + parseMessagesObject({ + items: { 1: 'One item', 2: 'Two items', n: '$1 items' }, + }), + ).toThrowError( + 'Plural message "items" has unsupported key(s) "2". Only 0, 1, and n are supported.', + ); + }); }); diff --git a/packages/i18n/src/__tests__/plural.test.ts b/packages/i18n/src/__tests__/plural.test.ts new file mode 100644 index 000000000..907fa803c --- /dev/null +++ b/packages/i18n/src/__tests__/plural.test.ts @@ -0,0 +1,74 @@ +import { browser } from '@wxt-dev/browser'; +import { describe, it, expect, vi } from 'vitest'; + +import { generateChromeMessages, parseMessagesObject } from '../build'; +import { createI18n } from '../index'; + +vi.mock('@wxt-dev/browser', async () => { + const { vi } = await import('vitest'); + return { + browser: { + i18n: { + getMessage: vi.fn(), + }, + }, + }; +}); +const getMessageMock = vi.mocked(browser.i18n.getMessage); + +/** Serve the generated messages.json like `browser.i18n.getMessage` does. */ +function useMessages(object: Parameters[0]) { + const messages = generateChromeMessages(parseMessagesObject(object)); + getMessageMock.mockImplementation((key, substitutions) => + (messages[key]?.message ?? '').replace(/\$(\d)/g, (_, index) => + String([substitutions ?? []].flat()[Number(index) - 1] ?? ''), + ), + ); +} + +describe('plural messages from build to runtime', () => { + it.each([ + [0, 'No items'], + [1, '1 items'], + [2, '2 items'], + ])( + 'should use the right form for %i when only 0 and n are defined', + (count, expected) => { + useMessages({ items: { 0: 'No items', n: '$1 items' } }); + + expect(createI18n().t('items', count)).toBe(expected); + }, + ); + + it.each([ + [0, '0 items'], + [1, 'One item'], + [2, '2 items'], + ])( + 'should keep the existing behavior of 1 and n for %i', + (count, expected) => { + useMessages({ items: { 1: 'One item', n: '$1 items' } }); + + expect(createI18n().t('items', count)).toBe(expected); + }, + ); + + it.each([ + [0, 'No items'], + [1, 'One item'], + [5, '5 items'], + ])( + 'should keep the existing behavior of 0, 1 and n for %i', + (count, expected) => { + useMessages({ items: { 0: 'No items', 1: 'One item', n: '$1 items' } }); + + expect(createI18n().t('items', count)).toBe(expected); + }, + ); + + it('should resolve numeric nested keys', () => { + useMessages({ errors: { 404: 'Not found', 500: 'Server error' } }); + + expect(createI18n().t('errors.404')).toBe('Not found'); + }); +}); diff --git a/packages/i18n/src/build.ts b/packages/i18n/src/build.ts index 16a22d2f0..5c041a4ef 100644 --- a/packages/i18n/src/build.ts +++ b/packages/i18n/src/build.ts @@ -198,6 +198,7 @@ function _parseMessagesObject( ); if (isPluralMessage(object)) { + assertSupportedPluralKeys(object, path); const message = Object.values(object).join('|'); const substitutions = getSubstitutionCount(message); const namedSubstitutions = getNamedSubstitutionNames(message); @@ -236,11 +237,47 @@ function _parseMessagesObject( } function isPluralMessage(object: Message): object is PluralMessage { - return Object.keys(object).every( - (key) => key === 'n' || isFinite(Number(key)), + // A plural message always has an `n` form. Objects with only numeric keys + // and no `n` (e.g. `{ 404: ..., 500: ... }`) are regular nested messages. + const keys = Object.keys(object); + return ( + keys.includes('n') && + keys.every((key) => key === 'n' || isFinite(Number(key))) ); } +const SUPPORTED_PLURAL_KEYS = new Set(['0', '1', 'n']); + +function assertSupportedPluralKeys( + object: PluralMessage, + path: string[], +): void { + const unsupported = Object.keys(object).filter( + (key) => !SUPPORTED_PLURAL_KEYS.has(key), + ); + if (unsupported.length > 0) { + throw Error( + `Plural message "${path.join('.')}" has unsupported key(s) ${unsupported + .map((key) => `"${key}"`) + .join(', ')}. Only 0, 1, and n are supported.`, + ); + } +} + +/** + * The runtime picks a plural form by position: "one | n" or "zero | one | n". + * Missing forms fall back to `n` so each count gets the right form regardless + * of which keys were defined. + */ +function serializePluralMessage( + plurals: ParsedPluralMessage['plurals'], +): string { + const { 0: zero, 1: one, n } = plurals; + if (zero != null) return [zero, one ?? n, n].join(' | '); + if (one != null) return [one, n].join(' | '); + return n; +} + function isChromeMessage(object: Message): object is ChromeMessage { return Object.keys(object).every((key) => ALLOWED_CHROME_MESSAGE_KEYS.has(key), @@ -302,7 +339,7 @@ export function generateChromeMessages( break; case 'plural': acc[key] = { - message: Object.values(message.plurals).join(' | '), + message: serializePluralMessage(message.plurals), }; break; case 'simple':