@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.
@@ -1,4 +1,5 @@
1
1
  import type { ExtractedString } from '../runtime/types';
2
+ import type { SourceScope } from '../utils/source-scope';
2
3
  export type FrameworkSupport = 'supported' | 'beta' | 'unsupported';
3
4
  /** How well `babelize translate` handles a detected framework. */
4
5
  export declare function frameworkSupport(framework: string): FrameworkSupport;
@@ -95,6 +96,8 @@ export interface AnalyzeOptions {
95
96
  targetLocales?: string[];
96
97
  /** Parent dir for the temp copy (default: OS temp dir). */
97
98
  tmpRoot?: string;
99
+ /** Source files to analyze; each list given replaces `.babelize/config.json` `include`/`exclude`. */
100
+ sourceScope?: SourceScope;
98
101
  }
99
102
  /** Analyze `projectDir` on a temp copy; the project itself is only read. */
100
103
  export declare function analyzeProject(projectDir: string, options?: AnalyzeOptions): Promise<ProjectAnalysis>;
@@ -131,6 +131,7 @@ async function analyzeWorkspace(workspacePath, options = {}) {
131
131
  targetLocales,
132
132
  confidenceThreshold: 80,
133
133
  dryRun: true,
134
+ ...(options.sourceScope ? { sourceScope: options.sourceScope } : {}),
134
135
  }));
135
136
  }
136
137
  catch (err) {
@@ -0,0 +1,21 @@
1
+ import { type SourceScope } from '../utils/source-scope';
2
+ export interface ScannedString {
3
+ text: string;
4
+ line: number;
5
+ /** An ICU message (plural/select) built from the source. */
6
+ is_icu: boolean;
7
+ }
8
+ export interface ScannedFile {
9
+ /** Relative to `cwd`. */
10
+ path: string;
11
+ hardcoded_strings: ScannedString[];
12
+ }
13
+ export interface ScanStringsOptions {
14
+ /** File extensions to read (default: .js .jsx .ts .tsx .vue .html). */
15
+ extensions?: string[];
16
+ /** Each list given replaces the project's `.babelize/config.json` include/exclude. */
17
+ sourceScope?: SourceScope;
18
+ /** Paths in the result are relative to this (default: process.cwd()). */
19
+ cwd?: string;
20
+ }
21
+ export declare function scanStrings(dir: string, options?: ScanStringsOptions): Promise<ScannedFile[]>;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.scanStrings = scanStrings;
37
+ /**
38
+ * `babelize scan` / MCP `babelize_scan`: the hardcoded strings in a folder,
39
+ * found by the same extractor `translate` uses (#381). Read-only, no network,
40
+ * no framework setup needed.
41
+ */
42
+ const fs_1 = require("fs");
43
+ const path = __importStar(require("path"));
44
+ const types_1 = require("../runtime/types");
45
+ const extract_1 = require("../modules/extractor/extract");
46
+ const file_utils_1 = require("../utils/file-utils");
47
+ const source_scope_1 = require("../utils/source-scope");
48
+ const PROJECT_MARKERS = ['.babelize', 'package.json', 'manage.py', '.git'];
49
+ /** The nearest folder at or above `dir` that looks like a project root; `dir` when none. */
50
+ async function projectRoot(dir) {
51
+ for (let current = dir;; current = path.dirname(current)) {
52
+ for (const marker of PROJECT_MARKERS) {
53
+ if (await fs_1.promises.stat(path.join(current, marker)).then(() => true, () => false))
54
+ return current;
55
+ }
56
+ if (path.dirname(current) === current)
57
+ return dir;
58
+ }
59
+ }
60
+ const ICU = /\{\s*\w+\s*,\s*(?:plural|select|selectordinal)\s*,/;
61
+ async function scanStrings(dir, options = {}) {
62
+ const abs = path.resolve(dir);
63
+ const cwd = options.cwd ?? process.cwd();
64
+ const root = await projectRoot(abs);
65
+ // Globs are relative to the project root, as in translate.
66
+ const inScope = (0, source_scope_1.createScopeMatcher)((0, source_scope_1.mergeSourceScope)(await (0, source_scope_1.readSourceScope)(root), options.sourceScope));
67
+ const extensions = (options.extensions ?? types_1.SUPPORTED_EXTENSIONS).map((e) => (e.startsWith('.') ? e : `.${e}`).toLowerCase());
68
+ (0, file_utils_1.clearFindFilesCache)();
69
+ const files = (await (0, file_utils_1.findFiles)(abs, extensions, types_1.EXCLUDED_PATTERNS))
70
+ .filter((file) => inScope(path.relative(root, file)))
71
+ .sort();
72
+ const out = [];
73
+ for (const file of files) {
74
+ const content = await fs_1.promises.readFile(file, 'utf8').catch(() => null);
75
+ if (content === null)
76
+ continue;
77
+ const rel = path.relative(root, file).split(path.sep).join('/');
78
+ const { strings } = await (0, extract_1.extractStringsFromFile)(content, rel).catch(() => ({ strings: [] }));
79
+ if (strings.length === 0)
80
+ continue;
81
+ out.push({
82
+ path: path.relative(cwd, file).split(path.sep).join('/'),
83
+ hardcoded_strings: strings.map((s) => ({ text: s.text, line: s.line, is_icu: ICU.test(s.text) })),
84
+ });
85
+ }
86
+ return out;
87
+ }
package/dist/index.d.ts CHANGED
@@ -61,4 +61,9 @@ export type { LocaleChangeReview, LocaleSetChangeReview, ReviewOptions } from '.
61
61
  export { checkProjectLocales, localeIssueFile, readProjectLocaleConfig } from './qa/check-project';
62
62
  export type { CheckProjectOptions, LocaleSetReport, ProjectLocaleCheck, ProjectLocaleConfig } from './qa/check-project';
63
63
  export { hashText, translationCacheKey, TRANSLATION_CACHE_TTL_SECONDS } from './utils/cache-keys';
64
+ export { createScopeMatcher, mergeSourceScope, normalizeScopePatterns, readSourceScope } from './utils/source-scope';
65
+ export { scanStrings } from './analysis/scan';
66
+ export type { ScannedFile, ScannedString, ScanStringsOptions } from './analysis/scan';
67
+ export { extractStringsFromFile } from './modules/extractor/extract';
68
+ export type { SourceScope } from './utils/source-scope';
64
69
  export * from './local';
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.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;
25
+ exports.extractStringsFromFile = exports.scanStrings = exports.readSourceScope = exports.normalizeScopePatterns = exports.mergeSourceScope = exports.createScopeMatcher = 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");
@@ -153,5 +153,14 @@ var cache_keys_1 = require("./utils/cache-keys");
153
153
  Object.defineProperty(exports, "hashText", { enumerable: true, get: function () { return cache_keys_1.hashText; } });
154
154
  Object.defineProperty(exports, "translationCacheKey", { enumerable: true, get: function () { return cache_keys_1.translationCacheKey; } });
155
155
  Object.defineProperty(exports, "TRANSLATION_CACHE_TTL_SECONDS", { enumerable: true, get: function () { return cache_keys_1.TRANSLATION_CACHE_TTL_SECONDS; } });
156
+ var source_scope_1 = require("./utils/source-scope");
157
+ Object.defineProperty(exports, "createScopeMatcher", { enumerable: true, get: function () { return source_scope_1.createScopeMatcher; } });
158
+ Object.defineProperty(exports, "mergeSourceScope", { enumerable: true, get: function () { return source_scope_1.mergeSourceScope; } });
159
+ Object.defineProperty(exports, "normalizeScopePatterns", { enumerable: true, get: function () { return source_scope_1.normalizeScopePatterns; } });
160
+ Object.defineProperty(exports, "readSourceScope", { enumerable: true, get: function () { return source_scope_1.readSourceScope; } });
161
+ var scan_1 = require("./analysis/scan");
162
+ Object.defineProperty(exports, "scanStrings", { enumerable: true, get: function () { return scan_1.scanStrings; } });
163
+ var extract_1 = require("./modules/extractor/extract");
164
+ Object.defineProperty(exports, "extractStringsFromFile", { enumerable: true, get: function () { return extract_1.extractStringsFromFile; } });
156
165
  // ── Local translation runner (CLI `babelize translate`, MCP `babelize_translate`) ──
157
166
  __exportStar(require("./local"), exports);
@@ -66,7 +66,15 @@ export interface HostedProviderOptions {
66
66
  timeoutMs?: number;
67
67
  /** Sent as User-Agent. */
68
68
  userAgent?: string;
69
+ /**
70
+ * Batch requests in flight at once, across every locale of the run
71
+ * (default HOSTED_MAX_IN_FLIGHT). The hosted translator is shared: a run
72
+ * that floods it times out and fails everyone's batches (#388).
73
+ */
74
+ maxInFlight?: number;
69
75
  }
76
+ /** Default cap on concurrent /v1/translate/batch requests per run. */
77
+ export declare const HOSTED_MAX_IN_FLIGHT = 2;
70
78
  export declare function parseRetryAfterMs(value: string | null): number | undefined;
71
79
  export declare class HostedTranslationProvider implements TranslationProvider {
72
80
  /** Model the server reported (X-Babelize-Model), once a request succeeded. */
@@ -86,6 +94,9 @@ export declare class HostedTranslationProvider implements TranslationProvider {
86
94
  private token;
87
95
  /** In-flight refresh, shared by concurrent batches that all got a 401. */
88
96
  private refreshing?;
97
+ /** Requests running now, and the ones waiting for a slot. */
98
+ private inFlight;
99
+ private readonly waiting;
89
100
  constructor(options: HostedProviderOptions);
90
101
  /**
91
102
  * Ask the server what serves translation (GET /v1/translate/capabilities)
@@ -95,6 +106,8 @@ export declare class HostedTranslationProvider implements TranslationProvider {
95
106
  detectCapabilities(): Promise<void>;
96
107
  translateBatch(request: TranslationBatchRequest): Promise<KeyResult[]>;
97
108
  private post;
109
+ /** Run `task` once fewer than maxInFlight requests are running. */
110
+ private withSlot;
98
111
  private backoff;
99
112
  private toError;
100
113
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostedTranslationProvider = exports.HostedTranslationError = exports.BILLING_URL = exports.API_KEYS_URL = exports.HOSTED_CREDITS_HEADER = exports.HOSTED_MODEL_HEADER = exports.HOSTED_REQUEST_TIMEOUT_MS = exports.HOSTED_MAX_BATCH = void 0;
3
+ exports.HostedTranslationProvider = exports.HOSTED_MAX_IN_FLIGHT = exports.HostedTranslationError = exports.BILLING_URL = exports.API_KEYS_URL = exports.HOSTED_CREDITS_HEADER = exports.HOSTED_MODEL_HEADER = exports.HOSTED_REQUEST_TIMEOUT_MS = exports.HOSTED_MAX_BATCH = void 0;
4
4
  exports.parseRetryAfterMs = parseRetryAfterMs;
5
5
  const node_crypto_1 = require("node:crypto");
6
6
  const language_codes_1 = require("../modules/translator/language-codes");
@@ -39,6 +39,8 @@ class HostedTranslationError extends Error {
39
39
  }
40
40
  }
41
41
  exports.HostedTranslationError = HostedTranslationError;
42
+ /** Default cap on concurrent /v1/translate/batch requests per run. */
43
+ exports.HOSTED_MAX_IN_FLIGHT = 2;
42
44
  const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
43
45
  function parseRetryAfterMs(value) {
44
46
  if (!value)
@@ -59,6 +61,9 @@ class HostedTranslationProvider {
59
61
  this.plainText = false;
60
62
  /** Credits charged so far by this provider's batches (X-Credits-Charged). */
61
63
  this.creditsCharged = 0;
64
+ /** Requests running now, and the ones waiting for a slot. */
65
+ this.inFlight = 0;
66
+ this.waiting = [];
62
67
  this.token = options.apiKey;
63
68
  this.opts = {
64
69
  fetch: globalThis.fetch.bind(globalThis),
@@ -67,6 +72,7 @@ class HostedTranslationProvider {
67
72
  baseDelayMs: 1000,
68
73
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
69
74
  timeoutMs: exports.HOSTED_REQUEST_TIMEOUT_MS,
75
+ maxInFlight: exports.HOSTED_MAX_IN_FLIGHT,
70
76
  ...options,
71
77
  apiUrl: options.apiUrl.replace(/\/+$/, ''),
72
78
  };
@@ -120,7 +126,7 @@ class HostedTranslationProvider {
120
126
  const hints = request.hints
121
127
  ? Object.fromEntries(Object.entries(request.hints).filter(([k]) => keys.has(k)))
122
128
  : undefined;
123
- for (const r of await this.post({ ...request, entries, hints }))
129
+ for (const r of await this.withSlot(() => this.post({ ...request, entries, hints })))
124
130
  remote.set(r.key, r);
125
131
  }
126
132
  return request.entries.flatMap((e) => {
@@ -227,6 +233,26 @@ class HostedTranslationProvider {
227
233
  throw error;
228
234
  }
229
235
  }
236
+ /** Run `task` once fewer than maxInFlight requests are running. */
237
+ async withSlot(task) {
238
+ if (this.inFlight >= Math.max(1, this.opts.maxInFlight)) {
239
+ // A finishing request hands its slot straight to us (inFlight unchanged).
240
+ await new Promise((resolve) => this.waiting.push(resolve));
241
+ }
242
+ else {
243
+ this.inFlight++;
244
+ }
245
+ try {
246
+ return await task();
247
+ }
248
+ finally {
249
+ const next = this.waiting.shift();
250
+ if (next)
251
+ next();
252
+ else
253
+ this.inFlight--;
254
+ }
255
+ }
230
256
  backoff(attempt) {
231
257
  return this.opts.baseDelayMs * 2 ** attempt;
232
258
  }
@@ -2,6 +2,7 @@ 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
4
  import type { FormalitySetting } from '../modules/translator/formality';
5
+ import type { SourceScope } from '../utils/source-scope';
5
6
  /** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
6
7
  export declare function configRulesStore(glossary: LocaleGlossary | undefined, extra?: {
7
8
  brandVoice?: string;
@@ -43,6 +44,11 @@ export interface LocalTranslateOptions {
43
44
  formality?: Record<string, FormalitySetting>;
44
45
  /** Tone and style for the translator; replaces `.babelize/config.json` `brandVoice`. */
45
46
  brandVoice?: string;
47
+ /**
48
+ * Source files to extract from and rewrite (`--include`/`--exclude` globs).
49
+ * Each list given replaces `.babelize/config.json` `include`/`exclude`.
50
+ */
51
+ sourceScope?: SourceScope;
46
52
  }
47
53
  export interface LocalTranslateDeps {
48
54
  /** Replaces the BYOK translator (tests). */
@@ -359,6 +359,7 @@ async function runScoped(opts, deps, engineLog, state) {
359
359
  // and the updated one comes back with the other changes — only on success.
360
360
  dataDir: temp.dir,
361
361
  byok: translator ? undefined : opts.byok,
362
+ ...(opts.sourceScope ? { sourceScope: opts.sourceScope } : {}),
362
363
  providers: translator || rules ? { ...(translator ? { translator } : {}), ...(rules ? { rules } : {}) } : undefined,
363
364
  installDependencies: false,
364
365
  onProgress: (message, step, status) => deps.onProgress?.(message, step, status),
@@ -49,6 +49,7 @@ const jsx_message_1 = require("../../utils/jsx-message");
49
49
  const ui_copy_1 = require("../../utils/ui-copy");
50
50
  const module_constants_1 = require("../../utils/module-constants");
51
51
  const react_native_1 = require("../../utils/react-native");
52
+ const source_scope_1 = require("../../utils/source-scope");
52
53
  /** Frameworks whose injection strategies can render a JSX sentence as one message. */
53
54
  const SENTENCE_FRAMEWORKS = new Set(['react', 'nextjs', 'react-native']);
54
55
  async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
@@ -60,10 +61,8 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
60
61
  const notInjected = [];
61
62
  const sourceFiles = [];
62
63
  if (filesToProcess && filesToProcess.length > 0) {
63
- // If specific files are provided, only scan those
64
- for (const relPath of filesToProcess) {
65
- sourceFiles.push(path.join(workspace.path, relPath));
66
- }
64
+ // If specific files are provided, only scan those (still within the project's scope)
65
+ sourceFiles.push(...(0, source_scope_1.filterToScope)(workspace, filesToProcess.map((relPath) => path.join(workspace.path, relPath))));
67
66
  }
68
67
  else {
69
68
  // Otherwise scan all source directories. Root-scanning frameworks use
@@ -74,7 +73,7 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
74
73
  const excluded = (0, types_1.workspaceExcludes)(workspace);
75
74
  for (const sourceDir of workspace.sourceDirs) {
76
75
  const dirPath = path.join(workspace.path, sourceDir);
77
- const files = await (0, file_utils_1.findFiles)(dirPath, extensions, excluded);
76
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, extensions, excluded));
78
77
  sourceFiles.push(...files);
79
78
  }
80
79
  }
@@ -182,6 +181,20 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
182
181
  const isTypeScript = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
183
182
  try {
184
183
  const ast = (0, ast_helpers_1.parseCode)(content, { isTypeScript });
184
+ // Options of this file's string-literal union types: never copy (#379).
185
+ const unionMembers = isTypeScript ? (0, ui_copy_1.literalUnionMembers)(ast) : new Set();
186
+ /**
187
+ * A string literal that picks a value rather than showing one: text
188
+ * direction, a union option, or a component prop option (#379).
189
+ */
190
+ const isOptionValue = (path, text) => {
191
+ if (!path.isStringLiteral?.())
192
+ return false;
193
+ if ((0, ui_copy_1.isDirectionValue)(text) || unionMembers.has(text))
194
+ return true;
195
+ const attribute = path.parentPath;
196
+ return !!attribute?.isJSXAttribute() && (0, ui_copy_1.isComponentOptionValue)(attribute.node, attribute.parentPath.node, text);
197
+ };
185
198
  // UI copy in module-level constants rendered by components (#248): keys
186
199
  // when every use is a render, otherwise reported — never silently skipped.
187
200
  if (!options?.framework || SENTENCE_FRAMEWORKS.has(options.framework)) {
@@ -240,6 +253,11 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
240
253
  return;
241
254
  if (/^\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+Z?)?$/.test(text))
242
255
  return;
256
+ if (isOptionValue(path, text))
257
+ return;
258
+ // SVG geometry (`<path d="M12 .297c-6.63…">`) is numbers, not copy or prices (#381).
259
+ if (isSvgGeometry(path))
260
+ return;
243
261
  // A literal in a branch (`role === 'brand' ? 'brand' : 'creator'`, `user?.id ?? 'usr_1'`)
244
262
  // goes where the whole expression goes, so that's where it's judged.
245
263
  const site = valueSite(path);
@@ -465,6 +483,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
465
483
  return;
466
484
  if ((0, ast_helpers_1.isAlreadyTranslated)(path.node, path))
467
485
  return;
486
+ if (isOptionValue(path.get('value'), text))
487
+ return;
468
488
  const id = `${filePath}:${path.node.loc?.start.line}:${(0, string_utils_1.hashString)(text)}`;
469
489
  noteOffset(id, path.node.start);
470
490
  if (!seenTexts.has(id)) {
@@ -597,6 +617,12 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
597
617
  return { strings, warnings, notInjected: unwired };
598
618
  }
599
619
  /** A string that names something rather than being shown: a property key, or part of a TypeScript type. */
620
+ /** SVG attributes whose value is geometry (`d`, `viewBox`, `points`, …). */
621
+ const SVG_GEOMETRY_ATTRS = new Set(['d', 'viewBox', 'points', 'transform', 'gradientTransform', 'patternTransform', 'strokeDasharray', 'stroke-dasharray', 'pathLength']);
622
+ function isSvgGeometry(path) {
623
+ const attr = path.parentPath;
624
+ return !!attr?.isJSXAttribute() && ast_helpers_1.t.isJSXIdentifier(attr.node.name) && SVG_GEOMETRY_ATTRS.has(attr.node.name.name);
625
+ }
600
626
  function isKeyOrType(path) {
601
627
  const parent = path.parentPath;
602
628
  if (!parent)
@@ -5,6 +5,12 @@ interface PackageJson {
5
5
  devDependencies?: Record<string, string>;
6
6
  [key: string]: unknown;
7
7
  }
8
+ /**
9
+ * Whether package.json describes a package published to npm (not an app):
10
+ * not private, with library entry points or a files list. `main` alone isn't
11
+ * enough: Expo, Electron and Node apps use it for their own entry.
12
+ */
13
+ export declare function isPublishedPackage(pkg: PackageJson): boolean;
8
14
  export declare function finalizeProject(workspace: WorkspaceInfo, dryRun: boolean, options?: {
9
15
  targetLocales?: string[];
10
16
  sourceLocale?: string;
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.isPublishedPackage = isPublishedPackage;
36
37
  exports.finalizeProject = finalizeProject;
37
38
  exports.i18nRuntimeFor = i18nRuntimeFor;
38
39
  const path = __importStar(require("path"));
@@ -49,6 +50,16 @@ const react_native_finalize_1 = require("./react-native-finalize");
49
50
  const dependencies_1 = require("./dependencies");
50
51
  const i18n_config_path_1 = require("../../utils/i18n-config-path");
51
52
  const i18next_icu_1 = require("../../utils/i18next-icu");
53
+ /**
54
+ * Whether package.json describes a package published to npm (not an app):
55
+ * not private, with library entry points or a files list. `main` alone isn't
56
+ * enough: Expo, Electron and Node apps use it for their own entry.
57
+ */
58
+ function isPublishedPackage(pkg) {
59
+ if (pkg.private === true)
60
+ return false;
61
+ return ['exports', 'module', 'types', 'typings', 'files', 'publishConfig'].some((field) => pkg[field] !== undefined);
62
+ }
52
63
  const DEPENDENCIES_BY_FRAMEWORK = {
53
64
  react: dependencies_1.I18NEXT_WEB_DEPENDENCIES,
54
65
  // Next.js projects that already use react-i18next keep it (injection picks
@@ -254,15 +265,22 @@ async function finalizeProject(workspace, dryRun, options = {}) {
254
265
  if (rn.warning)
255
266
  warnings.push(rn.warning);
256
267
  }
257
- const missingDeps = Object.keys(requiredDeps).filter((d) => !deps[d]);
268
+ // A package.json that is also a published library (a component kit with
269
+ // its docs site in the same package) would ship the site's i18n runtime
270
+ // to every consumer: it goes in devDependencies there (#378).
271
+ const field = isPublishedPackage(pkg) ? 'devDependencies' : 'dependencies';
272
+ const missingDeps = Object.keys(requiredDeps).filter((d) => !deps[d] && !(field === 'devDependencies' && pkg.devDependencies?.[d]));
258
273
  if (missingDeps.length > 0) {
259
- pkg.dependencies = pkg.dependencies || {};
274
+ const target = { ...pkg[field] };
260
275
  for (const dep of missingDeps) {
261
- pkg.dependencies[dep] = requiredDeps[dep];
276
+ target[dep] = requiredDeps[dep];
262
277
  }
263
278
  // Keep the user's key order (a sorted package.json is an unreviewable
264
279
  // diff); only the dependency map is sorted, as npm does.
265
- pkg.dependencies = Object.fromEntries(Object.entries(pkg.dependencies).sort(([a], [b]) => a.localeCompare(b)));
280
+ pkg[field] = Object.fromEntries(Object.entries(target).sort(([a], [b]) => a.localeCompare(b)));
281
+ if (field === 'devDependencies') {
282
+ warnings.push(`package.json is a published package, so ${missingDeps.join(', ')} went into devDependencies to keep ${missingDeps.length === 1 ? 'it' : 'them'} out of your consumers' installs.`);
283
+ }
266
284
  await writer.write(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
267
285
  if (!dryRun) {
268
286
  // A committed lockfile must move with package.json, or `npm ci` /
@@ -745,5 +763,7 @@ function i18nRuntimeFor(framework, pkg) {
745
763
  : fw === 'react-native' ? (0, react_native_finalize_1.reactNativeDependencies)(pkg ?? undefined).deps
746
764
  : DEPENDENCIES_BY_FRAMEWORK[fw] ?? {});
747
765
  const library = nextIntl ? 'next-intl' : fw === 'vue' ? 'vue-i18n' : 'react-i18next';
748
- return { library, required, missing: required.filter((d) => !(pkg?.dependencies ?? {})[d]) };
766
+ // A published package keeps them in devDependencies (see finalizeWorkspace).
767
+ const installed = pkg && isPublishedPackage(pkg) ? deps : pkg?.dependencies ?? {};
768
+ return { library, required, missing: required.filter((d) => !installed[d]) };
749
769
  }
@@ -6,28 +6,68 @@ import type { WorkspaceInfo } from '../../runtime/types';
6
6
  * Injection rewrites Next.js components to next-intl (`getTranslations` in
7
7
  * Server Components, `useTranslations` in Client Components — see
8
8
  * NextIntlStrategy), so the project must be wired for next-intl or every
9
- * page throws at runtime. This sets up next-intl's "without i18n routing"
10
- * mode: the locale comes from a NEXT_LOCALE cookie or the browser's
11
- * Accept-Language header, and messages are the generated
12
- * `public/locales/<locale>.json` files. URLs don't change.
9
+ * page throws at runtime. Each language gets its own URL without moving any
10
+ * route (#380): a generated proxy (middleware before Next 16) serves
11
+ * `/ja/docs` from the existing `app/docs` route and tells next-intl the
12
+ * locale in a request header. The source language stays unprefixed, a
13
+ * NEXT_LOCALE cookie remembers a visitor's choice, and every page announces
14
+ * its translations to search engines with hreflang `Link` headers. The root
15
+ * layout's <html> gets the locale's `lang` and `dir`. Messages are the
16
+ * generated `public/locales/<locale>.json` files.
17
+ *
18
+ * `"routing": "cookie"` in .babelize/config.json keeps one URL for every
19
+ * language (the locale comes from the cookie or Accept-Language).
13
20
  *
14
21
  * Every edit is a minimal text splice (the user's formatting is kept), and
15
22
  * anything that can't be wired automatically becomes a warning — never a
16
23
  * silently half-configured project.
17
24
  */
18
25
  export declare const NEXT_INTL_DEPENDENCIES: Record<string, string>;
26
+ /** Request header the proxy sets with the URL's locale. */
27
+ export declare const LOCALE_HEADER = "x-babelize-locale";
28
+ export type NextRouting = 'prefix' | 'cookie';
19
29
  export interface NextIntlFinalizeResult {
20
30
  configFileCreated: boolean;
21
31
  entryPointModified: boolean;
22
32
  warnings: string[];
23
33
  }
34
+ /**
35
+ * `i18n/locales`: the locale list and text direction, shared by the request
36
+ * config, the proxy and the root layout. Plain data, safe to import anywhere.
37
+ */
38
+ export declare function buildLocalesModule(opts: {
39
+ sourceLocale: string;
40
+ locales: string[];
41
+ typescript: boolean;
42
+ }): string;
24
43
  export declare function buildRequestConfig(opts: {
25
44
  sourceLocale: string;
26
45
  locales: string[];
27
46
  /** Import path from the request config file to a locale file, with `__LOCALE__` as placeholder. */
28
47
  messagesImportPath: string;
29
48
  typescript: boolean;
49
+ /** `prefix`: the proxy's locale header wins. Default `cookie` (no proxy). */
50
+ routing?: NextRouting;
30
51
  }): string;
52
+ /**
53
+ * The locale proxy (#380): `/ja/docs` is served by `app/docs` with the
54
+ * locale in a request header; the source language has no prefix. A visitor
55
+ * who picked a language (NEXT_LOCALE cookie) is sent to its URL. Every page
56
+ * lists its translations in hreflang `Link` headers.
57
+ */
58
+ export declare function buildProxy(opts: {
59
+ kind: 'proxy' | 'middleware';
60
+ typescript: boolean;
61
+ }): string;
62
+ /**
63
+ * Give the root layout's <html> the active locale's `lang` and `dir`
64
+ * (#380): `const locale = useLocale()` in the default-exported layout
65
+ * (`await getLocale()` when it is already async). Null when the layout's shape isn't one this
66
+ * can edit safely (no <html>, an expression-bodied arrow, no default export).
67
+ */
68
+ export declare function setHtmlLocale(content: string, typescript: boolean, localesImport: string): string | null;
69
+ /** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
70
+ export declare function nextMajor(packageJson: Record<string, any> | undefined): number | null;
31
71
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
32
72
  export declare function wrapNextConfig(content: string, requestConfigPath: string, typescript: boolean): string | null;
33
73
  /**