@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.36.0",
3
+ "version": "2.37.0",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
package/src/index.ts CHANGED
@@ -282,6 +282,8 @@ function hasLanguageField(schemaType: unknown, field: string): boolean {
282
282
  return Array.isArray(fields) && fields.some((f) => f?.name === field)
283
283
  }
284
284
 
285
+ export {withSameLanguageReferences} from './schema/sameLanguageReferences'
286
+ export {fixCrossLanguageReferences, type CrossLanguageReport} from './lib/fixCrossLanguageReferences'
285
287
  export {NcfPreviewHeader, ncfPreviewComponents} from './tools/presentation/PreviewHeader'
286
288
  export {ncfPresentationComponents} from './tools/presentation/PagesNavigator'
287
289
  export {NcfPreviewLauncher, createPreviewLauncher} from './tools/navbar/PreviewLauncher'
@@ -0,0 +1,76 @@
1
+ import type {SanityClient} from 'sanity'
2
+
3
+ type Obj = Record<string, unknown>
4
+ const isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)
5
+ const bare = (id: string) => id.replace(/^drafts\./, '')
6
+
7
+ export interface CrossLanguageReport {
8
+ /** Références repointées (ou à repointer en simulation). */
9
+ fixed: {documentId: string; path: string; from: string; to: string}[]
10
+ /** Références croisées sans équivalent dans la langue du document (laissées). */
11
+ missing: {documentId: string; path: string; ref: string; language: string}[]
12
+ }
13
+
14
+ /** Références d'une valeur, avec leur chemin de patch (`a.b[_key=="x"].c`). */
15
+ function refs(value: unknown, path: string, out: {path: string; ref: string}[]) {
16
+ if (Array.isArray(value)) {
17
+ value.forEach((item, i) => refs(item, `${path}[${isObj(item) && typeof item._key === 'string' ? `_key=="${item._key}"` : i}]`, out))
18
+ return
19
+ }
20
+ if (!isObj(value)) return
21
+ if (typeof value._ref === 'string' && !/^(image|file)-/.test(value._ref)) out.push({path: `${path}._ref`, ref: value._ref})
22
+ for (const [k, v] of Object.entries(value)) if (!k.startsWith('_')) refs(v, path ? `${path}.${k}` : k, out)
23
+ }
24
+
25
+ /**
26
+ * RÈGLE D'OR DU MULTILINGUE, côté données : chaque référence d'un document vise un
27
+ * document de SA langue (document sans langue : la langue principale). Une
28
+ * référence croisée est repointée vers la traduction de la bonne langue (liens de
29
+ * traduction) ; sans traduction, elle est signalée et laissée. Publiés et
30
+ * brouillons. `apply: false` : simulation.
31
+ *
32
+ * ```ts
33
+ * // studio/scripts/references-same-language.ts (sanity exec --with-user-token)
34
+ * const report = await fixCrossLanguageReferences(getCliClient(...), {defaultLocale: 'fr', apply})
35
+ * ```
36
+ */
37
+ export async function fixCrossLanguageReferences(
38
+ client: SanityClient,
39
+ options: {field?: string; defaultLocale: string; apply?: boolean},
40
+ ): Promise<CrossLanguageReport> {
41
+ const field = options.field ?? 'language'
42
+ const c = client.withConfig({perspective: 'raw'})
43
+ const docs = await c.fetch<Obj[]>(
44
+ `*[!(_type match "system.*") && !(_type match "sanity.*") && !(_type match "ncf.*") && _type != "translation.metadata"]`,
45
+ )
46
+ const language = new Map<string, string>()
47
+ for (const d of docs) if (typeof d[field] === 'string') language.set(bare(String(d._id)), String(d[field]))
48
+ const metas = await c.fetch<{translations?: {language?: string; _key?: string; value?: {_ref?: string}}[]}[]>(
49
+ `*[_type == "translation.metadata"]{translations}`,
50
+ )
51
+ const equivalent = new Map<string, Map<string, string>>()
52
+ for (const m of metas) {
53
+ const group = new Map<string, string>()
54
+ for (const t of m.translations ?? []) if (t.value?._ref) group.set(t.language ?? t._key ?? '', t.value._ref)
55
+ for (const id of group.values()) equivalent.set(id, group)
56
+ }
57
+
58
+ const report: CrossLanguageReport = {fixed: [], missing: []}
59
+ for (const d of docs) {
60
+ const own = typeof d[field] === 'string' ? String(d[field]) : options.defaultLocale
61
+ const found: {path: string; ref: string}[] = []
62
+ for (const [k, v] of Object.entries(d)) if (!k.startsWith('_')) refs(v, k, found)
63
+ const set: Record<string, string> = {}
64
+ for (const {path, ref} of found) {
65
+ const target = language.get(bare(ref))
66
+ if (!target || target === own) continue
67
+ const to = equivalent.get(bare(ref))?.get(own)
68
+ if (to) {
69
+ set[path] = to
70
+ report.fixed.push({documentId: String(d._id), path, from: ref, to})
71
+ } else report.missing.push({documentId: String(d._id), path, ref, language: own})
72
+ }
73
+ if (options.apply && Object.keys(set).length) await c.patch(String(d._id)).ifRevisionId(String(d._rev)).set(set).commit({visibility: 'async'})
74
+ }
75
+ return report
76
+ }
@@ -0,0 +1,65 @@
1
+ import type {NcfKitConfig} from '../config/types'
2
+
3
+ type Obj = Record<string, unknown>
4
+ type FilterResult = {filter?: string; params?: Record<string, unknown>}
5
+ type FilterFn = (context: {document?: Obj; [key: string]: unknown}) => FilterResult | Promise<FilterResult>
6
+
7
+ // Objet de configuration simple (jamais un élément React, une icône ou une instance).
8
+ const isObj = (v: unknown): v is Obj => {
9
+ if (!v || typeof v !== 'object' || Array.isArray(v) || '$$typeof' in v) return false
10
+ const proto = Object.getPrototypeOf(v)
11
+ return proto === Object.prototype || proto === null
12
+ }
13
+
14
+ /**
15
+ * RÈGLE D'OR DU MULTILINGUE : une référence ne propose que des documents de la
16
+ * MÊME langue que le document en cours (un article EN ne voit que les catégories EN,
17
+ * une page FR que les pages FR). Les documents sans langue (logos, régions, assets…)
18
+ * restent proposés. Un document commun à toutes les langues (Navigation…) vise la
19
+ * langue principale.
20
+ *
21
+ * Pose ce filtre sur TOUS les champs de référence des types donnés (champs, listes,
22
+ * objets imbriqués, annotations du texte riche), combiné avec un filtre déjà présent.
23
+ * À appliquer aux types du projet :
24
+ *
25
+ * ```ts
26
+ * schema: {types: withSameLanguageReferences(schemaTypes, ncfOptions)}
27
+ * ```
28
+ */
29
+ export function withSameLanguageReferences<T>(types: T[], options: Pick<NcfKitConfig, 'i18n'>): T[] {
30
+ const i18n = options.i18n
31
+ if (!i18n) return types
32
+ const field = i18n.field ?? 'language'
33
+ const fallback = i18n.defaultLocale ?? i18n.locales?.[0]
34
+ const condition = `(!defined(${field}) || ${field} == $ncfLanguage)`
35
+ const languageOf = (document: Obj | undefined) => (typeof document?.[field] === 'string' && document[field]) || fallback
36
+
37
+ const wrap = (opts: Obj | undefined): Obj => {
38
+ const previous = opts?.filter
39
+ const previousParams = (opts?.filterParams as Record<string, unknown> | undefined) ?? {}
40
+ const filter: FilterFn = async (context) => {
41
+ const base: FilterResult =
42
+ typeof previous === 'function'
43
+ ? ((await (previous as FilterFn)(context)) ?? {})
44
+ : typeof previous === 'string'
45
+ ? {filter: previous, params: previousParams}
46
+ : {}
47
+ return {
48
+ filter: base.filter ? `(${base.filter}) && ${condition}` : condition,
49
+ params: {...(base.params ?? {}), ncfLanguage: languageOf(context.document)},
50
+ }
51
+ }
52
+ const {filterParams: _ignored, ...rest} = opts ?? {}
53
+ return {...rest, filter}
54
+ }
55
+
56
+ const visit = (node: unknown): unknown => {
57
+ if (Array.isArray(node)) return node.map(visit)
58
+ if (!isObj(node)) return node
59
+ const out: Obj = {}
60
+ for (const [key, value] of Object.entries(node)) out[key] = key === 'options' || key === 'initialValue' || key === 'validation' ? value : visit(value)
61
+ if (node.type === 'reference' && Array.isArray(node.to)) out.options = wrap(node.options as Obj | undefined)
62
+ return out
63
+ }
64
+ return types.map((t) => visit(t) as T)
65
+ }
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.36.0'
6
+ export const KIT_VERSION = '2.37.0'