@nocode-factory/sanity-kit 2.65.0-rc.6 → 2.66.0-rc.1

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/dist/index.js CHANGED
@@ -1423,7 +1423,7 @@ function explainGrantError(error) {
1423
1423
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1424
1424
  * le vérifie.
1425
1425
  */
1426
- const KIT_VERSION = "2.65.0-rc.6";
1426
+ const KIT_VERSION = "2.66.0-rc.1";
1427
1427
  /**
1428
1428
  * Signale ce Studio au service du kit, une fois par montage.
1429
1429
  *
@@ -1931,7 +1931,7 @@ function useKitUpdate() {
1931
1931
  !controller.signal.aborted && body?.version && setLatest(body.version);
1932
1932
  }).catch(() => {}), () => controller.abort();
1933
1933
  }, []);
1934
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.65.0-rc.6") > 0);
1934
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.66.0-rc.1") > 0);
1935
1935
  return {
1936
1936
  current: KIT_VERSION,
1937
1937
  latest,
@@ -3941,18 +3941,7 @@ const MESSAGES = {
3941
3941
  project_inactive: "This project is not active in the NCF kit.",
3942
3942
  bad_key: "This project is not registered in the NCF kit (npx ncf-kit setup).",
3943
3943
  not_configured: "AI translation is not configured on the NCF kit service.",
3944
- too_long: "Text too long to translate at once.",
3945
- bad_model_output: "The AI returned an unreadable answer."
3946
- }, FATAL = /* @__PURE__ */ new Set([
3947
- "daily_limit",
3948
- "project_inactive",
3949
- "bad_key",
3950
- "not_configured"
3951
- ]);
3952
- var TranslateError = class extends Error {
3953
- constructor(message, code) {
3954
- super(message), this.code = code;
3955
- }
3944
+ too_long: "Text too long to translate at once."
3956
3945
  };
3957
3946
  async function call(service, from, to, texts) {
3958
3947
  let response = await fetch(`${service.endpoint}/translate`, {
@@ -3965,56 +3954,24 @@ async function call(service, from, to, texts) {
3965
3954
  texts
3966
3955
  })
3967
3956
  }), body = await response.json().catch(() => ({}));
3968
- if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) {
3969
- let code = body.error ?? (response.ok ? "bad_model_output" : String(response.status));
3970
- throw new TranslateError(MESSAGES[code] ?? `AI translation failed (${code}).`, code);
3971
- }
3957
+ if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) throw Error(MESSAGES[body.error ?? ""] ?? `AI translation failed (${body.error ?? response.status}).`);
3972
3958
  return body.texts;
3973
3959
  }
3974
3960
  /**
3975
- * Traduit un lot ; s'il échoue (réponse mal formée, texte trop long...), le redécoupe en
3976
- * deux jusqu'au texte seul. Rend une traduction par texte, ou null pour un texte raté.
3977
- */
3978
- async function translateBatch(service, from, to, texts, errors) {
3979
- try {
3980
- return await call(service, from, to, texts);
3981
- } catch (cause) {
3982
- let error = cause instanceof TranslateError ? cause : new TranslateError(cause instanceof Error ? cause.message : String(cause), "unknown");
3983
- if (FATAL.has(error.code)) throw error;
3984
- if (texts.length === 1) return errors.push(error.message), [null];
3985
- let half = Math.ceil(texts.length / 2);
3986
- return [...await translateBatch(service, from, to, texts.slice(0, half), errors), ...await translateBatch(service, from, to, texts.slice(half), errors)];
3987
- }
3988
- }
3989
- /**
3990
- * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to`, en lots,
3991
- * SANS tout perdre si une partie échoue : rend les valeurs traduites, les rangs des
3992
- * valeurs ratées (laissées telles quelles) et la raison de l'échec.
3993
- */
3994
- async function translateValuesSettled(service, from, to, values) {
3995
- let perValue = values.map((v) => collectTexts$1(v)), all = perValue.flat(), translated = [], errors = [], batch = [], size = 0, flush = async () => {
3996
- batch.length && (translated.push(...await translateBatch(service, from, to, batch, errors)), batch = [], size = 0);
3997
- };
3998
- for (let text of all) (batch.length >= 30 || size + text.length > 6e3) && await flush(), batch.push(text), size += text.length;
3999
- await flush();
4000
- let offset = 0, failed = [];
4001
- return {
4002
- values: values.map((value, n) => {
4003
- let count = perValue[n].length, slice = translated.slice(offset, offset + count);
4004
- return offset += count, count ? slice.some((t) => t === null) ? (failed.push(n), value) : replaceTexts(value, slice) : value;
4005
- }),
4006
- failed,
4007
- error: failed.length ? `${failed.length} text(s) not translated: ${[...new Set(errors)].join(" ")}` : null
4008
- };
4009
- }
4010
- /**
4011
3961
  * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
4012
- * mêmes valeurs, textes traduits. Échoue si une valeur n'a pas pu être traduite.
3962
+ * mêmes valeurs, textes traduits. Découpe en lots si besoin.
4013
3963
  */
4014
3964
  async function translateValues(service, from, to, values) {
4015
- let result = await translateValuesSettled(service, from, to, values);
4016
- if (result.error) throw Error(result.error);
4017
- return result.values;
3965
+ let perValue = values.map((v) => collectTexts$1(v)), all = perValue.flat(), translated = [], batch = [], size = 0, flush = async () => {
3966
+ batch.length && (translated.push(...await call(service, from, to, batch)), batch = [], size = 0);
3967
+ };
3968
+ for (let text of all) (batch.length >= 250 || size + text.length > 3e4) && await flush(), batch.push(text), size += text.length;
3969
+ await flush();
3970
+ let offset = 0;
3971
+ return values.map((value, n) => {
3972
+ let count = perValue[n].length, slice = translated.slice(offset, offset + count);
3973
+ return offset += count, count ? replaceTexts(value, slice) : value;
3974
+ });
4018
3975
  }
4019
3976
  const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
4020
3977
  "image",
@@ -4029,13 +3986,7 @@ const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
4029
3986
  "datetime",
4030
3987
  "number",
4031
3988
  "boolean"
4032
- ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), 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, NON_TEXT_VALUE = /^(?:[\w.+-]+@[\w-]+\.[\w.-]+|\+?[\d\s().-]{6,}|(?:https?:|mailto:|tel:)\S*|[/#]\S*|#[0-9a-f]{3,8})$/i;
4033
- /** Un texte libre qui n'est pas à traduire (nom du champ, ou valeur technique). */
4034
- function isNonTextValue(name, value) {
4035
- return name && NON_TEXT_NAMES.test(name) ? !0 : typeof value == "string" && NON_TEXT_VALUE.test(value.trim());
4036
- }
4037
- /** Dernier nom de champ d'un chemin lisible (« sections[k].cta.anchor » → « anchor »). */
4038
- const lastName = (path) => path.split(".").pop()?.replace(/\[.*$/, ""), isObj$2 = (v) => typeof v == "object" && !!v && !Array.isArray(v), same$2 = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null), keyed$1 = (v) => Array.isArray(v) && v.length > 0 && v.every((i) => isObj$2(i) && typeof i._key == "string");
3989
+ ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj$2 = (v) => typeof v == "object" && !!v && !Array.isArray(v), same$2 = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null), keyed$1 = (v) => Array.isArray(v) && v.length > 0 && v.every((i) => isObj$2(i) && typeof i._key == "string");
4039
3990
  function typeNames(t) {
4040
3991
  let out = [];
4041
3992
  for (let c = t; c; c = c.type) c.name && out.push(c.name);
@@ -4045,9 +3996,7 @@ function typeNames(t) {
4045
3996
  function kindOf(t, value) {
4046
3997
  if (t) {
4047
3998
  let names = typeNames(t);
4048
- if (t.options?.instanceOnly) return "value";
4049
- if (names.includes("image") && hasOwnFields(t)) return "object";
4050
- if (names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
3999
+ if (t.options?.instanceOnly || names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
4051
4000
  if (t.jsonType === "array") {
4052
4001
  let of = t.of ?? [];
4053
4002
  if (of.some((m) => typeNames(m).includes("block"))) return "text";
@@ -4059,15 +4008,6 @@ function kindOf(t, value) {
4059
4008
  }
4060
4009
  return keyed$1(value) ? "list" : isObj$2(value) ? "object" : "value";
4061
4010
  }
4062
- function hasOwnFields(t) {
4063
- for (let c = t; c; c = c.type) if (c.fields?.some((f) => ![
4064
- "asset",
4065
- "hotspot",
4066
- "crop",
4067
- "media"
4068
- ].includes(f.name))) return !0;
4069
- return !1;
4070
- }
4071
4011
  function fieldType(t, name) {
4072
4012
  for (let c = t; c; c = c.type) {
4073
4013
  let f = c.fields?.find((x) => x.name === name);
@@ -4082,17 +4022,15 @@ function itemType(t, item) {
4082
4022
  /** Tous les textes d'un élément ajouté : à traduire. */
4083
4023
  function collectTexts(value, t, path, acc) {
4084
4024
  let kind = kindOf(t, value);
4085
- if (!(kind === "text" && typeof value == "string" && isNonTextValue(lastName(path), value))) {
4086
- if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
4087
- else if (kind === "object" && isObj$2(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
4088
- else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj$2(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
4089
- }
4025
+ if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
4026
+ else if (kind === "object" && isObj$2(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
4027
+ else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj$2(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
4090
4028
  }
4091
4029
  const ABSENT$1 = Symbol("absent");
4092
4030
  function merge(target, before, after, t, path, acc) {
4093
4031
  if (same$2(before, after)) return target === void 0 ? ABSENT$1 : target;
4094
4032
  let kind = kindOf(t, after ?? before);
4095
- if (kind === "text" && typeof (after ?? before) == "string" && isNonTextValue(lastName(path), after ?? before) && (kind = "value"), kind === "text") return after == null || after === "" ? (target != null && target !== "" && acc.toTranslate.push(path), target === void 0 ? ABSENT$1 : target) : (acc.toTranslate.push(path), target == null || target === "" || same$2(target, before) ? after : target);
4033
+ if (kind === "text") return after == null || after === "" ? (target != null && target !== "" && acc.toTranslate.push(path), target === void 0 ? ABSENT$1 : target) : (acc.toTranslate.push(path), target == null || target === "" || same$2(target, before) ? after : target);
4096
4034
  if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
4097
4035
  if (kind === "object") {
4098
4036
  if (!isObj$2(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
@@ -4245,36 +4183,12 @@ async function linkTranslations(client, sourceId, sourceLanguage, type, created)
4245
4183
  * traduits par l'IA si `ai` (service du kit), slug traduit et unique, publiée si
4246
4184
  * tout est traduit (sinon brouillon et textes « To translate »). Relie la version.
4247
4185
  */
4248
- /** Champ slug d'un type (registre des pages du kit, sinon « slug » s'il est rempli). */
4249
- function slugFieldOf(config, type, source) {
4250
- let field = config.pageTypes.find((t) => t.type === type)?.slugField ?? (source.slug?.current ? "slug" : null);
4251
- return field && source[field]?.current ? field : null;
4252
- }
4253
- /**
4254
- * Slug d'une version traduite : tiré de son titre (déjà traduit), unique dans la langue
4255
- * (-2, -3...) ; à défaut de titre, le slug de la version source. JAMAIS « traduit » comme
4256
- * un texte (vu sur JAF : une reprise avait vidé le slug d'une page).
4257
- */
4258
- async function translatedSlug(client, config, type, doc, source, language) {
4259
- let field = config.i18n?.field ?? "language", pageType = config.pageTypes.find((t) => t.type === type), slugField = slugFieldOf(config, type, source) ?? "slug", titleField = pageType?.titleField ?? "title", base = slugify(typeof doc[titleField] == "string" ? doc[titleField] : "") || String(source[slugField].current), id = typeof doc._id == "string" ? doc._id.replace(/^drafts\./, "") : "", slug = base;
4260
- for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**")) && _id != $id]) > 0`, {
4261
- type,
4262
- slug,
4263
- language,
4264
- id
4265
- }); n++) slug = `${base}-${n}`;
4266
- return {
4267
- _type: "slug",
4268
- current: slug
4269
- };
4270
- }
4271
4186
  async function createTranslatedVersion(opts) {
4272
- let { client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai, publish = !1 } = opts, field = config.i18n?.field ?? "language", result = propagate({}, {}, source, schemaType), { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(result.document), id = translationIdFor(sourceId, sourceLanguage, language), remaining = result.toTranslate, aiError = null, written = [];
4187
+ let { client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai } = opts, field = config.i18n?.field ?? "language", result = propagate({}, {}, source, schemaType), { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(result.document), id = translationIdFor(sourceId, sourceLanguage, language), remaining = result.toTranslate, aiError = null, written = [];
4273
4188
  if (ai && config.history && remaining.length) try {
4274
- let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), result = await translateValuesSettled(config.history, sourceLanguage, language, toSend.map((v) => v ?? "")), failed = new Set(result.failed);
4275
- result.error && (aiError = result.error), remaining = remaining.filter((path, n) => {
4276
- if (failed.has(n)) return !0;
4277
- let value = toSend[n] === void 0 ? void 0 : result.values[n], ok = setAtKey(doc, path, value);
4189
+ let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, sourceLanguage, language, toSend.map((v) => v ?? ""));
4190
+ remaining = remaining.filter((path, n) => {
4191
+ let value = toSend[n] === void 0 ? void 0 : translated[n], ok = setAtKey(doc, path, value);
4278
4192
  return ok && value !== void 0 && written.push({
4279
4193
  path,
4280
4194
  value
@@ -4284,9 +4198,21 @@ async function createTranslatedVersion(opts) {
4284
4198
  aiError = cause instanceof Error ? cause.message : String(cause);
4285
4199
  }
4286
4200
  doc[field] = language, Object.assign(doc, await localizeReferences(client, doc, language));
4287
- let pageType = config.pageTypes.find((t) => t.type === type), slugField = slugFieldOf(config, type, source);
4288
- slugField && (doc[slugField] = await translatedSlug(client, config, type, doc, source, language)), slugField && remaining.includes(pageType?.titleField ?? "title") && !remaining.includes(slugField) && (remaining = [...remaining, slugField]);
4289
- let complete = ai && !remaining.length && !aiError, published = complete && publish;
4201
+ let pageType = config.pageTypes.find((t) => t.type === type), slugField = pageType?.slugField ?? (source.slug?.current ? "slug" : null);
4202
+ if (slugField && source[slugField]?.current) {
4203
+ let titleField = pageType?.titleField ?? "title", base = slugify(typeof doc[titleField] == "string" ? doc[titleField] : "") || String(source[slugField].current), slug = base;
4204
+ for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`, {
4205
+ type,
4206
+ slug,
4207
+ language
4208
+ }); n++) slug = `${base}-${n}`;
4209
+ doc[slugField] = {
4210
+ _type: "slug",
4211
+ current: slug
4212
+ };
4213
+ }
4214
+ slugField && remaining.includes(pageType?.titleField ?? "title") && !remaining.includes(slugField) && (remaining = [...remaining, slugField]);
4215
+ let published = ai && !remaining.length && !aiError;
4290
4216
  await client.createOrReplace({
4291
4217
  ...doc,
4292
4218
  _id: published ? id : `drafts.${id}`,
@@ -4309,9 +4235,7 @@ async function createTranslatedVersion(opts) {
4309
4235
  return redirects && await syncTranslationRedirects(client, redirects, [sourceId]).catch(() => {}), {
4310
4236
  id,
4311
4237
  published,
4312
- complete,
4313
- aiError,
4314
- remaining
4238
+ aiError
4315
4239
  };
4316
4240
  }
4317
4241
  /**
@@ -4321,127 +4245,59 @@ async function createTranslatedVersion(opts) {
4321
4245
  * Rend le document complété et le nombre de textes traduits.
4322
4246
  */
4323
4247
  async function fillTranslation(opts) {
4324
- let { config, schemaType, source, sourceLanguage, language, trace } = opts, document = structuredClone(opts.target);
4248
+ let { config, schemaType, source, sourceLanguage, language } = opts, document = structuredClone(opts.target);
4325
4249
  for (let [key, value] of Object.entries(source)) key.startsWith("_") || key === (config.i18n?.field ?? "language") || (document[key] === void 0 || document[key] === null) && (document[key] = structuredClone(value));
4326
- let paths = untranslatedPaths(source, document, schemaType, trace);
4250
+ let paths = untranslatedPaths(source, document, schemaType);
4327
4251
  if (!paths.length || !config.history) return {
4328
4252
  document,
4329
4253
  translated: 0,
4330
- written: [],
4331
- failed: 0,
4332
- error: null
4254
+ written: []
4333
4255
  };
4334
- let result = await translateValuesSettled(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), failed = new Set(result.failed), written = [];
4256
+ let translated = await translateValues(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), written = [];
4335
4257
  return paths.forEach((p, n) => {
4336
- !failed.has(n) && setAtKey(document, p, result.values[n]) && written.push({
4258
+ setAtKey(document, p, translated[n]) && written.push({
4337
4259
  path: p,
4338
- value: result.values[n]
4260
+ value: translated[n]
4339
4261
  });
4340
4262
  }), {
4341
4263
  document,
4342
4264
  translated: written.length,
4343
- written,
4344
- failed: failed.size,
4345
- error: result.error
4265
+ written
4346
4266
  };
4347
4267
  }
4348
4268
  /**
4349
4269
  * Textes de `source` absents ou non traduits dans `target` (vides, ou identiques au
4350
4270
  * texte source). Un texte déjà traduit, même à la main, n'y figure jamais.
4351
4271
  */
4352
- function untranslatedPaths(source, target, schemaType, trace) {
4272
+ function untranslatedPaths(source, target, schemaType) {
4353
4273
  return propagate({}, {}, source, schemaType).toTranslate.filter((path) => {
4354
4274
  let src = valueAtKey(source, path);
4355
4275
  if (!collectTexts$1(src).some((t) => t.trim())) return !1;
4356
4276
  let cur = target ? valueAtKey(target, path) : void 0;
4357
- return !collectTexts$1(cur).some((t) => t.trim()) || JSON.stringify(cur) === JSON.stringify(src) && trace?.get(path) !== hashValue(cur);
4277
+ return !collectTexts$1(cur).some((t) => t.trim()) || JSON.stringify(cur) === JSON.stringify(src);
4358
4278
  });
4359
4279
  }
4360
- /**
4361
- * Reprend une version traduite restée INACHEVÉE (textes « To translate » après un échec de
4362
- * l'IA) : retraduit seulement ces textes depuis la version source publiée, dans le
4363
- * brouillon (créé depuis la version publiée s'il n'existe pas). Publie si tout est traduit
4364
- * et `publish` demandé. Rend ce qui reste et l'erreur de l'IA, pour le dire à l'équipe.
4365
- */
4366
- async function retryTranslatedVersion(opts) {
4367
- let { client, config, todo, language, publish = !1 } = opts, id = todo.documentId.replace(/^drafts\./, ""), source = await client.getDocument(todo.sourceId), current = await client.getDocument(`drafts.${id}`) ?? await client.getDocument(id);
4368
- if (!source || !current) return {
4369
- published: !1,
4370
- remaining: todo.paths,
4371
- aiError: source ? "translated version not found" : "source version not found (unpublished or deleted)"
4372
- };
4373
- if (!config.history) return {
4374
- published: !1,
4375
- remaining: todo.paths,
4376
- aiError: "AI translation is not configured (kit project key missing)"
4377
- };
4378
- let { _rev, _createdAt, _updatedAt, ...doc } = structuredClone(current), type = String(current._type), slugField = slugFieldOf(config, type, source), nameOf = (path) => path.split(".").pop()?.replace(/\[.*$/, ""), technical = (path) => isNonTextValue(nameOf(path), valueAtKey(source, path)), slugPending = !!(slugField && todo.paths.includes(slugField)), remaining = todo.paths.filter((p) => p !== slugField && !technical(p)), aiError = null, written = [];
4379
- try {
4380
- let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), result = await translateValuesSettled(config.history, todo.sourceLanguage, language, toSend.map((v) => v ?? "")), failed = new Set(result.failed);
4381
- result.error && (aiError = result.error), remaining = remaining.filter((path, n) => {
4382
- if (failed.has(n)) return !0;
4383
- let value = toSend[n] === void 0 ? void 0 : result.values[n], ok = setAtKey(doc, path, value);
4384
- return ok && value !== void 0 && written.push({
4385
- path,
4386
- value
4387
- }), !ok;
4388
- });
4389
- } catch (cause) {
4390
- aiError = cause instanceof Error ? cause.message : String(cause);
4391
- }
4392
- if (slugPending && slugField) {
4393
- let titleField = config.pageTypes.find((t) => t.type === type)?.titleField ?? "title";
4394
- remaining.includes(titleField) ? remaining = [...remaining, slugField] : doc[slugField] = await translatedSlug(client, config, type, doc, source, language);
4395
- }
4396
- let published = publish && !remaining.length && !aiError, tx = client.transaction();
4397
- return published ? (tx.createOrReplace({
4398
- ...doc,
4399
- _id: id
4400
- }), tx.delete(`drafts.${id}`)) : tx.createOrReplace({
4401
- ...doc,
4402
- _id: `drafts.${id}`
4403
- }), tx.patch(translationTodoId(id), (p) => p.set({ paths: remaining })), await tx.commit(), await recordTrace(client, id, written, {
4404
- sourceId: todo.sourceId,
4405
- sourceLanguage: todo.sourceLanguage
4406
- }), {
4407
- published,
4408
- remaining,
4409
- aiError
4410
- };
4411
- }
4412
4280
  const EXCLUDED = [
4413
4281
  "translation.metadata",
4414
4282
  BOARD_LAYOUT_TYPE,
4415
4283
  TRANSLATION_TODO_TYPE
4416
- ], TITLE = "coalesce(title, name, heading, internalName, slug.current, _id)";
4417
- /** Erreur lisible pour l'équipe (le service renvoie parfois un message technique). */
4418
- function explain$1(error) {
4419
- let e = error.toLowerCase();
4420
- return /401|403|unauthori|forbidden|key/.test(e) ? `${error} (kit project key: run \`npx ncf-kit setup\`)` : /429|rate|quota|limit/.test(e) ? `${error} (AI service busy or quota reached: retry in a few minutes)` : /timeout|timed out|network|fetch|50\d/.test(e) ? `${error} (AI service unreachable: retry in a few minutes)` : /too (long|large)|length|token/.test(e) ? `${error} (text too long for one request: translate this field by hand)` : error;
4421
- }
4284
+ ];
4422
4285
  /**
4423
4286
  * Langues du site : met chaque langue au niveau de la langue principale, en UN clic
4424
- * explicite (jamais tout seul). Utile à l'ajout d'une langue et après l'ajout d'un
4425
- * composant (valeurs par défaut traduites dans chaque langue).
4426
- * - On choisit ce qu'on traduit (documents manquants, traductions inachevées, valeurs
4427
- * par défaut des composants) et, par défaut, tout est enregistré en BROUILLON à relire
4428
- * (kit >= 2.65.0) : une traduction de l'IA n'est publiée sans relecture que si on coche
4429
- * « Publish right away ».
4430
- * - Chaque échec est listé avec sa raison ; une version inachevée (échec de l'IA) est
4431
- * détectée et reprise par « Retry » (seulement ses textes à traduire).
4432
- * - Valeurs par défaut : seuls les textes vides ou restés identiques au texte source sont
4433
- * traduits (jamais un texte traduit à la main) ; un texte que l'IA a rendu à l'identique
4434
- * (nom propre, marque) n'est plus reproposé.
4287
+ * explicite (jamais tout seul). Utile à l'ajout d'une langue (« de » : toutes les
4288
+ * pages en allemand) et après l'ajout d'un composant (valeurs par défaut traduites
4289
+ * dans chaque langue).
4290
+ * - Documents : chaque document publié de la langue principale sans version dans
4291
+ * une langue reçoit sa version, traduite par l'IA, publiée et reliée.
4292
+ * - Valeurs par défaut des composants : langue source (anglais en général), puis
4293
+ * chaque langue ; un document absent est créé ; seuls les textes vides ou restés
4294
+ * identiques au texte source sont traduits (jamais un texte traduit à la main).
4435
4295
  */
4436
4296
  function LanguagesSync() {
4437
- let config = useKitConfig(), client = useKitClient(), schema = useSchema(), [open, setOpen] = useState(!1), [plan, setPlan] = useState(null), [busy, setBusy] = useState(!1), [progress, setProgress] = useState(null), [report, setReport] = useState(null), [pick, setPick] = useState({
4438
- missing: !0,
4439
- unfinished: !0,
4440
- defaults: !0
4441
- }), [publishNow, setPublishNow] = useState(!1), i18n = config.i18n, field = i18n?.field ?? "language", defaultsType = config.componentPreview.defaultsType, typeOf = (name) => schema.get(name), analyse = useCallback(async () => {
4297
+ let config = useKitConfig(), client = useKitClient(), schema = useSchema(), [open, setOpen] = useState(!1), [plan, setPlan] = useState(null), [busy, setBusy] = useState(!1), [progress, setProgress] = useState(null), [report, setReport] = useState(null), i18n = config.i18n, field = i18n?.field ?? "language", defaultsType = config.componentPreview.defaultsType, typeOf = (name) => schema.get(name), analyse = useCallback(async () => {
4442
4298
  if (!i18n) return;
4443
- setPlan(null);
4444
- let main = i18n.defaultLocale, others = i18n.locales.filter((l) => l !== main), sources = await client.fetch(`*[defined(${field}) && ${field} == $main && !(_id in path("drafts.**")) && !(_type in $excluded)]{_id, _type, "title": ${TITLE}}`, {
4299
+ setPlan(null), setReport(null);
4300
+ let main = i18n.defaultLocale, sources = await client.fetch(`*[defined(${field}) && ${field} == $main && !(_id in path("drafts.**")) && !(_type in $excluded)]{_id, _type}`, {
4445
4301
  main,
4446
4302
  excluded: [...EXCLUDED, defaultsType]
4447
4303
  }), metas = await client.fetch("*[_type == \"translation.metadata\"]{\"refs\": translations[]{\"lang\": coalesce(language, _key), \"id\": value._ref}}"), langsOf = /* @__PURE__ */ new Map();
@@ -4449,20 +4305,12 @@ function LanguagesSync() {
4449
4305
  let langs = new Set((m.refs ?? []).map((r) => r.lang ?? ""));
4450
4306
  for (let r of m.refs ?? []) r.id && langsOf.set(r.id, langs);
4451
4307
  }
4452
- let missing = others.map((language) => ({
4308
+ let missing = i18n.locales.filter((l) => l !== main).map((language) => ({
4453
4309
  language,
4454
4310
  docs: sources.filter((d) => !langsOf.get(d._id)?.has(language))
4455
- })), unfinished = await client.fetch(`*[_type == $todo && count(paths) > 0]{documentId, sourceId, sourceLanguage, paths,
4456
- "version": coalesce(*[_id == "drafts." + ^.documentId][0], *[_id == ^.documentId][0]){"language": ${field}, "title": ${TITLE}}}
4457
- {documentId, sourceId, sourceLanguage, paths, "language": version.language, "title": version.title}`, { todo: TRANSLATION_TODO_TYPE }), draftOnly = await client.fetch(`*[_id in path("drafts.**") && ${field} in $others && !(_type in $excluded) && !defined(*[_id == string::split(^._id, "drafts.")[1]][0]._id)]{"language": ${field}}`, {
4458
- others,
4459
- excluded: EXCLUDED
4460
- }), drafts = others.map((language) => ({
4461
- language,
4462
- count: draftOnly.filter((d) => d.language === language).length
4463
- })).filter((d) => d.count), defaultsDocs = await client.fetch("*[_type == $type && !(_id in path(\"drafts.**\"))]", { type: defaultsType }), byLang = (lang) => defaultsDocs.find((d) => d[field] === lang) ?? null, sourceLang = byLang(i18n.defaultsSourceLocale) ? i18n.defaultsSourceLocale : main, sourceDoc = byLang(sourceLang), mainDoc = byLang(main), defaults = [];
4311
+ })), defaultsDocs = await client.fetch("*[_type == $type && !(_id in path(\"drafts.**\"))]", { type: defaultsType }), byLang = (lang) => defaultsDocs.find((d) => d[field] === lang) ?? null, sourceLang = byLang(i18n.defaultsSourceLocale) ? i18n.defaultsSourceLocale : main, sourceDoc = byLang(sourceLang), mainDoc = byLang(main), defaults = [];
4464
4312
  if (sourceDoc && mainDoc && sourceLang !== main) {
4465
- let trace = await readTrace(client, String(sourceDoc._id)), texts = untranslatedPaths(mainDoc, sourceDoc, typeOf(defaultsType), trace).length;
4313
+ let texts = untranslatedPaths(mainDoc, sourceDoc, typeOf(defaultsType)).length;
4466
4314
  texts && defaults.push({
4467
4315
  language: sourceLang,
4468
4316
  exists: !0,
@@ -4471,18 +4319,16 @@ function LanguagesSync() {
4471
4319
  });
4472
4320
  }
4473
4321
  if (sourceDoc) for (let language of i18n.locales.filter((l) => l !== sourceLang)) {
4474
- let doc = byLang(language), trace = doc ? await readTrace(client, String(doc._id)) : void 0;
4322
+ let doc = byLang(language);
4475
4323
  defaults.push({
4476
4324
  language,
4477
4325
  exists: !!doc,
4478
- texts: untranslatedPaths(sourceDoc, doc, typeOf(defaultsType), trace).length,
4326
+ texts: untranslatedPaths(sourceDoc, doc, typeOf(defaultsType)).length,
4479
4327
  from: sourceLang
4480
4328
  });
4481
4329
  }
4482
4330
  setPlan({
4483
4331
  missing,
4484
- unfinished,
4485
- drafts,
4486
4332
  defaults
4487
4333
  });
4488
4334
  }, [
@@ -4492,158 +4338,92 @@ function LanguagesSync() {
4492
4338
  i18n
4493
4339
  ]), run = async () => {
4494
4340
  if (!plan || !i18n) return;
4495
- setBusy(!0), setReport(null);
4496
- let lines = [], fail = (what, error) => lines.push({
4497
- tone: "critical",
4498
- text: `${what}: ${explain$1(error)}`
4499
- });
4341
+ setBusy(!0);
4342
+ let lines = [];
4500
4343
  try {
4501
- if (pick.missing) {
4502
- let total = plan.missing.reduce((n, m) => n + m.docs.length, 0), n = 0;
4503
- for (let m of plan.missing) {
4504
- let published = 0, review = 0;
4505
- for (let d of m.docs) {
4506
- n++, setProgress(`Documents ${n}/${total} (${m.language.toUpperCase()})`);
4507
- let what = `${m.language.toUpperCase()} « ${d.title ?? d._id} »`;
4508
- try {
4509
- let source = await client.getDocument(d._id);
4510
- if (!source) {
4511
- fail(what, "source version not found");
4512
- continue;
4513
- }
4514
- let created = await createTranslatedVersion({
4515
- client,
4516
- config,
4517
- type: d._type,
4518
- schemaType: typeOf(d._type),
4519
- source,
4520
- sourceId: d._id,
4521
- sourceLanguage: i18n.defaultLocale,
4522
- language: m.language,
4523
- ai: !0,
4524
- publish: publishNow
4525
- });
4526
- created.published ? published++ : created.complete ? review++ : created.aiError ? fail(what, `AI translation failed, saved as a draft with ${created.remaining.length} text(s) to translate. ${created.aiError}`) : fail(what, `${created.remaining.length} text(s) not translated, saved as a draft (marked "To translate")`);
4527
- } catch (cause) {
4528
- fail(what, cause instanceof Error ? cause.message : String(cause));
4529
- }
4344
+ let total = plan.missing.reduce((n, m) => n + m.docs.length, 0), n = 0;
4345
+ for (let m of plan.missing) {
4346
+ let ok = 0, drafts = 0;
4347
+ for (let d of m.docs) {
4348
+ n++, setProgress(`Documents ${n}/${total} (${m.language.toUpperCase()})`);
4349
+ let source = await client.getDocument(d._id);
4350
+ if (source) try {
4351
+ (await createTranslatedVersion({
4352
+ client,
4353
+ config,
4354
+ type: d._type,
4355
+ schemaType: typeOf(d._type),
4356
+ source,
4357
+ sourceId: d._id,
4358
+ sourceLanguage: i18n.defaultLocale,
4359
+ language: m.language,
4360
+ ai: !0
4361
+ })).published ? ok++ : drafts++;
4362
+ } catch (cause) {
4363
+ lines.push(`${m.language.toUpperCase()} ${d._id}: ${cause instanceof Error ? cause.message : String(cause)}`);
4530
4364
  }
4531
- published && lines.push({
4532
- tone: "positive",
4533
- text: `${m.language.toUpperCase()}: ${published} document(s) translated and published`
4534
- }), review && lines.push({
4535
- tone: "caution",
4536
- text: `${m.language.toUpperCase()}: ${review} document(s) translated as drafts, to review then publish`
4537
- });
4538
4365
  }
4366
+ m.docs.length && lines.unshift(`${m.language.toUpperCase()}: ${ok} published${drafts ? `, ${drafts} saved as drafts (texts to translate)` : ""}`);
4539
4367
  }
4540
- if (pick.unfinished) for (let [n, t] of plan.unfinished.entries()) {
4541
- setProgress(`Unfinished translations ${n + 1}/${plan.unfinished.length}`);
4542
- let what = `${(t.language ?? "").toUpperCase()} « ${t.title ?? t.documentId} »`;
4543
- if (!t.language) {
4544
- fail(what, "language of the translated version unknown");
4368
+ for (let d of plan.defaults) {
4369
+ if (d.exists && !d.texts) continue;
4370
+ let src = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4371
+ type: defaultsType,
4372
+ lang: d.from
4373
+ });
4374
+ if (!src) continue;
4375
+ let sourceLang = d.from;
4376
+ if (setProgress(`Component defaults (${d.language.toUpperCase()})`), !d.exists) {
4377
+ await createTranslatedVersion({
4378
+ client,
4379
+ config,
4380
+ type: defaultsType,
4381
+ schemaType: typeOf(defaultsType),
4382
+ source: src,
4383
+ sourceId: String(src._id),
4384
+ sourceLanguage: sourceLang,
4385
+ language: d.language,
4386
+ ai: !0
4387
+ }), lines.push(`Component defaults ${d.language.toUpperCase()}: created`);
4545
4388
  continue;
4546
4389
  }
4547
- let r = await retryTranslatedVersion({
4548
- client,
4549
- config,
4550
- todo: t,
4551
- language: t.language,
4552
- publish: publishNow
4553
- });
4554
- r.aiError ? fail(what, `still ${r.remaining.length} text(s) to translate. ${r.aiError}`) : r.remaining.length ? fail(what, `${r.remaining.length} text(s) could not be placed (field changed since): translate them by hand`) : lines.push({
4555
- tone: r.published ? "positive" : "caution",
4556
- text: `${what}: completed${r.published ? " and published" : ", draft to review then publish"}`
4390
+ let target = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4391
+ type: defaultsType,
4392
+ lang: d.language
4557
4393
  });
4558
- }
4559
- if (pick.defaults) for (let d of plan.defaults) {
4560
- if (d.exists && !d.texts) continue;
4561
- let what = `Component defaults ${d.language.toUpperCase()}`;
4562
- try {
4563
- let src = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4564
- type: defaultsType,
4565
- lang: d.from
4566
- });
4567
- if (!src) continue;
4568
- if (setProgress(`${what}`), !d.exists) {
4569
- let created = await createTranslatedVersion({
4570
- client,
4571
- config,
4572
- type: defaultsType,
4573
- schemaType: typeOf(defaultsType),
4574
- source: src,
4575
- sourceId: String(src._id),
4576
- sourceLanguage: d.from,
4577
- language: d.language,
4578
- ai: !0,
4579
- publish: publishNow
4580
- });
4581
- created.aiError ? fail(what, `AI translation failed, created as a draft. ${created.aiError}`) : lines.push({
4582
- tone: created.published ? "positive" : "caution",
4583
- text: `${what}: created${created.published ? " and published" : " as a draft, to review then publish"}`
4584
- });
4585
- continue;
4586
- }
4587
- let published = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4588
- type: defaultsType,
4589
- lang: d.language
4590
- });
4591
- if (!published) continue;
4592
- let id = String(published._id), base = await client.getDocument(`drafts.${id}`) ?? published, filled = await fillTranslation({
4394
+ if (!target) continue;
4395
+ let filled = await fillTranslation({
4396
+ config,
4397
+ schemaType: typeOf(defaultsType),
4398
+ source: src,
4399
+ target,
4400
+ sourceLanguage: sourceLang,
4401
+ language: d.language
4402
+ }), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction().createOrReplace(doc), draft = await client.getDocument(`drafts.${String(target._id)}`);
4403
+ if (draft) {
4404
+ let { _rev: r2, _updatedAt: u2, _createdAt: c2, ...dd } = (await fillTranslation({
4593
4405
  config,
4594
4406
  schemaType: typeOf(defaultsType),
4595
4407
  source: src,
4596
- target: base,
4597
- sourceLanguage: d.from,
4598
- language: d.language,
4599
- trace: await readTrace(client, id)
4600
- }), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction();
4601
- publishNow ? (tx.createOrReplace({
4602
- ...doc,
4603
- _id: id
4604
- }), tx.delete(`drafts.${id}`)) : tx.createOrReplace({
4605
- ...doc,
4606
- _id: `drafts.${id}`
4607
- }), await tx.commit(), await recordTrace(client, id, filled.written, {
4608
- sourceId: String(src._id),
4609
- sourceLanguage: d.from
4610
- });
4611
- let unchanged = filled.written.filter((w) => JSON.stringify(w.value) === JSON.stringify(valueAtKey(src, w.path))).length;
4612
- filled.error && fail(what, `${filled.error} The other texts were kept; retry to translate the rest.`), lines.push({
4613
- tone: publishNow ? "positive" : "caution",
4614
- 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)` : ""}`
4615
- });
4616
- } catch (cause) {
4617
- fail(what, cause instanceof Error ? cause.message : String(cause));
4408
+ target: draft,
4409
+ sourceLanguage: sourceLang,
4410
+ language: d.language
4411
+ })).document;
4412
+ tx.createOrReplace(dd);
4618
4413
  }
4414
+ await tx.commit(), await recordTrace(client, String(target._id), filled.written, {
4415
+ sourceId: String(src._id),
4416
+ sourceLanguage: sourceLang
4417
+ }), lines.push(`Component defaults ${d.language.toUpperCase()}: ${filled.translated} text${filled.translated > 1 ? "s" : ""} translated`);
4619
4418
  }
4620
4419
  } catch (cause) {
4621
- fail("Stopped", cause instanceof Error ? cause.message : String(cause));
4420
+ lines.push(`Stopped: ${cause instanceof Error ? cause.message : String(cause)}`);
4622
4421
  } finally {
4623
- setBusy(!1), setProgress(null), setReport(lines.length ? lines : [{
4624
- tone: "positive",
4625
- text: "Everything was already up to date."
4626
- }]), analyse();
4422
+ setBusy(!1), setProgress(null), setReport(lines.length ? lines : ["Everything was already up to date."]), analyse();
4627
4423
  }
4628
4424
  };
4629
4425
  if (!i18n || !config.history) return null;
4630
- let pendingDocs = plan?.missing.reduce((n, m) => n + m.docs.length, 0) ?? 0, pendingDefaults = plan?.defaults.filter((d) => !d.exists || d.texts).length ?? 0, pendingUnfinished = plan?.unfinished.length ?? 0, selected = pick.missing && pendingDocs || pick.unfinished && pendingUnfinished || pick.defaults && pendingDefaults, failures = report?.filter((l) => l.tone === "critical").length ?? 0, option = (key, label, count) => /* @__PURE__ */ jsxs(Flex, {
4631
- as: "label",
4632
- align: "center",
4633
- gap: 2,
4634
- children: [/* @__PURE__ */ jsx(Checkbox, {
4635
- checked: pick[key] && count > 0,
4636
- disabled: !count || busy,
4637
- onChange: () => setPick({
4638
- ...pick,
4639
- [key]: !pick[key]
4640
- })
4641
- }), /* @__PURE__ */ jsx(Text, {
4642
- size: 1,
4643
- muted: !count,
4644
- children: label
4645
- })]
4646
- });
4426
+ let pendingDocs = plan?.missing.reduce((n, m) => n + m.docs.length, 0) ?? 0, pendingDefaults = plan?.defaults.filter((d) => !d.exists || d.texts).length ?? 0;
4647
4427
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
4648
4428
  icon: TranslateIcon,
4649
4429
  text: "Languages",
@@ -4651,7 +4431,7 @@ function LanguagesSync() {
4651
4431
  fontSize: 1,
4652
4432
  padding: 2,
4653
4433
  onClick: () => {
4654
- setOpen(!0), setReport(null), analyse();
4434
+ setOpen(!0), analyse();
4655
4435
  }
4656
4436
  }), open && /* @__PURE__ */ jsx(Dialog, {
4657
4437
  id: "ncf-languages",
@@ -4668,120 +4448,43 @@ function LanguagesSync() {
4668
4448
  children: [
4669
4449
  "Brings every language to the level of the main language (",
4670
4450
  i18n.defaultLocale.toUpperCase(),
4671
- ") with AI translation. Translations are saved as drafts to review, unless you choose to publish them right away. Texts already translated (even by hand) are never changed."
4451
+ "): missing pages and documents are created, translated with AI and published; component defaults are translated from",
4452
+ " ",
4453
+ i18n.defaultsSourceLocale.toUpperCase(),
4454
+ ". Texts already translated (even by hand) are never changed."
4672
4455
  ]
4673
4456
  }),
4674
4457
  plan ? /* @__PURE__ */ jsxs(Stack, {
4675
4458
  gap: 3,
4676
- children: [
4677
- plan.missing.map((m) => /* @__PURE__ */ jsx(Card, {
4678
- padding: 3,
4679
- radius: 2,
4680
- border: !0,
4681
- tone: m.docs.length ? "caution" : "positive",
4682
- children: /* @__PURE__ */ jsxs(Text, {
4683
- size: 1,
4684
- children: [
4685
- m.language.toUpperCase(),
4686
- ": ",
4687
- m.docs.length ? `${m.docs.length} document${m.docs.length > 1 ? "s" : ""} without a version` : "all documents have a version"
4688
- ]
4689
- })
4690
- }, m.language)),
4691
- plan.unfinished.length > 0 && /* @__PURE__ */ jsx(Card, {
4692
- padding: 3,
4693
- radius: 2,
4694
- border: !0,
4695
- tone: "critical",
4696
- children: /* @__PURE__ */ jsxs(Stack, {
4697
- gap: 2,
4698
- children: [/* @__PURE__ */ jsxs(Text, {
4699
- size: 1,
4700
- weight: "semibold",
4701
- children: [
4702
- plan.unfinished.length,
4703
- " unfinished translation",
4704
- plan.unfinished.length > 1 ? "s" : "",
4705
- " (texts still to translate)"
4706
- ]
4707
- }), plan.unfinished.slice(0, 8).map((t) => /* @__PURE__ */ jsxs(Text, {
4708
- size: 1,
4709
- muted: !0,
4710
- children: [
4711
- (t.language ?? "").toUpperCase(),
4712
- " « ",
4713
- t.title ?? t.documentId,
4714
- " »: ",
4715
- t.paths.length,
4716
- " text",
4717
- t.paths.length > 1 ? "s" : ""
4718
- ]
4719
- }, t.documentId))]
4720
- })
4721
- }),
4722
- plan.drafts.map((d) => /* @__PURE__ */ jsx(Card, {
4723
- padding: 3,
4724
- radius: 2,
4725
- border: !0,
4726
- tone: "caution",
4727
- children: /* @__PURE__ */ jsxs(Text, {
4728
- size: 1,
4729
- children: [
4730
- d.language.toUpperCase(),
4731
- ": ",
4732
- d.count,
4733
- " translated version",
4734
- d.count > 1 ? "s" : "",
4735
- " only in draft, not online yet (review then publish)"
4736
- ]
4737
- })
4738
- }, `dr-${d.language}`)),
4739
- plan.defaults.map((d) => /* @__PURE__ */ jsx(Card, {
4740
- padding: 3,
4741
- radius: 2,
4742
- border: !0,
4743
- tone: !d.exists || d.texts ? "caution" : "positive",
4744
- children: /* @__PURE__ */ jsxs(Text, {
4745
- size: 1,
4746
- children: [
4747
- "Component defaults ",
4748
- d.language.toUpperCase(),
4749
- ":",
4750
- " ",
4751
- d.exists ? d.texts ? `${d.texts} text${d.texts > 1 ? "s" : ""} to translate` : "translated" : "missing (will be created)"
4752
- ]
4753
- })
4754
- }, `d-${d.language}`)),
4755
- /* @__PURE__ */ jsxs(Stack, {
4756
- gap: 2,
4459
+ children: [plan.missing.map((m) => /* @__PURE__ */ jsx(Card, {
4460
+ padding: 3,
4461
+ radius: 2,
4462
+ border: !0,
4463
+ tone: m.docs.length ? "caution" : "positive",
4464
+ children: /* @__PURE__ */ jsxs(Text, {
4465
+ size: 1,
4757
4466
  children: [
4758
- /* @__PURE__ */ jsx(Text, {
4759
- size: 1,
4760
- weight: "semibold",
4761
- children: "Translate"
4762
- }),
4763
- option("missing", `Missing documents (${pendingDocs})`, pendingDocs),
4764
- option("unfinished", `Unfinished translations, retry (${pendingUnfinished})`, pendingUnfinished),
4765
- option("defaults", `Component defaults (${pendingDefaults} language${pendingDefaults > 1 ? "s" : ""})`, pendingDefaults),
4766
- /* @__PURE__ */ jsx(Box, {
4767
- paddingTop: 2,
4768
- children: /* @__PURE__ */ jsxs(Flex, {
4769
- as: "label",
4770
- align: "center",
4771
- gap: 2,
4772
- children: [/* @__PURE__ */ jsx(Checkbox, {
4773
- checked: publishNow,
4774
- disabled: busy,
4775
- onChange: () => setPublishNow(!publishNow)
4776
- }), /* @__PURE__ */ jsx(Text, {
4777
- size: 1,
4778
- children: "Publish right away, without review (otherwise: drafts to review then publish)"
4779
- })]
4780
- })
4781
- })
4467
+ m.language.toUpperCase(),
4468
+ ": ",
4469
+ m.docs.length ? `${m.docs.length} document${m.docs.length > 1 ? "s" : ""} without a version` : "all documents have a version"
4782
4470
  ]
4783
4471
  })
4784
- ]
4472
+ }, m.language)), plan.defaults.map((d) => /* @__PURE__ */ jsx(Card, {
4473
+ padding: 3,
4474
+ radius: 2,
4475
+ border: !0,
4476
+ tone: !d.exists || d.texts ? "caution" : "positive",
4477
+ children: /* @__PURE__ */ jsxs(Text, {
4478
+ size: 1,
4479
+ children: [
4480
+ "Component defaults ",
4481
+ d.language.toUpperCase(),
4482
+ ":",
4483
+ " ",
4484
+ d.exists ? d.texts ? `${d.texts} text${d.texts > 1 ? "s" : ""} to translate` : "translated" : "missing (will be created)"
4485
+ ]
4486
+ })
4487
+ }, `d-${d.language}`))]
4785
4488
  }) : /* @__PURE__ */ jsxs(Flex, {
4786
4489
  align: "center",
4787
4490
  gap: 2,
@@ -4799,26 +4502,17 @@ function LanguagesSync() {
4799
4502
  children: progress
4800
4503
  })]
4801
4504
  }),
4802
- report && /* @__PURE__ */ jsxs(Stack, {
4803
- gap: 2,
4804
- children: [failures > 0 && /* @__PURE__ */ jsxs(Text, {
4805
- size: 1,
4806
- weight: "semibold",
4807
- children: [
4808
- failures,
4809
- " item",
4810
- failures > 1 ? "s" : "",
4811
- " failed: the reason is given for each. Fix it if needed, then retry (unfinished translations are kept and listed above)."
4812
- ]
4813
- }), report.map((line, i) => /* @__PURE__ */ jsx(Card, {
4814
- padding: 3,
4815
- radius: 2,
4816
- tone: line.tone,
4817
- children: /* @__PURE__ */ jsx(Text, {
4505
+ report && /* @__PURE__ */ jsx(Card, {
4506
+ padding: 3,
4507
+ radius: 2,
4508
+ tone: "primary",
4509
+ children: /* @__PURE__ */ jsx(Stack, {
4510
+ gap: 2,
4511
+ children: report.map((line, i) => /* @__PURE__ */ jsx(Text, {
4818
4512
  size: 1,
4819
- children: line.text
4820
- })
4821
- }, i))]
4513
+ children: line
4514
+ }, i))
4515
+ })
4822
4516
  }),
4823
4517
  /* @__PURE__ */ jsxs(Flex, {
4824
4518
  justify: "flex-end",
@@ -4828,12 +4522,12 @@ function LanguagesSync() {
4828
4522
  mode: "ghost",
4829
4523
  disabled: busy,
4830
4524
  onClick: () => setOpen(!1)
4831
- }), /* @__PURE__ */ jsx(Button, {
4832
- tone: publishNow ? "caution" : "primary",
4833
- text: busy ? "Working…" : failures && pendingUnfinished ? "Retry" : publishNow ? "Translate with AI and publish" : "Translate with AI (drafts)",
4834
- disabled: busy || !plan || !selected,
4525
+ }), /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, {
4526
+ tone: "primary",
4527
+ text: busy ? "Working…" : "Translate with AI and publish",
4528
+ disabled: busy || !plan || !pendingDocs && !pendingDefaults,
4835
4529
  onClick: () => void run()
4836
- })]
4530
+ }) })]
4837
4531
  })
4838
4532
  ]
4839
4533
  })
@@ -11905,7 +11599,7 @@ function withTranslationTodo(Inner, config) {
11905
11599
  let alive = !0;
11906
11600
  return client.getDocument(sourceId).then((doc) => {
11907
11601
  if (!alive) return;
11908
- let value = valueAtKey(doc, key), text = (value && typeof value == "object" && typeof value.current == "string" ? value.current : "") || (typeof value == "string" ? value : collectTexts$1(value).join("").trim());
11602
+ let text = collectTexts$1(valueAtKey(doc, key)).join("").trim();
11909
11603
  setMaster(text || "(empty: follows the component default)");
11910
11604
  }).catch(() => alive && setMaster(null)), () => {
11911
11605
  alive = !1;
@@ -12134,37 +11828,6 @@ function withLanguageMismatch(Inner, config) {
12134
11828
  }
12135
11829
  return LanguageMismatch;
12136
11830
  }
12137
- /** Identifiants des documents référencés par `doc` (liens, pages liées...), hors images et fichiers. */
12138
- function referencedIds(doc) {
12139
- let out = /* @__PURE__ */ new Set(), walk = (node) => {
12140
- if (Array.isArray(node)) return node.forEach(walk);
12141
- if (!node || typeof node != "object") return;
12142
- let ref = node._ref;
12143
- typeof ref == "string" && !/^(image|file)-/.test(ref) && out.add(ref.replace(/^drafts\./, ""));
12144
- for (let [k, v] of Object.entries(node)) k.startsWith("_") || walk(v);
12145
- };
12146
- return walk(doc), [...out];
12147
- }
12148
- /**
12149
- * Pages liées depuis `doc` qui n'ont pas de version PUBLIÉE dans chacune des `languages`
12150
- * (kit >= 2.65.0). La version traduite d'un document qui les vise ne peut pas être
12151
- * publiée (« Cette page est en FR et n'a pas de version EN », vu sur JAF) : on le dit
12152
- * AVANT de la créer, avec les pages à traduire d'abord.
12153
- */
12154
- async function linkedWithoutVersion(client, doc, languages, field = "language") {
12155
- let result = /* @__PURE__ */ new Map(), ids = referencedIds(doc);
12156
- if (!ids.length || !languages.length) return result;
12157
- let linked = await client.fetch(`*[_id in $ids && defined(${field})]{
12158
- _id, "title": coalesce(title, name, slug.current, _id), "language": ${field},
12159
- "versions": *[_type == "translation.metadata" && references(^._id)][0].translations[]{"language": coalesce(language, _key), "id": value._ref}
12160
- }`, { ids }), versionIds = linked.flatMap((d) => (d.versions ?? []).map((v) => v.id ?? "")).filter(Boolean), published = new Set(versionIds.length ? await client.fetch("*[_id in $ids]._id", { ids: versionIds }) : []);
12161
- for (let language of languages) for (let d of linked) {
12162
- if (d.language === language) continue;
12163
- let version = (d.versions ?? []).find((v) => v.language === language);
12164
- version?.id && published.has(version.id) || result.set(language, [...result.get(language) ?? [], d.title]);
12165
- }
12166
- return result;
12167
- }
12168
11831
  /**
12169
11832
  * Publier la version PRINCIPALE d'une page :
12170
11833
  * - page déjà publiée qui a des traductions : « Propagate to other languages? »
@@ -12259,19 +11922,7 @@ async function findMissing(client, id, source, locales) {
12259
11922
  return locales.filter((l) => l !== source && !existing.has(l));
12260
11923
  }
12261
11924
  function PropagateDialog(props) {
12262
- let { config, id, type, mode, after, onDone } = props, client = useKitClient(), schema = useSchema(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), [targets, setTargets] = useState(props.targets), [unlinked, setUnlinked] = useState(/* @__PURE__ */ new Map());
12263
- useEffect(() => {
12264
- let alive = !0;
12265
- return linkedWithoutVersion(client, after, props.targets.map((t) => t.language), field).then((m) => alive && setUnlinked(m)).catch(() => {}), () => {
12266
- alive = !1;
12267
- };
12268
- }, [
12269
- client,
12270
- after,
12271
- props.targets,
12272
- field
12273
- ]);
12274
- let [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), [publishNow, setPublishNow] = useState(!1), [overwrite, setOverwrite] = useState(!1), editedCount = targets.reduce((n, t) => n + (t.selected ? t.edited.length : 0), 0), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
11925
+ let { config, id, type, mode, after, onDone } = props, client = useKitClient(), schema = useSchema(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), [targets, setTargets] = useState(props.targets), [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), [overwrite, setOverwrite] = useState(!1), editedCount = targets.reduce((n, t) => n + (t.selected ? t.edited.length : 0), 0), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
12275
11926
  setBusy(!0), setError(null);
12276
11927
  try {
12277
11928
  let published = [], drafted = [], aiError = null;
@@ -12287,8 +11938,7 @@ function PropagateDialog(props) {
12287
11938
  sourceId: id,
12288
11939
  sourceLanguage: source,
12289
11940
  language: t.language,
12290
- ai,
12291
- publish: publishNow
11941
+ ai
12292
11942
  });
12293
11943
  created.aiError && (aiError = created.aiError), (created.published ? published : drafted).push(t.language.toUpperCase());
12294
11944
  continue;
@@ -12297,12 +11947,9 @@ function PropagateDialog(props) {
12297
11947
  if (ai && config.history && remaining.length) {
12298
11948
  let toDo = remaining.filter((p) => !kept.includes(p));
12299
11949
  try {
12300
- let toSend = toDo.map((path) => valueAtKey(after, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), result = await translateValuesSettled(config.history, source, t.language, toSend.map((v) => v ?? "")), missed = new Set(result.failed);
12301
- result.error && (failed = !0, aiError = result.error);
12302
- let done = /* @__PURE__ */ new Set();
11950
+ let toSend = toDo.map((path) => valueAtKey(after, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, source, t.language, toSend.map((v) => v ?? "")), done = /* @__PURE__ */ new Set();
12303
11951
  toDo.forEach((path, n) => {
12304
- if (missed.has(n)) return;
12305
- let value = toSend[n] === void 0 ? void 0 : result.values[n];
11952
+ let value = toSend[n] === void 0 ? void 0 : translated[n];
12306
11953
  setAtKey(doc, path, value) && (done.add(path), value !== void 0 && written.push({
12307
11954
  path,
12308
11955
  value
@@ -12312,7 +11959,7 @@ function PropagateDialog(props) {
12312
11959
  failed = !0, aiError = cause instanceof Error ? cause.message : String(cause);
12313
11960
  }
12314
11961
  }
12315
- let publish = publishNow && ai && !failed && remaining.every((p) => kept.includes(p)), tx = client.transaction();
11962
+ let publish = ai && !failed && remaining.every((p) => kept.includes(p)), tx = client.transaction();
12316
11963
  publish ? (tx.createOrReplace({
12317
11964
  ...doc,
12318
11965
  _id: targetId,
@@ -12338,7 +11985,7 @@ function PropagateDialog(props) {
12338
11985
  toast.push({
12339
11986
  status: aiError ? "warning" : "success",
12340
11987
  title: [published.length ? `Published: ${published.join(", ")}` : "", drafted.length ? `Drafts: ${drafted.join(", ")}` : ""].filter(Boolean).join(" · "),
12341
- description: aiError ? `AI translation failed (${aiError}): saved as drafts, texts marked "To translate". Retry later from Pages → Languages (unfinished translations).` : drafted.length ? ai && !publishNow ? "Translated with AI as drafts: review each language, then publish it." : "Translate the fields marked \"To translate\", then publish each language." : "Translated with AI and published.",
11988
+ description: aiError ? `AI translation failed (${aiError}): saved as drafts, texts marked "To translate".` : drafted.length ? "Translate the fields marked \"To translate\", then publish each language." : "Translated with AI and published.",
12342
11989
  duration: 8e3
12343
11990
  }), onDone();
12344
11991
  } catch (cause) {
@@ -12356,7 +12003,7 @@ function PropagateDialog(props) {
12356
12003
  children: [
12357
12004
  mode === "create" ? `The ${source.toUpperCase()} page is published. Create it in the other languages?` : `The ${source.toUpperCase()} version is published. Apply its changes to the other languages?`,
12358
12005
  " ",
12359
- ai ? publishNow ? "Texts are translated with AI and each language is published right away." : "Texts are translated with AI; each language is saved as a draft to review, then publish." : "Each language is saved as a draft, texts marked \"To translate\"."
12006
+ ai ? "Texts are translated with AI and each language is published." : "Each language is saved as a draft, texts marked \"To translate\"."
12360
12007
  ]
12361
12008
  }),
12362
12009
  config.history && hasTexts && /* @__PURE__ */ jsxs(Flex, {
@@ -12368,19 +12015,7 @@ function PropagateDialog(props) {
12368
12015
  onChange: () => setAi(!ai)
12369
12016
  }), /* @__PURE__ */ jsx(Text, {
12370
12017
  size: 1,
12371
- children: "Translate with AI"
12372
- })]
12373
- }),
12374
- config.history && hasTexts && ai && /* @__PURE__ */ jsxs(Flex, {
12375
- as: "label",
12376
- align: "center",
12377
- gap: 2,
12378
- children: [/* @__PURE__ */ jsx(Checkbox, {
12379
- checked: publishNow,
12380
- onChange: () => setPublishNow(!publishNow)
12381
- }), /* @__PURE__ */ jsx(Text, {
12382
- size: 1,
12383
- children: "Publish right away, without review"
12018
+ children: "Translate with AI and publish"
12384
12019
  })]
12385
12020
  }),
12386
12021
  mode === "update" && editedCount > 0 && /* @__PURE__ */ jsxs(Flex, {
@@ -12421,42 +12056,15 @@ function PropagateDialog(props) {
12421
12056
  flex: 1,
12422
12057
  children: /* @__PURE__ */ jsxs(Stack, {
12423
12058
  gap: 2,
12424
- children: [
12425
- /* @__PURE__ */ jsx(Text, {
12426
- size: 1,
12427
- weight: "semibold",
12428
- children: t.language.toUpperCase()
12429
- }),
12430
- /* @__PURE__ */ jsxs(Text, {
12431
- size: 1,
12432
- muted: !0,
12433
- children: [mode === "create" ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result), t.edited.length ? ` · ${t.edited.length} edited by hand` : ""]
12434
- }),
12435
- unlinked.get(t.language)?.length ? /* @__PURE__ */ jsx(Card, {
12436
- tone: "caution",
12437
- padding: 2,
12438
- radius: 2,
12439
- children: /* @__PURE__ */ jsxs(Text, {
12440
- size: 1,
12441
- children: [
12442
- "Links to ",
12443
- unlinked.get(t.language).length,
12444
- " page",
12445
- unlinked.get(t.language).length > 1 ? "s" : "",
12446
- " with no published ",
12447
- t.language.toUpperCase(),
12448
- " version (",
12449
- unlinked.get(t.language).slice(0, 4).map((title) => `« ${title} »`).join(", "),
12450
- unlinked.get(t.language).length > 4 ? ", …" : "",
12451
- "): this version can be saved as a draft, but not published until",
12452
- unlinked.get(t.language).length > 1 ? " those pages are" : " that page is",
12453
- " translated and published. Not meant to be translated? In the ",
12454
- t.language.toUpperCase(),
12455
- " version, link to its address directly (link type URL) or remove the link."
12456
- ]
12457
- })
12458
- }) : null
12459
- ]
12059
+ children: [/* @__PURE__ */ jsx(Text, {
12060
+ size: 1,
12061
+ weight: "semibold",
12062
+ children: t.language.toUpperCase()
12063
+ }), /* @__PURE__ */ jsxs(Text, {
12064
+ size: 1,
12065
+ muted: !0,
12066
+ children: [mode === "create" ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result), t.edited.length ? ` · ${t.edited.length} edited by hand` : ""]
12067
+ })]
12460
12068
  })
12461
12069
  })]
12462
12070
  })