@bison-lab/payload-core 4.39.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 +63 -33
- package/dist/admin.d.mts +19 -7
- package/dist/admin.d.mts.map +1 -1
- package/dist/admin.mjs +229 -16
- package/dist/admin.mjs.map +1 -1
- package/dist/block-library.d.mts +1 -1
- package/dist/block-library.mjs +1 -1
- package/dist/{block-thumbnails-DXOUzGjY.mjs → block-thumbnails-DC34uFtE.mjs} +1 -1
- package/dist/{block-thumbnails-DXOUzGjY.mjs.map → block-thumbnails-DC34uFtE.mjs.map} +1 -1
- package/dist/block-thumbnails-cli.mjs +1 -1
- package/dist/block-thumbnails.mjs +1 -1
- package/dist/capability-CqdYCzG1.d.mts +434 -0
- package/dist/capability-CqdYCzG1.d.mts.map +1 -0
- package/dist/capability-DHPE2kon.mjs +2685 -0
- package/dist/capability-DHPE2kon.mjs.map +1 -0
- package/dist/{catalogue-FxH10X3v.d.mts → catalogue-DWqHWVE5.d.mts} +1 -1
- package/dist/{catalogue-FxH10X3v.d.mts.map → catalogue-DWqHWVE5.d.mts.map} +1 -1
- package/dist/{facet-field-DjaZ0C7D.d.mts → facet-field-2K22iuWA.d.mts} +1 -1
- package/dist/{facet-field-DjaZ0C7D.d.mts.map → facet-field-2K22iuWA.d.mts.map} +1 -1
- package/dist/{facet-field-Uf8S4yL1.mjs → facet-field-DO3VT_Cz.mjs} +1 -1
- package/dist/{facet-field-Uf8S4yL1.mjs.map → facet-field-DO3VT_Cz.mjs.map} +1 -1
- package/dist/index.d.mts +13 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +25 -667
- package/dist/index.mjs.map +1 -1
- package/dist/{locale-CFWfB4wP.mjs → locale-B6rUVwpg.mjs} +1 -1
- package/dist/locale-B6rUVwpg.mjs.map +1 -0
- package/dist/{locale-CWiIcGuU.d.mts → locale-CTT3nn6T.d.mts} +5 -4
- package/dist/locale-CTT3nn6T.d.mts.map +1 -0
- package/dist/messages-dZV_aAnR.mjs +93 -0
- package/dist/messages-dZV_aAnR.mjs.map +1 -0
- package/dist/metadata.d.mts +1 -1
- package/dist/navigation.d.mts +2 -2
- package/dist/navigation.mjs +1 -1
- package/dist/og.d.mts +2 -2
- package/dist/og.mjs +1 -1
- package/dist/{preview-CNBVfmM7.d.mts → preview-1vwxBgm5.d.mts} +2 -2
- package/dist/{preview-CNBVfmM7.d.mts.map → preview-1vwxBgm5.d.mts.map} +1 -1
- package/dist/{published-_1rrTj_B.d.mts → published-B3etM6X5.d.mts} +3 -3
- package/dist/{published-_1rrTj_B.d.mts.map → published-B3etM6X5.d.mts.map} +1 -1
- package/dist/{published-D3yVnbxs.mjs → published-BMt7Z5CF.mjs} +2 -2
- package/dist/{published-D3yVnbxs.mjs.map → published-BMt7Z5CF.mjs.map} +1 -1
- package/dist/{published-DefZv9na.mjs → published-CkqqY08H.mjs} +2 -2
- package/dist/{published-DefZv9na.mjs.map → published-CkqqY08H.mjs.map} +1 -1
- package/dist/{published-DXjnElZn.d.mts → published-QDNmDi02.d.mts} +2 -2
- package/dist/{published-DXjnElZn.d.mts.map → published-QDNmDi02.d.mts.map} +1 -1
- package/dist/{published-QyTcDznE.mjs → published-hqtvmVUD.mjs} +1 -1
- package/dist/{published-QyTcDznE.mjs.map → published-hqtvmVUD.mjs.map} +1 -1
- package/dist/{root-page-key-B86JwL8Z.mjs → root-page-key-kx3C1eyp.mjs} +1 -1
- package/dist/{root-page-key-B86JwL8Z.mjs.map → root-page-key-kx3C1eyp.mjs.map} +1 -1
- package/dist/seo.mjs +1 -1
- package/dist/{messages-Fl1spIwN.mjs → strings-Fd7kUCT7.mjs} +156 -118
- package/dist/strings-Fd7kUCT7.mjs.map +1 -0
- package/dist/taxonomy.d.mts +1 -1
- package/dist/taxonomy.mjs +1 -1
- package/dist/theme.d.mts +4 -4
- package/dist/theme.mjs +1 -1
- package/dist/{title-D_jixG36.d.mts → title-trhUexxM.d.mts} +1 -1
- package/dist/{title-D_jixG36.d.mts.map → title-trhUexxM.d.mts.map} +1 -1
- package/dist/translate-messages-cli.mjs +3 -2
- package/dist/translate-messages-cli.mjs.map +1 -1
- package/dist/translate.d.mts +300 -206
- package/dist/translate.d.mts.map +1 -1
- package/dist/translate.mjs +225 -1027
- package/dist/translate.mjs.map +1 -1
- package/dist/{types-Db6Iy3hJ.d.mts → types-DLBlHZUd.d.mts} +1 -1
- package/dist/{types-Db6Iy3hJ.d.mts.map → types-DLBlHZUd.d.mts.map} +1 -1
- package/dist/{wireframe-xcJNJzBf.mjs → wireframe-CXorKFU_.mjs} +1 -1
- package/dist/{wireframe-xcJNJzBf.mjs.map → wireframe-CXorKFU_.mjs.map} +1 -1
- package/dist/wireframe-cli.mjs +1 -1
- package/dist/wireframe.mjs +1 -1
- package/package.json +6 -8
- package/dist/locale-CFWfB4wP.mjs.map +0 -1
- package/dist/locale-CWiIcGuU.d.mts.map +0 -1
- package/dist/messages-Fl1spIwN.mjs.map +0 -1
|
@@ -29,4 +29,4 @@ function requiredPageKeys(extra = []) {
|
|
|
29
29
|
//#endregion
|
|
30
30
|
export { REQUIRED_PAGE_UNPUBLISH_MESSAGE as a, isRequiredPageKey as c, REQUIRED_PAGE_FIELD as i, isRootPageKey as l, REQUIRED_PAGE_CELL as n, ROOT_PAGE_KEY as o, REQUIRED_PAGE_DELETE_MESSAGE as r, ROOT_PAGE_SLUG as s, PAGE_SLUG_CELL as t, requiredPageKeys as u };
|
|
31
31
|
|
|
32
|
-
//# sourceMappingURL=root-page-key-
|
|
32
|
+
//# sourceMappingURL=root-page-key-kx3C1eyp.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"root-page-key-
|
|
1
|
+
{"version":3,"file":"root-page-key-kx3C1eyp.mjs","names":[],"sources":["../src/collections/root-page-key.ts"],"sourcesContent":["/**\n * The home page is the row whose `pageKey` is `/`. That key is the identifier.\n * The stored slug is an internal token so an unaddressed draft can keep an\n * empty slug without colliding with home. Editors see `/`, never the token.\n */\nexport const ROOT_PAGE_KEY = \"/\";\n\nexport const ROOT_PAGE_SLUG = \"__root__\";\n\nexport const REQUIRED_PAGE_CELL =\n \"@bison-lab/payload-core/admin#RequiredPageCell\";\n\nexport const REQUIRED_PAGE_FIELD =\n \"@bison-lab/payload-core/admin#RequiredPageField\";\n\nexport const PAGE_SLUG_CELL = \"@bison-lab/payload-core/admin#PageSlugCell\";\n\nexport const REQUIRED_PAGE_DELETE_MESSAGE =\n \"This page is required by the site and cannot be deleted.\";\n\nexport const REQUIRED_PAGE_UNPUBLISH_MESSAGE =\n \"This page is required by the site and cannot be unpublished.\";\n\nexport function isRootPageKey(value: unknown): value is typeof ROOT_PAGE_KEY {\n return value === ROOT_PAGE_KEY;\n}\n\nexport function isRequiredPageKey(\n value: unknown,\n requiredKeys: readonly string[],\n): boolean {\n return typeof value === \"string\" && requiredKeys.includes(value);\n}\n\n/** `/` is always required. Extras are site keys, not paths, and cannot be the root token. */\nexport function requiredPageKeys(extra: readonly string[] = []): string[] {\n const keys = [ROOT_PAGE_KEY];\n for (const key of extra) {\n if (key === ROOT_PAGE_KEY || key === ROOT_PAGE_SLUG || key.trim() === \"\") {\n throw new Error(\n `createPages requiredKeys cannot include ${JSON.stringify(key)}. The home page is always \"/\".`,\n );\n }\n if (!keys.includes(key)) keys.push(key);\n }\n return keys;\n}\n"],"mappings":";;;;;;AAKA,MAAa,gBAAgB;AAE7B,MAAa,iBAAiB;AAE9B,MAAa,qBACX;AAEF,MAAa,sBACX;AAEF,MAAa,iBAAiB;AAE9B,MAAa,+BACX;AAEF,MAAa,kCACX;AAEF,SAAgB,cAAc,OAA+C;AAC3E,QAAO,UAAA;;AAGT,SAAgB,kBACd,OACA,cACS;AACT,QAAO,OAAO,UAAU,YAAY,aAAa,SAAS,MAAM;;;AAIlE,SAAgB,iBAAiB,QAA2B,EAAE,EAAY;CACxE,MAAM,OAAO,CAAA,IAAe;AAC5B,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,QAAA,OAAyB,QAAA,cAA0B,IAAI,MAAM,KAAK,GACpE,OAAM,IAAI,MACR,2CAA2C,KAAK,UAAU,IAAI,CAAC,gCAChE;AAEH,MAAI,CAAC,KAAK,SAAS,IAAI,CAAE,MAAK,KAAK,IAAI;;AAEzC,QAAO"}
|
package/dist/seo.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { l as isRootPageKey } from "./root-page-key-
|
|
1
|
+
import { l as isRootPageKey } from "./root-page-key-kx3C1eyp.mjs";
|
|
2
2
|
import { createElement } from "react";
|
|
3
3
|
//#region src/seo/sitemap.ts
|
|
4
4
|
/** A page with no address yet has nothing to list. Home is keyed, not slugged. */
|
|
@@ -1,28 +1,23 @@
|
|
|
1
|
-
//#region src/translate/
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
async function translateStrings(strings, options) {
|
|
9
|
-
if (strings.length === 0) return [];
|
|
10
|
-
const { translator, ...request } = options;
|
|
11
|
-
const unique = [...new Set(strings)];
|
|
12
|
-
let result;
|
|
13
|
-
try {
|
|
14
|
-
result = await translator(unique, request);
|
|
15
|
-
} catch {
|
|
16
|
-
return null;
|
|
17
|
-
}
|
|
18
|
-
if (!Array.isArray(result) || result.length !== unique.length) return null;
|
|
19
|
-
if (!result.every((value) => typeof value === "string")) return null;
|
|
20
|
-
const byString = new Map(unique.map((value, index) => [value, result[index]]));
|
|
21
|
-
return strings.map((value) => byString.get(value) ?? value);
|
|
1
|
+
//#region src/translate/errors.ts
|
|
2
|
+
function errorType(error) {
|
|
3
|
+
if (typeof error.type === "string") return error.type;
|
|
4
|
+
const body = error.error;
|
|
5
|
+
if (typeof body?.error?.type === "string") return body.error.type;
|
|
6
|
+
if (typeof body?.type === "string") return body.type;
|
|
22
7
|
}
|
|
23
|
-
/**
|
|
24
|
-
function
|
|
25
|
-
|
|
8
|
+
/** Sorts an error thrown by the Anthropic SDK (or a network failure) into a `TranslationFailureKind`. */
|
|
9
|
+
function classifyAnthropicError(error) {
|
|
10
|
+
if (!error || typeof error !== "object") return "other";
|
|
11
|
+
const candidate = error;
|
|
12
|
+
const status = typeof candidate.status === "number" ? candidate.status : void 0;
|
|
13
|
+
const type = errorType(candidate);
|
|
14
|
+
const message = typeof candidate.message === "string" ? candidate.message : "";
|
|
15
|
+
if (status === 402 || type === "billing_error") return "out-of-credit";
|
|
16
|
+
if (status === 400 && /credit balance/i.test(message)) return "out-of-credit";
|
|
17
|
+
if (status === 401 || status === 403 || type === "authentication_error" || type === "permission_error") return "key-rejected";
|
|
18
|
+
if (status === 429 || type === "rate_limit_error") return "rate-limited";
|
|
19
|
+
if (status === void 0 || status >= 500) return "unreachable";
|
|
20
|
+
return "other";
|
|
26
21
|
}
|
|
27
22
|
//#endregion
|
|
28
23
|
//#region src/translate/anthropic.ts
|
|
@@ -32,6 +27,41 @@ function isTranslatorConfigured(translator) {
|
|
|
32
27
|
* price. A site overrides it per environment (`ANTHROPIC_TRANSLATE_MODEL`).
|
|
33
28
|
*/
|
|
34
29
|
const DEFAULT_TRANSLATE_MODEL = "claude-sonnet-5-5";
|
|
30
|
+
/** "Economy (Haiku)" on Settings → Translation: a fraction of Sonnet's price for plainer copy. */
|
|
31
|
+
const ECONOMY_TRANSLATE_MODEL = "claude-haiku-5-5";
|
|
32
|
+
/**
|
|
33
|
+
* Anthropic's list prices for the two models the screen offers. A model
|
|
34
|
+
* not listed (an `ANTHROPIC_TRANSLATE_MODEL` override) is estimated at
|
|
35
|
+
* Sonnet's price, so an estimate errs high rather than reading as free.
|
|
36
|
+
*/
|
|
37
|
+
const TRANSLATE_MODEL_PRICES = {
|
|
38
|
+
[DEFAULT_TRANSLATE_MODEL]: {
|
|
39
|
+
input: 2,
|
|
40
|
+
output: 10
|
|
41
|
+
},
|
|
42
|
+
[ECONOMY_TRANSLATE_MODEL]: {
|
|
43
|
+
input: .1,
|
|
44
|
+
output: .5
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
function modelPrice(model) {
|
|
48
|
+
return TRANSLATE_MODEL_PRICES[model] ?? TRANSLATE_MODEL_PRICES["claude-sonnet-5-5"];
|
|
49
|
+
}
|
|
50
|
+
/** Estimated USD for one call's tokens on `model`. */
|
|
51
|
+
function estimateCost(model, inputTokens, outputTokens) {
|
|
52
|
+
const price = modelPrice(model);
|
|
53
|
+
return (inputTokens * price.input + outputTokens * price.output) / 1e6;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* True when `text` contains `word` as a whole word, case-sensitively: "ProtectIQ"
|
|
57
|
+
* is in "Get ProtectIQ today" but not in "protectiq" or "ProtectIQs". A
|
|
58
|
+
* frozen word is only kept where it appears this way.
|
|
59
|
+
*/
|
|
60
|
+
function containsWord(text, word) {
|
|
61
|
+
if (!word) return false;
|
|
62
|
+
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
63
|
+
return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, "u").test(text);
|
|
64
|
+
}
|
|
35
65
|
/**
|
|
36
66
|
* The SDK's defaults are a 10-minute timeout with retries. A translation
|
|
37
67
|
* must stay bounded to seconds, not minutes: the manual endpoint awaits it
|
|
@@ -86,9 +116,9 @@ function parseJsonArray(text) {
|
|
|
86
116
|
}
|
|
87
117
|
/**
|
|
88
118
|
* The provided `Translator`: one Anthropic Messages call per batch, the
|
|
89
|
-
* strings as a JSON array in and out. `@anthropic-ai/sdk` is
|
|
90
|
-
*
|
|
91
|
-
*
|
|
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
|
|
92
122
|
* refusal, a malformed or wrong-length reply) returns `null` and is logged
|
|
93
123
|
* by the caller; it never throws.
|
|
94
124
|
*/
|
|
@@ -102,15 +132,29 @@ function anthropicTranslator(options) {
|
|
|
102
132
|
client = new (await (import("@anthropic-ai/sdk"))).default({ apiKey });
|
|
103
133
|
return client;
|
|
104
134
|
};
|
|
135
|
+
const report = async (event) => {
|
|
136
|
+
try {
|
|
137
|
+
await options.onCall?.(event);
|
|
138
|
+
} catch {}
|
|
139
|
+
};
|
|
105
140
|
const translate = async (strings, request) => {
|
|
106
141
|
if (strings.length === 0) return [];
|
|
142
|
+
let anthropic;
|
|
143
|
+
try {
|
|
144
|
+
anthropic = await getClient();
|
|
145
|
+
} catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
if (!anthropic) return null;
|
|
107
149
|
try {
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
150
|
+
const given = request.site ?? options.site;
|
|
151
|
+
const site = given?.keepVerbatim ? {
|
|
152
|
+
...given,
|
|
153
|
+
keepVerbatim: given.keepVerbatim.filter((word) => strings.some((value) => containsWord(value, word)))
|
|
154
|
+
} : given;
|
|
111
155
|
const to = languageName(request.to, site);
|
|
112
156
|
const content = (request.context ? `Context: ${request.context}\n\n` : "") + `Translate this JSON array of ${strings.length} strings to ${to}:\n${JSON.stringify(strings)}`;
|
|
113
|
-
const
|
|
157
|
+
const response = await anthropic.messages.create({
|
|
114
158
|
model,
|
|
115
159
|
max_tokens: 16e3,
|
|
116
160
|
output_config: { effort: "low" },
|
|
@@ -126,104 +170,98 @@ function anthropicTranslator(options) {
|
|
|
126
170
|
}, {
|
|
127
171
|
timeout: TIMEOUT_MS,
|
|
128
172
|
maxRetries: MAX_RETRIES
|
|
129
|
-
})
|
|
130
|
-
|
|
131
|
-
|
|
173
|
+
});
|
|
174
|
+
const parsed = parseJsonArray(response.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("").trim());
|
|
175
|
+
const usable = parsed && parsed.length === strings.length ? parsed : null;
|
|
176
|
+
if (usable) await report({
|
|
177
|
+
ok: true,
|
|
178
|
+
model,
|
|
179
|
+
strings: strings.length,
|
|
180
|
+
inputTokens: response.usage?.input_tokens ?? 0,
|
|
181
|
+
outputTokens: response.usage?.output_tokens ?? 0
|
|
182
|
+
});
|
|
183
|
+
else await report({
|
|
184
|
+
ok: false,
|
|
185
|
+
model,
|
|
186
|
+
strings: strings.length,
|
|
187
|
+
failure: "other",
|
|
188
|
+
message: "The reply was not a usable JSON array."
|
|
189
|
+
});
|
|
190
|
+
return usable;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const status = error.status;
|
|
193
|
+
await report({
|
|
194
|
+
ok: false,
|
|
195
|
+
model,
|
|
196
|
+
strings: strings.length,
|
|
197
|
+
failure: classifyAnthropicError(error),
|
|
198
|
+
...typeof status === "number" ? { status } : {},
|
|
199
|
+
message: error instanceof Error ? error.message : String(error)
|
|
200
|
+
});
|
|
132
201
|
return null;
|
|
133
202
|
}
|
|
134
203
|
};
|
|
135
204
|
return Object.assign(translate, { configured: Boolean(apiKey || options.client) });
|
|
136
205
|
}
|
|
137
|
-
//#endregion
|
|
138
|
-
//#region src/translate/messages.ts
|
|
139
|
-
const BATCH_SIZE = 40;
|
|
140
|
-
/** Every string leaf as [path, value]; array indexes are path segments. */
|
|
141
|
-
function stringLeaves(node, path = [], out = []) {
|
|
142
|
-
if (typeof node === "string") out.push([path, node]);
|
|
143
|
-
else if (Array.isArray(node)) node.forEach((item, index) => stringLeaves(item, [...path, String(index)], out));
|
|
144
|
-
else if (node && typeof node === "object") for (const [key, value] of Object.entries(node)) stringLeaves(value, [...path, key], out);
|
|
145
|
-
return out;
|
|
146
|
-
}
|
|
147
|
-
function getAtPath(root, path) {
|
|
148
|
-
let current = root;
|
|
149
|
-
for (const segment of path) {
|
|
150
|
-
if (current == null || typeof current !== "object") return void 0;
|
|
151
|
-
current = Array.isArray(current) ? current[Number(segment)] : current[segment];
|
|
152
|
-
}
|
|
153
|
-
return current;
|
|
154
|
-
}
|
|
155
|
-
function setAtPath(root, path, value) {
|
|
156
|
-
let current = root;
|
|
157
|
-
for (let i = 0; i < path.length - 1; i++) {
|
|
158
|
-
const segment = path[i];
|
|
159
|
-
const wantArray = /^\d+$/.test(path[i + 1]);
|
|
160
|
-
const container = current;
|
|
161
|
-
let child = container[segment];
|
|
162
|
-
if (child == null || typeof child !== "object" || Array.isArray(child) !== wantArray) {
|
|
163
|
-
child = wantArray ? [] : {};
|
|
164
|
-
container[segment] = child;
|
|
165
|
-
}
|
|
166
|
-
current = child;
|
|
167
|
-
}
|
|
168
|
-
current[path[path.length - 1]] = value;
|
|
169
|
-
}
|
|
170
206
|
/**
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
207
|
+
* Checks a key with the smallest call that proves both the key and the
|
|
208
|
+
* account's credit: one Haiku message with a few output tokens (a fraction
|
|
209
|
+
* of a cent). A 401 is `rejected`; a billing error `out-of-credit`; no
|
|
210
|
+
* answer, a 5xx or a rate limit `unreachable`, meaning "check again on
|
|
211
|
+
* first use". Never throws.
|
|
174
212
|
*/
|
|
175
|
-
function
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
213
|
+
async function verifyAnthropicKey(apiKey, options = {}) {
|
|
214
|
+
try {
|
|
215
|
+
let client = options.client;
|
|
216
|
+
if (!client) client = new (await (import("@anthropic-ai/sdk"))).default({ apiKey });
|
|
217
|
+
await client.messages.create({
|
|
218
|
+
model: ECONOMY_TRANSLATE_MODEL,
|
|
219
|
+
max_tokens: 16,
|
|
220
|
+
output_config: { effort: "low" },
|
|
221
|
+
messages: [{
|
|
222
|
+
role: "user",
|
|
223
|
+
content: "Reply with OK."
|
|
224
|
+
}]
|
|
225
|
+
}, {
|
|
226
|
+
timeout: 2e4,
|
|
227
|
+
maxRetries: 0
|
|
228
|
+
});
|
|
229
|
+
return "valid";
|
|
230
|
+
} catch (error) {
|
|
231
|
+
const kind = classifyAnthropicError(error);
|
|
232
|
+
if (kind === "key-rejected") return "rejected";
|
|
233
|
+
if (kind === "out-of-credit") return "out-of-credit";
|
|
234
|
+
return "unreachable";
|
|
235
|
+
}
|
|
183
236
|
}
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/translate/strings.ts
|
|
184
239
|
/**
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
* keys. `{placeholders}` survive because the translator's prompt keeps them.
|
|
240
|
+
* Translates `strings` with `translator` in one batch, preserving order.
|
|
241
|
+
* Repeated strings are sent once. Returns `null` when the translator throws,
|
|
242
|
+
* returns `null`, or returns anything but one string per string sent, so a
|
|
243
|
+
* caller can leave the target as it was. Never throws.
|
|
190
244
|
*/
|
|
191
|
-
async function
|
|
192
|
-
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
const batch = missing.slice(i, i + BATCH_SIZE);
|
|
201
|
-
const result = await translateStrings(batch.map(([, value]) => value), {
|
|
202
|
-
translator: options.translator,
|
|
203
|
-
from: options.from,
|
|
204
|
-
to: options.to,
|
|
205
|
-
context: options.context ?? "Website UI strings",
|
|
206
|
-
...options.site ? { site: options.site } : {}
|
|
207
|
-
});
|
|
208
|
-
batch.forEach(([path, source], index) => {
|
|
209
|
-
const value = result?.[index];
|
|
210
|
-
if (value !== void 0 && keepsPlaceholders(source, value)) {
|
|
211
|
-
translated += 1;
|
|
212
|
-
setAtPath(base, path, value);
|
|
213
|
-
} else {
|
|
214
|
-
fellBack += 1;
|
|
215
|
-
setAtPath(base, path, source);
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
options.onProgress?.(Math.min(i + BATCH_SIZE, missing.length), missing.length);
|
|
245
|
+
async function translateStrings(strings, options) {
|
|
246
|
+
if (strings.length === 0) return [];
|
|
247
|
+
const { translator, ...request } = options;
|
|
248
|
+
const unique = [...new Set(strings)];
|
|
249
|
+
let result;
|
|
250
|
+
try {
|
|
251
|
+
result = await translator(unique, request);
|
|
252
|
+
} catch {
|
|
253
|
+
return null;
|
|
219
254
|
}
|
|
220
|
-
return
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
255
|
+
if (!Array.isArray(result) || result.length !== unique.length) return null;
|
|
256
|
+
if (!result.every((value) => typeof value === "string")) return null;
|
|
257
|
+
const byString = new Map(unique.map((value, index) => [value, result[index]]));
|
|
258
|
+
return strings.map((value) => byString.get(value) ?? value);
|
|
259
|
+
}
|
|
260
|
+
/** True unless the translator says it cannot run (an Anthropic translator with no API key). */
|
|
261
|
+
function isTranslatorConfigured(translator) {
|
|
262
|
+
return translator !== void 0 && translator.configured !== false;
|
|
225
263
|
}
|
|
226
264
|
//#endregion
|
|
227
|
-
export {
|
|
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 };
|
|
228
266
|
|
|
229
|
-
//# sourceMappingURL=
|
|
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;CACj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AS,eAAgB,QAAO;AACpC,MAAI,SAAS,gBAAiB,QAAO;AACrC,SAAO;;;;;;;;;;;ACjSX,eAAsB,iBACpB,SACA,SAC0B;AAC1B,KAAI,QAAQ,WAAW,EAAG,QAAO,EAAE;CACnC,MAAM,EAAE,YAAY,GAAG,YAAY;CACnC,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,QAAQ,CAAC;CACpC,IAAI;AACJ,KAAI;AACF,WAAS,MAAM,WAAW,QAAQ,QAAQ;SACpC;AACN,SAAO;;AAET,KAAI,CAAC,MAAM,QAAQ,OAAO,IAAI,OAAO,WAAW,OAAO,OAAQ,QAAO;AACtE,KAAI,CAAC,OAAO,OAAO,UAAU,OAAO,UAAU,SAAS,CAAE,QAAO;CAChE,MAAM,WAAW,IAAI,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/taxonomy.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as facetField, t as FacetEntry } from "./facet-field-
|
|
1
|
+
import { n as facetField, t as FacetEntry } from "./facet-field-2K22iuWA.mjs";
|
|
2
2
|
export { type FacetEntry, facetField };
|
package/dist/taxonomy.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as facetField } from "./facet-field-
|
|
1
|
+
import { t as facetField } from "./facet-field-DO3VT_Cz.mjs";
|
|
2
2
|
export { facetField };
|
package/dist/theme.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-
|
|
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-
|
|
3
|
-
import { t as LocaleRead } from "./locale-
|
|
4
|
-
import { n as getPublishedIdentity, r as getPublishedTheme } from "./published-
|
|
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
|
+
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-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
|
package/dist/theme.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { l as stateFromColorDoc, n as SYSTEM_COLOR_KEYS, o as THEME_SLUG, t as resolveThemeIdentity, u as themeConfigFromDoc } from "./identity-CN6EOeDM.mjs";
|
|
2
2
|
import { a as pageEditorLooks, c as themeLibraryFromDoc, d as deleteLibraryColor, f as rewriteColorToken, i as PAGE_EDITOR_SYSTEM_KEYS, l as findColorTokens, n as colorTokenField, o as pageEditorSwatches, p as themeColorKeys, r as lookField, s as pageEditorTokens, t as THEME_PREVIEW_BREAKPOINTS, u as rewriteColorTokens } from "./preview-Br1SQCKn.mjs";
|
|
3
|
-
import { n as getPublishedTheme, t as getPublishedIdentity } from "./published-
|
|
3
|
+
import { n as getPublishedTheme, t as getPublishedIdentity } from "./published-CkqqY08H.mjs";
|
|
4
4
|
import { fontFaceCss, fontPreloads } from "@bison-lab/fonts";
|
|
5
5
|
import { buildThemeCss, generateNamedScaleCSS, lookBindingCss, themeFontIds } from "@bison-lab/tokens";
|
|
6
6
|
//#region src/theme/look-css.ts
|
|
@@ -52,4 +52,4 @@ declare function documentTitle(siteName: string, pageTitle: string): string;
|
|
|
52
52
|
declare function titleTemplate(siteName: string): string;
|
|
53
53
|
//#endregion
|
|
54
54
|
export { SeoImageSize as a, SeoImageDoc as i, titleTemplate as n, SeoImageValue as o, MediaId as r, SeoMeta as s, documentTitle as t };
|
|
55
|
-
//# sourceMappingURL=title-
|
|
55
|
+
//# sourceMappingURL=title-trhUexxM.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"title-
|
|
1
|
+
{"version":3,"file":"title-trhUexxM.d.mts","names":[],"sources":["../src/seo/types.ts","../src/seo/title.ts"],"mappings":";;KACY,OAAA;;UAGK,YAAA;EACf,GAAA;EACA,KAAA;EACA,MAAA;AAAA;;;;;;;;AAWF;UAAiB,WAAA;EACf,GAAA;EACA,GAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;IAAA,CAAW,IAAA,WAAe,YAAA;EAAA;AAAA;;KAIhB,aAAA,GAAgB,OAAA,GAAU,WAAA;;AAAtC;;;UAMiB,OAAA;EACf,KAAA;EACA,WAAA;EACA,KAAA,GAAQ,aAAA;EACR,OAAA;AAAA;;;;AApCF;;;;;iBCKgB,aAAA,CAAc,QAAA,UAAkB,SAAA;;;;;iBAQhC,aAAA,CAAc,QAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { o as anthropicTranslator } from "./strings-Fd7kUCT7.mjs";
|
|
3
|
+
import { t as fillMessages } from "./messages-dZV_aAnR.mjs";
|
|
3
4
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { basename, resolve } from "node:path";
|
|
5
6
|
import { parseArgs } from "node:util";
|
|
@@ -128,7 +129,7 @@ function loadEnvFiles(cwd) {
|
|
|
128
129
|
/**
|
|
129
130
|
* `bison-translate-messages`: fills a next-intl message file from the source
|
|
130
131
|
* locale's file with the Anthropic translator. Run it from the site, which
|
|
131
|
-
* installs `@anthropic-ai/sdk` (
|
|
132
|
+
* installs `@anthropic-ai/sdk` (a peer of this package).
|
|
132
133
|
*
|
|
133
134
|
* bison-translate-messages --source src/messages/en.json --out src/messages/es.json
|
|
134
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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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"}
|
|
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.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,MAAM;AACf,OAAK,IAAI,yBAAyB;AAClC,SAAO;;CAET,MAAM,aAAa,OAAO,OAAO,WAAW,WAAW,QAAQ,OAAO,OAAO,GAAG,KAAA;CAChF,MAA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