@babelize/engine 0.3.10 → 0.3.12
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.
|
@@ -356,6 +356,13 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
356
356
|
};
|
|
357
357
|
(0, ast_helpers_1.traverse)(ast, {
|
|
358
358
|
'JSXElement|JSXFragment'(path) {
|
|
359
|
+
// Code shown on the page (<pre>, <code>) is never copy: `import`,
|
|
360
|
+
// `return` and prop names translated into Japanese break the sample (#399).
|
|
361
|
+
if (path.isJSXElement() && ast_helpers_1.t.isJSXIdentifier(path.node.openingElement.name) && CODE_ELEMENTS.has(path.node.openingElement.name.name)) {
|
|
362
|
+
consumed.add(path.node);
|
|
363
|
+
path.traverse({ enter(inner) { consumed.add(inner.node); } });
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
359
366
|
if (!groupSentences || consumed.has(path.node))
|
|
360
367
|
return;
|
|
361
368
|
if ((0, ast_helpers_1.isAlreadyTranslated)(path.node, path))
|
|
@@ -470,6 +477,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
470
477
|
}
|
|
471
478
|
},
|
|
472
479
|
JSXAttribute(path) {
|
|
480
|
+
if (consumed.has(path.node))
|
|
481
|
+
return;
|
|
473
482
|
const name = path.node.name;
|
|
474
483
|
if (!ast_helpers_1.t.isJSXIdentifier(name))
|
|
475
484
|
return;
|
|
@@ -617,6 +626,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
617
626
|
return { strings, warnings, notInjected: unwired };
|
|
618
627
|
}
|
|
619
628
|
/** A string that names something rather than being shown: a property key, or part of a TypeScript type. */
|
|
629
|
+
/** Elements whose content is code, not copy. */
|
|
630
|
+
const CODE_ELEMENTS = new Set(['pre', 'code', 'kbd', 'samp']);
|
|
620
631
|
/** SVG attributes whose value is geometry (`d`, `viewBox`, `points`, …). */
|
|
621
632
|
const SVG_GEOMETRY_ATTRS = new Set(['d', 'viewBox', 'points', 'transform', 'gradientTransform', 'patternTransform', 'strokeDasharray', 'stroke-dasharray', 'pathLength']);
|
|
622
633
|
function isSvgGeometry(path) {
|
|
@@ -58,6 +58,7 @@ export declare function buildRequestConfig(opts: {
|
|
|
58
58
|
export declare function buildProxy(opts: {
|
|
59
59
|
kind: 'proxy' | 'middleware';
|
|
60
60
|
typescript: boolean;
|
|
61
|
+
sourceOnly?: string[];
|
|
61
62
|
}): string;
|
|
62
63
|
/**
|
|
63
64
|
* Give the root layout's <html> the active locale's `lang` and `dir`
|
|
@@ -68,6 +69,15 @@ export declare function buildProxy(opts: {
|
|
|
68
69
|
export declare function setHtmlLocale(content: string, typescript: boolean, localesImport: string): string | null;
|
|
69
70
|
/** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
|
|
70
71
|
export declare function nextMajor(packageJson: Record<string, any> | undefined): number | null;
|
|
72
|
+
/**
|
|
73
|
+
* `routing` from .babelize/config.json: `"cookie"` keeps one URL for every
|
|
74
|
+
* language; `"prefix"` (default) or `{ "sourceOnly": ["/docs"] }` gives each
|
|
75
|
+
* language its own URL, except the listed sections.
|
|
76
|
+
*/
|
|
77
|
+
export declare function readRouting(workspacePath: string): Promise<{
|
|
78
|
+
mode: NextRouting;
|
|
79
|
+
sourceOnly: string[];
|
|
80
|
+
}>;
|
|
71
81
|
/** Wrap the next.config default export / module.exports with next-intl's plugin. */
|
|
72
82
|
export declare function wrapNextConfig(content: string, requestConfigPath: string, typescript: boolean): string | null;
|
|
73
83
|
/**
|
|
@@ -39,6 +39,7 @@ exports.buildRequestConfig = buildRequestConfig;
|
|
|
39
39
|
exports.buildProxy = buildProxy;
|
|
40
40
|
exports.setHtmlLocale = setHtmlLocale;
|
|
41
41
|
exports.nextMajor = nextMajor;
|
|
42
|
+
exports.readRouting = readRouting;
|
|
42
43
|
exports.wrapNextConfig = wrapNextConfig;
|
|
43
44
|
exports.usesCacheComponents = usesCacheComponents;
|
|
44
45
|
exports.wrapRootLayout = wrapRootLayout;
|
|
@@ -159,10 +160,25 @@ import { locales, sourceLocale } from './locales';
|
|
|
159
160
|
|
|
160
161
|
export { locales, sourceLocale };
|
|
161
162
|
|
|
162
|
-
async function
|
|
163
|
+
${ts ? 'type Messages = { [key: string]: string | Messages };\n\n' : ''}async function load(locale${ts ? ': string' : ''})${ts ? ': Promise<Messages>' : ''} {
|
|
163
164
|
return (await import(\`${importPath}\`)).default;
|
|
164
165
|
}
|
|
165
166
|
|
|
167
|
+
/** \`base\` with \`over\` on top, key by key: a string a locale doesn't have yet shows the source text. */
|
|
168
|
+
function withFallback(base${ts ? ': Messages' : ''}, over${ts ? ': Messages' : ''})${ts ? ': Messages' : ''} {
|
|
169
|
+
const merged${ts ? ': Messages' : ''} = { ...base };
|
|
170
|
+
for (const [key, value] of Object.entries(over)) {
|
|
171
|
+
const fallback = base[key];
|
|
172
|
+
merged[key] = typeof value === 'object' && typeof fallback === 'object' ? withFallback(fallback, value) : value;
|
|
173
|
+
}
|
|
174
|
+
return merged;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function messagesFor(locale${ts ? ': string' : ''}) {
|
|
178
|
+
const source = await load(sourceLocale);
|
|
179
|
+
return locale === sourceLocale ? source : withFallback(source, await load(locale));
|
|
180
|
+
}
|
|
181
|
+
|
|
166
182
|
function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ? ': string' : ''} {
|
|
167
183
|
for (const candidate of candidates) {
|
|
168
184
|
if (!candidate) continue;
|
|
@@ -196,6 +212,33 @@ ${routed} // Otherwise the NEXT_LOCALE cookie, then the browser's Accept-Langua
|
|
|
196
212
|
function buildProxy(opts) {
|
|
197
213
|
const ts = opts.typescript;
|
|
198
214
|
const req = ts ? 'request: NextRequest' : 'request';
|
|
215
|
+
const sourceOnly = opts.sourceOnly ?? [];
|
|
216
|
+
// Sections that exist in the source language only (routing.sourceOnly): no
|
|
217
|
+
// /<locale>/ version, no redirect to one, no hreflang alternates (#399).
|
|
218
|
+
const sourceOnlyDecl = sourceOnly.length
|
|
219
|
+
? `
|
|
220
|
+
/** Served in the source language only (routing.sourceOnly in .babelize/config.json). */
|
|
221
|
+
const SOURCE_ONLY = ${JSON.stringify(sourceOnly)};
|
|
222
|
+
|
|
223
|
+
function isSourceOnly(pathname${ts ? ': string' : ''}) {
|
|
224
|
+
return SOURCE_ONLY.some((p) => pathname === p || pathname.startsWith(\`\${p}/\`));
|
|
225
|
+
}
|
|
226
|
+
`
|
|
227
|
+
: '';
|
|
228
|
+
const prefixedSourceOnly = sourceOnly.length
|
|
229
|
+
? ` // No translated version of this section: serve the source language.
|
|
230
|
+
if (isSourceOnly(url.pathname)) return NextResponse.redirect(url);
|
|
231
|
+
`
|
|
232
|
+
: '';
|
|
233
|
+
const unprefixedSourceOnly = sourceOnly.length
|
|
234
|
+
? ` if (isSourceOnly(pathname)) {
|
|
235
|
+
const headers = new Headers(request.headers);
|
|
236
|
+
headers.set('${exports.LOCALE_HEADER}', sourceLocale);
|
|
237
|
+
return NextResponse.next({ request: { headers } });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
`
|
|
241
|
+
: '';
|
|
199
242
|
return `// ${PROXY_MARKER}
|
|
200
243
|
// Babelize regenerates this file while the line above is present. Remove that
|
|
201
244
|
// line to take it over (keep the ${exports.LOCALE_HEADER} header and the matcher).
|
|
@@ -203,7 +246,7 @@ import { NextResponse${ts ? ', type NextRequest' : ''} } from 'next/server';
|
|
|
203
246
|
import { locales, sourceLocale } from './i18n/locales';
|
|
204
247
|
|
|
205
248
|
const ONE_YEAR = 60 * 60 * 24 * 365;
|
|
206
|
-
|
|
249
|
+
${sourceOnlyDecl}
|
|
207
250
|
function localized(pathname${ts ? ': string' : ''}, locale${ts ? ': string' : ''}) {
|
|
208
251
|
if (locale === sourceLocale) return pathname;
|
|
209
252
|
return pathname === '/' ? \`/\${locale}\` : \`/\${locale}\${pathname}\`;
|
|
@@ -226,7 +269,7 @@ export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req
|
|
|
226
269
|
// /ja/docs is app/docs, in Japanese.
|
|
227
270
|
const url = request.nextUrl.clone();
|
|
228
271
|
url.pathname = \`/\${rest.join('/')}\`;
|
|
229
|
-
const headers = new Headers(request.headers);
|
|
272
|
+
${prefixedSourceOnly} const headers = new Headers(request.headers);
|
|
230
273
|
headers.set('${exports.LOCALE_HEADER}', prefixed);
|
|
231
274
|
const response = NextResponse.rewrite(url, { request: { headers } });
|
|
232
275
|
response.cookies.set('NEXT_LOCALE', prefixed, { path: '/', maxAge: ONE_YEAR, sameSite: 'lax' });
|
|
@@ -234,7 +277,7 @@ export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req
|
|
|
234
277
|
return response;
|
|
235
278
|
}
|
|
236
279
|
|
|
237
|
-
// An unprefixed URL is the source language, unless the visitor chose another.
|
|
280
|
+
${unprefixedSourceOnly} // An unprefixed URL is the source language, unless the visitor chose another.
|
|
238
281
|
const chosen = request.cookies.get('NEXT_LOCALE')?.value;
|
|
239
282
|
if (chosen && chosen !== sourceLocale && locales.includes(chosen)) {
|
|
240
283
|
const url = request.nextUrl.clone();
|
|
@@ -345,15 +388,29 @@ function nextMajor(packageJson) {
|
|
|
345
388
|
const m = typeof range === 'string' ? /(\d+)/.exec(range) : null;
|
|
346
389
|
return m ? Number(m[1]) : null;
|
|
347
390
|
}
|
|
348
|
-
/**
|
|
391
|
+
/**
|
|
392
|
+
* `routing` from .babelize/config.json: `"cookie"` keeps one URL for every
|
|
393
|
+
* language; `"prefix"` (default) or `{ "sourceOnly": ["/docs"] }` gives each
|
|
394
|
+
* language its own URL, except the listed sections.
|
|
395
|
+
*/
|
|
349
396
|
async function readRouting(workspacePath) {
|
|
397
|
+
let raw;
|
|
350
398
|
try {
|
|
351
|
-
|
|
352
|
-
return raw?.routing === 'cookie' ? 'cookie' : 'prefix';
|
|
399
|
+
raw = JSON.parse(await fs.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'))?.routing;
|
|
353
400
|
}
|
|
354
401
|
catch {
|
|
355
|
-
|
|
402
|
+
raw = undefined;
|
|
356
403
|
}
|
|
404
|
+
if (raw === 'cookie')
|
|
405
|
+
return { mode: 'cookie', sourceOnly: [] };
|
|
406
|
+
const list = raw && typeof raw === 'object' && Array.isArray(raw.sourceOnly)
|
|
407
|
+
? raw.sourceOnly
|
|
408
|
+
: [];
|
|
409
|
+
const sourceOnly = list
|
|
410
|
+
.filter((p) => typeof p === 'string' && p.trim().length > 0)
|
|
411
|
+
.map((p) => `/${p.trim().replace(/^\/+|\/+$/g, '')}`)
|
|
412
|
+
.filter((p) => p !== '/');
|
|
413
|
+
return { mode: 'prefix', sourceOnly: [...new Set(sourceOnly)] };
|
|
357
414
|
}
|
|
358
415
|
/** Wrap the next.config default export / module.exports with next-intl's plugin. */
|
|
359
416
|
function wrapNextConfig(content, requestConfigPath, typescript) {
|
|
@@ -515,7 +572,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
515
572
|
// the content's syntax always matches its extension and next.config points
|
|
516
573
|
// at a file that exists.
|
|
517
574
|
const requestDir = path.join(path.dirname(appDir), 'i18n');
|
|
518
|
-
const routing = await readRouting(workspace.path);
|
|
575
|
+
const { mode: routing, sourceOnly } = await readRouting(workspace.path);
|
|
519
576
|
const locales = await availableLocales(workspace, options);
|
|
520
577
|
const sourceLocale = options.sourceLocale ?? 'en';
|
|
521
578
|
// 0. i18n/locales — the locale list the request config, proxy and layout share.
|
|
@@ -591,7 +648,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
591
648
|
const proxyFile = existingProxy
|
|
592
649
|
?? path.join(proxyDir, `${(nextMajor(workspace.packageJson) ?? 16) >= 16 ? 'proxy' : 'middleware'}.${typescript ? 'ts' : 'js'}`);
|
|
593
650
|
const kind = path.basename(proxyFile).startsWith('proxy') ? 'proxy' : 'middleware';
|
|
594
|
-
const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile) });
|
|
651
|
+
const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile), sourceOnly });
|
|
595
652
|
if (content !== proxyContent) {
|
|
596
653
|
await writer.write(proxyFile, content);
|
|
597
654
|
configFileCreated = true;
|
|
@@ -355,7 +355,11 @@ function addLabelMaps(plan, keys, isTypeScript, usedNames) {
|
|
|
355
355
|
const init = scope.getBinding(existing)?.path.node;
|
|
356
356
|
if (ast_helpers_1.t.isVariableDeclarator(init) && ast_helpers_1.t.isObjectExpression(init.init)) {
|
|
357
357
|
const obj = init.init;
|
|
358
|
-
|
|
358
|
+
// Formatters unquote keys that are valid identifiers (`"English": …` → `English: …`).
|
|
359
|
+
const has = new Set(obj.properties.flatMap((p) => !ast_helpers_1.t.isObjectProperty(p) || p.computed ? []
|
|
360
|
+
: ast_helpers_1.t.isStringLiteral(p.key) ? [p.key.value]
|
|
361
|
+
: ast_helpers_1.t.isIdentifier(p.key) ? [p.key.name]
|
|
362
|
+
: []));
|
|
359
363
|
for (const [value, key] of values) {
|
|
360
364
|
if (!has.has(value))
|
|
361
365
|
obj.properties.push(ast_helpers_1.t.objectProperty(ast_helpers_1.t.stringLiteral(value), ast_helpers_1.t.stringLiteral(key)));
|
|
@@ -35,6 +35,8 @@ exports.FALLBACK_QA_WARNING = 'translated with the backup translator; will be re
|
|
|
35
35
|
/** Keys re-sent after failing validation go in small batches with per-key notes. */
|
|
36
36
|
const REPAIR_BATCH_SIZE = 5;
|
|
37
37
|
const TRANSLATE_CONCURRENCY = 3; // Max concurrent locales/batches
|
|
38
|
+
/** Fragments of placeholder tokens ([#VAR_0#], the translator's {#0}) left in a translation. */
|
|
39
|
+
const PLACEHOLDER_DEBRIS = /\[#|#\]|\[\{#|\{#\d+\}|#VAR_\d+/;
|
|
38
40
|
/**
|
|
39
41
|
* ICU branches sent to a plain-text translator go in requests of up to this
|
|
40
42
|
* many sentences (the translator service's batch limit).
|
|
@@ -748,6 +750,12 @@ configuredFormality) {
|
|
|
748
750
|
// ("eng_Latn"), which the sanitizer strips to nothing: no translation.
|
|
749
751
|
if (!value.trim())
|
|
750
752
|
return fail('empty_value', true, 'The translator returned no usable text');
|
|
753
|
+
// A token mangled on the way back ("[{#0} ダーク") survives restoring:
|
|
754
|
+
// never write placeholder debris the source doesn't have.
|
|
755
|
+
const debris = PLACEHOLDER_DEBRIS.exec(value)?.[0];
|
|
756
|
+
if (debris && !entry.value.includes(debris)) {
|
|
757
|
+
return fail('placeholder_lost', true, `Placeholder problem: leftover token fragment "${debris}"`);
|
|
758
|
+
}
|
|
751
759
|
const warnings = [];
|
|
752
760
|
// A plural added for a count placeholder is validated as ICU too.
|
|
753
761
|
if (entry.icu || (0, icu_message_1.isIcuMessage)(value)) {
|
package/package.json
CHANGED