@verbaly/compiler 0.53.0 → 0.55.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
@@ -11,7 +11,7 @@
11
11
 
12
12
  ---
13
13
 
14
- The compiler behind [Verbaly](https://github.com/AronSoto/verbaly): AST extraction of `` t`…` `` **and JSX `<Trans>` children** into stable hashed keys (or **readable keys** via `` t.id('inbox.title')`…` `` and `<Trans id="inbox.title">…</Trans>`), flat JSON catalog sync, and typed codegen. It also ships the **`verbaly` CLI**.
14
+ The compiler behind [Verbaly](https://github.com/AronSoto/verbaly): AST extraction of `` t`…` `` **and JSX `<Trans>` children** into stable hashed keys (or **readable keys** via `` t.id('inbox.title')`…` `` and `<Trans id="inbox.title">…</Trans>`), JSON catalog sync, and typed codegen. It also ships the **`verbaly` CLI**.
15
15
 
16
16
  Extraction covers `.js`/`.ts`/`.jsx`/`.tsx` **and `.svelte`, `.vue` and `.astro` single-file components**: script blocks and frontmatter, plus markup expressions (Svelte's `$t` store form included). Text that only sits on screen is never extracted, so a documented snippet cannot become a real key.
17
17
 
@@ -23,6 +23,7 @@ Extraction covers `.js`/`.ts`/`.jsx`/`.tsx` **and `.svelte`, `.vue` and `.astro`
23
23
  npx verbaly init # scaffold config + locale catalogs (detects your framework)
24
24
  npx verbaly doctor # diagnose the setup (config, catalogs, wiring, types, translations)
25
25
  npx verbaly wrap # onboarding codemod: report plain JSX text, --write wraps it in t``
26
+ npx verbaly migrate # port catalogs from another i18n library (--write applies, --plurals merges)
26
27
  npx verbaly extract # sync catalogs + types
27
28
  npx verbaly extract --watch # keep extracting as you code (dev loop)
28
29
  npx verbaly extract --prune # drop orphaned keys
@@ -30,13 +31,14 @@ npx verbaly status # coverage per locale, plus unreviewed and broken cou
30
31
  npx verbaly check # exit 1 if anything is missing or broken (CI)
31
32
  npx verbaly translate # fill missing translations via Claude (or your provider), as drafts
32
33
  npx verbaly review # list machine drafts, --approve accepts them
34
+ npx verbaly-studio # the same catalogs on localhost (@verbaly/studio, separate package)
33
35
  npx verbaly export # translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)
34
36
  npx verbaly import <files> # fill catalogs back from translated XLIFF/CSV/PO files
35
37
  npx verbaly pseudo # generate a pseudo-locale catalog for i18n QA (en-XA)
36
38
  npx verbaly render # pre-fill data-verbaly HTML per locale (SSG, kills the FOUC)
37
39
  ```
38
40
 
39
- Reads `verbaly.config.{js,mjs,ts,mts,json}` (TS configs need `esbuild` installed). Generates `locales/<locale>.json` (flat, portable, no proprietary format) and `verbaly.d.ts` with params typed per key.
41
+ Reads `verbaly.config.{js,mjs,ts,mts,json}` (TS configs need `esbuild` installed). Generates `locales/<locale>.json` (portable JSON, flat or nested, whichever the file already is) and `verbaly.d.ts` with params typed per key.
40
42
 
41
43
  ## 🚦 The build gate
42
44
 
@@ -156,7 +158,7 @@ The other format cases stay in the runtime always, and that is measured rather t
156
158
 
157
159
  ## 🌍 Human translators & TMS
158
160
 
159
- 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:
161
+ Catalogs are **plain JSON**, in whichever shape your file already has: 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:
160
162
 
161
163
  ```bash
162
164
  npx verbaly export # verbaly-export/<locale>.xlf (XLIFF 2.0, source + target per unit)
package/dist/cli.js CHANGED
@@ -2428,6 +2428,169 @@ function csvRows(content) {
2428
2428
  return rows;
2429
2429
  }
2430
2430
  //#endregion
2431
+ //#region src/migrate.ts
2432
+ const KNOWN = [
2433
+ "i18next",
2434
+ "react-i18next",
2435
+ "vue-i18n",
2436
+ "react-intl",
2437
+ "next-intl",
2438
+ "svelte-i18n"
2439
+ ];
2440
+ function detectLibraries(root) {
2441
+ const path = join(root, "package.json");
2442
+ if (!existsSync(path)) return [];
2443
+ let manifest;
2444
+ try {
2445
+ manifest = JSON.parse(readFileSync(path, "utf8"));
2446
+ } catch {
2447
+ return [];
2448
+ }
2449
+ const deps = {
2450
+ ...manifest.dependencies,
2451
+ ...manifest.devDependencies
2452
+ };
2453
+ return KNOWN.filter((name) => deps[name] !== void 0);
2454
+ }
2455
+ const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
2456
+ const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
2457
+ const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
2458
+ const NESTED = /\$t\(/;
2459
+ const CATEGORIES = [
2460
+ "zero",
2461
+ "one",
2462
+ "two",
2463
+ "few",
2464
+ "many",
2465
+ "other"
2466
+ ];
2467
+ const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
2468
+ function convertBraces(text) {
2469
+ return text.replace(PLAIN, "{$1}");
2470
+ }
2471
+ function toHash(text) {
2472
+ return text.replaceAll("{count}", "#");
2473
+ }
2474
+ function order(a, b) {
2475
+ return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
2476
+ }
2477
+ function mergePlurals(locale, catalog, out, plurals, skipped) {
2478
+ const groups = /* @__PURE__ */ new Map();
2479
+ const legacy = /* @__PURE__ */ new Set();
2480
+ for (const [key, value] of Object.entries(catalog)) {
2481
+ const match = SUFFIX.exec(key);
2482
+ if (!match || typeof value !== "string") continue;
2483
+ const [, base, suffix] = match;
2484
+ if (suffix === "plural") legacy.add(base);
2485
+ const category = suffix === "plural" ? "other" : suffix;
2486
+ if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
2487
+ groups.get(base).set(category, {
2488
+ key,
2489
+ value
2490
+ });
2491
+ }
2492
+ for (const [base, forms] of groups) {
2493
+ const bare = catalog[base];
2494
+ if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
2495
+ key: base,
2496
+ value: bare
2497
+ });
2498
+ else if (bare !== void 0) {
2499
+ skipped.push({
2500
+ locale,
2501
+ key: base,
2502
+ reason: `"${base}" already exists, so merging would overwrite it`
2503
+ });
2504
+ continue;
2505
+ }
2506
+ if (!forms.has("other")) {
2507
+ skipped.push({
2508
+ locale,
2509
+ key: base,
2510
+ reason: "no _other form, so the block would have no catch-all"
2511
+ });
2512
+ continue;
2513
+ }
2514
+ if (forms.size === 1) {
2515
+ skipped.push({
2516
+ locale,
2517
+ key: base,
2518
+ reason: "only a plural form, so add the singular before merging"
2519
+ });
2520
+ continue;
2521
+ }
2522
+ const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
2523
+ const merged = `{count | ${sorted.map(([category, form]) => `${category}: ${toHash(convertBraces(form.value))}`).join(" | ")}}`;
2524
+ for (const [, form] of sorted) delete out[form.key];
2525
+ out[base] = merged;
2526
+ plurals.push({
2527
+ locale,
2528
+ key: base,
2529
+ from: sorted.map(([, form]) => form.key),
2530
+ after: merged
2531
+ });
2532
+ }
2533
+ }
2534
+ function migrateCatalogs(cfg, options = {}) {
2535
+ const braces = [];
2536
+ const plurals = [];
2537
+ const skipped = [];
2538
+ const written = [];
2539
+ for (const locale of cfg.locales) {
2540
+ const catalog = readCatalog(cfg, locale);
2541
+ const out = { ...catalog };
2542
+ for (const [key, value] of Object.entries(catalog)) {
2543
+ if (typeof value !== "string") continue;
2544
+ if (NESTED.test(value)) {
2545
+ skipped.push({
2546
+ locale,
2547
+ key,
2548
+ reason: "uses $t() nesting, which has no direct equivalent"
2549
+ });
2550
+ continue;
2551
+ }
2552
+ if (UNESCAPED.test(value)) {
2553
+ skipped.push({
2554
+ locale,
2555
+ key,
2556
+ reason: "uses {{- name}}, so decide whether the message is rich"
2557
+ });
2558
+ continue;
2559
+ }
2560
+ if (FORMATTED.test(value)) {
2561
+ skipped.push({
2562
+ locale,
2563
+ key,
2564
+ reason: "uses an i18next format, which needs the matching Verbaly one"
2565
+ });
2566
+ continue;
2567
+ }
2568
+ const after = convertBraces(value);
2569
+ if (after !== value) {
2570
+ braces.push({
2571
+ locale,
2572
+ key,
2573
+ before: value,
2574
+ after
2575
+ });
2576
+ out[key] = after;
2577
+ }
2578
+ }
2579
+ if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped);
2580
+ if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
2581
+ writeCatalog(cfg, locale, out);
2582
+ written.push(locale);
2583
+ }
2584
+ }
2585
+ return {
2586
+ detected: detectLibraries(cfg.root),
2587
+ braces,
2588
+ plurals,
2589
+ skipped,
2590
+ written
2591
+ };
2592
+ }
2593
+ //#endregion
2431
2594
  //#region src/render.ts
2432
2595
  function localeInstance(catalogs, locale, sourceLocale) {
2433
2596
  return createVerbaly({
@@ -3238,6 +3401,7 @@ Usage:
3238
3401
  verbaly init scaffold config + locale catalogs (detects your framework)
3239
3402
  verbaly doctor diagnose the setup (config, catalogs, plugin, types, keys)
3240
3403
  verbaly wrap find hardcoded JSX text and wrap it in t\`…\` (report; --write applies)
3404
+ verbaly migrate port catalogs from another i18n library (report; --write applies)
3241
3405
  verbaly extract scan sources, update catalogs and types
3242
3406
  verbaly status translation coverage per locale, at a glance
3243
3407
  verbaly check verify translations are complete (CI)
@@ -3255,7 +3419,8 @@ Options:
3255
3419
  --locales <csv> extra locales; for translate: target locales to fill
3256
3420
  --prune drop keys no longer referenced (extract)
3257
3421
  --watch keep extracting as source files change (extract)
3258
- --write apply the rewrites instead of only reporting (wrap)
3422
+ --write apply the rewrites instead of only reporting (wrap, migrate)
3423
+ --plurals also merge _one/_other into one message with variants (migrate)
3259
3424
  --json machine-readable output (status)
3260
3425
  --drafts also fail on unreviewed machine translations (check)
3261
3426
  --approve mark listed drafts as reviewed (review)
@@ -3304,6 +3469,7 @@ async function runCli(args = process.argv.slice(2)) {
3304
3469
  sitemap: { type: "boolean" },
3305
3470
  clean: { type: "boolean" },
3306
3471
  "dry-run": { type: "boolean" },
3472
+ plurals: { type: "boolean" },
3307
3473
  format: { type: "string" },
3308
3474
  out: { type: "string" },
3309
3475
  missing: { type: "boolean" },
@@ -3387,6 +3553,30 @@ async function runCli(args = process.argv.slice(2)) {
3387
3553
  }
3388
3554
  return;
3389
3555
  }
3556
+ if (command === "migrate") {
3557
+ const result = migrateCatalogs(cfg, {
3558
+ write: values.write,
3559
+ plurals: values.plurals
3560
+ });
3561
+ const from = result.detected.length ? result.detected.join(", ") : "no known i18n library";
3562
+ const changes = result.braces.length + result.plurals.length;
3563
+ if (changes === 0 && result.skipped.length === 0) {
3564
+ console.log(`[verbaly] catalogs need nothing (${from}) ✓`);
3565
+ return;
3566
+ }
3567
+ const verb = values.write ? "ported" : "would port";
3568
+ const note = values.write ? "" : " (report only, use --write to apply)";
3569
+ console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${note}`);
3570
+ for (const entry of result.braces) console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);
3571
+ for (const entry of result.plurals) console.log(` ${entry.locale} ${entry.key} ${entry.from.join(" + ")} → ${entry.after}`);
3572
+ if (!values.plurals && changes > 0) console.log(" --plurals also merges _one/_other into one message with variants");
3573
+ if (result.skipped.length > 0) {
3574
+ console.log(" needs a human:");
3575
+ for (const entry of result.skipped) console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);
3576
+ }
3577
+ if (values.write) console.log(" next: run verbaly check");
3578
+ return;
3579
+ }
3390
3580
  if (command === "wrap") {
3391
3581
  const result = await wrapProject(cfg, { write: values.write });
3392
3582
  if (result.wrapped.length === 0 && result.skipped.length === 0) {
@@ -3647,6 +3837,7 @@ const COMMAND_FLAGS = {
3647
3837
  "watch"
3648
3838
  ],
3649
3839
  wrap: ["write"],
3840
+ migrate: ["write", "plurals"],
3650
3841
  status: ["json"],
3651
3842
  check: ["reporter", "drafts"],
3652
3843
  translate: ["model", "dry-run"],