@bison-lab/payload-core 4.40.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -4
- package/dist/admin.mjs +5 -2
- package/dist/admin.mjs.map +1 -1
- package/dist/{capability-BVDhJV8A.d.mts → capability-CqdYCzG1.d.mts} +17 -7
- package/dist/{capability-BVDhJV8A.d.mts.map → capability-CqdYCzG1.d.mts.map} +1 -1
- package/dist/{capability-DdnN7AHB.mjs → capability-DHPE2kon.mjs} +235 -19
- package/dist/capability-DHPE2kon.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/locale-B6rUVwpg.mjs.map +1 -1
- package/dist/{locale-5z7KTvRJ.d.mts → locale-CTT3nn6T.d.mts} +5 -4
- package/dist/locale-CTT3nn6T.d.mts.map +1 -0
- package/dist/{messages-Bk1uYO3o.mjs → messages-dZV_aAnR.mjs} +2 -2
- package/dist/{messages-Bk1uYO3o.mjs.map → messages-dZV_aAnR.mjs.map} +1 -1
- package/dist/navigation.d.mts +2 -2
- package/dist/og.d.mts +1 -1
- package/dist/{published-CY5PIy5W.d.mts → published-B3etM6X5.d.mts} +2 -2
- package/dist/{published-CY5PIy5W.d.mts.map → published-B3etM6X5.d.mts.map} +1 -1
- package/dist/{published-BC8kg47c.d.mts → published-QDNmDi02.d.mts} +2 -2
- package/dist/{published-BC8kg47c.d.mts.map → published-QDNmDi02.d.mts.map} +1 -1
- package/dist/{strings-Bafwdg67.mjs → strings-Fd7kUCT7.mjs} +4 -4
- package/dist/strings-Fd7kUCT7.mjs.map +1 -0
- package/dist/theme.d.mts +2 -2
- package/dist/translate-messages-cli.mjs +3 -3
- package/dist/translate-messages-cli.mjs.map +1 -1
- package/dist/translate.d.mts +225 -3
- package/dist/translate.d.mts.map +1 -1
- package/dist/translate.mjs +238 -5
- package/dist/translate.mjs.map +1 -1
- package/package.json +7 -9
- package/dist/capability-DdnN7AHB.mjs.map +0 -1
- package/dist/locale-5z7KTvRJ.d.mts.map +0 -1
- package/dist/strings-Bafwdg67.mjs.map +0 -1
|
@@ -212,9 +212,9 @@ declare function translationSystemPrompt(request: Pick<TranslateRequest, "from"
|
|
|
212
212
|
declare function parseJsonArray(text: string): string[] | null;
|
|
213
213
|
/**
|
|
214
214
|
* The provided `Translator`: one Anthropic Messages call per batch, the
|
|
215
|
-
* strings as a JSON array in and out. `@anthropic-ai/sdk` is
|
|
216
|
-
*
|
|
217
|
-
*
|
|
215
|
+
* strings as a JSON array in and out. `@anthropic-ai/sdk` is a peer,
|
|
216
|
+
* imported on the first call, so a site that never translates never loads
|
|
217
|
+
* it. Every failure (no key, the SDK missing, a network error, a
|
|
218
218
|
* refusal, a malformed or wrong-length reply) returns `null` and is logged
|
|
219
219
|
* by the caller; it never throws.
|
|
220
220
|
*/
|
|
@@ -283,6 +283,10 @@ type KeyStatus = "valid" | "out-of-credit" | "rejected" | "unchecked";
|
|
|
283
283
|
/** The saved Settings → Translation document, as this package reads it. Optional and nullable. */
|
|
284
284
|
interface TranslationSettingsDoc {
|
|
285
285
|
enabled?: boolean | null;
|
|
286
|
+
/** Ticked target languages. */
|
|
287
|
+
languages?: string[] | null;
|
|
288
|
+
/** Set by the server once someone has saved the ticks; until then the defaults apply. */
|
|
289
|
+
languagesChosen?: boolean | null;
|
|
286
290
|
model?: TranslationModelChoice | null;
|
|
287
291
|
keyLast4?: string | null;
|
|
288
292
|
keySetAt?: string | null;
|
|
@@ -316,6 +320,8 @@ interface ResolvedTranslationSettings {
|
|
|
316
320
|
site?: TranslateSite;
|
|
317
321
|
/** True once the document has been saved. */
|
|
318
322
|
saved: boolean;
|
|
323
|
+
/** The ticked target languages, the only ones translated into. */
|
|
324
|
+
languages: string[];
|
|
319
325
|
doc: TranslationSettingsDoc;
|
|
320
326
|
state: TranslationStateDoc;
|
|
321
327
|
}
|
|
@@ -333,7 +339,9 @@ declare function resolveModel(choice: TranslationModelChoice | null | undefined,
|
|
|
333
339
|
declare function siteFromInstructions(instructions: TranslationSettingsDoc["instructions"]): TranslateSite | undefined;
|
|
334
340
|
/** Drops the cached read, so the next one sees a save at once. */
|
|
335
341
|
declare function invalidateTranslationSettings(payload: object): void;
|
|
336
|
-
type ReadPayload = Pick<Payload, "findGlobal"
|
|
342
|
+
type ReadPayload = Pick<Payload, "findGlobal"> & {
|
|
343
|
+
config?: Pick<Payload["config"], "localization" | "custom">;
|
|
344
|
+
};
|
|
337
345
|
/**
|
|
338
346
|
* Settings → Translation and its server state, read once per
|
|
339
347
|
* `SETTINGS_CACHE_MS` per process. A missing Global (a site that has not
|
|
@@ -413,12 +421,14 @@ declare function hasLocalizedFields(fields: readonly Field[], blocks?: readonly
|
|
|
413
421
|
* and endpoints are added once, and each entity is hooked once, so a second
|
|
414
422
|
* pass only picks up entities a later plugin registered.
|
|
415
423
|
*
|
|
416
|
-
*
|
|
417
|
-
*
|
|
424
|
+
* It also puts every library language (`LIBRARY_LOCALES`) into the
|
|
425
|
+
* config's `localization`, adding it when the site has none, so every site
|
|
426
|
+
* carries every language in its schema. A target language is translated
|
|
427
|
+
* and served only once it is ticked on the screen (`activeLocales`).
|
|
418
428
|
*/
|
|
419
429
|
declare function applyTranslation(config: Config, options?: TranslationOptions): Config;
|
|
420
430
|
/** `applyTranslation` as a plugin, for a site that does not use `adminNav()`. */
|
|
421
431
|
declare function translation(options?: TranslationOptions): (config: Config) => Config;
|
|
422
432
|
//#endregion
|
|
423
433
|
export { ModelPrice as A, AutoTranslateOptions as B, encryptApiKey as C, DEFAULT_TRANSLATE_MODEL as D, AnthropicTranslatorOptions as E, estimateCost as F, TranslateLocaleResult as G, BisonTranslationKind as H, modelPrice as I, TranslatedEntity as J, TranslateRequest as K, parseJsonArray as L, TranslatorCallEvent as M, anthropicTranslator as N, ECONOMY_TRANSLATE_MODEL as O, containsWord as P, translationSystemPrompt as R, decryptApiKey as S, AnthropicMessagesClient as T, BisonTranslationMarker as U, BISON_TRANSLATION_CONTEXT as V, Doc as W, TranslationFailureKind as X, Translator as Y, classifyAnthropicError as Z, readTranslationSettings as _, translation as a, KeySource as b, KeyStatus as c, TRANSLATION_KEY_PANEL as d, TRANSLATION_SETTINGS_SLUG as f, invalidateTranslationSettings as g, TranslationSettingsDoc as h, hasLocalizedFields as i, TRANSLATE_MODEL_PRICES as j, KeyCheck as k, ResolvedTranslationSettings as l, TranslationModelChoice as m, TranslationOptions as n, TranslationStatus as o, TRANSLATION_STATE_SLUG as p, TranslateSite as q, applyTranslation as r, translationSettingsEndpoints as s, TranslationEntityHint as t, TRANSLATION_GRANT as u, resolveModel as v, resolveApiKey as w, ResolvedKey as x, siteFromInstructions as y, verifyAnthropicKey as z };
|
|
424
|
-
//# sourceMappingURL=capability-
|
|
434
|
+
//# sourceMappingURL=capability-CqdYCzG1.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capability-
|
|
1
|
+
{"version":3,"file":"capability-CqdYCzG1.d.mts","names":[],"sources":["../src/translate/errors.ts","../src/translate/types.ts","../src/translate/anthropic.ts","../src/translate/key.ts","../src/translate/settings.ts","../src/translate/settings-endpoints.ts","../src/translate/capability.ts"],"mappings":";;;;;;AAWA;;;;;AAWA;;;KAXY,sBAAA;;iBAWI,sBAAA,CAAuB,KAAA,YAAiB,sBAAA;;;;KCrB5C,GAAA,GAAM,MAAA;;KAGN,oBAAA;;;;;ADkBZ;;;;;;;;ACrBA;UAkBiB,sBAAA;EACf,MAAA;EACA,IAAA,EAAM,oBAAA;AAAA;AAjBR;AAAA,cAqBa,yBAAA;;;;AANb;;UAaiB,aAAA;EAXW;EAa1B,IAAA;EAbA;EAeA,KAAA;EAf0B;EAiB1B,KAAA;EAbW;EAeX,YAAA;;;;AARF;;EAcE,SAAA,GAAY,MAAA;AAAA;;UAIG,gBAAA;EACf,IAAA;EACA,EAAA;EANA;EAQA,OAAA;EARkB;EAUlB,IAAA,GAAO,aAAA;AAAA;;;;;;;;;;KAYG,UAAA,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;;;;AAOA;;AAbA,iBKiHgB,gBAAA,CAAiB,MAAA,EAAQ,MAAA,EAAQ,OAAA,GAAS,kBAAA,GAA0B,MAAA;;iBAgFpE,WAAA,CAAY,OAAA,GAAS,kBAAA,IAC3B,MAAA,EAAQ,MAAA,KAAS,MAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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";
|
|
2
2
|
import { APIError } from "payload";
|
|
3
3
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
4
4
|
//#region src/features/types.ts
|
|
@@ -1050,6 +1050,162 @@ function resolveApiKey(input) {
|
|
|
1050
1050
|
};
|
|
1051
1051
|
}
|
|
1052
1052
|
//#endregion
|
|
1053
|
+
//#region src/translate/languages.ts
|
|
1054
|
+
/**
|
|
1055
|
+
* The languages every Bison site carries. The library owns this list: a new
|
|
1056
|
+
* language is a library release that sites take by updating the package
|
|
1057
|
+
* (and running the migration it brings). The first entry is the default
|
|
1058
|
+
* locale of a site that declares no localization of its own.
|
|
1059
|
+
*/
|
|
1060
|
+
const LIBRARY_LOCALES = [{
|
|
1061
|
+
code: "en",
|
|
1062
|
+
label: "English"
|
|
1063
|
+
}, {
|
|
1064
|
+
code: "es",
|
|
1065
|
+
label: "Español"
|
|
1066
|
+
}];
|
|
1067
|
+
const LIBRARY_DEFAULT_LOCALE = "en";
|
|
1068
|
+
/** The codes of `LIBRARY_LOCALES`, in order. */
|
|
1069
|
+
const LIBRARY_LOCALE_CODES = LIBRARY_LOCALES.map((locale) => locale.code);
|
|
1070
|
+
function codeOf(entry) {
|
|
1071
|
+
return typeof entry === "string" ? entry : entry.code;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* A config's `localization` with every library language in it. A site with
|
|
1075
|
+
* none gets the library's (English default, `fallback: true`, so an empty
|
|
1076
|
+
* Spanish field reads as English). A site with its own keeps its locales,
|
|
1077
|
+
* labels and default, and gains any library language it lacks.
|
|
1078
|
+
*/
|
|
1079
|
+
function withLibraryLocales(localization) {
|
|
1080
|
+
if (!localization) return {
|
|
1081
|
+
locales: LIBRARY_LOCALES.map((locale) => ({ ...locale })),
|
|
1082
|
+
defaultLocale: "en",
|
|
1083
|
+
fallback: true
|
|
1084
|
+
};
|
|
1085
|
+
const own = localization.locales;
|
|
1086
|
+
const have = new Set(own.map(codeOf));
|
|
1087
|
+
const missing = LIBRARY_LOCALES.filter((locale) => !have.has(locale.code));
|
|
1088
|
+
if (missing.length === 0) return localization;
|
|
1089
|
+
const locales = [...own.map((entry) => typeof entry === "string" ? {
|
|
1090
|
+
code: entry,
|
|
1091
|
+
label: entry
|
|
1092
|
+
} : entry), ...missing.map((locale) => ({ ...locale }))];
|
|
1093
|
+
return {
|
|
1094
|
+
...localization,
|
|
1095
|
+
locales
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
/** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
|
|
1099
|
+
const ACTIVE_LOCALES_CACHE_MS = 6e4;
|
|
1100
|
+
const cache$1 = /* @__PURE__ */ new WeakMap();
|
|
1101
|
+
/** The last answer read from the database, kept for when a later read fails. */
|
|
1102
|
+
const lastGood = /* @__PURE__ */ new WeakMap();
|
|
1103
|
+
/** After a failed read, how soon to try the database again. */
|
|
1104
|
+
const ACTIVE_LOCALES_RETRY_MS = 5e3;
|
|
1105
|
+
/** Drops the cached answer, so the next `activeLocales` reads again. */
|
|
1106
|
+
function invalidateActiveLocales(payload) {
|
|
1107
|
+
cache$1.delete(payload);
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* The ticked target languages, as the Translation screen stores them.
|
|
1111
|
+
* `null` or absent (never saved) means the defaults: the target locales the
|
|
1112
|
+
* site declared itself before the library's were added.
|
|
1113
|
+
*/
|
|
1114
|
+
function resolveActiveTargets(stored, targets, defaults) {
|
|
1115
|
+
const chosen = Array.isArray(stored) ? stored : defaults;
|
|
1116
|
+
return targets.filter((code) => chosen.includes(code));
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* The site's active languages, for routing and middleware: the default
|
|
1120
|
+
* locale plus each target language ticked on Settings → Translation. Cached
|
|
1121
|
+
* per process for `ttlMs` (60s by default): a request reads memory, and the
|
|
1122
|
+
* database is read only when the cache refreshes, or after a save of the
|
|
1123
|
+
* screen in the same process. Never throws. When a read fails it answers
|
|
1124
|
+
* with the last good read (or, before the first one, the defaults) and
|
|
1125
|
+
* tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
|
|
1126
|
+
* never stands in for the Admin's ticks for a whole cache period, which
|
|
1127
|
+
* would send a ticked language's visitors permanent redirects.
|
|
1128
|
+
*/
|
|
1129
|
+
function activeLocales(payload, options = {}) {
|
|
1130
|
+
const ttl = options.ttlMs ?? 6e4;
|
|
1131
|
+
const hit = cache$1.get(payload);
|
|
1132
|
+
if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;
|
|
1133
|
+
const entry = {
|
|
1134
|
+
at: Date.now(),
|
|
1135
|
+
value: void 0
|
|
1136
|
+
};
|
|
1137
|
+
entry.value = readActiveLocales(payload).then((read) => {
|
|
1138
|
+
if (read.ok) {
|
|
1139
|
+
lastGood.set(payload, read.value);
|
|
1140
|
+
return read.value;
|
|
1141
|
+
}
|
|
1142
|
+
entry.ttl = ACTIVE_LOCALES_RETRY_MS;
|
|
1143
|
+
return lastGood.get(payload) ?? read.value;
|
|
1144
|
+
});
|
|
1145
|
+
cache$1.set(payload, entry);
|
|
1146
|
+
return entry.value;
|
|
1147
|
+
}
|
|
1148
|
+
/** The slug `activeLocales` reads; the Translation screen's. */
|
|
1149
|
+
const SETTINGS_SLUG = "translation-settings";
|
|
1150
|
+
/** Where `applyTranslation` leaves the default ticks: the site's own target locales. */
|
|
1151
|
+
const DEFAULT_ACTIVE_LOCALES = "bisonDefaultActiveLocales";
|
|
1152
|
+
async function readActiveLocales(payload) {
|
|
1153
|
+
const localization = payload.config.localization;
|
|
1154
|
+
const codes = localization ? localization.locales.map(codeOf) : ["en"];
|
|
1155
|
+
const defaultLocale = localization ? localization.defaultLocale : "en";
|
|
1156
|
+
const targets = codes.filter((code) => code !== defaultLocale);
|
|
1157
|
+
const defaults = payload.config.custom?.["bisonDefaultActiveLocales"] ?? targets;
|
|
1158
|
+
let stored;
|
|
1159
|
+
let ok = true;
|
|
1160
|
+
try {
|
|
1161
|
+
const doc = await payload.findGlobal({
|
|
1162
|
+
slug: SETTINGS_SLUG,
|
|
1163
|
+
depth: 0,
|
|
1164
|
+
overrideAccess: true
|
|
1165
|
+
});
|
|
1166
|
+
stored = doc?.languagesChosen ? doc.languages ?? [] : void 0;
|
|
1167
|
+
} catch {
|
|
1168
|
+
stored = void 0;
|
|
1169
|
+
ok = false;
|
|
1170
|
+
}
|
|
1171
|
+
const ticked = resolveActiveTargets(stored, targets, defaults);
|
|
1172
|
+
return {
|
|
1173
|
+
ok,
|
|
1174
|
+
value: {
|
|
1175
|
+
defaultLocale,
|
|
1176
|
+
active: codes.filter((code) => code === defaultLocale || ticked.includes(code)),
|
|
1177
|
+
inactive: targets.filter((code) => !ticked.includes(code))
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Where a request for an inactive language goes: the same path without
|
|
1183
|
+
* its locale prefix, for a 308. `null` when the path is not under an
|
|
1184
|
+
* inactive locale. In a site's middleware:
|
|
1185
|
+
*
|
|
1186
|
+
* ```ts
|
|
1187
|
+
* const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
|
|
1188
|
+
* if (to) {
|
|
1189
|
+
* const response = NextResponse.redirect(new URL(to + url.search, url), 308);
|
|
1190
|
+
* response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
|
|
1191
|
+
* return response;
|
|
1192
|
+
* }
|
|
1193
|
+
* ```
|
|
1194
|
+
*/
|
|
1195
|
+
function inactiveLocaleRedirect(pathname, locales) {
|
|
1196
|
+
const [, first, ...rest] = pathname.split("/");
|
|
1197
|
+
if (!first || !locales.inactive.includes(first)) return null;
|
|
1198
|
+
return `/${rest.join("/").replace(/^[\\/]+/, "")}`;
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* A page's language alternates (for hreflang and a language switcher),
|
|
1202
|
+
* keeping only active languages. `paths` maps each locale to that
|
|
1203
|
+
* language's URL for the page.
|
|
1204
|
+
*/
|
|
1205
|
+
function activeAlternates(paths, locales) {
|
|
1206
|
+
return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));
|
|
1207
|
+
}
|
|
1208
|
+
//#endregion
|
|
1053
1209
|
//#region src/translate/settings.ts
|
|
1054
1210
|
/** Settings → Translation: the switch, model, instructions and the key's public record. Versioned. */
|
|
1055
1211
|
const TRANSLATION_SETTINGS_SLUG = "translation-settings";
|
|
@@ -1063,6 +1219,10 @@ const TRANSLATION_STATE_SLUG = "translation-state";
|
|
|
1063
1219
|
const TRANSLATION_GRANT = "translation";
|
|
1064
1220
|
/** The admin component for the key panel on Settings → Translation. */
|
|
1065
1221
|
const TRANSLATION_KEY_PANEL = "@bison-lab/payload-core/admin#TranslationKeyPanel";
|
|
1222
|
+
/** "Español" for `es`: the library's label, else the code. */
|
|
1223
|
+
function localeLabel(code) {
|
|
1224
|
+
return LIBRARY_LOCALES.find((locale) => locale.code === code)?.label ?? code;
|
|
1225
|
+
}
|
|
1066
1226
|
const MODEL_IDS = {
|
|
1067
1227
|
quality: DEFAULT_TRANSLATE_MODEL,
|
|
1068
1228
|
economy: ECONOMY_TRANSLATE_MODEL
|
|
@@ -1126,8 +1286,12 @@ function readTranslationSettings(payload, codeSite) {
|
|
|
1126
1286
|
const [doc, state] = await Promise.all([readGlobal(payload, TRANSLATION_SETTINGS_SLUG), readGlobal(payload, TRANSLATION_STATE_SLUG)]);
|
|
1127
1287
|
const saved = typeof doc.updatedAt === "string" && doc.updatedAt !== "";
|
|
1128
1288
|
const site = saved ? siteFromInstructions(doc.instructions) : codeSite;
|
|
1289
|
+
const localization = payload.config?.localization;
|
|
1290
|
+
const targets = localization ? localization.locales.map((locale) => typeof locale === "string" ? locale : locale.code).filter((code) => code !== localization.defaultLocale) : [];
|
|
1291
|
+
const defaults = (payload.config?.custom)?.["bisonDefaultActiveLocales"] ?? targets;
|
|
1129
1292
|
return {
|
|
1130
1293
|
enabled: doc.enabled === true,
|
|
1294
|
+
languages: resolveActiveTargets(doc.languagesChosen ? doc.languages ?? [] : void 0, targets, defaults),
|
|
1131
1295
|
model: doc.model === "economy" ? "economy" : "quality",
|
|
1132
1296
|
...site ? { site } : {},
|
|
1133
1297
|
saved,
|
|
@@ -1201,12 +1365,17 @@ const refuseOutOfCredit = async ({ data, originalDoc, req }) => {
|
|
|
1201
1365
|
if (state.keyCipher && state.keyStatus === "out-of-credit") throw new APIError(OUT_OF_CREDIT_MESSAGE, 400);
|
|
1202
1366
|
return data;
|
|
1203
1367
|
};
|
|
1204
|
-
/**
|
|
1368
|
+
/**
|
|
1369
|
+
* Who made each save, so every version in the history names them, and
|
|
1370
|
+
* whether the language ticks have been chosen. Set by the server, never by
|
|
1371
|
+
* the form.
|
|
1372
|
+
*/
|
|
1205
1373
|
const stampChangedBy = ({ data, req }) => {
|
|
1206
1374
|
if (!data) return data;
|
|
1207
1375
|
return {
|
|
1208
1376
|
...data,
|
|
1209
|
-
changedBy: who(req.user)
|
|
1377
|
+
changedBy: who(req.user),
|
|
1378
|
+
...Array.isArray(data.languages) ? { languagesChosen: true } : {}
|
|
1210
1379
|
};
|
|
1211
1380
|
};
|
|
1212
1381
|
/** A name for the user on a request: their name, else email, else id. */
|
|
@@ -1220,6 +1389,7 @@ function who(user) {
|
|
|
1220
1389
|
const serverOnly = { update: () => false };
|
|
1221
1390
|
const clearCache = ({ doc, req }) => {
|
|
1222
1391
|
invalidateTranslationSettings(req.payload);
|
|
1392
|
+
invalidateActiveLocales(req.payload);
|
|
1223
1393
|
return doc;
|
|
1224
1394
|
};
|
|
1225
1395
|
function instructionFields(options) {
|
|
@@ -1266,7 +1436,7 @@ function instructionFields(options) {
|
|
|
1266
1436
|
required: true,
|
|
1267
1437
|
enumName: "enum_translation_dialect_locale",
|
|
1268
1438
|
options: options.targetLocales.map((code) => ({
|
|
1269
|
-
label: code,
|
|
1439
|
+
label: localeLabel(code),
|
|
1270
1440
|
value: code
|
|
1271
1441
|
}))
|
|
1272
1442
|
}, {
|
|
@@ -1335,6 +1505,19 @@ function translationSettingsGlobal(options) {
|
|
|
1335
1505
|
defaultValue: false,
|
|
1336
1506
|
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
1507
|
},
|
|
1508
|
+
{
|
|
1509
|
+
name: "languages",
|
|
1510
|
+
type: "select",
|
|
1511
|
+
label: "Translate into",
|
|
1512
|
+
hasMany: true,
|
|
1513
|
+
defaultValue: [...options.defaultActive ?? []],
|
|
1514
|
+
options: options.targetLocales.map((code) => ({
|
|
1515
|
+
label: localeLabel(code),
|
|
1516
|
+
value: code
|
|
1517
|
+
})),
|
|
1518
|
+
hooks: { afterRead: [({ value, siblingData }) => siblingData?.languagesChosen ? value : [...options.defaultActive ?? []]] },
|
|
1519
|
+
admin: { description: "Only ticked languages are translated and served. An unticked language costs nothing and has no pages: its URLs redirect to English." }
|
|
1520
|
+
},
|
|
1338
1521
|
{
|
|
1339
1522
|
name: "model",
|
|
1340
1523
|
type: "radio",
|
|
@@ -1365,6 +1548,12 @@ function translationSettingsGlobal(options) {
|
|
|
1365
1548
|
description: "Who made this save. Each version in the history keeps it."
|
|
1366
1549
|
}
|
|
1367
1550
|
},
|
|
1551
|
+
{
|
|
1552
|
+
name: "languagesChosen",
|
|
1553
|
+
type: "checkbox",
|
|
1554
|
+
access: serverOnly,
|
|
1555
|
+
admin: { hidden: true }
|
|
1556
|
+
},
|
|
1368
1557
|
{
|
|
1369
1558
|
name: "keyLast4",
|
|
1370
1559
|
type: "text",
|
|
@@ -1527,12 +1716,12 @@ async function translateDocument(payload, options) {
|
|
|
1527
1716
|
if (!localization) throw new Error("translateDocument: the Payload config has no localization");
|
|
1528
1717
|
const state = readState(payload.config);
|
|
1529
1718
|
const given = options.translator ?? state?.translator;
|
|
1530
|
-
const settings = given && options.site ? void 0 : await readTranslationSettings(payload, state?.site);
|
|
1719
|
+
const settings = given && options.site && options.locale !== void 0 ? void 0 : await readTranslationSettings(payload, state?.site);
|
|
1531
1720
|
const translator = given ?? settingsTranslator(payload, settings);
|
|
1532
1721
|
const kind = options.kind ?? "manual";
|
|
1533
1722
|
const sourceLocale = localization.defaultLocale;
|
|
1534
1723
|
const codes = localeCodes(localization);
|
|
1535
|
-
const targets = options.locale === void 0 ? codes.filter((code) => code !== sourceLocale) : typeof options.locale === "string" ? [options.locale] : [...options.locale];
|
|
1724
|
+
const targets = options.locale === void 0 ? settings?.languages ?? codes.filter((code) => code !== sourceLocale) : typeof options.locale === "string" ? [options.locale] : [...options.locale];
|
|
1536
1725
|
for (const locale of targets) if (locale === sourceLocale || !codes.includes(locale)) throw new Error(`translateDocument: "${locale}" is not a target locale`);
|
|
1537
1726
|
const schema = schemaFor(payload, options);
|
|
1538
1727
|
const { req, user } = options;
|
|
@@ -1784,12 +1973,13 @@ function translateNowEndpoint(slug) {
|
|
|
1784
1973
|
if (!state) return Response.json({ error: "Translation is not set up on this site." }, { status: 503 });
|
|
1785
1974
|
const settings = await readTranslationSettings(req.payload, state.site);
|
|
1786
1975
|
if (!settings.enabled) return Response.json({ error: "Translation is switched off in Settings → Translation." }, { status: 409 });
|
|
1976
|
+
if (settings.languages.length === 0) return Response.json({ error: "No language is ticked in Settings → Translation." }, { status: 409 });
|
|
1787
1977
|
const translator = state.translator ?? settingsTranslator(req.payload, settings);
|
|
1788
1978
|
if (!isTranslatorConfigured(translator)) return Response.json({ error: "Translation has no API key here." }, { status: 503 });
|
|
1789
1979
|
const id = req.routeParams?.id;
|
|
1790
1980
|
if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Missing document id" }, { status: 400 });
|
|
1791
1981
|
const locale = req.searchParams?.get("locale") || void 0;
|
|
1792
|
-
if (locale !== void 0 && !
|
|
1982
|
+
if (locale !== void 0 && !settings.languages.includes(locale)) return Response.json({ error: `"${locale}" is not a locale this site translates into.` }, { status: 400 });
|
|
1793
1983
|
if (!await canUpdate(req, slug, String(id))) return Response.json({ error: "You are not allowed to update this document." }, { status: 403 });
|
|
1794
1984
|
let results;
|
|
1795
1985
|
try {
|
|
@@ -1843,7 +2033,10 @@ function translationAvailableEndpoint() {
|
|
|
1843
2033
|
if (!state) return Response.json({ available: false });
|
|
1844
2034
|
const settings = await readTranslationSettings(req.payload, state.site);
|
|
1845
2035
|
const translator = state.translator ?? settingsTranslator(req.payload, settings);
|
|
1846
|
-
return Response.json({
|
|
2036
|
+
return Response.json({
|
|
2037
|
+
available: settings.enabled && settings.languages.length > 0 && isTranslatorConfigured(translator),
|
|
2038
|
+
languages: settings.languages
|
|
2039
|
+
});
|
|
1847
2040
|
}
|
|
1848
2041
|
};
|
|
1849
2042
|
}
|
|
@@ -2072,9 +2265,11 @@ async function afterSourceChange(args) {
|
|
|
2072
2265
|
const { payload } = req;
|
|
2073
2266
|
let previous;
|
|
2074
2267
|
let translator;
|
|
2268
|
+
let targets;
|
|
2075
2269
|
try {
|
|
2076
2270
|
const settings = await readTranslationSettings(payload, state.site);
|
|
2077
|
-
if (!settings.enabled) return {};
|
|
2271
|
+
if (!settings.enabled || settings.languages.length === 0) return {};
|
|
2272
|
+
targets = settings.languages;
|
|
2078
2273
|
if (drafted && status === "draft") previous = null;
|
|
2079
2274
|
else if (drafted) previous = (await draftedTranslationDecision({
|
|
2080
2275
|
req,
|
|
@@ -2106,7 +2301,7 @@ async function afterSourceChange(args) {
|
|
|
2106
2301
|
} : { global: slug },
|
|
2107
2302
|
previous,
|
|
2108
2303
|
translator,
|
|
2109
|
-
locale:
|
|
2304
|
+
locale: targets,
|
|
2110
2305
|
kind: "auto",
|
|
2111
2306
|
...user ? { user } : {}
|
|
2112
2307
|
}));
|
|
@@ -2391,12 +2586,17 @@ function withGlobal(global) {
|
|
|
2391
2586
|
* and endpoints are added once, and each entity is hooked once, so a second
|
|
2392
2587
|
* pass only picks up entities a later plugin registered.
|
|
2393
2588
|
*
|
|
2394
|
-
*
|
|
2395
|
-
*
|
|
2589
|
+
* It also puts every library language (`LIBRARY_LOCALES`) into the
|
|
2590
|
+
* config's `localization`, adding it when the site has none, so every site
|
|
2591
|
+
* carries every language in its schema. A target language is translated
|
|
2592
|
+
* and served only once it is ticked on the screen (`activeLocales`).
|
|
2396
2593
|
*/
|
|
2397
2594
|
function applyTranslation(config, options = {}) {
|
|
2398
2595
|
const prior = readState(config);
|
|
2399
|
-
const
|
|
2596
|
+
const custom = config.custom ?? {};
|
|
2597
|
+
const siteDefault = config.localization ? config.localization.defaultLocale : void 0;
|
|
2598
|
+
const defaultActive = custom["bisonDefaultActiveLocales"] ?? localeCodes(config.localization).filter((code) => code !== siteDefault);
|
|
2599
|
+
const localization = withLibraryLocales(config.localization);
|
|
2400
2600
|
const codes = localeCodes(localization);
|
|
2401
2601
|
const sourceLocale = localization ? localization.defaultLocale : "en";
|
|
2402
2602
|
const targetLocales = codes.filter((code) => code !== sourceLocale);
|
|
@@ -2429,7 +2629,8 @@ function applyTranslation(config, options = {}) {
|
|
|
2429
2629
|
...config.globals ?? [],
|
|
2430
2630
|
...hasGlobal("translation-settings") ? [] : [translationSettingsGlobal({
|
|
2431
2631
|
site,
|
|
2432
|
-
targetLocales
|
|
2632
|
+
targetLocales,
|
|
2633
|
+
defaultActive
|
|
2433
2634
|
})],
|
|
2434
2635
|
...hasGlobal("translation-state") ? [] : [translationStateGlobal()]
|
|
2435
2636
|
].map((global) => {
|
|
@@ -2446,16 +2647,19 @@ function applyTranslation(config, options = {}) {
|
|
|
2446
2647
|
const hasEndpoints = endpoints.some((endpoint) => endpoint.path === "/translation/status");
|
|
2447
2648
|
return {
|
|
2448
2649
|
...config,
|
|
2650
|
+
localization,
|
|
2449
2651
|
custom: {
|
|
2450
|
-
...
|
|
2451
|
-
[AUTO_TRANSLATE_STATE]: state
|
|
2652
|
+
...custom,
|
|
2653
|
+
[AUTO_TRANSLATE_STATE]: state,
|
|
2654
|
+
[DEFAULT_ACTIVE_LOCALES]: defaultActive
|
|
2452
2655
|
},
|
|
2453
2656
|
collections,
|
|
2454
2657
|
globals,
|
|
2455
2658
|
endpoints: hasEndpoints ? endpoints : [
|
|
2456
2659
|
...endpoints,
|
|
2457
2660
|
...translationSettingsEndpoints(options.endpoints),
|
|
2458
|
-
translationAvailableEndpoint()
|
|
2661
|
+
translationAvailableEndpoint(),
|
|
2662
|
+
activeLocalesEndpoint()
|
|
2459
2663
|
]
|
|
2460
2664
|
};
|
|
2461
2665
|
}
|
|
@@ -2463,7 +2667,19 @@ function applyTranslation(config, options = {}) {
|
|
|
2463
2667
|
function translation(options = {}) {
|
|
2464
2668
|
return (config) => applyTranslation(config, options);
|
|
2465
2669
|
}
|
|
2670
|
+
/**
|
|
2671
|
+
* `GET /api/translation/locales`: the site's active languages, public and
|
|
2672
|
+
* cacheable for a minute, for middleware that cannot load Payload (an edge
|
|
2673
|
+
* runtime). Node middleware calls `activeLocales(payload)` directly.
|
|
2674
|
+
*/
|
|
2675
|
+
function activeLocalesEndpoint() {
|
|
2676
|
+
return {
|
|
2677
|
+
path: "/translation/locales",
|
|
2678
|
+
method: "get",
|
|
2679
|
+
handler: async (req) => Response.json(await activeLocales(req.payload), { headers: { "Cache-Control": "public, max-age=60, s-maxage=60" } })
|
|
2680
|
+
};
|
|
2681
|
+
}
|
|
2466
2682
|
//#endregion
|
|
2467
|
-
export {
|
|
2683
|
+
export { hasRole as $, isFeatureSlug as $t, activeLocales as A, featureCatalogue as At, allowedFeaturesForUser as B, THEME_FEATURE_SLUGS as Bt, resolveModel as C, resetRolesMatrix as Ct, LIBRARY_LOCALES as D, validateRolesMatrix as Dt, LIBRARY_DEFAULT_LOCALE as E, seedRoleRows as Et, encryptApiKey as F, CAPABILITIES as Ft, authenticatedOrPublished as G, sanitizeRoleNameInput as Gt, getFeaturesMatrix as H, isRoleName as Ht, resolveApiKey as I, CAPABILITY_FEATURES as It, canPublish as J, FEATURE_GROUPS as Jt, canManageBrand as K, slugifyRoleName as Kt, collectLocalizedStrings as L, DEFAULT_ROLE_GRANTS as Lt, invalidateActiveLocales as M, parseFeaturesMatrix as Mt, withLibraryLocales as N, stampFeatureCatalogue as Nt, LIBRARY_LOCALE_CODES as O, MISSING_PACKAGE_FEATURES_MESSAGE as Ot, decryptApiKey as P, validateFeaturesMatrix as Pt, hasGrant as Q, isFeatureGroupId as Qt, sameRow as R, ROLES as Rt, readTranslationSettings as S, parseRolesMatrix as St, ACTIVE_LOCALES_CACHE_MS as T, roleSelectOptions as Tt, hasFeature as U, isRoleSlug as Ut, canUseFeature as V, isRole as Vt, hideUnlessFeature as W, roleLabel as Wt, getRolesMatrix as X, PACKAGE_FEATURES as Xt, developerOnlyAccess as Y, FEATURE_GROUP_LABELS as Yt, hasCapability as Z, PACKAGE_FEATURE_SLUGS as Zt, TRANSLATION_GRANT as _, ROLES_SLUG as _t, isAutosave as a, isDeveloperTab as at, TRANSLATION_STATE_SLUG as b, grantsFromStoredRole as bt, shouldSkipDraftedTranslation as c, DEFAULT_ROLE_MATRIX as ct, runAfterCommit as d, DUPLICATE_ROLE_SLUG_MESSAGE as dt, isLockedFeature as en, hideUnlessDeveloper as et, TRANSLATE_NOW as f, INVALID_ROLE_NAME_MESSAGE as ft, withTranslator as g, ROLES_GLOBAL_DESCRIPTION as gt, readTranslateState as h, ROLES_FIELD_DESCRIPTION as ht, translationSettingsEndpoints as i, isDeveloper as it, inactiveLocaleRedirect as j, featureGroupLabel as jt, activeAlternates as k, defaultFeaturesFieldValue as kt, shouldSkipUndraftedTranslation as l, DEVELOPER_DESCRIPTION as lt, BISON_TRANSLATION_CONTEXT as m, MISSING_SEED_ROLES_MESSAGE as mt, hasLocalizedFields as n, isAdminOrSelf as nt, draftedTranslationDecision as o, isPrivilegedRole as ot, translateDocument as p, LAST_USERS_TICK_MESSAGE as pt, canManageContent as q, FEATURES_SLUG as qt, translation as r, isAuthenticated as rt, localizedCopyUnchanged as s, storedRoles as st, applyTranslation as t, isPackageFeatureSlug as tn, isAdmin as tt, TRANSACTION_TIMEOUT_MS as u, DUPLICATE_ROLE_NAME_MESSAGE as ut, TRANSLATION_KEY_PANEL as v, applyRoleSlugsFromNames as vt, siteFromInstructions as w, roleDescription as wt, invalidateTranslationSettings as x, normalizeStoredRoles as xt, TRANSLATION_SETTINGS_SLUG as y, defaultRolesFieldValue as yt, translationJob as z, ROLE_LABELS as zt };
|
|
2468
2684
|
|
|
2469
|
-
//# sourceMappingURL=capability-
|
|
2685
|
+
//# sourceMappingURL=capability-DHPE2kon.mjs.map
|