@bison-lab/payload-core 4.40.0 → 5.1.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.
Files changed (36) hide show
  1. package/README.md +47 -4
  2. package/dist/admin.d.mts +21 -1
  3. package/dist/admin.d.mts.map +1 -1
  4. package/dist/admin.mjs +270 -5
  5. package/dist/admin.mjs.map +1 -1
  6. package/dist/{capability-DdnN7AHB.mjs → capability-Cb62lWQo.mjs} +1392 -32
  7. package/dist/capability-Cb62lWQo.mjs.map +1 -0
  8. package/dist/{capability-BVDhJV8A.d.mts → capability-Dotbq58Q.d.mts} +85 -9
  9. package/dist/capability-Dotbq58Q.d.mts.map +1 -0
  10. package/dist/index.d.mts +3 -3
  11. package/dist/index.mjs +3 -3
  12. package/dist/locale-B6rUVwpg.mjs.map +1 -1
  13. package/dist/{locale-5z7KTvRJ.d.mts → locale-CTT3nn6T.d.mts} +5 -4
  14. package/dist/locale-CTT3nn6T.d.mts.map +1 -0
  15. package/dist/{messages-Bk1uYO3o.mjs → messages-dZV_aAnR.mjs} +2 -2
  16. package/dist/{messages-Bk1uYO3o.mjs.map → messages-dZV_aAnR.mjs.map} +1 -1
  17. package/dist/navigation.d.mts +2 -2
  18. package/dist/og.d.mts +1 -1
  19. package/dist/{published-CY5PIy5W.d.mts → published-B3etM6X5.d.mts} +2 -2
  20. package/dist/{published-CY5PIy5W.d.mts.map → published-B3etM6X5.d.mts.map} +1 -1
  21. package/dist/{published-BC8kg47c.d.mts → published-QDNmDi02.d.mts} +2 -2
  22. package/dist/{published-BC8kg47c.d.mts.map → published-QDNmDi02.d.mts.map} +1 -1
  23. package/dist/{strings-Bafwdg67.mjs → strings-Fd7kUCT7.mjs} +4 -4
  24. package/dist/strings-Fd7kUCT7.mjs.map +1 -0
  25. package/dist/theme.d.mts +2 -2
  26. package/dist/translate-messages-cli.mjs +3 -3
  27. package/dist/translate-messages-cli.mjs.map +1 -1
  28. package/dist/translate.d.mts +366 -6
  29. package/dist/translate.d.mts.map +1 -1
  30. package/dist/translate.mjs +238 -5
  31. package/dist/translate.mjs.map +1 -1
  32. package/package.json +8 -10
  33. package/dist/capability-BVDhJV8A.d.mts.map +0 -1
  34. package/dist/capability-DdnN7AHB.mjs.map +0 -1
  35. package/dist/locale-5z7KTvRJ.d.mts.map +0 -1
  36. package/dist/strings-Bafwdg67.mjs.map +0 -1
@@ -1,6 +1,6 @@
1
- import { f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, n as translateStrings, o as anthropicTranslator, r as DEFAULT_TRANSLATE_MODEL, t as isTranslatorConfigured } from "./strings-Bafwdg67.mjs";
1
+ import { c as estimateCost, f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, n as translateStrings, o as anthropicTranslator, r as DEFAULT_TRANSLATE_MODEL, s as containsWord, t as isTranslatorConfigured } from "./strings-Fd7kUCT7.mjs";
2
2
  import { APIError } from "payload";
3
- import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
3
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
4
  //#region src/features/types.ts
5
5
  const FEATURES_SLUG = "features";
6
6
  const FEATURE_GROUPS = [
@@ -798,6 +798,7 @@ function collectFields(fields, value, prefix, inLocalized, configBlocks, out) {
798
798
  */
799
799
  function wants(ctx, source, existing, before) {
800
800
  if (!filled(source)) return false;
801
+ if (ctx.force) return ctx.force(source, existing);
801
802
  if (ctx.overwrite || !filled(existing)) return true;
802
803
  return ctx.hasPrevious && source !== before;
803
804
  }
@@ -830,6 +831,7 @@ function translationJob(input) {
830
831
  overwrite: input.overwrite === true,
831
832
  hasPrevious: input.previous != null,
832
833
  configBlocks: input.schema.blocks,
834
+ ...input.force ? { force: input.force } : {},
833
835
  sources: [],
834
836
  setters: []
835
837
  };
@@ -961,7 +963,8 @@ function planRichText(ctx, source, target, previous) {
961
963
  };
962
964
  }
963
965
  const targetFilled = targetNodes?.some((ref) => filled(ref.node.text)) ?? false;
964
- if (!(ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
966
+ const targetText = (targetNodes ?? []).map((ref) => String(ref.node.text ?? "")).join(" ");
967
+ if (!(ctx.force ? sourceNodes.some((ref) => filled(ref.node.text) && ctx.force(ref.node.text, targetText)) : ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
965
968
  value: target,
966
969
  touched: false
967
970
  };
@@ -1050,6 +1053,398 @@ function resolveApiKey(input) {
1050
1053
  };
1051
1054
  }
1052
1055
  //#endregion
1056
+ //#region src/translate/languages.ts
1057
+ /**
1058
+ * The languages every Bison site carries. The library owns this list: a new
1059
+ * language is a library release that sites take by updating the package
1060
+ * (and running the migration it brings). The first entry is the default
1061
+ * locale of a site that declares no localization of its own.
1062
+ */
1063
+ const LIBRARY_LOCALES = [{
1064
+ code: "en",
1065
+ label: "English"
1066
+ }, {
1067
+ code: "es",
1068
+ label: "Español"
1069
+ }];
1070
+ const LIBRARY_DEFAULT_LOCALE = "en";
1071
+ /** The codes of `LIBRARY_LOCALES`, in order. */
1072
+ const LIBRARY_LOCALE_CODES = LIBRARY_LOCALES.map((locale) => locale.code);
1073
+ function codeOf(entry) {
1074
+ return typeof entry === "string" ? entry : entry.code;
1075
+ }
1076
+ /**
1077
+ * A config's `localization` with every library language in it. A site with
1078
+ * none gets the library's (English default, `fallback: true`, so an empty
1079
+ * Spanish field reads as English). A site with its own keeps its locales,
1080
+ * labels and default, and gains any library language it lacks.
1081
+ */
1082
+ function withLibraryLocales(localization) {
1083
+ if (!localization) return {
1084
+ locales: LIBRARY_LOCALES.map((locale) => ({ ...locale })),
1085
+ defaultLocale: "en",
1086
+ fallback: true
1087
+ };
1088
+ const own = localization.locales;
1089
+ const have = new Set(own.map(codeOf));
1090
+ const missing = LIBRARY_LOCALES.filter((locale) => !have.has(locale.code));
1091
+ if (missing.length === 0) return localization;
1092
+ const locales = [...own.map((entry) => typeof entry === "string" ? {
1093
+ code: entry,
1094
+ label: entry
1095
+ } : entry), ...missing.map((locale) => ({ ...locale }))];
1096
+ return {
1097
+ ...localization,
1098
+ locales
1099
+ };
1100
+ }
1101
+ /** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
1102
+ const ACTIVE_LOCALES_CACHE_MS = 6e4;
1103
+ const cache$1 = /* @__PURE__ */ new WeakMap();
1104
+ /** The last answer read from the database, kept for when a later read fails. */
1105
+ const lastGood = /* @__PURE__ */ new WeakMap();
1106
+ /** After a failed read, how soon to try the database again. */
1107
+ const ACTIVE_LOCALES_RETRY_MS = 5e3;
1108
+ /** Drops the cached answer, so the next `activeLocales` reads again. */
1109
+ function invalidateActiveLocales(payload) {
1110
+ cache$1.delete(payload);
1111
+ }
1112
+ /**
1113
+ * The ticked target languages, as the Translation screen stores them.
1114
+ * `null` or absent (never saved) means the defaults: the target locales the
1115
+ * site declared itself before the library's were added.
1116
+ */
1117
+ function resolveActiveTargets(stored, targets, defaults) {
1118
+ const chosen = Array.isArray(stored) ? stored : defaults;
1119
+ return targets.filter((code) => chosen.includes(code));
1120
+ }
1121
+ /**
1122
+ * The site's active languages, for routing and middleware: the default
1123
+ * locale plus each target language ticked on Settings → Translation. Cached
1124
+ * per process for `ttlMs` (60s by default): a request reads memory, and the
1125
+ * database is read only when the cache refreshes, or after a save of the
1126
+ * screen in the same process. Never throws. When a read fails it answers
1127
+ * with the last good read (or, before the first one, the defaults) and
1128
+ * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
1129
+ * never stands in for the Admin's ticks for a whole cache period, which
1130
+ * would send a ticked language's visitors permanent redirects.
1131
+ */
1132
+ function activeLocales(payload, options = {}) {
1133
+ const ttl = options.ttlMs ?? 6e4;
1134
+ const hit = cache$1.get(payload);
1135
+ if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;
1136
+ const entry = {
1137
+ at: Date.now(),
1138
+ value: void 0
1139
+ };
1140
+ entry.value = readActiveLocales(payload).then((read) => {
1141
+ if (read.ok) {
1142
+ lastGood.set(payload, read.value);
1143
+ return read.value;
1144
+ }
1145
+ entry.ttl = ACTIVE_LOCALES_RETRY_MS;
1146
+ return lastGood.get(payload) ?? read.value;
1147
+ });
1148
+ cache$1.set(payload, entry);
1149
+ return entry.value;
1150
+ }
1151
+ /** The slug `activeLocales` reads; the Translation screen's. */
1152
+ const SETTINGS_SLUG = "translation-settings";
1153
+ /** Where `applyTranslation` leaves the default ticks: the site's own target locales. */
1154
+ const DEFAULT_ACTIVE_LOCALES = "bisonDefaultActiveLocales";
1155
+ async function readActiveLocales(payload) {
1156
+ const localization = payload.config.localization;
1157
+ const codes = localization ? localization.locales.map(codeOf) : ["en"];
1158
+ const defaultLocale = localization ? localization.defaultLocale : "en";
1159
+ const targets = codes.filter((code) => code !== defaultLocale);
1160
+ const defaults = payload.config.custom?.["bisonDefaultActiveLocales"] ?? targets;
1161
+ let stored;
1162
+ let ok = true;
1163
+ try {
1164
+ const doc = await payload.findGlobal({
1165
+ slug: SETTINGS_SLUG,
1166
+ depth: 0,
1167
+ overrideAccess: true
1168
+ });
1169
+ stored = doc?.languagesChosen ? doc.languages ?? [] : void 0;
1170
+ } catch {
1171
+ stored = void 0;
1172
+ ok = false;
1173
+ }
1174
+ const ticked = resolveActiveTargets(stored, targets, defaults);
1175
+ return {
1176
+ ok,
1177
+ value: {
1178
+ defaultLocale,
1179
+ active: codes.filter((code) => code === defaultLocale || ticked.includes(code)),
1180
+ inactive: targets.filter((code) => !ticked.includes(code))
1181
+ }
1182
+ };
1183
+ }
1184
+ /**
1185
+ * Where a request for an inactive language goes: the same path without
1186
+ * its locale prefix, for a 308. `null` when the path is not under an
1187
+ * inactive locale. In a site's middleware:
1188
+ *
1189
+ * ```ts
1190
+ * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
1191
+ * if (to) {
1192
+ * const response = NextResponse.redirect(new URL(to + url.search, url), 308);
1193
+ * response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
1194
+ * return response;
1195
+ * }
1196
+ * ```
1197
+ */
1198
+ function inactiveLocaleRedirect(pathname, locales) {
1199
+ const [, first, ...rest] = pathname.split("/");
1200
+ if (!first || !locales.inactive.includes(first)) return null;
1201
+ return `/${rest.join("/").replace(/^[\\/]+/, "")}`;
1202
+ }
1203
+ /**
1204
+ * A page's language alternates (for hreflang and a language switcher),
1205
+ * keeping only active languages. `paths` maps each locale to that
1206
+ * language's URL for the page.
1207
+ */
1208
+ function activeAlternates(paths, locales) {
1209
+ return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));
1210
+ }
1211
+ //#endregion
1212
+ //#region src/translate/cas.ts
1213
+ /**
1214
+ * An atomic compare-and-set on one row: write `set` only where the row's
1215
+ * `guard` columns still hold the values given, and say whether it did.
1216
+ *
1217
+ * Payload's update-by-`where` is not this: it finds the matching rows, then
1218
+ * updates each, so two writers that both read the old value both "win".
1219
+ * The job lease and the usage counter need exactly one winner, so on
1220
+ * Postgres this is one parameterized `UPDATE … WHERE … RETURNING` through
1221
+ * the adapter's own pool (raw SQL because the Local API cannot express an
1222
+ * atomic conditional write; every value is a bound parameter, and table
1223
+ * and column names come only from this package's fixed `dbName`s and
1224
+ * field names). On another adapter it falls back to the Local API, which
1225
+ * is right for one writer at a time but not atomic.
1226
+ */
1227
+ async function compareAndSet(payload, input) {
1228
+ const pool = payload.db?.pool;
1229
+ if (pool && typeof pool.query === "function") {
1230
+ const values = [];
1231
+ const param = (value) => {
1232
+ values.push(value);
1233
+ return `$${values.length}`;
1234
+ };
1235
+ const assignments = Object.entries(input.set).map(([field, value]) => `${column(field)} = ${param(value)}`);
1236
+ const conditions = [`"id" = ${param(input.id)}`, ...Object.entries(input.guard).map(([field, value]) => value === null || value === void 0 ? `${column(field)} IS NULL` : `${column(field)} = ${param(value)}`)];
1237
+ return ((await pool.query(`UPDATE ${quote(input.table)} SET ${assignments.join(", ")}, "updated_at" = now() WHERE ${conditions.join(" AND ")}`, values)).rowCount ?? 0) === 1;
1238
+ }
1239
+ return ((await payload.update({
1240
+ collection: input.collection,
1241
+ where: { and: [{ id: { equals: input.id } }, ...Object.entries(input.guard).map(([field, value]) => ({ [field]: { equals: value ?? null } }))] },
1242
+ data: input.set,
1243
+ depth: 0,
1244
+ overrideAccess: true,
1245
+ context: { autoTranslate: false }
1246
+ })).docs?.length ?? 0) === 1;
1247
+ }
1248
+ /** `leaseRev` → `"lease_rev"`: Payload's Postgres column for a top-level field. */
1249
+ function column(field) {
1250
+ return quote(field.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase());
1251
+ }
1252
+ function quote(name) {
1253
+ if (!/^[a-z_][a-z0-9_]*$/.test(name)) throw new Error(`compareAndSet: unexpected identifier ${name}`);
1254
+ return `"${name}"`;
1255
+ }
1256
+ //#endregion
1257
+ //#region src/translate/usage.ts
1258
+ /**
1259
+ * What translation cost and why it last failed. Usage is one row per month
1260
+ * in a hidden collection (kept, so previous months stay viewable); the
1261
+ * failure lives on the unversioned `translation-state` Global and clears on
1262
+ * the next success.
1263
+ */
1264
+ const TRANSLATION_USAGE_SLUG = "translation-usage";
1265
+ /** How many 429s in a row make "rate limited" worth a banner. A single one is routine. */
1266
+ const RATE_LIMIT_STREAK = 3;
1267
+ /** `2026-11`, in UTC. */
1268
+ function monthKey(date = /* @__PURE__ */ new Date()) {
1269
+ return date.toISOString().slice(0, 7);
1270
+ }
1271
+ /** One row per month. Hidden; read by the screen's endpoints, written only by the server. */
1272
+ function translationUsageCollection() {
1273
+ return {
1274
+ slug: TRANSLATION_USAGE_SLUG,
1275
+ dbName: "translation_usage",
1276
+ labels: {
1277
+ singular: "Translation usage",
1278
+ plural: "Translation usage"
1279
+ },
1280
+ admin: { hidden: true },
1281
+ access: {
1282
+ read: () => false,
1283
+ create: () => false,
1284
+ update: () => false,
1285
+ delete: () => false
1286
+ },
1287
+ fields: [
1288
+ {
1289
+ name: "month",
1290
+ type: "text",
1291
+ required: true,
1292
+ unique: true,
1293
+ index: true
1294
+ },
1295
+ {
1296
+ name: "strings",
1297
+ type: "number",
1298
+ defaultValue: 0
1299
+ },
1300
+ {
1301
+ name: "inputTokens",
1302
+ type: "number",
1303
+ defaultValue: 0
1304
+ },
1305
+ {
1306
+ name: "outputTokens",
1307
+ type: "number",
1308
+ defaultValue: 0
1309
+ },
1310
+ {
1311
+ name: "cost",
1312
+ type: "number",
1313
+ defaultValue: 0
1314
+ },
1315
+ {
1316
+ name: "rev",
1317
+ type: "number",
1318
+ defaultValue: 0
1319
+ }
1320
+ ]
1321
+ };
1322
+ }
1323
+ /** Attempts at a compare-and-set increment before giving up on one call's usage. */
1324
+ const USAGE_ATTEMPTS = 8;
1325
+ async function monthRow(payload, month) {
1326
+ const { docs } = await payload.find({
1327
+ collection: TRANSLATION_USAGE_SLUG,
1328
+ where: { month: { equals: month } },
1329
+ limit: 1,
1330
+ depth: 0,
1331
+ overrideAccess: true
1332
+ });
1333
+ return docs[0];
1334
+ }
1335
+ /** This month's usage, zeros when nothing ran. */
1336
+ async function usageThisMonth(payload, now = /* @__PURE__ */ new Date()) {
1337
+ const month = monthKey(now);
1338
+ const row = await monthRow(payload, month).catch(() => void 0);
1339
+ return {
1340
+ month,
1341
+ strings: row?.strings ?? 0,
1342
+ inputTokens: row?.inputTokens ?? 0,
1343
+ outputTokens: row?.outputTokens ?? 0,
1344
+ cost: row?.cost ?? 0
1345
+ };
1346
+ }
1347
+ /** The last `months` months that have usage, newest first. */
1348
+ async function usageHistory(payload, months = 12) {
1349
+ try {
1350
+ const { docs } = await payload.find({
1351
+ collection: TRANSLATION_USAGE_SLUG,
1352
+ sort: "-month",
1353
+ limit: months,
1354
+ depth: 0,
1355
+ overrideAccess: true
1356
+ });
1357
+ return docs.map(({ month, strings, inputTokens, outputTokens, cost }) => ({
1358
+ month,
1359
+ strings: strings ?? 0,
1360
+ inputTokens: inputTokens ?? 0,
1361
+ outputTokens: outputTokens ?? 0,
1362
+ cost: cost ?? 0
1363
+ }));
1364
+ } catch {
1365
+ return [];
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Adds one successful call to its month. Calls finish concurrently (editor
1370
+ * saves beside a running job), so the add is a compare-and-set on the
1371
+ * row's `rev`: a write that lost the race reads again and retries, and no
1372
+ * call's tokens or cost are lost to the cap.
1373
+ */
1374
+ async function recordUsage(payload, event, now = /* @__PURE__ */ new Date()) {
1375
+ const month = monthKey(now);
1376
+ const cost = estimateCost(event.model, event.inputTokens, event.outputTokens);
1377
+ for (let attempt = 0; attempt < USAGE_ATTEMPTS; attempt++) {
1378
+ const row = await monthRow(payload, month);
1379
+ if (!row) try {
1380
+ await payload.create({
1381
+ collection: TRANSLATION_USAGE_SLUG,
1382
+ data: {
1383
+ month,
1384
+ strings: event.strings,
1385
+ inputTokens: event.inputTokens,
1386
+ outputTokens: event.outputTokens,
1387
+ cost,
1388
+ rev: 0
1389
+ },
1390
+ overrideAccess: true,
1391
+ context: { autoTranslate: false }
1392
+ });
1393
+ return;
1394
+ } catch {
1395
+ continue;
1396
+ }
1397
+ const rev = row.rev ?? 0;
1398
+ if (await compareAndSet(payload, {
1399
+ collection: "translation-usage",
1400
+ table: "translation_usage",
1401
+ id: row.id,
1402
+ guard: { rev },
1403
+ set: {
1404
+ strings: (row.strings ?? 0) + event.strings,
1405
+ inputTokens: (row.inputTokens ?? 0) + event.inputTokens,
1406
+ outputTokens: (row.outputTokens ?? 0) + event.outputTokens,
1407
+ cost: (row.cost ?? 0) + cost,
1408
+ rev: rev + 1
1409
+ }
1410
+ })) return;
1411
+ }
1412
+ }
1413
+ /** What an Admin should do about each failure, in the banner's words. */
1414
+ const FAILURE_ADVICE = {
1415
+ "out-of-credit": "The Anthropic account is out of credit, so nothing is being translated. Add credit in the Anthropic Console, then press Check again in Settings → Translation.",
1416
+ "key-rejected": "Anthropic rejected the API key, so nothing is being translated. Paste a working key in Settings → Translation.",
1417
+ "rate-limited": "Anthropic keeps refusing requests for going too fast (rate limit). Translation retries on the next save; if it persists, raise the account's limits.",
1418
+ "cap-reached": "This month's translation spending cap is reached, so translation is paused until next month. Raise or clear the cap in Settings → Translation to resume."
1419
+ };
1420
+ /**
1421
+ * The failure (if any) a call's outcome records on the state Global:
1422
+ * out of credit and a rejected key at once, a rate limit only after
1423
+ * `RATE_LIMIT_STREAK` in a row. A success clears it. `unreachable` and
1424
+ * `other` change nothing: the next save tries again.
1425
+ */
1426
+ function nextFailure(event, streak) {
1427
+ if (event.ok) return {
1428
+ failure: null,
1429
+ streak: 0
1430
+ };
1431
+ if (event.failure === "rate-limited") {
1432
+ const next = streak + 1;
1433
+ return {
1434
+ failure: next >= 3 ? "rate-limited" : void 0,
1435
+ streak: next
1436
+ };
1437
+ }
1438
+ if (event.failure === "out-of-credit" || event.failure === "key-rejected") return {
1439
+ failure: event.failure,
1440
+ streak: 0
1441
+ };
1442
+ return {
1443
+ failure: void 0,
1444
+ streak
1445
+ };
1446
+ }
1447
+ //#endregion
1053
1448
  //#region src/translate/settings.ts
1054
1449
  /** Settings → Translation: the switch, model, instructions and the key's public record. Versioned. */
1055
1450
  const TRANSLATION_SETTINGS_SLUG = "translation-settings";
@@ -1061,8 +1456,16 @@ const TRANSLATION_SETTINGS_SLUG = "translation-settings";
1061
1456
  const TRANSLATION_STATE_SLUG = "translation-state";
1062
1457
  /** The Roles grant that opens Settings → Translation. Developer and Admin always hold it. */
1063
1458
  const TRANSLATION_GRANT = "translation";
1459
+ /** The admin-wide month-to-date line and failure banner, for `translation` holders only. */
1460
+ const TRANSLATION_STATUS_BAR = "@bison-lab/payload-core/admin#TranslationStatusBar";
1461
+ /** Usage, jobs and the bulk buttons on Settings → Translation. */
1462
+ const TRANSLATION_ACTIVITY_PANEL = "@bison-lab/payload-core/admin#TranslationActivityPanel";
1064
1463
  /** The admin component for the key panel on Settings → Translation. */
1065
1464
  const TRANSLATION_KEY_PANEL = "@bison-lab/payload-core/admin#TranslationKeyPanel";
1465
+ /** "Español" for `es`: the library's label, else the code. */
1466
+ function localeLabel(code) {
1467
+ return LIBRARY_LOCALES.find((locale) => locale.code === code)?.label ?? code;
1468
+ }
1066
1469
  const MODEL_IDS = {
1067
1470
  quality: DEFAULT_TRANSLATE_MODEL,
1068
1471
  economy: ECONOMY_TRANSLATE_MODEL
@@ -1126,8 +1529,13 @@ function readTranslationSettings(payload, codeSite) {
1126
1529
  const [doc, state] = await Promise.all([readGlobal(payload, TRANSLATION_SETTINGS_SLUG), readGlobal(payload, TRANSLATION_STATE_SLUG)]);
1127
1530
  const saved = typeof doc.updatedAt === "string" && doc.updatedAt !== "";
1128
1531
  const site = saved ? siteFromInstructions(doc.instructions) : codeSite;
1532
+ const localization = payload.config?.localization;
1533
+ const targets = localization ? localization.locales.map((locale) => typeof locale === "string" ? locale : locale.code).filter((code) => code !== localization.defaultLocale) : [];
1534
+ const defaults = (payload.config?.custom)?.["bisonDefaultActiveLocales"] ?? targets;
1129
1535
  return {
1130
1536
  enabled: doc.enabled === true,
1537
+ monthlyCap: typeof doc.monthlyCap === "number" && doc.monthlyCap >= 0 ? doc.monthlyCap : null,
1538
+ languages: resolveActiveTargets(doc.languagesChosen ? doc.languages ?? [] : void 0, targets, defaults),
1131
1539
  model: doc.model === "economy" ? "economy" : "quality",
1132
1540
  ...site ? { site } : {},
1133
1541
  saved,
@@ -1172,21 +1580,69 @@ async function recordKeyOutcome(payload, settings, event) {
1172
1580
  });
1173
1581
  invalidateTranslationSettings(payload);
1174
1582
  }
1583
+ /** Writes a failure (or its clearing) and the rate-limit streak to the state Global, only when they change. */
1584
+ async function recordFailure(payload, state, outcome) {
1585
+ const failureChanged = outcome.failure !== void 0 && outcome.failure !== (state.failure ?? null);
1586
+ const streakChanged = outcome.streak !== (state.rateLimitStreak ?? 0);
1587
+ if (!failureChanged && !streakChanged) return;
1588
+ await payload.updateGlobal({
1589
+ slug: TRANSLATION_STATE_SLUG,
1590
+ data: {
1591
+ rateLimitStreak: outcome.streak,
1592
+ ...failureChanged ? {
1593
+ failure: outcome.failure,
1594
+ failureAt: outcome.failure ? (/* @__PURE__ */ new Date()).toISOString() : null
1595
+ } : {}
1596
+ },
1597
+ overrideAccess: true,
1598
+ context: { autoTranslate: false }
1599
+ });
1600
+ state.failure = outcome.failure === void 0 ? state.failure : outcome.failure;
1601
+ state.rateLimitStreak = outcome.streak;
1602
+ invalidateTranslationSettings(payload);
1603
+ }
1604
+ /** The advice the banner shows for the recorded failure, or `null`. */
1605
+ function failureAdvice(state) {
1606
+ return state.failure ? FAILURE_ADVICE[state.failure] : null;
1607
+ }
1175
1608
  /**
1176
1609
  * The translator Settings → Translation describes: its key (see
1177
1610
  * `resolveApiKey`), its model and its instructions. `configured: false`
1178
1611
  * when there is no key to use here.
1612
+ *
1613
+ * Every call is counted toward this month's usage, and its failure (out
1614
+ * of credit, a rejected key, persistent rate limits) is recorded for the
1615
+ * banner; a success clears it. With a monthly cap, a call that would start
1616
+ * once the month's estimated cost has reached it is not made: it records
1617
+ * `cap-reached` and returns no result, so the save goes on untranslated.
1179
1618
  */
1180
1619
  function settingsTranslator(payload, settings, seam = {}) {
1181
1620
  const key = keyFor(payload, settings);
1182
1621
  const production = key.source === "admin" || process.env.VERCEL_ENV === "production";
1183
- return anthropicTranslator({
1622
+ const inner = anthropicTranslator({
1184
1623
  apiKey: key.apiKey ?? null,
1185
1624
  ...seam.client && key.apiKey ? { client: seam.client } : {},
1186
1625
  model: resolveModel(settings.model, production),
1187
1626
  ...settings.site ? { site: settings.site } : {},
1188
- onCall: (event) => key.source === "admin" ? recordKeyOutcome(payload, settings, event) : void 0
1627
+ onCall: async (event) => {
1628
+ if (key.source === "admin") await recordKeyOutcome(payload, settings, event);
1629
+ if (event.ok) await recordUsage(payload, event);
1630
+ await recordFailure(payload, settings.state, nextFailure(event, settings.state.rateLimitStreak ?? 0));
1631
+ }
1189
1632
  });
1633
+ const capped = async (strings, request) => {
1634
+ if (settings.monthlyCap !== null && strings.length > 0) {
1635
+ if ((await usageThisMonth(payload)).cost >= settings.monthlyCap) {
1636
+ await recordFailure(payload, settings.state, {
1637
+ failure: "cap-reached",
1638
+ streak: settings.state.rateLimitStreak ?? 0
1639
+ });
1640
+ return null;
1641
+ }
1642
+ }
1643
+ return inner(strings, request);
1644
+ };
1645
+ return Object.assign(capped, { configured: inner.configured });
1190
1646
  }
1191
1647
  const FROZEN_WORDS_DESCRIPTION = "Kept exactly as written in every language. Matching is whole-word and case-sensitive: \"ProtectIQ\" does not match \"protectiq\".";
1192
1648
  const OUT_OF_CREDIT_MESSAGE = "The Anthropic account behind this key is out of credit, so translation cannot be switched on. Add credit, press Check again, then switch it on.";
@@ -1201,12 +1657,17 @@ const refuseOutOfCredit = async ({ data, originalDoc, req }) => {
1201
1657
  if (state.keyCipher && state.keyStatus === "out-of-credit") throw new APIError(OUT_OF_CREDIT_MESSAGE, 400);
1202
1658
  return data;
1203
1659
  };
1204
- /** Who made each save, so every version in the history names them. Set by the server, never by the form. */
1660
+ /**
1661
+ * Who made each save, so every version in the history names them, and
1662
+ * whether the language ticks have been chosen. Set by the server, never by
1663
+ * the form.
1664
+ */
1205
1665
  const stampChangedBy = ({ data, req }) => {
1206
1666
  if (!data) return data;
1207
1667
  return {
1208
1668
  ...data,
1209
- changedBy: who(req.user)
1669
+ changedBy: who(req.user),
1670
+ ...Array.isArray(data.languages) ? { languagesChosen: true } : {}
1210
1671
  };
1211
1672
  };
1212
1673
  /** A name for the user on a request: their name, else email, else id. */
@@ -1218,8 +1679,25 @@ function who(user) {
1218
1679
  }
1219
1680
  /** Fields only the server writes: the form and the REST API cannot change them. */
1220
1681
  const serverOnly = { update: () => false };
1682
+ /**
1683
+ * A raised or cleared cap clears a recorded `cap-reached`, so the banner
1684
+ * goes and paused jobs can resume, without waiting for a call to succeed.
1685
+ */
1686
+ const clearCapFailure = async ({ doc, req }) => {
1687
+ const state = await readGlobal(req.payload, TRANSLATION_STATE_SLUG);
1688
+ if (state.failure !== "cap-reached") return doc;
1689
+ const cap = doc.monthlyCap;
1690
+ const spent = (await usageThisMonth(req.payload)).cost;
1691
+ if (typeof cap === "number" && cap >= 0 && spent >= cap) return doc;
1692
+ await recordFailure(req.payload, state, {
1693
+ failure: null,
1694
+ streak: state.rateLimitStreak ?? 0
1695
+ });
1696
+ return doc;
1697
+ };
1221
1698
  const clearCache = ({ doc, req }) => {
1222
1699
  invalidateTranslationSettings(req.payload);
1700
+ invalidateActiveLocales(req.payload);
1223
1701
  return doc;
1224
1702
  };
1225
1703
  function instructionFields(options) {
@@ -1266,7 +1744,7 @@ function instructionFields(options) {
1266
1744
  required: true,
1267
1745
  enumName: "enum_translation_dialect_locale",
1268
1746
  options: options.targetLocales.map((code) => ({
1269
- label: code,
1747
+ label: localeLabel(code),
1270
1748
  value: code
1271
1749
  }))
1272
1750
  }, {
@@ -1320,7 +1798,7 @@ function translationSettingsGlobal(options) {
1320
1798
  versions: { max: 100 },
1321
1799
  hooks: {
1322
1800
  beforeChange: [refuseOutOfCredit, stampChangedBy],
1323
- afterChange: [clearCache]
1801
+ afterChange: [clearCache, clearCapFailure]
1324
1802
  },
1325
1803
  fields: [
1326
1804
  {
@@ -1328,6 +1806,11 @@ function translationSettingsGlobal(options) {
1328
1806
  type: "ui",
1329
1807
  admin: { components: { Field: TRANSLATION_KEY_PANEL } }
1330
1808
  },
1809
+ {
1810
+ name: "activityPanel",
1811
+ type: "ui",
1812
+ admin: { components: { Field: TRANSLATION_ACTIVITY_PANEL } }
1813
+ },
1331
1814
  {
1332
1815
  name: "enabled",
1333
1816
  type: "checkbox",
@@ -1335,6 +1818,26 @@ function translationSettingsGlobal(options) {
1335
1818
  defaultValue: false,
1336
1819
  admin: { description: "On: blank translations fill when copy is saved or published, and changed copy is re-translated on publish. Off: nothing translates; the key and existing translations are kept." }
1337
1820
  },
1821
+ {
1822
+ name: "languages",
1823
+ type: "select",
1824
+ label: "Translate into",
1825
+ hasMany: true,
1826
+ defaultValue: [...options.defaultActive ?? []],
1827
+ options: options.targetLocales.map((code) => ({
1828
+ label: localeLabel(code),
1829
+ value: code
1830
+ })),
1831
+ hooks: { afterRead: [({ value, siblingData }) => siblingData?.languagesChosen ? value : [...options.defaultActive ?? []]] },
1832
+ admin: { description: "Only ticked languages are translated and served. An unticked language costs nothing and has no pages: its URLs redirect to English." }
1833
+ },
1834
+ {
1835
+ name: "monthlyCap",
1836
+ type: "number",
1837
+ label: "Monthly spending cap (USD)",
1838
+ min: 0,
1839
+ admin: { description: "Blank: no cap. When this month's estimated cost reaches it, translation pauses until next month and translation managers see a banner." }
1840
+ },
1338
1841
  {
1339
1842
  name: "model",
1340
1843
  type: "radio",
@@ -1365,6 +1868,12 @@ function translationSettingsGlobal(options) {
1365
1868
  description: "Who made this save. Each version in the history keeps it."
1366
1869
  }
1367
1870
  },
1871
+ {
1872
+ name: "languagesChosen",
1873
+ type: "checkbox",
1874
+ access: serverOnly,
1875
+ admin: { hidden: true }
1876
+ },
1368
1877
  {
1369
1878
  name: "keyLast4",
1370
1879
  type: "text",
@@ -1422,6 +1931,25 @@ function translationStateGlobal() {
1422
1931
  {
1423
1932
  name: "keyCheckedAt",
1424
1933
  type: "date"
1934
+ },
1935
+ {
1936
+ name: "failure",
1937
+ type: "select",
1938
+ options: [
1939
+ "out-of-credit",
1940
+ "key-rejected",
1941
+ "rate-limited",
1942
+ "cap-reached"
1943
+ ]
1944
+ },
1945
+ {
1946
+ name: "failureAt",
1947
+ type: "date"
1948
+ },
1949
+ {
1950
+ name: "rateLimitStreak",
1951
+ type: "number",
1952
+ defaultValue: 0
1425
1953
  }
1426
1954
  ]
1427
1955
  };
@@ -1527,12 +2055,12 @@ async function translateDocument(payload, options) {
1527
2055
  if (!localization) throw new Error("translateDocument: the Payload config has no localization");
1528
2056
  const state = readState(payload.config);
1529
2057
  const given = options.translator ?? state?.translator;
1530
- const settings = given && options.site ? void 0 : await readTranslationSettings(payload, state?.site);
2058
+ const settings = given && options.site && options.locale !== void 0 ? void 0 : await readTranslationSettings(payload, state?.site);
1531
2059
  const translator = given ?? settingsTranslator(payload, settings);
1532
2060
  const kind = options.kind ?? "manual";
1533
2061
  const sourceLocale = localization.defaultLocale;
1534
2062
  const codes = localeCodes(localization);
1535
- const targets = options.locale === void 0 ? codes.filter((code) => code !== sourceLocale) : typeof options.locale === "string" ? [options.locale] : [...options.locale];
2063
+ const targets = options.locale === void 0 ? settings?.languages ?? codes.filter((code) => code !== sourceLocale) : typeof options.locale === "string" ? [options.locale] : [...options.locale];
1536
2064
  for (const locale of targets) if (locale === sourceLocale || !codes.includes(locale)) throw new Error(`translateDocument: "${locale}" is not a target locale`);
1537
2065
  const schema = schemaFor(payload, options);
1538
2066
  const { req, user } = options;
@@ -1582,7 +2110,8 @@ async function translateDocument(payload, options) {
1582
2110
  source: from,
1583
2111
  target,
1584
2112
  previous: options.previous,
1585
- overwrite: options.overwrite
2113
+ overwrite: options.overwrite,
2114
+ ...options.force ? { force: options.force } : {}
1586
2115
  });
1587
2116
  const results = [];
1588
2117
  for (const locale of targets) {
@@ -1784,12 +2313,13 @@ function translateNowEndpoint(slug) {
1784
2313
  if (!state) return Response.json({ error: "Translation is not set up on this site." }, { status: 503 });
1785
2314
  const settings = await readTranslationSettings(req.payload, state.site);
1786
2315
  if (!settings.enabled) return Response.json({ error: "Translation is switched off in Settings → Translation." }, { status: 409 });
2316
+ if (settings.languages.length === 0) return Response.json({ error: "No language is ticked in Settings → Translation." }, { status: 409 });
1787
2317
  const translator = state.translator ?? settingsTranslator(req.payload, settings);
1788
2318
  if (!isTranslatorConfigured(translator)) return Response.json({ error: "Translation has no API key here." }, { status: 503 });
1789
2319
  const id = req.routeParams?.id;
1790
2320
  if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Missing document id" }, { status: 400 });
1791
2321
  const locale = req.searchParams?.get("locale") || void 0;
1792
- if (locale !== void 0 && !state.targetLocales.includes(locale)) return Response.json({ error: `"${locale}" is not a locale this site translates into.` }, { status: 400 });
2322
+ if (locale !== void 0 && !settings.languages.includes(locale)) return Response.json({ error: `"${locale}" is not a locale this site translates into.` }, { status: 400 });
1793
2323
  if (!await canUpdate(req, slug, String(id))) return Response.json({ error: "You are not allowed to update this document." }, { status: 403 });
1794
2324
  let results;
1795
2325
  try {
@@ -1843,7 +2373,10 @@ function translationAvailableEndpoint() {
1843
2373
  if (!state) return Response.json({ available: false });
1844
2374
  const settings = await readTranslationSettings(req.payload, state.site);
1845
2375
  const translator = state.translator ?? settingsTranslator(req.payload, settings);
1846
- return Response.json({ available: settings.enabled && isTranslatorConfigured(translator) });
2376
+ return Response.json({
2377
+ available: settings.enabled && settings.languages.length > 0 && isTranslatorConfigured(translator),
2378
+ languages: settings.languages
2379
+ });
1847
2380
  }
1848
2381
  };
1849
2382
  }
@@ -2072,9 +2605,11 @@ async function afterSourceChange(args) {
2072
2605
  const { payload } = req;
2073
2606
  let previous;
2074
2607
  let translator;
2608
+ let targets;
2075
2609
  try {
2076
2610
  const settings = await readTranslationSettings(payload, state.site);
2077
- if (!settings.enabled) return {};
2611
+ if (!settings.enabled || settings.languages.length === 0) return {};
2612
+ targets = settings.languages;
2078
2613
  if (drafted && status === "draft") previous = null;
2079
2614
  else if (drafted) previous = (await draftedTranslationDecision({
2080
2615
  req,
@@ -2106,7 +2641,7 @@ async function afterSourceChange(args) {
2106
2641
  } : { global: slug },
2107
2642
  previous,
2108
2643
  translator,
2109
- locale: state.targetLocales,
2644
+ locale: targets,
2110
2645
  kind: "auto",
2111
2646
  ...user ? { user } : {}
2112
2647
  }));
@@ -2156,7 +2691,714 @@ function globalAutoTranslateHook(slug) {
2156
2691
  };
2157
2692
  }
2158
2693
  //#endregion
2694
+ //#region src/translate/jobs.ts
2695
+ /**
2696
+ * Background translation jobs: the backfill that starts when translation
2697
+ * is switched on (or a key is saved while it is on), "Fill all blank", and
2698
+ * "Apply frozen words to existing Spanish". A job is a row in a hidden
2699
+ * collection holding its queue of documents and a cursor, saved after every
2700
+ * document, so a job interrupted by a failure or a redeploy resumes where it
2701
+ * stopped and never redoes a finished document.
2702
+ *
2703
+ * A run processes documents for `RUN_BUDGET_MS`, then hands on to the next
2704
+ * run with a signed request to its own endpoint, so no single function
2705
+ * invocation runs long. A job whose last heartbeat is older than
2706
+ * `STALE_AFTER_MS` (its chain broke on a redeploy) is resumed on the next
2707
+ * cold start (`onInit`) or the next time the screen polls.
2708
+ */
2709
+ const TRANSLATION_JOBS_SLUG = "translation-jobs";
2710
+ const TRANSLATION_JOBS_TABLE = "translation_jobs";
2711
+ const RUN_BUDGET_MS = 25e3;
2712
+ /**
2713
+ * How long a claim lasts without renewal. Renewed before every document, so
2714
+ * it covers one document's model calls (90s, one retry) with room to spare;
2715
+ * a runner silent this long is gone, and the job may be claimed again.
2716
+ */
2717
+ const LEASE_MS = 3e5;
2718
+ function translationJobsCollection() {
2719
+ return {
2720
+ slug: TRANSLATION_JOBS_SLUG,
2721
+ dbName: TRANSLATION_JOBS_TABLE,
2722
+ labels: {
2723
+ singular: "Translation job",
2724
+ plural: "Translation jobs"
2725
+ },
2726
+ admin: { hidden: true },
2727
+ access: {
2728
+ read: () => false,
2729
+ create: () => false,
2730
+ update: () => false,
2731
+ delete: () => false
2732
+ },
2733
+ fields: [
2734
+ {
2735
+ name: "kind",
2736
+ type: "select",
2737
+ required: true,
2738
+ options: [
2739
+ "backfill",
2740
+ "fill-blank",
2741
+ "frozen-fix"
2742
+ ]
2743
+ },
2744
+ {
2745
+ name: "status",
2746
+ type: "select",
2747
+ required: true,
2748
+ index: true,
2749
+ options: [
2750
+ "running",
2751
+ "paused",
2752
+ "done",
2753
+ "failed"
2754
+ ]
2755
+ },
2756
+ {
2757
+ name: "queue",
2758
+ type: "json"
2759
+ },
2760
+ {
2761
+ name: "cursor",
2762
+ type: "number",
2763
+ defaultValue: 0
2764
+ },
2765
+ {
2766
+ name: "strings",
2767
+ type: "number",
2768
+ defaultValue: 0
2769
+ },
2770
+ {
2771
+ name: "translated",
2772
+ type: "number",
2773
+ defaultValue: 0
2774
+ },
2775
+ {
2776
+ name: "words",
2777
+ type: "json"
2778
+ },
2779
+ {
2780
+ name: "startedBy",
2781
+ type: "text"
2782
+ },
2783
+ {
2784
+ name: "origin",
2785
+ type: "text"
2786
+ },
2787
+ {
2788
+ name: "heartbeatAt",
2789
+ type: "date"
2790
+ },
2791
+ {
2792
+ name: "message",
2793
+ type: "text"
2794
+ },
2795
+ {
2796
+ name: "reason",
2797
+ type: "text"
2798
+ },
2799
+ {
2800
+ name: "skipped",
2801
+ type: "number",
2802
+ defaultValue: 0
2803
+ },
2804
+ {
2805
+ name: "lease",
2806
+ type: "text"
2807
+ },
2808
+ {
2809
+ name: "leaseUntil",
2810
+ type: "date"
2811
+ },
2812
+ {
2813
+ name: "leaseRev",
2814
+ type: "number",
2815
+ defaultValue: 0
2816
+ }
2817
+ ]
2818
+ };
2819
+ }
2820
+ /** Rough tokens per string, and per call, for an estimate before a bulk job. */
2821
+ const TOKENS_IN_PER_STRING = 40;
2822
+ const TOKENS_OUT_PER_STRING = 40;
2823
+ const TOKENS_PER_CALL = 600;
2824
+ function schemaOf(payload, target) {
2825
+ if ("collection" in target) {
2826
+ const config = payload.collections[target.collection].config;
2827
+ const versions = config.versions;
2828
+ return {
2829
+ fields: config.fields,
2830
+ blocks: payload.config.blocks,
2831
+ drafts: Boolean(versions && typeof versions === "object" && versions.drafts)
2832
+ };
2833
+ }
2834
+ const global = payload.config.globals.find((entry) => entry.slug === target.global);
2835
+ const versions = global.versions;
2836
+ return {
2837
+ fields: global.fields,
2838
+ blocks: payload.config.blocks,
2839
+ drafts: Boolean(versions && typeof versions === "object" && versions.drafts)
2840
+ };
2841
+ }
2842
+ async function readLatest(payload, target, locale, drafts, target2 = false) {
2843
+ const common = {
2844
+ locale,
2845
+ depth: 0,
2846
+ overrideAccess: true,
2847
+ ...drafts ? { draft: true } : {},
2848
+ ...target2 ? { fallbackLocale: false } : {}
2849
+ };
2850
+ return "collection" in target ? await payload.findByID({
2851
+ collection: target.collection,
2852
+ id: target.id,
2853
+ ...common
2854
+ }) : await payload.findGlobal({
2855
+ slug: target.global,
2856
+ ...common
2857
+ });
2858
+ }
2859
+ /** Strings in the frozen-word fix: English keeps a frozen word (whole word, case-sensitive) and the translation lost it. */
2860
+ function frozenWordForce(words) {
2861
+ return (source, existing) => words.some((word) => containsWord(source, word) && !(typeof existing === "string" && containsWord(existing, word)));
2862
+ }
2863
+ async function allTargets(payload) {
2864
+ const state = readState(payload.config);
2865
+ if (!state) return [];
2866
+ const out = [];
2867
+ for (const slug of Object.keys(state.collections)) {
2868
+ let page = 1;
2869
+ for (;;) {
2870
+ const result = await payload.find({
2871
+ collection: slug,
2872
+ depth: 0,
2873
+ limit: 100,
2874
+ page,
2875
+ sort: "id",
2876
+ overrideAccess: true,
2877
+ select: { id: true },
2878
+ draft: true
2879
+ });
2880
+ for (const doc of result.docs) out.push({
2881
+ collection: slug,
2882
+ id: doc.id
2883
+ });
2884
+ if (!result.hasNextPage) break;
2885
+ page += 1;
2886
+ }
2887
+ }
2888
+ for (const slug of Object.keys(state.globals)) out.push({ global: slug });
2889
+ return out;
2890
+ }
2891
+ /**
2892
+ * Counts what a job would translate, reading each document's latest version
2893
+ * (the published copy, or the current draft when there is one) in every
2894
+ * ticked language. Changes nothing.
2895
+ */
2896
+ async function estimateJob(payload, settings, kind, words = []) {
2897
+ const state = readState(payload.config);
2898
+ const source = payload.config.localization ? payload.config.localization.defaultLocale : "en";
2899
+ const lost = /* @__PURE__ */ new Set();
2900
+ const force = kind === "frozen-fix" ? (source, existing) => {
2901
+ const missing = words.filter((word) => containsWord(source, word) && !(typeof existing === "string" && containsWord(existing, word)));
2902
+ missing.forEach((word) => lost.add(word));
2903
+ return missing.length > 0;
2904
+ } : void 0;
2905
+ let strings = 0;
2906
+ let calls = 0;
2907
+ const queue = [];
2908
+ if (!state || settings.languages.length === 0 || kind === "frozen-fix" && words.length === 0) return {
2909
+ documents: 0,
2910
+ strings: 0,
2911
+ cost: 0,
2912
+ queue,
2913
+ lostWords: []
2914
+ };
2915
+ for (const target of await allTargets(payload)) {
2916
+ const schema = schemaOf(payload, target);
2917
+ let from;
2918
+ try {
2919
+ from = await readLatest(payload, target, source, schema.drafts);
2920
+ } catch {
2921
+ continue;
2922
+ }
2923
+ let count = 0;
2924
+ for (const locale of settings.languages) {
2925
+ const into = await readLatest(payload, target, locale, schema.drafts, true);
2926
+ const job = translationJob({
2927
+ schema,
2928
+ source: from,
2929
+ target: into,
2930
+ ...force ? { force } : {}
2931
+ });
2932
+ if (job) {
2933
+ count += job.sources.length;
2934
+ calls += 1;
2935
+ }
2936
+ }
2937
+ if (count > 0) {
2938
+ queue.push(target);
2939
+ strings += count;
2940
+ }
2941
+ }
2942
+ const cost = estimateCost(resolveModel(settings.model, process.env.VERCEL_ENV === "production"), strings * TOKENS_IN_PER_STRING + calls * TOKENS_PER_CALL, strings * TOKENS_OUT_PER_STRING);
2943
+ return {
2944
+ documents: queue.length,
2945
+ strings,
2946
+ cost,
2947
+ queue,
2948
+ lostWords: words.filter((word) => lost.has(word))
2949
+ };
2950
+ }
2951
+ /** The hand-on signature: the job and the lease it carries, so a captured header cannot restart another runner. */
2952
+ function sign(secret, id, lease) {
2953
+ return createHmac("sha256", `bison-translation-job:${secret}`).update(`${id}:${lease}`).digest("hex");
2954
+ }
2955
+ function verifySignature(secret, id, lease, signature) {
2956
+ if (!signature || !lease) return false;
2957
+ const expected = Buffer.from(sign(secret, id, lease));
2958
+ const given = Buffer.from(signature);
2959
+ return expected.length === given.length && timingSafeEqual(expected, given);
2960
+ }
2961
+ async function loadJob(payload, id) {
2962
+ try {
2963
+ return await payload.findByID({
2964
+ collection: TRANSLATION_JOBS_SLUG,
2965
+ id,
2966
+ depth: 0,
2967
+ overrideAccess: true
2968
+ });
2969
+ } catch {
2970
+ return null;
2971
+ }
2972
+ }
2973
+ async function saveJob(payload, id, data) {
2974
+ await payload.update({
2975
+ collection: TRANSLATION_JOBS_SLUG,
2976
+ id,
2977
+ data,
2978
+ overrideAccess: true,
2979
+ context: { autoTranslate: false }
2980
+ });
2981
+ }
2982
+ /**
2983
+ * Writes `data` only if `where` still matches the job (a compare-and-set
2984
+ * through Payload's update-by-where). True when it did.
2985
+ */
2986
+ async function saveJobIf(payload, id, where, data) {
2987
+ return compareAndSet(payload, {
2988
+ collection: TRANSLATION_JOBS_SLUG,
2989
+ table: TRANSLATION_JOBS_TABLE,
2990
+ id,
2991
+ guard: Object.fromEntries(Object.entries(where).map(([field, clause]) => [field, clause.equals])),
2992
+ set: data
2993
+ });
2994
+ }
2995
+ const leaseUntil = () => new Date(Date.now() + LEASE_MS).toISOString();
2996
+ /**
2997
+ * Takes the job for `lease` if it is running and nobody else holds a live
2998
+ * claim. The claim is a compare-and-set on `leaseRev`, so of two runners
2999
+ * reading the same job only one can win.
3000
+ */
3001
+ async function claimJob(payload, id, lease) {
3002
+ const job = await loadJob(payload, id);
3003
+ if (!job || job.status !== "running") return false;
3004
+ if (job.lease === lease) return true;
3005
+ if (job.lease && job.leaseUntil && Date.parse(job.leaseUntil) > Date.now()) return false;
3006
+ return saveJobIf(payload, id, { leaseRev: { equals: job.leaseRev ?? null } }, {
3007
+ lease,
3008
+ leaseUntil: leaseUntil(),
3009
+ leaseRev: (job.leaseRev ?? 0) + 1,
3010
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
3011
+ });
3012
+ }
3013
+ /** "Stopped at 40 of 85", from the cursor as it is now. */
3014
+ function stoppedAt(job) {
3015
+ return `Stopped at ${job.cursor} of ${Array.isArray(job.queue) ? job.queue.length : 0}`;
3016
+ }
3017
+ /** A recorded failure that pauses a job: the next call would fail the same way. */
3018
+ const STOPPING_FAILURES = new Set([
3019
+ "out-of-credit",
3020
+ "key-rejected",
3021
+ "cap-reached"
3022
+ ]);
3023
+ /**
3024
+ * Runs one job for up to `budgetMs` while holding `lease`: one document at
3025
+ * a time. Before each document it renews the lease (and stops if another
3026
+ * runner has it), re-reads the job (stops if it was paused) and the switch
3027
+ * (pauses if it is off). A document's write and the cursor after it are
3028
+ * made only while the lease is still this runner's. When a document's
3029
+ * translation records a stopping failure (out of credit, a rejected key,
3030
+ * the cap) the job pauses on that document, which is not counted done, and
3031
+ * Resume picks it up after the Admin has fixed the cause. A document that
3032
+ * fails for any other reason is skipped and counted. Returns `true` when
3033
+ * work is left and the lease is still held, so the caller hands on.
3034
+ */
3035
+ async function runJobSlice(payload, id, lease, budgetMs = RUN_BUDGET_MS) {
3036
+ const deadline = Date.now() + budgetMs;
3037
+ const state = readState(payload.config);
3038
+ if (!await claimJob(payload, id, lease)) return false;
3039
+ for (;;) {
3040
+ const job = await loadJob(payload, id);
3041
+ if (!job || job.status !== "running" || job.lease !== lease) return false;
3042
+ const queue = Array.isArray(job.queue) ? job.queue : [];
3043
+ if (job.cursor >= queue.length) {
3044
+ const skipped = job.skipped ?? 0;
3045
+ await saveJobIf(payload, id, { lease: { equals: lease } }, {
3046
+ status: "done",
3047
+ lease: null,
3048
+ message: `Translated ${job.translated} string(s) on ${queue.length} document(s)${skipped ? `; ${skipped} document(s) failed and were skipped (Fill all blank picks them up)` : ""}`
3049
+ });
3050
+ return false;
3051
+ }
3052
+ invalidateTranslationSettings(payload);
3053
+ const settings = await readTranslationSettings(payload, state?.site);
3054
+ if (!settings.enabled) {
3055
+ await saveJobIf(payload, id, { lease: { equals: lease } }, {
3056
+ status: "paused",
3057
+ lease: null,
3058
+ reason: null
3059
+ });
3060
+ return false;
3061
+ }
3062
+ if (Date.now() >= deadline) return true;
3063
+ if (!await saveJobIf(payload, id, { lease: { equals: lease } }, {
3064
+ leaseUntil: leaseUntil(),
3065
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
3066
+ })) return false;
3067
+ const target = queue[job.cursor];
3068
+ let count = 0;
3069
+ let failed = false;
3070
+ try {
3071
+ const results = await translateDocument(payload, {
3072
+ ...target,
3073
+ locale: settings.languages,
3074
+ kind: job.kind === "frozen-fix" ? "frozen-fix" : "backfill",
3075
+ ...job.kind === "frozen-fix" ? { force: frozenWordForce(job.words ?? []) } : {}
3076
+ });
3077
+ count = results.reduce((sum, result) => sum + result.count, 0);
3078
+ failed = results.some((result) => result.status === "failed");
3079
+ } catch (error) {
3080
+ failed = true;
3081
+ payload.logger.warn({ err: error }, `translation job ${String(id)}: a document failed`);
3082
+ }
3083
+ if (failed) {
3084
+ invalidateTranslationSettings(payload);
3085
+ const failure = (await readTranslationSettings(payload, state?.site)).state.failure;
3086
+ if (failure && STOPPING_FAILURES.has(failure)) {
3087
+ await saveJobIf(payload, id, { lease: { equals: lease } }, {
3088
+ status: "paused",
3089
+ lease: null,
3090
+ reason: failure
3091
+ });
3092
+ return false;
3093
+ }
3094
+ }
3095
+ if (!await saveJobIf(payload, id, { lease: { equals: lease } }, {
3096
+ cursor: job.cursor + 1,
3097
+ translated: (job.translated ?? 0) + count,
3098
+ skipped: (job.skipped ?? 0) + (failed ? 1 : 0),
3099
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
3100
+ })) return false;
3101
+ }
3102
+ }
3103
+ /** The URL a run hands on to: the job's origin plus the API route. */
3104
+ function runUrl(payload, origin) {
3105
+ const api = payload.config.routes?.api ?? "/api";
3106
+ return `${origin.replace(/\/$/, "")}${api}/translation/jobs/run`;
3107
+ }
3108
+ /**
3109
+ * Runs a slice now under `lease` (kept alive with `waitUntil`) and, if
3110
+ * work is left, swaps in a fresh lease and hands that on to a fresh
3111
+ * invocation with a signed POST to `/api/translation/jobs/run`. Without an
3112
+ * origin the next slice runs in this process instead. A new chain passes no
3113
+ * lease and gets a fresh one, which it must win from any other claimant.
3114
+ */
3115
+ function continueJob(payload, id, initialLease = randomUUID()) {
3116
+ let lease = initialLease;
3117
+ const state = readState(payload.config);
3118
+ const work = (async () => {
3119
+ if (!await runJobSlice(payload, id, lease)) return;
3120
+ const next = randomUUID();
3121
+ if (!await saveJobIf(payload, id, { lease: { equals: lease } }, {
3122
+ lease: next,
3123
+ leaseUntil: leaseUntil()
3124
+ })) return;
3125
+ lease = next;
3126
+ const origin = (await loadJob(payload, id))?.origin || payload.config.serverURL || "";
3127
+ if (!origin) {
3128
+ await continueJob(payload, id, lease);
3129
+ return;
3130
+ }
3131
+ try {
3132
+ await fetch(runUrl(payload, origin), {
3133
+ method: "POST",
3134
+ headers: {
3135
+ "Content-Type": "application/json",
3136
+ "x-bison-translation-job": sign(payload.secret, String(id), lease)
3137
+ },
3138
+ body: JSON.stringify({
3139
+ id,
3140
+ lease
3141
+ })
3142
+ });
3143
+ } catch (error) {
3144
+ payload.logger.warn({ err: error }, `translation job ${String(id)}: hand-on failed; it resumes when the claim lapses`);
3145
+ }
3146
+ })().catch((error) => {
3147
+ payload.logger.error({ err: error }, `translation job ${String(id)} failed`);
3148
+ });
3149
+ (state?.waitUntil ?? vercelWaitUntil())?.(work);
3150
+ return work;
3151
+ }
3152
+ /**
3153
+ * Restarts running jobs whose runner is gone (its claim lapsed, e.g. a
3154
+ * redeploy broke the chain). Safe to call from every poll and every cold
3155
+ * start: a fresh runner must win the claim, so at most one picks a job up.
3156
+ */
3157
+ async function resumeStaleJobs(payload) {
3158
+ let docs;
3159
+ try {
3160
+ docs = (await payload.find({
3161
+ collection: TRANSLATION_JOBS_SLUG,
3162
+ where: { status: { equals: "running" } },
3163
+ depth: 0,
3164
+ limit: 10,
3165
+ overrideAccess: true
3166
+ })).docs;
3167
+ } catch {
3168
+ return 0;
3169
+ }
3170
+ let resumed = 0;
3171
+ for (const job of docs) {
3172
+ if (job.lease && job.leaseUntil && Date.parse(job.leaseUntil) > Date.now()) continue;
3173
+ const lease = randomUUID();
3174
+ if (!await claimJob(payload, job.id, lease)) continue;
3175
+ continueJob(payload, job.id, lease);
3176
+ resumed += 1;
3177
+ }
3178
+ return resumed;
3179
+ }
3180
+ function originOf(req) {
3181
+ try {
3182
+ if (req?.url) return new URL(req.url).origin;
3183
+ } catch {}
3184
+ const host = req?.headers?.get?.("host");
3185
+ if (!host) return null;
3186
+ return `${req?.headers?.get?.("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https")}://${host}`;
3187
+ }
3188
+ /** The newest jobs, newest first. */
3189
+ async function latestJobs(payload, limit = 5) {
3190
+ try {
3191
+ return (await payload.find({
3192
+ collection: TRANSLATION_JOBS_SLUG,
3193
+ sort: "-createdAt",
3194
+ depth: 0,
3195
+ limit,
3196
+ overrideAccess: true
3197
+ })).docs;
3198
+ } catch {
3199
+ return [];
3200
+ }
3201
+ }
3202
+ /**
3203
+ * Creates a job from an estimate and starts it. Single-flight: a job
3204
+ * already running is returned instead, and if two starts race (switch-on
3205
+ * and a key save, two Admins), the newer one stands down for the older.
3206
+ */
3207
+ async function startJob(payload, input) {
3208
+ const running = (await latestJobs(payload, 10)).find((job) => job.status === "running");
3209
+ if (running) return running;
3210
+ const created = await payload.create({
3211
+ collection: TRANSLATION_JOBS_SLUG,
3212
+ data: {
3213
+ kind: input.kind,
3214
+ status: input.estimate.queue.length ? "running" : "done",
3215
+ queue: input.estimate.queue,
3216
+ cursor: 0,
3217
+ strings: input.estimate.strings,
3218
+ translated: 0,
3219
+ skipped: 0,
3220
+ leaseRev: 0,
3221
+ ...input.words ? { words: [...input.words] } : {},
3222
+ startedBy: who(input.user),
3223
+ origin: originOf(input.req),
3224
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString(),
3225
+ message: input.estimate.queue.length ? null : "Nothing to translate."
3226
+ },
3227
+ overrideAccess: true,
3228
+ context: { autoTranslate: false }
3229
+ });
3230
+ if (created.status !== "running") return created;
3231
+ const first = (await latestJobs(payload, 10)).filter((job) => job.status === "running").sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)) || String(a.id).localeCompare(String(b.id)))[0];
3232
+ if (first && String(first.id) !== String(created.id)) {
3233
+ await saveJob(payload, created.id, {
3234
+ status: "done",
3235
+ message: "Another job was already running."
3236
+ });
3237
+ return first;
3238
+ }
3239
+ continueJob(payload, created.id);
3240
+ return created;
3241
+ }
3242
+ /** Pauses every running job; its runner stops after the current document. */
3243
+ async function pauseRunningJobs(payload) {
3244
+ for (const job of await latestJobs(payload, 10)) if (job.status === "running") await saveJob(payload, job.id, {
3245
+ status: "paused",
3246
+ lease: null,
3247
+ reason: null
3248
+ });
3249
+ }
3250
+ /**
3251
+ * The backfill when translation is switched on or a key is saved while it
3252
+ * is on: unless a paused job is waiting to be resumed (the screen offers
3253
+ * that instead), estimate every blank string and start filling it.
3254
+ */
3255
+ async function startBackfill(payload, input = {}) {
3256
+ if ((await latestJobs(payload, 10)).some((job) => job.status === "running" || job.status === "paused")) return null;
3257
+ const settings = await readTranslationSettings(payload, readState(payload.config)?.site);
3258
+ if (!settings.enabled) return null;
3259
+ return startJob(payload, {
3260
+ kind: "backfill",
3261
+ estimate: await estimateJob(payload, settings, "backfill"),
3262
+ ...input
3263
+ });
3264
+ }
3265
+ async function allowed$1(req) {
3266
+ if (!req.user) return false;
3267
+ return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));
3268
+ }
3269
+ async function body(req) {
3270
+ try {
3271
+ const value = await req.json?.();
3272
+ return value && typeof value === "object" ? value : {};
3273
+ } catch {
3274
+ return {};
3275
+ }
3276
+ }
3277
+ function frozenWords(settings) {
3278
+ return settings.site?.keepVerbatim ?? [];
3279
+ }
3280
+ /** Public shape of a job for the screen. */
3281
+ function jobView(job) {
3282
+ const advice = job.reason ? failureAdvice({ failure: job.reason }) : null;
3283
+ const message = job.status === "paused" ? `${stoppedAt(job)}${advice ? `. ${advice}` : ""}` : job.message ?? null;
3284
+ return {
3285
+ id: job.id,
3286
+ kind: job.kind,
3287
+ status: job.status,
3288
+ done: job.cursor,
3289
+ total: Array.isArray(job.queue) ? job.queue.length : 0,
3290
+ strings: job.strings,
3291
+ translated: job.translated,
3292
+ skipped: job.skipped ?? 0,
3293
+ startedBy: job.startedBy ?? null,
3294
+ message,
3295
+ createdAt: job.createdAt ?? null
3296
+ };
3297
+ }
3298
+ /**
3299
+ * The job endpoints, behind the `translation` grant except `run`, which
3300
+ * takes only a request signed with `PAYLOAD_SECRET`:
3301
+ *
3302
+ * - `GET /api/translation/jobs`: the latest jobs (and resumes a stale one).
3303
+ * - `POST /api/translation/jobs/estimate` `{ kind }`: what a job would do; changes nothing.
3304
+ * - `POST /api/translation/jobs` `{ kind }`: estimates and starts it.
3305
+ * - `POST /api/translation/jobs/resume` `{ id }`: resumes a paused job.
3306
+ * - `POST /api/translation/jobs/run` `{ id }`: one slice, then the hand-on.
3307
+ */
3308
+ function translationJobEndpoints() {
3309
+ return [
3310
+ {
3311
+ path: "/translation/jobs",
3312
+ method: "get",
3313
+ handler: async (req) => {
3314
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3315
+ await resumeStaleJobs(req.payload);
3316
+ return Response.json({ jobs: (await latestJobs(req.payload)).map(jobView) });
3317
+ }
3318
+ },
3319
+ {
3320
+ path: "/translation/jobs/estimate",
3321
+ method: "post",
3322
+ handler: async (req) => {
3323
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3324
+ const kind = (await body(req)).kind;
3325
+ if (kind !== "fill-blank" && kind !== "frozen-fix") return Response.json({ error: "Unknown job." }, { status: 400 });
3326
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
3327
+ const words = frozenWords(settings);
3328
+ const estimate = await estimateJob(req.payload, settings, kind, words);
3329
+ return Response.json({
3330
+ documents: estimate.documents,
3331
+ strings: estimate.strings,
3332
+ cost: estimate.cost,
3333
+ words: estimate.lostWords
3334
+ });
3335
+ }
3336
+ },
3337
+ {
3338
+ path: "/translation/jobs",
3339
+ method: "post",
3340
+ handler: async (req) => {
3341
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3342
+ const kind = (await body(req)).kind;
3343
+ if (kind !== "fill-blank" && kind !== "frozen-fix") return Response.json({ error: "Unknown job." }, { status: 400 });
3344
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
3345
+ if (!settings.enabled) return Response.json({ error: "Switch translation on first." }, { status: 409 });
3346
+ const words = frozenWords(settings);
3347
+ const estimate = await estimateJob(req.payload, settings, kind, words);
3348
+ const job = await startJob(req.payload, {
3349
+ kind,
3350
+ estimate,
3351
+ words,
3352
+ user: req.user,
3353
+ req
3354
+ });
3355
+ return Response.json({ job: jobView(job) });
3356
+ }
3357
+ },
3358
+ {
3359
+ path: "/translation/jobs/resume",
3360
+ method: "post",
3361
+ handler: async (req) => {
3362
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3363
+ const id = (await body(req)).id;
3364
+ if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Which job?" }, { status: 400 });
3365
+ if (!(await readTranslationSettings(req.payload, readState(req.payload.config)?.site)).enabled) return Response.json({ error: "Switch translation on first." }, { status: 409 });
3366
+ const job = await loadJob(req.payload, id);
3367
+ if (!job || job.status !== "paused") return Response.json({ error: "That job is not paused." }, { status: 409 });
3368
+ await saveJob(req.payload, id, {
3369
+ status: "running",
3370
+ message: null,
3371
+ reason: null,
3372
+ lease: null,
3373
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString(),
3374
+ origin: job.origin ?? originOf(req)
3375
+ });
3376
+ continueJob(req.payload, id);
3377
+ return Response.json({ job: jobView({
3378
+ ...job,
3379
+ status: "running"
3380
+ }) });
3381
+ }
3382
+ },
3383
+ {
3384
+ path: "/translation/jobs/run",
3385
+ method: "post",
3386
+ handler: async (req) => {
3387
+ const { id, lease } = await body(req);
3388
+ if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Which job?" }, { status: 400 });
3389
+ if (typeof lease !== "string" || !verifySignature(req.payload.secret, String(id), lease, req.headers.get("x-bison-translation-job"))) return Response.json({ error: "Forbidden" }, { status: 403 });
3390
+ continueJob(req.payload, id, lease);
3391
+ return Response.json({ ok: true }, { status: 202 });
3392
+ }
3393
+ }
3394
+ ];
3395
+ }
3396
+ //#endregion
2159
3397
  //#region src/translate/settings-endpoints.ts
3398
+ /** Failures a working key settles. */
3399
+ function keyFailure(failure) {
3400
+ return failure === "out-of-credit" || failure === "key-rejected";
3401
+ }
2160
3402
  async function allowed(req) {
2161
3403
  if (!req.user) return false;
2162
3404
  return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));
@@ -2182,9 +3424,23 @@ async function status(req) {
2182
3424
  source: key.source,
2183
3425
  last4: key.last4
2184
3426
  } : null,
2185
- ...key.note ? { note: key.note } : {}
3427
+ ...key.note ? { note: key.note } : {},
3428
+ usage: {
3429
+ month: await usageThisMonth(req.payload),
3430
+ history: await usageHistory(req.payload),
3431
+ cap: settings.monthlyCap
3432
+ },
3433
+ failure: failureOf(settings.state)
2186
3434
  };
2187
3435
  }
3436
+ function failureOf(state) {
3437
+ const advice = failureAdvice(state);
3438
+ return state.failure && advice ? {
3439
+ kind: state.failure,
3440
+ at: state.failureAt ?? null,
3441
+ advice
3442
+ } : null;
3443
+ }
2188
3444
  const STATUS_BY_CHECK = {
2189
3445
  valid: "valid",
2190
3446
  "out-of-credit": "out-of-credit",
@@ -2257,7 +3513,11 @@ function translationSettingsEndpoints(options = {}) {
2257
3513
  await writeState(req, {
2258
3514
  keyCipher: encryptApiKey(key, req.payload.secret),
2259
3515
  keyStatus: STATUS_BY_CHECK[check],
2260
- keyCheckedAt: check === "unreachable" ? null : now
3516
+ keyCheckedAt: check === "unreachable" ? null : now,
3517
+ ...keyFailure(before.state.failure) && check !== "out-of-credit" ? {
3518
+ failure: null,
3519
+ rateLimitStreak: 0
3520
+ } : {}
2261
3521
  });
2262
3522
  await writeKeyRecord(req, {
2263
3523
  keyLast4: lastFour(key),
@@ -2266,6 +3526,16 @@ function translationSettingsEndpoints(options = {}) {
2266
3526
  keyChange: `${replaced} (ends …${lastFour(key)}) by ${by}, ${today()}`
2267
3527
  });
2268
3528
  invalidateTranslationSettings(req.payload);
3529
+ if (before.enabled && check !== "out-of-credit") {
3530
+ const started = startBackfill(req.payload, {
3531
+ user: req.user,
3532
+ req: {
3533
+ url: req.url,
3534
+ headers: req.headers
3535
+ }
3536
+ }).catch(() => null);
3537
+ (readState(req.payload.config)?.waitUntil ?? vercelWaitUntil())?.(started);
3538
+ }
2269
3539
  const message = check === "out-of-credit" ? "Key saved, but its Anthropic account is out of credit. Translation cannot be switched on until credit is added." : check === "unreachable" ? "Key saved. Anthropic did not answer, so it will be checked on first use." : "Key saved and checked.";
2270
3540
  return Response.json({
2271
3541
  message,
@@ -2274,6 +3544,22 @@ function translationSettingsEndpoints(options = {}) {
2274
3544
  });
2275
3545
  }
2276
3546
  },
3547
+ {
3548
+ path: "/translation/summary",
3549
+ method: "get",
3550
+ handler: async (req) => {
3551
+ if (!await allowed(req)) return Response.json({ visible: false }, { status: req.user ? 403 : 401 });
3552
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
3553
+ const month = await usageThisMonth(req.payload);
3554
+ return Response.json({
3555
+ visible: true,
3556
+ enabled: settings.enabled,
3557
+ month,
3558
+ cap: settings.monthlyCap,
3559
+ failure: failureOf(settings.state)
3560
+ });
3561
+ }
3562
+ },
2277
3563
  {
2278
3564
  path: "/translation/key/check",
2279
3565
  method: "post",
@@ -2286,7 +3572,11 @@ function translationSettingsEndpoints(options = {}) {
2286
3572
  const check = await verify(key);
2287
3573
  await writeState(req, {
2288
3574
  keyStatus: check === "rejected" ? "rejected" : STATUS_BY_CHECK[check],
2289
- keyCheckedAt: check === "unreachable" ? settings.state.keyCheckedAt ?? null : (/* @__PURE__ */ new Date()).toISOString()
3575
+ keyCheckedAt: check === "unreachable" ? settings.state.keyCheckedAt ?? null : (/* @__PURE__ */ new Date()).toISOString(),
3576
+ ...check === "valid" && keyFailure(settings.state.failure) ? {
3577
+ failure: null,
3578
+ rateLimitStreak: 0
3579
+ } : {}
2290
3580
  });
2291
3581
  invalidateTranslationSettings(req.payload);
2292
3582
  return Response.json({
@@ -2391,12 +3681,17 @@ function withGlobal(global) {
2391
3681
  * and endpoints are added once, and each entity is hooked once, so a second
2392
3682
  * pass only picks up entities a later plugin registered.
2393
3683
  *
2394
- * Without `localization`, or with one locale, it adds the screen and
2395
- * hooks nothing (there is nothing to translate into).
3684
+ * It also puts every library language (`LIBRARY_LOCALES`) into the
3685
+ * config's `localization`, adding it when the site has none, so every site
3686
+ * carries every language in its schema. A target language is translated
3687
+ * and served only once it is ticked on the screen (`activeLocales`).
2396
3688
  */
2397
3689
  function applyTranslation(config, options = {}) {
2398
3690
  const prior = readState(config);
2399
- const localization = config.localization;
3691
+ const custom = config.custom ?? {};
3692
+ const siteDefault = config.localization ? config.localization.defaultLocale : void 0;
3693
+ const defaultActive = custom["bisonDefaultActiveLocales"] ?? localeCodes(config.localization).filter((code) => code !== siteDefault);
3694
+ const localization = withLibraryLocales(config.localization);
2400
3695
  const codes = localeCodes(localization);
2401
3696
  const sourceLocale = localization ? localization.defaultLocale : "en";
2402
3697
  const targetLocales = codes.filter((code) => code !== sourceLocale);
@@ -2414,7 +3709,12 @@ function applyTranslation(config, options = {}) {
2414
3709
  };
2415
3710
  const translatable = codes.length >= 2;
2416
3711
  const blocks = config.blocks ?? [];
2417
- const collections = (config.collections ?? []).map((collection) => {
3712
+ const hasCollection = (slug) => (config.collections ?? []).some((entry) => entry.slug === slug);
3713
+ const collections = [
3714
+ ...config.collections ?? [],
3715
+ ...hasCollection("translation-usage") ? [] : [translationUsageCollection()],
3716
+ ...hasCollection("translation-jobs") ? [] : [translationJobsCollection()]
3717
+ ].map((collection) => {
2418
3718
  const hint = entityHint(collection, options.hints);
2419
3719
  if (collection.slug in state.collections) {
2420
3720
  if (hint.context) state.collections[collection.slug] = hint;
@@ -2427,10 +3727,11 @@ function applyTranslation(config, options = {}) {
2427
3727
  const hasGlobal = (slug) => (config.globals ?? []).some((global) => global.slug === slug);
2428
3728
  const globals = [
2429
3729
  ...config.globals ?? [],
2430
- ...hasGlobal("translation-settings") ? [] : [translationSettingsGlobal({
3730
+ ...hasGlobal("translation-settings") ? [] : [withJobsOnSwitch(translationSettingsGlobal({
2431
3731
  site,
2432
- targetLocales
2433
- })],
3732
+ targetLocales,
3733
+ defaultActive
3734
+ }))],
2434
3735
  ...hasGlobal("translation-state") ? [] : [translationStateGlobal()]
2435
3736
  ].map((global) => {
2436
3737
  const hint = entityHint(global, options.hints);
@@ -2446,24 +3747,83 @@ function applyTranslation(config, options = {}) {
2446
3747
  const hasEndpoints = endpoints.some((endpoint) => endpoint.path === "/translation/status");
2447
3748
  return {
2448
3749
  ...config,
3750
+ localization,
2449
3751
  custom: {
2450
- ...config.custom,
2451
- [AUTO_TRANSLATE_STATE]: state
3752
+ ...custom,
3753
+ [AUTO_TRANSLATE_STATE]: state,
3754
+ [DEFAULT_ACTIVE_LOCALES]: defaultActive
2452
3755
  },
2453
3756
  collections,
2454
3757
  globals,
2455
3758
  endpoints: hasEndpoints ? endpoints : [
2456
3759
  ...endpoints,
2457
3760
  ...translationSettingsEndpoints(options.endpoints),
2458
- translationAvailableEndpoint()
2459
- ]
3761
+ translationAvailableEndpoint(),
3762
+ activeLocalesEndpoint(),
3763
+ ...translationJobEndpoints()
3764
+ ],
3765
+ onInit: hasEndpoints ? config.onInit : async (payload) => {
3766
+ await config.onInit?.(payload);
3767
+ resumeStaleJobs(payload).catch(() => void 0);
3768
+ },
3769
+ admin: hasEndpoints ? config.admin : {
3770
+ ...config.admin,
3771
+ components: {
3772
+ ...config.admin?.components,
3773
+ header: [...config.admin?.components?.header ?? [], TRANSLATION_STATUS_BAR]
3774
+ }
3775
+ }
2460
3776
  };
2461
3777
  }
2462
3778
  /** `applyTranslation` as a plugin, for a site that does not use `adminNav()`. */
2463
3779
  function translation(options = {}) {
2464
3780
  return (config) => applyTranslation(config, options);
2465
3781
  }
3782
+ /**
3783
+ * `GET /api/translation/locales`: the site's active languages, public and
3784
+ * cacheable for a minute, for middleware that cannot load Payload (an edge
3785
+ * runtime). Node middleware calls `activeLocales(payload)` directly.
3786
+ */
3787
+ function activeLocalesEndpoint() {
3788
+ return {
3789
+ path: "/translation/locales",
3790
+ method: "get",
3791
+ handler: async (req) => Response.json(await activeLocales(req.payload), { headers: { "Cache-Control": "public, max-age=60, s-maxage=60" } })
3792
+ };
3793
+ }
3794
+ /**
3795
+ * Switching translation on starts the backfill (unless a paused job waits
3796
+ * to be resumed); switching it off pauses running jobs after their current
3797
+ * document. Both run once the save has committed.
3798
+ */
3799
+ function withJobsOnSwitch(global) {
3800
+ const onSwitch = ({ doc, previousDoc, req }) => {
3801
+ const was = previousDoc?.enabled === true;
3802
+ const now = doc?.enabled === true;
3803
+ if (was === now) return doc;
3804
+ const user = req.user;
3805
+ const from = {
3806
+ url: req.url,
3807
+ headers: req.headers
3808
+ };
3809
+ runAfterCommit(req, "translation-settings", async () => {
3810
+ if (now) await startBackfill(req.payload, {
3811
+ user,
3812
+ req: from
3813
+ });
3814
+ else await pauseRunningJobs(req.payload);
3815
+ });
3816
+ return doc;
3817
+ };
3818
+ return {
3819
+ ...global,
3820
+ hooks: {
3821
+ ...global.hooks,
3822
+ afterChange: [...global.hooks?.afterChange ?? [], onSwitch]
3823
+ }
3824
+ };
3825
+ }
2466
3826
  //#endregion
2467
- export { storedRoles as $, sameRow as A, ROLES as At, canPublish as B, FEATURE_GROUPS as Bt, readTranslationSettings as C, featureGroupLabel as Ct, encryptApiKey as D, CAPABILITIES as Dt, decryptApiKey as E, validateFeaturesMatrix as Et, hasFeature as F, isRoleSlug as Ft, hasRole as G, isFeatureSlug as Gt, getRolesMatrix as H, PACKAGE_FEATURES as Ht, hideUnlessFeature as I, roleLabel as It, isAdminOrSelf as J, hideUnlessDeveloper as K, isLockedFeature as Kt, authenticatedOrPublished as L, sanitizeRoleNameInput as Lt, allowedFeaturesForUser as M, THEME_FEATURE_SLUGS as Mt, canUseFeature as N, isRole as Nt, resolveApiKey as O, CAPABILITY_FEATURES as Ot, getFeaturesMatrix as P, isRoleName as Pt, isPrivilegedRole as Q, canManageBrand as R, slugifyRoleName as Rt, invalidateTranslationSettings as S, featureCatalogue as St, siteFromInstructions as T, stampFeatureCatalogue as Tt, hasCapability as U, PACKAGE_FEATURE_SLUGS as Ut, developerOnlyAccess as V, FEATURE_GROUP_LABELS as Vt, hasGrant as W, isFeatureGroupId as Wt, isDeveloper as X, isAuthenticated as Y, isDeveloperTab as Z, withTranslator as _, roleSelectOptions as _t, isAutosave as a, LAST_USERS_TICK_MESSAGE as at, TRANSLATION_SETTINGS_SLUG as b, MISSING_PACKAGE_FEATURES_MESSAGE as bt, shouldSkipDraftedTranslation as c, ROLES_GLOBAL_DESCRIPTION as ct, runAfterCommit as d, defaultRolesFieldValue as dt, DEFAULT_ROLE_MATRIX as et, TRANSLATE_NOW as f, grantsFromStoredRole as ft, readTranslateState as g, roleDescription as gt, localeCodes as h, resetRolesMatrix as ht, translationSettingsEndpoints as i, INVALID_ROLE_NAME_MESSAGE as it, translationJob as j, ROLE_LABELS as jt, collectLocalizedStrings as k, DEFAULT_ROLE_GRANTS as kt, shouldSkipUndraftedTranslation as l, ROLES_SLUG as lt, BISON_TRANSLATION_CONTEXT as m, parseRolesMatrix as mt, hasLocalizedFields as n, DUPLICATE_ROLE_NAME_MESSAGE as nt, draftedTranslationDecision as o, MISSING_SEED_ROLES_MESSAGE as ot, translateDocument as p, normalizeStoredRoles as pt, isAdmin as q, isPackageFeatureSlug as qt, translation as r, DUPLICATE_ROLE_SLUG_MESSAGE as rt, localizedCopyUnchanged as s, ROLES_FIELD_DESCRIPTION as st, applyTranslation as t, DEVELOPER_DESCRIPTION as tt, TRANSACTION_TIMEOUT_MS as u, applyRoleSlugsFromNames as ut, TRANSLATION_GRANT as v, seedRoleRows as vt, resolveModel as w, parseFeaturesMatrix as wt, TRANSLATION_STATE_SLUG as x, defaultFeaturesFieldValue as xt, TRANSLATION_KEY_PANEL as y, validateRolesMatrix as yt, canManageContent as z, FEATURES_SLUG as zt };
3827
+ export { decryptApiKey as $, validateFeaturesMatrix as $t, TRANSLATION_SETTINGS_SLUG as A, DUPLICATE_ROLE_SLUG_MESSAGE as At, monthKey as B, normalizeStoredRoles as Bt, translateDocument as C, isDeveloper as Ct, TRANSLATION_ACTIVITY_PANEL as D, DEFAULT_ROLE_MATRIX as Dt, withTranslator as E, storedRoles as Et, resolveModel as F, ROLES_GLOBAL_DESCRIPTION as Ft, LIBRARY_DEFAULT_LOCALE as G, seedRoleRows as Gt, usageHistory as H, resetRolesMatrix as Ht, siteFromInstructions as I, ROLES_SLUG as It, activeAlternates as J, defaultFeaturesFieldValue as Jt, LIBRARY_LOCALES as K, validateRolesMatrix as Kt, FAILURE_ADVICE as L, applyRoleSlugsFromNames as Lt, TRANSLATION_STATUS_BAR as M, LAST_USERS_TICK_MESSAGE as Mt, invalidateTranslationSettings as N, MISSING_SEED_ROLES_MESSAGE as Nt, TRANSLATION_GRANT as O, DEVELOPER_DESCRIPTION as Ot, readTranslationSettings as P, ROLES_FIELD_DESCRIPTION as Pt, withLibraryLocales as Q, stampFeatureCatalogue as Qt, RATE_LIMIT_STREAK as R, defaultRolesFieldValue as Rt, TRANSLATE_NOW as S, isAuthenticated as St, readTranslateState as T, isPrivilegedRole as Tt, usageThisMonth as U, roleDescription as Ut, recordUsage as V, parseRolesMatrix as Vt, ACTIVE_LOCALES_CACHE_MS as W, roleSelectOptions as Wt, inactiveLocaleRedirect as X, featureGroupLabel as Xt, activeLocales as Y, featureCatalogue as Yt, invalidateActiveLocales as Z, parseFeaturesMatrix as Zt, localizedCopyUnchanged as _, isFeatureGroupId as _n, hasGrant as _t, LEASE_MS as a, THEME_FEATURE_SLUGS as an, allowedFeaturesForUser as at, TRANSACTION_TIMEOUT_MS as b, isPackageFeatureSlug as bn, isAdmin as bt, estimateJob as c, isRoleSlug as cn, hasFeature as ct, resumeStaleJobs as d, slugifyRoleName as dn, canManageBrand as dt, CAPABILITIES as en, encryptApiKey as et, runJobSlice as f, FEATURES_SLUG as fn, canManageContent as ft, draftedTranslationDecision as g, PACKAGE_FEATURE_SLUGS as gn, hasCapability as gt, isAutosave as h, PACKAGE_FEATURES as hn, getRolesMatrix as ht, translationSettingsEndpoints as i, ROLE_LABELS as in, translationJob as it, TRANSLATION_STATE_SLUG as j, INVALID_ROLE_NAME_MESSAGE as jt, TRANSLATION_KEY_PANEL as k, DUPLICATE_ROLE_NAME_MESSAGE as kt, frozenWordForce as l, roleLabel as ln, hideUnlessFeature as lt, startJob as m, FEATURE_GROUP_LABELS as mn, developerOnlyAccess as mt, hasLocalizedFields as n, DEFAULT_ROLE_GRANTS as nn, collectLocalizedStrings as nt, TRANSLATION_JOBS_SLUG as o, isRole as on, canUseFeature as ot, startBackfill as p, FEATURE_GROUPS as pn, canPublish as pt, LIBRARY_LOCALE_CODES as q, MISSING_PACKAGE_FEATURES_MESSAGE as qt, translation as r, ROLES as rn, sameRow as rt, claimJob as s, isRoleName as sn, getFeaturesMatrix as st, applyTranslation as t, CAPABILITY_FEATURES as tn, resolveApiKey as tt, jobView as u, sanitizeRoleNameInput as un, authenticatedOrPublished as ut, shouldSkipDraftedTranslation as v, isFeatureSlug as vn, hasRole as vt, BISON_TRANSLATION_CONTEXT as w, isDeveloperTab as wt, runAfterCommit as x, isAdminOrSelf as xt, shouldSkipUndraftedTranslation as y, isLockedFeature as yn, hideUnlessDeveloper as yt, TRANSLATION_USAGE_SLUG as z, grantsFromStoredRole as zt };
2468
3828
 
2469
- //# sourceMappingURL=capability-DdnN7AHB.mjs.map
3829
+ //# sourceMappingURL=capability-Cb62lWQo.mjs.map