@nocode-factory/sanity-kit 2.36.0 → 2.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ncf-kit.mjs CHANGED
@@ -303,6 +303,9 @@ async function doctor() {
303
303
  const config = ['sanity.config.ts', 'sanity.config.tsx', 'sanity.config.js'].map((f) => read(join(studio, f))).find(Boolean) ?? ''
304
304
  if (!config.includes('ncfKit(')) ko('Plugin', 'ncfKit(...) absent de sanity.config')
305
305
  else ok('Plugin', 'ncfKit branché')
306
+ if (/locales|i18n/.test(config) && !config.includes('withSameLanguageReferences('))
307
+ ko('Références de la même langue', "règle d'or du multilingue : le kit a besoin de withSameLanguageReferences sur les types du projet pour que chaque référence ne propose que des documents de la même langue ; le projet ne l'a pas : schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}.")
308
+ else if (config.includes('withSameLanguageReferences(')) ok('Références de la même langue', 'withSameLanguageReferences')
306
309
  if (!config.includes('ncfPresentationComponents('))
307
310
  warn('Presentation : liste des pages', "le kit a besoin de ncfPresentationComponents dans presentationTool pour afficher la liste des pages à gauche de l'aperçu ; le projet ne l'a pas : presentationTool({components: ncfPresentationComponents(ncfOptions), ...}).")
308
311
  else ok('Presentation : liste des pages', 'ncfPresentationComponents')
package/dist/index.d.ts CHANGED
@@ -1134,6 +1134,55 @@ interface PreviewTargetState {
1134
1134
  isProduction: boolean;
1135
1135
  }
1136
1136
  export declare function usePreviewTarget(): PreviewTargetState;
1137
+ /**
1138
+ * RÈGLE D'OR DU MULTILINGUE : une référence ne propose que des documents de la
1139
+ * MÊME langue que le document en cours (un article EN ne voit que les catégories EN,
1140
+ * une page FR que les pages FR). Les documents sans langue (logos, régions, assets…)
1141
+ * restent proposés. Un document commun à toutes les langues (Navigation…) vise la
1142
+ * langue principale.
1143
+ *
1144
+ * Pose ce filtre sur TOUS les champs de référence des types donnés (champs, listes,
1145
+ * objets imbriqués, annotations du texte riche), combiné avec un filtre déjà présent.
1146
+ * À appliquer aux types du projet :
1147
+ *
1148
+ * ```ts
1149
+ * schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}
1150
+ * ```
1151
+ */
1152
+ export declare function withSameLanguageReferences<T>(types: T[], options: Pick<NcfKitConfig, 'i18n'>): T[];
1153
+ interface CrossLanguageReport {
1154
+ /** Références repointées (ou à repointer en simulation). */
1155
+ fixed: {
1156
+ documentId: string;
1157
+ path: string;
1158
+ from: string;
1159
+ to: string;
1160
+ }[];
1161
+ /** Références croisées sans équivalent dans la langue du document (laissées). */
1162
+ missing: {
1163
+ documentId: string;
1164
+ path: string;
1165
+ ref: string;
1166
+ language: string;
1167
+ }[];
1168
+ }
1169
+ /**
1170
+ * RÈGLE D'OR DU MULTILINGUE, côté données : chaque référence d'un document vise un
1171
+ * document de SA langue (document sans langue : la langue principale). Une
1172
+ * référence croisée est repointée vers la traduction de la bonne langue (liens de
1173
+ * traduction) ; sans traduction, elle est signalée et laissée. Publiés et
1174
+ * brouillons. `apply: false` : simulation.
1175
+ *
1176
+ * ```ts
1177
+ * // studio/scripts/references-same-language.ts (sanity exec --with-user-token)
1178
+ * const report = await fixCrossLanguageReferences(getCliClient(...), {defaultLocale: 'fr', apply})
1179
+ * ```
1180
+ */
1181
+ export declare function fixCrossLanguageReferences(client: SanityClient, options: {
1182
+ field?: string;
1183
+ defaultLocale: string;
1184
+ apply?: boolean;
1185
+ }): Promise<CrossLanguageReport>;
1137
1186
  /**
1138
1187
  * Bascule brouillons / en ligne, posée dans l'aperçu lui-même.
1139
1188
  *
@@ -1389,7 +1438,7 @@ export declare function ActorName(props: {
1389
1438
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1390
1439
  * le vérifie.
1391
1440
  */
1392
- export declare const KIT_VERSION = "2.36.0";
1441
+ export declare const KIT_VERSION = "2.37.0";
1393
1442
  /**
1394
1443
  * Données de la page proposées comme colonnes.
1395
1444
  *
@@ -1885,5 +1934,5 @@ export declare const NCF_HISTORY_TOOL = "ncf-history";
1885
1934
  export declare const NCF_DESIGN_SYSTEM_TOOL = "ncf-design-system";
1886
1935
  export declare const NCF_TOOL_NAMES: readonly ["ncf-pages", "ncf-components", "ncf-history", "ncf-design-system"];
1887
1936
  export declare const ncfKit: import("sanity").Plugin<NcfKitConfig>;
1888
- export { type AddColumnInput, type Annotation, type AnnotationsState, type BlockOccurrence, type BlockTypeInfo, type BoardEdge, type BoardGraph, type BoardLayoutState, type BoardNode, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, type Change, type ChangeKind, type CollectedLinks, type ColorBy, type ColorOptions, type ConfigIssue, DEFAULT_COMPONENT_DEFAULTS_TYPE, type DeriveOptions, type GroupBy, type GroupOptions, type HistoryDetail, type HistoryEvent, type IssueLevel, type KitContextValue, type KitUpdate, type LayoutMode, type MainDocumentRoute, type MergedDoc, type NcfBoardTag, type NcfComponentPreviewConfig, type NcfDocumentColumn, type NcfEnvironment, type NcfHistoryConfig, type NcfI18nConfig, type NcfInternalField, type NcfInternalFieldOption, type NcfKitConfig, type NcfPageTypeConfig, type NcfPageTypeInput, type NcfToolName, type NcfToolsConfig, type NodeLayout, type NodePosition, type OccurrenceInput, type OccurrencePage, type OccurrencesState, type PageContent, type PageContentsState, type PageDoc, type PageFilters, type PageRow, type PageStatus, type PagesState, type PathInput, type Positioned, type PresentationOptions, type PreviewGrant, type PreviewPerspective, type PreviewTargetState, type ProjectStatus, type Registration, type ResolvedComponentPreview, type ResolvedDocumentColumn, type ResolvedHistory, type ResolvedI18n, type ResolvedKitConfig, type ResolvedPageType, type RowColor, type RowGroup, type SchemaFieldLike, type SchemaTypeLike, type SectionLayout, type SectionMapNode, type SectionOrder, type SectionsMapOptions, type Segment, type SiteRoutesRegistry, type SortDirection, type SortKey, type ThumbnailInput, type VersionedDoc, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, requiredUnlessDefault, requiredUnlessDefaultFor };
1937
+ export { type AddColumnInput, type Annotation, type AnnotationsState, type BlockOccurrence, type BlockTypeInfo, type BoardEdge, type BoardGraph, type BoardLayoutState, type BoardNode, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, type Change, type ChangeKind, type CollectedLinks, type ColorBy, type ColorOptions, type ConfigIssue, type CrossLanguageReport, DEFAULT_COMPONENT_DEFAULTS_TYPE, type DeriveOptions, type GroupBy, type GroupOptions, type HistoryDetail, type HistoryEvent, type IssueLevel, type KitContextValue, type KitUpdate, type LayoutMode, type MainDocumentRoute, type MergedDoc, type NcfBoardTag, type NcfComponentPreviewConfig, type NcfDocumentColumn, type NcfEnvironment, type NcfHistoryConfig, type NcfI18nConfig, type NcfInternalField, type NcfInternalFieldOption, type NcfKitConfig, type NcfPageTypeConfig, type NcfPageTypeInput, type NcfToolName, type NcfToolsConfig, type NodeLayout, type NodePosition, type OccurrenceInput, type OccurrencePage, type OccurrencesState, type PageContent, type PageContentsState, type PageDoc, type PageFilters, type PageRow, type PageStatus, type PagesState, type PathInput, type Positioned, type PresentationOptions, type PreviewGrant, type PreviewPerspective, type PreviewTargetState, type ProjectStatus, type Registration, type ResolvedComponentPreview, type ResolvedDocumentColumn, type ResolvedHistory, type ResolvedI18n, type ResolvedKitConfig, type ResolvedPageType, type RowColor, type RowGroup, type SchemaFieldLike, type SchemaTypeLike, type SectionLayout, type SectionMapNode, type SectionOrder, type SectionsMapOptions, type Segment, type SiteRoutesRegistry, type SortDirection, type SortKey, type ThumbnailInput, type VersionedDoc, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, requiredUnlessDefault, requiredUnlessDefaultFor };
1889
1938
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1384,7 +1384,7 @@ function explainGrantError(error) {
1384
1384
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1385
1385
  * le vérifie.
1386
1386
  */
1387
- const KIT_VERSION = "2.36.0";
1387
+ const KIT_VERSION = "2.37.0";
1388
1388
  /**
1389
1389
  * Signale ce Studio au service du kit, une fois par montage.
1390
1390
  *
@@ -1727,7 +1727,7 @@ function useKitUpdate() {
1727
1727
  !controller.signal.aborted && body?.version && setLatest(body.version);
1728
1728
  }).catch(() => {}), () => controller.abort();
1729
1729
  }, []);
1730
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.36.0") > 0);
1730
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.37.0") > 0);
1731
1731
  return {
1732
1732
  current: KIT_VERSION,
1733
1733
  latest,
@@ -2960,22 +2960,22 @@ async function localizeReferences(client, value, language) {
2960
2960
  for (let row of rows ?? []) row?.from && row.to && row.to !== row.from && map.set(row.from, row.to);
2961
2961
  return map.size ? replaceRefs(value, map) : value;
2962
2962
  }
2963
- const isObj$1 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
2963
+ const isObj$3 = (v) => typeof v == "object" && !!v && !Array.isArray(v);
2964
2964
  /** Textes d'une valeur, dans l'ordre. */
2965
2965
  function collectTexts$1(value) {
2966
2966
  if (typeof value == "string") return [value];
2967
2967
  if (!Array.isArray(value)) return [];
2968
2968
  let out = [];
2969
2969
  for (let item of value) if (typeof item == "string") out.push(item);
2970
- 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);
2970
+ else if (isObj$3(item) && Array.isArray(item.children)) for (let child of item.children) isObj$3(child) && typeof child.text == "string" && out.push(child.text);
2971
2971
  return out;
2972
2972
  }
2973
2973
  /** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
2974
2974
  function replaceTexts(value, texts) {
2975
2975
  let i = 0, next = () => texts[i++] ?? "";
2976
- return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$1(item) && Array.isArray(item.children) ? {
2976
+ return typeof value == "string" ? next() : Array.isArray(value) ? value.map((item) => typeof item == "string" ? next() : isObj$3(item) && Array.isArray(item.children) ? {
2977
2977
  ...item,
2978
- children: item.children.map((child) => isObj$1(child) && typeof child.text == "string" ? {
2978
+ children: item.children.map((child) => isObj$3(child) && typeof child.text == "string" ? {
2979
2979
  ...child,
2980
2980
  text: next()
2981
2981
  } : child)
@@ -2988,14 +2988,14 @@ function parsePathKey(path) {
2988
2988
  return out;
2989
2989
  }
2990
2990
  function itemOf(list, key) {
2991
- return list.find((i) => isObj$1(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
2991
+ return list.find((i) => isObj$3(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : void 0);
2992
2992
  }
2993
2993
  /** Valeur d'un document au chemin `sections[a].title`. */
2994
2994
  function valueAtKey(doc, path) {
2995
2995
  let cur = doc;
2996
2996
  for (let seg of parsePathKey(path)) {
2997
2997
  if (cur == null) return;
2998
- cur = "field" in seg ? isObj$1(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
2998
+ cur = "field" in seg ? isObj$3(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0;
2999
2999
  }
3000
3000
  return cur;
3001
3001
  }
@@ -3004,10 +3004,10 @@ function setAtKey(doc, path, value) {
3004
3004
  let segs = parsePathKey(path), cur = doc;
3005
3005
  for (let n = 0; n < segs.length - 1; n++) {
3006
3006
  let seg = segs[n];
3007
- 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;
3007
+ if (cur = "field" in seg ? isObj$3(cur) ? cur[seg.field] : void 0 : Array.isArray(cur) ? itemOf(cur, seg.item) : void 0, cur == null) return !1;
3008
3008
  }
3009
3009
  let last = segs[segs.length - 1];
3010
- return !last || !("field" in last) || !isObj$1(cur) ? !1 : (cur[last.field] = value, !0);
3010
+ return !last || !("field" in last) || !isObj$3(cur) ? !1 : (cur[last.field] = value, !0);
3011
3011
  }
3012
3012
  const MESSAGES = {
3013
3013
  daily_limit: "Daily AI translation limit reached for this project.",
@@ -3059,7 +3059,7 @@ const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
3059
3059
  "datetime",
3060
3060
  "number",
3061
3061
  "boolean"
3062
- ]), 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");
3062
+ ]), 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");
3063
3063
  function typeNames(t) {
3064
3064
  let out = [];
3065
3065
  for (let c = t; c; c = c.type) c.name && out.push(c.name);
@@ -3078,7 +3078,7 @@ function kindOf(t, value) {
3078
3078
  }
3079
3079
  return t.jsonType === "object" ? "object" : t.jsonType === "string" ? t.options?.list?.length ? "value" : "text" : "value";
3080
3080
  }
3081
- return keyed$1(value) ? "list" : isObj(value) ? "object" : "value";
3081
+ return keyed$1(value) ? "list" : isObj$2(value) ? "object" : "value";
3082
3082
  }
3083
3083
  function fieldType(t, name) {
3084
3084
  for (let c = t; c; c = c.type) {
@@ -3095,8 +3095,8 @@ function itemType(t, item) {
3095
3095
  function collectTexts(value, t, path, acc) {
3096
3096
  let kind = kindOf(t, value);
3097
3097
  if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
3098
- else if (kind === "object" && isObj(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
3099
- else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
3098
+ 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);
3099
+ 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);
3100
3100
  }
3101
3101
  const ABSENT$1 = Symbol("absent");
3102
3102
  function merge(target, before, after, t, path, acc) {
@@ -3105,8 +3105,8 @@ function merge(target, before, after, t, path, acc) {
3105
3105
  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);
3106
3106
  if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3107
3107
  if (kind === "object") {
3108
- if (!isObj(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3109
- let base = isObj(target) ? { ...target } : { _type: after._type }, b = isObj(before) ? before : {};
3108
+ if (!isObj$2(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
3109
+ let base = isObj$2(target) ? { ...target } : { _type: after._type }, b = isObj$2(before) ? before : {};
3110
3110
  for (let k of /* @__PURE__ */ new Set([...Object.keys(b), ...Object.keys(after)])) {
3111
3111
  if (k.startsWith("_") || SKIP_KEYS.has(k)) continue;
3112
3112
  let v = merge(base[k], b[k], after[k], fieldType(t, k), path ? `${path}.${k}` : k, acc);
@@ -3114,7 +3114,7 @@ function merge(target, before, after, t, path, acc) {
3114
3114
  }
3115
3115
  return base;
3116
3116
  }
3117
- 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 = [];
3117
+ let tgt = Array.isArray(target) ? target.filter(isObj$2) : [], bef = Array.isArray(before) ? before.filter(isObj$2) : [], aft = Array.isArray(after) ? after.filter(isObj$2) : [], byKey = (list) => new Map(list.map((i) => [i._key, i])), tMap = byKey(tgt), bMap = byKey(bef), aMap = byKey(aft), result = [];
3118
3118
  for (let item of aft) {
3119
3119
  let key = item._key, it = itemType(t, item);
3120
3120
  if (tMap.has(key)) {
@@ -3148,7 +3148,7 @@ function propagate(target, before, after, documentType) {
3148
3148
  return {
3149
3149
  document: {
3150
3150
  ...target ?? {},
3151
- ...isObj(merged) ? merged : {}
3151
+ ...isObj$2(merged) ? merged : {}
3152
3152
  },
3153
3153
  ...acc
3154
3154
  };
@@ -9658,6 +9658,120 @@ function withMoreTool(tools, names = DEFAULT_MORE_TOOLS) {
9658
9658
  };
9659
9659
  return [...tools.filter((tool) => !names.includes(tool.name)), more];
9660
9660
  }
9661
+ const isObj$1 = (v) => {
9662
+ if (!v || typeof v != "object" || Array.isArray(v) || "$$typeof" in v) return !1;
9663
+ let proto = Object.getPrototypeOf(v);
9664
+ return proto === Object.prototype || proto === null;
9665
+ };
9666
+ /**
9667
+ * RÈGLE D'OR DU MULTILINGUE : une référence ne propose que des documents de la
9668
+ * MÊME langue que le document en cours (un article EN ne voit que les catégories EN,
9669
+ * une page FR que les pages FR). Les documents sans langue (logos, régions, assets…)
9670
+ * restent proposés. Un document commun à toutes les langues (Navigation…) vise la
9671
+ * langue principale.
9672
+ *
9673
+ * Pose ce filtre sur TOUS les champs de référence des types donnés (champs, listes,
9674
+ * objets imbriqués, annotations du texte riche), combiné avec un filtre déjà présent.
9675
+ * À appliquer aux types du projet :
9676
+ *
9677
+ * ```ts
9678
+ * schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}
9679
+ * ```
9680
+ */
9681
+ function withSameLanguageReferences(types, options) {
9682
+ let i18n = options.i18n;
9683
+ if (!i18n) return types;
9684
+ let field = i18n.field ?? "language", fallback = i18n.defaultLocale ?? i18n.locales?.[0], condition = `(!defined(${field}) || ${field} == $ncfLanguage)`, languageOf = (document) => typeof document?.[field] == "string" && document[field] || fallback, wrap = (opts) => {
9685
+ let previous = opts?.filter, previousParams = opts?.filterParams ?? {}, filter = async (context) => {
9686
+ let base = typeof previous == "function" ? await previous(context) ?? {} : typeof previous == "string" ? {
9687
+ filter: previous,
9688
+ params: previousParams
9689
+ } : {};
9690
+ return {
9691
+ filter: base.filter ? `(${base.filter}) && ${condition}` : condition,
9692
+ params: {
9693
+ ...base.params ?? {},
9694
+ ncfLanguage: languageOf(context.document)
9695
+ }
9696
+ };
9697
+ }, { filterParams: _ignored, ...rest } = opts ?? {};
9698
+ return {
9699
+ ...rest,
9700
+ filter
9701
+ };
9702
+ }, visit = (node) => {
9703
+ if (Array.isArray(node)) return node.map(visit);
9704
+ if (!isObj$1(node)) return node;
9705
+ let out = {};
9706
+ for (let [key, value] of Object.entries(node)) out[key] = key === "options" || key === "initialValue" || key === "validation" ? value : visit(value);
9707
+ return node.type === "reference" && Array.isArray(node.to) && (out.options = wrap(node.options)), out;
9708
+ };
9709
+ return types.map((t) => visit(t));
9710
+ }
9711
+ const isObj = (v) => !!v && typeof v == "object" && !Array.isArray(v), bare = (id) => id.replace(/^drafts\./, "");
9712
+ /** Références d'une valeur, avec leur chemin de patch (`a.b[_key=="x"].c`). */
9713
+ function refs(value, path, out) {
9714
+ if (Array.isArray(value)) {
9715
+ value.forEach((item, i) => refs(item, `${path}[${isObj(item) && typeof item._key == "string" ? `_key=="${item._key}"` : i}]`, out));
9716
+ return;
9717
+ }
9718
+ if (isObj(value)) {
9719
+ typeof value._ref == "string" && !/^(image|file)-/.test(value._ref) && out.push({
9720
+ path: `${path}._ref`,
9721
+ ref: value._ref
9722
+ });
9723
+ for (let [k, v] of Object.entries(value)) k.startsWith("_") || refs(v, path ? `${path}.${k}` : k, out);
9724
+ }
9725
+ }
9726
+ /**
9727
+ * RÈGLE D'OR DU MULTILINGUE, côté données : chaque référence d'un document vise un
9728
+ * document de SA langue (document sans langue : la langue principale). Une
9729
+ * référence croisée est repointée vers la traduction de la bonne langue (liens de
9730
+ * traduction) ; sans traduction, elle est signalée et laissée. Publiés et
9731
+ * brouillons. `apply: false` : simulation.
9732
+ *
9733
+ * ```ts
9734
+ * // studio/scripts/references-same-language.ts (sanity exec --with-user-token)
9735
+ * const report = await fixCrossLanguageReferences(getCliClient(...), {defaultLocale: 'fr', apply})
9736
+ * ```
9737
+ */
9738
+ async function fixCrossLanguageReferences(client, options) {
9739
+ let field = options.field ?? "language", c = client.withConfig({ perspective: "raw" }), docs = await c.fetch("*[!(_type match \"system.*\") && !(_type match \"sanity.*\") && !(_type match \"ncf.*\") && _type != \"translation.metadata\"]"), language = /* @__PURE__ */ new Map();
9740
+ for (let d of docs) typeof d[field] == "string" && language.set(bare(String(d._id)), String(d[field]));
9741
+ let metas = await c.fetch("*[_type == \"translation.metadata\"]{translations}"), equivalent = /* @__PURE__ */ new Map();
9742
+ for (let m of metas) {
9743
+ let group = /* @__PURE__ */ new Map();
9744
+ for (let t of m.translations ?? []) t.value?._ref && group.set(t.language ?? t._key ?? "", t.value._ref);
9745
+ for (let id of group.values()) equivalent.set(id, group);
9746
+ }
9747
+ let report = {
9748
+ fixed: [],
9749
+ missing: []
9750
+ };
9751
+ for (let d of docs) {
9752
+ let own = typeof d[field] == "string" ? String(d[field]) : options.defaultLocale, found = [];
9753
+ for (let [k, v] of Object.entries(d)) k.startsWith("_") || refs(v, k, found);
9754
+ let set = {};
9755
+ for (let { path, ref } of found) {
9756
+ let target = language.get(bare(ref));
9757
+ if (!target || target === own) continue;
9758
+ let to = equivalent.get(bare(ref))?.get(own);
9759
+ to ? (set[path] = to, report.fixed.push({
9760
+ documentId: String(d._id),
9761
+ path,
9762
+ from: ref,
9763
+ to
9764
+ })) : report.missing.push({
9765
+ documentId: String(d._id),
9766
+ path,
9767
+ ref,
9768
+ language: own
9769
+ });
9770
+ }
9771
+ options.apply && Object.keys(set).length && await c.patch(String(d._id)).ifRevisionId(String(d._rev)).set(set).commit({ visibility: "async" });
9772
+ }
9773
+ return report;
9774
+ }
9661
9775
  /**
9662
9776
  * Bascule brouillons / en ligne, posée dans l'aperçu lui-même.
9663
9777
  *
@@ -10215,6 +10329,6 @@ function hasLanguageField(schemaType, field) {
10215
10329
  let fields = schemaType?.fields;
10216
10330
  return Array.isArray(fields) && fields.some((f) => f?.name === field);
10217
10331
  }
10218
- export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineComponentDefaults, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool };
10332
+ export { ANNOTATION_TYPE, ActorName, BOARD_LAYOUT_ID, BOARD_LAYOUT_TYPE, BRAIN_NODE_SIZE, BoardLayoutProvider, COLUMN_TYPE, CONTENT_SCAN_LIMIT, CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT, CUSTOM_ENVIRONMENT_ID, DATA_PREFIX, DEFAULT_BOARD_TAGS, DEFAULT_COMPONENT_DEFAULTS_TYPE, DEFAULT_COMPONENT_PREVIEW, DEFAULT_I18N, DEFAULT_INTERNAL_FIELDS, DEFAULT_MORE_TOOLS, DEFAULT_PAGE_BUILDER_FIELD, DEFAULT_SLUG_FIELD, DEFAULT_TITLE_FIELD, KIT_API_VERSION, KIT_VERSION, NCF_COMPONENTS_TOOL, NCF_DESIGN_SYSTEM_TOOL, NCF_HIDDEN_TYPES, NCF_HISTORY_TOOL, NCF_MORE_TOOL, NCF_PAGES_TOOL, NCF_TOOL_NAMES, NODE_FIELD_TYPE, NODE_HEIGHT, NODE_WIDTH, NcfKitUpdate, NcfPreviewHeader, NcfPreviewLauncher, PERSPECTIVES, PROJECTION, SECTION_NODE_TYPE, STATUS_COLORS, STATUS_LABELS, SharePreview, UNSET_LABEL, addColumn, addColumnOption, announce, applySavedPositions, baseId, blockName, blockTypesFromSchema, buildContentsQuery, buildLinkGraph, buildPageRows, buildPagesQuery, collectLinks, collectOccurrences, colorForRow, colorFromString, columnId, compareVersions, componentDefaultsMainDocument, componentDefaultsMainDocuments, createPreviewLauncher, customEnvironment, defaultNodeSize, defaultsFieldName, defineComponentDefaults, depth, deriveDocumentColumns, diffDocuments, diffWords, editIntentPath, explainGrantError, fallbackLayout, fetchDetail, fetchTimeline, fillTemplate, filterRows, fixCrossLanguageReferences, flatten, formatDocumentValue, groupPageRows, groupValue, hasBlockingIssue, humanizeBlockName, isDraftId, isKitType, isPrerelease, isSafeColumnKey, isSafeFieldPath, isTextChange, isVersionId, issuesForTool, keyForPath, kitSchemaTypes, layoutGraph, layoutSectionsMap, localesInRows, mergeVersions, missingPageTypes, moveColumn, ncfAllowedOrigins, ncfKit, ncfMainDocuments, ncfPresentationComponents, ncfPreviewComponents, normalizeInternalPath, normalizePath, occurrencesForTypes, pageThumbnailUrl, pageTypeFor, pageTypesFromSiteRoutes, pageTypesWithoutBuilder, parentPath, presentationPath, pruneSavedPositions, releaseId, removeColumn, renameColumn, requestPreviewGrant, requiredUnlessDefault, requiredUnlessDefaultFor, resolveColorBy, resolveConfig, segments, slugKey, sortRows, summarize, toKebabCase, toPath, toUrl, topLevelBlockCount, uniqueColumnId, upsertLayout, urlOn, useAnnotations, useBoardLayout, useDocumentColumns, useHistory, useInternalColumns, useKitClient, useKitConfig, useKitContext, useKitUpdate, useOccurrences, usePageContents, usePages, usePreviewTarget, useRegistration, validateConfig, withAlpha, withMoreTool, withSameLanguageReferences };
10219
10333
 
10220
10334
  //# sourceMappingURL=index.js.map