@bison-lab/payload-core 4.40.0 → 5.0.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 +24 -4
- package/dist/admin.mjs +5 -2
- package/dist/admin.mjs.map +1 -1
- package/dist/{capability-BVDhJV8A.d.mts → capability-CqdYCzG1.d.mts} +17 -7
- package/dist/{capability-BVDhJV8A.d.mts.map → capability-CqdYCzG1.d.mts.map} +1 -1
- package/dist/{capability-DdnN7AHB.mjs → capability-DHPE2kon.mjs} +235 -19
- package/dist/capability-DHPE2kon.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/locale-B6rUVwpg.mjs.map +1 -1
- package/dist/{locale-5z7KTvRJ.d.mts → locale-CTT3nn6T.d.mts} +5 -4
- package/dist/locale-CTT3nn6T.d.mts.map +1 -0
- package/dist/{messages-Bk1uYO3o.mjs → messages-dZV_aAnR.mjs} +2 -2
- package/dist/{messages-Bk1uYO3o.mjs.map → messages-dZV_aAnR.mjs.map} +1 -1
- package/dist/navigation.d.mts +2 -2
- package/dist/og.d.mts +1 -1
- package/dist/{published-CY5PIy5W.d.mts → published-B3etM6X5.d.mts} +2 -2
- package/dist/{published-CY5PIy5W.d.mts.map → published-B3etM6X5.d.mts.map} +1 -1
- package/dist/{published-BC8kg47c.d.mts → published-QDNmDi02.d.mts} +2 -2
- package/dist/{published-BC8kg47c.d.mts.map → published-QDNmDi02.d.mts.map} +1 -1
- package/dist/{strings-Bafwdg67.mjs → strings-Fd7kUCT7.mjs} +4 -4
- package/dist/strings-Fd7kUCT7.mjs.map +1 -0
- package/dist/theme.d.mts +2 -2
- package/dist/translate-messages-cli.mjs +3 -3
- package/dist/translate-messages-cli.mjs.map +1 -1
- package/dist/translate.d.mts +225 -3
- package/dist/translate.d.mts.map +1 -1
- package/dist/translate.mjs +238 -5
- package/dist/translate.mjs.map +1 -1
- package/package.json +7 -9
- package/dist/capability-DdnN7AHB.mjs.map +0 -1
- package/dist/locale-5z7KTvRJ.d.mts.map +0 -1
- package/dist/strings-Bafwdg67.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages-
|
|
1
|
+
{"version":3,"file":"messages-dZV_aAnR.mjs","names":[],"sources":["../src/translate/messages.ts"],"sourcesContent":["import { translateStrings } from \"./strings\";\nimport type { TranslateSite, Translator } from \"./types\";\n\n/** A next-intl message file: nested objects and arrays with string leaves. */\nexport type MessagesJson = string | number | boolean | null | MessagesJson[] | { [key: string]: MessagesJson };\n\nconst BATCH_SIZE = 40;\n\n/** Every string leaf as [path, value]; array indexes are path segments. */\nfunction stringLeaves(\n node: MessagesJson,\n path: string[] = [],\n out: Array<[string[], string]> = [],\n): Array<[string[], string]> {\n if (typeof node === \"string\") out.push([path, node]);\n else if (Array.isArray(node)) node.forEach((item, index) => stringLeaves(item, [...path, String(index)], out));\n else if (node && typeof node === \"object\") {\n for (const [key, value] of Object.entries(node)) stringLeaves(value, [...path, key], out);\n }\n return out;\n}\n\nfunction getAtPath(root: MessagesJson, path: string[]): MessagesJson | undefined {\n let current: MessagesJson | undefined = root;\n for (const segment of path) {\n if (current == null || typeof current !== \"object\") return undefined;\n current = Array.isArray(current) ? current[Number(segment)] : current[segment];\n }\n return current;\n}\n\nfunction setAtPath(root: { [key: string]: MessagesJson }, path: string[], value: string): void {\n let current: { [key: string]: MessagesJson } | MessagesJson[] = root;\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i]!;\n const wantArray = /^\\d+$/.test(path[i + 1]!);\n const container = current as Record<string, MessagesJson>;\n let child = container[segment];\n // Create the container when missing, and REPAIR it when the existing\n // target node has the opposite shape from the source (the source changed\n // an object into a list) so string keys never land in an array or the\n // reverse.\n if (child == null || typeof child !== \"object\" || Array.isArray(child) !== wantArray) {\n child = wantArray ? [] : {};\n container[segment] = child;\n }\n current = child as { [key: string]: MessagesJson } | MessagesJson[];\n }\n (current as Record<string, MessagesJson>)[path[path.length - 1]!] = value;\n}\n\n/**\n * The `{name}` arguments of a message, sorted. Plural and select messages are\n * skipped (their branch bodies are braced text the model rightly translates),\n * so this only checks plain interpolations.\n */\nfunction placeholderNames(message: string): string | null {\n if (/,\\s*(plural|select|selectordinal)\\s*,/.test(message)) return null;\n const names = [...message.matchAll(/\\{\\s*([A-Za-z_][\\w]*)\\s*\\}/g)].map((match) => match[1]!);\n return names.sort().join(\",\");\n}\n\n/** A translation that dropped or renamed a `{placeholder}` would break at render; keep the source instead. */\nexport function keepsPlaceholders(source: string, translated: string): boolean {\n const before = placeholderNames(source);\n return before === null || before === placeholderNames(translated);\n}\n\nexport interface FillMessagesResult {\n /** The target file to write. */\n messages: MessagesJson;\n /** Keys translated. */\n translated: number;\n /**\n * Keys whose batch failed, or whose translation lost a `{placeholder}`.\n * They hold the source text, so the file stays\n * complete (a hole renders as MISSING_MESSAGE); a plain re-run will not\n * retry them, `--force` (or a hand edit) will.\n */\n fellBack: number;\n}\n\n/**\n * Fills a target next-intl message file from the source file. The source is\n * the truth; only keys that are missing or empty in the target are\n * translated, so reviewed copy is never overwritten, unless `force`\n * re-translates every key. Batches of 40, so one failure costs at most 40\n * keys. `{placeholders}` survive because the translator's prompt keeps them.\n */\nexport async function fillMessages(options: {\n source: MessagesJson;\n target?: MessagesJson;\n translator: Translator;\n from: string;\n to: string;\n force?: boolean;\n context?: string;\n site?: TranslateSite;\n onProgress?: (done: number, total: number) => void;\n}): Promise<FillMessagesResult> {\n const base =\n !options.force && options.target && typeof options.target === \"object\" && !Array.isArray(options.target)\n ? (structuredClone(options.target) as { [key: string]: MessagesJson })\n : {};\n const missing = stringLeaves(options.source).filter(([path]) => {\n const existing = getAtPath(base, path);\n return typeof existing !== \"string\" || existing.trim() === \"\";\n });\n\n let translated = 0;\n let fellBack = 0;\n for (let i = 0; i < missing.length; i += BATCH_SIZE) {\n const batch = missing.slice(i, i + BATCH_SIZE);\n const sources = batch.map(([, value]) => value);\n const result = await translateStrings(sources, {\n translator: options.translator,\n from: options.from,\n to: options.to,\n context: options.context ?? \"Website UI strings\",\n ...(options.site ? { site: options.site } : {}),\n });\n batch.forEach(([path, source], index) => {\n const value = result?.[index];\n if (value !== undefined && keepsPlaceholders(source, value)) {\n translated += 1;\n setAtPath(base, path, value);\n } else {\n fellBack += 1;\n setAtPath(base, path, source);\n }\n });\n options.onProgress?.(Math.min(i + BATCH_SIZE, missing.length), missing.length);\n }\n return { messages: base, translated, fellBack };\n}\n"],"mappings":";;AAMA,MAAM,aAAa;;AAGnB,SAAS,aACP,MACA,OAAiB,EAAE,EACnB,MAAiC,EAAE,EACR;AAC3B,KAAI,OAAO,SAAS,SAAU,KAAI,KAAK,CAAC,MAAM,KAAK,CAAC;UAC3C,MAAM,QAAQ,KAAK,CAAE,MAAK,SAAS,MAAM,UAAU,aAAa,MAAM,CAAC,GAAG,MAAM,OAAO,MAAM,CAAC,EAAE,IAAI,CAAC;UACrG,QAAQ,OAAO,SAAS,SAC/B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,CAAE,cAAa,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,IAAI;AAE3F,QAAO;;AAGT,SAAS,UAAU,MAAoB,MAA0C;CAC/E,IAAI,UAAoC;AACxC,MAAK,MAAM,WAAW,MAAM;AAC1B,MAAI,WAAW,QAAQ,OAAO,YAAY,SAAU,QAAO,KAAA;AAC3D,YAAU,MAAM,QAAQ,QAAQ,GAAG,QAAQ,OAAO,QAAQ,IAAI,QAAQ;;AAExE,QAAO;;AAGT,SAAS,UAAU,MAAuC,MAAgB,OAAqB;CAC7F,IAAI,UAA4D;AAChE,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS,GAAG,KAAK;EACxC,MAAM,UAAU,KAAK;EACrB,MAAM,YAAY,QAAQ,KAAK,KAAK,IAAI,GAAI;EAC5C,MAAM,YAAY;EAClB,IAAI,QAAQ,UAAU;AAKtB,MAAI,SAAS,QAAQ,OAAO,UAAU,YAA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AAS;AACvB,OAAI,UAAU,KAAA,KAAa,kBAAkB,QAAQ,MAAM,EAAE;AAC3D,kBAAc;AACd,cAAU,MAAM,MAAM,MAAM;UACvB;AACL,gBAAY;AACZ,cAAU,MAAM,MAAM,OAAO;;IAE/B;AACF,UAAQ,aAAa,KAAK,IAAI,IAAI,YAAY,QAAQ,OAAO,EAAE,QAAQ,OAAO;;AAEhF,QAAO;EAAE,UAAU;EAAM;EAAY;EAAU"}
|
package/dist/navigation.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as LocaleRead } from "./locale-
|
|
2
|
-
import { C as NAVIGATION_FOOTER_SLUG, D as NavigationFooter, E as NavigationDoc, O as NavigationHeader, S as NAVIGATION_FOOTER_DB_NAME, T as NavigationBar, _ as validateExternalHref, a as FOOTER_MAX_LINK_COLUMNS, b as NAVIGATION_DB_NAME, c as FooterColumnWidth, d as normalizeFooterDesktop, g as isValidExternalHref, i as FOOTER_MAX_COLUMNS, l as FooterSocial, m as EXTERNAL_HREF_MESSAGE, o as FOOTER_SOCIALS, p as validateFooterSocialUrl, r as FOOTER_COLUMN_WIDTHS, s as FOOTER_TWELFTHS, t as getNavigation, u as footerDesktopTracks, v as validateHeaderCta, w as NAVIGATION_SLUG } from "./published-
|
|
1
|
+
import { t as LocaleRead } from "./locale-CTT3nn6T.mjs";
|
|
2
|
+
import { C as NAVIGATION_FOOTER_SLUG, D as NavigationFooter, E as NavigationDoc, O as NavigationHeader, S as NAVIGATION_FOOTER_DB_NAME, T as NavigationBar, _ as validateExternalHref, a as FOOTER_MAX_LINK_COLUMNS, b as NAVIGATION_DB_NAME, c as FooterColumnWidth, d as normalizeFooterDesktop, g as isValidExternalHref, i as FOOTER_MAX_COLUMNS, l as FooterSocial, m as EXTERNAL_HREF_MESSAGE, o as FOOTER_SOCIALS, p as validateFooterSocialUrl, r as FOOTER_COLUMN_WIDTHS, s as FOOTER_TWELFTHS, t as getNavigation, u as footerDesktopTracks, v as validateHeaderCta, w as NAVIGATION_SLUG } from "./published-QDNmDi02.mjs";
|
|
3
3
|
export { EXTERNAL_HREF_MESSAGE, FOOTER_COLUMN_WIDTHS, FOOTER_MAX_COLUMNS, FOOTER_MAX_LINK_COLUMNS, FOOTER_SOCIALS, FOOTER_TWELFTHS, type FooterColumnWidth, type FooterSocial, type LocaleRead, NAVIGATION_DB_NAME, NAVIGATION_FOOTER_DB_NAME, NAVIGATION_FOOTER_SLUG, NAVIGATION_SLUG, type NavigationBar, type NavigationDoc, type NavigationFooter, type NavigationHeader, footerDesktopTracks, getNavigation, isValidExternalHref, normalizeFooterDesktop, validateExternalHref, validateFooterSocialUrl, validateHeaderCta };
|
package/dist/og.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as ThemeIdentityFallback } from "./types-DLBlHZUd.mjs";
|
|
2
|
-
import { t as ThemePayload } from "./published-
|
|
2
|
+
import { t as ThemePayload } from "./published-B3etM6X5.mjs";
|
|
3
3
|
import { FontId } from "@bison-lab/fonts";
|
|
4
4
|
import { ThemeConfig } from "@bison-lab/tokens";
|
|
5
5
|
import { Payload } from "payload";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as ThemeIdentityFallback, d as ThemeDoc, g as ResolvedThemeIdentity } from "./types-DLBlHZUd.mjs";
|
|
2
|
-
import { t as LocaleRead } from "./locale-
|
|
2
|
+
import { t as LocaleRead } from "./locale-CTT3nn6T.mjs";
|
|
3
3
|
import { ThemeConfig } from "@bison-lab/tokens";
|
|
4
4
|
|
|
5
5
|
//#region src/theme/published.d.ts
|
|
@@ -27,4 +27,4 @@ declare function getPublishedTheme(payload: ThemePayload, seed: ThemeConfig): Pr
|
|
|
27
27
|
declare function getPublishedIdentity(payload: ThemePayload, fallback?: ThemeIdentityFallback, read?: LocaleRead): Promise<ResolvedThemeIdentity>;
|
|
28
28
|
//#endregion
|
|
29
29
|
export { getPublishedIdentity as n, getPublishedTheme as r, ThemePayload as t };
|
|
30
|
-
//# sourceMappingURL=published-
|
|
30
|
+
//# sourceMappingURL=published-B3etM6X5.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"published-
|
|
1
|
+
{"version":3,"file":"published-B3etM6X5.d.mts","names":[],"sources":["../src/theme/published.ts"],"mappings":";;;;;UAQiB,YAAA;EAIf,UAAA,GAAa,IAAA;IACX,IAAA;IACA,KAAA;IACA,KAAA;IACA,cAAA;EAAA,MACI,OAAA,CAAQ,QAAA;AAAA;;;;;;iBAQM,iBAAA,CAAkB,OAAA,EAAS,YAAA,EAAc,IAAA,EAAM,WAAA,GAAc,OAAA,CAAQ,WAAA;;AAA3F;;;;;;iBAiBsB,oBAAA,CACpB,OAAA,EAAS,YAAA,EACT,QAAA,GAAW,qBAAA,EACX,IAAA,GAAM,UAAA,GACL,OAAA,CAAQ,qBAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as LocaleRead } from "./locale-
|
|
1
|
+
import { t as LocaleRead } from "./locale-CTT3nn6T.mjs";
|
|
2
2
|
import { ArrayFieldValidation, Block, Field, GlobalConfig } from "payload";
|
|
3
3
|
|
|
4
4
|
//#region src/navigation/types.d.ts
|
|
@@ -137,4 +137,4 @@ declare function getNavigation({
|
|
|
137
137
|
}: GetNavigationArgs): Promise<NavigationDoc>;
|
|
138
138
|
//#endregion
|
|
139
139
|
export { NAVIGATION_FOOTER_SLUG as C, NavigationFooter as D, NavigationDoc as E, NavigationHeader as O, NAVIGATION_FOOTER_DB_NAME as S, NavigationBar as T, validateExternalHref as _, FOOTER_MAX_LINK_COLUMNS as a, NAVIGATION_DB_NAME as b, FooterColumnWidth as c, normalizeFooterDesktop as d, validateFooterColumns as f, isValidExternalHref as g, headerCtaEnabled as h, FOOTER_MAX_COLUMNS as i, FooterSocial as l, EXTERNAL_HREF_MESSAGE as m, FOOTER_COLUMNS_FIELD as n, FOOTER_SOCIALS as o, validateFooterSocialUrl as p, FOOTER_COLUMN_WIDTHS as r, FOOTER_TWELFTHS as s, getNavigation as t, footerDesktopTracks as u, validateHeaderCta as v, NAVIGATION_SLUG as w, NAVIGATION_FEATURE as x, CreateNavigationOptions as y };
|
|
140
|
-
//# sourceMappingURL=published-
|
|
140
|
+
//# sourceMappingURL=published-QDNmDi02.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"published-
|
|
1
|
+
{"version":3,"file":"published-QDNmDi02.d.mts","names":[],"sources":["../src/navigation/types.ts","../src/navigation/link.ts","../src/navigation/footer.ts","../src/navigation/published.ts"],"mappings":";;;;cAaa,eAAA;AAAA,cACA,kBAAA;AAAA,cACA,sBAAA;AAAA,cACA,yBAAA;AAAA,cAEA,kBAAA;AAAA,UAEI,uBAAA;;;;AAJjB;EASE,MAAA,EAAQ,KAAA;;;;AAPV;EAYE,OAAA,GAAU,WAAA,CAAY,WAAA,CAAY,YAAA;EAClC,WAAA,GAAc,WAAA,CAAY,WAAA,CAAY,YAAA;EAbT;;AAE/B;;EAgBE,aAAA;EAXQ;EAaR,eAAA;EARsB;EAUtB,mBAAA;AAAA;AAAA,UAGe,gBAAA;EACf,KAAA;EACA,GAAA;AAAA;AAAA,UAGe,aAAA;EACf,YAAA;EACA,QAAA;EACA,eAAA;AAAA;AAAA,UAGe,gBAAA;EACf,OAAA;EACA,KAAA;AAAA;AAAA,UAGe,aAAA;EACf,MAAA,EAAQ,gBAAA;EACR,MAAA,EAAQ,gBAAA;EACR,GAAA,EAAK,aAAA;AAAA;AAAA,UAGU,iBAAA,SAA0B,UAAA;EACzC,OAAA;IACE,UAAA,GAAa,IAAA;MACX,IAAA;MACA,KAAA;MACA,cAAA;MACA,KAAA;IAAA,MACI,OAAA;EAAA;EAER,KAAA;AAAA;;;KChEG,QAAA;AAAA,cAaQ,qBAAA;;ADVb;;;;iBCoBgB,mBAAA,CAAoB,KAAA;AAAA,iBAgBpB,oBAAA,CAAqB,KAAA,WAAgB,QAAA;AAAA,UAyFpC,cAAA;EACf,OAAA;EACA,IAAA,GAAO,QAAA;EACP,IAAA;EACA,IAAA;EACA,KAAA;AAAA;;iBAIc,gBAAA,CAAiB,GAAA,EAAK,cAAA;ADnItC;;;;AAAA,iBC8IgB,iBAAA,CAAkB,KAAA;;;;;;ADjJlC;cELa,oBAAA;AAAA,KACD,iBAAA,WAA4B,oBAAA;;cAG3B,kBAAA;AFEb;AAAA,cEAa,uBAAA;AAAA,cAEA,cAAA;AAAA,KACD,YAAA,WAAuB,cAAA;;cAWtB,eAAA,EAAiB,MAAA,CAAO,iBAAA;AAAA,cASxB,oBAAA;;iBA+BG,sBAAA,CAAuB,KAAA,WAAgB,iBAAA;;AFpDvD;;;;iBE6DgB,mBAAA,CACd,KAAA,EAAO,iBAAA,qBACP,OAAA,EAAS,KAAA,CAAM,iBAAA;EAEf,YAAA;EACA,aAAA;EACA,aAAA;AAAA;;AF/DF;;;;;cEwFa,qBAAA,EAAuB,oBAAA;AAAA,iBA6CpB,uBAAA,CAAwB,KAAA;;;;;;AF5IxC;;;;;iBG4BsB,aAAA,CAAA;EACpB,OAAA;EACA,KAAA;EAAA,GACG;AAAA,GACF,iBAAA,GAAoB,OAAA,CAAQ,aAAA"}
|
|
@@ -116,9 +116,9 @@ function parseJsonArray(text) {
|
|
|
116
116
|
}
|
|
117
117
|
/**
|
|
118
118
|
* The provided `Translator`: one Anthropic Messages call per batch, the
|
|
119
|
-
* strings as a JSON array in and out. `@anthropic-ai/sdk` is
|
|
120
|
-
*
|
|
121
|
-
*
|
|
119
|
+
* strings as a JSON array in and out. `@anthropic-ai/sdk` is a peer,
|
|
120
|
+
* imported on the first call, so a site that never translates never loads
|
|
121
|
+
* it. Every failure (no key, the SDK missing, a network error, a
|
|
122
122
|
* refusal, a malformed or wrong-length reply) returns `null` and is logged
|
|
123
123
|
* by the caller; it never throws.
|
|
124
124
|
*/
|
|
@@ -264,4 +264,4 @@ function isTranslatorConfigured(translator) {
|
|
|
264
264
|
//#endregion
|
|
265
265
|
export { TRANSLATE_MODEL_PRICES as a, estimateCost as c, translationSystemPrompt as d, verifyAnthropicKey as f, ECONOMY_TRANSLATE_MODEL as i, modelPrice as l, translateStrings as n, anthropicTranslator as o, classifyAnthropicError as p, DEFAULT_TRANSLATE_MODEL as r, containsWord as s, isTranslatorConfigured as t, parseJsonArray as u };
|
|
266
266
|
|
|
267
|
-
//# sourceMappingURL=strings-
|
|
267
|
+
//# sourceMappingURL=strings-Fd7kUCT7.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strings-Fd7kUCT7.mjs","names":[],"sources":["../src/translate/errors.ts","../src/translate/anthropic.ts","../src/translate/strings.ts"],"sourcesContent":["/**\n * Why a translation call failed, in the terms an Admin can act on.\n *\n * - `out-of-credit`: the Anthropic account has no credit or a billing\n * problem (402 `billing_error`, or the older 400 \"credit balance is too\n * low\").\n * - `key-rejected`: the key is wrong, revoked or lacks permission (401, 403).\n * - `rate-limited`: 429, after the SDK's own retry.\n * - `unreachable`: no answer, a timeout, or a 5xx / 529 from Anthropic.\n * - `other`: anything else (a malformed reply, a refusal).\n */\nexport type TranslationFailureKind = \"out-of-credit\" | \"key-rejected\" | \"rate-limited\" | \"unreachable\" | \"other\";\n\nfunction errorType(error: { error?: unknown; type?: unknown }): string | undefined {\n if (typeof error.type === \"string\") return error.type;\n const body = error.error as { type?: unknown; error?: { type?: unknown } } | undefined;\n if (typeof body?.error?.type === \"string\") return body.error.type;\n if (typeof body?.type === \"string\") return body.type;\n return undefined;\n}\n\n/** Sorts an error thrown by the Anthropic SDK (or a network failure) into a `TranslationFailureKind`. */\nexport function classifyAnthropicError(error: unknown): TranslationFailureKind {\n if (!error || typeof error !== \"object\") return \"other\";\n const candidate = error as { status?: unknown; message?: unknown; error?: unknown; type?: unknown };\n const status = typeof candidate.status === \"number\" ? candidate.status : undefined;\n const type = errorType(candidate);\n const message = typeof candidate.message === \"string\" ? candidate.message : \"\";\n if (status === 402 || type === \"billing_error\") return \"out-of-credit\";\n if (status === 400 && /credit balance/i.test(message)) return \"out-of-credit\";\n if (status === 401 || status === 403 || type === \"authentication_error\" || type === \"permission_error\") {\n return \"key-rejected\";\n }\n if (status === 429 || type === \"rate_limit_error\") return \"rate-limited\";\n if (status === undefined || status >= 500) return \"unreachable\";\n return \"other\";\n}\n","import { classifyAnthropicError, type TranslationFailureKind } from \"./errors\";\nimport type { TranslateRequest, TranslateSite, Translator } from \"./types\";\n\n/**\n * The library's default model. Translating marketing copy does not need the\n * most capable model; a current Sonnet handles it well at a fraction of the\n * price. A site overrides it per environment (`ANTHROPIC_TRANSLATE_MODEL`).\n */\nexport const DEFAULT_TRANSLATE_MODEL = \"claude-sonnet-5-5\";\n\n/** \"Economy (Haiku)\" on Settings → Translation: a fraction of Sonnet's price for plainer copy. */\nexport const ECONOMY_TRANSLATE_MODEL = \"claude-haiku-5-5\";\n\n/** USD per million tokens, for the cost estimates on Settings → Translation. */\nexport interface ModelPrice {\n input: number;\n output: number;\n}\n\n/**\n * Anthropic's list prices for the two models the screen offers. A model\n * not listed (an `ANTHROPIC_TRANSLATE_MODEL` override) is estimated at\n * Sonnet's price, so an estimate errs high rather than reading as free.\n */\nexport const TRANSLATE_MODEL_PRICES: Record<string, ModelPrice> = {\n [DEFAULT_TRANSLATE_MODEL]: { input: 2, output: 10 },\n [ECONOMY_TRANSLATE_MODEL]: { input: 0.1, output: 0.5 },\n};\n\nexport function modelPrice(model: string): ModelPrice {\n return TRANSLATE_MODEL_PRICES[model] ?? TRANSLATE_MODEL_PRICES[DEFAULT_TRANSLATE_MODEL]!;\n}\n\n/** Estimated USD for one call's tokens on `model`. */\nexport function estimateCost(model: string, inputTokens: number, outputTokens: number): number {\n const price = modelPrice(model);\n return (inputTokens * price.input + outputTokens * price.output) / 1_000_000;\n}\n\n/** What one translator call did, for usage, cost and failure reporting. */\nexport type TranslatorCallEvent =\n | { ok: true; model: string; strings: number; inputTokens: number; outputTokens: number }\n | { ok: false; model: string; strings: number; failure: TranslationFailureKind; status?: number; message: string };\n\n/**\n * True when `text` contains `word` as a whole word, case-sensitively: \"ProtectIQ\"\n * is in \"Get ProtectIQ today\" but not in \"protectiq\" or \"ProtectIQs\". A\n * frozen word is only kept where it appears this way.\n */\nexport function containsWord(text: string, word: string): boolean {\n if (!word) return false;\n const escaped = word.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?<![\\\\p{L}\\\\p{N}_])${escaped}(?![\\\\p{L}\\\\p{N}_])`, \"u\").test(text);\n}\n\n/**\n * The SDK's defaults are a 10-minute timeout with retries. A translation\n * must stay bounded to seconds, not minutes: the manual endpoint awaits it\n * while an editor waits, and a deferred run must finish inside the host's\n * `waitUntil` window. One retry, 90s cap, then the target stays as it was.\n */\nconst TIMEOUT_MS = 90_000;\nconst MAX_RETRIES = 1;\n\n/** The slice of the Anthropic client this translator calls. */\nexport interface AnthropicMessagesClient {\n messages: {\n create(\n body: Record<string, unknown>,\n options?: { timeout?: number; maxRetries?: number },\n ): Promise<{\n content: Array<{ type: string; text?: string }>;\n usage?: { input_tokens?: number | null; output_tokens?: number | null } | null;\n }>;\n };\n}\n\nexport interface AnthropicTranslatorOptions {\n /**\n * The API key, usually `process.env.ANTHROPIC_API_KEY`. Without one the\n * translator reports `configured: false`: publishes still work, a\n * warning is logged, and \"Translate now\" is hidden.\n */\n apiKey?: string | null;\n /** The model id; omitted or blank uses `DEFAULT_TRANSLATE_MODEL`. */\n model?: string | null;\n /** The site facts the prompt carries. The plugin's own `site`, when given, wins. */\n site?: TranslateSite;\n /** A client to use instead of constructing one (tests, a proxied client). */\n client?: AnthropicMessagesClient;\n /**\n * Called once per API call with its token usage, or with why it failed.\n * Settings → Translation records usage and failures through it. A throw\n * here is ignored.\n */\n onCall?: (event: TranslatorCallEvent) => void | Promise<void>;\n}\n\nfunction languageName(code: string, site: TranslateSite | undefined): string {\n const named = site?.languages?.[code];\n if (named) return named;\n try {\n return new Intl.DisplayNames([\"en\"], { type: \"language\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/**\n * The system prompt: the library's generic rules plus the site's own facts.\n * Exported so a site can read exactly what the model is told.\n */\nexport function translationSystemPrompt(request: Pick<TranslateRequest, \"from\" | \"to\" | \"site\">): string {\n const { site } = request;\n const from = languageName(request.from, site);\n const to = languageName(request.to, site);\n const who = site?.name\n ? `You are a professional translator for ${site.name}${site.about ? `, ${site.about}` : \"\"}.`\n : \"You are a professional translator for a business website.\";\n const voice = site?.voice ? ` Keep the ${site.voice} brand voice.` : \" Keep the brand voice.\";\n const verbatim = [site?.name, ...(site?.keepVerbatim ?? [])].filter(\n (value, index, all): value is string => Boolean(value) && all.indexOf(value) === index,\n );\n const keep = verbatim.length\n ? `- Keep these EXACTLY as written, untranslated: ${verbatim.join(\n \", \",\n )}. Also keep URLs, email addresses and phone numbers as written.`\n : \"- Keep URLs, email addresses and phone numbers exactly as written.\";\n\n return `${who} Translate website and UI copy from ${from} into clear, natural ${to}.${voice}\n\nHard rules:\n- You receive a JSON array of strings. Return ONLY a JSON array of the translated strings, in the SAME ORDER and SAME LENGTH. No prose, no markdown, no code fences.\n${keep}\n- Preserve any ICU/message placeholders such as {year}, {count}, {name} verbatim, including the braces.\n- Preserve any HTML tags (e.g. <em>...</em>, <strong>...</strong>) and their positions; translate only the text between them.\n- For legal, regulatory or compliance copy, translate faithfully and literally. This output is a first-pass draft for a native speaker to review, not final compliance copy.\n- If a string is empty or is only a placeholder/URL/number, return it unchanged.`;\n}\n\n/** Tolerant JSON-array parse: strips accidental ``` fences and prose around the array, and checks the shape. */\nexport function parseJsonArray(text: string): string[] | null {\n let candidate = text.trim();\n const fenced = candidate.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced?.[1] !== undefined) candidate = fenced[1].trim();\n // If the model wrapped the array in prose, take the outermost [ ... ].\n const start = candidate.indexOf(\"[\");\n const end = candidate.lastIndexOf(\"]\");\n if (start !== -1 && end > start) candidate = candidate.slice(start, end + 1);\n try {\n const value: unknown = JSON.parse(candidate);\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value as string[];\n } catch {\n // fall through\n }\n return null;\n}\n\n/**\n * The provided `Translator`: one Anthropic Messages call per batch, the\n * strings as a JSON array in and out. `@anthropic-ai/sdk` is a peer,\n * imported on the first call, so a site that never translates never loads\n * it. Every failure (no key, the SDK missing, a network error, a\n * refusal, a malformed or wrong-length reply) returns `null` and is logged\n * by the caller; it never throws.\n */\nexport function anthropicTranslator(options: AnthropicTranslatorOptions): Translator {\n const apiKey = options.apiKey || undefined;\n const model = options.model?.trim() || DEFAULT_TRANSLATE_MODEL;\n let client: AnthropicMessagesClient | undefined = options.client;\n\n const getClient = async (): Promise<AnthropicMessagesClient | null> => {\n if (client) return client;\n if (!apiKey) return null;\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n return client;\n };\n\n const report = async (event: TranslatorCallEvent): Promise<void> => {\n try {\n await options.onCall?.(event);\n } catch {\n // Reporting must never change the translation's outcome.\n }\n };\n\n const translate = async (strings: string[], request: TranslateRequest): Promise<string[] | null> => {\n if (strings.length === 0) return [];\n let anthropic: AnthropicMessagesClient | null;\n try {\n anthropic = await getClient();\n } catch {\n return null;\n }\n if (!anthropic) return null;\n try {\n const given = request.site ?? options.site;\n // Only the frozen words this batch actually contains (whole word,\n // case-sensitive), so \"protectiq\" in English is never told to stay\n // \"ProtectIQ\".\n const site = given?.keepVerbatim\n ? {\n ...given,\n keepVerbatim: given.keepVerbatim.filter((word) => strings.some((value) => containsWord(value, word))),\n }\n : given;\n const to = languageName(request.to, site);\n const content =\n (request.context ? `Context: ${request.context}\\n\\n` : \"\") +\n `Translate this JSON array of ${strings.length} strings to ${to}:\\n${JSON.stringify(strings)}`;\n const response = await anthropic.messages.create(\n {\n model,\n max_tokens: 16000,\n // A batch of copy is routine work; low effort keeps it fast and\n // inside the timeout without changing the result.\n output_config: { effort: \"low\" },\n system: translationSystemPrompt({ from: request.from, to: request.to, site }),\n messages: [{ role: \"user\", content }],\n },\n { timeout: TIMEOUT_MS, maxRetries: MAX_RETRIES },\n );\n const text = response.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\")\n .trim();\n const parsed = parseJsonArray(text);\n const usable = parsed && parsed.length === strings.length ? parsed : null;\n if (usable) {\n await report({\n ok: true,\n model,\n strings: strings.length,\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n });\n } else {\n await report({ ok: false, model, strings: strings.length, failure: \"other\", message: \"The reply was not a usable JSON array.\" });\n }\n return usable;\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n await report({\n ok: false,\n model,\n strings: strings.length,\n failure: classifyAnthropicError(error),\n ...(typeof status === \"number\" ? { status } : {}),\n message: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n };\n\n return Object.assign(translate, { configured: Boolean(apiKey || options.client) });\n}\n\n/** What a key check found. */\nexport type KeyCheck = \"valid\" | \"rejected\" | \"out-of-credit\" | \"unreachable\";\n\n/**\n * Checks a key with the smallest call that proves both the key and the\n * account's credit: one Haiku message with a few output tokens (a fraction\n * of a cent). A 401 is `rejected`; a billing error `out-of-credit`; no\n * answer, a 5xx or a rate limit `unreachable`, meaning \"check again on\n * first use\". Never throws.\n */\nexport async function verifyAnthropicKey(\n apiKey: string,\n options: { client?: AnthropicMessagesClient } = {},\n): Promise<KeyCheck> {\n try {\n let client = options.client;\n if (!client) {\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n }\n await client.messages.create(\n {\n model: ECONOMY_TRANSLATE_MODEL,\n max_tokens: 16,\n output_config: { effort: \"low\" },\n messages: [{ role: \"user\", content: \"Reply with OK.\" }],\n },\n { timeout: 20_000, maxRetries: 0 },\n );\n return \"valid\";\n } catch (error) {\n const kind = classifyAnthropicError(error);\n if (kind === \"key-rejected\") return \"rejected\";\n if (kind === \"out-of-credit\") return \"out-of-credit\";\n return \"unreachable\";\n }\n}\n","import type { TranslateRequest, Translator } from \"./types\";\n\n/**\n * Translates `strings` with `translator` in one batch, preserving order.\n * Repeated strings are sent once. Returns `null` when the translator throws,\n * returns `null`, or returns anything but one string per string sent, so a\n * caller can leave the target as it was. Never throws.\n */\nexport async function translateStrings(\n strings: readonly string[],\n options: TranslateRequest & { translator: Translator },\n): Promise<string[] | null> {\n if (strings.length === 0) return [];\n const { translator, ...request } = options;\n const unique = [...new Set(strings)];\n let result: unknown;\n try {\n result = await translator(unique, request);\n } catch {\n return null;\n }\n if (!Array.isArray(result) || result.length !== unique.length) return null;\n if (!result.every((value) => typeof value === \"string\")) return null;\n const byString = new Map(unique.map((value, index) => [value, result[index] as string]));\n return strings.map((value) => byString.get(value) ?? value);\n}\n\n/** True unless the translator says it cannot run (an Anthropic translator with no API key). */\nexport function isTranslatorConfigured(translator: Translator | undefined): translator is Translator {\n return translator !== undefined && translator.configured !== false;\n}\n"],"mappings":";AAaA,SAAS,UAAU,OAAgE;AACjF,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,MAAM;CACjD,MAAM,OAAO,MAAM;AACnB,KAAI,OAAO,MAAM,OAAO,SAAS,SAAU,QAAO,KAAK,MAAM;AAC7D,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,KAAK;;;AAKlD,SAAgB,uBAAuB,OAAwC;AAC7E,KAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;CAChD,MAAM,YAAY;CAClB,MAAM,SAAS,OAAO,UAAU,WAAW,WAAW,UAAU,SAAS,KAAA;CACzE,MAAM,OAAO,UAAU,UAAU;CACjC,MAAM,UAAU,OAAO,UAAU,YAAY,WAAW,UAAU,UAAU;AAC5E,KAAI,WAAW,OAAO,SAAS,gBAAiB,QAAO;AACvD,KAAI,WAAW,OAAO,kBAAkB,KAAK,QAAQ,CAAE,QAAO;AAC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AAI,IAAI,OAAO,KAAK,OAAO,UAAU,CAAC,OAAO,OAAO,OAAiB,CAAC,CAAC;AACxF,QAAO,QAAQ,KAAK,UAAU,SAAS,IAAI,MAAM,IAAI,MAAM;;;AAI7D,SAAgB,uBAAuB,YAA8D;AACnG,QAAO,eAAe,KAAA,KAAa,WAAW,eAAe"}
|
package/dist/theme.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { _ as ThemeIdentityFallback, c as THEME_SLUG, d as ThemeDoc, f as ThemeHead, g as ResolvedThemeIdentity, h as ThemeUploadDoc, i as SystemColorKey, m as ThemeLibraryColorDoc, n as EditableTheme, p as ThemeHeadOptions, r as SYSTEM_COLOR_KEYS, t as CreateThemeOptions, u as ThemeColorDoc, v as resolveThemeIdentity } from "./types-DLBlHZUd.mjs";
|
|
2
2
|
import { _ as deleteLibraryColor, a as PageEditorSystemKey, c as pageEditorTokens, f as colorTokenField, g as rewriteColorTokens, h as findColorTokens, i as PAGE_EDITOR_SYSTEM_KEYS, l as themeLibraryFromDoc, m as ColorTokenHit, n as ColorSwatch, o as pageEditorLooks, p as lookField, r as LookOption, s as pageEditorSwatches, t as THEME_PREVIEW_BREAKPOINTS, v as rewriteColorToken, y as themeColorKeys } from "./preview-1vwxBgm5.mjs";
|
|
3
|
-
import { t as LocaleRead } from "./locale-
|
|
4
|
-
import { n as getPublishedIdentity, r as getPublishedTheme } from "./published-
|
|
3
|
+
import { t as LocaleRead } from "./locale-CTT3nn6T.mjs";
|
|
4
|
+
import { n as getPublishedIdentity, r as getPublishedTheme } from "./published-B3etM6X5.mjs";
|
|
5
5
|
import { ShadeStep, ThemeConfig } from "@bison-lab/tokens";
|
|
6
6
|
|
|
7
7
|
//#region src/theme/map.d.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { o as anthropicTranslator } from "./strings-
|
|
3
|
-
import { t as fillMessages } from "./messages-
|
|
2
|
+
import { o as anthropicTranslator } from "./strings-Fd7kUCT7.mjs";
|
|
3
|
+
import { t as fillMessages } from "./messages-dZV_aAnR.mjs";
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { basename, resolve } from "node:path";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
@@ -129,7 +129,7 @@ function loadEnvFiles(cwd) {
|
|
|
129
129
|
/**
|
|
130
130
|
* `bison-translate-messages`: fills a next-intl message file from the source
|
|
131
131
|
* locale's file with the Anthropic translator. Run it from the site, which
|
|
132
|
-
* installs `@anthropic-ai/sdk` (
|
|
132
|
+
* installs `@anthropic-ai/sdk` (a peer of this package).
|
|
133
133
|
*
|
|
134
134
|
* bison-translate-messages --source src/messages/en.json --out src/messages/es.json
|
|
135
135
|
* bison-translate-messages --source src/messages/en.json --out src/messages/es.json --force
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-messages-cli.mjs","names":[],"sources":["../src/translate/messages-cli.ts","../src/translate-messages-cli.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { anthropicTranslator } from \"./anthropic\";\nimport { fillMessages, type MessagesJson } from \"./messages\";\nimport type { TranslateSite, Translator } from \"./types\";\n\nexport const TRANSLATE_MESSAGES_USAGE = `Usage: bison-translate-messages --source <en.json> --out <es.json> [--force]\n [--from <code>] [--to <code>] [--language <name>] [--site-name <name>] [--about <line>]\n [--voice <words>] [--keep <a,b,c>] [--context <hint>]\n\n--language names the --to locale in the prompt, as the plugin's\nsite.languages does (\"Latin American Spanish\"), so message files and CMS\ncopy get the same dialect.\n\nFills keys that are missing or empty in --out from --source. --force\nre-translates every key. Reads ANTHROPIC_API_KEY (and the optional\nANTHROPIC_TRANSLATE_MODEL) from the environment, .env.local or .env.`;\n\ninterface CliDeps {\n env: Record<string, string | undefined>;\n log: (line: string) => void;\n error: (line: string) => void;\n /** Overrides the Anthropic translator (tests). */\n translator?: Translator;\n}\n\n/** Locale code from a message file name: `src/messages/es.json` is `es`. */\nconst codeOf = (path: string) => basename(path).replace(/\\.json$/i, \"\");\n\n/**\n * The `bison-translate-messages` run, as a function: returns the exit code.\n * Writes the target only after every batch has run. A batch that fails (or a\n * translation that loses a `{placeholder}`) keeps the source text, so the\n * file stays complete, and the run exits 1 and says how to redo those keys.\n */\nexport async function runTranslateMessagesCli(argv: string[], deps: CliDeps): Promise<number> {\n let values: Record<string, string | boolean | undefined>;\n try {\n ({ values } = parseArgs({\n args: argv,\n options: {\n source: { type: \"string\" },\n out: { type: \"string\" },\n force: { type: \"boolean\", default: false },\n from: { type: \"string\" },\n to: { type: \"string\" },\n language: { type: \"string\" },\n \"site-name\": { type: \"string\" },\n about: { type: \"string\" },\n voice: { type: \"string\" },\n keep: { type: \"string\" },\n context: { type: \"string\" },\n help: { type: \"boolean\", default: false },\n },\n }));\n } catch (error) {\n deps.error(`${(error as Error).message}\\n\\n${TRANSLATE_MESSAGES_USAGE}`);\n return 2;\n }\n if (values.help) {\n deps.log(TRANSLATE_MESSAGES_USAGE);\n return 0;\n }\n const sourcePath = typeof values.source === \"string\" ? resolve(values.source) : undefined;\n const outPath = typeof values.out === \"string\" ? resolve(values.out) : undefined;\n if (!sourcePath || !outPath) {\n deps.error(TRANSLATE_MESSAGES_USAGE);\n return 2;\n }\n\n const siteName = typeof values[\"site-name\"] === \"string\" ? values[\"site-name\"] : undefined;\n const to = typeof values.to === \"string\" ? values.to : codeOf(outPath);\n const language = typeof values.language === \"string\" && values.language ? values.language : undefined;\n const site: TranslateSite | undefined =\n siteName || language\n ? {\n name: siteName ?? \"\",\n ...(language ? { languages: { [to]: language } } : {}),\n ...(typeof values.about === \"string\" ? { about: values.about } : {}),\n ...(typeof values.voice === \"string\" ? { voice: values.voice } : {}),\n ...(typeof values.keep === \"string\"\n ? {\n keepVerbatim: values.keep\n .split(\",\")\n .map((word) => word.trim())\n .filter(Boolean),\n }\n : {}),\n }\n : undefined;\n const translator =\n deps.translator ??\n anthropicTranslator({ apiKey: deps.env.ANTHROPIC_API_KEY, model: deps.env.ANTHROPIC_TRANSLATE_MODEL });\n if (translator.configured === false) {\n deps.error(\"ANTHROPIC_API_KEY is not set. Add it to .env.local and retry.\");\n return 1;\n }\n\n const source = JSON.parse(readFileSync(sourcePath, \"utf8\")) as MessagesJson;\n const target =\n !values.force && existsSync(outPath) ? (JSON.parse(readFileSync(outPath, \"utf8\")) as MessagesJson) : undefined;\n const from = typeof values.from === \"string\" ? values.from : codeOf(sourcePath);\n\n const result = await fillMessages({\n source,\n ...(target !== undefined ? { target } : {}),\n translator,\n from,\n to,\n force: values.force === true,\n ...(typeof values.context === \"string\" ? { context: values.context } : {}),\n ...(site ? { site } : {}),\n onProgress: (done, total) => deps.log(` ${done}/${total}`),\n });\n if (result.translated === 0 && result.fellBack === 0) {\n deps.log(`${basename(outPath)} is already complete. Nothing to translate.`);\n return 0;\n }\n writeFileSync(outPath, `${JSON.stringify(result.messages, null, 2)}\\n`, \"utf8\");\n deps.log(`Wrote ${outPath} (${result.translated} key(s) translated). Review the diff before committing.`);\n if (result.fellBack > 0) {\n // The keys are now filled (so a plain re-run will skip them); say exactly\n // how to redo them once the transient issue is resolved.\n deps.error(\n `${result.fellBack} key(s) kept the ${from} text because a batch failed or a {placeholder} was lost. ` +\n \"They are not missing anymore, so a plain re-run skips them: re-run with --force, or edit them by hand.\",\n );\n return 1;\n }\n return 0;\n}\n\n/** Loads `.env.local` then `.env` from the working directory, never overriding a set variable. */\nexport function loadEnvFiles(cwd: string): void {\n const load = (process as unknown as { loadEnvFile?: (path: string) => void }).loadEnvFile;\n if (!load) return;\n for (const name of [\".env.local\", \".env\"]) {\n const path = resolve(cwd, name);\n if (!existsSync(path)) continue;\n const before = { ...process.env };\n try {\n load(path);\n } catch {\n continue;\n }\n // loadEnvFile overrides; restore anything that was already set.\n for (const [key, value] of Object.entries(before)) process.env[key] = value;\n }\n}\n","#!/usr/bin/env node\n/**\n * `bison-translate-messages`: fills a next-intl message file from the source\n * locale's file with the Anthropic translator. Run it from the site, which\n * installs `@anthropic-ai/sdk` (an optional peer of this package).\n *\n * bison-translate-messages --source src/messages/en.json --out src/messages/es.json\n * bison-translate-messages --source src/messages/en.json --out src/messages/es.json --force\n *\n * Only keys missing or empty in --out are translated unless --force is\n * passed. --site-name, --about, --voice and --keep (comma list) carry the\n * site's prompt facts. The key is read from ANTHROPIC_API_KEY (the\n * environment, `.env.local` or `.env`), never from arguments.\n */\nimport { loadEnvFiles, runTranslateMessagesCli } from \"./translate/messages-cli\";\n\nloadEnvFiles(process.cwd());\nconst code = await runTranslateMessagesCli(process.argv.slice(2), {\n env: process.env,\n log: (line) => console.log(line),\n error: (line) => console.error(line),\n});\nprocess.exit(code);\n"],"mappings":";;;;;;;AAQA,MAAa,2BAA2B;;;;;;;;;;;;AAqBxC,MAAM,UAAU,SAAiB,SAAS,KAAK,CAAC,QAAQ,YAAY,GAAG;;;;;;;AAQvE,eAAsB,wBAAwB,MAAgB,MAAgC;CAC5F,IAAI;AACJ,KAAI;AACF,GAAC,CAAE,UAAW,UAAU;GACtB,MAAM;GACN,SAAS;IACP,QAAQ,EAAE,MAAM,UAAU;IAC1B,KAAK,EAAE,MAAM,UAAU;IACvB,OAAO;KAAE,MAAM;KAAW,SAAS;KAAO;IAC1C,MAAM,EAAE,MAAM,UAAU;IACxB,IAAI,EAAE,MAAM,UAAU;IACtB,UAAU,EAAE,MAAM,UAAU;IAC5B,aAAa,EAAE,MAAM,UAAU;IAC/B,OAAO,EAAE,MAAM,UAAU;IACzB,OAAO,EAAE,MAAM,UAAU;IACzB,MAAM,EAAE,MAAM,UAAU;IACxB,SAAS,EAAE,MAAM,UAAU;IAC3B,MAAM;KAAE,MAAM;KAAW,SAAS;KAAO;IAC1C;GACF,CAAC;UACK,OAAO;AACd,OAAK,MAAM,GAAI,MAAgB,QAAQ,MAAM,2BAA2B;AACxE,SAAO;;AAET,KAAI,OAAO,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,QAAQ;CACb,MAAM,SAAS,QAAQ,IAAI,KAAK;CAChC,QAAQ,SAAS,QAAQ,MAAM,KAAK;CACrC,CAAC;AACF,QAAQ,KAAK,KAAK"}
|
|
1
|
+
{"version":3,"file":"translate-messages-cli.mjs","names":[],"sources":["../src/translate/messages-cli.ts","../src/translate-messages-cli.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { anthropicTranslator } from \"./anthropic\";\nimport { fillMessages, type MessagesJson } from \"./messages\";\nimport type { TranslateSite, Translator } from \"./types\";\n\nexport const TRANSLATE_MESSAGES_USAGE = `Usage: bison-translate-messages --source <en.json> --out <es.json> [--force]\n [--from <code>] [--to <code>] [--language <name>] [--site-name <name>] [--about <line>]\n [--voice <words>] [--keep <a,b,c>] [--context <hint>]\n\n--language names the --to locale in the prompt, as the plugin's\nsite.languages does (\"Latin American Spanish\"), so message files and CMS\ncopy get the same dialect.\n\nFills keys that are missing or empty in --out from --source. --force\nre-translates every key. Reads ANTHROPIC_API_KEY (and the optional\nANTHROPIC_TRANSLATE_MODEL) from the environment, .env.local or .env.`;\n\ninterface CliDeps {\n env: Record<string, string | undefined>;\n log: (line: string) => void;\n error: (line: string) => void;\n /** Overrides the Anthropic translator (tests). */\n translator?: Translator;\n}\n\n/** Locale code from a message file name: `src/messages/es.json` is `es`. */\nconst codeOf = (path: string) => basename(path).replace(/\\.json$/i, \"\");\n\n/**\n * The `bison-translate-messages` run, as a function: returns the exit code.\n * Writes the target only after every batch has run. A batch that fails (or a\n * translation that loses a `{placeholder}`) keeps the source text, so the\n * file stays complete, and the run exits 1 and says how to redo those keys.\n */\nexport async function runTranslateMessagesCli(argv: string[], deps: CliDeps): Promise<number> {\n let values: Record<string, string | boolean | undefined>;\n try {\n ({ values } = parseArgs({\n args: argv,\n options: {\n source: { type: \"string\" },\n out: { type: \"string\" },\n force: { type: \"boolean\", default: false },\n from: { type: \"string\" },\n to: { type: \"string\" },\n language: { type: \"string\" },\n \"site-name\": { type: \"string\" },\n about: { type: \"string\" },\n voice: { type: \"string\" },\n keep: { type: \"string\" },\n context: { type: \"string\" },\n help: { type: \"boolean\", default: false },\n },\n }));\n } catch (error) {\n deps.error(`${(error as Error).message}\\n\\n${TRANSLATE_MESSAGES_USAGE}`);\n return 2;\n }\n if (values.help) {\n deps.log(TRANSLATE_MESSAGES_USAGE);\n return 0;\n }\n const sourcePath = typeof values.source === \"string\" ? resolve(values.source) : undefined;\n const outPath = typeof values.out === \"string\" ? resolve(values.out) : undefined;\n if (!sourcePath || !outPath) {\n deps.error(TRANSLATE_MESSAGES_USAGE);\n return 2;\n }\n\n const siteName = typeof values[\"site-name\"] === \"string\" ? values[\"site-name\"] : undefined;\n const to = typeof values.to === \"string\" ? values.to : codeOf(outPath);\n const language = typeof values.language === \"string\" && values.language ? values.language : undefined;\n const site: TranslateSite | undefined =\n siteName || language\n ? {\n name: siteName ?? \"\",\n ...(language ? { languages: { [to]: language } } : {}),\n ...(typeof values.about === \"string\" ? { about: values.about } : {}),\n ...(typeof values.voice === \"string\" ? { voice: values.voice } : {}),\n ...(typeof values.keep === \"string\"\n ? {\n keepVerbatim: values.keep\n .split(\",\")\n .map((word) => word.trim())\n .filter(Boolean),\n }\n : {}),\n }\n : undefined;\n const translator =\n deps.translator ??\n anthropicTranslator({ apiKey: deps.env.ANTHROPIC_API_KEY, model: deps.env.ANTHROPIC_TRANSLATE_MODEL });\n if (translator.configured === false) {\n deps.error(\"ANTHROPIC_API_KEY is not set. Add it to .env.local and retry.\");\n return 1;\n }\n\n const source = JSON.parse(readFileSync(sourcePath, \"utf8\")) as MessagesJson;\n const target =\n !values.force && existsSync(outPath) ? (JSON.parse(readFileSync(outPath, \"utf8\")) as MessagesJson) : undefined;\n const from = typeof values.from === \"string\" ? values.from : codeOf(sourcePath);\n\n const result = await fillMessages({\n source,\n ...(target !== undefined ? { target } : {}),\n translator,\n from,\n to,\n force: values.force === true,\n ...(typeof values.context === \"string\" ? { context: values.context } : {}),\n ...(site ? { site } : {}),\n onProgress: (done, total) => deps.log(` ${done}/${total}`),\n });\n if (result.translated === 0 && result.fellBack === 0) {\n deps.log(`${basename(outPath)} is already complete. Nothing to translate.`);\n return 0;\n }\n writeFileSync(outPath, `${JSON.stringify(result.messages, null, 2)}\\n`, \"utf8\");\n deps.log(`Wrote ${outPath} (${result.translated} key(s) translated). Review the diff before committing.`);\n if (result.fellBack > 0) {\n // The keys are now filled (so a plain re-run will skip them); say exactly\n // how to redo them once the transient issue is resolved.\n deps.error(\n `${result.fellBack} key(s) kept the ${from} text because a batch failed or a {placeholder} was lost. ` +\n \"They are not missing anymore, so a plain re-run skips them: re-run with --force, or edit them by hand.\",\n );\n return 1;\n }\n return 0;\n}\n\n/** Loads `.env.local` then `.env` from the working directory, never overriding a set variable. */\nexport function loadEnvFiles(cwd: string): void {\n const load = (process as unknown as { loadEnvFile?: (path: string) => void }).loadEnvFile;\n if (!load) return;\n for (const name of [\".env.local\", \".env\"]) {\n const path = resolve(cwd, name);\n if (!existsSync(path)) continue;\n const before = { ...process.env };\n try {\n load(path);\n } catch {\n continue;\n }\n // loadEnvFile overrides; restore anything that was already set.\n for (const [key, value] of Object.entries(before)) process.env[key] = value;\n }\n}\n","#!/usr/bin/env node\n/**\n * `bison-translate-messages`: fills a next-intl message file from the source\n * locale's file with the Anthropic translator. Run it from the site, which\n * installs `@anthropic-ai/sdk` (a peer of this package).\n *\n * bison-translate-messages --source src/messages/en.json --out src/messages/es.json\n * bison-translate-messages --source src/messages/en.json --out src/messages/es.json --force\n *\n * Only keys missing or empty in --out are translated unless --force is\n * passed. --site-name, --about, --voice and --keep (comma list) carry the\n * site's prompt facts. The key is read from ANTHROPIC_API_KEY (the\n * environment, `.env.local` or `.env`), never from arguments.\n */\nimport { loadEnvFiles, runTranslateMessagesCli } from \"./translate/messages-cli\";\n\nloadEnvFiles(process.cwd());\nconst code = await runTranslateMessagesCli(process.arg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pD,OAAK,IAAI,GAAG,SAAS,QAAQ,CAAC,6CAA6C;AAC3E,SAAO;;AAET,eAAc,SAAS,GAAG,KAAK,UAAU,OAAO,UAAU,MAAM,EAAE,CAAC,KAAK,OAAO;AAC/E,MAAK,IAAI,SAAS,QAAQ,IAAI,OAAO,WAAW,yDAAyD;AACzG,KAAI,OAAO,WAAW,GAAG;AAGvB,OAAK,MACH,GAAG,OAAO,SAAS,mBAAmB,KAAK,kKAE5C;AACD,SAAO;;AAET,QAAO;;;AAIT,SAAgB,aAAa,KAAmB;CAC9C,MAAM,OAAQ,QAAgE;AAC9E,KAAI,CAAC,KAAM;AACX,MAAK,MAAM,QAAQ,CAAC,cAAc,OAAO,EAAE;EACzC,MAAM,OAAO,QAAQ,KAAK,KAAK;AAC/B,MAAI,CAAC,WAAW,KAAK,CAAE;EACvB,MAAM,SAAS,EAAE,GAAG,QAAQ,KAAK;AACjC,MAAI;AACF,QAAK,KAAK;UACJ;AACN;;AAGF,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,CAAE,SAAQ,IAAI,OAAO;;;;;;;;;;;;;;;;;;ACpI1E,aAAa,QAAQ,KAAK,CAAC;AAC3B,MAAM,OAAO,MAAM,wBAAwB,QAAQ,KAAK,MAAM,EAAE,EAAE;CAChE,KAAK,QAAQ;CACb,MAAM,SAAS,QAAQ,IAAI,KAAK;CAChC,QAAQ,SAAS,QAAQ,MAAM,KAAK;CACrC,CAAC;AACF,QAAQ,KAAK,KAAK"}
|
package/dist/translate.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as ModelPrice, B as AutoTranslateOptions, C as encryptApiKey, D as DEFAULT_TRANSLATE_MODEL, E as AnthropicTranslatorOptions, F as estimateCost, G as TranslateLocaleResult, H as BisonTranslationKind, I as modelPrice, J as TranslatedEntity, K as TranslateRequest, L as parseJsonArray, M as TranslatorCallEvent, N as anthropicTranslator, O as ECONOMY_TRANSLATE_MODEL, P as containsWord, R as translationSystemPrompt, S as decryptApiKey, T as AnthropicMessagesClient, U as BisonTranslationMarker, V as BISON_TRANSLATION_CONTEXT, W as Doc, X as TranslationFailureKind, Y as Translator, Z as classifyAnthropicError, _ as readTranslationSettings, a as translation, b as KeySource, c as KeyStatus, d as TRANSLATION_KEY_PANEL, f as TRANSLATION_SETTINGS_SLUG, g as invalidateTranslationSettings, h as TranslationSettingsDoc, i as hasLocalizedFields, j as TRANSLATE_MODEL_PRICES, k as KeyCheck, l as ResolvedTranslationSettings, m as TranslationModelChoice, n as TranslationOptions, o as TranslationStatus, p as TRANSLATION_STATE_SLUG, q as TranslateSite, r as applyTranslation, s as translationSettingsEndpoints, t as TranslationEntityHint, u as TRANSLATION_GRANT, v as resolveModel, w as resolveApiKey, x as ResolvedKey, y as siteFromInstructions, z as verifyAnthropicKey } from "./capability-
|
|
1
|
+
import { A as ModelPrice, B as AutoTranslateOptions, C as encryptApiKey, D as DEFAULT_TRANSLATE_MODEL, E as AnthropicTranslatorOptions, F as estimateCost, G as TranslateLocaleResult, H as BisonTranslationKind, I as modelPrice, J as TranslatedEntity, K as TranslateRequest, L as parseJsonArray, M as TranslatorCallEvent, N as anthropicTranslator, O as ECONOMY_TRANSLATE_MODEL, P as containsWord, R as translationSystemPrompt, S as decryptApiKey, T as AnthropicMessagesClient, U as BisonTranslationMarker, V as BISON_TRANSLATION_CONTEXT, W as Doc, X as TranslationFailureKind, Y as Translator, Z as classifyAnthropicError, _ as readTranslationSettings, a as translation, b as KeySource, c as KeyStatus, d as TRANSLATION_KEY_PANEL, f as TRANSLATION_SETTINGS_SLUG, g as invalidateTranslationSettings, h as TranslationSettingsDoc, i as hasLocalizedFields, j as TRANSLATE_MODEL_PRICES, k as KeyCheck, l as ResolvedTranslationSettings, m as TranslationModelChoice, n as TranslationOptions, o as TranslationStatus, p as TRANSLATION_STATE_SLUG, q as TranslateSite, r as applyTranslation, s as translationSettingsEndpoints, t as TranslationEntityHint, u as TRANSLATION_GRANT, v as resolveModel, w as resolveApiKey, x as ResolvedKey, y as siteFromInstructions, z as verifyAnthropicKey } from "./capability-CqdYCzG1.mjs";
|
|
2
2
|
import { Block, CollectionAfterChangeHook, Config, Endpoint, Field, Payload, PayloadRequest, Plugin, SanitizedConfig } from "payload";
|
|
3
3
|
|
|
4
4
|
//#region src/translate/plugin.d.ts
|
|
@@ -15,6 +15,228 @@ import { Block, CollectionAfterChangeHook, Config, Endpoint, Field, Payload, Pay
|
|
|
15
15
|
*/
|
|
16
16
|
declare function autoTranslate(options: AutoTranslateOptions): Plugin;
|
|
17
17
|
//#endregion
|
|
18
|
+
//#region src/translate/languages.d.ts
|
|
19
|
+
/**
|
|
20
|
+
* The languages every Bison site carries. The library owns this list: a new
|
|
21
|
+
* language is a library release that sites take by updating the package
|
|
22
|
+
* (and running the migration it brings). The first entry is the default
|
|
23
|
+
* locale of a site that declares no localization of its own.
|
|
24
|
+
*/
|
|
25
|
+
declare const LIBRARY_LOCALES: readonly [{
|
|
26
|
+
readonly code: "en";
|
|
27
|
+
readonly label: "English";
|
|
28
|
+
}, {
|
|
29
|
+
readonly code: "es";
|
|
30
|
+
readonly label: "Español";
|
|
31
|
+
}];
|
|
32
|
+
type LibraryLocaleCode = (typeof LIBRARY_LOCALES)[number]["code"];
|
|
33
|
+
declare const LIBRARY_DEFAULT_LOCALE: LibraryLocaleCode;
|
|
34
|
+
/** The codes of `LIBRARY_LOCALES`, in order. */
|
|
35
|
+
declare const LIBRARY_LOCALE_CODES: readonly string[];
|
|
36
|
+
/**
|
|
37
|
+
* A config's `localization` with every library language in it. A site with
|
|
38
|
+
* none gets the library's (English default, `fallback: true`, so an empty
|
|
39
|
+
* Spanish field reads as English). A site with its own keeps its locales,
|
|
40
|
+
* labels and default, and gains any library language it lacks.
|
|
41
|
+
*/
|
|
42
|
+
declare function withLibraryLocales(localization: Config["localization"]): Exclude<Config["localization"], false | undefined>;
|
|
43
|
+
/** What `activeLocales` answers. */
|
|
44
|
+
interface ActiveLocales {
|
|
45
|
+
/** The default (source) locale. Always active. */
|
|
46
|
+
defaultLocale: string;
|
|
47
|
+
/** The default locale and every ticked target locale, in config order. */
|
|
48
|
+
active: string[];
|
|
49
|
+
/** Target locales that are not ticked: no translation, no URL, no switcher entry, no hreflang. */
|
|
50
|
+
inactive: string[];
|
|
51
|
+
}
|
|
52
|
+
/** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
|
|
53
|
+
declare const ACTIVE_LOCALES_CACHE_MS = 60000;
|
|
54
|
+
type SettingsReader = Pick<Payload, "findGlobal" | "config">;
|
|
55
|
+
/** After a failed read, how soon to try the database again. */
|
|
56
|
+
/** Drops the cached answer, so the next `activeLocales` reads again. */
|
|
57
|
+
declare function invalidateActiveLocales(payload: object): void;
|
|
58
|
+
/**
|
|
59
|
+
* The site's active languages, for routing and middleware: the default
|
|
60
|
+
* locale plus each target language ticked on Settings → Translation. Cached
|
|
61
|
+
* per process for `ttlMs` (60s by default): a request reads memory, and the
|
|
62
|
+
* database is read only when the cache refreshes, or after a save of the
|
|
63
|
+
* screen in the same process. Never throws. When a read fails it answers
|
|
64
|
+
* with the last good read (or, before the first one, the defaults) and
|
|
65
|
+
* tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
|
|
66
|
+
* never stands in for the Admin's ticks for a whole cache period, which
|
|
67
|
+
* would send a ticked language's visitors permanent redirects.
|
|
68
|
+
*/
|
|
69
|
+
declare function activeLocales(payload: SettingsReader, options?: {
|
|
70
|
+
ttlMs?: number;
|
|
71
|
+
}): Promise<ActiveLocales>;
|
|
72
|
+
/**
|
|
73
|
+
* Where a request for an inactive language goes: the same path without
|
|
74
|
+
* its locale prefix, for a 308. `null` when the path is not under an
|
|
75
|
+
* inactive locale. In a site's middleware:
|
|
76
|
+
*
|
|
77
|
+
* ```ts
|
|
78
|
+
* const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
|
|
79
|
+
* if (to) {
|
|
80
|
+
* const response = NextResponse.redirect(new URL(to + url.search, url), 308);
|
|
81
|
+
* response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
|
|
82
|
+
* return response;
|
|
83
|
+
* }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
declare function inactiveLocaleRedirect(pathname: string, locales: Pick<ActiveLocales, "inactive" | "defaultLocale">): string | null;
|
|
87
|
+
/**
|
|
88
|
+
* A page's language alternates (for hreflang and a language switcher),
|
|
89
|
+
* keeping only active languages. `paths` maps each locale to that
|
|
90
|
+
* language's URL for the page.
|
|
91
|
+
*/
|
|
92
|
+
declare function activeAlternates(paths: Readonly<Record<string, string>>, locales: Pick<ActiveLocales, "active">): Record<string, string>;
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/translate/migrate-locales.d.ts
|
|
95
|
+
/**
|
|
96
|
+
* The data migration for a Postgres site going from one locale to several.
|
|
97
|
+
*
|
|
98
|
+
* Turning localization on moves every localized column out of its table
|
|
99
|
+
* into a `<table>_locales` table (one row per locale). `payload
|
|
100
|
+
* migrate:create` writes that as SQL that creates the new tables and then
|
|
101
|
+
* drops the old columns, which throws the copy away. This runs the same
|
|
102
|
+
* SQL with one step in between: after everything else and before any column
|
|
103
|
+
* or type is dropped, each column that moves is copied into its locale
|
|
104
|
+
* table as the default locale's row. Nothing else changes, so the result is
|
|
105
|
+
* exactly the schema Payload generated, holding the content it held before.
|
|
106
|
+
*
|
|
107
|
+
* In the generated migration, replace the body of `up`:
|
|
108
|
+
*
|
|
109
|
+
* ```ts
|
|
110
|
+
* import { localizeExistingContent } from "@bison-lab/payload-core/translate";
|
|
111
|
+
*
|
|
112
|
+
* export async function up({ db, payload }: MigrateUpArgs): Promise<void> {
|
|
113
|
+
* await localizeExistingContent({ db, payload, sql, statements: `
|
|
114
|
+
* ...the SQL migrate:create wrote inside sql`...`, unchanged...
|
|
115
|
+
* ` });
|
|
116
|
+
* }
|
|
117
|
+
* ```
|
|
118
|
+
*
|
|
119
|
+
* Postgres only. The migration has no `down`: going back to one locale
|
|
120
|
+
* would drop every other locale's copy.
|
|
121
|
+
*/
|
|
122
|
+
/** The slice of Payload's `db` (Drizzle) this uses. */
|
|
123
|
+
interface MigrationDb {
|
|
124
|
+
execute(query: never): Promise<unknown>;
|
|
125
|
+
}
|
|
126
|
+
/** `sql` from `@payloadcms/db-postgres`, for `sql.raw`. */
|
|
127
|
+
interface MigrationSql {
|
|
128
|
+
raw: (text: string) => unknown;
|
|
129
|
+
}
|
|
130
|
+
/** The slice of the site's Payload config the relationship step reads (`payload` from the migration's `up`). */
|
|
131
|
+
interface MigrationPayload {
|
|
132
|
+
/** The adapter's table-name suffixes, when a site changed them (`postgresAdapter({ localesSuffix })`). */
|
|
133
|
+
db?: {
|
|
134
|
+
localesSuffix?: string;
|
|
135
|
+
relationshipsSuffix?: string;
|
|
136
|
+
versionsSuffix?: string;
|
|
137
|
+
};
|
|
138
|
+
config: {
|
|
139
|
+
collections?: ReadonlyArray<{
|
|
140
|
+
slug: string;
|
|
141
|
+
dbName?: unknown;
|
|
142
|
+
fields: readonly unknown[];
|
|
143
|
+
}>;
|
|
144
|
+
globals?: ReadonlyArray<{
|
|
145
|
+
slug: string;
|
|
146
|
+
dbName?: unknown;
|
|
147
|
+
fields: readonly unknown[];
|
|
148
|
+
}>; /** Config-level blocks, for blocks fields that use `blockReferences`. */
|
|
149
|
+
blocks?: ReadonlyArray<{
|
|
150
|
+
slug: string;
|
|
151
|
+
fields: readonly unknown[];
|
|
152
|
+
}>;
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
interface LocalizeExistingContentOptions {
|
|
156
|
+
db: MigrationDb;
|
|
157
|
+
sql: MigrationSql;
|
|
158
|
+
/**
|
|
159
|
+
* The migration's `payload`. Needed when a localized relationship, upload
|
|
160
|
+
* or hasMany text/number field already holds rows: Payload keeps those in
|
|
161
|
+
* shared `_rels` / `_texts` / `_numbers` tables with a `locale` column it
|
|
162
|
+
* adds now, and only the config says which rows belong to a localized
|
|
163
|
+
* field. Without it, such rows make the migration stop with an error
|
|
164
|
+
* rather than lose them.
|
|
165
|
+
*/
|
|
166
|
+
payload?: MigrationPayload;
|
|
167
|
+
/** The SQL `migrate:create` generated for this change, as text. */
|
|
168
|
+
statements: string;
|
|
169
|
+
/** The locale existing content is in. Defaults to `en`. */
|
|
170
|
+
locale?: string;
|
|
171
|
+
/** The Postgres schema Payload's tables are in. Defaults to `public`. */
|
|
172
|
+
schema?: string;
|
|
173
|
+
/** Progress lines; defaults to `console.log`. */
|
|
174
|
+
log?: (line: string) => void;
|
|
175
|
+
}
|
|
176
|
+
interface LocalizedTableCopy {
|
|
177
|
+
table: string;
|
|
178
|
+
into: string;
|
|
179
|
+
columns: string[];
|
|
180
|
+
rows: number;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Splits generated SQL into statements at a `;` that ends a line, keeping a
|
|
184
|
+
* `DO $$ ... $$;` block whole.
|
|
185
|
+
*/
|
|
186
|
+
declare function splitStatements(text: string): string[];
|
|
187
|
+
interface PartitionedStatements {
|
|
188
|
+
/** Everything that does not drop: creates, adds, indexes, constraints. */
|
|
189
|
+
first: string[];
|
|
190
|
+
/** Tables that gain a nullable `locale` column (shared relationship / hasMany tables). */
|
|
191
|
+
localeColumns: string[];
|
|
192
|
+
/** The columns dropped, by table. */
|
|
193
|
+
drops: Map<string, string[]>;
|
|
194
|
+
/** The drops themselves, run last. */
|
|
195
|
+
last: string[];
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Sorts statements into what runs before the copy and the drops that run
|
|
199
|
+
* after it. A `_locale NOT NULL` column added to an existing table (a
|
|
200
|
+
* localized array or blocks field) gets the default locale as a default
|
|
201
|
+
* while it is added, so existing rows are kept as that locale's.
|
|
202
|
+
*/
|
|
203
|
+
declare function partitionStatements(statements: readonly string[], locale?: string): PartitionedStatements;
|
|
204
|
+
interface ConfigField {
|
|
205
|
+
type?: string;
|
|
206
|
+
name?: string;
|
|
207
|
+
localized?: boolean;
|
|
208
|
+
fields?: ConfigField[];
|
|
209
|
+
tabs?: Array<{
|
|
210
|
+
name?: string;
|
|
211
|
+
localized?: boolean;
|
|
212
|
+
fields: ConfigField[];
|
|
213
|
+
}>;
|
|
214
|
+
blocks?: Array<{
|
|
215
|
+
slug: string;
|
|
216
|
+
fields: ConfigField[];
|
|
217
|
+
}>;
|
|
218
|
+
blockReferences?: Array<string | {
|
|
219
|
+
slug: string;
|
|
220
|
+
fields: ConfigField[];
|
|
221
|
+
}>;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Whether the stored `path` of a relationship / hasMany row (`related`,
|
|
225
|
+
* `layout.1.items.0.ref`) is a localized field, or sits inside one.
|
|
226
|
+
* `undefined` when the path is not in the config. Throws when blocks
|
|
227
|
+
* disagree (two block types with the same sub-path, one localized).
|
|
228
|
+
*/
|
|
229
|
+
declare function isLocalizedPath(fields: readonly ConfigField[], segments: readonly string[], inherited?: boolean, configBlocks?: ReadonlyArray<{
|
|
230
|
+
slug: string;
|
|
231
|
+
fields: readonly unknown[];
|
|
232
|
+
}>): boolean | undefined;
|
|
233
|
+
/**
|
|
234
|
+
* Runs a localization migration without losing content: see the module
|
|
235
|
+
* comment. Returns what it copied. Throws (and Payload rolls the migration
|
|
236
|
+
* back) on any SQL error.
|
|
237
|
+
*/
|
|
238
|
+
declare function localizeExistingContent(options: LocalizeExistingContentOptions): Promise<LocalizedTableCopy[]>;
|
|
239
|
+
//#endregion
|
|
18
240
|
//#region src/translate/fields.d.ts
|
|
19
241
|
/** Field configs plus the config-level blocks a `blockReferences` field points at. */
|
|
20
242
|
interface FieldSchema {
|
|
@@ -87,7 +309,7 @@ type TranslateDocumentOptions = ({
|
|
|
87
309
|
} | {
|
|
88
310
|
global: string;
|
|
89
311
|
}) & {
|
|
90
|
-
/** Target locale or locales. Omitted: every
|
|
312
|
+
/** Target locale or locales. Omitted: every ticked target language on Settings → Translation. */locale?: string | readonly string[]; /** Re-translate every filled source string, replacing target copy a person may have corrected. */
|
|
91
313
|
overwrite?: boolean;
|
|
92
314
|
/**
|
|
93
315
|
* The source copy before the change being translated: the last published
|
|
@@ -331,5 +553,5 @@ declare function fillMessages(options: {
|
|
|
331
553
|
onProgress?: (done: number, total: number) => void;
|
|
332
554
|
}): Promise<FillMessagesResult>;
|
|
333
555
|
//#endregion
|
|
334
|
-
export { type AnthropicMessagesClient, type AnthropicTranslatorOptions, type AutoTranslateOptions, type AutoTranslateState, BISON_TRANSLATION_CONTEXT, type BisonTranslationKind, type BisonTranslationMarker, DEFAULT_TRANSLATE_MODEL, type Doc, ECONOMY_TRANSLATE_MODEL, type FieldSchema, type KeyCheck, type KeySource, type KeyStatus, type MessagesJson, type ModelPrice, type ResolvedKey, type ResolvedTranslationSettings, TRANSACTION_TIMEOUT_MS, TRANSLATE_MODEL_PRICES, TRANSLATE_NOW, TRANSLATION_GRANT, TRANSLATION_KEY_PANEL, TRANSLATION_SETTINGS_SLUG, TRANSLATION_STATE_SLUG, type TranslateDocumentOptions, type TranslateLocaleResult, type TranslateRequest, type TranslateSite, type TranslatedEntity, type TranslationEntityHint, type TranslationFailureKind, type TranslationJob, type TranslationModelChoice, type TranslationOptions, type TranslationSettingsDoc, type TranslationStatus, type Translator, type TranslatorCallEvent, anthropicTranslator, applyTranslation, autoTranslate, classifyAnthropicError, collectLocalizedStrings, containsWord, decryptApiKey, draftedTranslationDecision, encryptApiKey, estimateCost, fillMessages, hasLocalizedFields, invalidateTranslationSettings, isAutosave, isTranslatorConfigured, localizedCopyUnchanged, modelPrice, parseJsonArray, readTranslateState, readTranslationSettings, resolveApiKey, resolveModel, runAfterCommit, sameRow, shouldSkipDraftedTranslation, shouldSkipUndraftedTranslation, siteFromInstructions, translateDocument, translateStrings, translation, translationJob, translationSettingsEndpoints, translationSystemPrompt, verifyAnthropicKey, withTranslator };
|
|
556
|
+
export { ACTIVE_LOCALES_CACHE_MS, type ActiveLocales, type AnthropicMessagesClient, type AnthropicTranslatorOptions, type AutoTranslateOptions, type AutoTranslateState, BISON_TRANSLATION_CONTEXT, type BisonTranslationKind, type BisonTranslationMarker, DEFAULT_TRANSLATE_MODEL, type Doc, ECONOMY_TRANSLATE_MODEL, type FieldSchema, type KeyCheck, type KeySource, type KeyStatus, LIBRARY_DEFAULT_LOCALE, LIBRARY_LOCALES, LIBRARY_LOCALE_CODES, type LibraryLocaleCode, type LocalizeExistingContentOptions, type LocalizedTableCopy, type MessagesJson, type MigrationDb, type MigrationPayload, type MigrationSql, type ModelPrice, type ResolvedKey, type ResolvedTranslationSettings, TRANSACTION_TIMEOUT_MS, TRANSLATE_MODEL_PRICES, TRANSLATE_NOW, TRANSLATION_GRANT, TRANSLATION_KEY_PANEL, TRANSLATION_SETTINGS_SLUG, TRANSLATION_STATE_SLUG, type TranslateDocumentOptions, type TranslateLocaleResult, type TranslateRequest, type TranslateSite, type TranslatedEntity, type TranslationEntityHint, type TranslationFailureKind, type TranslationJob, type TranslationModelChoice, type TranslationOptions, type TranslationSettingsDoc, type TranslationStatus, type Translator, type TranslatorCallEvent, activeAlternates, activeLocales, anthropicTranslator, applyTranslation, autoTranslate, classifyAnthropicError, collectLocalizedStrings, containsWord, decryptApiKey, draftedTranslationDecision, encryptApiKey, estimateCost, fillMessages, hasLocalizedFields, inactiveLocaleRedirect, invalidateActiveLocales, invalidateTranslationSettings, isAutosave, isLocalizedPath, isTranslatorConfigured, localizeExistingContent, localizedCopyUnchanged, modelPrice, parseJsonArray, partitionStatements, readTranslateState, readTranslationSettings, resolveApiKey, resolveModel, runAfterCommit, sameRow, shouldSkipDraftedTranslation, shouldSkipUndraftedTranslation, siteFromInstructions, splitStatements, translateDocument, translateStrings, translation, translationJob, translationSettingsEndpoints, translationSystemPrompt, verifyAnthropicKey, withLibraryLocales, withTranslator };
|
|
335
557
|
//# sourceMappingURL=translate.d.mts.map
|
package/dist/translate.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate.d.mts","names":[],"sources":["../src/translate/plugin.ts","../src/translate/fields.ts","../src/translate/hooks.ts","../src/translate/document.ts","../src/translate/strings.ts","../src/translate/guards.ts","../src/translate/after-commit.ts","../src/translate/state.ts","../src/translate/endpoint.ts","../src/translate/messages.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"translate.d.mts","names":[],"sources":["../src/translate/plugin.ts","../src/translate/languages.ts","../src/translate/migrate-locales.ts","../src/translate/fields.ts","../src/translate/hooks.ts","../src/translate/document.ts","../src/translate/strings.ts","../src/translate/guards.ts","../src/translate/after-commit.ts","../src/translate/state.ts","../src/translate/endpoint.ts","../src/translate/messages.ts"],"mappings":";;;;;;AAsBA;;;;;;;;;iBAAgB,aAAA,CAAc,OAAA,EAAS,oBAAA,GAAuB,MAAA;;;;;;AAA9D;;;cCda,eAAA;EAAA;;;;;;KAKD,iBAAA,WAA4B,eAAA;AAAA,cAE3B,sBAAA,EAAwB,iBAAA;AAPrC;AAAA,cAUa,oBAAA;;;;;;;iBAcG,kBAAA,CACd,YAAA,EAAc,MAAA,mBACb,OAAA,CAAQ,MAAA;;UAyBM,aAAA;EA9CY;EAgD3B,aAAA;EAhDsC;EAkDtC,MAAA;EAhDW;EAkDX,QAAA;AAAA;;cAIW,uBAAA;AAAA,KAER,cAAA,GAAiB,IAAA,CAAK,OAAA;;;iBAWX,uBAAA,CAAwB,OAAA;;;;;;;;;AAvBxC;;;iBAoDgB,aAAA,CAAc,OAAA,EAAS,cAAA,EAAgB,OAAA;EAAW,KAAA;AAAA,IAAwB,OAAA,CAAQ,aAAA;;AA1ClG;;;;;AAA8C;;;;;AAa9C;;;iBAgGgB,sBAAA,CACd,QAAA,UACA,OAAA,EAAS,IAAA,CAAK,aAAA;;AArEhB;;;;iBAqFgB,gBAAA,CACd,KAAA,EAAO,QAAA,CAAS,MAAA,mBAChB,OAAA,EAAS,IAAA,CAAK,aAAA,cACb,MAAA;;;;;;;ADjLH;;;;;;;;;;;;ACdA;;;;;;;;;;AAKA;;UCgBiB,WAAA;EAIf,OAAA,CAAQ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