@justanarthur/payload-plugin-translator 3.0.3 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // src/resolvers/copy.ts
2
- var copyResolver = () => {
2
+ var copyResolver2 = () => {
3
3
  return {
4
4
  key: "copy",
5
5
  resolve: (args) => {
@@ -12,4 +12,4 @@ var copyResolver = () => {
12
12
  };
13
13
  };
14
14
 
15
- export { copyResolver };
15
+ export { copyResolver2 };
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  chunkArray
3
- } from "./chunk-frnemj69.js";
3
+ } from "./chunk-e6c0qzkt.js";
4
4
 
5
5
  // src/resolvers/google.ts
6
6
  var localeToCountryCodeMapper = {
7
7
  ua: "uk"
8
8
  };
9
9
  var mapLocale = (incoming) => (incoming in localeToCountryCodeMapper) ? localeToCountryCodeMapper[incoming] : incoming;
10
- var googleResolver = ({
10
+ var googleResolver2 = ({
11
11
  apiKey,
12
12
  chunkLength = 100
13
13
  }) => {
@@ -52,4 +52,4 @@ var googleResolver = ({
52
52
  };
53
53
  };
54
54
 
55
- export { googleResolver };
55
+ export { googleResolver2 };
package/dist/types.d.ts CHANGED
@@ -22,6 +22,14 @@ type TranslatorConfig = {
22
22
  globals: GlobalSlug[];
23
23
  resolvers: TranslateResolver[];
24
24
  autoTranslate?: boolean;
25
+ /**
26
+ * what a publish in the default locale does to the other locales.
27
+ * `missing` (default) fills empty fields and keeps existing translations and slugs;
28
+ * `all` re-translates every field.
29
+ */
30
+ autoTranslateMode?: "all" | "missing";
31
+ /** adds the /admin/translations review view, its endpoints and the status collection (default true) */
32
+ review?: boolean;
25
33
  _options?: {
26
34
  additionalTraverseRichText?: (args: {
27
35
  onText: (siblingData: Record<string, unknown>, attribute?: string) => void;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@justanarthur/payload-plugin-translator",
3
3
  "description": "Translator plugin for Payload CMS — automatic localization via Google, OpenAI, LibreTranslate, or custom resolvers.",
4
- "version": "3.0.3",
4
+ "version": "3.1.0",
5
5
  "type": "module",
6
6
  "private": false,
7
7
  "files": [
@@ -29,6 +29,12 @@
29
29
  "default": "./dist/types.js"
30
30
  }
31
31
  },
32
+ "./rsc": {
33
+ "import": {
34
+ "types": "./dist/rsc.d.ts",
35
+ "default": "./dist/rsc.js"
36
+ }
37
+ },
32
38
  "./client": {
33
39
  "import": {
34
40
  "types": "./dist/client.d.ts",
@@ -78,6 +84,7 @@
78
84
  "scripts": {
79
85
  "build": "NODE_ENV=production bunup",
80
86
  "clean": "rm -rf dist .tsbuildinfo",
87
+ "test": "bun test",
81
88
  "prepublishOnly": "bun run clean && bun run build"
82
89
  },
83
90
  "dependencies": {
@@ -85,18 +92,20 @@
85
92
  "he": "^1.2.0"
86
93
  },
87
94
  "devDependencies": {
88
- "@payloadcms/translations": "3.85.0",
89
- "@payloadcms/ui": "3.85.0",
95
+ "@payloadcms/next": "3.88.0",
96
+ "@payloadcms/translations": "3.88.0",
97
+ "@payloadcms/ui": "3.88.0",
90
98
  "@types/he": "^1.2.3",
91
- "@types/react": "19.2.14",
92
- "@types/react-dom": "19.2.3",
99
+ "@types/react": "19.2.18",
100
+ "@types/react-dom": "19.2.7",
93
101
  "bunup": "^0.16.32",
94
- "payload": "3.85.0",
95
- "react": "19.2.6",
96
- "react-dom": "19.2.6",
97
- "typescript": "5.7.3"
102
+ "payload": "3.88.0",
103
+ "react": "19.2.8",
104
+ "react-dom": "19.2.8",
105
+ "typescript": "^7.0.2"
98
106
  },
99
107
  "peerDependencies": {
108
+ "@payloadcms/next": "^3.85.0",
100
109
  "@payloadcms/translations": "^3.85.0",
101
110
  "@payloadcms/ui": "^3.85.0",
102
111
  "payload": "^3.85.0",
@@ -1,205 +0,0 @@
1
- import {
2
- chunkArray
3
- } from "./chunk-frnemj69.js";
4
-
5
- // src/resolvers/openAI.ts
6
- var LOCALE_DISPLAY_NAME = {
7
- en: "English",
8
- sk: "Slovak",
9
- cs: "Czech",
10
- de: "German",
11
- uk: "Ukrainian",
12
- ua: "Ukrainian",
13
- pl: "Polish",
14
- hu: "Hungarian",
15
- fr: "French",
16
- es: "Spanish",
17
- it: "Italian",
18
- pt: "Portuguese",
19
- nl: "Dutch",
20
- ro: "Romanian"
21
- };
22
- var RETRY_DELAYS_MS = [500, 1000, 2000];
23
- var defaultPrompt = ({ localeFrom, localeTo, texts }) => {
24
- const from = LOCALE_DISPLAY_NAME[localeFrom] ?? localeFrom;
25
- const to = LOCALE_DISPLAY_NAME[localeTo] ?? localeTo;
26
- return `You are a machine-translation engine. Translate each string in the input JSON array from ${from} (${localeFrom}) to ${to} (${localeTo}).
27
-
28
- Rules:
29
- 1. The output must be a valid JSON array of strings, with the same length and order as the input.
30
- 2. SLUGS: any input that looks like a URL slug (lowercase, contains only ASCII letters/digits/hyphens/underscores, no spaces, no punctuation) MUST be transliterated into the target language. Output the slug in the same format: lowercase ASCII only, using only letters a-z, digits 0-9, hyphens (-), and underscores (_). Never leave a slug unchanged. Never output accented characters, uppercase letters, spaces, or other symbols in a slug. Examples:
31
- - "about-us-copy" (en) → "o-nas-kopia" (sk) → "uber-uns-kopie" (de) → "sobre-nos-copia" (pt) → "a-propos-copie" (fr)
32
- - For Cyrillic source scripts, transliterate to Latin first, then translate.
33
- 3. URLs (containing "://" or "www."), email addresses, hex strings, and other opaque identifiers: keep as-is.
34
- 4. Apply locale-specific formatting for dates, currency, decimal separators in human-readable text.
35
- 5. Return only the JSON array. No markdown fences, no prose, no trailing commentary.
36
-
37
- INPUT:
38
- ${JSON.stringify(texts)}`;
39
- };
40
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
41
- var isRetryableStatus = (status) => status === 429 || status >= 500;
42
- var isGpt5Family = (model) => /^gpt-5/.test(model);
43
- var isGpt54Plus = (model) => /^gpt-5\.[1-9]/.test(model);
44
- var usesMaxCompletionTokens = (model) => isGpt5Family(model) || /^o[1-9]/.test(model);
45
- var deriveMaxTokens = (chunkLength, model) => {
46
- const base = Math.max(chunkLength * 100, 4000);
47
- if (model && isGpt54Plus(model))
48
- return Math.max(base * 4, 16000);
49
- return base;
50
- };
51
- var parseContent = (raw) => {
52
- const trimmed = raw.trim();
53
- const m = trimmed.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);
54
- const candidate = m ? m[1].trim() : trimmed;
55
- const fenceStripped = m !== null;
56
- let parsed;
57
- try {
58
- parsed = JSON.parse(candidate);
59
- } catch (e) {
60
- return {
61
- error: e instanceof Error ? e.message : String(e),
62
- fenceStripped,
63
- ok: false
64
- };
65
- }
66
- if (!Array.isArray(parsed)) {
67
- return { error: "parsed value is not an array", fenceStripped, ok: false };
68
- }
69
- if (!parsed.every((v) => typeof v === "string")) {
70
- return { error: "array contains non-string element", fenceStripped, ok: false };
71
- }
72
- return { fenceStripped, ok: true, translated: parsed };
73
- };
74
- var openAIResolver = ({
75
- apiKey,
76
- baseUrl,
77
- chunkLength = 100,
78
- model = "gpt-4o-mini",
79
- prompt = defaultPrompt
80
- }) => {
81
- return {
82
- key: "openai",
83
- resolve: async ({ localeFrom, localeTo, req, texts }) => {
84
- const apiUrl = `${baseUrl || "https://api.openai.com"}/v1/chat/completions`;
85
- const maxTokens = deriveMaxTokens(chunkLength, model);
86
- const maxTokensKey = usesMaxCompletionTokens(model) ? "max_completion_tokens" : "max_tokens";
87
- const supportsCustomTemperature = !isGpt5Family(model);
88
- const reasoningEffort = isGpt54Plus(model) ? "low" : undefined;
89
- const logger = req.payload.logger;
90
- try {
91
- const response = await Promise.all(chunkArray(texts, chunkLength).map(async (chunk) => {
92
- for (let attempt = 0;attempt <= RETRY_DELAYS_MS.length; attempt++) {
93
- let shouldRetry = false;
94
- let httpStatus = 0;
95
- try {
96
- const res = await fetch(apiUrl, {
97
- body: JSON.stringify({
98
- messages: [
99
- {
100
- content: prompt({ localeFrom, localeTo, texts: chunk }),
101
- role: "user"
102
- }
103
- ],
104
- model,
105
- ...supportsCustomTemperature ? { temperature: 0 } : {},
106
- ...reasoningEffort ? { reasoning_effort: reasoningEffort } : {},
107
- [maxTokensKey]: maxTokens
108
- }),
109
- headers: {
110
- Authorization: `Bearer ${apiKey}`,
111
- "Content-Type": "application/json"
112
- },
113
- method: "post"
114
- });
115
- httpStatus = res.status;
116
- const data = await res.json();
117
- if (res.ok) {
118
- const content = data?.choices?.[0]?.message?.content;
119
- if (!content) {
120
- logger.error({
121
- code: "OPENAI_BAD_JSON",
122
- message: "OpenAI response missing content",
123
- openAIResponse: data
124
- });
125
- shouldRetry = true;
126
- } else {
127
- const result = parseContent(content);
128
- if (result.ok) {
129
- if (result.fenceStripped) {
130
- logger.info({
131
- code: "OPENAI_FENCE_STRIPPED",
132
- message: "OpenAI returned fenced JSON despite json_object mode"
133
- });
134
- }
135
- return { success: true, translated: result.translated };
136
- }
137
- logger.error({
138
- code: "OPENAI_BAD_JSON",
139
- error: result.error,
140
- fenceStripped: result.fenceStripped,
141
- message: "Failed to parse OpenAI response"
142
- });
143
- shouldRetry = true;
144
- }
145
- } else {
146
- logger.error({
147
- code: "OPENAI_HTTP_ERROR",
148
- message: "OpenAI returned non-2xx status",
149
- openAIResponse: data,
150
- status: httpStatus
151
- });
152
- if (isRetryableStatus(httpStatus))
153
- shouldRetry = true;
154
- }
155
- } catch (e) {
156
- logger.error({
157
- code: "OPENAI_NETWORK_ERROR",
158
- message: "OpenAI request threw",
159
- originalErr: e instanceof Error ? e.message : String(e)
160
- });
161
- shouldRetry = true;
162
- }
163
- if (attempt < RETRY_DELAYS_MS.length && shouldRetry) {
164
- logger.info({
165
- attempt: attempt + 1,
166
- code: "OPENAI_RETRY",
167
- message: "Retrying OpenAI request after backoff",
168
- nextBackoffMs: RETRY_DELAYS_MS[attempt],
169
- status: httpStatus
170
- });
171
- await sleep(RETRY_DELAYS_MS[attempt]);
172
- continue;
173
- }
174
- logger.error({
175
- code: "OPENAI_GIVE_UP",
176
- message: "OpenAI chunk failed after retries",
177
- status: httpStatus
178
- });
179
- return { success: false };
180
- }
181
- return { success: false };
182
- }));
183
- const translated = [];
184
- for (const result of response) {
185
- if (!result.success)
186
- return { success: false };
187
- translated.push(...result.translated);
188
- }
189
- return {
190
- success: true,
191
- translatedTexts: translated
192
- };
193
- } catch (e) {
194
- logger.error({
195
- code: "OPENAI_UNEXPECTED",
196
- message: "OpenAI resolve threw an unexpected error",
197
- originalErr: e instanceof Error ? e.message : String(e)
198
- });
199
- return { success: false };
200
- }
201
- }
202
- };
203
- };
204
-
205
- export { openAIResolver };