@verbaly/compiler 0.31.0 → 0.33.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
@@ -20,7 +20,7 @@ Extraction covers `.js`/`.ts`/`.jsx`/`.tsx` **and `.svelte`, `.vue` and `.astro`
20
20
  ## 🧰 CLI
21
21
 
22
22
  ```bash
23
- npx verbaly init # scaffold config + locale catalogs (detects your bundler)
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
26
  npx verbaly extract # sync catalogs + types
@@ -69,12 +69,17 @@ Hand-edited catalogs get the same treatment as imported files: the gate does not
69
69
 
70
70
  **Machine output is a draft until a human says yes.** Everything `translate` writes is recorded in `locales/.verbaly-drafts.json` (commit it, never edit it by hand). `verbaly review` lists the drafts, `--approve` accepts them, and importing a translator's file clears the flag because a human already reviewed it. `verbaly check --drafts` turns "nothing unreviewed ships" into a CI rule; plain `check` leaves it alone, since a draft has a value and is therefore not missing.
71
71
 
72
- Plug your own provider in `verbaly.config.ts`:
72
+ Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider` types it for you:
73
73
 
74
74
  ```ts
75
- translate: {
76
- provider: async ({ sourceLocale, targetLocale, messages }) => ({ ...translated });
77
- }
75
+ import type { TranslateProvider } from '@verbaly/compiler';
76
+
77
+ const provider: TranslateProvider = async ({ sourceLocale, targetLocale, messages, origins }) => {
78
+ // origins maps a key to the source files it appears in, so you can translate with context
79
+ return { ...translated };
80
+ };
81
+
82
+ export default { sourceLocale: 'en', locales: ['en', 'es'], translate: { provider } };
78
83
  ```
79
84
 
80
85
  ## 🌍 Human translators & TMS
@@ -124,6 +129,52 @@ Per-element `data-verbaly-links='{"repo":"https://…"}'` merges over the config
124
129
 
125
130
  > ⚠️ Early development (`0.x`): API not stable yet.
126
131
 
132
+ ## 🧩 Programmatic API
133
+
134
+ Almost nobody needs this: the CLI and the framework plugins cover the whole cycle. It exists for the one case they do not, building your own integration for a bundler or a tool we do not ship.
135
+
136
+ The package exports two layers, and **nothing else is public**. Anything you can see in the source but not in this list is internal and can change in any release.
137
+
138
+ **Your project's own types**, for a typed config file or a custom provider:
139
+
140
+ `VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `TranslateConfig` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions`
141
+
142
+ **Building an integration.** This is exactly what `@verbaly/vite`, `@verbaly/unplugin`, `@verbaly/next`, `@verbaly/astro`, `@verbaly/nuxt` and `@verbaly/mcp` consume, so a third one has everything they have:
143
+
144
+ | Area | Exports |
145
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
146
+ | Config & catalogs | `loadConfig` `resolveConfig` `loadCatalogs` `writeCatalog` · types `Catalog` `Catalogs` |
147
+ | Extraction | `extractProject` `collectOrigins` `syncCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` · type `SyncResult` |
148
+ | Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · type `RuntimeModuleOptions` |
149
+ | Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
150
+ | The gate | `check` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `IssueSeverity` |
151
+ | Coverage | `status` `formatStatusResult` · types `StatusResult` `LocaleStatus` |
152
+ | Draft review | `loadDrafts` `saveDrafts` `markDrafts` `effectiveDrafts` · type `Drafts` |
153
+ | Translation | `translateCatalogs` `resolveProvider` |
154
+ | Static rendering | `renderSite` · types `RenderSiteOptions` `RenderSiteResult` |
155
+
156
+ A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
157
+
158
+ ```ts
159
+ import {
160
+ MessageRegistry,
161
+ loadCatalogs,
162
+ loadConfig,
163
+ runBuildGate,
164
+ transformSource,
165
+ } from '@verbaly/compiler';
166
+
167
+ const cfg = await loadConfig(process.cwd());
168
+ const catalogs = loadCatalogs(cfg);
169
+ const registry = new MessageRegistry();
170
+
171
+ // per file: rewrites t`…` to a keyed call and hands you the messages it found
172
+ const { messages, result } = transformSource(code, id, registry);
173
+
174
+ // at the end of the build: throws with the reason and the remedy
175
+ runBuildGate(cfg, registry);
176
+ ```
177
+
127
178
  ## License
128
179
 
129
180
  [MIT](https://github.com/AronSoto/verbaly/blob/develop/LICENSE) © Aron Soto
@@ -0,0 +1,53 @@
1
+ import { t as isModuleNotFound } from "./config-D8gkaunO.js";
2
+ //#region src/providers/claude.ts
3
+ const DEFAULT_MODEL = "claude-sonnet-5";
4
+ const SYSTEM = `You translate UI strings for the Verbaly i18n library.
5
+ Rules:
6
+ - Translate only the human-readable text, naturally for the target locale.
7
+ - 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 {{ }} || ##.
8
+ - Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;
9
+ function claudeProvider(options = {}) {
10
+ return async (request) => {
11
+ const text = (await new (await (loadSdk()))(options.apiKey ? { apiKey: options.apiKey } : {}).messages.create({
12
+ model: options.model ?? DEFAULT_MODEL,
13
+ max_tokens: options.maxTokens ?? 16e3,
14
+ thinking: { type: "disabled" },
15
+ system: SYSTEM,
16
+ messages: [{
17
+ role: "user",
18
+ content: buildPrompt(request)
19
+ }],
20
+ output_config: { format: batchFormat(request) }
21
+ })).content.find((block) => block.type === "text")?.text ?? "{}";
22
+ return JSON.parse(text);
23
+ };
24
+ }
25
+ function buildPrompt(request) {
26
+ const origins = request.origins;
27
+ const context = origins && Object.keys(origins).length ? `\n\nWhere each string appears (context for tone and length, do not translate these paths):\n` + Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(", ")}`).join("\n") : "";
28
+ return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.\n\n` + JSON.stringify(request.messages, null, 2) + context;
29
+ }
30
+ function batchFormat(request) {
31
+ const keys = Object.keys(request.messages);
32
+ return {
33
+ type: "json_schema",
34
+ schema: {
35
+ type: "object",
36
+ properties: Object.fromEntries(keys.map((key) => [key, { type: "string" }])),
37
+ required: keys,
38
+ additionalProperties: false
39
+ }
40
+ };
41
+ }
42
+ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
43
+ try {
44
+ return (await load()).default;
45
+ } catch (error) {
46
+ if (isModuleNotFound(error, "@anthropic-ai/sdk")) throw new Error("[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", { cause: error });
47
+ throw error;
48
+ }
49
+ }
50
+ //#endregion
51
+ export { claudeProvider };
52
+
53
+ //# sourceMappingURL=claude-CrAkiSVP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-CrAkiSVP.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 claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n return async (request: TranslateRequest) => {\n const Anthropic = await loadSdk();\n const client = new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {});\n const response = await client.messages.create({\n model: options.model ?? DEFAULT_MODEL,\n max_tokens: options.maxTokens ?? 16000,\n thinking: { type: 'disabled' },\n system: SYSTEM,\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n return JSON.parse(text) as Record<string, string>;\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n const origins = request.origins;\n const context =\n origins && Object.keys(origins).length\n ? `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n` +\n Object.entries(origins)\n .map(([key, files]) => ` ${key}: ${files.join(', ')}`)\n .join('\\n')\n : '';\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 context\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":";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F,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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import { basename, dirname, join, relative, resolve } from "node:path";
2
3
  import { parseArgs } from "node:util";
3
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
- import { basename, dirname, join, relative, resolve } from "node:path";
5
5
  import { RICH_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { glob } from "tinyglobby";
@@ -113,6 +113,10 @@ function surplus(a, b) {
113
113
  function list(items) {
114
114
  return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
115
115
  }
116
+ const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*[\w.]+\s*[|:][^{}]*\}\}/;
117
+ function escapedSyntax(message) {
118
+ return ESCAPED_SYNTAX.exec(message)?.[0];
119
+ }
116
120
  function validateMessage(message, locale) {
117
121
  const issues = [];
118
122
  for (const [name, shape] of shapes(message)) {
@@ -691,6 +695,9 @@ var MessageRegistry = class {
691
695
  }
692
696
  return out;
693
697
  }
698
+ strayImports() {
699
+ return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
700
+ }
694
701
  origins() {
695
702
  const out = this.usedKeys();
696
703
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
@@ -725,8 +732,10 @@ function analyze(code, file, options = {}) {
725
732
  });
726
733
  const tagged = [];
727
734
  const usedKeys = [];
735
+ const strayImports = [];
728
736
  walk(ast.program, (node) => {
729
- if (node.type === "TaggedTemplateExpression") {
737
+ if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
738
+ else if (node.type === "TaggedTemplateExpression") {
730
739
  const tag = node.tag;
731
740
  const explicit = explicitId(tag, names);
732
741
  if (!explicit && !isTReference(tag, names)) return;
@@ -755,9 +764,24 @@ function analyze(code, file, options = {}) {
755
764
  });
756
765
  return {
757
766
  tagged,
758
- usedKeys
767
+ usedKeys,
768
+ strayImports
759
769
  };
760
770
  }
771
+ const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
772
+ function collectStrayImports(node, file, out) {
773
+ const source = node.source;
774
+ if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
775
+ for (const spec of node.specifiers) {
776
+ if (spec.type !== "ImportSpecifier") continue;
777
+ const imported = spec.imported;
778
+ if (imported.type === "Identifier" && imported.name === "t") out.push({
779
+ name: "t",
780
+ source: source.value,
781
+ file
782
+ });
783
+ }
784
+ }
761
785
  function handleTrans(code, node, file, tagged, usedKeys, names) {
762
786
  const opening = node.openingElement;
763
787
  const nameNode = opening.name;
@@ -986,6 +1010,7 @@ function analyzeSfc(code, file) {
986
1010
  const options = svelte ? { tNames: ["t", "$t"] } : void 0;
987
1011
  const tagged = [];
988
1012
  const usedKeys = [];
1013
+ const strayImports = [];
989
1014
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
990
1015
  if (frontmatter?.[2]) merge(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length, false);
991
1016
  for (const match of code.matchAll(SCRIPT_RE)) {
@@ -1010,7 +1035,8 @@ function analyzeSfc(code, file) {
1010
1035
  }
1011
1036
  return {
1012
1037
  tagged,
1013
- usedKeys
1038
+ usedKeys,
1039
+ strayImports
1014
1040
  };
1015
1041
  function merge(analysis, offset, markupSegment) {
1016
1042
  if (!analysis) return;
@@ -1028,6 +1054,7 @@ function analyzeSfc(code, file) {
1028
1054
  ...markupSegment && { singleQuote: true }
1029
1055
  });
1030
1056
  usedKeys.push(...analysis.usedKeys);
1057
+ strayImports.push(...analysis.strayImports);
1031
1058
  }
1032
1059
  }
1033
1060
  function analyzeSegment(code, file, options) {
@@ -1330,7 +1357,7 @@ async function doctor(cfg) {
1330
1357
  const deps = readDependencies(cfg.root);
1331
1358
  const host = detectHost(cfg.root);
1332
1359
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
1333
- if (!host) ok("plugin", "no bundler detected, the CLI flow (extract/check) applies");
1360
+ if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
1334
1361
  else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
1335
1362
  else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
1336
1363
  const scanning = cfg.include.length > 0;
@@ -1342,6 +1369,18 @@ async function doctor(cfg) {
1342
1369
  else ok("types", "verbaly.d.ts is up to date");
1343
1370
  }
1344
1371
  const registry = await extractProject(cfg);
1372
+ if (scanning) {
1373
+ const stray = registry.strayImports();
1374
+ if (stray.length > 0) {
1375
+ const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1376
+ error("imports", `${files.length} ${files.length === 1 ? "file imports" : "files import"} t from a verbaly package, which never exports it (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1377
+ }
1378
+ const escaped = [...registry.messages().values()].map((msg) => ({
1379
+ file: rel(msg.file),
1380
+ slice: escapedSyntax(msg.message)
1381
+ })).filter((entry) => entry.slice !== void 0);
1382
+ if (escaped.length > 0) warn("messages", `${escaped.length} extracted ${escaped.length === 1 ? "message keeps" : "messages keep"} a block as literal text (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1383
+ }
1345
1384
  if (source && scanning) {
1346
1385
  const extracted = registry.messages();
1347
1386
  const used = registry.usedKeys();
@@ -2635,7 +2674,7 @@ function line(node) {
2635
2674
  const HELP = `verbaly · i18n compiler
2636
2675
 
2637
2676
  Usage:
2638
- verbaly init scaffold config + locale catalogs (detects your bundler)
2677
+ verbaly init scaffold config + locale catalogs (detects your framework)
2639
2678
  verbaly doctor diagnose the setup (config, catalogs, plugin, types, keys)
2640
2679
  verbaly wrap find hardcoded JSX text and wrap it in t\`…\` (report; --write applies)
2641
2680
  verbaly extract scan sources, update catalogs and types
@@ -2779,6 +2818,7 @@ async function runCli(args = process.argv.slice(2)) {
2779
2818
  const total = registry.messages().size;
2780
2819
  console.log(`[verbaly] ${total} messages · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
2781
2820
  for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
2821
+ reportEscapedSyntax(cfg, registry);
2782
2822
  }
2783
2823
  await runExtract();
2784
2824
  if (values.watch) {
@@ -2989,6 +3029,19 @@ async function runCli(args = process.argv.slice(2)) {
2989
3029
  console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
2990
3030
  process.exitCode = 1;
2991
3031
  }
3032
+ function formatCliError(error) {
3033
+ const message = error instanceof Error ? error.message : String(error);
3034
+ return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3035
+ }
3036
+ function reportEscapedSyntax(cfg, registry) {
3037
+ for (const msg of registry.messages().values()) {
3038
+ const slice = escapedSyntax(msg.message);
3039
+ if (!slice) continue;
3040
+ const file = relative(cfg.root, msg.file).replaceAll("\\", "/");
3041
+ console.warn(` ${file}: ${slice} renders as literal text, a tagged template has no params`);
3042
+ console.warn(" use t(key, params) for a plural or format block, or pass a ${…} value");
3043
+ }
3044
+ }
2992
3045
  const COMMON_FLAGS = /* @__PURE__ */ new Set([
2993
3046
  "root",
2994
3047
  "dir",
@@ -3041,7 +3094,7 @@ function rejectStrayFlags(command, values) {
3041
3094
  //#endregion
3042
3095
  //#region src/cli.ts
3043
3096
  runCli().catch((error) => {
3044
- console.error("[verbaly]", error instanceof Error ? error.message : error);
3097
+ console.error(formatCliError(error));
3045
3098
  process.exitCode = 1;
3046
3099
  });
3047
3100
  //#endregion