🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(i18n-extractor): support i18next translators (#21227)
Innei217dbcb9438d
diff --git a/apps/share/app/lib/seo.test.ts b/apps/share/app/lib/seo.test.tsnew file mode 100644index 00000000000..eb5892e243f--- /dev/null+++ b/apps/share/app/lib/seo.test.ts@@ -0,0 +1,23 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import { describe, expect, it } from 'vitest';++import { createShareT } from '../../src/shell/createShareI18n';+import { shareMetaDescription } from './seo';++describe('shareMetaDescription', () => {+ it('translates through the chat translator', () => {+ const t = createShareT('zh-CN', {+ chat: { 'sharePage.meta.pageDescription': '分享自 {{appName}} 的页面。' },+ });+ expect(shareMetaDescription(t, 'pageDescription')).toBe(`分享自 ${BRANDING_NAME} 的页面。`);+ });++ it('falls back to English copy without a translation', () => {+ expect(shareMetaDescription(createShareT('zh-CN', { chat: {} }), 'topicDescription')).toBe(+ `A conversation shared from ${BRANDING_NAME}.`,+ );+ expect(shareMetaDescription(undefined, 'artifactDescription')).toBe(+ `An artifact shared from ${BRANDING_NAME}.`,+ );+ });+});diff --git a/apps/share/app/lib/seo.ts b/apps/share/app/lib/seo.tsindex 90a3fed268b..ea413e8bbe6 100644--- a/apps/share/app/lib/seo.ts+++ b/apps/share/app/lib/seo.ts@@ -1,4 +1,5 @@import { BRANDING_NAME } from '@lobechat/business-const';+import type { TFunction } from 'i18next';import type { MetaDescriptor } from 'react-router';// Shared with landing-rr: share pages ship behind the lobehub.com gateway, so@@ -15,14 +16,13 @@ const FALLBACK_DESCRIPTION: Record<DescriptionKey, string> = {topicDescription: `A conversation shared from ${BRANDING_NAME}.`,};-export const shareMetaDescription = (resources: unknown, key: DescriptionKey): string => {- const chat = (resources as Record<string, Record<string, unknown>> | undefined)?.chat;- const text = chat?.[`sharePage.meta.${key}`];-- return typeof text === 'string'- ? text.replaceAll('{{appName}}', BRANDING_NAME)+export const shareMetaDescription = (+ t: TFunction<'chat'> | undefined,+ key: DescriptionKey,+): string =>+ t+ ? t(`sharePage.meta.${key}`, { appName: BRANDING_NAME, defaultValue: FALLBACK_DESCRIPTION[key] }): FALLBACK_DESCRIPTION[key];-};export const truncateDescription = (text: string | null | undefined, max = 200) => {if (!text) return undefined;diff --git a/apps/share/app/root.tsx b/apps/share/app/root.tsxindex a7e338d810b..3a7e66a1d63 100644--- a/apps/share/app/root.tsx+++ b/apps/share/app/root.tsx@@ -18,7 +18,7 @@ import { resolveRequestLocale } from '@/locales/requestLocale';import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';import ShareAppShell from '../src/shell';-import { loadShareResources } from '../src/shell/createShareI18n';+import { createShareT, loadShareResources } from '../src/shell/createShareI18n';import { buildPageMeta, shareMetaDescription } from './lib/seo';export const loader = async ({ request }: LoaderFunctionArgs) => {@@ -26,6 +26,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {const resources = await loadShareResources(locale);return {+ description: shareMetaDescription(createShareT(locale, resources), 'topicDescription'),dir: isRtlLang(locale) ? 'rtl' : 'ltr',locale,resources,@@ -34,7 +35,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {export const meta: MetaFunction<typeof loader> = ({ loaderData }) =>buildPageMeta({- description: shareMetaDescription(loaderData?.resources, 'topicDescription'),+ description: loaderData?.description ?? shareMetaDescription(undefined, 'topicDescription'),locale: loaderData?.locale,title: BRANDING_NAME,});diff --git a/apps/share/app/routes/shareArtifact.tsx b/apps/share/app/routes/shareArtifact.tsxindex 4878226cb55..0d2b3c9ba62 100644--- a/apps/share/app/routes/shareArtifact.tsx+++ b/apps/share/app/routes/shareArtifact.tsx@@ -7,7 +7,7 @@ import { shareKeys } from '@/libs/swr/keys';import { resolveRequestLocale } from '@/locales/requestLocale';import SharedArtifactView from '../../src/features/artifact/SharedArtifactView';-import { loadShareResources } from '../../src/shell/createShareI18n';+import { loadShareT } from '../../src/shell/createShareI18n';import { cloudflareContext } from '../lib/cloudflareContext';import { buildPageMeta, shareMetaDescription } from '../lib/seo';import { createServerLambdaClient } from '../lib/serverTrpc';@@ -26,7 +26,7 @@ export const loader = async ({ context, params, request }: LoaderFunctionArgs) =return {artifact,- description: shareMetaDescription(await loadShareResources(locale), 'artifactDescription'),+ description: shareMetaDescription(await loadShareT(locale), 'artifactDescription'),id,locale,};diff --git a/apps/share/app/routes/sharePage.tsx b/apps/share/app/routes/sharePage.tsxindex 29d106f1071..21c389f2155 100644--- a/apps/share/app/routes/sharePage.tsx+++ b/apps/share/app/routes/sharePage.tsx@@ -8,7 +8,7 @@ import { resolveRequestLocale } from '@/locales/requestLocale';import { getIdFromIdentifier } from '@/utils/identifier';import SharedPageView from '../../src/features/page/SharedPageView';-import { loadShareResources } from '../../src/shell/createShareI18n';+import { loadShareT } from '../../src/shell/createShareI18n';import { cloudflareContext } from '../lib/cloudflareContext';import { buildPageMeta, shareMetaDescription } from '../lib/seo';import { createServerLambdaClient } from '../lib/serverTrpc';@@ -26,7 +26,7 @@ export const loader = async ({ context, params, request }: LoaderFunctionArgs) =});return {- description: shareMetaDescription(await loadShareResources(locale), 'pageDescription'),+ description: shareMetaDescription(await loadShareT(locale), 'pageDescription'),documentId,locale,sharedDocument,diff --git a/apps/share/app/routes/shareTopic.tsx b/apps/share/app/routes/shareTopic.tsxindex 8c234b2fe15..7669b7e2f64 100644--- a/apps/share/app/routes/shareTopic.tsx+++ b/apps/share/app/routes/shareTopic.tsx@@ -12,7 +12,7 @@ import {} from '../../src/features/topic/sharedConversation';import SharedTopicView, { preloadSharedTopic } from '../../src/features/topic/SharedTopicView';import { buildTopicByline } from '../../src/features/topic/topicByline';-import { loadShareResources } from '../../src/shell/createShareI18n';+import { loadShareT } from '../../src/shell/createShareI18n';import { cloudflareContext } from '../lib/cloudflareContext';import { buildPageMeta, shareMetaDescription, truncateDescription } from '../lib/seo';import { createServerLambdaClient } from '../lib/serverTrpc';@@ -38,7 +38,7 @@ export const loader = async ({ context, params, request }: LoaderFunctionArgs) =firstPage,messageReadMode,byline: topic ? buildTopicByline(topic) : undefined,- description: shareMetaDescription(await loadShareResources(locale), 'topicDescription'),+ description: shareMetaDescription(await loadShareT(locale), 'topicDescription'),locale,shareId,topic,diff --git a/apps/share/src/shell/createShareI18n.ts b/apps/share/src/shell/createShareI18n.tsindex 46ba0d6df15..2a996633742 100644--- a/apps/share/src/shell/createShareI18n.ts+++ b/apps/share/src/shell/createShareI18n.ts@@ -36,6 +36,30 @@ export const loadShareResources = async (lang?: string) => {return Object.fromEntries(entries) as ShareResources;};+const translationOptions = {+ interpolation: { escapeValue: false },+ keySeparator: false,+ showSupportNotice: false,+} as const;++// Loader-side copy: a bare instance, so react-i18next's global instance stays the one rendering.+export const createShareT = (lang: string | undefined, resources: ShareResources) => {+ const locale = normalizeLocale(lang);+ const instance = i18next.createInstance();++ void instance.init({+ ...translationOptions,+ initAsync: false,+ lng: locale,+ resources: { [locale]: resources },+ });++ return instance.getFixedT(locale, 'chat');+};++export const loadShareT = async (lang?: string) =>+ createShareT(lang, await loadShareResources(lang));+export const createShareI18n = (lang?: string, bundledResources?: ShareResources) => {const locale = normalizeLocale(lang);const resources = bundledResources ? { [locale]: bundledResources } : undefined;@@ -48,11 +72,10 @@ export const createShareI18n = (lang?: string, bundledResources?: ShareResourcesreturn {init: (params: { initAsync?: boolean } = {}) =>instance.init({+ ...translationOptions,defaultNS: 'chat',fallbackLng: DEFAULT_LANG,initAsync: params.initAsync ?? true,- interpolation: { escapeValue: false },- keySeparator: false,lng: locale,ns: [],partialBundledLanguages: true,@@ -61,7 +84,6 @@ export const createShareI18n = (lang?: string, bundledResources?: ShareResourcesuseSuspense: false,},resources,- showSupportNotice: false,}),instance,};diff --git a/packages/i18n-extractor/README.md b/packages/i18n-extractor/README.mdindex cae60bae987..e67cabd5b85 100644--- a/packages/i18n-extractor/README.md+++ b/packages/i18n-extractor/README.md@@ -21,7 +21,21 @@ export interface Translator<N extends string> {- `Namespaced<N, F>`: `F & NamespaceMarker<N>`.- `NamespacedTranslate<N, Result = string, Options = Record<string, unknown>>`: a branded `(key, options?) => Result`.-Calls whose result type includes `undefined` (such as `find`) are optional: their keys need not exist in the default catalog. Passing a branded translator, or an object whose `t`/`find` fields are branded, into a type without the marker fails with `namespace erased`. `t.call`, `t.apply` and `t.bind` are rejected.+### i18next++i18next already brands its `TFunction` with `$TFunctionBrand` once `CustomTypeOptions.resources` is declared. The analysis program includes every declaration file of the tsconfig; list one it does not include in `declarations`, or the brand loses its namespace and extraction fails with `unknown translation namespace`. Pass `i18nextPreset` as the extract options:++```ts+import { extractI18n, i18nextPreset } from '@lobechat/i18n-extractor';++await extractI18n({ ...config, extract: i18nextPreset });+```++It sets `marker: '$TFunctionBrand'`, `translatorFields: ['t']`, `namespaceOption: 'ns'` (`t(key, { ns: 'topic' })` records `topic`; an omittable option also keeps the branded namespace) `namespaceSeparator: ':'` (`t('error:title')` records `error` / `title`), `countOption: 'count'` and `contextOption: 'context'`. A non-string `count` also retains `key_<category>` and `key_ordinal_<category>` for every plural category, and a `context` retains `key_<context>` (combined with the plural suffixes when both are passed), so each language keeps whichever forms its catalog has. `pluralSeparator` and `contextSeparator` default to `_`. i18next brands only the first namespace of `useTranslation(['a', 'b'])`, so reach the others through the option or the prefix.++### Calls++Calls whose result type includes `undefined` (such as `find`) are optional: their keys need not exist in the default catalog. Passing a branded translator, or an object whose `t`/`find` fields are branded, into a type without the marker fails with `namespace erased`. `t.call`, `t.apply` and `t.bind` are rejected. A translator listed in an `unknown`-typed array, such as a hook dependency list, is a reference and not an erasure.## Key patterns@@ -29,8 +43,12 @@ Calls whose result type includes `undefined` (such as `find`) are optional: thei| --------------------------------------------------------------------- | ---------------------------------------------------- || `'title'`, `const key = 'title'` | exactly `title` || `key: 'a' \| 'b'`, `` key: `level.${'low' \| 'high'}` `` | each member |+| `` `status.${reason}` `` with `reason: 'safety' \| undefined` | `status.safety` and `status.undefined` |+| `key as any`, `key!`, `(key)`, `key satisfies K` | whatever the inner expression retains || `` `status.${code}` `` with `code: string` (or any non-literal value) | every key matching `status\..*` || `key: string` | the whole namespace, only with a `dynamicKeys` entry |+| `t('views', { count })` | `views` and `views_<plural category>` |+| `t('friend', { context: 'male' \| 'female' })` | `friend`, `friend_male`, `friend_female` || `key: any`, `unknown`, objects | rejected |## Orchestrator@@ -53,17 +71,18 @@ const { resources, report } = await extractI18n({});```-| Option | Meaning |-| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `root` | Project root; `entries`, `tsconfig`, `dynamicKeys[].file` and report paths are relative to it. |-| `entries` | Files the graph starts from. `listSourceFiles(dir)` helps discover them. |-| `catalog` | `defaultLanguage`, `languages` (array or sync/async function) and `load(language, namespace)` returning a flat `Record<string, string>`. Return `{}` for a missing translation. |-| `dynamicKeys` | Allowlist for unbounded keys, matched by file and namespace. `reason` is required; a missing file fails. |-| `tsconfig` | Defaults to `tsconfig.json`. `compilerOptions` overrides the parsed options. |-| `workspace` | `{ packagesDirs }` (default `['packages']`) for `addWorkspacePaths`, or `false` to disable. |-| `graph` | `forbiddenImports`, `isBoundary`, `skip`, `mustResolve`; see `traceImportGraph`. |-| `extract` | `marker` (default `__i18nNamespace`), `translatorFields` (default `['t', 'find']`), `skip` for files that implement the translator itself. |-| `allowEmpty` | Allow a result with no translation calls. |+| Option | Meaning |+| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `root` | Project root; `entries`, `tsconfig`, `dynamicKeys[].file` and report paths are relative to it. |+| `entries` | Files the graph starts from. `listSourceFiles(dir)` helps discover them. |+| `catalog` | `defaultLanguage`, `languages` (array or sync/async function) and `load(language, namespace)` returning a flat `Record<string, string>`. Return `{}` for a missing translation. |+| `dynamicKeys` | Allowlist for unbounded keys, matched by file and namespace. `reason` is required; a missing file fails. |+| `tsconfig` | Defaults to `tsconfig.json`. `compilerOptions` overrides the parsed options. Its declaration files join the analysis program. |+| `declarations` | Extra declaration files for the analysis program, such as an i18next `CustomTypeOptions` augmentation the tsconfig does not include. A missing file fails. |+| `workspace` | `{ packagesDirs }` (default `['packages']`) for `addWorkspacePaths`, or `false` to disable. |+| `graph` | `forbiddenImports`, `isBoundary`, `skip`, `mustResolve`; see `traceImportGraph`. |+| `extract` | `marker` (default `__i18nNamespace`), `translatorFields` (default `['t', 'find']`), `namespaceOption`, `namespaceSeparator`, `countOption`, `contextOption`, `skip` for files that implement the translator itself. `i18nextPreset` fills these for i18next. |+| `allowEmpty` | Allow a result with no translation calls. |Every non-optional pattern must match at least one default-language key. `resources` has the shape `{ [language]: { [namespace]: { [key]: value } } }` for the default language plus every listed language. `report` records the traced file count, boundaries, import edges, call sites with their patterns, and per-namespace key counts, with paths relative to `root`.diff --git a/packages/i18n-extractor/src/extract.test.ts b/packages/i18n-extractor/src/extract.test.tsindex 364debe0b66..ede3b1a81f0 100644--- a/packages/i18n-extractor/src/extract.test.ts+++ b/packages/i18n-extractor/src/extract.test.ts@@ -4,7 +4,12 @@ import ts from 'typescript';import { describe, expect, it } from 'vitest';import type { ExtractTranslationUsesOptions } from './extract';-import { assertBoundedTranslationUses, extractTranslationUses, selectKeys } from './extract';+import {+ assertBoundedTranslationUses,+ extractTranslationUses,+ i18nextPreset,+ selectKeys,+} from './extract';import { createFixture, translatorType } from './testUtils';const extract = async (code: string, options?: ExtractTranslationUsesOptions) => {@@ -155,4 +160,190 @@ describe('extractTranslationUses', () => {const uses = await extract('declare const code: any; t(code);', { skip: () => true });expect(uses).toEqual([]);});++ it('stringifies nullish interpolation members like JavaScript does', async () => {+ const uses = await extract(+ "declare const reason: 'safety' | undefined | null; t(`block.${reason}`);",+ );+ expect(+ selectKeys(+ ['block.safety', 'block.undefined', 'block.null', 'block.other'],+ uses[0].patterns,+ ),+ ).toEqual(['block.null', 'block.safety', 'block.undefined']);+ });++ it('keeps flow narrowing instead of widening through a computed initializer', async () => {+ const uses = await extract(+ 'declare function read(): string | undefined; const reason = read(); if (reason) t(`block.${reason}`);',+ );+ expect(uses[0].patterns).toEqual(['block\\..*']);+ });++ it('analyzes the expression under a type assertion', async () => {+ const uses = await extract(+ "declare const id: 'done' | 'todo'; t(`group.${id}` as any); t(('plain') as string); t('bang'!);",+ );+ expect(uses.map((use) => use.patterns)).toEqual([+ ['group\\.done', 'group\\.todo'],+ ['plain'],+ ['bang'],+ ]);+ });++ it('still rejects an opaque key behind a type assertion', async () => {+ await expect(extract('declare const key: any; t(key as string);')).rejects.toThrow(+ 'Cannot statically classify translation key',+ );+ });++ it('reads the namespace from a configured option', async () => {+ const uses = await extract(+ "declare const ns: 'error' | 'topic'; declare const options: { ns: 'common' }; t('a', { ns: 'home' }); t('b', { ns }); t('c', options); t('d', {});",+ { namespaceOption: 'ns' },+ );+ expect(uses.map((use) => `${use.namespace}:${use.patterns.join('|')}`)).toEqual([+ 'home:a',+ 'error:b',+ 'topic:b',+ 'common:c',+ 'chat:d',+ ]);+ });++ it('keeps the branded namespace when the option may be omitted', async () => {+ const uses = await extract("declare const options: { ns?: 'home' }; t('a', options);", {+ namespaceOption: 'ns',+ });+ expect(uses.map((use) => use.namespace)).toEqual(['home', 'chat']);+ });++ it('rejects an open namespace option', async () => {+ await expect(+ extract("declare const ns: string; t('a', { ns });", { namespaceOption: 'ns' }),+ ).rejects.toThrow('unknown translation namespace');+ });++ it('ignores the namespace option unless configured', async () => {+ const uses = await extract("t('a', { ns: 'home' });");+ expect(uses[0].namespace).toBe('chat');+ });++ it('splits a namespace prefix from the key', async () => {+ const uses = await extract(+ "declare const code: 'A' | 'B'; t('home:title'); t(`runtime:${code}`); t('plain');",+ { namespaceSeparator: ':' },+ );+ expect(uses.map((use) => `${use.namespace}|${use.patterns.join(',')}`)).toEqual([+ 'home|title',+ 'runtime|A,B',+ 'chat|plain',+ ]);+ });++ it('keeps a prefixed key in the branded namespace unless a separator is configured', async () => {+ const uses = await extract("t('home:title');");+ expect(uses[0]).toMatchObject({ namespace: 'chat', patterns: ['home:title'] });+ });++ it('treats a translator listed in an unknown-typed array as a reference', async () => {+ const root = await createFixture({+ 'entry.ts': `${translatorType}\ndeclare const t: T<'chat'>;\ndeclare function useMemo<V>(factory: () => V, deps: readonly unknown[]): V;\nuseMemo(() => t('memo'), [t]);`,+ });+ const file = path.join(root, 'entry.ts');+ const uses = extractTranslationUses(ts.createProgram([file], { strict: true }), [file]);+ expect(uses.flatMap((use) => use.patterns)).toEqual(['memo']);+ });++ it('still rejects passing a translator to an unknown parameter', async () => {+ await expect(extract('declare function sink(value: unknown): void; sink(t);')).rejects.toThrow(+ 'namespace erased',+ );+ });++ it('retains plural suffixes when a count option is passed', async () => {+ const uses = await extract(+ "declare const count: number; declare const options: { count?: number }; t('views', { count }); t('items', options); t('plain', {});",+ { countOption: 'count' },+ );+ const keys = [+ 'items_one',+ 'plain',+ 'plain_one',+ 'views',+ 'views_few',+ 'views_one',+ 'views_ordinal_two',+ 'views_other',+ 'views_total',+ ];+ expect(uses.map((use) => selectKeys(keys, use.patterns))).toEqual([+ ['views', 'views_few', 'views_one', 'views_ordinal_two', 'views_other'],+ ['items_one'],+ ['plain'],+ ]);+ });++ it('does not treat a string count as plural', async () => {+ const uses = await extract("t('views', { count: '3' });", { countOption: 'count' });+ expect(selectKeys(['views', 'views_other'], uses[0].patterns)).toEqual(['views']);+ });++ it('retains context suffixes, alone and combined with plurals', async () => {+ const uses = await extract(+ "declare const gender: 'male' | 'female' | undefined; declare const count: number; t('friend', { context: gender, count }); t('label', { context: 'short' });",+ { contextOption: 'context', countOption: 'count' },+ );+ const keys = [+ 'friend',+ 'friend_female_one',+ 'friend_male',+ 'friend_other',+ 'friend_robot',+ 'label',+ 'label_long',+ 'label_short',+ ];+ expect(uses.map((use) => selectKeys(keys, use.patterns))).toEqual([+ ['friend', 'friend_female_one', 'friend_male', 'friend_other'],+ ['label', 'label_short'],+ ]);+ });++ it('bounds an open context by the key prefix', async () => {+ const uses = await extract("declare const kind: string; t('label', { context: kind });", {+ contextOption: 'context',+ });+ expect(selectKeys(['label', 'label_any', 'other'], uses[0].patterns)).toEqual([+ 'label',+ 'label_any',+ ]);+ });++ it('keeps plural suffixes on namespace-prefixed keys', async () => {+ const uses = await extract("t('error:retry', { count: 2 });", {+ countOption: 'count',+ namespaceSeparator: ':',+ });+ expect(uses[0].namespace).toBe('error');+ expect(selectKeys(['retry_one'], uses[0].patterns)).toEqual(['retry_one']);+ });++ it('extracts i18next-branded translators with the preset', async () => {+ const root = await createFixture({+ 'entry.ts':+ "type TFunction<N extends string> = ((key: string, options?: { ns?: string }) => string) & { $TFunctionBrand: N };\ndeclare const t: TFunction<'chat'>;\nt('a'); t('error:b'); t('c', { ns: 'topic' });",+ });+ const file = path.join(root, 'entry.ts');+ const uses = extractTranslationUses(+ ts.createProgram([file], { noLib: true, strict: true }),+ [file],+ i18nextPreset,+ );+ expect(uses.map((use) => `${use.namespace}|${use.patterns.join(',')}`)).toEqual([+ 'chat|a',+ 'error|b',+ 'topic|c',+ ]);+ });});diff --git a/packages/i18n-extractor/src/extract.ts b/packages/i18n-extractor/src/extract.tsindex 2b3182999e9..04f46ec0d40 100644--- a/packages/i18n-extractor/src/extract.ts+++ b/packages/i18n-extractor/src/extract.ts@@ -17,11 +17,26 @@ export interface DynamicKeyEntry {}export interface ExtractTranslationUsesOptions {+ contextOption?: string;+ contextSeparator?: string;+ countOption?: string;marker?: string;+ namespaceOption?: string;+ namespaceSeparator?: string;+ pluralSeparator?: string;skip?: (file: string) => boolean;translatorFields?: string[];}+export const i18nextPreset = {+ contextOption: 'context',+ countOption: 'count',+ marker: '$TFunctionBrand',+ namespaceOption: 'ns',+ namespaceSeparator: ':',+ translatorFields: ['t'],+} satisfies ExtractTranslationUsesOptions;+export const UNBOUNDED_PATTERN = '.*';export const assertBoundedTranslationUses = (@@ -42,6 +57,22 @@ export const assertBoundedTranslationUses = (const escape = (value: string) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');const product = (left: string[], right: string[]) => left.flatMap((a) => right.map((b) => a + b));const INDIRECT_CALLS = new Set(['apply', 'bind', 'call']);+const PLURAL_CATEGORIES = 'zero|one|two|few|many|other';+const unwrapAssertions = (node: ts.Expression): ts.Expression =>+ ts.isAsExpression(node) ||+ ts.isTypeAssertionExpression(node) ||+ ts.isSatisfiesExpression(node) ||+ ts.isNonNullExpression(node) ||+ ts.isParenthesizedExpression(node)+ ? unwrapAssertions(node.expression)+ : node;+// Other initializers are already summarized by the use-site type, which also carries flow narrowing.+const tracesKeyText = (initializer: ts.Expression) => {+ const node = unwrapAssertions(initializer);+ return ts.isStringLiteralLike(node) || ts.isTemplateExpression(node) || ts.isIdentifier(node);+};+const OPAQUE_INTERPOLATION =+ ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Object | ts.TypeFlags.BooleanLike;// Patterns are anchored at selection time. Unknown strings deliberately retain every matching key.export const typePatterns = (type: ts.Type): string[] => {@@ -68,7 +99,13 @@ export const extractTranslationUses = (program: ts.Program,files: string[],{+ contextOption,+ contextSeparator = '_',+ countOption,marker: markerName = DEFAULT_NAMESPACE_MARKER,+ namespaceOption,+ namespaceSeparator,+ pluralSeparator = '_',skip,translatorFields = ['t', 'find'],}: ExtractTranslationUsesOptions = {},@@ -86,6 +123,7 @@ export const extractTranslationUses = (const patternsFor = (node: ts.Expression, seen = new Set<ts.Node>()): string[] => {if (seen.has(node)) throw new Error('Cyclic translation key initializer');seen.add(node);+ if (unwrapAssertions(node) !== node) return patternsFor(unwrapAssertions(node), seen);if (ts.isStringLiteralLike(node)) return [escape(node.text)];if (ts.isTemplateExpression(node))return node.templateSpans.reduce(@@ -103,20 +141,27 @@ export const extractTranslationUses = (ts.isVariableDeclaration(declaration) &&declaration.initializer &&ts.isVariableDeclarationList(declaration.parent) &&- declaration.parent.flags & ts.NodeFlags.Const+ declaration.parent.flags & ts.NodeFlags.Const &&+ tracesKeyText(declaration.initializer))return patternsFor(declaration.initializer, seen);}return typePatterns(type);};+ // JS stringifies arbitrary interpolation values; a fixed surrounding pattern still bounds the resource set.+ const stringifiedPatterns = (type: ts.Type): string[] | undefined => {+ if (type.flags & ts.TypeFlags.Undefined) return ['undefined'];+ if (type.flags & ts.TypeFlags.Null) return ['null'];+ if (type.flags & OPAQUE_INTERPOLATION) return [UNBOUNDED_PATTERN];+ };const interpolationPatterns = (node: ts.Expression, seen: Set<ts.Node>): string[] => {const type = checker.getTypeAtLocation(node);- // JS stringifies arbitrary interpolation values; a fixed surrounding pattern still bounds the resource set.- if (- type.flags &- (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Object | ts.TypeFlags.BooleanLike)- )- return [UNBOUNDED_PATTERN];+ const direct = stringifiedPatterns(type);+ if (direct) return direct;+ if (type.isUnion() && type.types.some(stringifiedPatterns))+ return [+ ...new Set(type.types.flatMap((part) => stringifiedPatterns(part) ?? typePatterns(part))),+ ];return patternsFor(node, new Set(seen));};for (const file of files) {@@ -134,6 +179,13 @@ export const extractTranslationUses = (: ts.isAsExpression(node.parent)? checker.getTypeAtLocation(node.parent): checker.getContextualType(node);+ // An unknown-typed list element (e.g. a hook dependency list) cannot be called without a cast.+ if (+ context &&+ ts.isArrayLiteralExpression(node.parent) &&+ context.flags & ts.TypeFlags.Unknown+ )+ return;if (context) {const target = checker.getNonNullableType(context);const erased = marker@@ -153,33 +205,92 @@ export const extractTranslationUses = (`Unsupported indirect translation call in ${file}; call the typed translator directly`,);};- const recordCall = (node: ts.CallExpression) => {+ const namespaceTypes = (type: ts.Type) => {+ const parts = (type.isUnion() ? type.types : [type]).filter(+ (part) => !(part.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)),+ );+ return {+ literals: parts.map((part) => (part.isStringLiteral() ? part.value : undefined)),+ omittable: parts.length < (type.isUnion() ? type.types.length : 1),+ };+ };+ const optionType = (node: ts.CallExpression, name: string | undefined) => {+ const options = node.arguments[1];+ if (!name || !options) return;+ const option = checker.getTypeAtLocation(options).getProperty(name);+ if (!option) return;+ // Object literal properties widen without a contextual type; the initializer keeps its literal.+ const declaration = ts.isObjectLiteralExpression(options)+ ? options.properties.find((property) => property.name?.getText(source) === name)+ : undefined;+ return {+ optional: !declaration && Boolean(option.flags & ts.SymbolFlags.Optional),+ type:+ declaration && ts.isPropertyAssignment(declaration)+ ? checker.getTypeAtLocation(declaration.initializer)+ : declaration && ts.isShorthandPropertyAssignment(declaration)+ ? checker.getTypeAtLocation(declaration.name)+ : checker.getTypeOfSymbolAtLocation(option, options),+ };+ };+ const callNamespaces = (node: ts.CallExpression) => {const marker = markerOf(checker.getTypeAtLocation(node.expression));if (!marker) return;- const namespaceType = checker.getNonNullableType(- checker.getTypeOfSymbolAtLocation(marker, node.expression),- );- const namespaces = namespaceType.isUnion() ? namespaceType.types : [namespaceType];+ const branded = namespaceTypes(+ checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(marker, node.expression)),+ ).literals;+ const option = optionType(node, namespaceOption);+ if (!option) return branded;+ const { literals, omittable } = namespaceTypes(option.type);+ return omittable || option.optional ? [...new Set([...literals, ...branded])] : literals;+ };+ // i18next also tries `key_<context>` and `key[_<context>]_[ordinal_]<plural category>`, falling back to `key`.+ const lookupSuffix = (node: ts.CallExpression) => {+ let suffix = '';+ const context = optionType(node, contextOption);+ const contextType = context && checker.getNonNullableType(context.type);+ if (contextType && !(contextType.flags & ts.TypeFlags.Never))+ suffix += `(?:${escape(contextSeparator)}(?:${typePatterns(contextType).join('|')}))?`;+ const count = optionType(node, countOption);+ const countType = count && checker.getNonNullableType(count.type);+ const countParts = countType?.isUnion() ? countType.types : countType ? [countType] : [];+ if (countParts.some((part) => !(part.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Never))))+ suffix += `(?:${escape(pluralSeparator)}(?:ordinal${escape(pluralSeparator)})?(?:${PLURAL_CATEGORIES}))?`;+ return suffix;+ };+ const prefixPattern = namespaceSeparator+ ? new RegExp(`^([A-Za-z_][\\w-]*)${escape(escape(namespaceSeparator))}([^]*)$`)+ : undefined;+ const recordCall = (node: ts.CallExpression) => {+ const namespaces = callNamespaces(node);+ if (!namespaces) return;const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;if (!node.arguments[0]) throw new Error(`${file}:${line}: missing translation key`);+ let patterns: string[];+ let optional: boolean;+ try {+ const resultType = checker.getTypeAtLocation(node);+ optional =+ resultType.isUnion() &&+ resultType.types.some((type) => type.flags & ts.TypeFlags.Undefined);+ const suffix = lookupSuffix(node);+ patterns = patternsFor(node.arguments[0]).map((pattern) => pattern + suffix);+ } catch (error) {+ throw new Error(`${file}:${line}: ${String(error)}`, { cause: error });+ }for (const namespace of namespaces) {- if (!namespace.isStringLiteral())- throw new Error(`${file}:${line}: unknown translation namespace`);- try {- const resultType = checker.getTypeAtLocation(node);- const optional =- resultType.isUnion() &&- resultType.types.some((type) => type.flags & ts.TypeFlags.Undefined);- uses.push({- file,- line,- namespace: namespace.value,- optional,- patterns: patternsFor(node.arguments[0]),- });- } catch (error) {- throw new Error(`${file}:${line}: ${String(error)}`, { cause: error });+ if (namespace === undefined)+ throw new Error(+ `${file}:${line}: unknown translation namespace; make sure the declaration that types the translator (such as i18next CustomTypeOptions) is part of the program`,+ );+ const grouped = new Map<string, string[]>();+ for (const pattern of patterns) {+ const prefixed = prefixPattern?.exec(pattern);+ const target = prefixed ? prefixed[1] : namespace;+ grouped.set(target, [...(grouped.get(target) ?? []), prefixed ? prefixed[2] : pattern]);}+ for (const [target, keys] of grouped)+ uses.push({ file, line, namespace: target, optional, patterns: keys });}};const visit = (node: ts.Node) => {diff --git a/packages/i18n-extractor/src/extractI18n.test.ts b/packages/i18n-extractor/src/extractI18n.test.tsindex fcd16a215fe..8951096429a 100644--- a/packages/i18n-extractor/src/extractI18n.test.ts+++ b/packages/i18n-extractor/src/extractI18n.test.ts@@ -1,4 +1,4 @@-import { writeFile } from 'node:fs/promises';+import { mkdir, readFile, writeFile } from 'node:fs/promises';import path from 'node:path';import { describe, expect, it } from 'vitest';@@ -114,6 +114,46 @@ describe('extractI18n', () => {expect(resources['en-US'].home).toEqual({});});+ it('type-checks with the declaration files of the tsconfig', async () => {+ const { config, root } = await setup();+ await mkdir(path.join(root, 'src/types'));+ await writeFile(+ path.join(root, 'src/types/translator.d.ts'),+ `${translatorType} declare const homeT: T<"home">;`,+ );+ await writeFile(+ path.join(root, 'src/copy.ts'),+ 'export const copy = () => homeT("outer.key");',+ );+ const { resources } = await extractI18n(config);+ expect(resources['en-US'].home).toEqual({ 'outer.key': 'Wrapper copy' });+ });++ it('type-checks with declarations outside the tsconfig', async () => {+ const { config, root } = await setup();+ await mkdir(path.join(root, 'typings'));+ await writeFile(+ path.join(root, 'typings/translator.d.ts'),+ `${translatorType} declare const homeT: T<"home">;`,+ );+ await writeFile(+ path.join(root, 'src/copy.ts'),+ 'export const copy = () => homeT("outer.key");',+ );+ const tsconfig = path.join(root, 'tsconfig.json');+ const { compilerOptions } = JSON.parse(await readFile(tsconfig, 'utf8'));+ await writeFile(tsconfig, JSON.stringify({ compilerOptions, include: ['src', 'upstream'] }));+ expect((await extractI18n(config)).resources['en-US'].home).toBeUndefined();+ const { resources } = await extractI18n({+ ...config,+ declarations: ['typings/translator.d.ts'],+ });+ expect(resources['en-US'].home).toEqual({ 'outer.key': 'Wrapper copy' });+ await expect(+ extractI18n({ ...config, declarations: ['typings/missing.d.ts'] }),+ ).rejects.toThrow('ENOENT');+ });+it('refuses to emit empty resources unless allowed', async () => {const { config, root } = await setup();await writeFile(path.join(root, 'src/app/route.ts'), 'export const value = 1;');diff --git a/packages/i18n-extractor/src/extractI18n.ts b/packages/i18n-extractor/src/extractI18n.tsindex d874fa1eacb..e52e7d7e5f1 100644--- a/packages/i18n-extractor/src/extractI18n.ts+++ b/packages/i18n-extractor/src/extractI18n.ts@@ -27,6 +27,7 @@ export interface ExtractI18nConfig {allowEmpty?: boolean;catalog: CatalogAdapter;compilerOptions?: ts.CompilerOptions;+ declarations?: string[];dynamicKeys?: DynamicKeyEntry[];entries: string[];extract?: ExtractTranslationUsesOptions;@@ -49,21 +50,36 @@ export interface ExtractI18nResult {resources: Resources;}-const readCompilerOptions = (file: string): ts.CompilerOptions => {+const readTsconfig = (file: string) => {const config = ts.readConfigFile(file, ts.sys.readFile);if (config.error)throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'));- return ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(file)).options;+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(file));+ return {+ declarations: parsed.fileNames.filter((name) => DECLARATION_FILE.test(name)),+ options: parsed.options,+ };};-const createAnalysisProgram = (graph: ImportGraph, compilerOptions: ts.CompilerOptions) => {+const DECLARATION_FILE = /\.d\.[cm]?ts$/;++const createAnalysisProgram = (+ graph: ImportGraph,+ compilerOptions: ts.CompilerOptions,+ declarations: string[],+) => {const host = ts.createCompilerHost(compilerOptions);const getSourceFile = host.getSourceFile.bind(host);const boundaries = new Set(graph.boundaries);// Boundary modules resolve as missing so the checker never loads the graph behind them.host.getSourceFile = (file, ...args) =>boundaries.has(file) ? undefined : getSourceFile(file, ...args);- return ts.createProgram(graph.files, { ...compilerOptions, noEmit: true }, host);+ // Ambient declarations (module augmentation, globals) type the translators but are never imported.+ return ts.createProgram(+ [...new Set([...graph.files, ...declarations])],+ { ...compilerOptions, noEmit: true },+ host,+ );};const pick = (values: Catalog, patterns: string[]) =>@@ -71,10 +87,14 @@ const pick = (values: Catalog, patterns: string[]) =>export const extractI18n = async (config: ExtractI18nConfig): Promise<ExtractI18nResult> => {const root = await realpath(config.root);- const compilerOptions: ts.CompilerOptions = {- ...readCompilerOptions(path.resolve(root, config.tsconfig ?? 'tsconfig.json')),- ...config.compilerOptions,- };+ const tsconfig = readTsconfig(path.resolve(root, config.tsconfig ?? 'tsconfig.json'));+ const compilerOptions: ts.CompilerOptions = { ...tsconfig.options, ...config.compilerOptions };+ const declarations = [+ ...tsconfig.declarations,+ ...(await Promise.all(+ (config.declarations ?? []).map((file) => realpath(path.resolve(root, file))),+ )),+ ];if (config.workspace !== false) await addWorkspacePaths(root, compilerOptions, config.workspace);const graph = await traceImportGraph({...config.graph,@@ -83,7 +103,7 @@ export const extractI18n = async (config: ExtractI18nConfig): Promise<ExtractI18root,});const uses = extractTranslationUses(- createAnalysisProgram(graph, compilerOptions),+ createAnalysisProgram(graph, compilerOptions, declarations),graph.files,config.extract,);diff --git a/packages/i18n-extractor/src/index.ts b/packages/i18n-extractor/src/index.tsindex 30b5d8afe15..c391b9b14d4 100644--- a/packages/i18n-extractor/src/index.ts+++ b/packages/i18n-extractor/src/index.ts@@ -4,6 +4,7 @@ export type { DynamicKeyEntry, ExtractTranslationUsesOptions, TranslationUse } fexport {assertBoundedTranslationUses,extractTranslationUses,+ i18nextPreset,selectKeys,typePatterns,UNBOUNDED_PATTERN,