@bison-lab/payload-core 4.39.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -33
- package/dist/admin.d.mts +19 -7
- package/dist/admin.d.mts.map +1 -1
- package/dist/admin.mjs +229 -16
- package/dist/admin.mjs.map +1 -1
- package/dist/block-library.d.mts +1 -1
- package/dist/block-library.mjs +1 -1
- package/dist/{block-thumbnails-DXOUzGjY.mjs → block-thumbnails-DC34uFtE.mjs} +1 -1
- package/dist/{block-thumbnails-DXOUzGjY.mjs.map → block-thumbnails-DC34uFtE.mjs.map} +1 -1
- package/dist/block-thumbnails-cli.mjs +1 -1
- package/dist/block-thumbnails.mjs +1 -1
- package/dist/capability-CqdYCzG1.d.mts +434 -0
- package/dist/capability-CqdYCzG1.d.mts.map +1 -0
- package/dist/capability-DHPE2kon.mjs +2685 -0
- package/dist/capability-DHPE2kon.mjs.map +1 -0
- package/dist/{catalogue-FxH10X3v.d.mts → catalogue-DWqHWVE5.d.mts} +1 -1
- package/dist/{catalogue-FxH10X3v.d.mts.map → catalogue-DWqHWVE5.d.mts.map} +1 -1
- package/dist/{facet-field-DjaZ0C7D.d.mts → facet-field-2K22iuWA.d.mts} +1 -1
- package/dist/{facet-field-DjaZ0C7D.d.mts.map → facet-field-2K22iuWA.d.mts.map} +1 -1
- package/dist/{facet-field-Uf8S4yL1.mjs → facet-field-DO3VT_Cz.mjs} +1 -1
- package/dist/{facet-field-Uf8S4yL1.mjs.map → facet-field-DO3VT_Cz.mjs.map} +1 -1
- package/dist/index.d.mts +13 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +25 -667
- package/dist/index.mjs.map +1 -1
- package/dist/{locale-CFWfB4wP.mjs → locale-B6rUVwpg.mjs} +1 -1
- package/dist/locale-B6rUVwpg.mjs.map +1 -0
- package/dist/{locale-CWiIcGuU.d.mts → locale-CTT3nn6T.d.mts} +5 -4
- package/dist/locale-CTT3nn6T.d.mts.map +1 -0
- package/dist/messages-dZV_aAnR.mjs +93 -0
- package/dist/messages-dZV_aAnR.mjs.map +1 -0
- package/dist/metadata.d.mts +1 -1
- package/dist/navigation.d.mts +2 -2
- package/dist/navigation.mjs +1 -1
- package/dist/og.d.mts +2 -2
- package/dist/og.mjs +1 -1
- package/dist/{preview-CNBVfmM7.d.mts → preview-1vwxBgm5.d.mts} +2 -2
- package/dist/{preview-CNBVfmM7.d.mts.map → preview-1vwxBgm5.d.mts.map} +1 -1
- package/dist/{published-_1rrTj_B.d.mts → published-B3etM6X5.d.mts} +3 -3
- package/dist/{published-_1rrTj_B.d.mts.map → published-B3etM6X5.d.mts.map} +1 -1
- package/dist/{published-D3yVnbxs.mjs → published-BMt7Z5CF.mjs} +2 -2
- package/dist/{published-D3yVnbxs.mjs.map → published-BMt7Z5CF.mjs.map} +1 -1
- package/dist/{published-DefZv9na.mjs → published-CkqqY08H.mjs} +2 -2
- package/dist/{published-DefZv9na.mjs.map → published-CkqqY08H.mjs.map} +1 -1
- package/dist/{published-DXjnElZn.d.mts → published-QDNmDi02.d.mts} +2 -2
- package/dist/{published-DXjnElZn.d.mts.map → published-QDNmDi02.d.mts.map} +1 -1
- package/dist/{published-QyTcDznE.mjs → published-hqtvmVUD.mjs} +1 -1
- package/dist/{published-QyTcDznE.mjs.map → published-hqtvmVUD.mjs.map} +1 -1
- package/dist/{root-page-key-B86JwL8Z.mjs → root-page-key-kx3C1eyp.mjs} +1 -1
- package/dist/{root-page-key-B86JwL8Z.mjs.map → root-page-key-kx3C1eyp.mjs.map} +1 -1
- package/dist/seo.mjs +1 -1
- package/dist/{messages-Fl1spIwN.mjs → strings-Fd7kUCT7.mjs} +156 -118
- package/dist/strings-Fd7kUCT7.mjs.map +1 -0
- package/dist/taxonomy.d.mts +1 -1
- package/dist/taxonomy.mjs +1 -1
- package/dist/theme.d.mts +4 -4
- package/dist/theme.mjs +1 -1
- package/dist/{title-D_jixG36.d.mts → title-trhUexxM.d.mts} +1 -1
- package/dist/{title-D_jixG36.d.mts.map → title-trhUexxM.d.mts.map} +1 -1
- package/dist/translate-messages-cli.mjs +3 -2
- package/dist/translate-messages-cli.mjs.map +1 -1
- package/dist/translate.d.mts +300 -206
- package/dist/translate.d.mts.map +1 -1
- package/dist/translate.mjs +225 -1027
- package/dist/translate.mjs.map +1 -1
- package/dist/{types-Db6Iy3hJ.d.mts → types-DLBlHZUd.d.mts} +1 -1
- package/dist/{types-Db6Iy3hJ.d.mts.map → types-DLBlHZUd.d.mts.map} +1 -1
- package/dist/{wireframe-xcJNJzBf.mjs → wireframe-CXorKFU_.mjs} +1 -1
- package/dist/{wireframe-xcJNJzBf.mjs.map → wireframe-CXorKFU_.mjs.map} +1 -1
- package/dist/wireframe-cli.mjs +1 -1
- package/dist/wireframe.mjs +1 -1
- package/package.json +6 -8
- package/dist/locale-CFWfB4wP.mjs.map +0 -1
- package/dist/locale-CWiIcGuU.d.mts.map +0 -1
- package/dist/messages-Fl1spIwN.mjs.map +0 -1
package/dist/translate.mjs
CHANGED
|
@@ -1,1071 +1,269 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
function isHidden(field) {
|
|
8
|
-
return field.hidden === true || field.admin?.hidden === true;
|
|
9
|
-
}
|
|
10
|
-
function blocksOf(field, configBlocks) {
|
|
11
|
-
const own = field.blocks ?? [];
|
|
12
|
-
const referenced = (field.blockReferences ?? []).flatMap((ref) => {
|
|
13
|
-
if (typeof ref !== "string") return [ref];
|
|
14
|
-
const found = configBlocks?.find((block) => block.slug === ref);
|
|
15
|
-
return found ? [found] : [];
|
|
16
|
-
});
|
|
17
|
-
return [...own, ...referenced];
|
|
1
|
+
import { A as activeLocales, C as resolveModel, D as LIBRARY_LOCALES, E as LIBRARY_DEFAULT_LOCALE, F as encryptApiKey, I as resolveApiKey, L as collectLocalizedStrings, M as invalidateActiveLocales, N as withLibraryLocales, O as LIBRARY_LOCALE_CODES, P as decryptApiKey, R as sameRow, S as readTranslationSettings, T as ACTIVE_LOCALES_CACHE_MS, _ as TRANSLATION_GRANT, a as isAutosave, b as TRANSLATION_STATE_SLUG, c as shouldSkipDraftedTranslation, d as runAfterCommit, f as TRANSLATE_NOW, g as withTranslator, h as readTranslateState, i as translationSettingsEndpoints, j as inactiveLocaleRedirect, k as activeAlternates, l as shouldSkipUndraftedTranslation, m as BISON_TRANSLATION_CONTEXT, n as hasLocalizedFields, o as draftedTranslationDecision, p as translateDocument, r as translation, s as localizedCopyUnchanged, t as applyTranslation, u as TRANSACTION_TIMEOUT_MS, v as TRANSLATION_KEY_PANEL, w as siteFromInstructions, x as invalidateTranslationSettings, y as TRANSLATION_SETTINGS_SLUG, z as translationJob } from "./capability-DHPE2kon.mjs";
|
|
2
|
+
import { a as TRANSLATE_MODEL_PRICES, c as estimateCost, d as translationSystemPrompt, f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, l as modelPrice, n as translateStrings, o as anthropicTranslator, p as classifyAnthropicError, r as DEFAULT_TRANSLATE_MODEL, s as containsWord, t as isTranslatorConfigured, u as parseJsonArray } from "./strings-Fd7kUCT7.mjs";
|
|
3
|
+
import { t as fillMessages } from "./messages-dZV_aAnR.mjs";
|
|
4
|
+
//#region src/translate/plugin.ts
|
|
5
|
+
function hints(list) {
|
|
6
|
+
return (list ?? []).map((entry) => typeof entry === "string" ? [entry, {}] : [entry.slug, entry.context ? { context: entry.context } : {}]);
|
|
18
7
|
}
|
|
19
8
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
9
|
+
* @deprecated Every site now has translation through `adminNav()` (or
|
|
10
|
+
* `translation()`), switched on by an Admin in Settings → Translation, and
|
|
11
|
+
* it covers every collection and global with localized fields. This keeps
|
|
12
|
+
* an existing `autoTranslate({ ... })` line working: `enabled: false`
|
|
13
|
+
* returns the config untouched; `enabled: true` applies the capability with
|
|
14
|
+
* its `site` (the instructions' first values), `waitUntil`, the listed
|
|
15
|
+
* entities' `context` hints, and `translator`, which then replaces the
|
|
16
|
+
* screen's key and model (tests). The listed slugs must exist. The screen's
|
|
17
|
+
* switch governs it either way.
|
|
29
18
|
*/
|
|
30
|
-
function
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const visit = (node, path) => {
|
|
41
|
-
if (node.type === "text" && typeof node.text === "string") out.push({
|
|
42
|
-
path,
|
|
43
|
-
node
|
|
44
|
-
});
|
|
45
|
-
const children = node.children;
|
|
46
|
-
if (Array.isArray(children)) children.forEach((child, index) => {
|
|
47
|
-
if (isDoc(child)) visit(child, `${path}.${index}`);
|
|
19
|
+
function autoTranslate(options) {
|
|
20
|
+
return (config) => {
|
|
21
|
+
if (!options.enabled) return config;
|
|
22
|
+
for (const [slug] of hints(options.collections)) if (!config.collections?.some((collection) => collection.slug === slug)) throw new Error(`autoTranslate: no collection "${slug}" in the config`);
|
|
23
|
+
for (const [slug] of hints(options.globals)) if (!config.globals?.some((global) => global.slug === slug)) throw new Error(`autoTranslate: no global "${slug}" in the config`);
|
|
24
|
+
return applyTranslation(config, {
|
|
25
|
+
translator: options.translator,
|
|
26
|
+
...options.site ? { site: options.site } : {},
|
|
27
|
+
...options.waitUntil ? { waitUntil: options.waitUntil } : {},
|
|
28
|
+
hints: Object.fromEntries([...hints(options.collections), ...hints(options.globals)])
|
|
48
29
|
});
|
|
49
30
|
};
|
|
50
|
-
visit(state.root, "root");
|
|
51
|
-
return out;
|
|
52
31
|
}
|
|
53
|
-
|
|
54
|
-
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/translate/migrate-locales.ts
|
|
55
34
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* changed; the path keeps a string moved from one field to another from
|
|
59
|
-
* reading as unchanged.
|
|
35
|
+
* Splits generated SQL into statements at a `;` that ends a line, keeping a
|
|
36
|
+
* `DO $$ ... $$;` block whole.
|
|
60
37
|
*/
|
|
61
|
-
function
|
|
38
|
+
function splitStatements(text) {
|
|
62
39
|
const out = [];
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
case "tabs":
|
|
73
|
-
for (const tab of field.tabs ?? []) if (tab.name) {
|
|
74
|
-
const nested = value[tab.name];
|
|
75
|
-
if (isDoc(nested)) collectFields(tab.fields, nested, `${prefix}${tab.name}.`, inLocalized || tab.localized === true, configBlocks, out);
|
|
76
|
-
} else collectFields(tab.fields, value, prefix, inLocalized, configBlocks, out);
|
|
77
|
-
break;
|
|
78
|
-
case "row":
|
|
79
|
-
case "collapsible":
|
|
80
|
-
collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);
|
|
81
|
-
break;
|
|
82
|
-
case "group":
|
|
83
|
-
if (!field.name) collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);
|
|
84
|
-
else if (isDoc(value[field.name])) collectFields(field.fields ?? [], value[field.name], `${path}.`, localized, configBlocks, out);
|
|
85
|
-
break;
|
|
86
|
-
case "array":
|
|
87
|
-
if (!field.name) break;
|
|
88
|
-
(asRows(value[field.name]) ?? []).forEach((row, index) => {
|
|
89
|
-
const key = typeof row.id === "string" && !localized ? row.id : String(index);
|
|
90
|
-
collectFields(field.fields ?? [], row, `${path}.${key}.`, localized, configBlocks, out);
|
|
91
|
-
});
|
|
92
|
-
break;
|
|
93
|
-
case "blocks": {
|
|
94
|
-
if (!field.name) break;
|
|
95
|
-
const blocks = blocksOf(field, configBlocks);
|
|
96
|
-
(asRows(value[field.name]) ?? []).forEach((row, index) => {
|
|
97
|
-
const block = blocks.find((candidate) => candidate.slug === row.blockType);
|
|
98
|
-
if (!block) return;
|
|
99
|
-
const key = typeof row.id === "string" && !localized ? row.id : String(index);
|
|
100
|
-
collectFields(block.fields, row, `${path}.${key}.`, localized, configBlocks, out);
|
|
101
|
-
});
|
|
102
|
-
break;
|
|
103
|
-
}
|
|
104
|
-
case "text":
|
|
105
|
-
case "textarea":
|
|
106
|
-
if (localized && field.name && !field.hasMany && filled(value[field.name])) out.push(`${path}=${value[field.name]}`);
|
|
107
|
-
break;
|
|
108
|
-
case "richText":
|
|
109
|
-
if (localized && field.name) {
|
|
110
|
-
for (const ref of textNodes(value[field.name]) ?? []) if (filled(ref.node.text)) out.push(`${path}:${ref.path}=${ref.node.text}`);
|
|
111
|
-
}
|
|
112
|
-
break;
|
|
113
|
-
default: break;
|
|
40
|
+
let current = [];
|
|
41
|
+
let inDollar = false;
|
|
42
|
+
for (const line of text.split("\n")) {
|
|
43
|
+
if (line.trim() === "" && current.length === 0) continue;
|
|
44
|
+
current.push(line);
|
|
45
|
+
if ((line.match(/\$\$/g)?.length ?? 0) % 2 === 1) inDollar = !inDollar;
|
|
46
|
+
if (!inDollar && /;\s*$/.test(line)) {
|
|
47
|
+
out.push(current.join("\n").trim());
|
|
48
|
+
current = [];
|
|
114
49
|
}
|
|
115
50
|
}
|
|
51
|
+
const rest = current.join("\n").trim();
|
|
52
|
+
if (rest) out.push(rest);
|
|
53
|
+
return out;
|
|
116
54
|
}
|
|
55
|
+
const DROP_COLUMN = /^ALTER TABLE\s+(?:"[^"]+"\.)?"([^"]+)"\s+DROP COLUMN\s+(?:IF EXISTS\s+)?"([^"]+)"/i;
|
|
56
|
+
const DROP_TYPE = /^DROP TYPE\b/i;
|
|
57
|
+
/** The bare name of a type in `DROP TYPE` / `CREATE TYPE` (`"public"."enum_x"` → `enum_x`). */
|
|
58
|
+
const TYPE_NAME = /^(?:DROP|CREATE) TYPE\s+(?:IF EXISTS\s+)?(?:"[^"]+"\.)?"?([^"\s(]+)"?/i;
|
|
59
|
+
const ADD_LOCALE = /^ALTER TABLE\s+(?:"[^"]+"\.)?"([^"]+)"\s+ADD COLUMN\s+"locale"\s/i;
|
|
117
60
|
/**
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
* target it already has, so a string a person corrected by hand in the
|
|
122
|
-
* target locale survives every later publish that does not touch its
|
|
123
|
-
* source.
|
|
124
|
-
*/
|
|
125
|
-
function wants(ctx, source, existing, before) {
|
|
126
|
-
if (!filled(source)) return false;
|
|
127
|
-
if (ctx.overwrite || !filled(existing)) return true;
|
|
128
|
-
return ctx.hasPrevious && source !== before;
|
|
129
|
-
}
|
|
130
|
-
function enqueue(ctx, source, set) {
|
|
131
|
-
ctx.sources.push(source);
|
|
132
|
-
ctx.setters.push(set);
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* What to translate in one target locale, or `null` when the target is
|
|
136
|
-
* already in step with the source.
|
|
137
|
-
*
|
|
138
|
-
* - `source`: the document in the source locale, read at depth 0 so
|
|
139
|
-
* uploads are ids and array rows carry their real ids.
|
|
140
|
-
* - `target`: the document in the target locale, read with
|
|
141
|
-
* `fallbackLocale: false`. With fallback on, a blank target reads as the
|
|
142
|
-
* source, looks "already translated", and nothing is ever written.
|
|
143
|
-
* - `previous`: the source as it was before this change (the last
|
|
144
|
-
* published version, or the hook's `previousDoc` on a collection without
|
|
145
|
-
* drafts). `null` or omitted: there is none.
|
|
146
|
-
*
|
|
147
|
-
* The write carries only the top-level fields that hold a translated
|
|
148
|
-
* string. Inside them it is built from the source's structure (so
|
|
149
|
-
* non-localized values such as links and images are kept, and each array
|
|
150
|
-
* row keeps the source row's id, which is how Payload lands the target copy
|
|
151
|
-
* on the right row), with every localized string set to its translation or
|
|
152
|
-
* to the target copy it already had.
|
|
153
|
-
*/
|
|
154
|
-
function translationJob(input) {
|
|
155
|
-
const ctx = {
|
|
156
|
-
overwrite: input.overwrite === true,
|
|
157
|
-
hasPrevious: input.previous != null,
|
|
158
|
-
configBlocks: input.schema.blocks,
|
|
159
|
-
sources: [],
|
|
160
|
-
setters: []
|
|
161
|
-
};
|
|
162
|
-
const out = {};
|
|
163
|
-
const touched = planFields(input.schema.fields, input.source, input.target ?? void 0, input.previous ?? void 0, out, ctx, false);
|
|
164
|
-
if (ctx.sources.length === 0) return null;
|
|
165
|
-
return {
|
|
166
|
-
sources: ctx.sources,
|
|
167
|
-
patch: (translated) => {
|
|
168
|
-
translated.forEach((value, index) => ctx.setters[index]?.(value));
|
|
169
|
-
const data = {};
|
|
170
|
-
for (const name of touched) data[name] = out[name];
|
|
171
|
-
return data;
|
|
172
|
-
}
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Walks `fields` over one level of the source, writing into `out` (which
|
|
177
|
-
* starts as a copy of the source level) and returning the names at this
|
|
178
|
-
* level that hold a string being translated.
|
|
179
|
-
*/
|
|
180
|
-
function planFields(fields, source, target, previous, out, ctx, inLocalized) {
|
|
181
|
-
const touched = /* @__PURE__ */ new Set();
|
|
182
|
-
const nested = (name, subFields, localized) => {
|
|
183
|
-
const value = source[name];
|
|
184
|
-
if (!isDoc(value)) return;
|
|
185
|
-
const copy = { ...value };
|
|
186
|
-
const prevValue = previous?.[name];
|
|
187
|
-
const targetValue = target?.[name];
|
|
188
|
-
const inner = planFields(subFields, value, isDoc(targetValue) ? targetValue : void 0, isDoc(prevValue) ? prevValue : void 0, copy, ctx, localized);
|
|
189
|
-
out[name] = copy;
|
|
190
|
-
if (inner.size > 0) touched.add(name);
|
|
191
|
-
};
|
|
192
|
-
for (const field of fields) {
|
|
193
|
-
if (isHidden(field)) continue;
|
|
194
|
-
const localized = inLocalized || field.localized === true;
|
|
195
|
-
switch (field.type) {
|
|
196
|
-
case "tabs":
|
|
197
|
-
for (const tab of field.tabs ?? []) if (tab.name) nested(tab.name, tab.fields, inLocalized || tab.localized === true);
|
|
198
|
-
else for (const name of planFields(tab.fields, source, target, previous, out, ctx, inLocalized)) touched.add(name);
|
|
199
|
-
break;
|
|
200
|
-
case "row":
|
|
201
|
-
case "collapsible":
|
|
202
|
-
for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) touched.add(name);
|
|
203
|
-
break;
|
|
204
|
-
case "group":
|
|
205
|
-
if (field.name) nested(field.name, field.fields ?? [], localized);
|
|
206
|
-
else for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) touched.add(name);
|
|
207
|
-
break;
|
|
208
|
-
case "array":
|
|
209
|
-
case "blocks": {
|
|
210
|
-
if (!field.name) break;
|
|
211
|
-
const rows = asRows(source[field.name]);
|
|
212
|
-
if (!rows) break;
|
|
213
|
-
const targetRows = asRows(target?.[field.name]);
|
|
214
|
-
const previousRows = asRows(previous?.[field.name]);
|
|
215
|
-
const blocks = field.type === "blocks" ? blocksOf(field, ctx.configBlocks) : [];
|
|
216
|
-
let any = false;
|
|
217
|
-
out[field.name] = rows.map((row, index) => {
|
|
218
|
-
const rowFields = field.type === "blocks" ? blocks.find((block) => block.slug === row.blockType)?.fields : field.fields;
|
|
219
|
-
const copy = { ...row };
|
|
220
|
-
if (localized) delete copy.id;
|
|
221
|
-
if (!rowFields) return copy;
|
|
222
|
-
if (planFields(rowFields, row, sameRow(targetRows, row, index, localized), sameRow(previousRows, row, index), copy, ctx, localized).size > 0) any = true;
|
|
223
|
-
return copy;
|
|
224
|
-
});
|
|
225
|
-
if (any) touched.add(field.name);
|
|
226
|
-
break;
|
|
227
|
-
}
|
|
228
|
-
case "text":
|
|
229
|
-
case "textarea": {
|
|
230
|
-
if (!localized || !field.name || field.hasMany) break;
|
|
231
|
-
const name = field.name;
|
|
232
|
-
const value = source[name];
|
|
233
|
-
const existing = target?.[name];
|
|
234
|
-
if (wants(ctx, value, existing, previous?.[name])) {
|
|
235
|
-
enqueue(ctx, value, (translated) => out[name] = translated);
|
|
236
|
-
out[name] = value;
|
|
237
|
-
touched.add(name);
|
|
238
|
-
} else out[name] = filled(existing) ? existing : value;
|
|
239
|
-
break;
|
|
240
|
-
}
|
|
241
|
-
case "richText": {
|
|
242
|
-
if (!localized || !field.name) break;
|
|
243
|
-
const name = field.name;
|
|
244
|
-
const result = planRichText(ctx, source[name], target?.[name], previous?.[name]);
|
|
245
|
-
out[name] = result.value;
|
|
246
|
-
if (result.touched) touched.add(name);
|
|
247
|
-
break;
|
|
248
|
-
}
|
|
249
|
-
default: break;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
return touched;
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Rich text is translated per Lexical text node (sentence context across
|
|
256
|
-
* formatting runs is out of scope). When the target tree has the same
|
|
257
|
-
* shape as the source, each node follows the per-string rule. When a
|
|
258
|
-
* person restructured the target (split a run to bold a word), node paths
|
|
259
|
-
* no longer pair: the field is then kept whole unless its source changed,
|
|
260
|
-
* in which case it is rebuilt from the source and every node translated.
|
|
261
|
-
*/
|
|
262
|
-
function planRichText(ctx, source, target, previous) {
|
|
263
|
-
const sourceNodes = textNodes(source);
|
|
264
|
-
if (!sourceNodes || !sourceNodes.some((ref) => filled(ref.node.text))) return {
|
|
265
|
-
value: target ?? source,
|
|
266
|
-
touched: false
|
|
267
|
-
};
|
|
268
|
-
const targetNodes = textNodes(target);
|
|
269
|
-
const previousNodes = textNodes(previous);
|
|
270
|
-
const clone = structuredClone(source);
|
|
271
|
-
const cloneNodes = textNodes(clone);
|
|
272
|
-
let touched = false;
|
|
273
|
-
if (sameShape(sourceNodes, targetNodes)) {
|
|
274
|
-
const previousPairs = sameShape(sourceNodes, previousNodes);
|
|
275
|
-
sourceNodes.forEach((ref, index) => {
|
|
276
|
-
const node = cloneNodes[index].node;
|
|
277
|
-
const existing = targetNodes[index].node.text;
|
|
278
|
-
const before = previousPairs ? previousNodes[index].node.text : void 0;
|
|
279
|
-
if (wants(ctx, ref.node.text, existing, before)) {
|
|
280
|
-
enqueue(ctx, ref.node.text, (translated) => node.text = translated);
|
|
281
|
-
touched = true;
|
|
282
|
-
} else if (filled(existing)) node.text = existing;
|
|
283
|
-
});
|
|
284
|
-
return {
|
|
285
|
-
value: clone,
|
|
286
|
-
touched
|
|
287
|
-
};
|
|
288
|
-
}
|
|
289
|
-
const targetFilled = targetNodes?.some((ref) => filled(ref.node.text)) ?? false;
|
|
290
|
-
if (!(ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
|
|
291
|
-
value: target,
|
|
292
|
-
touched: false
|
|
293
|
-
};
|
|
294
|
-
sourceNodes.forEach((ref, index) => {
|
|
295
|
-
if (!filled(ref.node.text)) return;
|
|
296
|
-
const node = cloneNodes[index].node;
|
|
297
|
-
enqueue(ctx, ref.node.text, (translated) => node.text = translated);
|
|
298
|
-
touched = true;
|
|
299
|
-
});
|
|
300
|
-
return {
|
|
301
|
-
value: clone,
|
|
302
|
-
touched
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
//#endregion
|
|
306
|
-
//#region src/translate/state.ts
|
|
307
|
-
/**
|
|
308
|
-
* Where an enabled plugin leaves its options for `translateDocument` and the
|
|
309
|
-
* endpoint to find. Root `config.custom` is server-only in Payload, so the
|
|
310
|
-
* translator never reaches the admin bundle.
|
|
311
|
-
*/
|
|
312
|
-
const AUTO_TRANSLATE_STATE = "bisonAutoTranslate";
|
|
313
|
-
function readState(config) {
|
|
314
|
-
return config.custom?.[AUTO_TRANSLATE_STATE];
|
|
315
|
-
}
|
|
316
|
-
/**
|
|
317
|
-
* The test seam: the plugin's state (translator, site, locales, listed
|
|
318
|
-
* collections and globals) on a config that went through `autoTranslate`,
|
|
319
|
-
* or `undefined` when the plugin is off or was not applied. Read it instead
|
|
320
|
-
* of reaching into `config.custom` by key.
|
|
321
|
-
*/
|
|
322
|
-
function readTranslateState(config) {
|
|
323
|
-
return readState(config);
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* The test seam: a copy of `config` whose plugin uses `translator` (a fake in
|
|
327
|
-
* a test) in place of the one it was registered with. The input is not
|
|
328
|
-
* changed. Throws when the config did not go through an enabled
|
|
329
|
-
* `autoTranslate`, so a test cannot silently translate nothing.
|
|
61
|
+
* A NOT NULL locale column added to a table that already has rows: `_locale`
|
|
62
|
+
* on a localized array or blocks table, or `locale` on a localized hasMany
|
|
63
|
+
* select's own table. Either would fail on the first existing row.
|
|
330
64
|
*/
|
|
331
|
-
|
|
332
|
-
const state = readState(config);
|
|
333
|
-
if (!state) throw new Error("withTranslator: the config has no autoTranslate state; is the plugin enabled?");
|
|
334
|
-
return {
|
|
335
|
-
...config,
|
|
336
|
-
custom: {
|
|
337
|
-
...config.custom,
|
|
338
|
-
[AUTO_TRANSLATE_STATE]: {
|
|
339
|
-
...state,
|
|
340
|
-
translator
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
/** The locale codes of a localization config, in order. */
|
|
346
|
-
function localeCodes(localization) {
|
|
347
|
-
if (!localization) return [];
|
|
348
|
-
return localization.locales.map((locale) => typeof locale === "string" ? locale : locale.code);
|
|
349
|
-
}
|
|
350
|
-
//#endregion
|
|
351
|
-
//#region src/translate/document.ts
|
|
352
|
-
function schemaFor(payload, options) {
|
|
353
|
-
if ("collection" in options) {
|
|
354
|
-
const collection = payload.collections[options.collection];
|
|
355
|
-
if (!collection) throw new Error(`translateDocument: no collection "${options.collection}"`);
|
|
356
|
-
return {
|
|
357
|
-
fields: collection.config.fields,
|
|
358
|
-
blocks: payload.config.blocks,
|
|
359
|
-
useAsTitle: collection.config.admin?.useAsTitle
|
|
360
|
-
};
|
|
361
|
-
}
|
|
362
|
-
const global = payload.config.globals.find((candidate) => candidate.slug === options.global);
|
|
363
|
-
if (!global) throw new Error(`translateDocument: no global "${options.global}"`);
|
|
364
|
-
return {
|
|
365
|
-
fields: global.fields,
|
|
366
|
-
blocks: payload.config.blocks
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
/** How many times a write is planned again because the source changed during the model call. */
|
|
370
|
-
const REPLANS = 2;
|
|
371
|
-
function defaultContext(slug, doc, useAsTitle) {
|
|
372
|
-
const meta = doc.meta;
|
|
373
|
-
const title = [
|
|
374
|
-
useAsTitle ? doc[useAsTitle] : void 0,
|
|
375
|
-
meta?.title,
|
|
376
|
-
doc.title,
|
|
377
|
-
doc.name
|
|
378
|
-
].find((value) => typeof value === "string" && value.trim() !== "");
|
|
379
|
-
return title ? `${slug}: ${title}` : slug;
|
|
380
|
-
}
|
|
65
|
+
const ADD_LOCALE_NOT_NULL = /^(ALTER TABLE\s+((?:"[^"]+"\.)?"[^"]+")\s+ADD COLUMN\s+"(_?locale)"\s+(\S+)\s+NOT NULL)(\s*;)$/i;
|
|
381
66
|
/**
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
* target copy a person may have corrected.
|
|
387
|
-
*
|
|
388
|
-
* Reads the source at depth 0 (uploads as ids, array rows with their real
|
|
389
|
-
* ids) and each target with `fallbackLocale: false`, sends one batch per
|
|
390
|
-
* target locale, and writes the target with `context: { autoTranslate:
|
|
391
|
-
* false }` so the write cannot start another round.
|
|
392
|
-
*
|
|
393
|
-
* Returns one result per target locale. A translator failure is a `failed`
|
|
394
|
-
* result and leaves that locale as it was; it only throws on Payload errors
|
|
395
|
-
* or a misconfiguration (no localization, no translator, unknown slug).
|
|
67
|
+
* Sorts statements into what runs before the copy and the drops that run
|
|
68
|
+
* after it. A `_locale NOT NULL` column added to an existing table (a
|
|
69
|
+
* localized array or blocks field) gets the default locale as a default
|
|
70
|
+
* while it is added, so existing rows are kept as that locale's.
|
|
396
71
|
*/
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
const
|
|
401
|
-
const
|
|
402
|
-
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
overrideAccess: false
|
|
412
|
-
} : { overrideAccess: true };
|
|
413
|
-
const versions = "collection" in options ? payload.collections[options.collection]?.config.versions : payload.config.globals.find((candidate) => candidate.slug === options.global)?.versions;
|
|
414
|
-
const hasDrafts = Boolean(versions && typeof versions === "object" && versions.drafts);
|
|
415
|
-
const drafted = user !== void 0 && user !== null && "collection" in options && hasDrafts;
|
|
416
|
-
let draftMode = false;
|
|
417
|
-
if (drafted && "collection" in options) draftMode = (await payload.findByID({
|
|
418
|
-
collection: options.collection,
|
|
419
|
-
id: options.id,
|
|
420
|
-
locale: sourceLocale,
|
|
421
|
-
draft: true,
|
|
422
|
-
depth: 0,
|
|
423
|
-
overrideAccess: true,
|
|
424
|
-
req
|
|
425
|
-
}))._status === "draft";
|
|
426
|
-
const read = async (locale, opts) => "collection" in options ? await payload.findByID({
|
|
427
|
-
collection: options.collection,
|
|
428
|
-
id: options.id,
|
|
429
|
-
locale,
|
|
430
|
-
...opts.draft ? { draft: true } : {},
|
|
431
|
-
...opts.fallbackLocale === false ? { fallbackLocale: false } : {},
|
|
432
|
-
depth: 0,
|
|
433
|
-
overrideAccess: true,
|
|
434
|
-
req
|
|
435
|
-
}) : await payload.findGlobal({
|
|
436
|
-
slug: options.global,
|
|
437
|
-
locale,
|
|
438
|
-
...opts.draft ? { draft: true } : {},
|
|
439
|
-
...opts.fallbackLocale === false ? { fallbackLocale: false } : {},
|
|
440
|
-
depth: 0,
|
|
441
|
-
overrideAccess: true,
|
|
442
|
-
req
|
|
443
|
-
});
|
|
444
|
-
const source = await read(sourceLocale, { draft: draftMode });
|
|
445
|
-
const slug = "collection" in options ? options.collection : options.global;
|
|
446
|
-
const label = "collection" in options ? `${slug}/${String(options.id)}` : `globals/${slug}`;
|
|
447
|
-
const configured = "collection" in options ? state?.collections[slug] : state?.globals[slug];
|
|
448
|
-
const context = options.context ?? configured?.context?.(source) ?? defaultContext(slug, source, schema.useAsTitle);
|
|
449
|
-
const site = options.site ?? state?.site;
|
|
450
|
-
const plan = (from, target) => translationJob({
|
|
451
|
-
schema,
|
|
452
|
-
source: from,
|
|
453
|
-
target,
|
|
454
|
-
previous: options.previous,
|
|
455
|
-
overwrite: options.overwrite
|
|
456
|
-
});
|
|
457
|
-
const results = [];
|
|
458
|
-
for (const locale of targets) {
|
|
459
|
-
const first = plan(source, await read(locale, {
|
|
460
|
-
draft: draftMode,
|
|
461
|
-
fallbackLocale: false
|
|
462
|
-
}));
|
|
463
|
-
if (!first) {
|
|
464
|
-
results.push({
|
|
465
|
-
locale,
|
|
466
|
-
status: "nothing",
|
|
467
|
-
count: 0
|
|
468
|
-
});
|
|
72
|
+
function partitionStatements(statements, locale = "en") {
|
|
73
|
+
const first = [];
|
|
74
|
+
const last = [];
|
|
75
|
+
const localeColumns = [];
|
|
76
|
+
const drops = /* @__PURE__ */ new Map();
|
|
77
|
+
const recreated = new Set(statements.filter((statement) => /^CREATE TYPE\b/i.test(statement)).map((statement) => statement.match(TYPE_NAME)?.[1]).filter((name) => Boolean(name)));
|
|
78
|
+
for (const statement of statements) {
|
|
79
|
+
const addLocaleColumn = statement.match(ADD_LOCALE);
|
|
80
|
+
if (addLocaleColumn) localeColumns.push(addLocaleColumn[1]);
|
|
81
|
+
const drop = statement.match(DROP_COLUMN);
|
|
82
|
+
if (drop) {
|
|
83
|
+
const [, table, column] = drop;
|
|
84
|
+
drops.set(table, [...drops.get(table) ?? [], column]);
|
|
85
|
+
last.push(statement);
|
|
469
86
|
continue;
|
|
470
87
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
from: sourceLocale,
|
|
476
|
-
to: locale,
|
|
477
|
-
context,
|
|
478
|
-
...site ? { site } : {}
|
|
479
|
-
});
|
|
480
|
-
if (!translated) return false;
|
|
481
|
-
strings.forEach((value, index) => known.set(value, translated[index]));
|
|
482
|
-
return true;
|
|
483
|
-
};
|
|
484
|
-
if (!await translate(first.sources)) {
|
|
485
|
-
results.push({
|
|
486
|
-
locale,
|
|
487
|
-
status: "failed",
|
|
488
|
-
count: 0
|
|
489
|
-
});
|
|
88
|
+
if (DROP_TYPE.test(statement)) {
|
|
89
|
+
const name = statement.match(TYPE_NAME)?.[1];
|
|
90
|
+
if (name && recreated.has(name)) first.push(statement);
|
|
91
|
+
else last.push(statement);
|
|
490
92
|
continue;
|
|
491
93
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
* 1. Payload's update merges into the latest version row
|
|
499
|
-
* (`getLatestCollectionVersion` / `getLatestGlobalVersion`), draft or
|
|
500
|
-
* not: `beforeValidate` fills every field the write omits from it and
|
|
501
|
-
* `beforeChange` fills every localized field's other locales from it,
|
|
502
|
-
* and a non-draft update writes that to the live row and saves it as
|
|
503
|
-
* a version. So a live write after an autosave would publish the
|
|
504
|
-
* draft's copy with no Publish click. A newer draft is therefore
|
|
505
|
-
* written as a draft (`draft: true` leaves the live row and `_status`
|
|
506
|
-
* alone), and its target reaches the site with the next publish. A
|
|
507
|
-
* caller already on a draft stays on drafts even if the latest was
|
|
508
|
-
* published meanwhile, so the button never escalates to a live write.
|
|
509
|
-
* 2. The write carries whole top-level fields built from the planned
|
|
510
|
-
* source's structure (`translationJob`), and a non-localized array or
|
|
511
|
-
* blocks field (`layout`, `hero`) is one row list for every locale. A
|
|
512
|
-
* patch planned from an older version would replace the newer row
|
|
513
|
-
* list: rows the editor added dropped, removed ones restored, links
|
|
514
|
-
* and images reverted. So the job is planned again from the latest
|
|
515
|
-
* source and target, with the same `previous`, which keeps the
|
|
516
|
-
* per-string rule: strings changed since the last publish translate,
|
|
517
|
-
* filled target copy whose source did not change stays.
|
|
518
|
-
*
|
|
519
|
-
* Strings the re-plan meets for the first time go to the model, and the
|
|
520
|
-
* latest version is read again after that call, up to `REPLANS` times.
|
|
521
|
-
* What is left is the gap between the last read and Payload's own read
|
|
522
|
-
* inside the update: milliseconds, against the seconds to minutes of a
|
|
523
|
-
* model call. Closing it would need a row lock Payload's update does not
|
|
524
|
-
* take, so a save landing in exactly that gap can still be overwritten.
|
|
525
|
-
*/
|
|
526
|
-
async function writeLatest(locale) {
|
|
527
|
-
for (let round = 0;; round++) {
|
|
528
|
-
const latest = await read(sourceLocale, { draft: hasDrafts || draftMode });
|
|
529
|
-
const writeDraft = draftMode || hasDrafts && latest._status === "draft";
|
|
530
|
-
const job = plan(latest, await read(locale, {
|
|
531
|
-
draft: writeDraft,
|
|
532
|
-
fallbackLocale: false
|
|
533
|
-
}));
|
|
534
|
-
if (!job) return {
|
|
535
|
-
locale,
|
|
536
|
-
status: "nothing",
|
|
537
|
-
count: 0
|
|
538
|
-
};
|
|
539
|
-
const missing = job.sources.filter((value) => !known.has(value));
|
|
540
|
-
if (missing.length > 0) {
|
|
541
|
-
if (round >= REPLANS) {
|
|
542
|
-
payload.logger.warn(`${label}: ${locale} source kept changing during translation; ${locale} left as-is`);
|
|
543
|
-
return {
|
|
544
|
-
locale,
|
|
545
|
-
status: "failed",
|
|
546
|
-
count: 0
|
|
547
|
-
};
|
|
548
|
-
}
|
|
549
|
-
if (!await translate(missing)) return {
|
|
550
|
-
locale,
|
|
551
|
-
status: "failed",
|
|
552
|
-
count: 0
|
|
553
|
-
};
|
|
554
|
-
continue;
|
|
555
|
-
}
|
|
556
|
-
const data = job.patch(job.sources.map((value) => known.get(value)));
|
|
557
|
-
if (writeDraft && !draftMode) payload.logger.info(`${label}: latest version is a draft; ${locale} translation written into the draft, the live ${locale} copy updates on the next publish`);
|
|
558
|
-
const common = {
|
|
559
|
-
locale,
|
|
560
|
-
data,
|
|
561
|
-
depth: 0,
|
|
562
|
-
...writeDraft ? { draft: true } : {},
|
|
563
|
-
context: { autoTranslate: false },
|
|
564
|
-
...writeAs,
|
|
565
|
-
req
|
|
566
|
-
};
|
|
567
|
-
if ("collection" in options) await payload.update({
|
|
568
|
-
collection: options.collection,
|
|
569
|
-
id: options.id,
|
|
570
|
-
...common
|
|
571
|
-
});
|
|
572
|
-
else await payload.updateGlobal({
|
|
573
|
-
slug: options.global,
|
|
574
|
-
...common
|
|
575
|
-
});
|
|
576
|
-
return {
|
|
577
|
-
locale,
|
|
578
|
-
status: "translated",
|
|
579
|
-
count: job.sources.length
|
|
580
|
-
};
|
|
581
|
-
}
|
|
94
|
+
const addLocale = statement.match(ADD_LOCALE_NOT_NULL);
|
|
95
|
+
if (addLocale && !/DEFAULT/i.test(statement)) {
|
|
96
|
+
const [, head, table, columnName, type] = addLocale;
|
|
97
|
+
first.push(`${head} DEFAULT '${locale}'::text::${type};`);
|
|
98
|
+
first.push(`ALTER TABLE ${table} ALTER COLUMN "${columnName}" DROP DEFAULT;`);
|
|
99
|
+
continue;
|
|
582
100
|
}
|
|
101
|
+
first.push(statement);
|
|
583
102
|
}
|
|
584
|
-
return results;
|
|
585
|
-
}
|
|
586
|
-
//#endregion
|
|
587
|
-
//#region src/translate/endpoint.ts
|
|
588
|
-
/** The admin component key for the "Translate now" document menu item. */
|
|
589
|
-
const TRANSLATE_NOW = "@bison-lab/payload-core/admin#TranslateNowMenuItem";
|
|
590
|
-
/**
|
|
591
|
-
* True when the request's user may update this document, by the collection's
|
|
592
|
-
* own `access.update`. A query result (`Where`) counts only when it matches
|
|
593
|
-
* this document. It counts against the main document, as Payload's own update
|
|
594
|
-
* does for a draft save, even when the latest version is a newer draft: the
|
|
595
|
-
* write that follows is judged by Payload again, so this is only the early
|
|
596
|
-
* refusal.
|
|
597
|
-
*/
|
|
598
|
-
async function canUpdate(req, slug, id) {
|
|
599
|
-
if (!req.user) return false;
|
|
600
|
-
const access = req.payload.collections[slug]?.config.access?.update;
|
|
601
|
-
if (!access) return true;
|
|
602
|
-
const result = await access({
|
|
603
|
-
req,
|
|
604
|
-
id
|
|
605
|
-
});
|
|
606
|
-
if (typeof result === "boolean") return result;
|
|
607
|
-
if (!result || typeof result !== "object") return false;
|
|
608
|
-
const { totalDocs } = await req.payload.count({
|
|
609
|
-
collection: slug,
|
|
610
|
-
where: { and: [result, { id: { equals: id } }] },
|
|
611
|
-
overrideAccess: true
|
|
612
|
-
});
|
|
613
|
-
return totalDocs > 0;
|
|
614
|
-
}
|
|
615
|
-
/**
|
|
616
|
-
* `POST /api/<slug>/:id/translate?locale=<code>`: the "Translate now"
|
|
617
|
-
* action. Re-translates one document with `overwrite`, replacing the target
|
|
618
|
-
* locale's copy (every target locale when `locale` is omitted). Needs update
|
|
619
|
-
* access to the document. Awaits the model, unlike the publish hook: a
|
|
620
|
-
* person pressed the button and is waiting for the answer.
|
|
621
|
-
*/
|
|
622
|
-
function translateNowEndpoint(slug) {
|
|
623
103
|
return {
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
const state = readState(req.payload.config);
|
|
629
|
-
if (!state || !isTranslatorConfigured(state.translator)) return Response.json({ error: "Translation is not configured on the server." }, { status: 503 });
|
|
630
|
-
const id = req.routeParams?.id;
|
|
631
|
-
if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Missing document id" }, { status: 400 });
|
|
632
|
-
const locale = req.searchParams?.get("locale") || void 0;
|
|
633
|
-
if (locale !== void 0 && !state.targetLocales.includes(locale)) return Response.json({ error: `"${locale}" is not a locale this site translates into.` }, { status: 400 });
|
|
634
|
-
if (!await canUpdate(req, slug, String(id))) return Response.json({ error: "You are not allowed to update this document." }, { status: 403 });
|
|
635
|
-
let results;
|
|
636
|
-
try {
|
|
637
|
-
results = await translateDocument(req.payload, {
|
|
638
|
-
collection: slug,
|
|
639
|
-
id,
|
|
640
|
-
...locale ? { locale } : {},
|
|
641
|
-
overwrite: true,
|
|
642
|
-
user: req.user
|
|
643
|
-
});
|
|
644
|
-
} catch (error) {
|
|
645
|
-
const status = error.status;
|
|
646
|
-
if (typeof status === "number" && status >= 400 && status < 500) {
|
|
647
|
-
const message = error instanceof Error && error.message ? error.message : "Not allowed.";
|
|
648
|
-
return Response.json({ error: message }, { status });
|
|
649
|
-
}
|
|
650
|
-
throw error;
|
|
651
|
-
}
|
|
652
|
-
const failed = results.filter((result) => result.status === "failed");
|
|
653
|
-
const count = results.reduce((sum, result) => sum + result.count, 0);
|
|
654
|
-
if (failed.length > 0 && failed.length === results.length) {
|
|
655
|
-
req.payload.logger.warn(`${slug}/${id}: "Translate now" returned no result`);
|
|
656
|
-
return Response.json({
|
|
657
|
-
error: "The translation service gave no result. Try again in a minute.",
|
|
658
|
-
results
|
|
659
|
-
}, { status: 502 });
|
|
660
|
-
}
|
|
661
|
-
const message = count === 0 ? "Nothing to translate." : `Translated ${count} string(s) into ${results.filter((result) => result.status === "translated").map((result) => result.locale).join(", ")}.${failed.length ? ` ${failed.map((result) => result.locale).join(", ")} failed.` : ""}`;
|
|
662
|
-
return Response.json({
|
|
663
|
-
count,
|
|
664
|
-
message,
|
|
665
|
-
results
|
|
666
|
-
});
|
|
667
|
-
}
|
|
104
|
+
first,
|
|
105
|
+
localeColumns,
|
|
106
|
+
drops,
|
|
107
|
+
last
|
|
668
108
|
};
|
|
669
109
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
/**
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
* in-process signal that the transaction is over — both commitTransaction and
|
|
686
|
-
* killTransaction finish with `delete req.transactionID`. The alternative,
|
|
687
|
-
* patching payload.db.commitTransaction, is global and order-dependent, and
|
|
688
|
-
* would affect every operation in the process to serve one hook.
|
|
689
|
-
*
|
|
690
|
-
* An absent transactionID means there is nothing to wait for: a script running
|
|
691
|
-
* with `disableTransaction`, or a unit test.
|
|
692
|
-
*/
|
|
693
|
-
async function waitForTransactionEnd(req) {
|
|
694
|
-
const deadline = Date.now() + TRANSACTION_TIMEOUT_MS;
|
|
695
|
-
while (req.transactionID !== void 0) {
|
|
696
|
-
if (Date.now() >= deadline) return false;
|
|
697
|
-
await sleep(POLL_INTERVAL_MS);
|
|
698
|
-
}
|
|
699
|
-
return true;
|
|
700
|
-
}
|
|
701
|
-
/**
|
|
702
|
-
* Run `work` once the request's database transaction has ended, so an expensive
|
|
703
|
-
* or failure-prone tail never holds that transaction open.
|
|
704
|
-
*
|
|
705
|
-
* Payload runs `afterOperation` BEFORE commitTransaction (see updateByID.js), so
|
|
706
|
-
* no hook is late enough to do this on its own. Anything scheduled here must
|
|
707
|
-
* also open its own transaction rather than joining `req`'s: joining is
|
|
708
|
-
* mandatory only while the outer transaction is still live — once it has
|
|
709
|
-
* committed, its row locks are released and a fresh transaction is both safe
|
|
710
|
-
* and required. So `work` must pass no `req` to the Local API.
|
|
711
|
-
*
|
|
712
|
-
* The returned promise is handed to `waitUntil` (the site's, e.g. Vercel's),
|
|
713
|
-
* without which a serverless instance may be frozen the moment the response is
|
|
714
|
-
* flushed and the work would never finish. It is also returned to the caller,
|
|
715
|
-
* so tests and scripts can await the deferred work instead of sleeping.
|
|
716
|
-
*
|
|
717
|
-
* Deliberately not awaited by its callers: not awaiting is what removes the
|
|
718
|
-
* hold, and `waitUntil` is what keeps the work alive afterwards.
|
|
719
|
-
*
|
|
720
|
-
* Never rejects. The final catch is a backstop only — callers own their own
|
|
721
|
-
* error reporting — so that a defect in this helper cannot escape as an
|
|
722
|
-
* unhandled rejection and take the process down.
|
|
723
|
-
*/
|
|
724
|
-
function runAfterCommit(req, label, work, waitUntil) {
|
|
725
|
-
const deferred = waitForTransactionEnd(req).then((ended) => {
|
|
726
|
-
if (ended) return work();
|
|
727
|
-
req.payload.logger.warn(`${label}: transaction still open after ${TRANSACTION_TIMEOUT_MS}ms; deferred work skipped`);
|
|
728
|
-
}).catch((error) => {
|
|
729
|
-
req.payload.logger.error({ err: error }, `${label}: deferred post-commit work threw`);
|
|
110
|
+
/** Payload's default table name for a slug (`toSnakeCase`). */
|
|
111
|
+
function snake(value) {
|
|
112
|
+
return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
|
|
113
|
+
}
|
|
114
|
+
/** Named fields at this level, looking through rows, collapsibles, unnamed groups and unnamed tabs. */
|
|
115
|
+
function named(fields) {
|
|
116
|
+
return fields.flatMap((field) => {
|
|
117
|
+
if (field.type === "tabs") return (field.tabs ?? []).flatMap((tab) => tab.name ? [{
|
|
118
|
+
type: "group",
|
|
119
|
+
name: tab.name,
|
|
120
|
+
localized: tab.localized,
|
|
121
|
+
fields: tab.fields
|
|
122
|
+
}] : named(tab.fields));
|
|
123
|
+
if (!field.name && field.fields) return named(field.fields);
|
|
124
|
+
return field.name ? [field] : [];
|
|
730
125
|
});
|
|
731
|
-
try {
|
|
732
|
-
waitUntil?.(deferred);
|
|
733
|
-
} catch (error) {
|
|
734
|
-
req.payload.logger.error({ err: error }, `${label}: waitUntil threw; the deferred work still runs`);
|
|
735
|
-
}
|
|
736
|
-
return deferred;
|
|
737
|
-
}
|
|
738
|
-
//#endregion
|
|
739
|
-
//#region src/translate/guards.ts
|
|
740
|
-
const FIELD_SEPARATOR = String.fromCharCode(0);
|
|
741
|
-
/** True when no localized copy differs between the two documents. */
|
|
742
|
-
function localizedCopyUnchanged(previousDoc, doc, schema) {
|
|
743
|
-
const before = collectLocalizedStrings(schema, previousDoc ?? {});
|
|
744
|
-
const after = collectLocalizedStrings(schema, doc ?? {});
|
|
745
|
-
return before.join(FIELD_SEPARATOR) === after.join(FIELD_SEPARATOR);
|
|
746
126
|
}
|
|
747
127
|
/**
|
|
748
|
-
*
|
|
749
|
-
*
|
|
750
|
-
*
|
|
128
|
+
* Whether the stored `path` of a relationship / hasMany row (`related`,
|
|
129
|
+
* `layout.1.items.0.ref`) is a localized field, or sits inside one.
|
|
130
|
+
* `undefined` when the path is not in the config. Throws when blocks
|
|
131
|
+
* disagree (two block types with the same sub-path, one localized).
|
|
751
132
|
*/
|
|
752
|
-
function
|
|
753
|
-
const
|
|
754
|
-
|
|
755
|
-
|
|
133
|
+
function isLocalizedPath(fields, segments, inherited = false, configBlocks = []) {
|
|
134
|
+
const [head, ...rest] = segments;
|
|
135
|
+
const field = named(fields).find((candidate) => candidate.name === head);
|
|
136
|
+
if (!field) return void 0;
|
|
137
|
+
const localized = inherited || field.localized === true;
|
|
138
|
+
if (rest.length === 0) return localized;
|
|
139
|
+
if (field.type === "array") return isLocalizedPath(field.fields ?? [], rest.slice(1), localized, configBlocks);
|
|
140
|
+
if (field.type === "blocks") {
|
|
141
|
+
const referenced = (field.blockReferences ?? []).flatMap((ref) => typeof ref === "string" ? configBlocks.filter((block) => block.slug === ref) : [ref]);
|
|
142
|
+
const answers = [...field.blocks ?? [], ...referenced].map((block) => isLocalizedPath(block.fields, rest.slice(1), localized, configBlocks)).filter((answer) => answer !== void 0);
|
|
143
|
+
if (answers.length === 0) return void 0;
|
|
144
|
+
if (answers.some((answer) => answer !== answers[0])) throw new Error(`localizeExistingContent: "${segments.join(".")}" is localized in one block type and not another`);
|
|
145
|
+
return answers[0];
|
|
146
|
+
}
|
|
147
|
+
return isLocalizedPath(field.fields ?? [], rest, localized, configBlocks);
|
|
756
148
|
}
|
|
757
|
-
/**
|
|
758
|
-
|
|
759
|
-
* NOT use the hook's `previousDoc`.
|
|
760
|
-
*
|
|
761
|
-
* Payload hands `afterChange` the most recently saved version, and with autosave
|
|
762
|
-
* on (375ms) that is the draft the editor was just typing into, carrying copy
|
|
763
|
-
* identical to what is being published. Diffing against it therefore reported
|
|
764
|
-
* "nothing changed" on essentially every admin publish, so auto-translation
|
|
765
|
-
* never ran from the admin at all. Diffing against the LAST PUBLISHED version
|
|
766
|
-
* is the question actually worth asking: did the published copy change?
|
|
767
|
-
*
|
|
768
|
-
* That also keeps the property the naive fix broke, namely that a publish which
|
|
769
|
-
* touches no localized copy (an image swap, a reordering) leaves a hand-edited
|
|
770
|
-
* target locale alone. A document with no earlier published version is a first
|
|
771
|
-
* publish and always translates, even one written entirely as a draft.
|
|
772
|
-
*
|
|
773
|
-
* Returns that previous published version too: it is the "before" the
|
|
774
|
-
* per-string rule compares each source string with.
|
|
775
|
-
*/
|
|
776
|
-
async function draftedTranslationDecision(opts) {
|
|
777
|
-
const { req, entity, doc, schema, sourceLocale } = opts;
|
|
778
|
-
if (doc?._status !== "published") return {
|
|
779
|
-
skip: true,
|
|
780
|
-
previous: null
|
|
781
|
-
};
|
|
782
|
-
const docUpdatedAt = doc.updatedAt;
|
|
783
|
-
if (typeof docUpdatedAt !== "string") return {
|
|
784
|
-
skip: false,
|
|
785
|
-
previous: null
|
|
786
|
-
};
|
|
787
|
-
const where = {
|
|
788
|
-
"version._status": { equals: "published" },
|
|
789
|
-
updatedAt: { less_than: docUpdatedAt }
|
|
790
|
-
};
|
|
791
|
-
const common = {
|
|
792
|
-
sort: "-updatedAt",
|
|
793
|
-
limit: 1,
|
|
794
|
-
pagination: false,
|
|
795
|
-
depth: 0,
|
|
796
|
-
locale: sourceLocale,
|
|
797
|
-
overrideAccess: true,
|
|
798
|
-
req
|
|
799
|
-
};
|
|
800
|
-
const { docs } = "collection" in entity ? await req.payload.findVersions({
|
|
801
|
-
...common,
|
|
802
|
-
collection: entity.collection,
|
|
803
|
-
where: {
|
|
804
|
-
parent: { equals: doc.id },
|
|
805
|
-
...where
|
|
806
|
-
}
|
|
807
|
-
}) : await req.payload.findGlobalVersions({
|
|
808
|
-
...common,
|
|
809
|
-
slug: entity.global,
|
|
810
|
-
where
|
|
811
|
-
});
|
|
812
|
-
const previousPublished = docs[0]?.version;
|
|
813
|
-
if (!previousPublished || typeof previousPublished !== "object") return {
|
|
814
|
-
skip: false,
|
|
815
|
-
previous: null
|
|
816
|
-
};
|
|
817
|
-
const current = "collection" in entity ? await req.payload.findByID({
|
|
818
|
-
collection: entity.collection,
|
|
819
|
-
id: doc.id,
|
|
820
|
-
locale: sourceLocale,
|
|
821
|
-
depth: 0,
|
|
822
|
-
overrideAccess: true,
|
|
823
|
-
req
|
|
824
|
-
}) : await req.payload.findGlobal({
|
|
825
|
-
slug: entity.global,
|
|
826
|
-
locale: sourceLocale,
|
|
827
|
-
depth: 0,
|
|
828
|
-
overrideAccess: true,
|
|
829
|
-
req
|
|
830
|
-
});
|
|
831
|
-
const previous = previousPublished;
|
|
149
|
+
/** The adapter's table suffixes: Payload's defaults unless the site set its own. */
|
|
150
|
+
function suffixes(payload) {
|
|
832
151
|
return {
|
|
833
|
-
|
|
834
|
-
|
|
152
|
+
locales: payload?.db?.localesSuffix ?? "_locales",
|
|
153
|
+
rels: payload?.db?.relationshipsSuffix ?? "_rels",
|
|
154
|
+
versions: payload?.db?.versionsSuffix ?? "_v"
|
|
835
155
|
};
|
|
836
156
|
}
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
157
|
+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
158
|
+
/** A shared relationship / hasMany table: `<base><relationshipsSuffix>`, `<base>_texts`, `<base>_numbers`. */
|
|
159
|
+
function sharedSuffix(payload) {
|
|
160
|
+
return new RegExp(`(${escapeRegExp(suffixes(payload).rels)}|_texts|_numbers)$`);
|
|
161
|
+
}
|
|
162
|
+
function entityFor(payload, table) {
|
|
163
|
+
const { versions } = suffixes(payload);
|
|
164
|
+
const base = table.replace(sharedSuffix(payload), "");
|
|
165
|
+
const version = base.startsWith("_") && base.endsWith(versions);
|
|
166
|
+
const name = version ? base.slice(1, -versions.length) : base;
|
|
167
|
+
const entity = [...payload.config.collections ?? [], ...payload.config.globals ?? []].find((candidate) => (typeof candidate.dbName === "string" ? candidate.dbName : snake(candidate.slug)) === name);
|
|
168
|
+
return entity ? {
|
|
169
|
+
fields: entity.fields,
|
|
170
|
+
version
|
|
171
|
+
} : null;
|
|
172
|
+
}
|
|
173
|
+
const quote = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
174
|
+
const literal = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
175
|
+
function rowsOf(result) {
|
|
176
|
+
if (Array.isArray(result)) return result;
|
|
177
|
+
const rows = result?.rows;
|
|
178
|
+
return Array.isArray(rows) ? rows : [];
|
|
840
179
|
}
|
|
841
|
-
//#endregion
|
|
842
|
-
//#region src/translate/hooks.ts
|
|
843
180
|
/**
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
*
|
|
847
|
-
* - `autoTranslate: false` context skips the hook entirely (set by seed
|
|
848
|
-
* scripts, which run their own pass, and by the plugin's own target write
|
|
849
|
-
* so it can never re-fire itself).
|
|
850
|
-
* - Edits in a target locale are ignored: a hand edit there must never be
|
|
851
|
-
* clobbered by a machine pass.
|
|
852
|
-
* - Drafts are ignored; Live Preview autosaves every ~375ms and translating
|
|
853
|
-
* each keystroke would be absurd. Publish is the commit point.
|
|
854
|
-
* - No-op RE-publishes are ignored: if no localized string differs from the
|
|
855
|
-
* previously published version (e.g. an image swap), targets stay
|
|
856
|
-
* untouched. A FIRST publish is never a no-op, even though a doc written
|
|
857
|
-
* entirely as a draft carries identical copy either side of the transition:
|
|
858
|
-
* its targets have never been generated. See draftedTranslationDecision.
|
|
859
|
-
* - No API key: the publish goes through and a warning is logged.
|
|
860
|
-
*
|
|
861
|
-
* Failures log a warning and never block or fail the publish; the source goes
|
|
862
|
-
* live and each target stays as it was until the next publish. That holds
|
|
863
|
-
* structurally: the translation does not even begin until the publish is
|
|
864
|
-
* durable.
|
|
865
|
-
*
|
|
866
|
-
* Only the guards run inside the publish's transaction — two cheap indexed
|
|
867
|
-
* reads that need to see the publish's own state. The model round trip and the
|
|
868
|
-
* target writes are deferred past the commit by runAfterCommit, so a publish
|
|
869
|
-
* never holds its transaction open for the seconds a long document takes. The
|
|
870
|
-
* deferred call passes no `req`: it must open its own transaction, and safely
|
|
871
|
-
* can, because the outer one has released its row locks by then.
|
|
181
|
+
* Runs a localization migration without losing content: see the module
|
|
182
|
+
* comment. Returns what it copied. Throws (and Payload rolls the migration
|
|
183
|
+
* back) on any SQL error.
|
|
872
184
|
*/
|
|
873
|
-
async function
|
|
874
|
-
const {
|
|
875
|
-
|
|
876
|
-
const
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
const
|
|
880
|
-
const
|
|
881
|
-
const
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
schema,
|
|
890
|
-
sourceLocale: state.sourceLocale
|
|
891
|
-
});
|
|
892
|
-
if (decision.skip) return {};
|
|
893
|
-
previous = decision.previous;
|
|
894
|
-
} else {
|
|
895
|
-
const previousDoc = args.operation === "create" ? void 0 : args.previousDoc;
|
|
896
|
-
if (shouldSkipUndraftedTranslation({
|
|
897
|
-
previousDoc,
|
|
898
|
-
doc,
|
|
899
|
-
schema
|
|
900
|
-
})) return {};
|
|
901
|
-
previous = previousDoc && Object.keys(previousDoc).length > 0 ? previousDoc : null;
|
|
902
|
-
}
|
|
903
|
-
} catch (error) {
|
|
904
|
-
payload.logger.error({ err: error }, `${label}: auto-translation guard failed; targets left as-is`);
|
|
905
|
-
return {};
|
|
906
|
-
}
|
|
907
|
-
if (!isTranslatorConfigured(state.translator)) {
|
|
908
|
-
payload.logger.warn(`${label}: source copy changed but the translator has no API key; targets not translated`);
|
|
909
|
-
return {};
|
|
910
|
-
}
|
|
911
|
-
return { deferred: runAfterCommit(req, label, async () => {
|
|
912
|
-
try {
|
|
913
|
-
logResults(payload, label, await translateDocument(payload, {
|
|
914
|
-
..."collection" in entity ? {
|
|
915
|
-
collection: slug,
|
|
916
|
-
id: doc.id
|
|
917
|
-
} : { global: slug },
|
|
918
|
-
previous
|
|
919
|
-
}));
|
|
920
|
-
} catch (error) {
|
|
921
|
-
payload.logger.error({ err: error }, `${label}: auto-translation failed; targets left as-is`);
|
|
185
|
+
async function localizeExistingContent(options) {
|
|
186
|
+
const { db, sql } = options;
|
|
187
|
+
const locale = options.locale ?? "en";
|
|
188
|
+
const schema = options.schema ?? "public";
|
|
189
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
190
|
+
const run = (text) => db.execute(sql.raw(text));
|
|
191
|
+
const { first, localeColumns, drops, last } = partitionStatements(splitStatements(options.statements), locale);
|
|
192
|
+
for (const statement of first) await run(statement);
|
|
193
|
+
for (const table of localeColumns) {
|
|
194
|
+
const qualifiedTable = `${quote(schema)}.${quote(table)}`;
|
|
195
|
+
const tableColumns = rowsOf(await run(`SELECT column_name, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(schema)} AND table_name = ${literal(table)} AND column_name IN ('locale', 'path')`));
|
|
196
|
+
const localeInfo = tableColumns.find((info) => info.column_name === "locale");
|
|
197
|
+
const value = localeInfo ? `${literal(locale)}::text::${quote(localeInfo.udt_schema)}.${quote(localeInfo.udt_name)}` : literal(locale);
|
|
198
|
+
if (!tableColumns.some((info) => info.column_name === "path")) {
|
|
199
|
+
log(`[localize] ${table}: locale set on ${(await run(`UPDATE ${qualifiedTable} SET "locale" = ${value} WHERE "locale" IS NULL`))?.rowCount ?? "?"} rows`);
|
|
200
|
+
continue;
|
|
922
201
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
schema: {
|
|
935
|
-
fields: collection.fields,
|
|
936
|
-
blocks: req.payload.config.blocks
|
|
937
|
-
},
|
|
938
|
-
doc,
|
|
939
|
-
previousDoc,
|
|
940
|
-
operation,
|
|
941
|
-
req,
|
|
942
|
-
context
|
|
202
|
+
const paths = rowsOf(await run(`SELECT DISTINCT "path" FROM ${qualifiedTable} WHERE "locale" IS NULL`)).map((row) => String(row.path));
|
|
203
|
+
if (paths.length === 0) continue;
|
|
204
|
+
if (!options.payload) throw new Error(`localizeExistingContent: ${table} holds relationship or hasMany rows that may belong to localized fields. Pass the migration's payload ({ db, payload, sql, statements }) so they keep their content.`);
|
|
205
|
+
const entity = entityFor(options.payload, table);
|
|
206
|
+
if (!entity) throw new Error(`localizeExistingContent: no collection or global stores its relationships in ${table}. If one does under a custom table name, give that collection or global a dbName matching ${table.replace(sharedSuffix(options.payload), "")}.`);
|
|
207
|
+
const localized = paths.filter((path) => {
|
|
208
|
+
const segments = path.split(".");
|
|
209
|
+
const own = entity.version && segments[0] === "version" ? segments.slice(1) : segments;
|
|
210
|
+
const answer = isLocalizedPath(entity.fields, own, false, options.payload.config.blocks ?? []);
|
|
211
|
+
if (answer === void 0) throw new Error(`localizeExistingContent: ${table} has rows at "${path}", which is not a field in the config passed`);
|
|
212
|
+
return answer;
|
|
943
213
|
});
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
},
|
|
956
|
-
doc,
|
|
957
|
-
previousDoc,
|
|
958
|
-
operation: "update",
|
|
959
|
-
req,
|
|
960
|
-
context
|
|
961
|
-
});
|
|
962
|
-
return doc;
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
//#endregion
|
|
966
|
-
//#region src/translate/plugin.ts
|
|
967
|
-
function entries(list) {
|
|
968
|
-
return (list ?? []).map((entry) => typeof entry === "string" ? { slug: entry } : entry);
|
|
969
|
-
}
|
|
970
|
-
function withCollection(collection, configured, sourceLocale, targetLocales) {
|
|
971
|
-
const edit = collection.admin?.components?.edit;
|
|
972
|
-
return {
|
|
973
|
-
...collection,
|
|
974
|
-
hooks: {
|
|
975
|
-
...collection.hooks,
|
|
976
|
-
afterChange: [...collection.hooks?.afterChange ?? [], collectionAutoTranslateHook(collection.slug)]
|
|
977
|
-
},
|
|
978
|
-
endpoints: [...collection.endpoints || [], translateNowEndpoint(collection.slug)],
|
|
979
|
-
admin: {
|
|
980
|
-
...collection.admin,
|
|
981
|
-
components: {
|
|
982
|
-
...collection.admin?.components,
|
|
983
|
-
edit: {
|
|
984
|
-
...edit,
|
|
985
|
-
editMenuItems: [...edit?.editMenuItems ?? [], {
|
|
986
|
-
path: TRANSLATE_NOW,
|
|
987
|
-
clientProps: {
|
|
988
|
-
sourceLocale,
|
|
989
|
-
targetLocales,
|
|
990
|
-
configured
|
|
991
|
-
}
|
|
992
|
-
}]
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
};
|
|
997
|
-
}
|
|
998
|
-
function withGlobal(global) {
|
|
999
|
-
return {
|
|
1000
|
-
...global,
|
|
1001
|
-
hooks: {
|
|
1002
|
-
...global.hooks,
|
|
1003
|
-
afterChange: [...global.hooks?.afterChange ?? [], globalAutoTranslateHook(global.slug)]
|
|
1004
|
-
}
|
|
1005
|
-
};
|
|
1006
|
-
}
|
|
1007
|
-
/**
|
|
1008
|
-
* Fills every locale but the default from the default whenever copy is
|
|
1009
|
-
* published, without overwriting a translation a person corrected. Each site
|
|
1010
|
-
* switches it on or off in its own `payload.config.ts`:
|
|
1011
|
-
*
|
|
1012
|
-
* ```ts
|
|
1013
|
-
* autoTranslate({
|
|
1014
|
-
* enabled: true,
|
|
1015
|
-
* collections: ["pages", { slug: "plans", context: (doc) => `Internet plan: ${doc.name}` }],
|
|
1016
|
-
* translator: anthropicTranslator({ apiKey: process.env.ANTHROPIC_API_KEY, site: { name: "ZoomFiber" } }),
|
|
1017
|
-
* waitUntil,
|
|
1018
|
-
* })
|
|
1019
|
-
* ```
|
|
1020
|
-
*
|
|
1021
|
-
* `enabled: false` returns the config untouched. Without `localization` (or
|
|
1022
|
-
* with one locale) it logs one warning and registers nothing. Otherwise each
|
|
1023
|
-
* listed collection gets an `afterChange` hook, `POST /api/<slug>/:id/translate`
|
|
1024
|
-
* and a "Translate now" item in the document menu (`TRANSLATE_NOW`, run
|
|
1025
|
-
* `payload generate:importmap`). The item is registered whether or not the
|
|
1026
|
-
* translator has a key, so the import map never depends on the environment;
|
|
1027
|
-
* it renders nothing when there is no key. Each listed
|
|
1028
|
-
* global gets the hook.
|
|
1029
|
-
*/
|
|
1030
|
-
function autoTranslate(options) {
|
|
1031
|
-
return (config) => {
|
|
1032
|
-
if (!options.enabled) return config;
|
|
1033
|
-
const localization = config.localization;
|
|
1034
|
-
const codes = localeCodes(localization);
|
|
1035
|
-
if (!localization || codes.length < 2) {
|
|
1036
|
-
console.warn("[@bison-lab/payload-core] autoTranslate is enabled but the config has no localization with two or more locales; it registers nothing.");
|
|
1037
|
-
return config;
|
|
214
|
+
if (localized.length === 0) continue;
|
|
215
|
+
log(`[localize] ${table}: locale set on ${(await run(`UPDATE ${qualifiedTable} SET "locale" = ${value} WHERE "locale" IS NULL AND "path" IN (${localized.map(literal).join(", ")})`))?.rowCount ?? "?"} rows (${localized.join(", ")})`);
|
|
216
|
+
}
|
|
217
|
+
const columnsOf = async (table) => rowsOf(await run(`SELECT column_name, data_type, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(schema)} AND table_name = ${literal(table)}`));
|
|
218
|
+
const copies = [];
|
|
219
|
+
for (const [table, dropped] of drops) {
|
|
220
|
+
const into = `${table}${suffixes(options.payload).locales}`;
|
|
221
|
+
const target = await columnsOf(into);
|
|
222
|
+
if (target.length === 0) {
|
|
223
|
+
log(`[localize] ${table}: ${dropped.join(", ")} dropped with no locale table to keep them; not copied`);
|
|
224
|
+
continue;
|
|
1038
225
|
}
|
|
1039
|
-
const
|
|
1040
|
-
const
|
|
1041
|
-
const
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
...options.site ? { site: options.site } : {},
|
|
1048
|
-
...options.waitUntil ? { waitUntil: options.waitUntil } : {},
|
|
1049
|
-
sourceLocale,
|
|
1050
|
-
targetLocales,
|
|
1051
|
-
collections: Object.fromEntries(collections.map(({ slug, context }) => [slug, context ? { context } : {}])),
|
|
1052
|
-
globals: Object.fromEntries(globals.map(({ slug, context }) => [slug, context ? { context } : {}]))
|
|
226
|
+
const byName = new Map(target.map((column) => [column.column_name, column]));
|
|
227
|
+
const moving = dropped.filter((column) => byName.has(column));
|
|
228
|
+
const lost = dropped.filter((column) => !byName.has(column));
|
|
229
|
+
if (lost.length) log(`[localize] ${table}: ${lost.join(", ")} dropped, not localized; not copied`);
|
|
230
|
+
if (moving.length === 0) continue;
|
|
231
|
+
const cast = (column) => {
|
|
232
|
+
const info = byName.get(column);
|
|
233
|
+
return info.data_type === "USER-DEFINED" ? `${quote(column)}::text::${quote(info.udt_schema)}.${quote(info.udt_name)}` : quote(column);
|
|
1053
234
|
};
|
|
1054
|
-
const
|
|
1055
|
-
|
|
1056
|
-
const
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
235
|
+
const localeColumn = byName.get("_locale");
|
|
236
|
+
if (!localeColumn || !byName.has("_parent_id")) throw new Error(`localizeExistingContent: ${into} has no _locale / _parent_id column`);
|
|
237
|
+
const localeValue = `${literal(locale)}::text::${quote(localeColumn.udt_schema)}.${quote(localeColumn.udt_name)}`;
|
|
238
|
+
const qualified = (name) => `${quote(schema)}.${quote(name)}`;
|
|
239
|
+
const statement = `INSERT INTO ${qualified(into)} (${[
|
|
240
|
+
...moving.map(quote),
|
|
241
|
+
"\"_locale\"",
|
|
242
|
+
"\"_parent_id\""
|
|
243
|
+
].join(", ")})
|
|
244
|
+
SELECT ${[
|
|
245
|
+
...moving.map((column) => `p.${cast(column)}`),
|
|
246
|
+
localeValue,
|
|
247
|
+
"p.\"id\""
|
|
248
|
+
].join(", ")}
|
|
249
|
+
FROM ${qualified(table)} p
|
|
250
|
+
WHERE NOT EXISTS (SELECT 1 FROM ${qualified(into)} l WHERE l."_parent_id" = p."id" AND l."_locale"::text = ${literal(locale)})`;
|
|
251
|
+
const updated = await run(`UPDATE ${qualified(into)} l SET ${moving.map((column) => `${quote(column)} = p.${cast(column)}`).join(", ")}
|
|
252
|
+
FROM ${qualified(table)} p
|
|
253
|
+
WHERE l."_parent_id" = p."id" AND l."_locale"::text = ${literal(locale)}`);
|
|
254
|
+
const rows = ((await run(statement))?.rowCount ?? 0) + (updated?.rowCount ?? 0);
|
|
255
|
+
copies.push({
|
|
256
|
+
table,
|
|
257
|
+
into,
|
|
258
|
+
columns: moving,
|
|
259
|
+
rows
|
|
260
|
+
});
|
|
261
|
+
log(`[localize] ${table} -> ${into}: ${moving.join(", ")} (${rows} rows)`);
|
|
262
|
+
}
|
|
263
|
+
for (const statement of last) await run(statement);
|
|
264
|
+
return copies;
|
|
1067
265
|
}
|
|
1068
266
|
//#endregion
|
|
1069
|
-
export { DEFAULT_TRANSLATE_MODEL, TRANSACTION_TIMEOUT_MS, TRANSLATE_NOW, anthropicTranslator, autoTranslate, collectLocalizedStrings, draftedTranslationDecision, fillMessages, isTranslatorConfigured, localizedCopyUnchanged, parseJsonArray, readTranslateState, runAfterCommit, sameRow, shouldSkipDraftedTranslation, shouldSkipUndraftedTranslation, translateDocument, translateStrings, translationJob, translationSystemPrompt, withTranslator };
|
|
267
|
+
export { ACTIVE_LOCALES_CACHE_MS, BISON_TRANSLATION_CONTEXT, DEFAULT_TRANSLATE_MODEL, ECONOMY_TRANSLATE_MODEL, LIBRARY_DEFAULT_LOCALE, LIBRARY_LOCALES, LIBRARY_LOCALE_CODES, TRANSACTION_TIMEOUT_MS, TRANSLATE_MODEL_PRICES, TRANSLATE_NOW, TRANSLATION_GRANT, TRANSLATION_KEY_PANEL, TRANSLATION_SETTINGS_SLUG, TRANSLATION_STATE_SLUG, activeAlternates, activeLocales, anthropicTranslator, applyTranslation, autoTranslate, classifyAnthropicError, collectLocalizedStrings, containsWord, decryptApiKey, draftedTranslationDecision, encryptApiKey, estimateCost, fillMessages, hasLocalizedFields, inactiveLocaleRedirect, invalidateActiveLocales, invalidateTranslationSettings, isAutosave, isLocalizedPath, isTranslatorConfigured, localizeExistingContent, localizedCopyUnchanged, modelPrice, parseJsonArray, partitionStatements, readTranslateState, readTranslationSettings, resolveApiKey, resolveModel, runAfterCommit, sameRow, shouldSkipDraftedTranslation, shouldSkipUndraftedTranslation, siteFromInstructions, splitStatements, translateDocument, translateStrings, translation, translationJob, translationSettingsEndpoints, translationSystemPrompt, verifyAnthropicKey, withLibraryLocales, withTranslator };
|
|
1070
268
|
|
|
1071
269
|
//# sourceMappingURL=translate.mjs.map
|