@babelize/engine 0.3.4 → 0.3.5

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.
@@ -10,6 +10,12 @@ export interface ExtractOptions {
10
10
  plurals?: boolean;
11
11
  }
12
12
  export declare function extractStrings(workspace: WorkspaceInfo, filesToProcess?: string[], extractOptions?: ExtractOptions): Promise<Phase1Result>;
13
+ /**
14
+ * Next.js files that never render UI: App Router route handlers
15
+ * (`app/<segments>/route.ts`), Pages Router API routes (`pages/api/<file>`) and
16
+ * middleware / proxy at the app root.
17
+ */
18
+ export declare function isNextServerOnlyFile(filePath: string): boolean;
13
19
  export declare function extractStringsFromFile(content: string, filePath: string, detectFormats?: boolean, options?: {
14
20
  relaxComponentGuard?: boolean;
15
21
  framework?: string;
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.extractStrings = extractStrings;
37
+ exports.isNextServerOnlyFile = isNextServerOnlyFile;
37
38
  exports.extractStringsFromFile = extractStringsFromFile;
38
39
  const path = __importStar(require("path"));
39
40
  const types_1 = require("../../runtime/types");
@@ -116,12 +117,33 @@ function isBabelizeGenerated(content) {
116
117
  const head = content.slice(0, 500);
117
118
  return GENERATED_FILE_MARKERS.some((marker) => head.includes(marker));
118
119
  }
120
+ /**
121
+ * Next.js files that never render UI: App Router route handlers
122
+ * (`app/<segments>/route.ts`), Pages Router API routes (`pages/api/<file>`) and
123
+ * middleware / proxy at the app root.
124
+ */
125
+ function isNextServerOnlyFile(filePath) {
126
+ const segments = filePath.split(/[\\/]/).filter(Boolean);
127
+ const base = segments[segments.length - 1] ?? '';
128
+ const dirs = segments.slice(0, -1);
129
+ if (/^route\.[cm]?[jt]sx?$/.test(base) && dirs.includes('app'))
130
+ return true;
131
+ const pages = dirs.indexOf('pages');
132
+ if (pages !== -1 && dirs[pages + 1] === 'api')
133
+ return true;
134
+ // middleware.ts / proxy.ts (Next 16) sit next to app/, never inside a route or component folder.
135
+ return /^(?:middleware|proxy)\.[cm]?[jt]s$/.test(base) && !dirs.some((d) => d === 'app' || d === 'pages' || d === 'components');
136
+ }
119
137
  async function extractStringsFromFile(content, filePath, detectFormats, options) {
120
138
  // Files Babelize generated itself (i18n config, next-intl request config)
121
139
  // hold config values such as bindI18n: 'languageChanged loaded'. A re-run
122
140
  // used to extract those and inject t() into the i18n config, breaking it.
123
141
  if (isBabelizeGenerated(content))
124
142
  return { strings: [], warnings: [] };
143
+ // Next.js server-only code (route handlers, API routes, middleware) answers
144
+ // requests, not people: its strings are API messages and header values.
145
+ if (options?.framework === 'nextjs' && isNextServerOnlyFile(filePath))
146
+ return { strings: [], warnings: [] };
125
147
  // Django: gettext calls, translate tags and hardcoded text in templates/forms/models/views.
126
148
  if (options?.framework === 'django') {
127
149
  return (0, extract_1.extractDjangoFile)(content, filePath, { icu: options.plurals === true });
@@ -271,7 +271,8 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
271
271
  `Make sure it loads messages from ${toPosix(workspace.publicDir)}/locales/<locale>.json.`);
272
272
  }
273
273
  else {
274
- const sampleLocale = (0, file_utils_1.localeFilePath)(root, workspace.publicDir, 'json', '__LOCALE__').file;
274
+ // publicDir is relative to the workspace (apps/web/public in a monorepo), not the app.
275
+ const sampleLocale = (0, file_utils_1.localeFilePath)(workspace.path, workspace.publicDir, 'json', '__LOCALE__').file;
275
276
  let messagesImportPath = toPosix(path.relative(requestDir, sampleLocale));
276
277
  if (!messagesImportPath.startsWith('.'))
277
278
  messagesImportPath = `./${messagesImportPath}`;
@@ -238,6 +238,20 @@ 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
+ /**
242
+ * A translated string literal keeps the whitespace around its text, which
243
+ * the message itself leaves out: a mail body `Page: ${href}` followed by two
244
+ * line breaks becomes a template literal holding t(…) and the line breaks,
245
+ * not a bare t() call that drops them.
246
+ */
247
+ function keepEdgeWhitespace(original, call) {
248
+ const leading = original.match(/^\s*/)?.[0] ?? '';
249
+ const trailing = original.length > leading.length ? (original.match(/\s*$/)?.[0] ?? '') : '';
250
+ if (!leading && !trailing)
251
+ return call;
252
+ const quasi = (cooked, tail) => ast_helpers_1.t.templateElement({ cooked, raw: cooked.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') }, tail);
253
+ return ast_helpers_1.t.templateLiteral([quasi(leading, false), quasi(trailing, true)], [call]);
254
+ }
241
255
  /**
242
256
  * Replace a JSXText node with `{t(...)}` without changing the rendered
243
257
  * spacing. In JSX, whitespace at the edge of a text node is significant when
@@ -616,8 +630,9 @@ positions, options = {}) {
616
630
  return null;
617
631
  const names = [];
618
632
  const exprs = [];
619
- const text = (0, ast_helpers_1.extractExpressionContent)(path.node, names, exprs)?.trim();
620
- if (!text)
633
+ const full = (0, ast_helpers_1.extractExpressionContent)(path.node, names, exprs);
634
+ const text = full?.trim();
635
+ if (!full || !text)
621
636
  return null;
622
637
  const extractionId = `${filePath}:${path.node.loc?.start.line || 0}:${(0, string_utils_1.hashString)(text)}`;
623
638
  const key = keyMapping.get(extractionId);
@@ -633,7 +648,7 @@ positions, options = {}) {
633
648
  byName.set(names[i], exprs[i]);
634
649
  }
635
650
  if (byName.size === 0)
636
- return { key, values: null };
651
+ return { key, values: null, full };
637
652
  const props = [...byName].map(([name, expr]) => {
638
653
  const shorthand = ast_helpers_1.t.isIdentifier(expr) && expr.name === name;
639
654
  const keyNode = ast_helpers_1.t.isValidIdentifier(name) ? ast_helpers_1.t.identifier(name) : ast_helpers_1.t.stringLiteral(name);
@@ -641,7 +656,7 @@ positions, options = {}) {
641
656
  // fallback string inside (`name || 'your business'`) couldn't be wired.
642
657
  return ast_helpers_1.t.objectProperty(keyNode, expr, false, shorthand);
643
658
  });
644
- return { key, values: ast_helpers_1.t.objectExpression(props) };
659
+ return { key, values: ast_helpers_1.t.objectExpression(props), full };
645
660
  };
646
661
  // Pre-scan to determine if we should fall back to vanilla strategy and identify hooks needed
647
662
  (0, ast_helpers_1.traverse)(ast, {
@@ -959,7 +974,7 @@ positions, options = {}) {
959
974
  const args = [ast_helpers_1.t.stringLiteral(message.key)];
960
975
  if (message.values)
961
976
  args.push(message.values);
962
- const call = ast_helpers_1.t.callExpression(ast_helpers_1.t.identifier(name), args);
977
+ const call = keepEdgeWhitespace(message.full, ast_helpers_1.t.callExpression(ast_helpers_1.t.identifier(name), args));
963
978
  const line = path.node.loc?.start.line || 0;
964
979
  const column = path.node.loc?.start.column || 0;
965
980
  const original = (0, ast_helpers_1.generate)(path.node).code;
@@ -1021,7 +1036,7 @@ positions, options = {}) {
1021
1036
  if (!source)
1022
1037
  return;
1023
1038
  const tFunctionName = pickTranslator(path, source);
1024
- path.replaceWith(useTranslatorName((0, ast_helpers_1.createTCall)(key), tFunctionName));
1039
+ path.replaceWith(keepEdgeWhitespace(path.node.value, useTranslatorName((0, ast_helpers_1.createTCall)(key), tFunctionName)));
1025
1040
  injections.push({
1026
1041
  file: filePath,
1027
1042
  line,
@@ -28,5 +28,10 @@ export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: stri
28
28
  * new language still has to be registered.
29
29
  */
30
30
  export declare function adoptedSetupNotes(workspace: WorkspaceInfo, sourceLocale: string, targetLocales: string[], hardcoded: NotInjectedString[]): string[];
31
- /** Strings found in code that an adopted setup leaves alone (reported, never injected). */
31
+ /**
32
+ * Strings found in code that an adopted setup leaves alone (reported, never
33
+ * injected): UI text only. Template/JSX text and attributes, and literals in
34
+ * component files; literals in plain .js/.ts (servers, scripts, utilities)
35
+ * are mostly API messages and identifiers, and would drown the real ones.
36
+ */
32
37
  export declare function hardcodedStrings(strings: ExtractedString[], workspace: WorkspaceInfo): NotInjectedString[];
@@ -162,10 +162,17 @@ function adoptedSetupNotes(workspace, sourceLocale, targetLocales, hardcoded) {
162
162
  }
163
163
  return notes;
164
164
  }
165
- /** Strings found in code that an adopted setup leaves alone (reported, never injected). */
165
+ const COMPONENT_FILE = /\.(?:vue|jsx|tsx|html?)$/;
166
+ /**
167
+ * Strings found in code that an adopted setup leaves alone (reported, never
168
+ * injected): UI text only. Template/JSX text and attributes, and literals in
169
+ * component files; literals in plain .js/.ts (servers, scripts, utilities)
170
+ * are mostly API messages and identifiers, and would drown the real ones.
171
+ */
166
172
  function hardcodedStrings(strings, workspace) {
167
173
  const library = workspace.existingSetup ? i18n_1.I18N_LIBRARY_NAMES[workspace.existingSetup.library] : 'i18n';
168
- return strings.map((s) => ({
174
+ const ui = strings.filter((s) => s.context === 'jsx-text' || s.context === 'jsx-attr' || COMPONENT_FILE.test(s.file));
175
+ return ui.map((s) => ({
169
176
  file: s.file,
170
177
  key: '',
171
178
  text: s.text,
@@ -478,6 +478,15 @@ function isNonTranslatableContext(path) {
478
478
  (t.isStringLiteral(propKey) && TECH_OBJ_KEYS.has(propKey.value))) {
479
479
  return true;
480
480
  }
481
+ // HTTP headers: `{ Authorization: `Bearer ${key}` }`, `headers: { Prefer: 'return=minimal' }`.
482
+ // A translated header value breaks the request.
483
+ if (isHttpHeaderName(propertyName(propKey)))
484
+ return true;
485
+ const owner = current.parentPath?.parentPath;
486
+ if (owner?.isObjectProperty() && propertyName(owner.node.key)?.toLowerCase() === 'headers')
487
+ return true;
488
+ if (owner?.isNewExpression() && t.isIdentifier(owner.node.callee, { name: 'Headers' }))
489
+ return true;
481
490
  }
482
491
  // An object key, also when picked by a ternary or fallback:
483
492
  // `Colors[scheme === 'unspecified' ? 'light' : scheme]`, `map[key ?? 'default']`.
@@ -534,6 +543,25 @@ function isNonTranslatableContext(path) {
534
543
  }
535
544
  return false;
536
545
  }
546
+ const HTTP_HEADER_NAMES = new Set([
547
+ 'authorization', 'proxy-authorization', 'content-type', 'content-length', 'content-encoding', 'content-disposition',
548
+ 'accept', 'accept-encoding', 'accept-language', 'cache-control', 'cookie', 'set-cookie', 'user-agent',
549
+ 'origin', 'referer', 'prefer', 'apikey', 'api-key', 'if-none-match', 'if-match', 'etag', 'location',
550
+ ]);
551
+ function propertyName(key) {
552
+ if (t.isIdentifier(key))
553
+ return key.name;
554
+ if (t.isStringLiteral(key))
555
+ return key.value;
556
+ return null;
557
+ }
558
+ /** `Authorization`, `'Content-Type'`, `'x-api-key'`: a request/response header name. */
559
+ function isHttpHeaderName(name) {
560
+ if (!name)
561
+ return false;
562
+ const lower = name.toLowerCase();
563
+ return HTTP_HEADER_NAMES.has(lower) || /^x-[a-z0-9-]+$/.test(lower);
564
+ }
537
565
  /**
538
566
  * Expressions a value passes through unchanged on its way to its slot:
539
567
  * `a ? 'x' : b`, `k ?? 'x'`, `('x' as K)`, `x!`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",