@babelize/engine 0.3.8 → 0.3.10

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.
@@ -33,8 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.NEXT_INTL_DEPENDENCIES = void 0;
36
+ exports.LOCALE_HEADER = exports.NEXT_INTL_DEPENDENCIES = void 0;
37
+ exports.buildLocalesModule = buildLocalesModule;
37
38
  exports.buildRequestConfig = buildRequestConfig;
39
+ exports.buildProxy = buildProxy;
40
+ exports.setHtmlLocale = setHtmlLocale;
41
+ exports.nextMajor = nextMajor;
38
42
  exports.wrapNextConfig = wrapNextConfig;
39
43
  exports.usesCacheComponents = usesCacheComponents;
40
44
  exports.wrapRootLayout = wrapRootLayout;
@@ -44,16 +48,24 @@ const path = __importStar(require("path"));
44
48
  const file_utils_1 = require("../../utils/file-utils");
45
49
  const writes_1 = require("./writes");
46
50
  const ast_helpers_1 = require("../../utils/ast-helpers");
51
+ const rtl_languages_1 = require("../translator/language-codes/rtl-languages");
47
52
  /**
48
53
  * Next.js finalization for next-intl.
49
54
  *
50
55
  * Injection rewrites Next.js components to next-intl (`getTranslations` in
51
56
  * Server Components, `useTranslations` in Client Components — see
52
57
  * NextIntlStrategy), so the project must be wired for next-intl or every
53
- * page throws at runtime. This sets up next-intl's "without i18n routing"
54
- * mode: the locale comes from a NEXT_LOCALE cookie or the browser's
55
- * Accept-Language header, and messages are the generated
56
- * `public/locales/<locale>.json` files. URLs don't change.
58
+ * page throws at runtime. Each language gets its own URL without moving any
59
+ * route (#380): a generated proxy (middleware before Next 16) serves
60
+ * `/ja/docs` from the existing `app/docs` route and tells next-intl the
61
+ * locale in a request header. The source language stays unprefixed, a
62
+ * NEXT_LOCALE cookie remembers a visitor's choice, and every page announces
63
+ * its translations to search engines with hreflang `Link` headers. The root
64
+ * layout's <html> gets the locale's `lang` and `dir`. Messages are the
65
+ * generated `public/locales/<locale>.json` files.
66
+ *
67
+ * `"routing": "cookie"` in .babelize/config.json keeps one URL for every
68
+ * language (the locale comes from the cookie or Accept-Language).
57
69
  *
58
70
  * Every edit is a minimal text splice (the user's formatting is kept), and
59
71
  * anything that can't be wired automatically becomes a warning — never a
@@ -63,6 +75,11 @@ exports.NEXT_INTL_DEPENDENCIES = {
63
75
  'next-intl': '^4.0.0',
64
76
  };
65
77
  const GENERATED_MARKER = '@babelize-generated next-intl request config';
78
+ const LOCALES_MARKER = '@babelize-generated locale list';
79
+ const PROXY_MARKER = '@babelize-generated locale routing';
80
+ /** Request header the proxy sets with the URL's locale. */
81
+ exports.LOCALE_HEADER = 'x-babelize-locale';
82
+ const PROXY_FILES = ['proxy.ts', 'proxy.js', 'middleware.ts', 'middleware.js'];
66
83
  const NEXT_CONFIG_FILES = ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs'];
67
84
  const LAYOUT_FILES = ['layout.tsx', 'layout.jsx', 'layout.js', 'layout.ts'];
68
85
  function applySplices(content, splices) {
@@ -99,18 +116,52 @@ async function findFirst(dir, names) {
99
116
  }
100
117
  return null;
101
118
  }
119
+ /** `sourceLocale` first, then the rest, without duplicates. */
120
+ function orderedLocales(sourceLocale, locales) {
121
+ return [sourceLocale, ...new Set(locales.filter((l) => l !== sourceLocale))];
122
+ }
123
+ /**
124
+ * `i18n/locales`: the locale list and text direction, shared by the request
125
+ * config, the proxy and the root layout. Plain data, safe to import anywhere.
126
+ */
127
+ function buildLocalesModule(opts) {
128
+ const locales = orderedLocales(opts.sourceLocale, opts.locales);
129
+ const rtl = locales.filter(rtl_languages_1.isRTL);
130
+ const ts = opts.typescript;
131
+ return `// ${LOCALES_MARKER}
132
+ // Babelize regenerates this file while the line above is present.
133
+ export const sourceLocale = ${JSON.stringify(opts.sourceLocale)};
134
+ export const locales = ${JSON.stringify(locales)}${ts ? ' as string[]' : ''};
135
+
136
+ const rightToLeft = ${JSON.stringify(rtl)}${ts ? ' as string[]' : ''};
137
+
138
+ /** \`dir\` for <html>: right-to-left scripts (Arabic, Hebrew, Persian, Urdu…). */
139
+ export function localeDirection(locale${ts ? ': string' : ''})${ts ? ": 'rtl' | 'ltr'" : ''} {
140
+ return rightToLeft.includes(locale) ? 'rtl' : 'ltr';
141
+ }
142
+ `;
143
+ }
102
144
  function buildRequestConfig(opts) {
103
- const locales = [opts.sourceLocale, ...opts.locales.filter((l) => l !== opts.sourceLocale)];
104
145
  const ts = opts.typescript;
105
146
  const importPath = opts.messagesImportPath.replace('__LOCALE__', '${locale}');
147
+ const routed = opts.routing === 'prefix'
148
+ ? ` // The URL's language (/ja/…), from the locale proxy.
149
+ const routed = requestHeaders.get('${exports.LOCALE_HEADER}');
150
+ if (routed && locales.includes(routed)) return { locale: routed, messages: await messagesFor(routed) };
151
+ `
152
+ : '';
106
153
  return `// ${GENERATED_MARKER}
107
154
  // Babelize regenerates this file (to update the locale list) while the line
108
155
  // above is present. Remove that line to take it over.
109
156
  import { getRequestConfig } from 'next-intl/server';
110
157
  import { cookies, headers } from 'next/headers';
158
+ import { locales, sourceLocale } from './locales';
111
159
 
112
- export const sourceLocale = ${JSON.stringify(opts.sourceLocale)};
113
- export const locales = ${JSON.stringify(locales)};
160
+ export { locales, sourceLocale };
161
+
162
+ async function messagesFor(locale${ts ? ': string' : ''}) {
163
+ return (await import(\`${importPath}\`)).default;
164
+ }
114
165
 
115
166
  function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ? ': string' : ''} {
116
167
  for (const candidate of candidates) {
@@ -125,19 +176,185 @@ function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ?
125
176
  }
126
177
 
127
178
  export default getRequestConfig(async () => {
128
- // Locale preference: the NEXT_LOCALE cookie, then the browser's Accept-Language.
179
+ const requestHeaders = await headers();
180
+ ${routed} // Otherwise the NEXT_LOCALE cookie, then the browser's Accept-Language.
129
181
  const cookieLocale = (await cookies()).get('NEXT_LOCALE')?.value;
130
- const acceptLanguage = ((await headers()).get('accept-language') ?? '')
182
+ const acceptLanguage = (requestHeaders.get('accept-language') ?? '')
131
183
  .split(',')
132
184
  .map((part) => part.split(';')[0].trim());
133
185
  const locale = pickLocale([cookieLocale, ...acceptLanguage]);
134
- return {
135
- locale,
136
- messages: (await import(\`${importPath}\`)).default,
137
- };
186
+ return { locale, messages: await messagesFor(locale) };
138
187
  });
139
188
  `;
140
189
  }
190
+ /**
191
+ * The locale proxy (#380): `/ja/docs` is served by `app/docs` with the
192
+ * locale in a request header; the source language has no prefix. A visitor
193
+ * who picked a language (NEXT_LOCALE cookie) is sent to its URL. Every page
194
+ * lists its translations in hreflang `Link` headers.
195
+ */
196
+ function buildProxy(opts) {
197
+ const ts = opts.typescript;
198
+ const req = ts ? 'request: NextRequest' : 'request';
199
+ return `// ${PROXY_MARKER}
200
+ // Babelize regenerates this file while the line above is present. Remove that
201
+ // line to take it over (keep the ${exports.LOCALE_HEADER} header and the matcher).
202
+ import { NextResponse${ts ? ', type NextRequest' : ''} } from 'next/server';
203
+ import { locales, sourceLocale } from './i18n/locales';
204
+
205
+ const ONE_YEAR = 60 * 60 * 24 * 365;
206
+
207
+ function localized(pathname${ts ? ': string' : ''}, locale${ts ? ': string' : ''}) {
208
+ if (locale === sourceLocale) return pathname;
209
+ return pathname === '/' ? \`/\${locale}\` : \`/\${locale}\${pathname}\`;
210
+ }
211
+
212
+ /** hreflang alternates for search engines, as an HTTP Link header. */
213
+ function alternates(${req}, pathname${ts ? ': string' : ''}) {
214
+ const origin = request.nextUrl.origin;
215
+ const links = locales.map((l) => \`<\${origin}\${localized(pathname, l)}>; rel="alternate"; hreflang="\${l}"\`);
216
+ links.push(\`<\${origin}\${pathname}>; rel="alternate"; hreflang="x-default"\`);
217
+ return links.join(', ');
218
+ }
219
+
220
+ export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req}) {
221
+ const { pathname } = request.nextUrl;
222
+ const [, first = '', ...rest] = pathname.split('/');
223
+ const prefixed = locales.find((l) => l !== sourceLocale && l.toLowerCase() === first.toLowerCase());
224
+
225
+ if (prefixed) {
226
+ // /ja/docs is app/docs, in Japanese.
227
+ const url = request.nextUrl.clone();
228
+ url.pathname = \`/\${rest.join('/')}\`;
229
+ const headers = new Headers(request.headers);
230
+ headers.set('${exports.LOCALE_HEADER}', prefixed);
231
+ const response = NextResponse.rewrite(url, { request: { headers } });
232
+ response.cookies.set('NEXT_LOCALE', prefixed, { path: '/', maxAge: ONE_YEAR, sameSite: 'lax' });
233
+ response.headers.set('Link', alternates(request, url.pathname));
234
+ return response;
235
+ }
236
+
237
+ // An unprefixed URL is the source language, unless the visitor chose another.
238
+ const chosen = request.cookies.get('NEXT_LOCALE')?.value;
239
+ if (chosen && chosen !== sourceLocale && locales.includes(chosen)) {
240
+ const url = request.nextUrl.clone();
241
+ url.pathname = localized(pathname, chosen);
242
+ return NextResponse.redirect(url);
243
+ }
244
+
245
+ const headers = new Headers(request.headers);
246
+ headers.set('${exports.LOCALE_HEADER}', sourceLocale);
247
+ const response = NextResponse.next({ request: { headers } });
248
+ response.headers.set('Link', alternates(request, pathname));
249
+ return response;
250
+ }
251
+
252
+ export const config = {
253
+ // Pages only: not API routes, Next.js internals or files (anything with a dot).
254
+ matcher: ['/((?!api|trpc|_next|_vercel|.*\\\\..*).*)'],
255
+ };
256
+ `;
257
+ }
258
+ /**
259
+ * Give the root layout's <html> the active locale's `lang` and `dir`
260
+ * (#380): `const locale = useLocale()` in the default-exported layout
261
+ * (`await getLocale()` when it is already async). Null when the layout's shape isn't one this
262
+ * can edit safely (no <html>, an expression-bodied arrow, no default export).
263
+ */
264
+ function setHtmlLocale(content, typescript, localesImport) {
265
+ if (/\blocaleDirection\(/.test(content))
266
+ return content;
267
+ let ast;
268
+ try {
269
+ ast = (0, ast_helpers_1.parseCode)(content, { isTypeScript: typescript });
270
+ }
271
+ catch {
272
+ return null;
273
+ }
274
+ let fn = null;
275
+ for (const node of ast.program.body) {
276
+ if (!ast_helpers_1.t.isExportDefaultDeclaration(node))
277
+ continue;
278
+ const decl = node.declaration;
279
+ if (ast_helpers_1.t.isFunctionDeclaration(decl) || ast_helpers_1.t.isFunctionExpression(decl) || ast_helpers_1.t.isArrowFunctionExpression(decl))
280
+ fn = decl;
281
+ else if (ast_helpers_1.t.isIdentifier(decl)) {
282
+ for (const other of ast.program.body) {
283
+ if (ast_helpers_1.t.isFunctionDeclaration(other) && other.id?.name === decl.name)
284
+ fn = other;
285
+ if (ast_helpers_1.t.isVariableDeclaration(other)) {
286
+ for (const d of other.declarations) {
287
+ if (ast_helpers_1.t.isIdentifier(d.id, { name: decl.name }) && (ast_helpers_1.t.isArrowFunctionExpression(d.init) || ast_helpers_1.t.isFunctionExpression(d.init)))
288
+ fn = d.init;
289
+ }
290
+ }
291
+ }
292
+ }
293
+ }
294
+ if (!fn || !ast_helpers_1.t.isBlockStatement(fn.body) || fn.body.start == null || fn.start == null)
295
+ return null;
296
+ let html = null;
297
+ (0, ast_helpers_1.traverse)(ast, {
298
+ JSXOpeningElement(p) {
299
+ if (ast_helpers_1.t.isJSXIdentifier(p.node.name, { name: 'html' })) {
300
+ html = p.node;
301
+ p.stop();
302
+ }
303
+ },
304
+ });
305
+ const opening = html;
306
+ if (!opening || opening.name.end == null)
307
+ return null;
308
+ // A sync layout stays sync: it may call useTranslations(), which next-intl
309
+ // forbids in async components. useLocale() works in sync Server Components.
310
+ const read = fn.async
311
+ ? { importLine: `import { getLocale } from 'next-intl/server';`, call: 'await getLocale()' }
312
+ : { importLine: `import { useLocale } from 'next-intl';`, call: 'useLocale()' };
313
+ // `useLocale` joins an existing `import { … } from 'next-intl'` (the provider's) rather than a second line.
314
+ const source = fn.async ? 'next-intl/server' : 'next-intl';
315
+ const named = fn.async ? 'getLocale' : 'useLocale';
316
+ const existing = ast.program.body.find((n) => ast_helpers_1.t.isImportDeclaration(n) && n.source.value === source && n.importKind !== 'type' &&
317
+ n.specifiers.length > 0 && n.specifiers.every((sp) => ast_helpers_1.t.isImportSpecifier(sp)));
318
+ const lastSpecifier = existing?.specifiers[existing.specifiers.length - 1];
319
+ const imports = [
320
+ ...(lastSpecifier ? [] : [read.importLine]),
321
+ `import { localeDirection } from ${JSON.stringify(localesImport)};`,
322
+ ].join('\n');
323
+ const splices = [
324
+ ...(lastSpecifier?.end != null ? [{ at: lastSpecifier.end, insert: `, ${named}` }] : []),
325
+ insertTopLevel(ast, imports),
326
+ { at: fn.body.start + 1, insert: `\n const locale = ${read.call};` },
327
+ ];
328
+ // New attributes go after the existing ones: <html lang={locale} dir={…}>.
329
+ const lastAttr = opening.attributes[opening.attributes.length - 1];
330
+ const appendAt = lastAttr?.end ?? opening.name.end;
331
+ for (const [name, value] of [['lang', '{locale}'], ['dir', '{localeDirection(locale)}']]) {
332
+ const attr = opening.attributes.find((a) => ast_helpers_1.t.isJSXAttribute(a) && ast_helpers_1.t.isJSXIdentifier(a.name, { name }));
333
+ if (attr?.value && attr.value.start != null && attr.value.end != null) {
334
+ splices.push({ at: attr.value.start, remove: attr.value.end - attr.value.start, insert: value });
335
+ }
336
+ else if (!attr) {
337
+ splices.push({ at: appendAt, insert: ` ${name}=${value}` });
338
+ }
339
+ }
340
+ return applySplices(content, splices);
341
+ }
342
+ /** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
343
+ function nextMajor(packageJson) {
344
+ const range = packageJson?.dependencies?.next ?? packageJson?.devDependencies?.next;
345
+ const m = typeof range === 'string' ? /(\d+)/.exec(range) : null;
346
+ return m ? Number(m[1]) : null;
347
+ }
348
+ /** `routing` from .babelize/config.json: `cookie` opts out of locale URLs. */
349
+ async function readRouting(workspacePath) {
350
+ try {
351
+ const raw = JSON.parse(await fs.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'));
352
+ return raw?.routing === 'cookie' ? 'cookie' : 'prefix';
353
+ }
354
+ catch {
355
+ return 'prefix';
356
+ }
357
+ }
141
358
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
142
359
  function wrapNextConfig(content, requestConfigPath, typescript) {
143
360
  if (content.includes('next-intl/plugin'))
@@ -298,6 +515,24 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
298
515
  // the content's syntax always matches its extension and next.config points
299
516
  // at a file that exists.
300
517
  const requestDir = path.join(path.dirname(appDir), 'i18n');
518
+ const routing = await readRouting(workspace.path);
519
+ const locales = await availableLocales(workspace, options);
520
+ const sourceLocale = options.sourceLocale ?? 'en';
521
+ // 0. i18n/locales — the locale list the request config, proxy and layout share.
522
+ const localesFile = (await findFirst(requestDir, ['locales.ts', 'locales.js'])) ?? path.join(requestDir, `locales.${typescript ? 'ts' : 'js'}`);
523
+ const localesContent = await (0, file_utils_1.readFile)(localesFile).catch(() => null);
524
+ const ownsLocales = localesContent === null || localesContent.includes(LOCALES_MARKER);
525
+ if (!ownsLocales) {
526
+ warnings.push(`${toPosix(path.relative(root, localesFile))} already exists and was not generated by Babelize; left untouched. ` +
527
+ 'It must export sourceLocale, locales and localeDirection(locale).');
528
+ }
529
+ else {
530
+ const content = buildLocalesModule({ sourceLocale, locales, typescript: /\.ts$/.test(localesFile) });
531
+ if (content !== localesContent) {
532
+ await writer.write(localesFile, content);
533
+ configFileCreated = true;
534
+ }
535
+ }
301
536
  const existingRequest = await findFirst(requestDir, ['request.ts', 'request.tsx', 'request.js', 'request.jsx', 'request.mjs']);
302
537
  const requestFile = existingRequest ?? path.join(requestDir, `request.${typescript ? 'ts' : 'js'}`);
303
538
  const requestIsTs = /\.tsx?$/.test(requestFile);
@@ -312,12 +547,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
312
547
  let messagesImportPath = toPosix(path.relative(requestDir, sampleLocale));
313
548
  if (!messagesImportPath.startsWith('.'))
314
549
  messagesImportPath = `./${messagesImportPath}`;
315
- const content = buildRequestConfig({
316
- sourceLocale: options.sourceLocale ?? 'en',
317
- locales: await availableLocales(workspace, options),
318
- messagesImportPath,
319
- typescript: requestIsTs,
320
- });
550
+ const content = buildRequestConfig({ sourceLocale, locales, messagesImportPath, typescript: requestIsTs, routing });
321
551
  if (content !== existingContent) {
322
552
  await writer.write(requestFile, content);
323
553
  configFileCreated = true;
@@ -346,14 +576,38 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
346
576
  configFileCreated = true;
347
577
  }
348
578
  }
349
- // 3. Root layout — NextIntlClientProvider so Client Components can use useTranslations().
579
+ // 3. proxy.ts (middleware.ts before Next 16) — a URL per language (#380).
580
+ if (routing === 'prefix') {
581
+ const proxyDir = path.dirname(appDir);
582
+ const existingProxy = await findFirst(proxyDir, PROXY_FILES);
583
+ const proxyContent = existingProxy ? await (0, file_utils_1.readFile)(existingProxy).catch(() => '') : null;
584
+ if (existingProxy && !proxyContent.includes(PROXY_MARKER)) {
585
+ warnings.push(`${toPosix(path.relative(root, existingProxy))} already exists, so locale URLs (/ja/…) were not set up. ` +
586
+ `Rewrite /<locale>/… to /… with the ${exports.LOCALE_HEADER} request header set to the locale (Babelize's generated proxy does this), ` +
587
+ 'or set "routing": "cookie" in .babelize/config.json to keep one URL for every language.');
588
+ }
589
+ else {
590
+ // Our earlier file keeps its name (middleware.ts still runs on Next 16).
591
+ const proxyFile = existingProxy
592
+ ?? path.join(proxyDir, `${(nextMajor(workspace.packageJson) ?? 16) >= 16 ? 'proxy' : 'middleware'}.${typescript ? 'ts' : 'js'}`);
593
+ const kind = path.basename(proxyFile).startsWith('proxy') ? 'proxy' : 'middleware';
594
+ const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile) });
595
+ if (content !== proxyContent) {
596
+ await writer.write(proxyFile, content);
597
+ configFileCreated = true;
598
+ }
599
+ }
600
+ }
601
+ // 4. Root layout — NextIntlClientProvider so Client Components can use
602
+ // useTranslations(), and <html lang dir> from the active locale.
350
603
  const layoutPath = await findFirst(appDir, LAYOUT_FILES);
351
604
  if (!layoutPath) {
352
605
  warnings.push('No root layout found in app/: wrap your app in <NextIntlClientProvider> from next-intl.');
353
606
  }
354
607
  else {
355
608
  const content = await (0, file_utils_1.readFile)(layoutPath);
356
- const wrapped = wrapRootLayout(content, /\.tsx?$/.test(layoutPath), { suspense: cacheComponents });
609
+ const layoutIsTs = /\.tsx?$/.test(layoutPath);
610
+ let wrapped = wrapRootLayout(content, layoutIsTs, { suspense: cacheComponents });
357
611
  const layoutName = toPosix(path.relative(root, layoutPath));
358
612
  if (cacheComponents && content.includes('NextIntlClientProvider') && !/<Suspense\b/.test(content)) {
359
613
  warnings.push(`next.config enables cacheComponents, and ${layoutName} renders NextIntlClientProvider outside <Suspense>. ` +
@@ -363,7 +617,24 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
363
617
  warnings.push(`Could not find {children} inside <body> in ${layoutName}: ` +
364
618
  'wrap it in <NextIntlClientProvider> from next-intl so Client Components can translate.');
365
619
  }
366
- else if (wrapped !== content) {
620
+ // Cache Components can't read the locale outside <Suspense>, and <html> can't be inside one.
621
+ if (ownsLocales && !cacheComponents) {
622
+ let localesImport = toPosix(path.relative(path.dirname(layoutPath), localesFile)).replace(/\.(t|j)s$/, '');
623
+ if (!localesImport.startsWith('.'))
624
+ localesImport = `./${localesImport}`;
625
+ const located = setHtmlLocale(wrapped ?? content, layoutIsTs, localesImport);
626
+ if (located === null) {
627
+ warnings.push(`Could not set <html lang> and dir in ${layoutName}: use \`lang={await getLocale()}\` (next-intl/server) and ` +
628
+ `dir={localeDirection(locale)} from ${localesImport}, or right-to-left languages render left-to-right.`);
629
+ }
630
+ else {
631
+ wrapped = located;
632
+ }
633
+ }
634
+ else if (cacheComponents && locales.some(rtl_languages_1.isRTL)) {
635
+ warnings.push(`${layoutName}: set <html lang> and dir from the locale yourself (Cache Components is on); right-to-left languages need dir="rtl".`);
636
+ }
637
+ if (wrapped !== null && wrapped !== content) {
367
638
  await writer.write(layoutPath, wrapped);
368
639
  entryPointModified = true;
369
640
  }
@@ -43,6 +43,7 @@ const file_utils_1 = require("../../utils/file-utils");
43
43
  const types_1 = require("../../runtime/types");
44
44
  const StrategyFactory_1 = require("../../injection/StrategyFactory");
45
45
  const generator_1 = require("@babel/generator");
46
+ const source_scope_1 = require("../../utils/source-scope");
46
47
  /** The local name of `import X from 'i18next'` in a file, if it has one. */
47
48
  function i18nextDefaultImport(ast) {
48
49
  for (const node of ast.program.body) {
@@ -91,7 +92,7 @@ async function injectFormats(workspace, formatStrings, formatConfig, dryRun = fa
91
92
  const sourceFiles = [];
92
93
  for (const sourceDir of workspace.sourceDirs) {
93
94
  const dirPath = path.join(workspace.path, sourceDir);
94
- const files = await (0, file_utils_1.findFiles)(dirPath, types_1.SUPPORTED_EXTENSIONS, (0, types_1.workspaceExcludes)(workspace));
95
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, types_1.SUPPORTED_EXTENSIONS, (0, types_1.workspaceExcludes)(workspace)));
95
96
  sourceFiles.push(...files);
96
97
  }
97
98
  // Build a lookup of format strings by (relative file path, line)
@@ -225,7 +226,7 @@ async function injectFormats(workspace, formatStrings, formatConfig, dryRun = fa
225
226
  const htmlExtensions = ['.html', '.htm'];
226
227
  for (const sourceDir of workspace.sourceDirs) {
227
228
  const dirPath = path.join(workspace.path, sourceDir);
228
- const files = await (0, file_utils_1.findFiles)(dirPath, htmlExtensions, (0, types_1.workspaceExcludes)(workspace));
229
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, htmlExtensions, (0, types_1.workspaceExcludes)(workspace)));
229
230
  for (const filePath of files) {
230
231
  const relativePath = (0, file_utils_1.getRelativePath)(workspace.path, filePath);
231
232
  const fileStrings = stringsByFile.get(relativePath);
@@ -49,6 +49,7 @@ const file_utils_1 = require("../../utils/file-utils");
49
49
  const i18n_config_path_1 = require("../../utils/i18n-config-path");
50
50
  const i18next_icu_1 = require("../../utils/i18next-icu");
51
51
  const string_utils_1 = require("../../utils/string-utils");
52
+ const source_scope_1 = require("../../utils/source-scope");
52
53
  const ast_helpers_1 = require("../../utils/ast-helpers");
53
54
  /**
54
55
  * An arrow function that defines a component: assigned to a capitalized name
@@ -414,7 +415,7 @@ positions) {
414
415
  const sourceFiles = [];
415
416
  for (const sourceDir of workspace.sourceDirs) {
416
417
  const dirPath = path.join(workspace.path, sourceDir);
417
- const files = await (0, file_utils_1.findFiles)(dirPath, extensions, (0, types_2.workspaceExcludes)(workspace));
418
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, extensions, (0, types_2.workspaceExcludes)(workspace)));
418
419
  sourceFiles.push(...files);
419
420
  }
420
421
  // react-i18next projects get Babelize's config, which exports a module-level
@@ -43,6 +43,7 @@ const types_1 = require("../../runtime/types");
43
43
  const types_2 = require("@babelize/types");
44
44
  const extraction_options_1 = require("../../utils/extraction-options");
45
45
  const validate_1 = require("../workspace/validate");
46
+ const source_scope_1 = require("../../utils/source-scope");
46
47
  /**
47
48
  * Extraction options the project's engine runs use (sentence grouping, ICU
48
49
  * plurals, data-literal rules), so a sync check compares like with like and
@@ -148,9 +149,11 @@ async function detectSyncIssues(projectId, workspacePath, changedFiles, commitSh
148
149
  // 1. Filter changed files to only source files
149
150
  const extractOptions = await runExtractionOptions(workspacePath, options);
150
151
  const frameworkExcludes = types_2.FRAMEWORK_CONFIGS[extractOptions.framework]?.excludedPatterns ?? [];
152
+ // Files outside the project's include/exclude are never translated, so changing them can't drift.
153
+ const inScope = (0, source_scope_1.createScopeMatcher)(await (0, source_scope_1.readSourceScope)(workspacePath));
151
154
  const sourceFiles = [];
152
155
  for (const file of changedFiles) {
153
- if (isSourceFile(file, frameworkExcludes)) {
156
+ if (isSourceFile(file, frameworkExcludes) && inScope(file)) {
154
157
  sourceFiles.push(file);
155
158
  }
156
159
  else {
@@ -16,6 +16,7 @@ const placeholder_protection_1 = require("../../utils/placeholder-protection");
16
16
  const icu_message_1 = require("../../utils/icu-message");
17
17
  const keygen_1 = require("../keygen");
18
18
  const concurrent_map_1 = require("../../utils/concurrent-map");
19
+ const endonyms_1 = require("../../utils/endonyms");
19
20
  const language_codes_1 = require("./language-codes");
20
21
  const glossary_1 = require("../glossary");
21
22
  const check_project_1 = require("../../qa/check-project");
@@ -674,6 +675,13 @@ configuredFormality) {
674
675
  const countArgs = options.targetPlurals && !icu && (isLlm || (0, icu_branches_1.targetCategories)(targetLocale, 'cardinal').length > 1)
675
676
  ? (0, icu_message_1.countArguments)(entry.value)
676
677
  : [];
678
+ if ((0, endonyms_1.isEndonym)(entry.value)) {
679
+ // A language's own name ("Deutsch", "日本語") stays as written: language
680
+ // pickers list them so every visitor finds their language.
681
+ result[entry.key] = entry.value;
682
+ metadata[entry.key] = { ...(metadata[entry.key] ?? {}), passthrough: true, endonym: true };
683
+ continue;
684
+ }
677
685
  const ownTokens = (0, placeholder_protection_1.protectText)(entry.value, neverTranslateTerms);
678
686
  if ((0, placeholder_protection_1.hasNothingToTranslate)(ownTokens.text)) {
679
687
  result[entry.key] = entry.value;
@@ -49,6 +49,7 @@ const stack_1 = require("../../detection/stack");
49
49
  const django_finalize_1 = require("../finalization/django-finalize");
50
50
  const locale_names_1 = require("../../django/locale-names");
51
51
  const existing_setup_1 = require("./existing-setup");
52
+ const source_scope_1 = require("../../utils/source-scope");
52
53
  const PY_IGNORE = ['**/node_modules/**', '**/.venv/**', '**/venv/**', '**/site-packages/**', '**/.git/**'];
53
54
  /**
54
55
  * The Django project root (directory of the shallowest manage.py), relative
@@ -252,6 +253,11 @@ async function validateWorkspace(config) {
252
253
  }
253
254
  const babelizeDir = path.join(workspacePath, '.babelize');
254
255
  await (0, file_utils_1.ensureDir)(babelizeDir);
256
+ // The project's include/exclude (#378): a published library's components,
257
+ // its CLI or fixtures stay untouched while the app around them is localized.
258
+ const sourceScope = (0, source_scope_1.mergeSourceScope)(await (0, source_scope_1.readSourceScope)(workspacePath), config.sourceScope);
259
+ if ((0, source_scope_1.hasSourceScope)(sourceScope))
260
+ logger_1.engineLogger.info('Limiting the run to the configured source scope', { ...sourceScope });
255
261
  const workspace = {
256
262
  path: workspacePath,
257
263
  framework,
@@ -262,6 +268,7 @@ async function validateWorkspace(config) {
262
268
  publicDir,
263
269
  ...(appDir !== '.' ? { appDir } : {}),
264
270
  ...(frameworkConfig.excludedPatterns ? { excludedPatterns: frameworkConfig.excludedPatterns } : {}),
271
+ ...((0, source_scope_1.hasSourceScope)(sourceScope) ? { sourceScope } : {}),
265
272
  packageJson: (packageJson ?? {}),
266
273
  formatConfig: config.formatConfig,
267
274
  ...(framework === 'django' ? { djangoRoot: djangoRoot ?? '.' } : {}),
@@ -9,6 +9,7 @@ import type { ByokProvider, FormatLocaleConfig, Framework } from '@babelize/type
9
9
  import type { EngineProviders, TranslationFailure } from '../providers/types';
10
10
  import type { EngineLogger } from '../utils/logger';
11
11
  import type { I18nLibraryId } from '../detection/i18n';
12
+ import type { SourceScope } from '../utils/source-scope';
12
13
  export interface EngineConfigV2 {
13
14
  /** Path to the workspace directory */
14
15
  workspacePath: string;
@@ -26,6 +27,11 @@ export interface EngineConfigV2 {
26
27
  dryRun: boolean;
27
28
  /** Force translation even if locale files exist */
28
29
  forceTranslation?: boolean;
30
+ /**
31
+ * Source files this run may extract from and rewrite. Each list given
32
+ * replaces the same list in `.babelize/config.json` (`--include`/`--exclude`).
33
+ */
34
+ sourceScope?: SourceScope;
29
35
  /**
30
36
  * Most (key, locale) pairs this run may send to the translator: the
31
37
  * caller's credit budget. Pairs past it are left untranslated (not in the
@@ -126,6 +132,8 @@ export interface WorkspaceInfo {
126
132
  appDir?: string;
127
133
  /** Framework-specific scan exclusions (FrameworkConfig.excludedPatterns); see workspaceExcludes(). */
128
134
  excludedPatterns?: readonly string[];
135
+ /** The project's `include`/`exclude` globs (config.json, or the run's override); see filterToScope(). */
136
+ sourceScope?: SourceScope;
129
137
  packageJson?: Record<string, any>;
130
138
  /** Output locale file format (e.g., 'json' for React, 'po' for Django) */
131
139
  localeFormat: 'json' | 'po' | 'arb';
@@ -831,6 +831,35 @@ function getParentContext(path) {
831
831
  siblingGroupId: Math.abs(hash).toString(36),
832
832
  };
833
833
  }
834
+ /**
835
+ * A readable placeholder for an interpolated value, so translators and
836
+ * reviewers see `{locale}` rather than `{var1}` (#379): the identifier or
837
+ * property, or for a call the function's subject (`getLocaleLabel(l)` →
838
+ * `localeLabel`, `format(price)` → `price`).
839
+ */
840
+ function placeholderName(expr) {
841
+ if (t.isIdentifier(expr))
842
+ return expr.name;
843
+ if ((t.isMemberExpression(expr) || t.isOptionalMemberExpression(expr)) && t.isIdentifier(expr.property) && !expr.computed)
844
+ return expr.property.name;
845
+ if (t.isCallExpression(expr) || t.isOptionalCallExpression(expr)) {
846
+ const callee = expr.callee;
847
+ const arg = expr.arguments[0];
848
+ const method = (t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) && t.isIdentifier(callee.property) ? callee.property.name : null;
849
+ const fn = t.isIdentifier(callee) ? callee.name : method;
850
+ const subject = fn?.replace(/^(?:get|format|render|compute)(?=[A-Z])/, '');
851
+ if (subject && subject !== fn)
852
+ return subject[0].toLowerCase() + subject.slice(1);
853
+ // `fmt.format(price)` names its argument; `count.toFixed(1)` or `name.trim()` its receiver.
854
+ if (method && method !== 'format')
855
+ return placeholderName(callee.object);
856
+ if (arg)
857
+ return placeholderName(arg);
858
+ }
859
+ if (t.isTSAsExpression(expr) || t.isTSNonNullExpression(expr))
860
+ return placeholderName(expr.expression);
861
+ return null;
862
+ }
834
863
  /**
835
864
  * A string-building expression as one message: `\`Hi ${user.name}\`` and
836
865
  * `'Hi ' + name` → "Hi {name}". `variables` receives the placeholder names
@@ -844,9 +873,7 @@ function extractExpressionContent(node, variables = [], expressions = []) {
844
873
  let result = '';
845
874
  const quasis = node.quasis;
846
875
  const exprs = node.expressions;
847
- const nameOf = (expr) => t.isIdentifier(expr) ? expr.name
848
- : t.isMemberExpression(expr) && t.isIdentifier(expr.property) ? expr.property.name
849
- : `var${variables.length}`;
876
+ const nameOf = (expr) => placeholderName(expr) ?? `var${variables.length}`;
850
877
  for (let i = 0; i < quasis.length; i++) {
851
878
  // The text as it runs (`\n` is a line break), not as it's escaped in the source.
852
879
  result += quasis[i].value.cooked ?? quasis[i].value.raw;
@@ -872,7 +899,11 @@ function extractExpressionContent(node, variables = [], expressions = []) {
872
899
  + `{${name}, plural, one {${hash}${word[1]}${suffix.one}} other {${hash}${word[1]}${suffix.other}}}`;
873
900
  continue;
874
901
  }
875
- const varName = nameOf(expr);
902
+ // Two different values never share a placeholder: `${a.name} and ${b.name}` → {name}, {name2}.
903
+ let varName = nameOf(expr);
904
+ const base = varName;
905
+ for (let n = 2; variables.some((v, j) => v === varName && !t.isNodesEquivalent(expressions[j], expr)); n++)
906
+ varName = `${base}${n}`;
876
907
  variables.push(varName);
877
908
  expressions.push(expr);
878
909
  result += `{${varName}}`;
@@ -0,0 +1,2 @@
1
+ /** True when `text` is exactly some language's own name, in any letter case. */
2
+ export declare function isEndonym(text: string): boolean;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isEndonym = isEndonym;
4
+ /**
5
+ * A language's name for itself ("Deutsch", "español", "日本語"). Language
6
+ * pickers list these on purpose so every visitor can find their own
7
+ * language; translating them ("Deutsch" → "ドイツ語") breaks the picker.
8
+ */
9
+ let endonyms = null;
10
+ /** Regional variants pickers commonly list besides the plain languages. */
11
+ const REGIONAL = ['pt-BR', 'pt-PT', 'zh-Hans', 'zh-Hant', 'zh-CN', 'zh-TW', 'es-419', 'es-MX', 'en-GB', 'en-US', 'fr-CA', 'sr-Latn'];
12
+ const normalize = (name) => name.trim().toLocaleLowerCase('und');
13
+ function build() {
14
+ const names = new Set();
15
+ const add = (code) => {
16
+ try {
17
+ const name = new Intl.DisplayNames([code], { type: 'language' }).of(code);
18
+ // An unknown code comes back as itself.
19
+ if (name && normalize(name) !== code.toLowerCase())
20
+ names.add(normalize(name));
21
+ }
22
+ catch {
23
+ // Not a valid tag in this runtime.
24
+ }
25
+ };
26
+ const letters = 'abcdefghijklmnopqrstuvwxyz';
27
+ for (const a of letters)
28
+ for (const b of letters)
29
+ add(a + b);
30
+ for (const code of REGIONAL)
31
+ add(code);
32
+ return names;
33
+ }
34
+ /** True when `text` is exactly some language's own name, in any letter case. */
35
+ function isEndonym(text) {
36
+ endonyms ?? (endonyms = build());
37
+ return endonyms.has(normalize(text));
38
+ }