@verbaly/compiler 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -100,6 +100,44 @@ const provider: TranslateProvider = async ({ targetLocale, messages, origins, gl
100
100
  export default { sourceLocale: 'en', locales: ['en', 'es'], translate: { provider } };
101
101
  ```
102
102
 
103
+ ## 🔗 Where the language lives in the URL
104
+
105
+ One setting, because every other URL answer follows from it:
106
+
107
+ **You usually write nothing.** The mode follows your setup: a project with a `render` section builds one URL tree per language, so it is `prefix-except-source`; a project without one has a single address, so it is `no-prefix`. Say it out loud only to disagree:
108
+
109
+ ```ts
110
+ export default {
111
+ sourceLocale: 'en',
112
+ locales: ['en', 'es', 'pt'],
113
+ routing: 'prefix-all', // /en/docs and /es/docs, when no language is the house language
114
+ };
115
+ ```
116
+
117
+ | `routing` | The address | Switching language is |
118
+ | ---------------------- | ------------------------- | ----------------------------- |
119
+ | `prefix-except-source` | `/docs` and `/es/docs` | a navigation |
120
+ | `prefix-all` | `/en/docs` and `/es/docs` | a navigation |
121
+ | `no-prefix` | `/docs` in every language | the text changing where it is |
122
+
123
+ Pick by surface, not by taste: [Google recommends a different URL per language](https://developers.google.com/search/docs/specialty/international/managing-multi-regional-sites) rather than cookies or browser settings, so anything people reach through search wants the language in the address. An app behind a login loses nothing with `no-prefix`.
124
+
125
+ `virtual:verbaly` exports `routing`, `localePath`, `localeFromPath` and **`switchLocale`, already bound** to your locales, source and mode. The switcher is one line and it is the same line in every mode:
126
+
127
+ ```ts
128
+ import { switchLocale } from 'virtual:verbaly';
129
+
130
+ await switchLocale('es');
131
+ ```
132
+
133
+ Under a prefix mode that goes to `/es/…`, which is already rendered in Spanish, so there is no catalog to fetch and no flash. Under `no-prefix` it swaps the text where it stands and the address never changes. Either way it remembers the choice, in the cookie a server reads **and** in the storage the pre-paint redirect reads, and it sets `<html lang>` and `<html dir>`. Pass your framework's router so the app survives the switch:
134
+
135
+ ```ts
136
+ await switchLocale('es', { navigate: (path) => router.push(path) });
137
+ ```
138
+
139
+ `npx verbaly doctor` names the mode you are in, and says so when `no-prefix` sits next to a `render` section that writes one URL tree per locale.
140
+
103
141
  ## 🌍 Human translators & TMS
104
142
 
105
143
  Catalogs are **flat JSON**: most TMS platforms (Crowdin, Lokalise, Phrase, …) ingest them natively; point the platform at `locales/` and you're done. For everything else there's a built-in round-trip:
@@ -137,6 +175,16 @@ render: { links: { docs: { href: '/docs', target: '_blank', rel: 'noopener' } }
137
175
 
138
176
  Per-element `data-verbaly-links='{"repo":"https://…"}'` merges over the config map.
139
177
 
178
+ **The head is half of what a search result shows.** A mirrored page whose `<title>` and `<meta name="description">` are not bound ships the source language to every locale, which is most of the reason to give a locale its own URL in the first place. Bind them like anything else, and `render` fills them:
179
+
180
+ ```html
181
+ <title data-verbaly="page.title">URL strategy</title>
182
+ <meta name="description" content="…" data-verbaly-attr='{"content":"page.desc"}' />
183
+ <meta property="og:title" content="…" data-verbaly-attr='{"content":"page.title"}' />
184
+ ```
185
+
186
+ `verbaly render` counts the pages whose title never varies and says so, once, with the fix. It is a warning and never fails a build: a site can have a name that does not translate.
187
+
140
188
  **Multi-locale SEO**: set `render.baseUrl` (or `--base-url`) and every page gets reciprocal `<link rel="alternate" hreflang>` (plus `x-default`) for the whole locale set; `--sitemap` writes a locale-aware `sitemap-i18n.xml`. `--clean` drops stale `dist/<locale>/` pages before mirroring. Injection is idempotent.
141
189
 
142
190
  ## 🔍 Pseudo-localization
@@ -171,7 +219,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
171
219
  | Translation | `translateCatalogs` `resolveProvider` `formatTranslateFailures` |
172
220
  | Diagnosis | `doctor` `formatDoctorEntry` · types `DoctorResult` `DoctorEntry` |
173
221
  | Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapOptions` |
174
- | Static rendering | `renderSite` · types `RenderSiteOptions` `RenderSiteResult` |
222
+ | Static rendering | `renderSite` `formatRenderWarnings` · types `RenderSiteOptions` `RenderSiteResult` |
175
223
 
176
224
  A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
177
225
 
@@ -1,4 +1,4 @@
1
- import { n as isModuleNotFound } from "./config-pSOnS9OZ.js";
1
+ import { n as isModuleNotFound } from "./config-dVhga3PS.js";
2
2
  //#region src/providers/claude.ts
3
3
  const DEFAULT_MODEL = "claude-sonnet-5";
4
4
  const SYSTEM = `You translate UI strings for the Verbaly i18n library.
@@ -69,4 +69,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
69
69
  //#endregion
70
70
  export { claudeProvider };
71
71
 
72
- //# sourceMappingURL=claude-0MJOMelz.js.map
72
+ //# sourceMappingURL=claude-DYAwaLJz.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claude-0MJOMelz.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport type { TranslateProvider, TranslateRequest } from '../translate';\n\nexport interface ClaudeProviderOptions {\n model?: string;\n apiKey?: string;\n maxTokens?: number;\n}\n\n// balanced default for translation\nconst DEFAULT_MODEL = 'claude-sonnet-5';\n\nconst SYSTEM = `You translate UI strings for the Verbaly i18n library.\nRules:\n- Translate only the human-readable text, naturally for the target locale.\n- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.\n- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;\n\nexport function systemPrompt(instructions?: string): string {\n return instructions ? `${SYSTEM}\\n\\nProject instructions:\\n${instructions}` : SYSTEM;\n}\n\nexport function claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n // one client per provider: a batch is a request, not a reason to rebuild the transport\n let client: Promise<InstanceType<typeof import('@anthropic-ai/sdk').default>> | undefined;\n\n return async (request: TranslateRequest) => {\n client ??= loadSdk().then(\n (Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}),\n );\n const response = await (\n await client\n ).messages.create({\n model: options.model ?? DEFAULT_MODEL,\n max_tokens: options.maxTokens ?? 16000,\n thinking: { type: 'disabled' },\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${Object.keys(request.messages).length} messages: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n try {\n return JSON.parse(text) as Record<string, string>;\n } catch (error) {\n throw new Error('[verbaly] the model did not answer with the JSON object it was asked for', {\n cause: error,\n });\n }\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n return (\n `Translate each value from \"${request.sourceLocale}\" to \"${request.targetLocale}\". ` +\n `Return a JSON object with the same keys and translated values.\\n\\n` +\n JSON.stringify(request.messages, null, 2) +\n glossarySection(request) +\n originsSection(request)\n );\n}\n\n// the glossary is a requirement, not a hint: it exists because a brand name came back translated\nfunction glossarySection(request: TranslateRequest): string {\n const glossary = request.glossary;\n if (!glossary || Object.keys(glossary).length === 0) return '';\n const lines = Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`);\n return `\\n\\nGlossary, these renderings are required wherever the term appears:\\n${lines.join('\\n')}`;\n}\n\nfunction originsSection(request: TranslateRequest): string {\n const origins = request.origins;\n if (!origins || Object.keys(origins).length === 0) return '';\n const lines = Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(', ')}`);\n return `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n${lines.join('\\n')}`;\n}\n\nexport function batchFormat(request: TranslateRequest) {\n const keys = Object.keys(request.messages);\n return {\n type: 'json_schema' as const,\n schema: {\n type: 'object',\n properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),\n required: keys,\n additionalProperties: false,\n },\n };\n}\n\ntype SdkModule = { default: typeof import('@anthropic-ai/sdk').default };\n\n// injectable for tests\nexport async function loadSdk(\n load: () => Promise<SdkModule> = () => import('@anthropic-ai/sdk'),\n): Promise<SdkModule['default']> {\n try {\n const mod = await load();\n return mod.default;\n } catch (error) {\n if (isModuleNotFound(error, '@anthropic-ai/sdk')) {\n throw new Error(\n '[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY',\n { cause: error },\n );\n }\n throw error;\n }\n}\n"],"mappings":";;AAUA,MAAM,gBAAgB;AAEtB,MAAM,SAAS;;;;;AAMf,SAAgB,aAAa,cAA+B;CAC1D,OAAO,eAAe,GAAG,OAAO,6BAA6B,iBAAiB;AAChF;AAEA,SAAgB,eAAe,UAAiC,CAAC,GAAsB;CAErF,IAAI;CAEJ,OAAO,OAAO,YAA8B;EAC1C,WAAW,QAAQ,CAAC,CAAC,MAClB,cAAc,IAAI,UAAU,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAAC,CAC/E;EACA,MAAM,WAAW,OACf,MAAM,OAAA,CACN,SAAS,OAAO;GAChB,OAAO,QAAQ,SAAS;GACxB,YAAY,QAAQ,aAAa;GACjC,UAAU,EAAE,MAAM,WAAW;GAC7B,QAAQ,aAAa,QAAQ,YAAY;GACzC,UAAU,CAAC;IAAE,MAAM;IAAQ,SAAS,YAAY,OAAO;GAAE,CAAC;GAC1D,eAAe,EAAE,QAAQ,YAAY,OAAO,EAAE;EAChD,CAAC;EACD,IAAI,SAAS,gBAAgB,cAC3B,MAAM,IAAI,MACR,4DAA4D,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,OAAO,0EACnG;EAEF,MAAM,OAAO,SAAS,QAAQ,MAAM,UAAU,MAAM,SAAS,MAAM,CAAC,EAAE,QAAQ;EAC9E,IAAI;GACF,OAAO,KAAK,MA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jB;EAEF,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"claude-DYAwaLJz.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport type { TranslateProvider, TranslateRequest } from '../translate';\n\nexport interface ClaudeProviderOptions {\n model?: string;\n apiKey?: string;\n maxTokens?: number;\n}\n\n// balanced default for translation\nconst DEFAULT_MODEL = 'claude-sonnet-5';\n\nconst SYSTEM = `You translate UI strings for the Verbaly i18n library.\nRules:\n- Translate only the human-readable text, naturally for the target locale.\n- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.\n- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;\n\nexport function systemPrompt(instructions?: string): string {\n return instructions ? `${SYSTEM}\\n\\nProject instructions:\\n${instructions}` : SYSTEM;\n}\n\nexport function claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n // one client per provider: a batch is a request, not a reason to rebuild the transport\n let client: Promise<InstanceType<typeof import('@anthropic-ai/sdk').default>> | undefined;\n\n return async (request: TranslateRequest) => {\n client ??= loadSdk().then(\n (Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}),\n );\n const response = await (\n await client\n ).messages.create({\n model: options.model ?? DEFAULT_MODEL,\n max_tokens: options.maxTokens ?? 16000,\n thinking: { type: 'disabled' },\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${Object.keys(request.messages).length} messages: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n try {\n return JSON.parse(text) as Record<string, string>;\n } catch (error) {\n throw new Error('[verbaly] the model did not answer with the JSON object it was asked for', {\n cause: error,\n });\n }\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n return (\n `Translate each value from \"${request.sourceLocale}\" to \"${request.targetLocale}\". ` +\n `Return a JSON object with the same keys and translated values.\\n\\n` +\n JSON.stringify(request.messages, null, 2) +\n glossarySection(request) +\n originsSection(request)\n );\n}\n\n// the glossary is a requirement, not a hint: it exists because a brand name came back translated\nfunction glossarySection(request: TranslateRequest): string {\n const glossary = request.glossary;\n if (!glossary || Object.keys(glossary).length === 0) return '';\n const lines = Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`);\n return `\\n\\nGlossary, these renderings are required wherever the term appears:\\n${lines.join('\\n')}`;\n}\n\nfunction originsSection(request: TranslateRequest): string {\n const origins = request.origins;\n if (!origins || Object.keys(origins).length === 0) return '';\n const lines = Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(', ')}`);\n return `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n${lines.join('\\n')}`;\n}\n\nexport function batchFormat(request: TranslateRequest) {\n const keys = Object.keys(request.messages);\n return {\n type: 'json_schema' as const,\n schema: {\n type: 'object',\n properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),\n required: keys,\n additionalProperties: false,\n },\n };\n}\n\ntype SdkModule = { default: typeof import('@anthropic-ai/sdk').default };\n\n// injectable for tests\nexport async function loadSdk(\n load: () => Promise<SdkModule> = () => import('@anthropic-ai/sdk'),\n): Promise<SdkModule['default']> {\n try {\n const mod = await load();\n return mod.default;\n } catch (error) {\n if (isModuleNotFound(error, '@anthropic-ai/sdk')) {\n throw new Error(\n '[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY',\n { cause: error },\n );\n }\n throw error;\n }\n}\n"],"mappings":";;AAUA,MAAM,gBAAgB;AAEtB,MAAM,SAAS;;;;;AAMf,SAAgB,aAAa,cAA+B;CAC1D,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AAK,KAAK,MAAM,WACI,CAAC,CAAC,KAAK,IAAI;AACnG;AAEA,SAAS,eAAe,SAAmC;CACzD,MAAM,UAAU,QAAQ;CACxB,IAAI,CAAC,WAAW,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG,OAAO;CAE1D,OAAO,+FADO,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,GACkB,CAAC,CAAC,KAAK,IAAI;AACvH;AAEA,SAAgB,YAAY,SAA2B;CACrD,MAAM,OAAO,OAAO,KAAK,QAAQ,QAAQ;CACzC,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,YAAY,OAAO,YAAY,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC;GAC3E,UAAU;GACV,sBAAsB;EACxB;CACF;AACF;AAKA,eAAsB,QACpB,aAAuC,OAAO,sBACf;CAC/B,IAAI;EAEF,QAAO,MADW,KAAK,EAAA,CACZ;CACb,SAAS,OAAO;EACd,IAAI,iBAAiB,OAAO,mBAAmB,GAC7C,MAAM,IAAI,MACR,mMACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;AACF"}
package/dist/cli.js CHANGED
@@ -488,6 +488,15 @@ ${lines.join("\n")}
488
488
 
489
489
  export const sourceLocale: string;
490
490
  export const locales: string[];
491
+ export const routing: import('verbaly').Routing;
492
+ export function localePath(
493
+ locale: string,
494
+ options?: { path?: string; base?: string },
495
+ ): string;
496
+ export function localeFromPath(options?: {
497
+ path?: string;
498
+ base?: string;
499
+ }): string | undefined;
491
500
  export function loadMessages(locale: string): Promise<Record<string, string>>;
492
501
  export function createInstance(
493
502
  options?: import('verbaly').VerbalyOptions<VerbalyKey>,
@@ -508,6 +517,13 @@ ${lines.join("\n")}
508
517
  }
509
518
 
510
519
  export function setLocale(locale: string): Promise<void>;
520
+ export function switchLocale(
521
+ locale: string,
522
+ options?: Omit<
523
+ import('verbaly').SwitchLocaleOptions,
524
+ 'routing' | 'supported' | 'sourceLocale'
525
+ >,
526
+ ): Promise<void>;
511
527
  export function getLocale(): string;
512
528
  export function subscribe(listener: () => void): () => void;
513
529
  }
@@ -660,6 +676,7 @@ function resolveConfig(config = {}) {
660
676
  root,
661
677
  dir,
662
678
  sourceLocale,
679
+ routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
663
680
  locales: [...locales],
664
681
  include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
665
682
  exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
@@ -1396,6 +1413,18 @@ function counted(count, noun, many = `${noun}s`) {
1396
1413
  //#endregion
1397
1414
  //#region src/doctor.ts
1398
1415
  const PREVIEW = 5;
1416
+ function readRoutingChoice(root, configFile) {
1417
+ try {
1418
+ return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
1419
+ } catch {
1420
+ return false;
1421
+ }
1422
+ }
1423
+ const ROUTING_SAYS = {
1424
+ "prefix-except-source": "the source locale has no prefix, every other locale does",
1425
+ "prefix-all": "every locale has a prefix, the source included",
1426
+ "no-prefix": "the language is not in the url, one address serves every locale"
1427
+ };
1399
1428
  const ICON = {
1400
1429
  ok: "✓",
1401
1430
  warn: "⚠",
@@ -1458,6 +1487,12 @@ async function doctor(cfg) {
1458
1487
  }
1459
1488
  const source = catalogs[cfg.sourceLocale];
1460
1489
  if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
1490
+ const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
1491
+ if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
1492
+ else {
1493
+ const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
1494
+ ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
1495
+ }
1461
1496
  const deps = readDependencies(cfg.root);
1462
1497
  const host = detectHost(cfg.root);
1463
1498
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
@@ -2481,6 +2516,13 @@ function injectAlternates(ms, html, alternates) {
2481
2516
  const head = /<\/head\s*>/i.exec(html);
2482
2517
  if (head) ms.appendLeft(head.index, block);
2483
2518
  }
2519
+ const TITLE_TAG = /<title\b([^>]*)>/i;
2520
+ const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
2521
+ function headIsBound(html, attr) {
2522
+ if (REFRESH_META.test(html)) return true;
2523
+ const title = TITLE_TAG.exec(html);
2524
+ return title ? title[1].includes(attr) : true;
2525
+ }
2484
2526
  async function renderSite(cfg, options = {}) {
2485
2527
  const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
2486
2528
  const locales = options.locales ?? cfg.locales;
@@ -2514,10 +2556,12 @@ async function renderSite(cfg, options = {}) {
2514
2556
  });
2515
2557
  const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
2516
2558
  const missing = {};
2559
+ const untranslatedHead = [];
2517
2560
  const urls = [];
2518
2561
  for (const file of files) {
2519
2562
  const html = readFileSync(file, "utf8");
2520
2563
  const rel = relative(site, file).replace(/\\/g, "/");
2564
+ if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
2521
2565
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
2522
2566
  if (wantHreflang) urls.push({
2523
2567
  rel,
@@ -2553,9 +2597,16 @@ async function renderSite(cfg, options = {}) {
2553
2597
  return {
2554
2598
  files: files.length,
2555
2599
  locales: [...locales],
2556
- missing
2600
+ missing,
2601
+ untranslatedHead
2557
2602
  };
2558
2603
  }
2604
+ function formatRenderWarnings(result, sourceLocale) {
2605
+ const lines = [];
2606
+ for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
2607
+ if (result.untranslatedHead.length > 0) lines.push(` ${counted(result.untranslatedHead.length, "page")} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`, ` fix: bind the head too, <title data-verbaly="key"> and a meta through data-verbaly-attr`);
2608
+ return lines;
2609
+ }
2559
2610
  function pageUrl(baseUrl, prefix, rel) {
2560
2611
  const path = rel.replace(/(^|\/)index\.html$/, "$1");
2561
2612
  return `${baseUrl}${prefix}${path ? `/${path}` : "/"}`;
@@ -3311,7 +3362,7 @@ async function runCli(args = process.argv.slice(2)) {
3311
3362
  clean: values.clean
3312
3363
  });
3313
3364
  console.log(`[verbaly] ${counted(result.files, "page")} × ${counted(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3314
- for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3365
+ for (const line of formatRenderWarnings(result, cfg.sourceLocale)) console.warn(line);
3315
3366
  return;
3316
3367
  }
3317
3368
  if (command === "pseudo") {