@nocode-factory/sanity-kit 2.47.1 → 2.48.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
@@ -1,4 +1,6 @@
1
- import { A as DEFAULT_PAGE_BUILDER_FIELD, C as toUrl, D as DEFAULT_COMPONENT_PREVIEW, E as DEFAULT_BOARD_TAGS, M as DEFAULT_TITLE_FIELD, O as DEFAULT_I18N, S as toPath, T as resolveConfig, _ as redirectMapOf, a as componentDefaultsMainDocument, b as parentPath, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, j as DEFAULT_SLUG_FIELD, k as DEFAULT_INTERNAL_FIELDS, l as requiredUnlessDefault, m as finalPath, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, p as translationRedirectOptions, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor, v as depth, w as normalizePath, x as segments, y as pageTypeFor } from "./fixCrossLanguageReferences-CQGzpNii.js";
1
+ import { _ as DEFAULT_PAGE_BUILDER_FIELD, a as depth, c as segments, d as normalizePath, f as resolveConfig, g as DEFAULT_INTERNAL_FIELDS, h as DEFAULT_I18N, i as redirectMapOf, l as toPath, m as DEFAULT_COMPONENT_PREVIEW, o as pageTypeFor, p as DEFAULT_BOARD_TAGS, s as parentPath, t as finalPath, u as toUrl, v as DEFAULT_SLUG_FIELD, y as DEFAULT_TITLE_FIELD } from "./finalUrl-C1kzYMzQ.js";
2
+ import { a as collectTexts$1, c as valueAtKey, d as useKitContext, i as guessDocumentTitle, l as KitProvider, o as replaceTexts, r as collectDocumentText, s as setAtKey, t as generateJsonLd, u as useKitConfig } from "./aiJsonLd-DiYeDzou.js";
3
+ import { a as componentDefaultsMainDocument, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, p as translationRedirectOptions, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-BZk9CkdI.js";
2
4
  import { i as codeEditorInput, n as CodeEmbedInput, r as CodeEditorInput, t as defineCodeEmbedType } from "./codeEmbedType-1bEOTxBT.js";
3
5
  import { createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
6
  import { ToolLink, defineField, definePlugin, defineType, pathToString, set, unset, useClient, useCurrentUser, useFormValue, usePerspective, useSchema, useSetPerspective, useUser, useWorkspace } from "sanity";
@@ -99,27 +101,16 @@ function issuesForTool(issues, tool) {
99
101
  function hasBlockingIssue(issues, tool) {
100
102
  return issuesForTool(issues, tool).some((issue) => issue.level === "error");
101
103
  }
102
- const KitContext = createContext(null);
103
- function KitProvider(props) {
104
- let { config, issues, children } = props, value = useMemo(() => ({
105
- config,
106
- issues
107
- }), [config, issues]);
108
- return /* @__PURE__ */ jsx(KitContext.Provider, {
109
- value,
110
- children
111
- });
112
- }
113
104
  /**
114
- * Configuration résolue du kit. Erreur explicite hors contexte : une
115
- * dépendance oubliée se voit tout de suite au développement.
105
+ * Champs « à traduire » d'une traduction, écrits par la propagation (publication de
106
+ * la version principale). Un document par traduction : `ncfTodo.<id de la traduction>`
107
+ * (point = jamais servi par l'API publique). Jamais créé ni édité à la main : la
108
+ * pastille du formulaire le lit et « Marquer comme traduit » retire le champ.
109
+ * `machine` : empreinte de chaque texte écrit par l'IA (chemin + empreinte). Un texte
110
+ * dont l'empreinte ne correspond plus a été modifié à la main dans cette langue : la
111
+ * propagation ne l'écrase pas sans la case « Overwrite texts edited by hand ».
116
112
  */
117
- function useKitContext() {
118
- let value = useContext(KitContext);
119
- if (!value) throw Error("useKitContext must be called inside a tool of the @nocode-factory/sanity-kit plugin.");
120
- return value;
121
- }
122
- const useKitConfig = () => useKitContext().config, TRANSLATION_TODO_TYPE = "ncfTranslationTodo", translationTodoId = (documentId) => `ncfTodo.${documentId.replace(/^drafts\./, "")}`, translationTodoType = defineType({
113
+ const TRANSLATION_TODO_TYPE = "ncfTranslationTodo", translationTodoId = (documentId) => `ncfTodo.${documentId.replace(/^drafts\./, "")}`, translationTodoType = defineType({
123
114
  name: TRANSLATION_TODO_TYPE,
124
115
  title: "To translate (NCF)",
125
116
  type: "document",
@@ -1275,7 +1266,7 @@ function explainGrantError(error) {
1275
1266
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1276
1267
  * le vérifie.
1277
1268
  */
1278
- const KIT_VERSION = "2.47.1";
1269
+ const KIT_VERSION = "2.48.1";
1279
1270
  /**
1280
1271
  * Signale ce Studio au service du kit, une fois par montage.
1281
1272
  *
@@ -1618,7 +1609,7 @@ function useKitUpdate() {
1618
1609
  !controller.signal.aborted && body?.version && setLatest(body.version);
1619
1610
  }).catch(() => {}), () => controller.abort();
1620
1611
  }, []);
1621
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.47.1") > 0);
1612
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.48.1") > 0);
1622
1613
  return {
1623
1614
  current: KIT_VERSION,
1624
1615
  latest,
@@ -2934,55 +2925,6 @@ async function localizeReferences(client, value, language) {
2934
2925
  for (let row of rows ?? []) row?.from && row.to && row.to !== row.from && map.set(row.from, row.to);
2935
2926
  return map.size ? replaceRefs(value, map) : value;
2936
2927
  }
2937
- const isObj$1 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
2938
- /** Textes d'une valeur, dans l'ordre. */
2939
- function collectTexts$1(value) {
2940
- if (typeof value == "string") return [value];
2941
- if (!Array.isArray(value)) return [];
2942
- let out = [];
2943
- for (let item of value) if (typeof item == "string") out.push(item);
2944
- else if (isObj$1(item) && Array.isArray(item.children)) for (let child of item.children) isObj$1(child) && typeof child.text == "string" && out.push(child.text);
2945
- return out;
2946
- }
2947
- /** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
2948
- function replaceTexts(value, texts) {
2949
- let i = 0, next = () => texts[i++] ?? "";
2950
- return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$1(item) && Array.isArray(item.children) ? {
2951
- ...item,
2952
- children: item.children.map((child) => isObj$1(child) && typeof child.text == "string" ? {
2953
- ...child,
2954
- text: next()
2955
- } : child)
2956
- } : item) : value;
2957
- }
2958
- /** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */
2959
- function parsePathKey(path) {
2960
- let out = [];
2961
- for (let m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] === void 0 ? { item: m[2] } : { field: m[1] });
2962
- return out;
2963
- }
2964
- function itemOf(list, key) {
2965
- return list.find((i) => isObj$1(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
2966
- }
2967
- /** Valeur d'un document au chemin `sections[a].title`. */
2968
- function valueAtKey(doc, path) {
2969
- let cur = doc;
2970
- for (let seg of parsePathKey(path)) {
2971
- if (cur == null) return;
2972
- cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
2973
- }
2974
- return cur;
2975
- }
2976
- /** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */
2977
- function setAtKey(doc, path, value) {
2978
- let segs = parsePathKey(path), cur = doc;
2979
- for (let n = 0; n < segs.length - 1; n++) {
2980
- let seg = segs[n];
2981
- if (cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0, cur == null) return !1;
2982
- }
2983
- let last = segs[segs.length - 1];
2984
- return !last || !("field" in last) || !isObj$1(cur) ? !1 : (cur[last.field] = value, !0);
2985
- }
2986
2928
  const MESSAGES = {
2987
2929
  daily_limit: "Daily AI translation limit reached for this project.",
2988
2930
  project_inactive: "This project is not active in the NCF kit.",
@@ -3033,7 +2975,7 @@ const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
3033
2975
  "datetime",
3034
2976
  "number",
3035
2977
  "boolean"
3036
- ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj = (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(i) && typeof i._key == "string");
2978
+ ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj$1 = (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$1(i) && typeof i._key == "string");
3037
2979
  function typeNames(t) {
3038
2980
  let out = [];
3039
2981
  for (let c = t; c; c = c.type) c.name && out.push(c.name);
@@ -3053,7 +2995,7 @@ function kindOf(t, value) {
3053
2995
  }
3054
2996
  return t.jsonType === "object" ? "object" : t.jsonType === "string" ? t.options?.list?.length ? "value" : "text" : "value";
3055
2997
  }
3056
- return keyed$1(value) ? "list" : isObj(value) ? "object" : "value";
2998
+ return keyed$1(value) ? "list" : isObj$1(value) ? "object" : "value";
3057
2999
  }
3058
3000
  function fieldType(t, name) {
3059
3001
  for (let c = t; c; c = c.type) {
@@ -3070,8 +3012,8 @@ function itemType(t, item) {
3070
3012
  function collectTexts(value, t, path, acc) {
3071
3013
  let kind = kindOf(t, value);
3072
3014
  if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
3073
- else if (kind === "object" && isObj(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
3074
- else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
3015
+ else if (kind === "object" && isObj$1(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
3016
+ else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj$1(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
3075
3017
  }
3076
3018
  const ABSENT$1 = Symbol("absent");
3077
3019
  function merge(target, before, after, t, path, acc) {
@@ -3080,8 +3022,8 @@ function merge(target, before, after, t, path, acc) {
3080
3022
  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);
3081
3023
  if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3082
3024
  if (kind === "object") {
3083
- if (!isObj(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3084
- let base = isObj(target) ? { ...target } : { _type: after._type }, b = isObj(before) ? before : {};
3025
+ if (!isObj$1(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3026
+ let base = isObj$1(target) ? { ...target } : { _type: after._type }, b = isObj$1(before) ? before : {};
3085
3027
  for (let k of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(after)])) {
3086
3028
  if (k.startsWith("_") || SKIP_KEYS.has(k)) continue;
3087
3029
  let v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc);
@@ -3089,7 +3031,7 @@ function merge(target, before, after, t, path, acc) {
3089
3031
  }
3090
3032
  return base;
3091
3033
  }
3092
- let tgt = Array.isArray(target) ? target.filter(isObj) : [], bef = Array.isArray(before) ? before.filter(isObj) : [], aft = Array.isArray(after) ? after.filter(isObj) : [], byKey = (list) => new Map(list.map((i) => [i._key, i])), tMap = byKey(tgt), bMap = byKey(bef), aMap = byKey(aft), result = [];
3034
+ let tgt = Array.isArray(target) ? target.filter(isObj$1) : [], bef = Array.isArray(before) ? before.filter(isObj$1) : [], aft = Array.isArray(after) ? after.filter(isObj$1) : [], byKey = (list) => new Map(list.map((i) => [i._key, i])), tMap = byKey(tgt), bMap = byKey(bef), aMap = byKey(aft), result = [];
3093
3035
  for (let item of aft) {
3094
3036
  let key = item._key, it = itemType(t, item);
3095
3037
  if (tMap.has(key)) {
@@ -3123,7 +3065,7 @@ function propagate(target, before, after, documentType) {
3123
3065
  return {
3124
3066
  document: {
3125
3067
  ...target ?? {},
3126
- ...isObj(merged) ? merged : {}
3068
+ ...isObj$1(merged) ? merged : {}
3127
3069
  },
3128
3070
  ...acc
3129
3071
  };
@@ -8897,7 +8839,7 @@ function withTranslationTodo(Inner, config) {
8897
8839
  if (todo?.sourceId && todo.sourceLanguage && language && config.history) {
8898
8840
  setBusy(!0), setError(null);
8899
8841
  try {
8900
- let value = valueAtKey(await client.getDocument(todo.sourceId) ?? await client.getDocument(`drafts.${todo.sourceId}`), key);
8842
+ let source = await client.getDocument(todo.sourceId) ?? await client.getDocument(`drafts.${todo.sourceId}`), value = valueAtKey(source, key);
8901
8843
  if (!collectTexts$1(value).some((t) => t.trim())) props.onChange(unset());
8902
8844
  else {
8903
8845
  let [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value]);
@@ -9384,6 +9326,51 @@ function summary(r) {
9384
9326
  let parts = [];
9385
9327
  return r.added && parts.push(`${r.added} item${r.added > 1 ? "s" : ""} added`), r.removed && parts.push(`${r.removed} removed`), r.moved && parts.push("order updated"), r.copied.length && parts.push(`${r.copied.length} value${r.copied.length > 1 ? "s" : ""} copied (images, links, options…)`), r.toTranslate.length && parts.push(`${r.toTranslate.length} text${r.toTranslate.length > 1 ? "s" : ""} to translate`), parts.join(" · ");
9386
9328
  }
9329
+ const isObj = (v) => typeof v == "object" && !!v && !Array.isArray(v);
9330
+ /** Régénère le JSON-LD de la page publiée, sauf en mode manuel. Non bloquant. */
9331
+ async function regenerate(client, config, id, published) {
9332
+ if (!config.jsonLd || !config.history) return;
9333
+ let field = config.jsonLd.field, current = published[field];
9334
+ if (isObj(current) && current.mode === "manuel") return;
9335
+ let pageType = pageTypeFor(published._type, config.pageTypes), slugValue = pageType?.slugField ? valueAtKey(published, pageType.slugField) : null, slug = isObj(slugValue) ? slugValue.current ?? null : typeof slugValue == "string" ? slugValue : null, locale = config.i18n ? published[config.i18n.field] ?? null : null, url = toUrl(config.previewUrl, finalPath({
9336
+ slug,
9337
+ locale
9338
+ }, pageType, config, null));
9339
+ if (!url) return;
9340
+ let content = collectDocumentText(published, [field]);
9341
+ if (!content.trim()) return;
9342
+ let result = await generateJsonLd(config.history, {
9343
+ url,
9344
+ locale: locale ?? void 0,
9345
+ type: published._type,
9346
+ title: guessDocumentTitle(published),
9347
+ content
9348
+ }), publishedId = id.replace(/^drafts\./, "");
9349
+ await client.patch(publishedId).set({ [field]: {
9350
+ mode: "auto",
9351
+ data: JSON.stringify(result, null, 2)
9352
+ } }).commit();
9353
+ }
9354
+ /**
9355
+ * Enveloppe l'action « Publier » : après la publication, en mode auto, régénère
9356
+ * le JSON-LD de la page par IA à partir du contenu publié et l'écrit sur le
9357
+ * document publié. Le délai réseau de l'IA laisse la publication s'achever
9358
+ * avant l'écriture. Jamais bloquant : une erreur est seulement journalisée.
9359
+ */
9360
+ function withJsonLd(Publish, config) {
9361
+ let Wrapped = (props) => {
9362
+ let base = Publish(props), client = useKitClient();
9363
+ if (!base || !config.jsonLd || !config.history) return base;
9364
+ let source = props.draft ?? props.published;
9365
+ return {
9366
+ ...base,
9367
+ onHandle: () => {
9368
+ base.onHandle?.(), source && regenerate(client, config, props.id, source).catch((error) => console.error("JSON-LD auto:", error));
9369
+ }
9370
+ };
9371
+ };
9372
+ return Wrapped.action = Publish.action, Wrapped;
9373
+ }
9387
9374
  /** Identifiants publiés + brouillons d'une liste de documents. */
9388
9375
  const withDrafts = (ids) => ids.flatMap((id) => [id, `drafts.${id}`]);
9389
9376
  /**
@@ -10153,7 +10140,7 @@ function createKitInput(config) {
10153
10140
  return withPublishedHint(config.i18n ? withLanguageMismatch(withTranslationTodo(KitInput, config), config) : KitInput);
10154
10141
  }
10155
10142
  const ncfKit = definePlugin((options) => {
10156
- let config = resolveConfig(options), issues = validateConfig(config);
10143
+ let config = resolveConfig(options), issues = validateConfig(config), addJsonLd = (action) => config.jsonLd ? withJsonLd(action, config) : action;
10157
10144
  return {
10158
10145
  name: "@nocode-factory/sanity-kit",
10159
10146
  tools: [
@@ -10224,7 +10211,7 @@ const ncfKit = definePlugin((options) => {
10224
10211
  },
10225
10212
  document: {
10226
10213
  newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
10227
- actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction : action.action === "publish" && config.i18n ? withTranslationRedirects(withPropagation(action, config, void 0, { allowCreate: !0 }), config) : action.action === "delete" && config.i18n ? withTranslationDelete(action, config) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === "delete" ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action) : config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field) ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action.action === "delete" ? withTranslationDelete(action, config) : action.action === "unpublish" ? createRemoveFromSite(config) : action) : prev
10214
+ actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? config.i18n ? createRemoveFromSite(config) : RemoveFromSiteAction : action.action === "publish" ? addJsonLd(config.i18n ? withTranslationRedirects(withPropagation(action, config, void 0, { allowCreate: !0 }), config) : action) : action.action === "delete" && config.i18n ? withTranslationDelete(action, config) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action.action === "delete" ? withTranslationDelete(action, config, config.i18n?.defaultsSourceLocale) : action) : config.i18n && !isKitType(context.schemaType) && hasLanguageField(context.schema.get(context.schemaType), config.i18n.field) ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action.action === "delete" ? withTranslationDelete(action, config) : action.action === "unpublish" ? createRemoveFromSite(config) : action) : prev
10228
10215
  },
10229
10216
  studio: { components: {
10230
10217
  toolMenu: createPreviewLauncher(config, issues),