@bison-lab/payload-core 5.0.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.
- package/README.md +23 -0
- package/dist/admin.d.mts +21 -1
- package/dist/admin.d.mts.map +1 -1
- package/dist/admin.mjs +265 -3
- package/dist/admin.mjs.map +1 -1
- package/dist/{capability-DHPE2kon.mjs → capability-Cb62lWQo.mjs} +1161 -17
- package/dist/capability-Cb62lWQo.mjs.map +1 -0
- package/dist/{capability-CqdYCzG1.d.mts → capability-Dotbq58Q.d.mts} +69 -3
- package/dist/capability-Dotbq58Q.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/translate.d.mts +143 -5
- package/dist/translate.d.mts.map +1 -1
- package/dist/translate.mjs +2 -2
- package/package.json +3 -3
- package/dist/capability-CqdYCzG1.d.mts.map +0 -1
- package/dist/capability-DHPE2kon.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-Fd7kUCT7.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
|
-
|
|
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
|
};
|
|
@@ -1206,6 +1209,242 @@ function activeAlternates(paths, locales) {
|
|
|
1206
1209
|
return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));
|
|
1207
1210
|
}
|
|
1208
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
|
|
1209
1448
|
//#region src/translate/settings.ts
|
|
1210
1449
|
/** Settings → Translation: the switch, model, instructions and the key's public record. Versioned. */
|
|
1211
1450
|
const TRANSLATION_SETTINGS_SLUG = "translation-settings";
|
|
@@ -1217,6 +1456,10 @@ const TRANSLATION_SETTINGS_SLUG = "translation-settings";
|
|
|
1217
1456
|
const TRANSLATION_STATE_SLUG = "translation-state";
|
|
1218
1457
|
/** The Roles grant that opens Settings → Translation. Developer and Admin always hold it. */
|
|
1219
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";
|
|
1220
1463
|
/** The admin component for the key panel on Settings → Translation. */
|
|
1221
1464
|
const TRANSLATION_KEY_PANEL = "@bison-lab/payload-core/admin#TranslationKeyPanel";
|
|
1222
1465
|
/** "Español" for `es`: the library's label, else the code. */
|
|
@@ -1291,6 +1534,7 @@ function readTranslationSettings(payload, codeSite) {
|
|
|
1291
1534
|
const defaults = (payload.config?.custom)?.["bisonDefaultActiveLocales"] ?? targets;
|
|
1292
1535
|
return {
|
|
1293
1536
|
enabled: doc.enabled === true,
|
|
1537
|
+
monthlyCap: typeof doc.monthlyCap === "number" && doc.monthlyCap >= 0 ? doc.monthlyCap : null,
|
|
1294
1538
|
languages: resolveActiveTargets(doc.languagesChosen ? doc.languages ?? [] : void 0, targets, defaults),
|
|
1295
1539
|
model: doc.model === "economy" ? "economy" : "quality",
|
|
1296
1540
|
...site ? { site } : {},
|
|
@@ -1336,21 +1580,69 @@ async function recordKeyOutcome(payload, settings, event) {
|
|
|
1336
1580
|
});
|
|
1337
1581
|
invalidateTranslationSettings(payload);
|
|
1338
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
|
+
}
|
|
1339
1608
|
/**
|
|
1340
1609
|
* The translator Settings → Translation describes: its key (see
|
|
1341
1610
|
* `resolveApiKey`), its model and its instructions. `configured: false`
|
|
1342
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.
|
|
1343
1618
|
*/
|
|
1344
1619
|
function settingsTranslator(payload, settings, seam = {}) {
|
|
1345
1620
|
const key = keyFor(payload, settings);
|
|
1346
1621
|
const production = key.source === "admin" || process.env.VERCEL_ENV === "production";
|
|
1347
|
-
|
|
1622
|
+
const inner = anthropicTranslator({
|
|
1348
1623
|
apiKey: key.apiKey ?? null,
|
|
1349
1624
|
...seam.client && key.apiKey ? { client: seam.client } : {},
|
|
1350
1625
|
model: resolveModel(settings.model, production),
|
|
1351
1626
|
...settings.site ? { site: settings.site } : {},
|
|
1352
|
-
onCall: (event) =>
|
|
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
|
+
}
|
|
1353
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 });
|
|
1354
1646
|
}
|
|
1355
1647
|
const FROZEN_WORDS_DESCRIPTION = "Kept exactly as written in every language. Matching is whole-word and case-sensitive: \"ProtectIQ\" does not match \"protectiq\".";
|
|
1356
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.";
|
|
@@ -1387,6 +1679,22 @@ function who(user) {
|
|
|
1387
1679
|
}
|
|
1388
1680
|
/** Fields only the server writes: the form and the REST API cannot change them. */
|
|
1389
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
|
+
};
|
|
1390
1698
|
const clearCache = ({ doc, req }) => {
|
|
1391
1699
|
invalidateTranslationSettings(req.payload);
|
|
1392
1700
|
invalidateActiveLocales(req.payload);
|
|
@@ -1490,7 +1798,7 @@ function translationSettingsGlobal(options) {
|
|
|
1490
1798
|
versions: { max: 100 },
|
|
1491
1799
|
hooks: {
|
|
1492
1800
|
beforeChange: [refuseOutOfCredit, stampChangedBy],
|
|
1493
|
-
afterChange: [clearCache]
|
|
1801
|
+
afterChange: [clearCache, clearCapFailure]
|
|
1494
1802
|
},
|
|
1495
1803
|
fields: [
|
|
1496
1804
|
{
|
|
@@ -1498,6 +1806,11 @@ function translationSettingsGlobal(options) {
|
|
|
1498
1806
|
type: "ui",
|
|
1499
1807
|
admin: { components: { Field: TRANSLATION_KEY_PANEL } }
|
|
1500
1808
|
},
|
|
1809
|
+
{
|
|
1810
|
+
name: "activityPanel",
|
|
1811
|
+
type: "ui",
|
|
1812
|
+
admin: { components: { Field: TRANSLATION_ACTIVITY_PANEL } }
|
|
1813
|
+
},
|
|
1501
1814
|
{
|
|
1502
1815
|
name: "enabled",
|
|
1503
1816
|
type: "checkbox",
|
|
@@ -1518,6 +1831,13 @@ function translationSettingsGlobal(options) {
|
|
|
1518
1831
|
hooks: { afterRead: [({ value, siblingData }) => siblingData?.languagesChosen ? value : [...options.defaultActive ?? []]] },
|
|
1519
1832
|
admin: { description: "Only ticked languages are translated and served. An unticked language costs nothing and has no pages: its URLs redirect to English." }
|
|
1520
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
|
+
},
|
|
1521
1841
|
{
|
|
1522
1842
|
name: "model",
|
|
1523
1843
|
type: "radio",
|
|
@@ -1611,6 +1931,25 @@ function translationStateGlobal() {
|
|
|
1611
1931
|
{
|
|
1612
1932
|
name: "keyCheckedAt",
|
|
1613
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
|
|
1614
1953
|
}
|
|
1615
1954
|
]
|
|
1616
1955
|
};
|
|
@@ -1771,7 +2110,8 @@ async function translateDocument(payload, options) {
|
|
|
1771
2110
|
source: from,
|
|
1772
2111
|
target,
|
|
1773
2112
|
previous: options.previous,
|
|
1774
|
-
overwrite: options.overwrite
|
|
2113
|
+
overwrite: options.overwrite,
|
|
2114
|
+
...options.force ? { force: options.force } : {}
|
|
1775
2115
|
});
|
|
1776
2116
|
const results = [];
|
|
1777
2117
|
for (const locale of targets) {
|
|
@@ -2351,7 +2691,714 @@ function globalAutoTranslateHook(slug) {
|
|
|
2351
2691
|
};
|
|
2352
2692
|
}
|
|
2353
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
|
|
2354
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
|
+
}
|
|
2355
3402
|
async function allowed(req) {
|
|
2356
3403
|
if (!req.user) return false;
|
|
2357
3404
|
return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));
|
|
@@ -2377,9 +3424,23 @@ async function status(req) {
|
|
|
2377
3424
|
source: key.source,
|
|
2378
3425
|
last4: key.last4
|
|
2379
3426
|
} : null,
|
|
2380
|
-
...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)
|
|
2381
3434
|
};
|
|
2382
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
|
+
}
|
|
2383
3444
|
const STATUS_BY_CHECK = {
|
|
2384
3445
|
valid: "valid",
|
|
2385
3446
|
"out-of-credit": "out-of-credit",
|
|
@@ -2452,7 +3513,11 @@ function translationSettingsEndpoints(options = {}) {
|
|
|
2452
3513
|
await writeState(req, {
|
|
2453
3514
|
keyCipher: encryptApiKey(key, req.payload.secret),
|
|
2454
3515
|
keyStatus: STATUS_BY_CHECK[check],
|
|
2455
|
-
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
|
+
} : {}
|
|
2456
3521
|
});
|
|
2457
3522
|
await writeKeyRecord(req, {
|
|
2458
3523
|
keyLast4: lastFour(key),
|
|
@@ -2461,6 +3526,16 @@ function translationSettingsEndpoints(options = {}) {
|
|
|
2461
3526
|
keyChange: `${replaced} (ends …${lastFour(key)}) by ${by}, ${today()}`
|
|
2462
3527
|
});
|
|
2463
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
|
+
}
|
|
2464
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.";
|
|
2465
3540
|
return Response.json({
|
|
2466
3541
|
message,
|
|
@@ -2469,6 +3544,22 @@ function translationSettingsEndpoints(options = {}) {
|
|
|
2469
3544
|
});
|
|
2470
3545
|
}
|
|
2471
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
|
+
},
|
|
2472
3563
|
{
|
|
2473
3564
|
path: "/translation/key/check",
|
|
2474
3565
|
method: "post",
|
|
@@ -2481,7 +3572,11 @@ function translationSettingsEndpoints(options = {}) {
|
|
|
2481
3572
|
const check = await verify(key);
|
|
2482
3573
|
await writeState(req, {
|
|
2483
3574
|
keyStatus: check === "rejected" ? "rejected" : STATUS_BY_CHECK[check],
|
|
2484
|
-
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
|
+
} : {}
|
|
2485
3580
|
});
|
|
2486
3581
|
invalidateTranslationSettings(req.payload);
|
|
2487
3582
|
return Response.json({
|
|
@@ -2614,7 +3709,12 @@ function applyTranslation(config, options = {}) {
|
|
|
2614
3709
|
};
|
|
2615
3710
|
const translatable = codes.length >= 2;
|
|
2616
3711
|
const blocks = config.blocks ?? [];
|
|
2617
|
-
const
|
|
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) => {
|
|
2618
3718
|
const hint = entityHint(collection, options.hints);
|
|
2619
3719
|
if (collection.slug in state.collections) {
|
|
2620
3720
|
if (hint.context) state.collections[collection.slug] = hint;
|
|
@@ -2627,11 +3727,11 @@ function applyTranslation(config, options = {}) {
|
|
|
2627
3727
|
const hasGlobal = (slug) => (config.globals ?? []).some((global) => global.slug === slug);
|
|
2628
3728
|
const globals = [
|
|
2629
3729
|
...config.globals ?? [],
|
|
2630
|
-
...hasGlobal("translation-settings") ? [] : [translationSettingsGlobal({
|
|
3730
|
+
...hasGlobal("translation-settings") ? [] : [withJobsOnSwitch(translationSettingsGlobal({
|
|
2631
3731
|
site,
|
|
2632
3732
|
targetLocales,
|
|
2633
3733
|
defaultActive
|
|
2634
|
-
})],
|
|
3734
|
+
}))],
|
|
2635
3735
|
...hasGlobal("translation-state") ? [] : [translationStateGlobal()]
|
|
2636
3736
|
].map((global) => {
|
|
2637
3737
|
const hint = entityHint(global, options.hints);
|
|
@@ -2659,8 +3759,20 @@ function applyTranslation(config, options = {}) {
|
|
|
2659
3759
|
...endpoints,
|
|
2660
3760
|
...translationSettingsEndpoints(options.endpoints),
|
|
2661
3761
|
translationAvailableEndpoint(),
|
|
2662
|
-
activeLocalesEndpoint()
|
|
2663
|
-
|
|
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
|
+
}
|
|
2664
3776
|
};
|
|
2665
3777
|
}
|
|
2666
3778
|
/** `applyTranslation` as a plugin, for a site that does not use `adminNav()`. */
|
|
@@ -2679,7 +3791,39 @@ function activeLocalesEndpoint() {
|
|
|
2679
3791
|
handler: async (req) => Response.json(await activeLocales(req.payload), { headers: { "Cache-Control": "public, max-age=60, s-maxage=60" } })
|
|
2680
3792
|
};
|
|
2681
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
|
+
}
|
|
2682
3826
|
//#endregion
|
|
2683
|
-
export {
|
|
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 };
|
|
2684
3828
|
|
|
2685
|
-
//# sourceMappingURL=capability-
|
|
3829
|
+
//# sourceMappingURL=capability-Cb62lWQo.mjs.map
|