@babelize/engine 0.3.5 → 0.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config.d.ts +14 -58
- package/dist/index.d.ts +2 -0
- package/dist/index.js +11 -1
- package/dist/local/hosted-provider.js +1 -0
- package/dist/local/translate-core.d.ts +13 -2
- package/dist/local/translate-core.js +27 -9
- package/dist/local/translate-messages.d.ts +5 -0
- package/dist/local/translate-messages.js +1 -1
- package/dist/modules/finalization/nextjs-finalize.d.ts +19 -2
- package/dist/modules/finalization/nextjs-finalize.js +46 -4
- package/dist/modules/injection/inject.js +46 -1
- package/dist/modules/locale-builder/adopted.d.ts +29 -2
- package/dist/modules/locale-builder/adopted.js +185 -16
- package/dist/modules/locale-builder/locales.js +11 -2
- package/dist/modules/locale-builder/message-modules.d.ts +40 -0
- package/dist/modules/locale-builder/message-modules.js +263 -0
- package/dist/modules/lockfile/schema.d.ts +5 -157
- package/dist/modules/translator/client/byok.provider.js +8 -2
- package/dist/modules/translator/formality.d.ts +40 -0
- package/dist/modules/translator/formality.js +313 -0
- package/dist/modules/translator/translate.d.ts +18 -0
- package/dist/modules/translator/translate.js +78 -11
- package/dist/modules/workspace/existing-setup.d.ts +3 -1
- package/dist/modules/workspace/existing-setup.js +32 -15
- package/dist/orchestrator.js +51 -7
- package/dist/providers/default-translation-provider.js +2 -2
- package/dist/providers/types.d.ts +5 -0
- package/dist/qa/check-project.d.ts +7 -0
- package/dist/qa/check-project.js +12 -2
- package/dist/qa/locale-files.d.ts +8 -5
- package/dist/qa/locale-files.js +37 -9
- package/dist/qa/locale-qa.d.ts +10 -1
- package/dist/qa/locale-qa.js +9 -0
- package/dist/qa/review.js +1 -1
- package/dist/runtime/types.d.ts +21 -1
- package/dist/types.d.ts +2 -0
- package/dist/utils/translator-caller.d.ts +19 -0
- package/dist/utils/translator-caller.js +55 -21
- package/package.json +3 -3
package/dist/config.d.ts
CHANGED
|
@@ -3,72 +3,28 @@ import type { BabelizeConfig } from './types';
|
|
|
3
3
|
declare const configSchema: z.ZodObject<{
|
|
4
4
|
workspacePath: z.ZodString;
|
|
5
5
|
sourceLocale: z.ZodDefault<z.ZodString>;
|
|
6
|
-
targetLocales: z.ZodDefault<z.ZodArray<z.ZodString
|
|
7
|
-
framework: z.ZodOptional<z.ZodEnum<
|
|
6
|
+
targetLocales: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
7
|
+
framework: z.ZodOptional<z.ZodEnum<{
|
|
8
|
+
react: "react";
|
|
9
|
+
nextjs: "nextjs";
|
|
10
|
+
vue: "vue";
|
|
11
|
+
static: "static";
|
|
12
|
+
django: "django";
|
|
13
|
+
"react-native": "react-native";
|
|
14
|
+
unknown: "unknown";
|
|
15
|
+
}>>;
|
|
8
16
|
dryRun: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
9
17
|
projectId: z.ZodOptional<z.ZodString>;
|
|
10
18
|
sourceDir: z.ZodOptional<z.ZodString>;
|
|
11
19
|
localesDir: z.ZodOptional<z.ZodString>;
|
|
12
20
|
glossary: z.ZodOptional<z.ZodObject<{
|
|
13
|
-
neverTranslate: z.ZodDefault<z.ZodArray<z.ZodString
|
|
21
|
+
neverTranslate: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
14
22
|
alwaysTranslateAs: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
15
23
|
term: z.ZodString;
|
|
16
24
|
translations: z.ZodRecord<z.ZodString, z.ZodString>;
|
|
17
|
-
},
|
|
18
|
-
|
|
19
|
-
term: string;
|
|
20
|
-
}, {
|
|
21
|
-
translations: Record<string, string>;
|
|
22
|
-
term: string;
|
|
23
|
-
}>, "many">>;
|
|
24
|
-
}, "strip", z.ZodTypeAny, {
|
|
25
|
-
neverTranslate: string[];
|
|
26
|
-
alwaysTranslateAs: {
|
|
27
|
-
translations: Record<string, string>;
|
|
28
|
-
term: string;
|
|
29
|
-
}[];
|
|
30
|
-
}, {
|
|
31
|
-
neverTranslate?: string[] | undefined;
|
|
32
|
-
alwaysTranslateAs?: {
|
|
33
|
-
translations: Record<string, string>;
|
|
34
|
-
term: string;
|
|
35
|
-
}[] | undefined;
|
|
36
|
-
}>>;
|
|
25
|
+
}, z.core.$strip>>>;
|
|
26
|
+
}, z.core.$strip>>;
|
|
37
27
|
lockfilePath: z.ZodOptional<z.ZodString>;
|
|
38
|
-
},
|
|
39
|
-
workspacePath: string;
|
|
40
|
-
sourceLocale: string;
|
|
41
|
-
targetLocales: string[];
|
|
42
|
-
dryRun: boolean;
|
|
43
|
-
framework?: "react" | "nextjs" | "vue" | "static" | "django" | "react-native" | "unknown" | undefined;
|
|
44
|
-
projectId?: string | undefined;
|
|
45
|
-
sourceDir?: string | undefined;
|
|
46
|
-
localesDir?: string | undefined;
|
|
47
|
-
glossary?: {
|
|
48
|
-
neverTranslate: string[];
|
|
49
|
-
alwaysTranslateAs: {
|
|
50
|
-
translations: Record<string, string>;
|
|
51
|
-
term: string;
|
|
52
|
-
}[];
|
|
53
|
-
} | undefined;
|
|
54
|
-
lockfilePath?: string | undefined;
|
|
55
|
-
}, {
|
|
56
|
-
workspacePath: string;
|
|
57
|
-
framework?: "react" | "nextjs" | "vue" | "static" | "django" | "react-native" | "unknown" | undefined;
|
|
58
|
-
sourceLocale?: string | undefined;
|
|
59
|
-
targetLocales?: string[] | undefined;
|
|
60
|
-
dryRun?: boolean | undefined;
|
|
61
|
-
projectId?: string | undefined;
|
|
62
|
-
sourceDir?: string | undefined;
|
|
63
|
-
localesDir?: string | undefined;
|
|
64
|
-
glossary?: {
|
|
65
|
-
neverTranslate?: string[] | undefined;
|
|
66
|
-
alwaysTranslateAs?: {
|
|
67
|
-
translations: Record<string, string>;
|
|
68
|
-
term: string;
|
|
69
|
-
}[] | undefined;
|
|
70
|
-
} | undefined;
|
|
71
|
-
lockfilePath?: string | undefined;
|
|
72
|
-
}>;
|
|
28
|
+
}, z.core.$strip>;
|
|
73
29
|
export declare function loadBabelizeConfig(input: unknown): BabelizeConfig;
|
|
74
30
|
export { configSchema as babelizeConfigSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export type { AnalyzeOptions, AnalyzedString, FrameworkSupport, ProjectAnalysis
|
|
|
51
51
|
export { checkLocalePair, flattenLocaleMessages, tallyLocaleIssues } from './qa/locale-qa';
|
|
52
52
|
export { canonicalLocale, canonicalizeLocaleKeys, containsTerm, localeValue, normalizeGlossary, glossaryFingerprint, } from './modules/glossary';
|
|
53
53
|
export type { GlossaryRules, GlossaryRuleInput } from './modules/glossary';
|
|
54
|
+
export { detectFormality, formalityFor, formalityInstruction, formalityIssues, formalityOf, hasFormalitySplit, parseFormalityList, sanitizeFormality, } from './modules/translator/formality';
|
|
55
|
+
export type { FormalityLevel, FormalitySetting } from './modules/translator/formality';
|
|
54
56
|
export type { LocaleGlossary, LocaleIssue, LocaleIssueCode, LocaleIssueSeverity, LocalePairOptions, LocalePairReport, } from './qa/locale-qa';
|
|
55
57
|
export { DEFAULT_LOCALE_IGNORE_DIRS, findLocaleFileSets, groupLocaleFiles, isIgnoredLocalePath, isLocaleCode, loadLocale } from './qa/locale-files';
|
|
56
58
|
export type { FindLocaleOptions, LoadedLocale, LocaleFileSet, ProjectFileReader } from './qa/locale-files';
|
package/dist/index.js
CHANGED
|
@@ -22,7 +22,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
22
22
|
};
|
|
23
23
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
24
|
exports.CircuitBreaker = exports.validateBatchQuality = exports.validateTranslationQuality = exports.translatorLoadBalancer = exports.warmupTranslator = exports.checkTranslatorHealth = exports.callTranslator = exports.requiredPluralCategories = exports.parseIcu = exports.isIcuMessage = exports.compareIcuMessages = exports.sameProtectedSpans = exports.restoreText = exports.protectText = exports.hasNothingToTranslate = exports.checkTokens = exports.validateRawTokens = exports.sanitizeTranslation = exports.restorePlaceholders = exports.protectPlaceholders = exports.hashString = exports.hasICUSyntax = exports.extractPlaceholders = exports.parseCode = exports.I18N_LIBRARY_NAMES = exports.detectI18n = exports.SUPPORTED_SUMMARY = exports.FRAMEWORK_DISPLAY_NAMES = exports.localRepoFiles = exports.detectStack = exports.saveProjectConfig = exports.saveCachedStrings = exports.getProjectInfo = exports.getBabelizeSummary = exports.detectProjectInfo = exports.addBabelToHistory = exports.formatSyncNotificationMessage = exports.detectSyncIssues = exports.matchFromMemory = exports.setLocaleValue = exports.applyTranslationOverrides = exports.setEngineLogger = exports.runWithEngineLogger = exports.validateWorkspace = exports.scanKeyReferences = exports.RunAbortedError = exports.validateEngineConfigV2 = exports.runEngineV2 = exports.loadBabelizeConfig = exports.BabelizeEngine = void 0;
|
|
25
|
-
exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
|
|
25
|
+
exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.sanitizeFormality = exports.parseFormalityList = exports.hasFormalitySplit = exports.formalityOf = exports.formalityIssues = exports.formalityInstruction = exports.formalityFor = exports.detectFormality = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
|
|
26
26
|
var BabelizeEngine_1 = require("./BabelizeEngine");
|
|
27
27
|
Object.defineProperty(exports, "BabelizeEngine", { enumerable: true, get: function () { return BabelizeEngine_1.BabelizeEngine; } });
|
|
28
28
|
var config_1 = require("./config");
|
|
@@ -125,6 +125,16 @@ Object.defineProperty(exports, "containsTerm", { enumerable: true, get: function
|
|
|
125
125
|
Object.defineProperty(exports, "localeValue", { enumerable: true, get: function () { return glossary_1.localeValue; } });
|
|
126
126
|
Object.defineProperty(exports, "normalizeGlossary", { enumerable: true, get: function () { return glossary_1.normalizeGlossary; } });
|
|
127
127
|
Object.defineProperty(exports, "glossaryFingerprint", { enumerable: true, get: function () { return glossary_1.glossaryFingerprint; } });
|
|
128
|
+
// Formal vs informal address per target language.
|
|
129
|
+
var formality_1 = require("./modules/translator/formality");
|
|
130
|
+
Object.defineProperty(exports, "detectFormality", { enumerable: true, get: function () { return formality_1.detectFormality; } });
|
|
131
|
+
Object.defineProperty(exports, "formalityFor", { enumerable: true, get: function () { return formality_1.formalityFor; } });
|
|
132
|
+
Object.defineProperty(exports, "formalityInstruction", { enumerable: true, get: function () { return formality_1.formalityInstruction; } });
|
|
133
|
+
Object.defineProperty(exports, "formalityIssues", { enumerable: true, get: function () { return formality_1.formalityIssues; } });
|
|
134
|
+
Object.defineProperty(exports, "formalityOf", { enumerable: true, get: function () { return formality_1.formalityOf; } });
|
|
135
|
+
Object.defineProperty(exports, "hasFormalitySplit", { enumerable: true, get: function () { return formality_1.hasFormalitySplit; } });
|
|
136
|
+
Object.defineProperty(exports, "parseFormalityList", { enumerable: true, get: function () { return formality_1.parseFormalityList; } });
|
|
137
|
+
Object.defineProperty(exports, "sanitizeFormality", { enumerable: true, get: function () { return formality_1.sanitizeFormality; } });
|
|
128
138
|
var locale_files_1 = require("./qa/locale-files");
|
|
129
139
|
Object.defineProperty(exports, "DEFAULT_LOCALE_IGNORE_DIRS", { enumerable: true, get: function () { return locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS; } });
|
|
130
140
|
Object.defineProperty(exports, "findLocaleFileSets", { enumerable: true, get: function () { return locale_files_1.findLocaleFileSets; } });
|
|
@@ -153,6 +153,7 @@ class HostedTranslationProvider {
|
|
|
153
153
|
...(glossary.length ? { glossary } : {}),
|
|
154
154
|
...(Object.keys(hints).length > 0 ? { hints } : {}),
|
|
155
155
|
...(request.brandVoice ? { brandVoice: request.brandVoice.slice(0, types_1.TRANSLATE_BATCH_LIMITS.maxBrandVoiceChars) } : {}),
|
|
156
|
+
...(request.formality ? { formality: request.formality } : {}),
|
|
156
157
|
});
|
|
157
158
|
// One key per logical batch, reused by its retries: if an earlier attempt
|
|
158
159
|
// was answered (and charged) but the response was lost, the server
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import type { EngineConfigV2, EngineResultV2 } from '../runtime/types';
|
|
2
2
|
import type { ProjectRulesStore, TranslationFailure, TranslationProvider } from '../providers/types';
|
|
3
3
|
import type { LocaleGlossary } from '../qa/locale-qa';
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
import type { FormalitySetting } from '../modules/translator/formality';
|
|
5
|
+
/** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
|
|
6
|
+
export declare function configRulesStore(glossary: LocaleGlossary | undefined, extra?: {
|
|
7
|
+
brandVoice?: string;
|
|
8
|
+
formality?: Record<string, FormalitySetting>;
|
|
9
|
+
}): ProjectRulesStore;
|
|
6
10
|
import { type ByokProvider } from '@babelize/types';
|
|
7
11
|
import type { HostedTranslationProvider } from './hosted-provider';
|
|
8
12
|
import { type FormatResult } from './formatter';
|
|
@@ -32,6 +36,13 @@ export interface LocalTranslateOptions {
|
|
|
32
36
|
* brought up to date (from the lockfile, so only new strings cost tokens).
|
|
33
37
|
*/
|
|
34
38
|
replace?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Form of address per target locale (or base language), e.g. `{ de: 'formal' }`
|
|
41
|
+
* (`--formality de=formal`). Merged over `.babelize/config.json` `formality`.
|
|
42
|
+
*/
|
|
43
|
+
formality?: Record<string, FormalitySetting>;
|
|
44
|
+
/** Tone and style for the translator; replaces `.babelize/config.json` `brandVoice`. */
|
|
45
|
+
brandVoice?: string;
|
|
35
46
|
}
|
|
36
47
|
export interface LocalTranslateDeps {
|
|
37
48
|
/** Replaces the BYOK translator (tests). */
|
|
@@ -52,15 +52,16 @@ const orchestrator_1 = require("../orchestrator");
|
|
|
52
52
|
const logger_1 = require("../utils/logger");
|
|
53
53
|
const workspace_1 = require("../modules/workspace");
|
|
54
54
|
const check_project_1 = require("../qa/check-project");
|
|
55
|
-
/** A rules store serving
|
|
56
|
-
function configRulesStore(glossary) {
|
|
55
|
+
/** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
|
|
56
|
+
function configRulesStore(glossary, extra = {}) {
|
|
57
57
|
const rules = [
|
|
58
|
-
...(glossary
|
|
59
|
-
...(glossary
|
|
58
|
+
...(glossary?.neverTranslate ?? []).map((term) => ({ term, type: 'never_translate', translations: null })),
|
|
59
|
+
...(glossary?.alwaysTranslateAs ?? []).map((e) => ({ term: e.term, type: 'always_translate_as', translations: e.translations })),
|
|
60
60
|
];
|
|
61
61
|
return {
|
|
62
62
|
getGlossary: async () => rules,
|
|
63
|
-
getBrandVoice: async () => null,
|
|
63
|
+
getBrandVoice: async () => extra.brandVoice?.trim() || null,
|
|
64
|
+
getFormality: async () => (extra.formality && Object.keys(extra.formality).length > 0 ? extra.formality : null),
|
|
64
65
|
};
|
|
65
66
|
}
|
|
66
67
|
const types_1 = require("@babelize/types");
|
|
@@ -334,10 +335,15 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
334
335
|
const targetLocales = [...opts.targetLocales, ...keptLocales];
|
|
335
336
|
const before = await (0, workspace_copy_1.snapshot)(temp.dir);
|
|
336
337
|
state.collecting = true;
|
|
337
|
-
// The project's glossary
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
const
|
|
338
|
+
// The project's glossary, brand voice and formality from
|
|
339
|
+
// .babelize/config.json — the same file and schema `babelize check`
|
|
340
|
+
// reads — applied like a cloud project's. Options win over the file.
|
|
341
|
+
const config = await (0, check_project_1.readProjectLocaleConfig)(projectDir);
|
|
342
|
+
const brandVoice = opts.brandVoice?.trim() || config.brandVoice;
|
|
343
|
+
const formality = { ...config.formality, ...opts.formality };
|
|
344
|
+
const rules = config.glossary || brandVoice || Object.keys(formality).length > 0
|
|
345
|
+
? configRulesStore(config.glossary, { brandVoice, formality })
|
|
346
|
+
: undefined;
|
|
341
347
|
const runEngine = deps.runEngine ?? orchestrator_1.runEngineV2;
|
|
342
348
|
const result = await runEngine({
|
|
343
349
|
workspacePath: temp.dir,
|
|
@@ -390,6 +396,18 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
390
396
|
if (locale.locale === opts.sourceLocale || locale.noFile)
|
|
391
397
|
continue;
|
|
392
398
|
const rel = locale.path.split(path.sep).join('/');
|
|
399
|
+
if (locale.files) {
|
|
400
|
+
// An adopted folder per locale (#370): each namespace file or module
|
|
401
|
+
// exactly as the engine produced it, existing translations kept.
|
|
402
|
+
for (const f of locale.files) {
|
|
403
|
+
const abs = path.resolve(temp.dir, f.path.split(path.sep).join('/'));
|
|
404
|
+
if (path.relative(temp.dir, abs).startsWith('..'))
|
|
405
|
+
continue;
|
|
406
|
+
await (0, promises_1.mkdir)(path.dirname(abs), { recursive: true });
|
|
407
|
+
await (0, promises_1.writeFile)(abs, f.content);
|
|
408
|
+
}
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
393
411
|
if (locale.content !== undefined && !rel.endsWith('.json')) {
|
|
394
412
|
// A merged catalogue (Django .po): written exactly as the engine
|
|
395
413
|
// produced it. The merge never drops existing translations.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ByokProvider } from '@babelize/types';
|
|
2
2
|
import type { TranslationFailure, TranslationProvider } from '../providers/types';
|
|
3
|
+
import type { FormalitySetting } from '../modules/translator/formality';
|
|
3
4
|
/**
|
|
4
5
|
* Translate a flat key → text map with the engine's translate phase, without
|
|
5
6
|
* a project: the same placeholder protection, ICU/plural handling, glossary,
|
|
@@ -25,6 +26,10 @@ export interface TranslateMessagesOptions {
|
|
|
25
26
|
translations: Record<string, string>;
|
|
26
27
|
}>;
|
|
27
28
|
};
|
|
29
|
+
/** Tone and style for the translator (LLM providers). */
|
|
30
|
+
brandVoice?: string;
|
|
31
|
+
/** Form of address per target locale (or base language), e.g. `{ de: 'formal' }`. */
|
|
32
|
+
formality?: Record<string, FormalitySetting>;
|
|
28
33
|
/**
|
|
29
34
|
* The app's runtime formats ICU (next-intl, i18next-icu): count
|
|
30
35
|
* placeholders may become plurals. Default true.
|
|
@@ -70,7 +70,7 @@ async function run(opts) {
|
|
|
70
70
|
localeFormat: 'json',
|
|
71
71
|
};
|
|
72
72
|
const result = await (0, translate_1.translateLocales)(workspace, { locale: opts.sourceLocale, path: '', data: { ...opts.messages }, isNew: false }, opts.targetLocales, false, true, // dry run: nothing written
|
|
73
|
-
undefined, opts.onProgress, undefined, undefined, opts.translator ? undefined : opts.byok, undefined, undefined, opts.translator ? { translator: opts.translator } : {}, { targetPlurals: opts.targetPlurals ?? true, rules: { glossary, brandVoice: null, complete: true } });
|
|
73
|
+
undefined, opts.onProgress, undefined, undefined, opts.translator ? undefined : opts.byok, undefined, undefined, opts.translator ? { translator: opts.translator } : {}, { targetPlurals: opts.targetPlurals ?? true, rules: { glossary, brandVoice: opts.brandVoice?.trim() || null, formality: opts.formality ?? null, complete: true } });
|
|
74
74
|
const targets = {};
|
|
75
75
|
for (const file of result.translation.locales) {
|
|
76
76
|
const flat = (0, keygen_1.flattenLocaleData)(file.data);
|
|
@@ -30,8 +30,25 @@ export declare function buildRequestConfig(opts: {
|
|
|
30
30
|
}): string;
|
|
31
31
|
/** Wrap the next.config default export / module.exports with next-intl's plugin. */
|
|
32
32
|
export declare function wrapNextConfig(content: string, requestConfigPath: string, typescript: boolean): string | null;
|
|
33
|
-
/**
|
|
34
|
-
|
|
33
|
+
/**
|
|
34
|
+
* True when next.config turns on Cache Components (`cacheComponents: true`,
|
|
35
|
+
* the default in create-next-app 16.4+, or `experimental.dynamicIO` before
|
|
36
|
+
* Next 16). Then request data — the cookies and headers our request config
|
|
37
|
+
* reads — may only be read inside <Suspense>, or `next build` fails with
|
|
38
|
+
* "Next.js encountered uncached or runtime data during prerendering".
|
|
39
|
+
*/
|
|
40
|
+
export declare function usesCacheComponents(nextConfig: string): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>.
|
|
43
|
+
*
|
|
44
|
+
* With `suspense` (Cache Components on), the whole <body> content is wrapped
|
|
45
|
+
* in <Suspense><NextIntlClientProvider>…, so every translated component —
|
|
46
|
+
* including a header or footer rendered by the layout itself — reads the
|
|
47
|
+
* locale inside a Suspense boundary.
|
|
48
|
+
*/
|
|
49
|
+
export declare function wrapRootLayout(content: string, typescript: boolean, options?: {
|
|
50
|
+
suspense?: boolean;
|
|
51
|
+
}): string | null;
|
|
35
52
|
export declare function finalizeNextIntl(workspace: WorkspaceInfo, dryRun: boolean, options: {
|
|
36
53
|
sourceLocale?: string;
|
|
37
54
|
targetLocales?: string[];
|
|
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
36
36
|
exports.NEXT_INTL_DEPENDENCIES = void 0;
|
|
37
37
|
exports.buildRequestConfig = buildRequestConfig;
|
|
38
38
|
exports.wrapNextConfig = wrapNextConfig;
|
|
39
|
+
exports.usesCacheComponents = usesCacheComponents;
|
|
39
40
|
exports.wrapRootLayout = wrapRootLayout;
|
|
40
41
|
exports.finalizeNextIntl = finalizeNextIntl;
|
|
41
42
|
const fs = __importStar(require("fs"));
|
|
@@ -179,8 +180,25 @@ function wrapNextConfig(content, requestConfigPath, typescript) {
|
|
|
179
180
|
}
|
|
180
181
|
return null;
|
|
181
182
|
}
|
|
182
|
-
/**
|
|
183
|
-
|
|
183
|
+
/**
|
|
184
|
+
* True when next.config turns on Cache Components (`cacheComponents: true`,
|
|
185
|
+
* the default in create-next-app 16.4+, or `experimental.dynamicIO` before
|
|
186
|
+
* Next 16). Then request data — the cookies and headers our request config
|
|
187
|
+
* reads — may only be read inside <Suspense>, or `next build` fails with
|
|
188
|
+
* "Next.js encountered uncached or runtime data during prerendering".
|
|
189
|
+
*/
|
|
190
|
+
function usesCacheComponents(nextConfig) {
|
|
191
|
+
return /\b(cacheComponents|dynamicIO)\s*:\s*true\b/.test(nextConfig);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>.
|
|
195
|
+
*
|
|
196
|
+
* With `suspense` (Cache Components on), the whole <body> content is wrapped
|
|
197
|
+
* in <Suspense><NextIntlClientProvider>…, so every translated component —
|
|
198
|
+
* including a header or footer rendered by the layout itself — reads the
|
|
199
|
+
* locale inside a Suspense boundary.
|
|
200
|
+
*/
|
|
201
|
+
function wrapRootLayout(content, typescript, options = {}) {
|
|
184
202
|
if (content.includes('NextIntlClientProvider'))
|
|
185
203
|
return content;
|
|
186
204
|
let ast;
|
|
@@ -191,11 +209,16 @@ function wrapRootLayout(content, typescript) {
|
|
|
191
209
|
return null;
|
|
192
210
|
}
|
|
193
211
|
let target = null;
|
|
212
|
+
let bodyContent = null;
|
|
194
213
|
(0, ast_helpers_1.traverse)(ast, {
|
|
195
214
|
JSXElement(p) {
|
|
196
215
|
const name = p.node.openingElement.name;
|
|
197
216
|
if (!ast_helpers_1.t.isJSXIdentifier(name, { name: 'body' }))
|
|
198
217
|
return;
|
|
218
|
+
const { openingElement, closingElement } = p.node;
|
|
219
|
+
if (openingElement.end != null && closingElement?.start != null) {
|
|
220
|
+
bodyContent = { start: openingElement.end, end: closingElement.start };
|
|
221
|
+
}
|
|
199
222
|
p.traverse({
|
|
200
223
|
JSXExpressionContainer(inner) {
|
|
201
224
|
if (ast_helpers_1.t.isIdentifier(inner.node.expression, { name: 'children' }) && inner.node.start != null && inner.node.end != null) {
|
|
@@ -209,6 +232,19 @@ function wrapRootLayout(content, typescript) {
|
|
|
209
232
|
});
|
|
210
233
|
if (!target)
|
|
211
234
|
return null;
|
|
235
|
+
if (options.suspense && bodyContent) {
|
|
236
|
+
const { start, end } = bodyContent;
|
|
237
|
+
const importsSuspense = /import\s*\{[^}]*\bSuspense\b[^}]*\}\s*from\s*['"]react['"]/.test(content);
|
|
238
|
+
const imports = [
|
|
239
|
+
...(importsSuspense ? [] : [`import { Suspense } from 'react';`]),
|
|
240
|
+
`import { NextIntlClientProvider } from 'next-intl';`,
|
|
241
|
+
].join('\n');
|
|
242
|
+
return applySplices(content, [
|
|
243
|
+
insertTopLevel(ast, imports),
|
|
244
|
+
{ at: start, insert: '<Suspense><NextIntlClientProvider>' },
|
|
245
|
+
{ at: end, insert: '</NextIntlClientProvider></Suspense>' },
|
|
246
|
+
]);
|
|
247
|
+
}
|
|
212
248
|
const { start, end } = target;
|
|
213
249
|
return applySplices(content, [
|
|
214
250
|
insertTopLevel(ast, `import { NextIntlClientProvider } from 'next-intl';`),
|
|
@@ -290,6 +326,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
290
326
|
// 2. next.config — wrap with the next-intl plugin.
|
|
291
327
|
const pluginPath = `./${toPosix(path.relative(root, requestFile))}`;
|
|
292
328
|
const nextConfigPath = await findFirst(root, NEXT_CONFIG_FILES);
|
|
329
|
+
const cacheComponents = nextConfigPath ? usesCacheComponents(await (0, file_utils_1.readFile)(nextConfigPath)) : false;
|
|
293
330
|
if (!nextConfigPath) {
|
|
294
331
|
const created = `import createNextIntlPlugin from 'next-intl/plugin';\n\n` +
|
|
295
332
|
`const withNextIntl = createNextIntlPlugin(${JSON.stringify(pluginPath)});\n\n` +
|
|
@@ -316,9 +353,14 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
316
353
|
}
|
|
317
354
|
else {
|
|
318
355
|
const content = await (0, file_utils_1.readFile)(layoutPath);
|
|
319
|
-
const wrapped = wrapRootLayout(content, /\.tsx?$/.test(layoutPath));
|
|
356
|
+
const wrapped = wrapRootLayout(content, /\.tsx?$/.test(layoutPath), { suspense: cacheComponents });
|
|
357
|
+
const layoutName = toPosix(path.relative(root, layoutPath));
|
|
358
|
+
if (cacheComponents && content.includes('NextIntlClientProvider') && !/<Suspense\b/.test(content)) {
|
|
359
|
+
warnings.push(`next.config enables cacheComponents, and ${layoutName} renders NextIntlClientProvider outside <Suspense>. ` +
|
|
360
|
+
'next-intl reads the locale from cookies and headers here, so wrap the <body> content in <Suspense> or next build fails.');
|
|
361
|
+
}
|
|
320
362
|
if (wrapped === null) {
|
|
321
|
-
warnings.push(`Could not find {children} inside <body> in ${
|
|
363
|
+
warnings.push(`Could not find {children} inside <body> in ${layoutName}: ` +
|
|
322
364
|
'wrap it in <NextIntlClientProvider> from next-intl so Client Components can translate.');
|
|
323
365
|
}
|
|
324
366
|
else if (wrapped !== content) {
|
|
@@ -238,6 +238,45 @@ function renderMessage(strategy, key, message, options) {
|
|
|
238
238
|
return null;
|
|
239
239
|
return { node: ast_helpers_1.t.jsxExpressionContainer((0, jsx_message_1.createMessageTCall)(key, message)) };
|
|
240
240
|
}
|
|
241
|
+
const DEPS_HOOKS = /^use(?:Callback|Memo|Effect|LayoutEffect|InsertionEffect)$/;
|
|
242
|
+
/**
|
|
243
|
+
* A component's translator used in a useCallback/useMemo/useEffect callback
|
|
244
|
+
* is one of its dependencies: left out of the array, the callback keeps the
|
|
245
|
+
* first render's t() and shows the old language after a switch (and
|
|
246
|
+
* react-hooks/exhaustive-deps flags it). Only callbacks holding a t() call
|
|
247
|
+
* this run injected are touched.
|
|
248
|
+
*/
|
|
249
|
+
function addTranslatorToHookDeps(ast, names, keys) {
|
|
250
|
+
(0, ast_helpers_1.traverse)(ast, {
|
|
251
|
+
CallExpression(path) {
|
|
252
|
+
const callee = path.node.callee;
|
|
253
|
+
const hook = ast_helpers_1.t.isIdentifier(callee)
|
|
254
|
+
? callee.name
|
|
255
|
+
: ast_helpers_1.t.isMemberExpression(callee) && ast_helpers_1.t.isIdentifier(callee.property) ? callee.property.name : null;
|
|
256
|
+
if (!hook || !DEPS_HOOKS.test(hook))
|
|
257
|
+
return;
|
|
258
|
+
const [fn, deps] = path.node.arguments;
|
|
259
|
+
if (!(ast_helpers_1.t.isArrowFunctionExpression(fn) || ast_helpers_1.t.isFunctionExpression(fn)) || !ast_helpers_1.t.isArrayExpression(deps))
|
|
260
|
+
return;
|
|
261
|
+
const listed = new Set(deps.elements.flatMap((e) => (ast_helpers_1.t.isIdentifier(e) ? [e.name] : [])));
|
|
262
|
+
const params = new Set(fn.params.flatMap((p) => (ast_helpers_1.t.isIdentifier(p) ? [p.name] : [])));
|
|
263
|
+
const used = new Set();
|
|
264
|
+
path.get('arguments.0').traverse({
|
|
265
|
+
CallExpression(inner) {
|
|
266
|
+
const c = inner.node.callee;
|
|
267
|
+
// t("key") and next-intl's t.rich("key") / t.markup("key").
|
|
268
|
+
const name = ast_helpers_1.t.isIdentifier(c) ? c.name : ast_helpers_1.t.isMemberExpression(c) && ast_helpers_1.t.isIdentifier(c.object) ? c.object.name : null;
|
|
269
|
+
const first = inner.node.arguments[0];
|
|
270
|
+
if (name && names.has(name) && ast_helpers_1.t.isStringLiteral(first) && keys.has(first.value))
|
|
271
|
+
used.add(name);
|
|
272
|
+
},
|
|
273
|
+
});
|
|
274
|
+
for (const name of used)
|
|
275
|
+
if (!listed.has(name) && !params.has(name))
|
|
276
|
+
deps.elements.push(ast_helpers_1.t.identifier(name));
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
}
|
|
241
280
|
/**
|
|
242
281
|
* A translated string literal keeps the whitespace around its text, which
|
|
243
282
|
* the message itself leaves out: a mail body `Page: ${href}` followed by two
|
|
@@ -792,6 +831,8 @@ positions, options = {}) {
|
|
|
792
831
|
};
|
|
793
832
|
let moduleTranslatorUsed = false;
|
|
794
833
|
let hookTranslatorUsed = false;
|
|
834
|
+
// Translators bound by a component hook (t, or an alias where t is taken).
|
|
835
|
+
const hookTranslatorNames = new Set();
|
|
795
836
|
/** The t() expression for a replacement, recording which import it needs. */
|
|
796
837
|
const pickTranslator = (p, source) => {
|
|
797
838
|
if (source === 'module') {
|
|
@@ -799,7 +840,9 @@ positions, options = {}) {
|
|
|
799
840
|
return 't';
|
|
800
841
|
}
|
|
801
842
|
hookTranslatorUsed = true;
|
|
802
|
-
|
|
843
|
+
const name = nameFor(p);
|
|
844
|
+
hookTranslatorNames.add(name);
|
|
845
|
+
return name;
|
|
803
846
|
};
|
|
804
847
|
for (const { plan, keys } of moduleRewrites) {
|
|
805
848
|
plan.literals.forEach((lit, i) => {
|
|
@@ -1111,6 +1154,8 @@ positions, options = {}) {
|
|
|
1111
1154
|
importAdded = true;
|
|
1112
1155
|
}
|
|
1113
1156
|
}
|
|
1157
|
+
if (hookTranslatorNames.size > 0)
|
|
1158
|
+
addTranslatorToHookDeps(ast, hookTranslatorNames, new Set(injections.map((i) => i.key)));
|
|
1114
1159
|
const modifiedContent = (0, ast_helpers_1.placeStatementsOnOwnLines)((0, ast_helpers_1.generateCode)(ast, content), [...insertedStatements]);
|
|
1115
1160
|
return {
|
|
1116
1161
|
file: filePath,
|
|
@@ -1,18 +1,42 @@
|
|
|
1
1
|
import type { ExtractedString, LocaleData, LocaleFile, NotInjectedString, WorkspaceInfo } from '../../runtime/types';
|
|
2
2
|
import type { LockfileData } from '../lockfile/schema';
|
|
3
|
+
import { type MessageModule } from './message-modules';
|
|
3
4
|
export interface AdoptedLocale {
|
|
5
|
+
/** Namespaced and modules layouts: `{ <namespace>: <that file's messages> }`. */
|
|
4
6
|
data: LocaleData;
|
|
7
|
+
/** Flat layout: the file's content. */
|
|
5
8
|
raw: string;
|
|
9
|
+
/** Namespaced and modules layouts: the locale's files, by namespace. */
|
|
10
|
+
parts?: Record<string, AdoptedPart>;
|
|
11
|
+
/** Modules: the locale's combining module (`index.ts`) as written. */
|
|
12
|
+
indexRaw?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface AdoptedPart {
|
|
15
|
+
/** File name in the locale's folder (`auth.json`, `auth.ts`). */
|
|
16
|
+
file: string;
|
|
17
|
+
raw: string;
|
|
18
|
+
data: LocaleData;
|
|
19
|
+
/** Modules: where each string sits, to write a module like this one. */
|
|
20
|
+
module?: MessageModule;
|
|
6
21
|
}
|
|
7
22
|
/** The locale files as they are before the run (the translator writes to the same paths). */
|
|
8
23
|
export declare function readAdoptedLocales(workspace: WorkspaceInfo, locales: string[]): Promise<Record<string, AdoptedLocale | null>>;
|
|
24
|
+
export declare function readAdoptedLocale(workspace: WorkspaceInfo, locale: string): Promise<AdoptedLocale | null>;
|
|
9
25
|
/**
|
|
10
26
|
* Record the translations already in the project's locale files in the
|
|
11
27
|
* lockfile, so they are reused instead of re-translated. A file value wins
|
|
12
28
|
* over the lockfile's (someone edited the file); a key whose source text
|
|
13
29
|
* changed since the lockfile recorded it is left for re-translation.
|
|
14
30
|
*/
|
|
15
|
-
export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null
|
|
31
|
+
export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>, options?: {
|
|
32
|
+
/**
|
|
33
|
+
* Only replace translations the lockfile already recorded (files Babelize
|
|
34
|
+
* generated itself): a value it never recorded — a backup-translator
|
|
35
|
+
* draft, or a failed key — is retried as usual, and so is a recorded copy
|
|
36
|
+
* of the source text.
|
|
37
|
+
*/
|
|
38
|
+
onlyOverRecorded?: boolean;
|
|
39
|
+
}): LockfileData;
|
|
16
40
|
/** Keys of `source` missing (or empty) in each target file: the work for a run without a lockfile. */
|
|
17
41
|
export declare function missingKeysByLocale(flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): Record<string, string[]>;
|
|
18
42
|
/**
|
|
@@ -20,8 +44,11 @@ export declare function missingKeysByLocale(flatKeys: Record<string, string>, ta
|
|
|
20
44
|
* extra keys, non-string values) with `values` filled in, or — for a new
|
|
21
45
|
* file — the source file's structure and order. Serialized like the source
|
|
22
46
|
* file (indentation, trailing newline) and handed to hosts as exact content.
|
|
47
|
+
* `others` are the setup's other locales, whose modules can serve as the
|
|
48
|
+
* template for a new language's (they already import the source and say
|
|
49
|
+
* `satisfies`).
|
|
23
50
|
*/
|
|
24
|
-
export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null): LocaleFile;
|
|
51
|
+
export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null, others?: Record<string, AdoptedLocale | null>): LocaleFile;
|
|
25
52
|
/**
|
|
26
53
|
* What the user needs to know after translating an adopted setup: where the
|
|
27
54
|
* translations went, strings in the code that aren't wired up, and where a
|