@verbaly/compiler 0.41.0 → 0.42.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 +13 -1
- package/dist/{claude-DYAwaLJz.js → claude-CJsHMxsE.js} +2 -2
- package/dist/{claude-DYAwaLJz.js.map → claude-CJsHMxsE.js.map} +1 -1
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/{config-dVhga3PS.js → config-BjWd3mkT.js} +2 -1
- package/dist/config-BjWd3mkT.js.map +1 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +11 -6
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/dist/config-dVhga3PS.js.map +0 -1
package/README.md
CHANGED
|
@@ -138,6 +138,18 @@ await switchLocale('es', { navigate: (path) => router.push(path) });
|
|
|
138
138
|
|
|
139
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
140
|
|
|
141
|
+
## 🧪 ICU, and what it costs you
|
|
142
|
+
|
|
143
|
+
Verbaly's own syntax covers plurals, selects and formats, and [ICU message syntax](https://unicode-org.github.io/icu/userguide/format_parse/messages/) is the escape hatch for what it does not. **You pay for the escape hatch only if you open it.** The compiler reads your catalogs, and if any message uses ICU it wires the parser into the generated runtime; if none does, the parser is not in your bundle at all. Measured on a real app bundle: **544 bytes gzip**, which is 15% of the runtime.
|
|
144
|
+
|
|
145
|
+
Nothing to configure. The one case the catalogs cannot answer is a message that arrives after the build, from a CMS or a fetched catalog:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
export default { locales: ['en', 'es'], icu: true }; // ship the parser anyway
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Without that, such a message renders **its own source text** and warns once naming the fix, rather than half-rendering into something that looks plausible.
|
|
152
|
+
|
|
141
153
|
## 🌍 Human translators & TMS
|
|
142
154
|
|
|
143
155
|
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:
|
|
@@ -209,7 +221,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
209
221
|
|
|
210
222
|
| Area | Exports |
|
|
211
223
|
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
212
|
-
| Config & catalogs | `loadConfig` `resolveConfig` `loadCatalogs` `writeCatalog` · types `Catalog` `Catalogs`
|
|
224
|
+
| Config & catalogs | `loadConfig` `resolveConfig` `loadCatalogs` `writeCatalog` `needsIcu` · types `Catalog` `Catalogs` |
|
|
213
225
|
| Extraction | `extractProject` `collectOrigins` `syncCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` · type `SyncResult` |
|
|
214
226
|
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · type `RuntimeModuleOptions` |
|
|
215
227
|
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as isModuleNotFound } from "./config-
|
|
1
|
+
import { n as isModuleNotFound } from "./config-BjWd3mkT.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-
|
|
72
|
+
//# sourceMappingURL=claude-CJsHMxsE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-
|
|
1
|
+
{"version":3,"file":"claude-CJsHMxsE.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,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,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
|
@@ -677,6 +677,7 @@ function resolveConfig(config = {}) {
|
|
|
677
677
|
dir,
|
|
678
678
|
sourceLocale,
|
|
679
679
|
routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
|
|
680
|
+
icu: config.icu,
|
|
680
681
|
locales: [...locales],
|
|
681
682
|
include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
|
|
682
683
|
exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
|