@nocode-factory/sanity-kit 2.65.0-rc.2 → 2.65.0-rc.4
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/CHANGELOG.md +18 -0
- package/bin/ncf-kit.mjs +7 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +141 -54
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +10 -3
- package/src/form/TranslationTodoInput.tsx +5 -1
- package/src/lib/aiTranslate.ts +72 -11
- package/src/lib/propagate.ts +29 -1
- package/src/lib/translateDocument.ts +74 -31
- package/src/tools/pages/LanguagesSync.tsx +10 -1
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -7,7 +7,7 @@ import {useKitClient} from '../hooks/useKitClient'
|
|
|
7
7
|
import {hasChanges, propagate, type PropagationResult, type SchemaTypeLike} from '../lib/propagate'
|
|
8
8
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
9
9
|
import {collectTexts, setAtKey, valueAtKey} from '../lib/aiTexts'
|
|
10
|
-
import {
|
|
10
|
+
import {translateValuesSettled} from '../lib/aiTranslate'
|
|
11
11
|
import {createTranslatedVersion, translationsOf} from '../lib/translateDocument'
|
|
12
12
|
import {isReplaceable, readTrace, recordTrace} from '../lib/translationTrace'
|
|
13
13
|
import {localizeReferences} from '../lib/localizeReferences'
|
|
@@ -204,10 +204,17 @@ function PropagateDialog(props: {
|
|
|
204
204
|
const values = toDo.map((path) => valueAtKey(after, path))
|
|
205
205
|
// Texte vidé dans la version principale : vidé aussi (suit la valeur par défaut).
|
|
206
206
|
const toSend = values.map((v) => (collectTexts(v).some((s) => s.trim()) ? v : undefined))
|
|
207
|
-
|
|
207
|
+
// Traduction partielle : un texte raté reste « To translate », les autres sont gardés.
|
|
208
|
+
const result = await translateValuesSettled(config.history, source, t.language, toSend.map((v) => v ?? ''))
|
|
209
|
+
const missed = new Set(result.failed)
|
|
210
|
+
if (result.error) {
|
|
211
|
+
failed = true
|
|
212
|
+
aiError = result.error
|
|
213
|
+
}
|
|
208
214
|
const done = new Set<string>()
|
|
209
215
|
toDo.forEach((path, n) => {
|
|
210
|
-
|
|
216
|
+
if (missed.has(n)) return
|
|
217
|
+
const value = toSend[n] === undefined ? undefined : result.values[n]
|
|
211
218
|
if (setAtKey(doc, path, value)) {
|
|
212
219
|
done.add(path)
|
|
213
220
|
if (value !== undefined) written.push({path, value})
|
|
@@ -35,7 +35,11 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
35
35
|
.getDocument(sourceId)
|
|
36
36
|
.then((doc) => {
|
|
37
37
|
if (!alive) return
|
|
38
|
-
const
|
|
38
|
+
const value = valueAtKey(doc, key)
|
|
39
|
+
// Slug : sa valeur est dans `current` (ce n'est pas un texte). Avant, la source
|
|
40
|
+
// d'un slug s'affichait « vide » alors qu'il était rempli (vu sur JAF).
|
|
41
|
+
const slug = value && typeof value === 'object' && typeof (value as {current?: unknown}).current === 'string' ? (value as {current: string}).current : ''
|
|
42
|
+
const text = slug || (typeof value === 'string' ? value : collectTexts(value).join('').trim())
|
|
39
43
|
setMaster(text || '(empty: follows the component default)')
|
|
40
44
|
})
|
|
41
45
|
.catch(() => alive && setMaster(null))
|
package/src/lib/aiTranslate.ts
CHANGED
|
@@ -6,8 +6,11 @@ export interface TranslateService {
|
|
|
6
6
|
projectKey: string
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
// Lots MODESTES (kit >= 2.65.0) : au-delà, la réponse de l'IA arrive parfois incomplète ou
|
|
10
|
+
// mal formée (« bad_model_output », vu sur JAF avec 66 textes d'une page) et tout le lot
|
|
11
|
+
// échouait. Un lot qui échoue est redécoupé en deux, jusqu'au texte seul.
|
|
12
|
+
const MAX_TEXTS = 30
|
|
13
|
+
const MAX_CHARS = 6_000
|
|
11
14
|
|
|
12
15
|
const MESSAGES: Record<string, string> = {
|
|
13
16
|
daily_limit: 'Daily AI translation limit reached for this project.',
|
|
@@ -15,6 +18,19 @@ const MESSAGES: Record<string, string> = {
|
|
|
15
18
|
bad_key: 'This project is not registered in the NCF kit (npx ncf-kit setup).',
|
|
16
19
|
not_configured: 'AI translation is not configured on the NCF kit service.',
|
|
17
20
|
too_long: 'Text too long to translate at once.',
|
|
21
|
+
bad_model_output: 'The AI returned an unreadable answer.',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Erreurs qui ne se règlent pas en redécoupant le lot (inutile de réessayer texte par texte). */
|
|
25
|
+
const FATAL = new Set(['daily_limit', 'project_inactive', 'bad_key', 'not_configured'])
|
|
26
|
+
|
|
27
|
+
class TranslateError extends Error {
|
|
28
|
+
constructor(
|
|
29
|
+
message: string,
|
|
30
|
+
readonly code: string,
|
|
31
|
+
) {
|
|
32
|
+
super(message)
|
|
33
|
+
}
|
|
18
34
|
}
|
|
19
35
|
|
|
20
36
|
async function call(service: TranslateService, from: string, to: string, texts: string[]): Promise<string[]> {
|
|
@@ -24,24 +40,52 @@ async function call(service: TranslateService, from: string, to: string, texts:
|
|
|
24
40
|
body: JSON.stringify({key: service.projectKey, from, to, texts}),
|
|
25
41
|
})
|
|
26
42
|
const body = (await response.json().catch(() => ({}))) as {texts?: string[]; error?: string}
|
|
27
|
-
if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length)
|
|
28
|
-
|
|
43
|
+
if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) {
|
|
44
|
+
const code = body.error ?? (response.ok ? 'bad_model_output' : String(response.status))
|
|
45
|
+
throw new TranslateError(MESSAGES[code] ?? `AI translation failed (${code}).`, code)
|
|
46
|
+
}
|
|
29
47
|
return body.texts
|
|
30
48
|
}
|
|
31
49
|
|
|
32
50
|
/**
|
|
33
|
-
* Traduit
|
|
34
|
-
*
|
|
51
|
+
* Traduit un lot ; s'il échoue (réponse mal formée, texte trop long...), le redécoupe en
|
|
52
|
+
* deux jusqu'au texte seul. Rend une traduction par texte, ou null pour un texte raté.
|
|
35
53
|
*/
|
|
36
|
-
|
|
54
|
+
async function translateBatch(service: TranslateService, from: string, to: string, texts: string[], errors: string[]): Promise<(string | null)[]> {
|
|
55
|
+
try {
|
|
56
|
+
return await call(service, from, to, texts)
|
|
57
|
+
} catch (cause) {
|
|
58
|
+
const error = cause instanceof TranslateError ? cause : new TranslateError(cause instanceof Error ? cause.message : String(cause), 'unknown')
|
|
59
|
+
if (FATAL.has(error.code)) throw error
|
|
60
|
+
if (texts.length === 1) {
|
|
61
|
+
errors.push(error.message)
|
|
62
|
+
return [null]
|
|
63
|
+
}
|
|
64
|
+
const half = Math.ceil(texts.length / 2)
|
|
65
|
+
return [...(await translateBatch(service, from, to, texts.slice(0, half), errors)), ...(await translateBatch(service, from, to, texts.slice(half), errors))]
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to`, en lots,
|
|
71
|
+
* SANS tout perdre si une partie échoue : rend les valeurs traduites, les rangs des
|
|
72
|
+
* valeurs ratées (laissées telles quelles) et la raison de l'échec.
|
|
73
|
+
*/
|
|
74
|
+
export async function translateValuesSettled(
|
|
75
|
+
service: TranslateService,
|
|
76
|
+
from: string,
|
|
77
|
+
to: string,
|
|
78
|
+
values: readonly unknown[],
|
|
79
|
+
): Promise<{values: unknown[]; failed: number[]; error: string | null}> {
|
|
37
80
|
const perValue = values.map((v) => collectTexts(v))
|
|
38
81
|
const all = perValue.flat()
|
|
39
|
-
const translated: string[] = []
|
|
82
|
+
const translated: (string | null)[] = []
|
|
83
|
+
const errors: string[] = []
|
|
40
84
|
let batch: string[] = []
|
|
41
85
|
let size = 0
|
|
42
86
|
const flush = async () => {
|
|
43
87
|
if (!batch.length) return
|
|
44
|
-
translated.push(...(await
|
|
88
|
+
translated.push(...(await translateBatch(service, from, to, batch, errors)))
|
|
45
89
|
batch = []
|
|
46
90
|
size = 0
|
|
47
91
|
}
|
|
@@ -52,10 +96,27 @@ export async function translateValues(service: TranslateService, from: string, t
|
|
|
52
96
|
}
|
|
53
97
|
await flush()
|
|
54
98
|
let offset = 0
|
|
55
|
-
|
|
99
|
+
const failed: number[] = []
|
|
100
|
+
const out = values.map((value, n) => {
|
|
56
101
|
const count = perValue[n]!.length
|
|
57
102
|
const slice = translated.slice(offset, offset + count)
|
|
58
103
|
offset += count
|
|
59
|
-
|
|
104
|
+
if (!count) return value
|
|
105
|
+
if (slice.some((t) => t === null)) {
|
|
106
|
+
failed.push(n)
|
|
107
|
+
return value
|
|
108
|
+
}
|
|
109
|
+
return replaceTexts(value, slice as string[])
|
|
60
110
|
})
|
|
111
|
+
return {values: out, failed, error: failed.length ? `${failed.length} text(s) not translated: ${[...new Set(errors)].join(' ')}` : null}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
|
|
116
|
+
* mêmes valeurs, textes traduits. Échoue si une valeur n'a pas pu être traduite.
|
|
117
|
+
*/
|
|
118
|
+
export async function translateValues(service: TranslateService, from: string, to: string, values: readonly unknown[]): Promise<unknown[]> {
|
|
119
|
+
const result = await translateValuesSettled(service, from, to, values)
|
|
120
|
+
if (result.error) throw new Error(result.error)
|
|
121
|
+
return result.values
|
|
61
122
|
}
|
package/src/lib/propagate.ts
CHANGED
|
@@ -44,6 +44,23 @@ export interface PropagationResult {
|
|
|
44
44
|
const VALUE_TYPE_NAMES = new Set(['image', 'file', 'reference', 'crossDatasetReference', 'slug', 'geopoint', 'url', 'email', 'date', 'datetime', 'number', 'boolean'])
|
|
45
45
|
const SKIP_KEYS = new Set(['language', 'slug'])
|
|
46
46
|
|
|
47
|
+
// Champs texte qui ne se TRADUISENT pas (kit >= 2.65.0, vu sur JAF : ancres traduites en
|
|
48
|
+
// « start of school year », couleur « sun », téléphone et email envoyés à l'IA) :
|
|
49
|
+
// - par leur nom : ancres (d'une section ou de la page visée par un lien), adresses,
|
|
50
|
+
// jetons de couleur, codes, icônes ;
|
|
51
|
+
// - par leur valeur : email, téléphone, adresse web ou chemin, ancre, couleur hexadécimale.
|
|
52
|
+
const NON_TEXT_NAMES = /^(anchor|pageAnchor|.*Anchor|href|url|link|email|mail|phone|tel|telephone|token|customHex|hex|color|colour|icon|code|key|id|slug|path|target|rel)$/i
|
|
53
|
+
const NON_TEXT_VALUE = /^(?:[\w.+-]+@[\w-]+\.[\w.-]+|\+?[\d\s().-]{6,}|(?:https?:|mailto:|tel:)\S*|[/#]\S*|#[0-9a-f]{3,8})$/i
|
|
54
|
+
|
|
55
|
+
/** Un texte libre qui n'est pas à traduire (nom du champ, ou valeur technique). */
|
|
56
|
+
export function isNonTextValue(name: string | undefined, value: unknown): boolean {
|
|
57
|
+
if (name && NON_TEXT_NAMES.test(name)) return true
|
|
58
|
+
return typeof value === 'string' && NON_TEXT_VALUE.test(value.trim())
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Dernier nom de champ d'un chemin lisible (« sections[k].cta.anchor » → « anchor »). */
|
|
62
|
+
const lastName = (path: string) => path.split('.').pop()?.replace(/\[.*$/, '')
|
|
63
|
+
|
|
47
64
|
const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
48
65
|
const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
|
|
49
66
|
const keyed = (v: unknown): v is Record<string, unknown>[] => Array.isArray(v) && v.length > 0 && v.every((i) => isObj(i) && typeof i._key === 'string')
|
|
@@ -61,6 +78,9 @@ export function kindOf(t: SchemaTypeLike | undefined, value: unknown): FieldKind
|
|
|
61
78
|
// Champ propre à l'instance (options.instanceOnly, ex. ancre d'une section) :
|
|
62
79
|
// une valeur recopiée telle quelle, jamais traduite.
|
|
63
80
|
if (t.options?.instanceOnly) return 'value'
|
|
81
|
+
// Image avec ses propres champs (alt, légende) : ses textes se traduisent, l'image
|
|
82
|
+
// (asset, recadrage) est recopiée. Avant, l'image entière était recopiée, alt compris.
|
|
83
|
+
if (names.includes('image') && hasOwnFields(t)) return 'object'
|
|
64
84
|
if (names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return 'value'
|
|
65
85
|
if (t.jsonType === 'array') {
|
|
66
86
|
const of = t.of ?? []
|
|
@@ -78,6 +98,11 @@ export function kindOf(t: SchemaTypeLike | undefined, value: unknown): FieldKind
|
|
|
78
98
|
return 'value'
|
|
79
99
|
}
|
|
80
100
|
|
|
101
|
+
function hasOwnFields(t: SchemaTypeLike | undefined): boolean {
|
|
102
|
+
for (let c = t; c; c = c.type) if (c.fields?.some((f) => !['asset', 'hotspot', 'crop', 'media'].includes(f.name))) return true
|
|
103
|
+
return false
|
|
104
|
+
}
|
|
105
|
+
|
|
81
106
|
function fieldType(t: SchemaTypeLike | undefined, name: string): SchemaTypeLike | undefined {
|
|
82
107
|
for (let c = t; c; c = c.type) {
|
|
83
108
|
const f = c.fields?.find((x) => x.name === name)
|
|
@@ -104,6 +129,7 @@ interface Acc {
|
|
|
104
129
|
/** Tous les textes d'un élément ajouté : à traduire. */
|
|
105
130
|
function collectTexts(value: unknown, t: SchemaTypeLike | undefined, path: string, acc: Acc) {
|
|
106
131
|
const kind = kindOf(t, value)
|
|
132
|
+
if (kind === 'text' && typeof value === 'string' && isNonTextValue(lastName(path), value)) return
|
|
107
133
|
if (kind === 'text') {
|
|
108
134
|
if (value !== undefined && value !== null && value !== '') acc.toTranslate.push(path)
|
|
109
135
|
} else if (kind === 'object' && isObj(value)) {
|
|
@@ -117,7 +143,9 @@ const ABSENT = Symbol('absent')
|
|
|
117
143
|
|
|
118
144
|
function merge(target: unknown, before: unknown, after: unknown, t: SchemaTypeLike | undefined, path: string, acc: Acc): unknown {
|
|
119
145
|
if (same(before, after)) return target === undefined ? ABSENT : target
|
|
120
|
-
|
|
146
|
+
let kind = kindOf(t, after ?? before)
|
|
147
|
+
// Texte libre technique (ancre, email, téléphone, couleur...) : recopié, jamais traduit.
|
|
148
|
+
if (kind === 'text' && typeof (after ?? before) === 'string' && isNonTextValue(lastName(path), after ?? before)) kind = 'value'
|
|
121
149
|
|
|
122
150
|
if (kind === 'text') {
|
|
123
151
|
if (after === undefined || after === null || after === '') {
|
|
@@ -4,8 +4,8 @@ import type {SanityClient} from 'sanity'
|
|
|
4
4
|
import type {ResolvedKitConfig} from '../config/types'
|
|
5
5
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
6
6
|
import {collectTexts, setAtKey, valueAtKey} from './aiTexts'
|
|
7
|
-
import {
|
|
8
|
-
import {propagate, type SchemaTypeLike} from './propagate'
|
|
7
|
+
import {translateValuesSettled} from './aiTranslate'
|
|
8
|
+
import {isNonTextValue, propagate, type SchemaTypeLike} from './propagate'
|
|
9
9
|
import {slugify} from './slugify'
|
|
10
10
|
import {hashValue, recordTrace} from './translationTrace'
|
|
11
11
|
|
|
@@ -84,6 +84,39 @@ export async function linkTranslations(
|
|
|
84
84
|
* traduits par l'IA si `ai` (service du kit), slug traduit et unique, publiée si
|
|
85
85
|
* tout est traduit (sinon brouillon et textes « To translate »). Relie la version.
|
|
86
86
|
*/
|
|
87
|
+
/** Champ slug d'un type (registre des pages du kit, sinon « slug » s'il est rempli). */
|
|
88
|
+
function slugFieldOf(config: ResolvedKitConfig, type: string, source: Doc): string | null {
|
|
89
|
+
const pageType = config.pageTypes.find((t) => t.type === type)
|
|
90
|
+
const field = pageType?.slugField ?? ((source.slug as {current?: string} | undefined)?.current ? 'slug' : null)
|
|
91
|
+
return field && (source[field] as {current?: string} | undefined)?.current ? field : null
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Slug d'une version traduite : tiré de son titre (déjà traduit), unique dans la langue
|
|
96
|
+
* (-2, -3...) ; à défaut de titre, le slug de la version source. JAMAIS « traduit » comme
|
|
97
|
+
* un texte (vu sur JAF : une reprise avait vidé le slug d'une page).
|
|
98
|
+
*/
|
|
99
|
+
async function translatedSlug(client: SanityClient, config: ResolvedKitConfig, type: string, doc: Doc, source: Doc, language: string): Promise<{_type: 'slug'; current: string}> {
|
|
100
|
+
const field = config.i18n?.field ?? 'language'
|
|
101
|
+
const pageType = config.pageTypes.find((t) => t.type === type)
|
|
102
|
+
const slugField = slugFieldOf(config, type, source) ?? 'slug'
|
|
103
|
+
const titleField = pageType?.titleField ?? 'title'
|
|
104
|
+
const title = typeof doc[titleField] === 'string' ? (doc[titleField] as string) : ''
|
|
105
|
+
const base = slugify(title) || String((source[slugField] as {current: string}).current)
|
|
106
|
+
const id = typeof doc._id === 'string' ? doc._id.replace(/^drafts\./, '') : ''
|
|
107
|
+
let slug = base
|
|
108
|
+
for (
|
|
109
|
+
let n = 2;
|
|
110
|
+
await client.fetch<boolean>(
|
|
111
|
+
`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**")) && _id != $id]) > 0`,
|
|
112
|
+
{type, slug, language, id},
|
|
113
|
+
);
|
|
114
|
+
n++
|
|
115
|
+
)
|
|
116
|
+
slug = `${base}-${n}`
|
|
117
|
+
return {_type: 'slug', current: slug}
|
|
118
|
+
}
|
|
119
|
+
|
|
87
120
|
export async function createTranslatedVersion(opts: {
|
|
88
121
|
client: SanityClient
|
|
89
122
|
config: ResolvedKitConfig
|
|
@@ -113,9 +146,13 @@ export async function createTranslatedVersion(opts: {
|
|
|
113
146
|
try {
|
|
114
147
|
const values = remaining.map((path) => valueAtKey(source, path))
|
|
115
148
|
const toSend = values.map((v) => (collectTexts(v).some((s) => s.trim()) ? v : undefined))
|
|
116
|
-
|
|
149
|
+
// Traduction partielle : un texte raté reste « To translate », les autres sont gardés.
|
|
150
|
+
const result = await translateValuesSettled(config.history, sourceLanguage, language, toSend.map((v) => v ?? ''))
|
|
151
|
+
const failed = new Set(result.failed)
|
|
152
|
+
if (result.error) aiError = result.error
|
|
117
153
|
remaining = remaining.filter((path, n) => {
|
|
118
|
-
|
|
154
|
+
if (failed.has(n)) return true
|
|
155
|
+
const value = toSend[n] === undefined ? undefined : result.values[n]
|
|
119
156
|
const ok = setAtKey(doc, path, value)
|
|
120
157
|
if (ok && value !== undefined) written.push({path, value})
|
|
121
158
|
return !ok
|
|
@@ -129,23 +166,8 @@ export async function createTranslatedVersion(opts: {
|
|
|
129
166
|
Object.assign(doc, await localizeReferences(client, doc, language))
|
|
130
167
|
// Slug : traduit depuis le titre, unique dans la langue (-2, -3...).
|
|
131
168
|
const pageType = config.pageTypes.find((t) => t.type === type)
|
|
132
|
-
const slugField =
|
|
133
|
-
if (slugField
|
|
134
|
-
const titleField = pageType?.titleField ?? 'title'
|
|
135
|
-
const title = typeof doc[titleField] === 'string' ? (doc[titleField] as string) : ''
|
|
136
|
-
const base = slugify(title) || String((source[slugField] as {current: string}).current)
|
|
137
|
-
let slug = base
|
|
138
|
-
for (
|
|
139
|
-
let n = 2;
|
|
140
|
-
await client.fetch<boolean>(
|
|
141
|
-
`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`,
|
|
142
|
-
{type, slug, language},
|
|
143
|
-
);
|
|
144
|
-
n++
|
|
145
|
-
)
|
|
146
|
-
slug = `${base}-${n}`
|
|
147
|
-
doc[slugField] = {_type: 'slug', current: slug}
|
|
148
|
-
}
|
|
169
|
+
const slugField = slugFieldOf(config, type, source)
|
|
170
|
+
if (slugField) doc[slugField] = await translatedSlug(client, config, type, doc, source, language)
|
|
149
171
|
// Slug non traduit (titre resté dans la langue source) : marqué « To translate »
|
|
150
172
|
// avec le titre, la règle d'or veut un slug dans la langue de la version.
|
|
151
173
|
if (slugField && remaining.includes(pageType?.titleField ?? 'title') && !remaining.includes(slugField)) remaining = [...remaining, slugField]
|
|
@@ -182,27 +204,31 @@ export async function fillTranslation(opts: {
|
|
|
182
204
|
target: Doc
|
|
183
205
|
sourceLanguage: string
|
|
184
206
|
language: string
|
|
185
|
-
|
|
186
|
-
|
|
207
|
+
/** Trace de l'IA (readTrace) : un texte déjà rendu à l'identique n'est pas renvoyé. */
|
|
208
|
+
trace?: Map<string, string>
|
|
209
|
+
}): Promise<{document: Doc; translated: number; written: {path: string; value: unknown}[]; failed: number; error: string | null}> {
|
|
210
|
+
const {config, schemaType, source, sourceLanguage, language, trace} = opts
|
|
187
211
|
const document = structuredClone(opts.target) as Doc
|
|
188
212
|
// Blocs (champs de premier niveau) absents de la cible : recopiés tels quels.
|
|
189
213
|
for (const [key, value] of Object.entries(source)) {
|
|
190
214
|
if (key.startsWith('_') || key === (config.i18n?.field ?? 'language')) continue
|
|
191
215
|
if (document[key] === undefined || document[key] === null) document[key] = structuredClone(value)
|
|
192
216
|
}
|
|
193
|
-
const paths = untranslatedPaths(source, document, schemaType)
|
|
194
|
-
if (!paths.length || !config.history) return {document, translated: 0, written: []}
|
|
195
|
-
|
|
217
|
+
const paths = untranslatedPaths(source, document, schemaType, trace)
|
|
218
|
+
if (!paths.length || !config.history) return {document, translated: 0, written: [], failed: 0, error: null}
|
|
219
|
+
// Traduction partielle : un texte raté reste tel quel (reproposé au prochain passage).
|
|
220
|
+
const result = await translateValuesSettled(
|
|
196
221
|
config.history,
|
|
197
222
|
sourceLanguage,
|
|
198
223
|
language,
|
|
199
224
|
paths.map((p) => valueAtKey(source, p)),
|
|
200
225
|
)
|
|
226
|
+
const failed = new Set(result.failed)
|
|
201
227
|
const written: {path: string; value: unknown}[] = []
|
|
202
228
|
paths.forEach((p, n) => {
|
|
203
|
-
if (setAtKey(document, p,
|
|
229
|
+
if (!failed.has(n) && setAtKey(document, p, result.values[n])) written.push({path: p, value: result.values[n]})
|
|
204
230
|
})
|
|
205
|
-
return {document, translated: written.length, written}
|
|
231
|
+
return {document, translated: written.length, written, failed: failed.size, error: result.error}
|
|
206
232
|
}
|
|
207
233
|
|
|
208
234
|
/**
|
|
@@ -247,15 +273,26 @@ export async function retryTranslatedVersion(opts: {
|
|
|
247
273
|
if (!source || !current) return {published: false, remaining: todo.paths, aiError: !source ? 'source version not found (unpublished or deleted)' : 'translated version not found'}
|
|
248
274
|
if (!config.history) return {published: false, remaining: todo.paths, aiError: 'AI translation is not configured (kit project key missing)'}
|
|
249
275
|
const {_rev, _createdAt, _updatedAt, ...doc} = structuredClone(current) as Doc
|
|
250
|
-
|
|
276
|
+
const type = String(current._type)
|
|
277
|
+
// Slug : jamais traduit comme un texte, recalculé depuis le titre traduit (plus bas).
|
|
278
|
+
// Valeurs techniques (ancre, email, téléphone, couleur) marquées par une version
|
|
279
|
+
// antérieure du kit : retirées de la liste, gardées telles quelles.
|
|
280
|
+
const slugField = slugFieldOf(config, type, source)
|
|
281
|
+
const nameOf = (path: string) => path.split('.').pop()?.replace(/\[.*$/, '')
|
|
282
|
+
const technical = (path: string) => isNonTextValue(nameOf(path), valueAtKey(source, path))
|
|
283
|
+
const slugPending = Boolean(slugField && todo.paths.includes(slugField))
|
|
284
|
+
let remaining = todo.paths.filter((p) => p !== slugField && !technical(p))
|
|
251
285
|
let aiError: string | null = null
|
|
252
286
|
const written: {path: string; value: unknown}[] = []
|
|
253
287
|
try {
|
|
254
288
|
const values = remaining.map((path) => valueAtKey(source, path))
|
|
255
289
|
const toSend = values.map((v) => (collectTexts(v).some((s) => s.trim()) ? v : undefined))
|
|
256
|
-
const
|
|
290
|
+
const result = await translateValuesSettled(config.history, todo.sourceLanguage, language, toSend.map((v) => v ?? ''))
|
|
291
|
+
const failed = new Set(result.failed)
|
|
292
|
+
if (result.error) aiError = result.error
|
|
257
293
|
remaining = remaining.filter((path, n) => {
|
|
258
|
-
|
|
294
|
+
if (failed.has(n)) return true
|
|
295
|
+
const value = toSend[n] === undefined ? undefined : result.values[n]
|
|
259
296
|
const ok = setAtKey(doc, path, value)
|
|
260
297
|
if (ok && value !== undefined) written.push({path, value})
|
|
261
298
|
return !ok
|
|
@@ -263,6 +300,12 @@ export async function retryTranslatedVersion(opts: {
|
|
|
263
300
|
} catch (cause) {
|
|
264
301
|
aiError = cause instanceof Error ? cause.message : String(cause)
|
|
265
302
|
}
|
|
303
|
+
if (slugPending && slugField) {
|
|
304
|
+
const titleField = config.pageTypes.find((t) => t.type === type)?.titleField ?? 'title'
|
|
305
|
+
// Titre traduit : slug recalculé depuis lui ; sinon le slug reste « To translate ».
|
|
306
|
+
if (remaining.includes(titleField)) remaining = [...remaining, slugField]
|
|
307
|
+
else doc[slugField] = await translatedSlug(client, config, type, doc, source, language)
|
|
308
|
+
}
|
|
266
309
|
const published = publish && !remaining.length && !aiError
|
|
267
310
|
const tx = client.transaction()
|
|
268
311
|
if (published) {
|
|
@@ -222,7 +222,15 @@ export function LanguagesSync() {
|
|
|
222
222
|
const id = String(published._id)
|
|
223
223
|
// Brouillon : complété depuis le brouillon en cours s'il existe (rien n'est défait).
|
|
224
224
|
const base = (await client.getDocument<Doc>(`drafts.${id}`)) ?? published
|
|
225
|
-
const filled = await fillTranslation({
|
|
225
|
+
const filled = await fillTranslation({
|
|
226
|
+
config,
|
|
227
|
+
schemaType: typeOf(defaultsType),
|
|
228
|
+
source: src,
|
|
229
|
+
target: base,
|
|
230
|
+
sourceLanguage: d.from,
|
|
231
|
+
language: d.language,
|
|
232
|
+
trace: await readTrace(client, id),
|
|
233
|
+
})
|
|
226
234
|
const {_rev, _updatedAt, _createdAt, ...doc} = filled.document
|
|
227
235
|
const tx = client.transaction()
|
|
228
236
|
if (publishNow) {
|
|
@@ -233,6 +241,7 @@ export function LanguagesSync() {
|
|
|
233
241
|
await recordTrace(client, id, filled.written, {sourceId: String(src._id), sourceLanguage: d.from})
|
|
234
242
|
// Textes rendus à l'identique par l'IA (noms propres, marques) : signalés à vérifier.
|
|
235
243
|
const unchanged = filled.written.filter((w) => JSON.stringify(w.value) === JSON.stringify(valueAtKey(src, w.path))).length
|
|
244
|
+
if (filled.error) fail(what, `${filled.error} The other texts were kept; retry to translate the rest.`)
|
|
236
245
|
lines.push({
|
|
237
246
|
tone: publishNow ? 'positive' : 'caution',
|
|
238
247
|
text: `${what}: ${filled.translated} text(s) translated${publishNow ? ' and published' : ' in the draft, to review then publish'}${unchanged ? ` (${unchanged} kept identical by the AI: names, brands... check them)` : ''}`,
|
package/src/version.ts
CHANGED