@verbaly/compiler 0.48.0 → 0.50.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/dist/{claude-B-vethK9.js → claude-CbKynSMc.js} +2 -2
- package/dist/{claude-B-vethK9.js.map → claude-CbKynSMc.js.map} +1 -1
- package/dist/cli.js +38 -3
- package/dist/cli.js.map +1 -1
- package/dist/{config-iLrfRYDB.js → config-DYlbHrPc.js} +2 -2
- package/dist/config-DYlbHrPc.js.map +1 -0
- package/dist/index.d.ts +65 -46
- package/dist/index.js +96 -13
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/config-iLrfRYDB.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as isModuleNotFound } from "./config-
|
|
1
|
+
import { n as isModuleNotFound } from "./config-DYlbHrPc.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-CbKynSMc.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-
|
|
1
|
+
{"version":3,"file":"claude-CbKynSMc.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,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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
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
|
|
5
|
-
import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
|
|
5
|
+
import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { glob } from "tinyglobby";
|
|
8
8
|
import { parse as parse$1 } from "@babel/parser";
|
|
@@ -2438,6 +2438,8 @@ function localeInstance(catalogs, locale, sourceLocale) {
|
|
|
2438
2438
|
}
|
|
2439
2439
|
const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
|
|
2440
2440
|
const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
|
|
2441
|
+
const CATALOG_OPEN = "<!--verbaly:catalog-->";
|
|
2442
|
+
const CATALOG_CLOSE = "<!--/verbaly:catalog-->";
|
|
2441
2443
|
const REDIRECT_OPEN = "<!--verbaly:redirect-->";
|
|
2442
2444
|
const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
|
|
2443
2445
|
const VOID = new Set(VOID_TAGS);
|
|
@@ -2456,6 +2458,7 @@ function renderHtml(html, options) {
|
|
|
2456
2458
|
const t = v.t;
|
|
2457
2459
|
const ms = new MagicString(html);
|
|
2458
2460
|
const missing = /* @__PURE__ */ new Set();
|
|
2461
|
+
const used = /* @__PURE__ */ new Set();
|
|
2459
2462
|
const skip = protectedRanges(html);
|
|
2460
2463
|
const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
|
|
2461
2464
|
const filled = [];
|
|
@@ -2498,6 +2501,7 @@ function renderHtml(html, options) {
|
|
|
2498
2501
|
if (key) {
|
|
2499
2502
|
if (!v.has(key)) missing.add(key);
|
|
2500
2503
|
else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
|
|
2504
|
+
used.add(key);
|
|
2501
2505
|
const close = findClose(html, tagName, openEnd, inSkip);
|
|
2502
2506
|
if (close) {
|
|
2503
2507
|
const text = t(key, args);
|
|
@@ -2523,6 +2527,7 @@ function renderHtml(html, options) {
|
|
|
2523
2527
|
missing.add(attrKey);
|
|
2524
2528
|
continue;
|
|
2525
2529
|
}
|
|
2530
|
+
used.add(attrKey);
|
|
2526
2531
|
const value = safeAttribute(name, t(attrKey, args));
|
|
2527
2532
|
if (value !== void 0) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);
|
|
2528
2533
|
}
|
|
@@ -2530,11 +2535,24 @@ function renderHtml(html, options) {
|
|
|
2530
2535
|
}
|
|
2531
2536
|
if (options.alternates?.length) injectAlternates(ms, html, options.alternates);
|
|
2532
2537
|
if (options.redirect) injectRedirect(ms, html, options.redirect);
|
|
2538
|
+
if (options.inlineCatalog && options.locale !== sourceLocale) {
|
|
2539
|
+
const slice = pageSlice(v, options.locale, used);
|
|
2540
|
+
if (Object.keys(slice).length > 0) injectCatalog(ms, html, slice);
|
|
2541
|
+
}
|
|
2533
2542
|
return {
|
|
2534
2543
|
html: ms.toString(),
|
|
2535
|
-
missing: [...missing]
|
|
2544
|
+
missing: [...missing],
|
|
2545
|
+
used: [...used]
|
|
2536
2546
|
};
|
|
2537
2547
|
}
|
|
2548
|
+
function pageSlice(v, locale, used) {
|
|
2549
|
+
const slice = {};
|
|
2550
|
+
for (const key of used) {
|
|
2551
|
+
const found = v.inspect(key);
|
|
2552
|
+
if (found?.from === locale) slice[key] = found.source;
|
|
2553
|
+
}
|
|
2554
|
+
return slice;
|
|
2555
|
+
}
|
|
2538
2556
|
function publicPath(rel) {
|
|
2539
2557
|
const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
|
|
2540
2558
|
return path.length > 1 ? path.replace(/\/+$/, "") : path;
|
|
@@ -2602,6 +2620,22 @@ function injectAlternates(ms, html, alternates) {
|
|
|
2602
2620
|
const head = /<\/head\s*>/i.exec(html);
|
|
2603
2621
|
if (head) ms.appendLeft(head.index, block);
|
|
2604
2622
|
}
|
|
2623
|
+
function injectCatalog(ms, html, messages) {
|
|
2624
|
+
const json = JSON.stringify(messages).replace(/<\//g, "<\\/");
|
|
2625
|
+
const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
|
|
2626
|
+
const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
|
|
2627
|
+
const from = html.indexOf(CATALOG_OPEN);
|
|
2628
|
+
if (from !== -1) {
|
|
2629
|
+
const to = html.indexOf(CATALOG_CLOSE, from);
|
|
2630
|
+
if (to !== -1) {
|
|
2631
|
+
const end = to + 23;
|
|
2632
|
+
if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
|
|
2633
|
+
return;
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
const head = /<\/head\s*>/i.exec(html);
|
|
2637
|
+
if (head) ms.appendLeft(head.index, block);
|
|
2638
|
+
}
|
|
2605
2639
|
const TITLE_TAG = /<title\b([^>]*)>/i;
|
|
2606
2640
|
const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
|
|
2607
2641
|
const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
|
|
@@ -2674,7 +2708,8 @@ async function renderSite(cfg, options = {}) {
|
|
|
2674
2708
|
base,
|
|
2675
2709
|
pages
|
|
2676
2710
|
},
|
|
2677
|
-
redirect: routed && locale === cfg.sourceLocale ? script : void 0
|
|
2711
|
+
redirect: routed && locale === cfg.sourceLocale ? script : void 0,
|
|
2712
|
+
inlineCatalog: cfg.render.inlineCatalog === true
|
|
2678
2713
|
});
|
|
2679
2714
|
for (const key of result.missing) {
|
|
2680
2715
|
const list = missing[locale] ??= [];
|