@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/README.md +1 -0
- package/dist/aiJsonLd-DiYeDzou.js +170 -0
- package/dist/aiJsonLd-DiYeDzou.js.map +1 -0
- package/dist/finalUrl-C1kzYMzQ.js +273 -0
- package/dist/finalUrl-C1kzYMzQ.js.map +1 -0
- package/dist/{fixCrossLanguageReferences-CQGzpNii.js → fixCrossLanguageReferences-BZk9CkdI.js} +3 -271
- package/dist/fixCrossLanguageReferences-BZk9CkdI.js.map +1 -0
- package/dist/{fixCrossLanguageReferences-CFZax-Nb.d.ts → fixCrossLanguageReferences-CjL_Xy0U.d.ts} +23 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +69 -82
- package/dist/index.js.map +1 -1
- package/dist/jsonld.d.ts +79 -0
- package/dist/jsonld.js +225 -0
- package/dist/jsonld.js.map +1 -0
- package/dist/schema.d.ts +2 -2
- package/dist/schema.js +4 -2
- package/dist/schema.js.map +1 -1
- package/package.json +7 -2
- package/src/actions/JsonLdPublish.tsx +69 -0
- package/src/config/resolve.ts +6 -0
- package/src/config/types.ts +24 -0
- package/src/form/JsonLdInput.tsx +191 -0
- package/src/form/jsonLdType.ts +61 -0
- package/src/index.ts +8 -2
- package/src/jsonld.ts +19 -0
- package/src/lib/aiJsonLd.ts +53 -0
- package/src/lib/jsonLdContent.ts +91 -0
- package/src/schema/formTabs.ts +4 -2
- package/src/version.ts +1 -1
- package/dist/fixCrossLanguageReferences-CQGzpNii.js.map +0 -1
package/dist/jsonld.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { ObjectDefinition, ObjectInputProps } from "sanity";
|
|
2
|
+
interface JsonLdTypeOptions {
|
|
3
|
+
/** Nom du type (défaut `jsonLd`). */
|
|
4
|
+
name?: string;
|
|
5
|
+
/** Titre affiché. */
|
|
6
|
+
title?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Type d'objet « Données structurées (JSON-LD) » à poser sur les pages.
|
|
10
|
+
*
|
|
11
|
+
* Deux champs : `mode` (auto / manuel) et `data` (le JSON-LD stocké). En mode
|
|
12
|
+
* auto, le JSON-LD est régénéré par l'IA à chaque publication (voir
|
|
13
|
+
* `withJsonLd`) ; en mode manuel, il n'est jamais touché automatiquement.
|
|
14
|
+
* L'édition et la (re)génération passent par {@link JsonLdInput}.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* import {defineJsonLdType} from '@nocode-factory/sanity-kit/jsonld'
|
|
18
|
+
* export const jsonLd = defineJsonLdType()
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export declare function defineJsonLdType(options?: JsonLdTypeOptions): ObjectDefinition;
|
|
22
|
+
type JsonLdMode = 'auto' | 'manuel';
|
|
23
|
+
interface JsonLdValue {
|
|
24
|
+
mode?: JsonLdMode;
|
|
25
|
+
data?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Champ « Données structurées (JSON-LD) » avec deux modes :
|
|
29
|
+
*
|
|
30
|
+
* - **Auto** (défaut) : l'IA régénère le JSON-LD à chaque publication, à partir
|
|
31
|
+
* du contenu de la page. Lecture seule ici (une saisie serait écrasée).
|
|
32
|
+
* - **Manuel** : le bouton « Rédiger avec l'IA » propose un JSON-LD une fois,
|
|
33
|
+
* puis plus rien ne le modifie ; on l'édite librement.
|
|
34
|
+
*
|
|
35
|
+
* Le bouton de (re)génération est présent dans les deux modes.
|
|
36
|
+
*/
|
|
37
|
+
export declare function JsonLdInput(props: ObjectInputProps): React.JSX.Element;
|
|
38
|
+
/** Service du kit (même clé de projet et même adresse que l'historique et la traduction). */
|
|
39
|
+
interface JsonLdService {
|
|
40
|
+
endpoint: string;
|
|
41
|
+
projectKey: string;
|
|
42
|
+
}
|
|
43
|
+
/** Ce que le Studio envoie pour décrire la page à l'IA. */
|
|
44
|
+
interface JsonLdRequest {
|
|
45
|
+
/** URL absolue de la page en ligne (sert d'`url`/`@id`). */
|
|
46
|
+
url: string;
|
|
47
|
+
/** Langue de la page (BCP 47), devient `inLanguage`. */
|
|
48
|
+
locale?: string;
|
|
49
|
+
/** Indice sur la nature de la page (type Sanity, ou « article »...). */
|
|
50
|
+
type?: string;
|
|
51
|
+
/** Titre de la page. */
|
|
52
|
+
title?: string;
|
|
53
|
+
/** Texte de la page (titres, descriptions, corps), assemblé par le Studio. */
|
|
54
|
+
content: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Demande à l'IA le JSON-LD d'une page, à partir de son contenu. Renvoie l'objet
|
|
58
|
+
* JSON-LD (jamais une chaîne). L'appel passe par l'Edge Function `jsonld` du kit,
|
|
59
|
+
* qui détient la clé Anthropic : le Studio ne transmet que sa clé de projet.
|
|
60
|
+
*/
|
|
61
|
+
export declare function generateJsonLd(service: JsonLdService, input: JsonLdRequest): Promise<Record<string, unknown>>;
|
|
62
|
+
/**
|
|
63
|
+
* Assemble le TEXTE d'un document Sanity pour la génération de JSON-LD par IA :
|
|
64
|
+
* titres, descriptions, corps (texte riche compris). On parcourt le document en
|
|
65
|
+
* profondeur et on ne garde que les chaînes lisibles, en écartant la plomberie
|
|
66
|
+
* (identifiants, slugs, styles de texte, références d'images...).
|
|
67
|
+
*/
|
|
68
|
+
/** Nom du champ JSON-LD par défaut (écarté du contenu envoyé, pour ne pas boucler). */
|
|
69
|
+
export declare const DEFAULT_JSONLD_FIELD = "jsonLd";
|
|
70
|
+
/**
|
|
71
|
+
* Texte lisible d'un document, dans l'ordre, prêt à être envoyé à l'IA.
|
|
72
|
+
* `extraSkip` : champs supplémentaires à ignorer (au moins le champ JSON-LD
|
|
73
|
+
* lui-même, pour ne pas renvoyer l'ancien JSON-LD au modèle).
|
|
74
|
+
*/
|
|
75
|
+
export declare function collectDocumentText(doc: unknown, extraSkip?: readonly string[]): string;
|
|
76
|
+
/** Titre probable d'un document (pour aider le modèle), sinon chaîne vide. */
|
|
77
|
+
export declare function guessDocumentTitle(doc: unknown): string;
|
|
78
|
+
export type { JsonLdMode, JsonLdRequest, JsonLdService, JsonLdTypeOptions, JsonLdValue };
|
|
79
|
+
//# sourceMappingURL=jsonld.d.ts.map
|
package/dist/jsonld.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { o as pageTypeFor, t as finalPath, u as toUrl } from "./finalUrl-C1kzYMzQ.js";
|
|
2
|
+
import { c as valueAtKey, i as guessDocumentTitle, n as DEFAULT_JSONLD_FIELD, r as collectDocumentText, t as generateJsonLd, u as useKitConfig } from "./aiJsonLd-DiYeDzou.js";
|
|
3
|
+
import { useCallback, useMemo, useState } from "react";
|
|
4
|
+
import { defineField, defineType, set, setIfMissing, unset, useFormValue } from "sanity";
|
|
5
|
+
import { Badge, Box, Button, Card, Flex, Stack, Text, TextArea } from "@sanity/ui";
|
|
6
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
7
|
+
const isObj = (v) => typeof v == "object" && !!v && !Array.isArray(v);
|
|
8
|
+
/** Vrai si `data` est un JSON valide (ou vide). */
|
|
9
|
+
function jsonError(data) {
|
|
10
|
+
if (!data || !data.trim()) return null;
|
|
11
|
+
try {
|
|
12
|
+
return JSON.parse(data), null;
|
|
13
|
+
} catch (error) {
|
|
14
|
+
return error instanceof Error ? error.message : "JSON invalide";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Champ « Données structurées (JSON-LD) » avec deux modes :
|
|
19
|
+
*
|
|
20
|
+
* - **Auto** (défaut) : l'IA régénère le JSON-LD à chaque publication, à partir
|
|
21
|
+
* du contenu de la page. Lecture seule ici (une saisie serait écrasée).
|
|
22
|
+
* - **Manuel** : le bouton « Rédiger avec l'IA » propose un JSON-LD une fois,
|
|
23
|
+
* puis plus rien ne le modifie ; on l'édite librement.
|
|
24
|
+
*
|
|
25
|
+
* Le bouton de (re)génération est présent dans les deux modes.
|
|
26
|
+
*/
|
|
27
|
+
function JsonLdInput(props) {
|
|
28
|
+
let { onChange, readOnly } = props, value = props.value ?? {}, mode = value.mode === "manuel" ? "manuel" : "auto", config = useKitConfig(), doc = useFormValue([]), [busy, setBusy] = useState(!1), [error, setError] = useState(null), field = config.jsonLd?.field ?? "jsonLd", invalid = jsonError(value.data), url = useMemo(() => {
|
|
29
|
+
if (!doc) return null;
|
|
30
|
+
let pageType = pageTypeFor(doc._type, config.pageTypes), slugValue = pageType?.slugField ? valueAtKey(doc, pageType.slugField) : null, slug = isObj(slugValue) ? slugValue.current ?? null : typeof slugValue == "string" ? slugValue : null, locale = config.i18n ? doc[config.i18n.field] ?? null : null;
|
|
31
|
+
return toUrl(config.previewUrl, finalPath({
|
|
32
|
+
slug,
|
|
33
|
+
locale
|
|
34
|
+
}, pageType, config, null));
|
|
35
|
+
}, [doc, config]), setMode = useCallback((next) => onChange([setIfMissing({}), set(next, ["mode"])]), [onChange]), setData = useCallback((next) => onChange(next ? [setIfMissing({}), set(next, ["data"])] : unset(["data"])), [onChange]), generate = useCallback(async () => {
|
|
36
|
+
if (config.history && doc) {
|
|
37
|
+
setBusy(!0), setError(null);
|
|
38
|
+
try {
|
|
39
|
+
if (!url) throw Error("URL du site introuvable : renseigne l'URL de prévisualisation et le slug.");
|
|
40
|
+
let content = collectDocumentText(doc, [field]);
|
|
41
|
+
if (!content.trim()) throw Error("Aucun contenu à décrire sur cette page.");
|
|
42
|
+
let result = await generateJsonLd(config.history, {
|
|
43
|
+
url,
|
|
44
|
+
locale: config.i18n ? doc[config.i18n.field] ?? void 0 : void 0,
|
|
45
|
+
type: doc._type,
|
|
46
|
+
title: guessDocumentTitle(doc),
|
|
47
|
+
content
|
|
48
|
+
});
|
|
49
|
+
onChange([setIfMissing({}), set(JSON.stringify(result, null, 2), ["data"])]);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
setError(err instanceof Error ? err.message : "Génération échouée.");
|
|
52
|
+
} finally {
|
|
53
|
+
setBusy(!1);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}, [
|
|
57
|
+
config,
|
|
58
|
+
doc,
|
|
59
|
+
url,
|
|
60
|
+
field,
|
|
61
|
+
onChange
|
|
62
|
+
]), hasData = !!(value.data && value.data.trim()), aiAvailable = !!config.history && !readOnly;
|
|
63
|
+
return /* @__PURE__ */ jsxs(Stack, {
|
|
64
|
+
gap: 3,
|
|
65
|
+
children: [
|
|
66
|
+
/* @__PURE__ */ jsxs(Flex, {
|
|
67
|
+
gap: 2,
|
|
68
|
+
children: [
|
|
69
|
+
/* @__PURE__ */ jsx(Button, {
|
|
70
|
+
mode: mode === "auto" ? "default" : "ghost",
|
|
71
|
+
tone: mode === "auto" ? "primary" : "default",
|
|
72
|
+
text: "Auto",
|
|
73
|
+
disabled: readOnly,
|
|
74
|
+
onClick: () => setMode("auto")
|
|
75
|
+
}),
|
|
76
|
+
/* @__PURE__ */ jsx(Button, {
|
|
77
|
+
mode: mode === "manuel" ? "default" : "ghost",
|
|
78
|
+
tone: mode === "manuel" ? "primary" : "default",
|
|
79
|
+
text: "Manuel",
|
|
80
|
+
disabled: readOnly,
|
|
81
|
+
onClick: () => setMode("manuel")
|
|
82
|
+
}),
|
|
83
|
+
/* @__PURE__ */ jsx(Box, { flex: 1 }),
|
|
84
|
+
aiAvailable ? /* @__PURE__ */ jsx(Button, {
|
|
85
|
+
text: busy ? "Génération…" : mode === "manuel" ? hasData ? "Régénérer la proposition" : "Rédiger avec l’IA" : "Régénérer maintenant",
|
|
86
|
+
tone: "primary",
|
|
87
|
+
disabled: busy,
|
|
88
|
+
onClick: () => void generate()
|
|
89
|
+
}) : null
|
|
90
|
+
]
|
|
91
|
+
}),
|
|
92
|
+
/* @__PURE__ */ jsx(Text, {
|
|
93
|
+
size: 1,
|
|
94
|
+
muted: !0,
|
|
95
|
+
children: mode === "auto" ? "Auto : le JSON-LD est régénéré par l’IA à chaque publication, d’après le contenu de la page. Lecture seule." : "Manuel : à toi de gérer ce JSON-LD. « Rédiger avec l’IA » propose une base ; ensuite, la publication n’y touche plus."
|
|
96
|
+
}),
|
|
97
|
+
error ? /* @__PURE__ */ jsx(Card, {
|
|
98
|
+
tone: "critical",
|
|
99
|
+
padding: 3,
|
|
100
|
+
radius: 2,
|
|
101
|
+
border: !0,
|
|
102
|
+
children: /* @__PURE__ */ jsx(Text, {
|
|
103
|
+
size: 1,
|
|
104
|
+
children: error
|
|
105
|
+
})
|
|
106
|
+
}) : null,
|
|
107
|
+
config.history ? null : /* @__PURE__ */ jsx(Card, {
|
|
108
|
+
tone: "caution",
|
|
109
|
+
padding: 3,
|
|
110
|
+
radius: 2,
|
|
111
|
+
border: !0,
|
|
112
|
+
children: /* @__PURE__ */ jsx(Text, {
|
|
113
|
+
size: 1,
|
|
114
|
+
children: "Génération IA indisponible : la clé de projet du kit (SANITY_STUDIO_NCF_PROJECT_KEY) n’est pas configurée."
|
|
115
|
+
})
|
|
116
|
+
}),
|
|
117
|
+
mode === "manuel" ? /* @__PURE__ */ jsx(TextArea, {
|
|
118
|
+
value: value.data ?? "",
|
|
119
|
+
readOnly,
|
|
120
|
+
rows: 12,
|
|
121
|
+
placeholder: "{ \"@context\": \"https://schema.org\", \"@type\": \"WebPage\" }",
|
|
122
|
+
onChange: (event) => setData(event.currentTarget.value),
|
|
123
|
+
style: {
|
|
124
|
+
fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
125
|
+
fontSize: 12
|
|
126
|
+
}
|
|
127
|
+
}) : hasData ? /* @__PURE__ */ jsx(Card, {
|
|
128
|
+
tone: "transparent",
|
|
129
|
+
padding: 3,
|
|
130
|
+
radius: 2,
|
|
131
|
+
border: !0,
|
|
132
|
+
children: /* @__PURE__ */ jsx(Box, {
|
|
133
|
+
overflow: "auto",
|
|
134
|
+
style: { maxHeight: 320 },
|
|
135
|
+
children: /* @__PURE__ */ jsx(Text, {
|
|
136
|
+
size: 1,
|
|
137
|
+
as: "pre",
|
|
138
|
+
style: {
|
|
139
|
+
fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
140
|
+
whiteSpace: "pre-wrap"
|
|
141
|
+
},
|
|
142
|
+
children: value.data
|
|
143
|
+
})
|
|
144
|
+
})
|
|
145
|
+
}) : /* @__PURE__ */ jsx(Card, {
|
|
146
|
+
tone: "transparent",
|
|
147
|
+
padding: 3,
|
|
148
|
+
radius: 2,
|
|
149
|
+
border: !0,
|
|
150
|
+
children: /* @__PURE__ */ jsx(Text, {
|
|
151
|
+
size: 1,
|
|
152
|
+
muted: !0,
|
|
153
|
+
children: "Aucun JSON-LD pour l’instant : il sera généré à la prochaine publication (ou tout de suite avec le bouton)."
|
|
154
|
+
})
|
|
155
|
+
}),
|
|
156
|
+
hasData ? /* @__PURE__ */ jsx(Flex, { children: invalid ? /* @__PURE__ */ jsx(Badge, {
|
|
157
|
+
tone: "critical",
|
|
158
|
+
title: invalid,
|
|
159
|
+
children: "JSON invalide"
|
|
160
|
+
}) : /* @__PURE__ */ jsx(Badge, {
|
|
161
|
+
tone: "positive",
|
|
162
|
+
children: "JSON valide"
|
|
163
|
+
}) }) : null
|
|
164
|
+
]
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Type d'objet « Données structurées (JSON-LD) » à poser sur les pages.
|
|
169
|
+
*
|
|
170
|
+
* Deux champs : `mode` (auto / manuel) et `data` (le JSON-LD stocké). En mode
|
|
171
|
+
* auto, le JSON-LD est régénéré par l'IA à chaque publication (voir
|
|
172
|
+
* `withJsonLd`) ; en mode manuel, il n'est jamais touché automatiquement.
|
|
173
|
+
* L'édition et la (re)génération passent par {@link JsonLdInput}.
|
|
174
|
+
*
|
|
175
|
+
* ```ts
|
|
176
|
+
* import {defineJsonLdType} from '@nocode-factory/sanity-kit/jsonld'
|
|
177
|
+
* export const jsonLd = defineJsonLdType()
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
function defineJsonLdType(options = {}) {
|
|
181
|
+
let { name = "jsonLd", title = "Données structurées (JSON-LD)" } = options;
|
|
182
|
+
return defineType({
|
|
183
|
+
name,
|
|
184
|
+
title,
|
|
185
|
+
type: "object",
|
|
186
|
+
components: { input: JsonLdInput },
|
|
187
|
+
fields: [defineField({
|
|
188
|
+
name: "mode",
|
|
189
|
+
title: "Mode",
|
|
190
|
+
type: "string",
|
|
191
|
+
options: {
|
|
192
|
+
list: [{
|
|
193
|
+
title: "Auto (IA, régénéré à la publication)",
|
|
194
|
+
value: "auto"
|
|
195
|
+
}, {
|
|
196
|
+
title: "Manuel",
|
|
197
|
+
value: "manuel"
|
|
198
|
+
}],
|
|
199
|
+
layout: "radio"
|
|
200
|
+
},
|
|
201
|
+
initialValue: "auto"
|
|
202
|
+
}), defineField({
|
|
203
|
+
name: "data",
|
|
204
|
+
title: "JSON-LD",
|
|
205
|
+
type: "text",
|
|
206
|
+
rows: 12
|
|
207
|
+
})],
|
|
208
|
+
preview: {
|
|
209
|
+
select: {
|
|
210
|
+
mode: "mode",
|
|
211
|
+
data: "data"
|
|
212
|
+
},
|
|
213
|
+
prepare({ mode, data }) {
|
|
214
|
+
let m = mode === "manuel" ? "Manuel" : "Auto";
|
|
215
|
+
return {
|
|
216
|
+
title: "Données structurées (JSON-LD)",
|
|
217
|
+
subtitle: data ? `${m} · défini` : `${m} · vide`
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
export { DEFAULT_JSONLD_FIELD, JsonLdInput, collectDocumentText, defineJsonLdType, generateJsonLd, guessDocumentTitle };
|
|
224
|
+
|
|
225
|
+
//# sourceMappingURL=jsonld.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonld.js","names":[],"sources":["../src/form/JsonLdInput.tsx","../src/form/jsonLdType.ts"],"sourcesContent":["import {useCallback, useMemo, useState} from 'react'\nimport {set, setIfMissing, unset, useFormValue, type ObjectInputProps} from 'sanity'\nimport {Badge, Box, Button, Card, Flex, Stack, Text, TextArea} from '@sanity/ui'\nimport {useKitConfig} from '../context/KitContext'\nimport {finalPath} from '../lib/finalUrl'\nimport {toUrl} from '../lib/paths'\nimport {pageTypeFor} from '../lib/paths'\nimport {valueAtKey} from '../lib/aiTexts'\nimport {collectDocumentText, guessDocumentTitle} from '../lib/jsonLdContent'\nimport {generateJsonLd} from '../lib/aiJsonLd'\n\ntype Rec = Record<string, unknown>\nconst isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)\n\nexport type JsonLdMode = 'auto' | 'manuel'\n\nexport interface JsonLdValue {\n mode?: JsonLdMode\n data?: string\n}\n\n/** Vrai si `data` est un JSON valide (ou vide). */\nfunction jsonError(data: string | undefined): string | null {\n if (!data || !data.trim()) return null\n try {\n JSON.parse(data)\n return null\n } catch (error) {\n return error instanceof Error ? error.message : 'JSON invalide'\n }\n}\n\n/**\n * Champ « Données structurées (JSON-LD) » avec deux modes :\n *\n * - **Auto** (défaut) : l'IA régénère le JSON-LD à chaque publication, à partir\n * du contenu de la page. Lecture seule ici (une saisie serait écrasée).\n * - **Manuel** : le bouton « Rédiger avec l'IA » propose un JSON-LD une fois,\n * puis plus rien ne le modifie ; on l'édite librement.\n *\n * Le bouton de (re)génération est présent dans les deux modes.\n */\nexport function JsonLdInput(props: ObjectInputProps): React.JSX.Element {\n const {onChange, readOnly} = props\n const value = (props.value ?? {}) as JsonLdValue\n const mode: JsonLdMode = value.mode === 'manuel' ? 'manuel' : 'auto'\n const config = useKitConfig()\n const doc = useFormValue([]) as Rec | undefined\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n const field = config.jsonLd?.field ?? 'jsonLd'\n const invalid = jsonError(value.data)\n\n // URL publique de la page : sert d'`url`/`@id` dans le JSON-LD.\n const url = useMemo(() => {\n if (!doc) return null\n const pageType = pageTypeFor(doc._type as string, config.pageTypes)\n const slugValue = pageType?.slugField ? valueAtKey(doc, pageType.slugField) : null\n const slug = isObj(slugValue) ? (slugValue.current as string) ?? null : typeof slugValue === 'string' ? slugValue : null\n const locale = config.i18n ? ((doc[config.i18n.field] as string) ?? null) : null\n return toUrl(config.previewUrl, finalPath({slug, locale}, pageType, config, null))\n }, [doc, config])\n\n const setMode = useCallback(\n (next: JsonLdMode) => onChange([setIfMissing({}), set(next, ['mode'])]),\n [onChange],\n )\n\n const setData = useCallback(\n (next: string) => onChange(next ? [setIfMissing({}), set(next, ['data'])] : unset(['data'])),\n [onChange],\n )\n\n const generate = useCallback(async () => {\n if (!config.history || !doc) return\n setBusy(true)\n setError(null)\n try {\n if (!url) throw new Error(\"URL du site introuvable : renseigne l'URL de prévisualisation et le slug.\")\n const content = collectDocumentText(doc, [field])\n if (!content.trim()) throw new Error('Aucun contenu à décrire sur cette page.')\n const result = await generateJsonLd(config.history, {\n url,\n locale: config.i18n ? ((doc[config.i18n.field] as string) ?? undefined) : undefined,\n type: doc._type as string,\n title: guessDocumentTitle(doc),\n content,\n })\n onChange([setIfMissing({}), set(JSON.stringify(result, null, 2), ['data'])])\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Génération échouée.')\n } finally {\n setBusy(false)\n }\n }, [config, doc, url, field, onChange])\n\n const hasData = Boolean(value.data && value.data.trim())\n const aiAvailable = Boolean(config.history) && !readOnly\n const buttonText = busy\n ? 'Génération…'\n : mode === 'manuel'\n ? hasData\n ? 'Régénérer la proposition'\n : 'Rédiger avec l’IA'\n : 'Régénérer maintenant'\n\n return (\n <Stack gap={3}>\n {/* Mode */}\n <Flex gap={2}>\n <Button\n mode={mode === 'auto' ? 'default' : 'ghost'}\n tone={mode === 'auto' ? 'primary' : 'default'}\n text=\"Auto\"\n disabled={readOnly}\n onClick={() => setMode('auto')}\n />\n <Button\n mode={mode === 'manuel' ? 'default' : 'ghost'}\n tone={mode === 'manuel' ? 'primary' : 'default'}\n text=\"Manuel\"\n disabled={readOnly}\n onClick={() => setMode('manuel')}\n />\n <Box flex={1} />\n {aiAvailable ? (\n <Button text={buttonText} tone=\"primary\" disabled={busy} onClick={() => void generate()} />\n ) : null}\n </Flex>\n\n <Text size={1} muted>\n {mode === 'auto'\n ? 'Auto : le JSON-LD est régénéré par l’IA à chaque publication, d’après le contenu de la page. Lecture seule.'\n : 'Manuel : à toi de gérer ce JSON-LD. « Rédiger avec l’IA » propose une base ; ensuite, la publication n’y touche plus.'}\n </Text>\n\n {error ? (\n <Card tone=\"critical\" padding={3} radius={2} border>\n <Text size={1}>{error}</Text>\n </Card>\n ) : null}\n\n {!config.history ? (\n <Card tone=\"caution\" padding={3} radius={2} border>\n <Text size={1}>\n Génération IA indisponible : la clé de projet du kit (SANITY_STUDIO_NCF_PROJECT_KEY) n’est pas configurée.\n </Text>\n </Card>\n ) : null}\n\n {/* Données */}\n {mode === 'manuel' ? (\n <TextArea\n value={value.data ?? ''}\n readOnly={readOnly}\n rows={12}\n placeholder=\"{ "@context": "https://schema.org", "@type": "WebPage" }\"\n onChange={(event) => setData(event.currentTarget.value)}\n style={{fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 12}}\n />\n ) : hasData ? (\n <Card tone=\"transparent\" padding={3} radius={2} border>\n <Box overflow=\"auto\" style={{maxHeight: 320}}>\n <Text size={1} as=\"pre\" style={{fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', whiteSpace: 'pre-wrap'}}>\n {value.data}\n </Text>\n </Box>\n </Card>\n ) : (\n <Card tone=\"transparent\" padding={3} radius={2} border>\n <Text size={1} muted>\n Aucun JSON-LD pour l’instant : il sera généré à la prochaine publication (ou tout de suite avec le bouton).\n </Text>\n </Card>\n )}\n\n {hasData ? (\n <Flex>\n {invalid ? (\n <Badge tone=\"critical\" title={invalid}>\n JSON invalide\n </Badge>\n ) : (\n <Badge tone=\"positive\">JSON valide</Badge>\n )}\n </Flex>\n ) : null}\n </Stack>\n )\n}\n","import {defineField, defineType, type ObjectDefinition} from 'sanity'\nimport {JsonLdInput} from './JsonLdInput'\n\nexport interface JsonLdTypeOptions {\n /** Nom du type (défaut `jsonLd`). */\n name?: string\n /** Titre affiché. */\n title?: string\n}\n\n/**\n * Type d'objet « Données structurées (JSON-LD) » à poser sur les pages.\n *\n * Deux champs : `mode` (auto / manuel) et `data` (le JSON-LD stocké). En mode\n * auto, le JSON-LD est régénéré par l'IA à chaque publication (voir\n * `withJsonLd`) ; en mode manuel, il n'est jamais touché automatiquement.\n * L'édition et la (re)génération passent par {@link JsonLdInput}.\n *\n * ```ts\n * import {defineJsonLdType} from '@nocode-factory/sanity-kit/jsonld'\n * export const jsonLd = defineJsonLdType()\n * ```\n */\nexport function defineJsonLdType(options: JsonLdTypeOptions = {}): ObjectDefinition {\n const {name = 'jsonLd', title = 'Données structurées (JSON-LD)'} = options\n\n return defineType({\n name,\n title,\n type: 'object',\n components: {input: JsonLdInput},\n fields: [\n defineField({\n name: 'mode',\n title: 'Mode',\n type: 'string',\n options: {\n list: [\n {title: 'Auto (IA, régénéré à la publication)', value: 'auto'},\n {title: 'Manuel', value: 'manuel'},\n ],\n layout: 'radio',\n },\n initialValue: 'auto',\n }),\n defineField({\n name: 'data',\n title: 'JSON-LD',\n type: 'text',\n rows: 12,\n }),\n ],\n preview: {\n select: {mode: 'mode', data: 'data'},\n prepare({mode, data}) {\n const m = mode === 'manuel' ? 'Manuel' : 'Auto'\n return {title: 'Données structurées (JSON-LD)', subtitle: data ? `${m} · défini` : `${m} · vide`}\n },\n },\n }) as ObjectDefinition\n}\n"],"mappings":";;;;;;AAYA,MAAM,SAAS,MAAyB,OAAO,KAAM,cAAY,KAAc,CAAC,MAAM,QAAQ,CAAC;;AAU/F,SAAS,UAAU,MAAyC;CAC1D,IAAI,CAAC,QAAQ,CAAC,KAAK,KAAK,GAAG,OAAO;CAClC,IAAI;EAEF,OADA,KAAK,MAAM,IAAI,GACR;CACT,SAAS,OAAO;EACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU;CAClD;AACF;;;;;;;;;;;AAYA,SAAgB,YAAY,OAA4C;CACtE,IAAM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O,YAAW;EAC/B,QAAQ,CACN,YAAY;GACV,MAAM;GACN,OAAO;GACP,MAAM;GACN,SAAS;IACP,MAAM,CACJ;KAAC,OAAO;KAAwC,OAAO;IAAM,GAC7D;KAAC,OAAO;KAAU,OAAO;IAAQ,CACnC;IACA,QAAQ;GACV;GACA,cAAc;EAChB,CAAC,GACD,YAAY;GACV,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACR,CAAC,CACH;EACA,SAAS;GACP,QAAQ;IAAC,MAAM;IAAQ,MAAM;GAAM;GACnC,QAAQ,EAAC,MAAM,QAAO;IACpB,IAAM,IAAI,SAAS,WAAW,WAAW;IACzC,OAAO;KAAC,OAAO;KAAiC,UAAU,OAAO,GAAG,EAAE,aAAa,GAAG,EAAE;IAAQ;GAClG;EACF;CACF,CAAC;AACH"}
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as componentDefaultsMainDocuments, d as requiredUnlessDefault, f as requiredUnlessDefaultFor, i as SiteRoutesRegistry, l as defaultsFieldName, n as fixCrossLanguageReferences, o as DEFAULT_COMPONENT_DEFAULTS_TYPE, r as withSameLanguageReferences, s as componentDefaultsMainDocument, t as CrossLanguageReport, u as defineComponentDefaults } from "./fixCrossLanguageReferences-
|
|
1
|
+
import { c as componentDefaultsMainDocuments, d as requiredUnlessDefault, f as requiredUnlessDefaultFor, i as SiteRoutesRegistry, l as defaultsFieldName, n as fixCrossLanguageReferences, o as DEFAULT_COMPONENT_DEFAULTS_TYPE, r as withSameLanguageReferences, s as componentDefaultsMainDocument, t as CrossLanguageReport, u as defineComponentDefaults } from "./fixCrossLanguageReferences-CjL_Xy0U.js";
|
|
2
2
|
import { ComponentType } from "react";
|
|
3
3
|
import { SanityClient } from "sanity";
|
|
4
4
|
import { ListItemBuilder, StructureBuilder } from "sanity/structure";
|
|
@@ -10,7 +10,7 @@ import { ListItemBuilder, StructureBuilder } from "sanity/structure";
|
|
|
10
10
|
* document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.
|
|
11
11
|
* - Sections : le champ du page builder (`pageBuilderField`, défaut `sections`,
|
|
12
12
|
* comme l'option du même nom de ncfKit).
|
|
13
|
-
* - SEO : `seo`, `structuredData` et les champs de métadonnées connus.
|
|
13
|
+
* - SEO : `seo`, `structuredData`, `jsonLd` et les champs de métadonnées connus.
|
|
14
14
|
* - Settings : réglages de page (`pageOptions`, `options`, `settings`...).
|
|
15
15
|
* - Content : tout le reste (titre, slug, corps, image...).
|
|
16
16
|
* Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son
|
package/dist/schema.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as DEFAULT_PAGE_BUILDER_FIELD, i as redirectMapOf, l as toPath, n as followRedirects, r as redirectKey } from "./finalUrl-C1kzYMzQ.js";
|
|
2
|
+
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, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-BZk9CkdI.js";
|
|
2
3
|
/**
|
|
3
4
|
* Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
|
|
4
5
|
*
|
|
@@ -7,7 +8,7 @@ import { A as DEFAULT_PAGE_BUILDER_FIELD, S as toPath, _ as redirectMapOf, a as
|
|
|
7
8
|
* document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.
|
|
8
9
|
* - Sections : le champ du page builder (`pageBuilderField`, défaut `sections`,
|
|
9
10
|
* comme l'option du même nom de ncfKit).
|
|
10
|
-
* - SEO : `seo`, `structuredData` et les champs de métadonnées connus.
|
|
11
|
+
* - SEO : `seo`, `structuredData`, `jsonLd` et les champs de métadonnées connus.
|
|
11
12
|
* - Settings : réglages de page (`pageOptions`, `options`, `settings`...).
|
|
12
13
|
* - Content : tout le reste (titre, slug, corps, image...).
|
|
13
14
|
* Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son
|
|
@@ -21,6 +22,7 @@ const SEO_FIELDS = /* @__PURE__ */ new Set([
|
|
|
21
22
|
"seo",
|
|
22
23
|
"structuredData",
|
|
23
24
|
"jsonld",
|
|
25
|
+
"jsonLd",
|
|
24
26
|
"noindex",
|
|
25
27
|
"metaTitle",
|
|
26
28
|
"metaDescription",
|
package/dist/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","names":[],"sources":["../src/schema/formTabs.ts","../src/schema/redirects.ts"],"sourcesContent":["/**\n * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.\n *\n * Un formulaire de page en une seule colonne mélange le contenu, le page builder et\n * les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un\n * document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.\n * - Sections : le champ du page builder (`pageBuilderField`, défaut `sections`,\n * comme l'option du même nom de ncfKit).\n * - SEO : `seo`, `structuredData` et les champs de métadonnées connus.\n * - Settings : réglages de page (`pageOptions`, `options`, `settings`...).\n * - Content : tout le reste (titre, slug, corps, image...).\n * Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son\n * `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.\n *\n * ```ts\n * schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}\n * ```\n */\n\nimport {DEFAULT_PAGE_BUILDER_FIELD} from '../config/defaults'\n\nconst SEO_FIELDS = new Set(['seo', 'structuredData', 'jsonld', 'noindex', 'metaTitle', 'metaDescription', 'ogImage', 'canonical', 'canonicalUrl'])\nconst SETTINGS_FIELDS = new Set(['pageOptions', 'options', 'settings', 'hideFromMenu', 'showInMenu', 'parent', 'publishedAt', 'redirects'])\n\nconst GROUPS = [\n {name: 'content', title: 'Content', default: true},\n {name: 'sections', title: 'Sections'},\n {name: 'seo', title: 'SEO'},\n {name: 'settings', title: 'Settings'},\n] as const\n\ntype Field = {name?: string; group?: unknown; hidden?: unknown}\ntype TypeLike = {type?: string; groups?: unknown; fields?: Field[]}\n\n/** Onglet d'un champ d'après son nom. */\nexport function formTabOf(name: string, pageBuilderField = DEFAULT_PAGE_BUILDER_FIELD): (typeof GROUPS)[number]['name'] {\n if (name === pageBuilderField) return 'sections'\n if (SEO_FIELDS.has(name)) return 'seo'\n if (SETTINGS_FIELDS.has(name)) return 'settings'\n return 'content'\n}\n\nexport function withNcfFormTabs<T>(types: readonly T[], options: {pageBuilderField?: string} = {}): T[] {\n return types.map((input) => {\n const type = input as unknown as TypeLike\n if (type.type !== 'document' || type.groups || !Array.isArray(type.fields)) return input\n // Champ toujours caché (hidden: true) : pas d'onglet (il n'en ferait naître un vide).\n const fields = type.fields.map((field) =>\n field.group || !field.name || field.hidden === true ? field : {...field, group: formTabOf(field.name, options.pageBuilderField)},\n )\n const used = new Set(fields.map((f) => f.group).flat())\n const groups = GROUPS.filter((g) => used.has(g.name)).map((g) => ({...g}))\n if (groups.length < 2) return input\n if (!groups.some((g) => 'default' in g && g.default)) (groups[0] as {default?: boolean}).default = true\n return {...type, groups, fields} as unknown as T\n })\n}\n","import type {ComponentType} from 'react'\nimport type {SanityClient} from 'sanity'\nimport type {StructureBuilder, ListItemBuilder} from 'sanity/structure'\nimport {redirectKey, redirectMapOf, followRedirects} from '../lib/finalUrl'\nimport {toPath} from '../lib/paths'\nimport {pageTypesFromSiteRoutes, type SiteRoutesRegistry} from '../lib/siteRoutes'\n\n/**\n * RÈGLES DES REDIRECTIONS (embarquées par le kit, mêmes dans tous les projets) :\n *\n * 1. Trois familles, rangées chacune dans son sous-dossier du Studio (« Redirects ») :\n * - manuelles : saisies par l'équipe ;\n * - changements de slug : créées à la publication d'un nouveau slug\n * (identifiant `redirect-auto-…`) ;\n * - langues : adresse « slug d'origine » d'une version traduite vers son slug\n * traduit (identifiant `redirect-translation-…`, syncTranslationRedirects).\n * La famille vient de l'identifiant : rien à migrer, rien à saisir.\n *\n * 2. Une redirection EN CONFLIT ne peut pas être publiée (validation, erreur) :\n * - même adresse de départ qu'une autre redirection ;\n * - départ = adresse d'une page en ligne (elle deviendrait inaccessible) ;\n * - destination = départ d'une autre redirection (chaîne : viser l'adresse finale) ;\n * - boucle (la destination ramène au départ) ;\n * - destination identique au départ.\n */\n\nexport type RedirectKind = 'manual' | 'slug' | 'translation'\n\nexport const TRANSLATION_REDIRECT_PREFIX = 'redirect-translation-'\nexport const SLUG_REDIRECT_PREFIX = 'redirect-auto-'\n\n/** Famille d'une redirection, d'après son identifiant (brouillon compris). */\nexport function redirectKindOf(id: string | null | undefined): RedirectKind {\n const clean = (id ?? '').replace(/^drafts\\./, '')\n if (clean.startsWith(TRANSLATION_REDIRECT_PREFIX)) return 'translation'\n if (clean.startsWith(SLUG_REDIRECT_PREFIX)) return 'slug'\n return 'manual'\n}\n\nconst idIn = (prefix: string) => `(_id in path(\"${prefix}*\") || _id in path(\"drafts.${prefix}*\"))`\n\n/** Filtre GROQ de chaque famille (à combiner avec `_type == $type`). */\nexport const REDIRECT_KIND_FILTERS: Record<RedirectKind, string> = {\n translation: idIn(TRANSLATION_REDIRECT_PREFIX),\n slug: idIn(SLUG_REDIRECT_PREFIX),\n manual: `!${idIn(TRANSLATION_REDIRECT_PREFIX)} && !${idIn(SLUG_REDIRECT_PREFIX)}`,\n}\n\nexport interface RedirectsStructureOptions {\n /** Type des redirections. Défaut : `redirect`. */\n redirectType?: string\n /** Titre de l'entrée. Défaut : « Redirects ». */\n title?: string\n /** Icône de l'entrée (celle du projet). */\n icon?: ComponentType\n /** Libellés des sous-dossiers (langue du Studio du projet). Défaut : anglais. */\n labels?: Partial<Record<RedirectKind | 'all', string>>\n}\n\nconst DEFAULT_LABELS: Record<RedirectKind | 'all', string> = {\n manual: 'Manual',\n slug: 'Slug changes (automatic)',\n translation: 'Languages (automatic)',\n all: 'All redirects',\n}\n\n/**\n * Entrée « Redirects » du Studio, rangée en sous-dossiers : manuelles (création\n * possible), changements de slug et langues (automatiques), puis toutes.\n * S.list().items([..., redirectsStructure(S, {icon: MyIcon})])\n */\nexport function redirectsStructure(S: StructureBuilder, options: RedirectsStructureOptions = {}): ListItemBuilder {\n const type = options.redirectType ?? 'redirect'\n const title = options.title ?? 'Redirects'\n const labels = {...DEFAULT_LABELS, ...options.labels}\n const list = (kind: RedirectKind, label: string) =>\n S.listItem()\n .id(`redirects-${kind}`)\n .title(label)\n .schemaType(type)\n .child(\n S.documentList()\n .id(`redirects-${kind}-list`)\n .title(label)\n .schemaType(type)\n .apiVersion('2024-10-01')\n .filter(`_type == $type && ${REDIRECT_KIND_FILTERS[kind]}`)\n .params({type})\n .defaultOrdering([{field: 'from', direction: 'asc'}])\n // Création seulement dans les manuelles : les autres sont automatiques.\n .initialValueTemplates(kind === 'manual' ? [S.initialValueTemplateItem(type)] : []),\n )\n const item = S.listItem()\n .id('redirects')\n .title(title)\n .child(\n S.list()\n .id('redirects')\n .title(title)\n .items([\n list('manual', labels.manual),\n list('slug', labels.slug),\n list('translation', labels.translation),\n S.divider(),\n S.listItem().id('redirects-all').title(labels.all).schemaType(type).child(S.documentTypeList(type).title(labels.all)),\n ]),\n )\n return options.icon ? item.icon(options.icon) : item\n}\n\nexport interface RedirectConflictOptions {\n /** Type des redirections. Défaut : `redirect`. */\n redirectType?: string\n /** Registre des pages du site (site-routes.json) : adresses des pages en ligne. */\n siteRoutes?: SiteRoutesRegistry | null\n /** Langues : langue principale (sans préfixe) et champ de langue. */\n i18n?: {defaultLocale: string; field?: string} | null\n /** Champ slug des pages. Défaut : `slug`. */\n slugField?: string\n}\n\ntype Ctx = {document?: {_id?: string; from?: unknown; to?: unknown} | null; getClient: (o: {apiVersion: string}) => SanityClient}\ntype Row = {_id: string; from?: string | null; to?: string | null}\n\nconst clean = (v: unknown) => (typeof v === 'string' ? v.trim() : '')\n\nasync function otherRedirects(ctx: Ctx, type: string): Promise<Row[]> {\n const id = (ctx.document?._id ?? '').replace(/^drafts\\./, '')\n // Publiées et brouillons des AUTRES redirections (le brouillon d'une publiée la remplace).\n const rows = await ctx\n .getClient({apiVersion: '2024-10-01'})\n .withConfig({perspective: 'raw'})\n .fetch<Row[]>(`*[_type == $type && !(_id in [$id, $draft])]{_id, from, to}`, {type, id, draft: `drafts.${id}`})\n const byBase = new Map<string, Row>()\n for (const r of rows) {\n const base = r._id.replace(/^drafts\\./, '')\n if (!byBase.has(base) || r._id.startsWith('drafts.')) byBase.set(base, r)\n }\n return [...byBase.values()]\n}\n\nconst label = (r: Row) => `${clean(r.from)} → ${clean(r.to)}`\n\n/**\n * Validations anti-conflit des champs `from` et `to` d'une redirection (erreurs :\n * la publication est bloquée, avec la raison et la redirection en cause).\n * const conflicts = redirectConflicts({siteRoutes: routes, i18n: {defaultLocale}})\n * defineField({name: 'from', validation: (r) => r.required().custom(conflicts.from)})\n * defineField({name: 'to', validation: (r) => r.required().custom(conflicts.to)})\n */\nexport function redirectConflicts(options: RedirectConflictOptions = {}) {\n const type = options.redirectType ?? 'redirect'\n const field = options.i18n?.field ?? 'language'\n const slugField = options.slugField ?? 'slug'\n const pageTypes = options.siteRoutes ? pageTypesFromSiteRoutes(options.siteRoutes).filter((t) => !t.path) : []\n const i18n = options.i18n ? {field, defaultLocale: options.i18n.defaultLocale, locales: [], defaultsSourceLocale: options.i18n.defaultLocale} : null\n\n // Page en ligne à cette adresse (publiée, dossier et slug de sa langue) ?\n async function pageAt(ctx: Ctx, path: string): Promise<string | null> {\n if (!pageTypes.length) return null\n const key = redirectKey(path)\n const docs = await ctx\n .getClient({apiVersion: '2024-10-01'})\n .withConfig({perspective: 'published'})\n .fetch<{_type: string; title?: string; slug?: string; lang?: string}[]>(\n `*[_type in $types && defined(${slugField}.current)]{_type, title, \"slug\": ${slugField}.current, \"lang\": ${field}}`,\n {types: pageTypes.map((t) => t.type)},\n )\n for (const d of docs) {\n const t = pageTypes.find((p) => p.type === d._type)\n const p = t && toPath({slug: d.slug, pathPrefix: t.pathPrefix, localizedPrefixes: t.localizedPrefixes, locale: d.lang}, i18n)\n if (p && redirectKey(p) === key) return d.title || p\n }\n return null\n }\n\n return {\n async from(value: unknown, context: unknown): Promise<true | string> {\n const ctx = context as Ctx\n const from = clean(value)\n if (!from.startsWith('/')) return true\n const others = await otherRedirects(ctx, type)\n const same = others.find((r) => r.from && redirectKey(r.from) === redirectKey(from))\n if (same) return `Conflict: another redirect already starts from this address (${label(same)}). Edit that one instead.`\n const page = await pageAt(ctx, from)\n if (page) return `Conflict: \"${from}\" is the address of a live page (\"${page}\"). Redirecting it would make that page unreachable.`\n return true\n },\n async to(value: unknown, context: unknown): Promise<true | string> {\n const ctx = context as Ctx\n const to = clean(value)\n const from = clean(ctx.document?.from)\n if (!to.startsWith('/')) return true\n if (from && redirectKey(from) === redirectKey(to)) return 'Conflict: the new address is the same as the old one.'\n const others = await otherRedirects(ctx, type)\n const chained = others.find((r) => r.from && redirectKey(r.from) === redirectKey(to))\n if (chained) {\n const final = followRedirects(to, redirectMapOf(others))\n if (from && redirectKey(final) === redirectKey(from)) return `Conflict: loop. \"${to}\" already redirects back to \"${from}\" (${label(chained)}).`\n return `Conflict: \"${to}\" is itself redirected (${label(chained)}). Point directly to the final address: ${final}`\n }\n return true\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAO;CAAkB;CAAU;CAAW;CAAa;CAAmB;CAAW;CAAa;AAAc,CAAC,GAC3I,kCAAkB,IAAI,IAAI;CAAC;CAAe;CAAW;CAAY;CAAgB;CAAc;CAAU;CAAe;AAAW,CAAC,GAEpI,SAAS;CACb;EAAC,MAAM;EAAW,OAAO;EAAW,SAAS;CAAI;CACjD;EAAC,MAAM;EAAY,OAAO;CAAU;CACpC;EAAC,MAAM;EAAO,OAAO;CAAK;CAC1B;EAAC,MAAM;EAA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IACX,IAAM,QAAQ,gBAAgB,IAAI,cAAc,MAAM,CAAC;IAEvD,OADI,QAAQ,YAAY,KAAK,MAAM,YAAY,IAAI,IAAU,oBAAoB,GAAG,+BAA+B,KAAK,KAAK,MAAM,OAAO,EAAE,MACrI,cAAc,GAAG,0BAA0B,MAAM,OAAO,EAAE,0CAA0C;GAC7G;GACA,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../src/schema/formTabs.ts","../src/schema/redirects.ts"],"sourcesContent":["/**\n * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.\n *\n * Un formulaire de page en une seule colonne mélange le contenu, le page builder et\n * les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un\n * document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.\n * - Sections : le champ du page builder (`pageBuilderField`, défaut `sections`,\n * comme l'option du même nom de ncfKit).\n * - SEO : `seo`, `structuredData`, `jsonLd` et les champs de métadonnées connus.\n * - Settings : réglages de page (`pageOptions`, `options`, `settings`...).\n * - Content : tout le reste (titre, slug, corps, image...).\n * Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son\n * `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.\n *\n * ```ts\n * schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}\n * ```\n */\n\nimport {DEFAULT_PAGE_BUILDER_FIELD} from '../config/defaults'\n\n// `jsonLd` : champ « Données structurées » du kit (defineJsonLdType), avec ses modes\n// auto / manuel et le bouton IA : toujours dans l'onglet SEO.\nconst SEO_FIELDS = new Set(['seo', 'structuredData', 'jsonld', 'jsonLd', 'noindex', 'metaTitle', 'metaDescription', 'ogImage', 'canonical', 'canonicalUrl'])\nconst SETTINGS_FIELDS = new Set(['pageOptions', 'options', 'settings', 'hideFromMenu', 'showInMenu', 'parent', 'publishedAt', 'redirects'])\n\nconst GROUPS = [\n {name: 'content', title: 'Content', default: true},\n {name: 'sections', title: 'Sections'},\n {name: 'seo', title: 'SEO'},\n {name: 'settings', title: 'Settings'},\n] as const\n\ntype Field = {name?: string; group?: unknown; hidden?: unknown}\ntype TypeLike = {type?: string; groups?: unknown; fields?: Field[]}\n\n/** Onglet d'un champ d'après son nom. */\nexport function formTabOf(name: string, pageBuilderField = DEFAULT_PAGE_BUILDER_FIELD): (typeof GROUPS)[number]['name'] {\n if (name === pageBuilderField) return 'sections'\n if (SEO_FIELDS.has(name)) return 'seo'\n if (SETTINGS_FIELDS.has(name)) return 'settings'\n return 'content'\n}\n\nexport function withNcfFormTabs<T>(types: readonly T[], options: {pageBuilderField?: string} = {}): T[] {\n return types.map((input) => {\n const type = input as unknown as TypeLike\n if (type.type !== 'document' || type.groups || !Array.isArray(type.fields)) return input\n // Champ toujours caché (hidden: true) : pas d'onglet (il n'en ferait naître un vide).\n const fields = type.fields.map((field) =>\n field.group || !field.name || field.hidden === true ? field : {...field, group: formTabOf(field.name, options.pageBuilderField)},\n )\n const used = new Set(fields.map((f) => f.group).flat())\n const groups = GROUPS.filter((g) => used.has(g.name)).map((g) => ({...g}))\n if (groups.length < 2) return input\n if (!groups.some((g) => 'default' in g && g.default)) (groups[0] as {default?: boolean}).default = true\n return {...type, groups, fields} as unknown as T\n })\n}\n","import type {ComponentType} from 'react'\nimport type {SanityClient} from 'sanity'\nimport type {StructureBuilder, ListItemBuilder} from 'sanity/structure'\nimport {redirectKey, redirectMapOf, followRedirects} from '../lib/finalUrl'\nimport {toPath} from '../lib/paths'\nimport {pageTypesFromSiteRoutes, type SiteRoutesRegistry} from '../lib/siteRoutes'\n\n/**\n * RÈGLES DES REDIRECTIONS (embarquées par le kit, mêmes dans tous les projets) :\n *\n * 1. Trois familles, rangées chacune dans son sous-dossier du Studio (« Redirects ») :\n * - manuelles : saisies par l'équipe ;\n * - changements de slug : créées à la publication d'un nouveau slug\n * (identifiant `redirect-auto-…`) ;\n * - langues : adresse « slug d'origine » d'une version traduite vers son slug\n * traduit (identifiant `redirect-translation-…`, syncTranslationRedirects).\n * La famille vient de l'identifiant : rien à migrer, rien à saisir.\n *\n * 2. Une redirection EN CONFLIT ne peut pas être publiée (validation, erreur) :\n * - même adresse de départ qu'une autre redirection ;\n * - départ = adresse d'une page en ligne (elle deviendrait inaccessible) ;\n * - destination = départ d'une autre redirection (chaîne : viser l'adresse finale) ;\n * - boucle (la destination ramène au départ) ;\n * - destination identique au départ.\n */\n\nexport type RedirectKind = 'manual' | 'slug' | 'translation'\n\nexport const TRANSLATION_REDIRECT_PREFIX = 'redirect-translation-'\nexport const SLUG_REDIRECT_PREFIX = 'redirect-auto-'\n\n/** Famille d'une redirection, d'après son identifiant (brouillon compris). */\nexport function redirectKindOf(id: string | null | undefined): RedirectKind {\n const clean = (id ?? '').replace(/^drafts\\./, '')\n if (clean.startsWith(TRANSLATION_REDIRECT_PREFIX)) return 'translation'\n if (clean.startsWith(SLUG_REDIRECT_PREFIX)) return 'slug'\n return 'manual'\n}\n\nconst idIn = (prefix: string) => `(_id in path(\"${prefix}*\") || _id in path(\"drafts.${prefix}*\"))`\n\n/** Filtre GROQ de chaque famille (à combiner avec `_type == $type`). */\nexport const REDIRECT_KIND_FILTERS: Record<RedirectKind, string> = {\n translation: idIn(TRANSLATION_REDIRECT_PREFIX),\n slug: idIn(SLUG_REDIRECT_PREFIX),\n manual: `!${idIn(TRANSLATION_REDIRECT_PREFIX)} && !${idIn(SLUG_REDIRECT_PREFIX)}`,\n}\n\nexport interface RedirectsStructureOptions {\n /** Type des redirections. Défaut : `redirect`. */\n redirectType?: string\n /** Titre de l'entrée. Défaut : « Redirects ». */\n title?: string\n /** Icône de l'entrée (celle du projet). */\n icon?: ComponentType\n /** Libellés des sous-dossiers (langue du Studio du projet). Défaut : anglais. */\n labels?: Partial<Record<RedirectKind | 'all', string>>\n}\n\nconst DEFAULT_LABELS: Record<RedirectKind | 'all', string> = {\n manual: 'Manual',\n slug: 'Slug changes (automatic)',\n translation: 'Languages (automatic)',\n all: 'All redirects',\n}\n\n/**\n * Entrée « Redirects » du Studio, rangée en sous-dossiers : manuelles (création\n * possible), changements de slug et langues (automatiques), puis toutes.\n * S.list().items([..., redirectsStructure(S, {icon: MyIcon})])\n */\nexport function redirectsStructure(S: StructureBuilder, options: RedirectsStructureOptions = {}): ListItemBuilder {\n const type = options.redirectType ?? 'redirect'\n const title = options.title ?? 'Redirects'\n const labels = {...DEFAULT_LABELS, ...options.labels}\n const list = (kind: RedirectKind, label: string) =>\n S.listItem()\n .id(`redirects-${kind}`)\n .title(label)\n .schemaType(type)\n .child(\n S.documentList()\n .id(`redirects-${kind}-list`)\n .title(label)\n .schemaType(type)\n .apiVersion('2024-10-01')\n .filter(`_type == $type && ${REDIRECT_KIND_FILTERS[kind]}`)\n .params({type})\n .defaultOrdering([{field: 'from', direction: 'asc'}])\n // Création seulement dans les manuelles : les autres sont automatiques.\n .initialValueTemplates(kind === 'manual' ? [S.initialValueTemplateItem(type)] : []),\n )\n const item = S.listItem()\n .id('redirects')\n .title(title)\n .child(\n S.list()\n .id('redirects')\n .title(title)\n .items([\n list('manual', labels.manual),\n list('slug', labels.slug),\n list('translation', labels.translation),\n S.divider(),\n S.listItem().id('redirects-all').title(labels.all).schemaType(type).child(S.documentTypeList(type).title(labels.all)),\n ]),\n )\n return options.icon ? item.icon(options.icon) : item\n}\n\nexport interface RedirectConflictOptions {\n /** Type des redirections. Défaut : `redirect`. */\n redirectType?: string\n /** Registre des pages du site (site-routes.json) : adresses des pages en ligne. */\n siteRoutes?: SiteRoutesRegistry | null\n /** Langues : langue principale (sans préfixe) et champ de langue. */\n i18n?: {defaultLocale: string; field?: string} | null\n /** Champ slug des pages. Défaut : `slug`. */\n slugField?: string\n}\n\ntype Ctx = {document?: {_id?: string; from?: unknown; to?: unknown} | null; getClient: (o: {apiVersion: string}) => SanityClient}\ntype Row = {_id: string; from?: string | null; to?: string | null}\n\nconst clean = (v: unknown) => (typeof v === 'string' ? v.trim() : '')\n\nasync function otherRedirects(ctx: Ctx, type: string): Promise<Row[]> {\n const id = (ctx.document?._id ?? '').replace(/^drafts\\./, '')\n // Publiées et brouillons des AUTRES redirections (le brouillon d'une publiée la remplace).\n const rows = await ctx\n .getClient({apiVersion: '2024-10-01'})\n .withConfig({perspective: 'raw'})\n .fetch<Row[]>(`*[_type == $type && !(_id in [$id, $draft])]{_id, from, to}`, {type, id, draft: `drafts.${id}`})\n const byBase = new Map<string, Row>()\n for (const r of rows) {\n const base = r._id.replace(/^drafts\\./, '')\n if (!byBase.has(base) || r._id.startsWith('drafts.')) byBase.set(base, r)\n }\n return [...byBase.values()]\n}\n\nconst label = (r: Row) => `${clean(r.from)} → ${clean(r.to)}`\n\n/**\n * Validations anti-conflit des champs `from` et `to` d'une redirection (erreurs :\n * la publication est bloquée, avec la raison et la redirection en cause).\n * const conflicts = redirectConflicts({siteRoutes: routes, i18n: {defaultLocale}})\n * defineField({name: 'from', validation: (r) => r.required().custom(conflicts.from)})\n * defineField({name: 'to', validation: (r) => r.required().custom(conflicts.to)})\n */\nexport function redirectConflicts(options: RedirectConflictOptions = {}) {\n const type = options.redirectType ?? 'redirect'\n const field = options.i18n?.field ?? 'language'\n const slugField = options.slugField ?? 'slug'\n const pageTypes = options.siteRoutes ? pageTypesFromSiteRoutes(options.siteRoutes).filter((t) => !t.path) : []\n const i18n = options.i18n ? {field, defaultLocale: options.i18n.defaultLocale, locales: [], defaultsSourceLocale: options.i18n.defaultLocale} : null\n\n // Page en ligne à cette adresse (publiée, dossier et slug de sa langue) ?\n async function pageAt(ctx: Ctx, path: string): Promise<string | null> {\n if (!pageTypes.length) return null\n const key = redirectKey(path)\n const docs = await ctx\n .getClient({apiVersion: '2024-10-01'})\n .withConfig({perspective: 'published'})\n .fetch<{_type: string; title?: string; slug?: string; lang?: string}[]>(\n `*[_type in $types && defined(${slugField}.current)]{_type, title, \"slug\": ${slugField}.current, \"lang\": ${field}}`,\n {types: pageTypes.map((t) => t.type)},\n )\n for (const d of docs) {\n const t = pageTypes.find((p) => p.type === d._type)\n const p = t && toPath({slug: d.slug, pathPrefix: t.pathPrefix, localizedPrefixes: t.localizedPrefixes, locale: d.lang}, i18n)\n if (p && redirectKey(p) === key) return d.title || p\n }\n return null\n }\n\n return {\n async from(value: unknown, context: unknown): Promise<true | string> {\n const ctx = context as Ctx\n const from = clean(value)\n if (!from.startsWith('/')) return true\n const others = await otherRedirects(ctx, type)\n const same = others.find((r) => r.from && redirectKey(r.from) === redirectKey(from))\n if (same) return `Conflict: another redirect already starts from this address (${label(same)}). Edit that one instead.`\n const page = await pageAt(ctx, from)\n if (page) return `Conflict: \"${from}\" is the address of a live page (\"${page}\"). Redirecting it would make that page unreachable.`\n return true\n },\n async to(value: unknown, context: unknown): Promise<true | string> {\n const ctx = context as Ctx\n const to = clean(value)\n const from = clean(ctx.document?.from)\n if (!to.startsWith('/')) return true\n if (from && redirectKey(from) === redirectKey(to)) return 'Conflict: the new address is the same as the old one.'\n const others = await otherRedirects(ctx, type)\n const chained = others.find((r) => r.from && redirectKey(r.from) === redirectKey(to))\n if (chained) {\n const final = followRedirects(to, redirectMapOf(others))\n if (from && redirectKey(final) === redirectKey(from)) return `Conflict: loop. \"${to}\" already redirects back to \"${from}\" (${label(chained)}).`\n return `Conflict: \"${to}\" is itself redirected (${label(chained)}). Point directly to the final address: ${final}`\n }\n return true\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAO;CAAkB;CAAU;CAAU;CAAW;CAAa;CAAmB;CAAW;CAAa;AAAc,CAAC,GACrJ,kCAAkB,IAAI,IAAI;CAAC;CAAe;CAAW;CAAY;CAAgB;CAAc;CAAU;CAAe;AAAW,CAAC,GAEpI,SAAS;CACb;EAAC,MAAM;EAAW,OAAO;EAAW,SAAS;CAAI;CACjD;EAAC,MAAM;EAAY,OAAO;CAAU;CACpC;EAAC,MAAM;EAAO,OAAO;CAAK;CAC1B;EAAC,MAAM;EAAY,OAAO;CAAU;AACtC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BAAgB,IAAI,cAAc,MAAM,CAAC;IAEvD,OADI,QAAQ,YAAY,KAAK,MAAM,YAAY,IAAI,IAAU,oBAAoB,GAAG,+BAA+B,KAAK,KAAK,MAAM,OAAO,EAAE,MACrI,cAAc,GAAG,0BAA0B,MAAM,OAAO,EAAE,0CAA0C;GAC7G;GACA,OAAO;EACT;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nocode-factory/sanity-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.48.1",
|
|
4
4
|
"description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
"source": "./src/code-embed.ts",
|
|
20
20
|
"default": "./dist/code-embed.js"
|
|
21
21
|
},
|
|
22
|
+
"./jsonld": {
|
|
23
|
+
"source": "./src/jsonld.ts",
|
|
24
|
+
"default": "./dist/jsonld.js"
|
|
25
|
+
},
|
|
22
26
|
"./web": {
|
|
23
27
|
"source": "./src/web/index.ts",
|
|
24
28
|
"default": "./dist/web.js"
|
|
@@ -97,7 +101,8 @@
|
|
|
97
101
|
"./web/server": "./dist/web-server.js",
|
|
98
102
|
"./web/defaults": "./dist/web-defaults.js",
|
|
99
103
|
"./schema": "./dist/schema.js",
|
|
100
|
-
"./code-embed": "./dist/code-embed.js"
|
|
104
|
+
"./code-embed": "./dist/code-embed.js",
|
|
105
|
+
"./jsonld": "./dist/jsonld.js"
|
|
101
106
|
}
|
|
102
107
|
},
|
|
103
108
|
"repository": {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import {type DocumentActionComponent, type DocumentActionProps, type SanityClient} from 'sanity'
|
|
2
|
+
import type {ResolvedKitConfig} from '../config/types'
|
|
3
|
+
import {useKitClient} from '../hooks/useKitClient'
|
|
4
|
+
import {finalPath} from '../lib/finalUrl'
|
|
5
|
+
import {toUrl, pageTypeFor} from '../lib/paths'
|
|
6
|
+
import {valueAtKey} from '../lib/aiTexts'
|
|
7
|
+
import {collectDocumentText, guessDocumentTitle} from '../lib/jsonLdContent'
|
|
8
|
+
import {generateJsonLd} from '../lib/aiJsonLd'
|
|
9
|
+
|
|
10
|
+
type Rec = Record<string, unknown>
|
|
11
|
+
const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
12
|
+
|
|
13
|
+
/** Régénère le JSON-LD de la page publiée, sauf en mode manuel. Non bloquant. */
|
|
14
|
+
async function regenerate(client: SanityClient, config: ResolvedKitConfig, id: string, published: Rec): Promise<void> {
|
|
15
|
+
if (!config.jsonLd || !config.history) return
|
|
16
|
+
const field = config.jsonLd.field
|
|
17
|
+
const current = published[field]
|
|
18
|
+
// Mode manuel : jamais d'override automatique à la publication.
|
|
19
|
+
if (isObj(current) && current.mode === 'manuel') return
|
|
20
|
+
|
|
21
|
+
const pageType = pageTypeFor(published._type as string, config.pageTypes)
|
|
22
|
+
const slugValue = pageType?.slugField ? valueAtKey(published, pageType.slugField) : null
|
|
23
|
+
const slug = isObj(slugValue) ? ((slugValue.current as string) ?? null) : typeof slugValue === 'string' ? slugValue : null
|
|
24
|
+
const locale = config.i18n ? ((published[config.i18n.field] as string) ?? null) : null
|
|
25
|
+
const url = toUrl(config.previewUrl, finalPath({slug, locale}, pageType, config, null))
|
|
26
|
+
if (!url) return
|
|
27
|
+
|
|
28
|
+
const content = collectDocumentText(published, [field])
|
|
29
|
+
if (!content.trim()) return
|
|
30
|
+
|
|
31
|
+
const result = await generateJsonLd(config.history, {
|
|
32
|
+
url,
|
|
33
|
+
locale: locale ?? undefined,
|
|
34
|
+
type: published._type as string,
|
|
35
|
+
title: guessDocumentTitle(published),
|
|
36
|
+
content,
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
const publishedId = id.replace(/^drafts\./, '')
|
|
40
|
+
await client
|
|
41
|
+
.patch(publishedId)
|
|
42
|
+
.set({[field]: {mode: 'auto', data: JSON.stringify(result, null, 2)}})
|
|
43
|
+
.commit()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Enveloppe l'action « Publier » : après la publication, en mode auto, régénère
|
|
48
|
+
* le JSON-LD de la page par IA à partir du contenu publié et l'écrit sur le
|
|
49
|
+
* document publié. Le délai réseau de l'IA laisse la publication s'achever
|
|
50
|
+
* avant l'écriture. Jamais bloquant : une erreur est seulement journalisée.
|
|
51
|
+
*/
|
|
52
|
+
export function withJsonLd(Publish: DocumentActionComponent, config: ResolvedKitConfig): DocumentActionComponent {
|
|
53
|
+
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
54
|
+
const base = Publish(props)
|
|
55
|
+
const client = useKitClient()
|
|
56
|
+
if (!base || !config.jsonLd || !config.history) return base
|
|
57
|
+
// Contenu publié = le brouillon en cours de publication (sinon le publié actuel).
|
|
58
|
+
const source = (props.draft ?? props.published) as Rec | null
|
|
59
|
+
return {
|
|
60
|
+
...base,
|
|
61
|
+
onHandle: () => {
|
|
62
|
+
base.onHandle?.()
|
|
63
|
+
if (source) void regenerate(client, config, props.id, source).catch((error) => console.error('JSON-LD auto:', error))
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
Wrapped.action = Publish.action
|
|
68
|
+
return Wrapped
|
|
69
|
+
}
|
package/src/config/resolve.ts
CHANGED
|
@@ -130,6 +130,12 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
|
|
|
130
130
|
),
|
|
131
131
|
}
|
|
132
132
|
: null,
|
|
133
|
+
// Le JSON-LD IA s'appuie sur le même service que la traduction : sans
|
|
134
|
+
// `history.projectKey`, il n'y a pas d'IA à brancher.
|
|
135
|
+
jsonLd:
|
|
136
|
+
input.jsonLd?.enabled && input.history?.projectKey?.trim()
|
|
137
|
+
? {field: input.jsonLd.field?.trim() || 'jsonLd'}
|
|
138
|
+
: null,
|
|
133
139
|
tools: {...DEFAULT_TOOLS, ...input.tools},
|
|
134
140
|
moreTools: input.moreTools === false ? [] : (input.moreTools ?? DEFAULT_TOOLBAR_MORE),
|
|
135
141
|
boardTags: input.boardTags?.length ? input.boardTags : DEFAULT_BOARD_TAGS,
|
package/src/config/types.ts
CHANGED
|
@@ -89,6 +89,21 @@ export interface NcfHistoryConfig {
|
|
|
89
89
|
endpoint?: string
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
/** Données structurées (JSON-LD) générées par IA. */
|
|
93
|
+
export interface NcfJsonLdConfig {
|
|
94
|
+
/**
|
|
95
|
+
* Active la génération par IA : bouton « Rédiger avec l'IA » sur le champ et
|
|
96
|
+
* régénération à la publication des pages en mode auto. Nécessite le service
|
|
97
|
+
* du kit (`history.projectKey`) ; sans lui, rien n'est branché.
|
|
98
|
+
*/
|
|
99
|
+
enabled?: boolean
|
|
100
|
+
/**
|
|
101
|
+
* Nom du champ objet qui porte le mode (auto/manuel) et le JSON-LD stocké.
|
|
102
|
+
* Défaut : 'jsonLd'.
|
|
103
|
+
*/
|
|
104
|
+
field?: string
|
|
105
|
+
}
|
|
106
|
+
|
|
92
107
|
/** Étiquette de suivi posable sur une page dans le board. */
|
|
93
108
|
export interface NcfBoardTag {
|
|
94
109
|
/** Identifiant stable, enregistré dans le document de disposition. */
|
|
@@ -222,6 +237,8 @@ export interface NcfKitConfig {
|
|
|
222
237
|
i18n?: NcfI18nConfig | false
|
|
223
238
|
componentPreview?: NcfComponentPreviewConfig
|
|
224
239
|
history?: NcfHistoryConfig
|
|
240
|
+
/** Données structurées (JSON-LD) générées par IA sur les pages. */
|
|
241
|
+
jsonLd?: NcfJsonLdConfig
|
|
225
242
|
/**
|
|
226
243
|
* Base des Edge Functions du kit, pour l'enregistrement et l'historique.
|
|
227
244
|
* `false` coupe tout appel sortant, y compris le signalement de présence.
|
|
@@ -297,6 +314,8 @@ export interface ResolvedKitConfig {
|
|
|
297
314
|
i18n: ResolvedI18n | null
|
|
298
315
|
componentPreview: ResolvedComponentPreview
|
|
299
316
|
history: ResolvedHistory | null
|
|
317
|
+
/** `null` quand le JSON-LD IA est désactivé ou que le service du kit manque. */
|
|
318
|
+
jsonLd: ResolvedJsonLd | null
|
|
300
319
|
/** `null` quand on a explicitement coupé les appels sortants. */
|
|
301
320
|
serviceEndpoint: string | null
|
|
302
321
|
tools: Required<NcfToolsConfig>
|
|
@@ -312,6 +331,11 @@ export interface ResolvedHistory {
|
|
|
312
331
|
endpoint: string
|
|
313
332
|
}
|
|
314
333
|
|
|
334
|
+
export interface ResolvedJsonLd {
|
|
335
|
+
/** Nom du champ objet qui porte le mode et le JSON-LD stocké. */
|
|
336
|
+
field: string
|
|
337
|
+
}
|
|
338
|
+
|
|
315
339
|
export interface ResolvedDocumentColumn {
|
|
316
340
|
key: string
|
|
317
341
|
label: string
|