@nocode-factory/sanity-kit 2.49.0 → 2.49.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/bin/ncf-kit.mjs +15 -0
- package/dist/{aiJsonLd-DiYeDzou.js → aiJsonLd-BFyxgYen.js} +15 -3
- package/dist/aiJsonLd-BFyxgYen.js.map +1 -0
- package/dist/index.d.ts +55 -3
- package/dist/index.js +185 -61
- package/dist/index.js.map +1 -1
- package/dist/jsonld.js +13 -6
- package/dist/jsonld.js.map +1 -1
- package/package.json +1 -1
- package/src/context/KitContext.tsx +15 -1
- package/src/form/JsonLdInput.tsx +21 -6
- package/src/hooks/useOccurrences.ts +4 -2
- package/src/hooks/usePageBuilder.ts +22 -0
- package/src/hooks/usePageContents.ts +8 -1
- package/src/hooks/usePages.ts +5 -1
- package/src/index.ts +6 -1
- package/src/lib/schemaTypes.ts +105 -0
- package/src/tools/createToolComponent.tsx +39 -10
- package/src/version.ts +1 -1
- package/dist/aiJsonLd-DiYeDzou.js.map +0 -1
package/dist/jsonld.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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
|
|
2
|
+
import { c as valueAtKey, f as useOptionalKitConfig, i as guessDocumentTitle, n as DEFAULT_JSONLD_FIELD, r as collectDocumentText, t as generateJsonLd } from "./aiJsonLd-BFyxgYen.js";
|
|
3
3
|
import { useCallback, useMemo, useState } from "react";
|
|
4
4
|
import { defineField, defineType, set, setIfMissing, unset, useFormValue } from "sanity";
|
|
5
5
|
import { Badge, Box, Button, Card, Flex, Stack, Text, TextArea } from "@sanity/ui";
|
|
@@ -25,7 +25,7 @@ function jsonError(data) {
|
|
|
25
25
|
* Le bouton de (re)génération est présent dans les deux modes.
|
|
26
26
|
*/
|
|
27
27
|
function JsonLdInput(props) {
|
|
28
|
-
let { onChange, readOnly } = props, value = props.value ?? {}, mode = value.mode === "manuel" ? "manuel" : "auto", config =
|
|
28
|
+
let { onChange, readOnly } = props, value = props.value ?? {}, mode = value.mode === "manuel" ? "manuel" : "auto", config = useOptionalKitConfig(), doc = useFormValue([]), [busy, setBusy] = useState(!1), [error, setError] = useState(null), field = config?.jsonLd?.field ?? "jsonLd", fallbackFn = props.schemaType.options?.ncfFallback, fallbackJson = useMemo(() => {
|
|
29
29
|
if (!fallbackFn || !doc) return null;
|
|
30
30
|
try {
|
|
31
31
|
let out = fallbackFn(doc);
|
|
@@ -34,14 +34,14 @@ function JsonLdInput(props) {
|
|
|
34
34
|
return null;
|
|
35
35
|
}
|
|
36
36
|
}, [fallbackFn, doc]), invalid = jsonError(value.data), url = useMemo(() => {
|
|
37
|
-
if (!doc) return null;
|
|
37
|
+
if (!doc || !config) return null;
|
|
38
38
|
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;
|
|
39
39
|
return toUrl(config.previewUrl, finalPath({
|
|
40
40
|
slug,
|
|
41
41
|
locale
|
|
42
42
|
}, pageType, config, null));
|
|
43
43
|
}, [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 () => {
|
|
44
|
-
if (config
|
|
44
|
+
if (config?.history && doc) {
|
|
45
45
|
setBusy(!0), setError(null);
|
|
46
46
|
try {
|
|
47
47
|
if (!url) throw Error("URL du site introuvable : renseigne l'URL de prévisualisation et le slug.");
|
|
@@ -67,8 +67,8 @@ function JsonLdInput(props) {
|
|
|
67
67
|
url,
|
|
68
68
|
field,
|
|
69
69
|
onChange
|
|
70
|
-
]), hasData = !!(value.data && value.data.trim()), aiAvailable = !!config
|
|
71
|
-
return /* @__PURE__ */ jsxs(Stack, {
|
|
70
|
+
]), hasData = !!(value.data && value.data.trim()), aiAvailable = !!config?.history && !readOnly;
|
|
71
|
+
return config ? /* @__PURE__ */ jsxs(Stack, {
|
|
72
72
|
gap: 3,
|
|
73
73
|
children: [
|
|
74
74
|
/* @__PURE__ */ jsxs(Flex, {
|
|
@@ -201,6 +201,13 @@ function JsonLdInput(props) {
|
|
|
201
201
|
children: "JSON valide"
|
|
202
202
|
}) }) : null
|
|
203
203
|
]
|
|
204
|
+
}) : /* @__PURE__ */ jsxs(Stack, {
|
|
205
|
+
gap: 2,
|
|
206
|
+
children: [props.renderDefault(props), /* @__PURE__ */ jsx(Text, {
|
|
207
|
+
size: 1,
|
|
208
|
+
muted: !0,
|
|
209
|
+
children: "Kit NCF non branché sur ce formulaire : modes et génération IA indisponibles ici."
|
|
210
|
+
})]
|
|
204
211
|
});
|
|
205
212
|
}
|
|
206
213
|
/**
|
package/dist/jsonld.js.map
CHANGED
|
@@ -1 +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 // JSON-LD servi par le site tant que rien n'est stocké (calculé par le projet depuis\n // les champs : option `fallback` de defineJsonLdType). Montré ici, au même endroit\n // que le réglage, pour qu'on voie toujours ce que le site publie.\n const fallbackFn = (props.schemaType.options as {ncfFallback?: (doc: Rec) => unknown} | undefined)?.ncfFallback\n const fallbackJson = useMemo(() => {\n if (!fallbackFn || !doc) return null\n try {\n const out = fallbackFn(doc)\n return out ? JSON.stringify(out, null, 2) : null\n } catch {\n return null\n }\n }, [fallbackFn, doc])\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 {/* Ce que le site sert tant que rien n'est stocké (vide en mode auto ou manuel). */}\n {!hasData && fallbackJson ? (\n <Stack gap={2}>\n <Text size={1} weight=\"semibold\">\n {mode === 'auto'\n ? 'Servi aujourd’hui par le site (calculé depuis les champs) : l’IA le remplacera à la prochaine publication, ou tout de suite avec « Régénérer maintenant ».'\n : 'Servi aujourd’hui par le site (calculé depuis les champs), tant que le JSON-LD ci-dessous est vide.'}\n </Text>\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 {fallbackJson}\n </Text>\n </Box>\n </Card>\n </Stack>\n ) : null}\n\n {hasData ? (\n <Text size={1} weight=\"semibold\">\n {mode === 'auto' ? 'Servi par le site (dernière génération par l’IA) :' : 'Servi par le site :'}\n </Text>\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 ) : fallbackJson ? null : (\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 * JSON-LD que le site sert quand rien n'est stocké (calculé par le projet depuis\n * les champs du document). Affiché dans le champ pour que l'équipe voie, au même\n * endroit que le réglage, ce que le site publie réellement. `null` : rien.\n */\n fallback?: (doc: Record<string, unknown>) => unknown\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)', fallback} = options\n\n return defineType({\n name,\n title,\n type: 'object',\n components: {input: JsonLdInput},\n // Lu par JsonLdInput : JSON-LD servi par le site quand rien n'est stocké.\n options: {ncfFallback: fallback} as never,\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,EAAC,UAAU,aAAY,OACvB,QAAS,MAAM,SAAS,CAAC,GACzB,OAAmB,MAAM,SAAS,WAAW,WAAW,QACxD,SAAS,aAAa,GACtB,MAAM,aAAa,CAAC,CAAC,GACrB,CAAC,MAAM,WAAW,SAAS,EAAK,GAChC,CAAC,OAAO,YAAY,SAAwB,IAAI,GAEhD,QAAQ,OAAO,QAAQ,SAAS,UAIhC,aAAc,MAAM,WAAW,SAA+D,aAC9F,eAAe,cAAc;EACjC,IAAI,CAAC,cAAc,CAAC,KAAK,OAAO;EAChC,IAAI;GACF,IAAM,MAAM,WAAW,GAAG;GAC1B,OAAO,MAAM,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI;EAC9C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F,CAAA;GAGP,UACC,oBAAC,MAAD,EAAA,UACG,UACC,oBAAC,OAAD;IAAO,MAAK;IAAW,OAAO;IAAS,UAAA;GAEhC,CAAA,IAEP,oBAAC,OAAD;IAAO,MAAK;IAAW,UAAA;GAAkB,CAAA,EAEvC,CAAA,IACJ;EACC;;AAEX;;;;;;;;;;;;;;ACtMA,SAAgB,iBAAiB,UAA6B,CAAC,GAAqB;CAClF,IAAM,EAAC,OAAO,UAAU,QAAQ,iCAAiC,aAAY;CAE7E,OAAO,WAAW;EAChB;EACA;EACA,MAAM;EACN,YAAY,EAAC,OAAO,YAAW;EAE/B,SAAS,EAAC,aAAa,SAAQ;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"}
|
|
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 {useOptionalKitConfig} 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 // Optionnel : ce champ peut, en théorie, être rendu hors d'un KitProvider.\n // On se replie alors sur le rendu par défaut plutôt que de planter le formulaire.\n const config = useOptionalKitConfig()\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 // JSON-LD servi par le site tant que rien n'est stocké (calculé par le projet depuis\n // les champs : option `fallback` de defineJsonLdType). Montré ici, au même endroit\n // que le réglage, pour qu'on voie toujours ce que le site publie.\n const fallbackFn = (props.schemaType.options as {ncfFallback?: (doc: Rec) => unknown} | undefined)?.ncfFallback\n const fallbackJson = useMemo(() => {\n if (!fallbackFn || !doc) return null\n try {\n const out = fallbackFn(doc)\n return out ? JSON.stringify(out, null, 2) : null\n } catch {\n return null\n }\n }, [fallbackFn, doc])\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 || !config) 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 // Hors KitProvider (cas théorique) : rendu par défaut, sans réglage ni IA, au\n // lieu de planter le formulaire.\n if (!config) {\n return (\n <Stack gap={2}>\n {props.renderDefault(props)}\n <Text size={1} muted>\n Kit NCF non branché sur ce formulaire : modes et génération IA indisponibles ici.\n </Text>\n </Stack>\n )\n }\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 {/* Ce que le site sert tant que rien n'est stocké (vide en mode auto ou manuel). */}\n {!hasData && fallbackJson ? (\n <Stack gap={2}>\n <Text size={1} weight=\"semibold\">\n {mode === 'auto'\n ? 'Servi aujourd’hui par le site (calculé depuis les champs) : l’IA le remplacera à la prochaine publication, ou tout de suite avec « Régénérer maintenant ».'\n : 'Servi aujourd’hui par le site (calculé depuis les champs), tant que le JSON-LD ci-dessous est vide.'}\n </Text>\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 {fallbackJson}\n </Text>\n </Box>\n </Card>\n </Stack>\n ) : null}\n\n {hasData ? (\n <Text size={1} weight=\"semibold\">\n {mode === 'auto' ? 'Servi par le site (dernière génération par l’IA) :' : 'Servi par le site :'}\n </Text>\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 ) : fallbackJson ? null : (\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 * JSON-LD que le site sert quand rien n'est stocké (calculé par le projet depuis\n * les champs du document). Affiché dans le champ pour que l'équipe voie, au même\n * endroit que le réglage, ce que le site publie réellement. `null` : rien.\n */\n fallback?: (doc: Record<string, unknown>) => unknown\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)', fallback} = options\n\n return defineType({\n name,\n title,\n type: 'object',\n components: {input: JsonLdInput},\n // Lu par JsonLdInput : JSON-LD servi par le site quand rien n'est stocké.\n options: {ncfFallback: fallback} as never,\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,UA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,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/package.json
CHANGED
|
@@ -15,9 +15,23 @@ export function KitProvider(props: KitProviderProps) {
|
|
|
15
15
|
return <KitContext.Provider value={value}>{children}</KitContext.Provider>
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Contexte du kit, ou `null` hors d'un `KitProvider`. À utiliser dans un
|
|
20
|
+
* composant qui peut être rendu HORS d'un outil (un champ de formulaire) et doit
|
|
21
|
+
* alors se replier proprement plutôt que de faire planter le formulaire.
|
|
22
|
+
*/
|
|
23
|
+
export function useOptionalKitContext(): KitContextValue | null {
|
|
24
|
+
return useContext(KitContext)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Configuration résolue, ou `null` hors contexte. Voir {@link useOptionalKitContext}. */
|
|
28
|
+
export const useOptionalKitConfig = (): ResolvedKitConfig | null => useOptionalKitContext()?.config ?? null
|
|
29
|
+
|
|
18
30
|
/**
|
|
19
31
|
* Configuration résolue du kit. Erreur explicite hors contexte : une
|
|
20
|
-
* dépendance oubliée se voit tout de suite au développement.
|
|
32
|
+
* dépendance oubliée se voit tout de suite au développement. À réserver au code
|
|
33
|
+
* rendu DANS un outil du kit (toujours sous `KitProvider`). Pour un champ de
|
|
34
|
+
* formulaire, préférer {@link useOptionalKitConfig}.
|
|
21
35
|
*/
|
|
22
36
|
export function useKitContext(): KitContextValue {
|
|
23
37
|
const value = useContext(KitContext)
|
package/src/form/JsonLdInput.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {useCallback, useMemo, useState} from 'react'
|
|
2
2
|
import {set, setIfMissing, unset, useFormValue, type ObjectInputProps} from 'sanity'
|
|
3
3
|
import {Badge, Box, Button, Card, Flex, Stack, Text, TextArea} from '@sanity/ui'
|
|
4
|
-
import {
|
|
4
|
+
import {useOptionalKitConfig} from '../context/KitContext'
|
|
5
5
|
import {finalPath} from '../lib/finalUrl'
|
|
6
6
|
import {toUrl} from '../lib/paths'
|
|
7
7
|
import {pageTypeFor} from '../lib/paths'
|
|
@@ -44,12 +44,14 @@ export function JsonLdInput(props: ObjectInputProps): React.JSX.Element {
|
|
|
44
44
|
const {onChange, readOnly} = props
|
|
45
45
|
const value = (props.value ?? {}) as JsonLdValue
|
|
46
46
|
const mode: JsonLdMode = value.mode === 'manuel' ? 'manuel' : 'auto'
|
|
47
|
-
|
|
47
|
+
// Optionnel : ce champ peut, en théorie, être rendu hors d'un KitProvider.
|
|
48
|
+
// On se replie alors sur le rendu par défaut plutôt que de planter le formulaire.
|
|
49
|
+
const config = useOptionalKitConfig()
|
|
48
50
|
const doc = useFormValue([]) as Rec | undefined
|
|
49
51
|
const [busy, setBusy] = useState(false)
|
|
50
52
|
const [error, setError] = useState<string | null>(null)
|
|
51
53
|
|
|
52
|
-
const field = config
|
|
54
|
+
const field = config?.jsonLd?.field ?? 'jsonLd'
|
|
53
55
|
// JSON-LD servi par le site tant que rien n'est stocké (calculé par le projet depuis
|
|
54
56
|
// les champs : option `fallback` de defineJsonLdType). Montré ici, au même endroit
|
|
55
57
|
// que le réglage, pour qu'on voie toujours ce que le site publie.
|
|
@@ -67,7 +69,7 @@ export function JsonLdInput(props: ObjectInputProps): React.JSX.Element {
|
|
|
67
69
|
|
|
68
70
|
// URL publique de la page : sert d'`url`/`@id` dans le JSON-LD.
|
|
69
71
|
const url = useMemo(() => {
|
|
70
|
-
if (!doc) return null
|
|
72
|
+
if (!doc || !config) return null
|
|
71
73
|
const pageType = pageTypeFor(doc._type as string, config.pageTypes)
|
|
72
74
|
const slugValue = pageType?.slugField ? valueAtKey(doc, pageType.slugField) : null
|
|
73
75
|
const slug = isObj(slugValue) ? (slugValue.current as string) ?? null : typeof slugValue === 'string' ? slugValue : null
|
|
@@ -86,7 +88,7 @@ export function JsonLdInput(props: ObjectInputProps): React.JSX.Element {
|
|
|
86
88
|
)
|
|
87
89
|
|
|
88
90
|
const generate = useCallback(async () => {
|
|
89
|
-
if (!config
|
|
91
|
+
if (!config?.history || !doc) return
|
|
90
92
|
setBusy(true)
|
|
91
93
|
setError(null)
|
|
92
94
|
try {
|
|
@@ -109,7 +111,7 @@ export function JsonLdInput(props: ObjectInputProps): React.JSX.Element {
|
|
|
109
111
|
}, [config, doc, url, field, onChange])
|
|
110
112
|
|
|
111
113
|
const hasData = Boolean(value.data && value.data.trim())
|
|
112
|
-
const aiAvailable = Boolean(config
|
|
114
|
+
const aiAvailable = Boolean(config?.history) && !readOnly
|
|
113
115
|
const buttonText = busy
|
|
114
116
|
? 'Génération…'
|
|
115
117
|
: mode === 'manuel'
|
|
@@ -118,6 +120,19 @@ export function JsonLdInput(props: ObjectInputProps): React.JSX.Element {
|
|
|
118
120
|
: 'Rédiger avec l’IA'
|
|
119
121
|
: 'Régénérer maintenant'
|
|
120
122
|
|
|
123
|
+
// Hors KitProvider (cas théorique) : rendu par défaut, sans réglage ni IA, au
|
|
124
|
+
// lieu de planter le formulaire.
|
|
125
|
+
if (!config) {
|
|
126
|
+
return (
|
|
127
|
+
<Stack gap={2}>
|
|
128
|
+
{props.renderDefault(props)}
|
|
129
|
+
<Text size={1} muted>
|
|
130
|
+
Kit NCF non branché sur ce formulaire : modes et génération IA indisponibles ici.
|
|
131
|
+
</Text>
|
|
132
|
+
</Stack>
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
|
|
121
136
|
return (
|
|
122
137
|
<Stack gap={3}>
|
|
123
138
|
{/* Mode */}
|
|
@@ -5,6 +5,7 @@ import {PROJECTION} from '../lib/query'
|
|
|
5
5
|
import {blockTypesFromSchema, type BlockTypeInfo} from '../lib/schemaTypes'
|
|
6
6
|
import {occurrencesForTypes, type BlockOccurrence} from '../lib/occurrences'
|
|
7
7
|
import {usePageContents, CONTENT_SCAN_LIMIT} from './usePageContents'
|
|
8
|
+
import {usePageBuilder} from './usePageBuilder'
|
|
8
9
|
|
|
9
10
|
export {CONTENT_SCAN_LIMIT as OCCURRENCE_SCAN_LIMIT}
|
|
10
11
|
|
|
@@ -30,11 +31,12 @@ export interface OccurrencesState {
|
|
|
30
31
|
export function useOccurrences(): OccurrencesState {
|
|
31
32
|
const config = useKitConfig()
|
|
32
33
|
const schema = useSchema()
|
|
34
|
+
const {field: pageBuilderField} = usePageBuilder()
|
|
33
35
|
const {contents, truncated, scanned, loading, error, refresh} = usePageContents()
|
|
34
36
|
|
|
35
37
|
const blockTypes = useMemo(
|
|
36
|
-
() => blockTypesFromSchema(schema, config.pageTypes,
|
|
37
|
-
[schema, config.pageTypes,
|
|
38
|
+
() => blockTypesFromSchema(schema, config.pageTypes, pageBuilderField),
|
|
39
|
+
[schema, config.pageTypes, pageBuilderField],
|
|
38
40
|
)
|
|
39
41
|
|
|
40
42
|
const occurrences = useMemo(() => {
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {useMemo} from 'react'
|
|
2
|
+
import {useSchema} from 'sanity'
|
|
3
|
+
import {useKitConfig} from '../context/KitContext'
|
|
4
|
+
import {resolvePageBuilderField, sectionNamesFromDefaults, type PageBuilderResolution} from '../lib/schemaTypes'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Champ page builder EFFECTIF, résolu contre le schéma : le champ configuré
|
|
8
|
+
* (`pageBuilderField`) s'il convient, sinon le champ auto-détecté dont les
|
|
9
|
+
* membres sont les sections déclarées (`defineComponentDefaults`), sinon
|
|
10
|
+
* `ok: false` (aucun champ de sections : configuration à corriger).
|
|
11
|
+
*
|
|
12
|
+
* Évite le défaut silencieux : un projet qui met ses sections dans un autre
|
|
13
|
+
* champ (ex. `pageBuilder`) sans passer `pageBuilderField` est quand même servi.
|
|
14
|
+
*/
|
|
15
|
+
export function usePageBuilder(): PageBuilderResolution {
|
|
16
|
+
const schema = useSchema()
|
|
17
|
+
const config = useKitConfig()
|
|
18
|
+
return useMemo(() => {
|
|
19
|
+
const sectionNames = sectionNamesFromDefaults(schema, config.componentPreview.defaultsType)
|
|
20
|
+
return resolvePageBuilderField(schema, config.pageTypes, config.pageBuilderField, sectionNames)
|
|
21
|
+
}, [schema, config])
|
|
22
|
+
}
|
|
@@ -3,6 +3,7 @@ import {useKitConfig} from '../context/KitContext'
|
|
|
3
3
|
import {buildContentsQuery, PROJECTION} from '../lib/query'
|
|
4
4
|
import {mergeVersions} from '../lib/status'
|
|
5
5
|
import {useQueryData} from './useQueryData'
|
|
6
|
+
import {usePageBuilder} from './usePageBuilder'
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Plafond du balayage. La requête rapatrie les documents entiers : c'est le
|
|
@@ -36,8 +37,14 @@ export interface PageContentsState {
|
|
|
36
37
|
*/
|
|
37
38
|
export function usePageContents(): PageContentsState {
|
|
38
39
|
const config = useKitConfig()
|
|
40
|
+
// Champ page builder effectif (configuré ou auto-détecté) : la projection des
|
|
41
|
+
// blocs doit viser le bon champ, sinon toutes les occurrences sont à zéro.
|
|
42
|
+
const {field: pageBuilderField} = usePageBuilder()
|
|
39
43
|
|
|
40
|
-
const query = useMemo(
|
|
44
|
+
const query = useMemo(
|
|
45
|
+
() => buildContentsQuery({...config, pageBuilderField}, CONTENT_SCAN_LIMIT),
|
|
46
|
+
[config, pageBuilderField],
|
|
47
|
+
)
|
|
41
48
|
const params = useMemo(() => ({types: config.pageTypeNames}), [config.pageTypeNames])
|
|
42
49
|
|
|
43
50
|
const {data, loading, error, refresh} = useQueryData<PageContent[]>(query, params, {
|
package/src/hooks/usePages.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {useMemo} from 'react'
|
|
2
2
|
import {useKitConfig} from '../context/KitContext'
|
|
3
|
+
import {usePageBuilder} from './usePageBuilder'
|
|
3
4
|
import {buildPagesQuery} from '../lib/query'
|
|
4
5
|
import {buildPageRows, type PageDoc, type PageRow} from '../lib/pages'
|
|
5
6
|
import {useQueryData} from './useQueryData'
|
|
@@ -22,11 +23,14 @@ export interface PagesState {
|
|
|
22
23
|
*/
|
|
23
24
|
export function usePages(documentColumns: readonly ResolvedDocumentColumn[] = []): PagesState {
|
|
24
25
|
const config = useKitConfig()
|
|
26
|
+
// Champ page builder effectif (configuré ou auto-détecté) : la colonne « nb de
|
|
27
|
+
// blocs » compte sur le bon champ.
|
|
28
|
+
const {field: pageBuilderField} = usePageBuilder()
|
|
25
29
|
// La signature de la projection suffit à distinguer deux requêtes : deux
|
|
26
30
|
// rendus avec les mêmes colonnes ne doivent pas en reconstruire une.
|
|
27
31
|
const signature = documentColumns.map((column) => `${column.key}:${column.paths.join('|')}`).join(',')
|
|
28
32
|
const columns = useMemo(() => documentColumns, [signature]) // eslint-disable-line react-hooks/exhaustive-deps
|
|
29
|
-
const query = useMemo(() => buildPagesQuery(config, columns), [config, columns])
|
|
33
|
+
const query = useMemo(() => buildPagesQuery({...config, pageBuilderField}, columns), [config, pageBuilderField, columns])
|
|
30
34
|
const params = useMemo(() => ({types: config.pageTypeNames}), [config.pageTypeNames])
|
|
31
35
|
|
|
32
36
|
const {data, loading, error, refresh} = useQueryData<PageDoc[]>(query, params, {
|
package/src/index.ts
CHANGED
|
@@ -247,7 +247,7 @@ export {
|
|
|
247
247
|
kitSchemaTypes,
|
|
248
248
|
} from './schema/boardLayout'
|
|
249
249
|
|
|
250
|
-
export {useKitConfig, useKitContext} from './context/KitContext'
|
|
250
|
+
export {useKitConfig, useKitContext, useOptionalKitConfig, useOptionalKitContext} from './context/KitContext'
|
|
251
251
|
|
|
252
252
|
export {toPath, toUrl, segments, depth, parentPath, pageTypeFor} from './lib/paths'
|
|
253
253
|
export {pageTypesFromSiteRoutes, type SiteRoutesRegistry} from './lib/siteRoutes'
|
|
@@ -268,7 +268,12 @@ export {
|
|
|
268
268
|
blockTypesFromSchema,
|
|
269
269
|
missingPageTypes,
|
|
270
270
|
pageTypesWithoutBuilder,
|
|
271
|
+
sectionNamesFromDefaults,
|
|
272
|
+
detectPageBuilderField,
|
|
273
|
+
resolvePageBuilderField,
|
|
271
274
|
} from './lib/schemaTypes'
|
|
275
|
+
export type {PageBuilderResolution} from './lib/schemaTypes'
|
|
276
|
+
export {usePageBuilder} from './hooks/usePageBuilder'
|
|
272
277
|
export {
|
|
273
278
|
buildPagesQuery,
|
|
274
279
|
buildContentsQuery,
|
package/src/lib/schemaTypes.ts
CHANGED
|
@@ -73,3 +73,108 @@ export function pageTypesWithoutBuilder(
|
|
|
73
73
|
})
|
|
74
74
|
.map((p) => p.type)
|
|
75
75
|
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Noms des sections déclarées via `defineComponentDefaults` (type de document
|
|
79
|
+
* des valeurs par défaut) : un champ par section, dont le nom est la section
|
|
80
|
+
* SANS son namespace (ex. `cta` pour `section.cta`). Set vide si le type est
|
|
81
|
+
* absent du schéma.
|
|
82
|
+
*/
|
|
83
|
+
export function sectionNamesFromDefaults(schema: Schema, defaultsType: string): Set<string> {
|
|
84
|
+
const type = schema.get(defaultsType)
|
|
85
|
+
if (!isObjectType(type)) return new Set()
|
|
86
|
+
return new Set(type.fields.map((f) => f.name))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Nom de membre sans son namespace : `section.cta` -> `cta`, `cta` -> `cta`. */
|
|
90
|
+
const withoutNamespace = (name: string): string => {
|
|
91
|
+
const dot = name.lastIndexOf('.')
|
|
92
|
+
return dot >= 0 ? name.slice(dot + 1) : name
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Vrai si `field` est un tableau dont au moins un membre est une section
|
|
97
|
+
* déclarée. On compare sans dépendre du namespace (les membres `of` sont par
|
|
98
|
+
* ex. `section.cta`, les champs de `componentDefaults` sont `cta`).
|
|
99
|
+
*/
|
|
100
|
+
function isSectionArrayField(field: {type?: SchemaType} | undefined, sectionNames: Set<string>): boolean {
|
|
101
|
+
const type = field?.type
|
|
102
|
+
return (
|
|
103
|
+
isArrayType(type) &&
|
|
104
|
+
type.of.some((member) => Boolean(member.name) && (sectionNames.has(member.name as string) || sectionNames.has(withoutNamespace(member.name as string))))
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Détecte le champ tableau des sections d'un type de page : le champ (hors
|
|
110
|
+
* `pageBuilderField` configuré) dont les membres sont les sections déclarées.
|
|
111
|
+
* Renvoie le nom du champ couvrant le plus de types de pages, sinon `null`.
|
|
112
|
+
*/
|
|
113
|
+
export function detectPageBuilderField(
|
|
114
|
+
schema: Schema,
|
|
115
|
+
pageTypes: readonly ResolvedPageType[],
|
|
116
|
+
sectionNames: Set<string>,
|
|
117
|
+
): string | null {
|
|
118
|
+
if (sectionNames.size === 0) return null
|
|
119
|
+
const counts = new Map<string, number>()
|
|
120
|
+
for (const pageType of pageTypes) {
|
|
121
|
+
const documentType = schema.get(pageType.type)
|
|
122
|
+
if (!isObjectType(documentType)) continue
|
|
123
|
+
for (const field of documentType.fields) {
|
|
124
|
+
if (isSectionArrayField(field, sectionNames)) counts.set(field.name, (counts.get(field.name) ?? 0) + 1)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
let best: string | null = null
|
|
128
|
+
let bestCount = 0
|
|
129
|
+
for (const [name, count] of counts) {
|
|
130
|
+
if (count > bestCount) {
|
|
131
|
+
best = name
|
|
132
|
+
bestCount = count
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return best
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface PageBuilderResolution {
|
|
139
|
+
/** Champ page builder effectif (configuré s'il convient, sinon détecté). */
|
|
140
|
+
field: string
|
|
141
|
+
/** Vrai si le champ a été auto-détecté (le champ configuré ne convenait pas). */
|
|
142
|
+
detected: boolean
|
|
143
|
+
/** Faux si aucun champ tableau de sections n'a été trouvé (configuration à corriger). */
|
|
144
|
+
ok: boolean
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Champ page builder à utiliser réellement :
|
|
149
|
+
* - le champ configuré s'il est bien un tableau de sections sur un type de page ;
|
|
150
|
+
* - sinon le champ auto-détecté (ses membres sont les sections déclarées) ;
|
|
151
|
+
* - sinon le champ configuré avec `ok: false` (rien trouvé : à corriger).
|
|
152
|
+
*
|
|
153
|
+
* Quand les sections ne sont pas connues (pas de `componentDefaults` dans le
|
|
154
|
+
* schéma), on garde le comportement historique : le champ configuré est réputé
|
|
155
|
+
* bon dès qu'il existe comme tableau sur au moins un type de page.
|
|
156
|
+
*/
|
|
157
|
+
export function resolvePageBuilderField(
|
|
158
|
+
schema: Schema,
|
|
159
|
+
pageTypes: readonly ResolvedPageType[],
|
|
160
|
+
configuredField: string,
|
|
161
|
+
sectionNames: Set<string>,
|
|
162
|
+
): PageBuilderResolution {
|
|
163
|
+
if (sectionNames.size === 0) {
|
|
164
|
+
const missing = pageTypesWithoutBuilder(schema, pageTypes, configuredField)
|
|
165
|
+
const ok = pageTypes.length === 0 || missing.length < pageTypes.length
|
|
166
|
+
return {field: configuredField, detected: false, ok}
|
|
167
|
+
}
|
|
168
|
+
const configuredIsSectionArray = pageTypes.some((pageType) => {
|
|
169
|
+
const documentType = schema.get(pageType.type)
|
|
170
|
+
if (!isObjectType(documentType)) return false
|
|
171
|
+
return isSectionArrayField(
|
|
172
|
+
documentType.fields.find((f) => f.name === configuredField),
|
|
173
|
+
sectionNames,
|
|
174
|
+
)
|
|
175
|
+
})
|
|
176
|
+
if (configuredIsSectionArray) return {field: configuredField, detected: false, ok: true}
|
|
177
|
+
const detected = detectPageBuilderField(schema, pageTypes, sectionNames)
|
|
178
|
+
if (detected) return {field: detected, detected: true, ok: true}
|
|
179
|
+
return {field: configuredField, detected: false, ok: false}
|
|
180
|
+
}
|
|
@@ -6,6 +6,7 @@ import {BoardLayoutProvider} from '../context/BoardLayoutContext'
|
|
|
6
6
|
import {PreviewTargetProvider} from '../context/PreviewTargetContext'
|
|
7
7
|
import {ConfigIssues} from '../ui/ConfigIssues'
|
|
8
8
|
import {useRegistration} from '../hooks/useRegistration'
|
|
9
|
+
import {usePageBuilder} from '../hooks/usePageBuilder'
|
|
9
10
|
import {ProjectStatusNotice} from '../ui/ProjectStatusNotice'
|
|
10
11
|
import {PreviewOriginsNotice} from '../ui/PreviewOriginsNotice'
|
|
11
12
|
import {issuesForTool} from '../config/validate'
|
|
@@ -35,6 +36,40 @@ export interface ToolComponentProps {
|
|
|
35
36
|
tool: Tool
|
|
36
37
|
}
|
|
37
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Corps d'un outil, rendu SOUS le KitProvider : il peut donc lire le schéma
|
|
41
|
+
* (`usePageBuilder`). Ajoute aux problèmes statiques l'erreur « champ page
|
|
42
|
+
* builder introuvable » (Pages et Composants), qui a besoin du schéma et ne
|
|
43
|
+
* peut pas être produite par `validateConfig` (appelée hors React).
|
|
44
|
+
*/
|
|
45
|
+
function ToolBody(props: {name: NcfToolName; title: string; staticScoped: ConfigIssue[]; Component: ComponentType}) {
|
|
46
|
+
const {name, title, staticScoped, Component} = props
|
|
47
|
+
const pageBuilder = usePageBuilder()
|
|
48
|
+
const concernsSections = name === 'pages' || name === 'components'
|
|
49
|
+
const runtimeIssues: ConfigIssue[] =
|
|
50
|
+
concernsSections && !pageBuilder.ok
|
|
51
|
+
? [
|
|
52
|
+
{
|
|
53
|
+
level: 'error',
|
|
54
|
+
path: 'pageBuilderField',
|
|
55
|
+
tools: ['pages', 'components'],
|
|
56
|
+
message:
|
|
57
|
+
"Aucun champ de sections trouvé dans les types de pages. Vérifier que les sections sont dans un champ tableau d'un type de page, et passer pageBuilderField: '<nom du champ>' à ncfKit().",
|
|
58
|
+
},
|
|
59
|
+
]
|
|
60
|
+
: []
|
|
61
|
+
const scoped = [...staticScoped, ...runtimeIssues]
|
|
62
|
+
const blocking = scoped.some((issue) => issue.level === 'error')
|
|
63
|
+
return (
|
|
64
|
+
<Stack gap={4}>
|
|
65
|
+
<ConfigIssues issues={scoped} toolTitle={title} />
|
|
66
|
+
{name === 'pages' && <PreviewOriginsNotice />}
|
|
67
|
+
<Registered />
|
|
68
|
+
{blocking ? null : <Component />}
|
|
69
|
+
</Stack>
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
38
73
|
/**
|
|
39
74
|
* Enveloppe commune aux trois outils : fournit la configuration, affiche les
|
|
40
75
|
* problèmes qui concernent cet outil, et ne monte son contenu que si rien ne
|
|
@@ -45,22 +80,16 @@ export function createToolComponent(
|
|
|
45
80
|
args: CreateToolComponentArgs,
|
|
46
81
|
): ComponentType<ToolComponentProps> {
|
|
47
82
|
const {name, title, config, issues, Component} = args
|
|
48
|
-
const
|
|
49
|
-
const blocking = scoped.some((issue) => issue.level === 'error')
|
|
83
|
+
const staticScoped = issuesForTool(issues, name)
|
|
50
84
|
|
|
51
85
|
return function NcfToolRoot() {
|
|
52
86
|
return (
|
|
53
87
|
<KitProvider config={config} issues={issues}>
|
|
54
88
|
<BoardLayoutProvider>
|
|
55
89
|
<PreviewTargetProvider>
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
{name === 'pages' && <PreviewOriginsNotice />}
|
|
60
|
-
<Registered />
|
|
61
|
-
{blocking ? null : <Component />}
|
|
62
|
-
</Stack>
|
|
63
|
-
</Box>
|
|
90
|
+
<Box padding={4} height="fill" overflow="auto">
|
|
91
|
+
<ToolBody name={name} title={title} staticScoped={staticScoped} Component={Component} />
|
|
92
|
+
</Box>
|
|
64
93
|
</PreviewTargetProvider>
|
|
65
94
|
</BoardLayoutProvider>
|
|
66
95
|
</KitProvider>
|
package/src/version.ts
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"aiJsonLd-DiYeDzou.js","names":["isObj"],"sources":["../src/context/KitContext.tsx","../src/lib/aiTexts.ts","../src/lib/jsonLdContent.ts","../src/lib/aiJsonLd.ts"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react'\nimport type {KitContextValue, ResolvedKitConfig, ConfigIssue} from '../config/types'\n\nconst KitContext = createContext<KitContextValue | null>(null)\n\nexport interface KitProviderProps {\n config: ResolvedKitConfig\n issues: ConfigIssue[]\n children: ReactNode\n}\n\nexport function KitProvider(props: KitProviderProps) {\n const {config, issues, children} = props\n const value = useMemo<KitContextValue>(() => ({config, issues}), [config, issues])\n return <KitContext.Provider value={value}>{children}</KitContext.Provider>\n}\n\n/**\n * Configuration résolue du kit. Erreur explicite hors contexte : une\n * dépendance oubliée se voit tout de suite au développement.\n */\nexport function useKitContext(): KitContextValue {\n const value = useContext(KitContext)\n if (!value) {\n throw new Error('useKitContext must be called inside a tool of the @nocode-factory/sanity-kit plugin.')\n }\n return value\n}\n\nexport const useKitConfig = (): ResolvedKitConfig => useKitContext().config\n","/**\n * Textes d'une valeur de champ, pour la traduction par IA : une chaîne, ou les\n * morceaux de texte (spans) d'un texte riche. La structure (styles, liens, marques,\n * _key) n'est jamais envoyée ni modifiée : seuls les textes sont remplacés.\n */\n\ntype Rec = Record<string, unknown>\nconst isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** Textes d'une valeur, dans l'ordre. */\nexport function collectTexts(value: unknown): string[] {\n if (typeof value === 'string') return [value]\n if (!Array.isArray(value)) return []\n const out: string[] = []\n for (const item of value) {\n if (typeof item === 'string') out.push(item)\n else if (isObj(item) && Array.isArray(item.children))\n for (const child of item.children) if (isObj(child) && typeof child.text === 'string') out.push(child.text)\n }\n return out\n}\n\n/** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */\nexport function replaceTexts(value: unknown, texts: readonly string[]): unknown {\n let i = 0\n const next = () => texts[i++] ?? ''\n if (typeof value === 'string') return next()\n if (!Array.isArray(value)) return value\n return value.map((item) => {\n if (typeof item === 'string') return next()\n if (isObj(item) && Array.isArray(item.children))\n return {...item, children: item.children.map((child) => (isObj(child) && typeof child.text === 'string' ? {...child, text: next()} : child))}\n return item\n })\n}\n\n/** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */\nexport function parsePathKey(path: string): ({field: string} | {item: string})[] {\n const out: ({field: string} | {item: string})[] = []\n for (const m of path.matchAll(/([^.[\\]]+)|\\[([^\\]]+)\\]/g)) out.push(m[1] !== undefined ? {field: m[1]} : {item: m[2]!})\n return out\n}\n\nfunction itemOf(list: unknown[], key: string): unknown {\n return list.find((i) => isObj(i) && i._key === key) ?? (/^\\d+$/.test(key) ? list[Number(key)] : undefined)\n}\n\n/** Valeur d'un document au chemin `sections[a].title`. */\nexport function valueAtKey(doc: unknown, path: string): unknown {\n let cur: unknown = doc\n for (const seg of parsePathKey(path)) {\n if (cur == null) return undefined\n if ('field' in seg) cur = isObj(cur) ? cur[seg.field] : undefined\n else cur = Array.isArray(cur) ? itemOf(cur, seg.item) : undefined\n }\n return cur\n}\n\n/** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */\nexport function setAtKey(doc: Rec, path: string, value: unknown): boolean {\n const segs = parsePathKey(path)\n let cur: unknown = doc\n for (let n = 0; n < segs.length - 1; n++) {\n const seg = segs[n]!\n cur = 'field' in seg ? (isObj(cur) ? cur[seg.field] : undefined) : Array.isArray(cur) ? itemOf(cur, seg.item) : undefined\n if (cur == null) return false\n }\n const last = segs[segs.length - 1]\n if (!last || !('field' in last) || !isObj(cur)) return false\n cur[last.field] = value\n return true\n}\n","/**\n * Assemble le TEXTE d'un document Sanity pour la génération de JSON-LD par IA :\n * titres, descriptions, corps (texte riche compris). On parcourt le document en\n * profondeur et on ne garde que les chaînes lisibles, en écartant la plomberie\n * (identifiants, slugs, styles de texte, références d'images...).\n */\n\ntype Rec = Record<string, unknown>\nconst isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** Clés dont la valeur n'apporte pas de contenu lisible (bruit ou plomberie). */\nconst SKIP_KEYS = new Set([\n '_type',\n '_id',\n '_rev',\n '_key',\n '_ref',\n '_weak',\n '_createdAt',\n '_updatedAt',\n '_originalId',\n 'slug',\n 'language',\n 'hotspot',\n 'crop',\n 'asset',\n 'marks',\n 'markDefs',\n 'style',\n 'listItem',\n 'level',\n 'href',\n 'noindex',\n])\n\nconst MAX_CHARS = 30_000\n\n/** Nom du champ JSON-LD par défaut (écarté du contenu envoyé, pour ne pas boucler). */\nexport const DEFAULT_JSONLD_FIELD = 'jsonLd'\n\nfunction walk(value: unknown, out: string[], skip: Set<string>, depth: number): void {\n if (depth > 12) return\n if (typeof value === 'string') {\n const text = value.trim()\n if (text) out.push(text)\n return\n }\n if (Array.isArray(value)) {\n for (const item of value) walk(item, out, skip, depth + 1)\n return\n }\n if (isObj(value)) {\n for (const [key, val] of Object.entries(value)) {\n if (skip.has(key)) continue\n walk(val, out, skip, depth + 1)\n }\n }\n}\n\n/**\n * Texte lisible d'un document, dans l'ordre, prêt à être envoyé à l'IA.\n * `extraSkip` : champs supplémentaires à ignorer (au moins le champ JSON-LD\n * lui-même, pour ne pas renvoyer l'ancien JSON-LD au modèle).\n */\nexport function collectDocumentText(doc: unknown, extraSkip: readonly string[] = [DEFAULT_JSONLD_FIELD]): string {\n const skip = new Set(SKIP_KEYS)\n for (const field of extraSkip) skip.add(field)\n const out: string[] = []\n walk(doc, out, skip, 0)\n // Dédoublonne en gardant l'ordre : un même libellé répété n'aide pas le modèle.\n const seen = new Set<string>()\n const lines: string[] = []\n let size = 0\n for (const text of out) {\n if (seen.has(text)) continue\n seen.add(text)\n if (size + text.length > MAX_CHARS) break\n lines.push(text)\n size += text.length\n }\n return lines.join('\\n')\n}\n\n/** Titre probable d'un document (pour aider le modèle), sinon chaîne vide. */\nexport function guessDocumentTitle(doc: unknown): string {\n if (!isObj(doc)) return ''\n const seo = isObj(doc.seo) ? doc.seo : undefined\n const candidates = [doc.title, doc.name, doc.heading, seo?.metaTitle]\n for (const candidate of candidates) if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()\n return ''\n}\n","/** Service du kit (même clé de projet et même adresse que l'historique et la traduction). */\nexport interface JsonLdService {\n endpoint: string\n projectKey: string\n}\n\n/** Ce que le Studio envoie pour décrire la page à l'IA. */\nexport interface JsonLdRequest {\n /** URL absolue de la page en ligne (sert d'`url`/`@id`). */\n url: string\n /** Langue de la page (BCP 47), devient `inLanguage`. */\n locale?: string\n /** Indice sur la nature de la page (type Sanity, ou « article »...). */\n type?: string\n /** Titre de la page. */\n title?: string\n /** Texte de la page (titres, descriptions, corps), assemblé par le Studio. */\n content: string\n}\n\nconst MESSAGES: Record<string, string> = {\n daily_limit: 'Limite IA quotidienne atteinte pour ce projet.',\n project_inactive: \"Ce projet n'est pas actif dans le kit NCF.\",\n bad_key: \"Ce projet n'est pas enregistré dans le kit NCF (npx ncf-kit setup).\",\n not_configured: \"L'IA n'est pas configurée sur le service du kit NCF.\",\n too_long: 'Contenu trop long pour générer le JSON-LD en une fois.',\n empty_content: 'Aucun contenu à décrire sur cette page.',\n missing_url: \"L'URL de la page est introuvable (slug ou URL du site manquant).\",\n}\n\n/**\n * Demande à l'IA le JSON-LD d'une page, à partir de son contenu. Renvoie l'objet\n * JSON-LD (jamais une chaîne). L'appel passe par l'Edge Function `jsonld` du kit,\n * qui détient la clé Anthropic : le Studio ne transmet que sa clé de projet.\n */\nexport async function generateJsonLd(service: JsonLdService, input: JsonLdRequest): Promise<Record<string, unknown>> {\n const response = await fetch(`${service.endpoint}/jsonld`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n key: service.projectKey,\n url: input.url,\n locale: input.locale ?? '',\n type: input.type ?? '',\n title: input.title ?? '',\n content: input.content,\n }),\n })\n const body = (await response.json().catch(() => ({}))) as {jsonld?: Record<string, unknown>; error?: string}\n if (!response.ok || !body.jsonld || typeof body.jsonld !== 'object')\n throw new Error(MESSAGES[body.error ?? ''] ?? `Génération JSON-LD échouée (${body.error ?? response.status}).`)\n return body.jsonld\n}\n"],"mappings":";;AAGA,MAAM,aAAa,cAAsC,IAAI;AAQ7D,SAAgB,YAAY,OAAyB;CACnD,IAAM,EAAC,QAAQ,QAAQ,aAAY,OAC7B,QAAQ,eAAgC;EAAC;EAAQ;CAAM,IAAI,CAAC,QAAQ,MAAM,CAAC;CACjF,OAAO,oBAAC,WAAW,UAAZ;EAA4B;EAAQ;CAA8B,CAAA;AAC3E;;;;;AAMA,SAAgB,gBAAiC;CAC/C,IAAM,QAAQ,WAAW,UAAU;CACnC,IAAI,CAAC,OACH,MAAU,MAAM,sFAAsF;CAExG,OAAO;AACT;AAEA,MAAa,qBAAwC,cAAc,CAAC,CAAC,QCtB/DA,WAAS,MAAyB,OAAO,KAAM,cAAY,KAAc,CAAC,MAAM,QAAQ,CAAC;;AAG/F,SAAgB,aAAa,OAA0B;CACrD,IAAI,OAAO,SAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;CACnC,IAAM,MAAgB,CAAC;CACvB,KAAK,IAAM,QAAQ,OACjB,IAAI,OAAO,QAAS,UAAU,IAAI,KAAK,IAAI;MACtC,IAAIA,QAAM,IAAI,KAAK,MAAM,QAAQ,KAAK,QAAQ,GAC5C,KAAA,IAAM,SAAS,KAAK,UAAU,AAAIA,QAAM,KAAK,KAAK,OAAO,MAAM,QAAS,YAAU,IAAI,KAAK,MAAM,IAAI;CAE9G,OAAO;AACT;;AAGA,SAAgB,aAAa,OAAgB,OAAmC;CAC9E,IAAI,IAAI,GACF,aAAa,MAAM,QAAQ;CAGjC,OAFI,OAAO,SAAU,WAAiB,KAAK,IACtC,MAAM,QAAQ,KAAK,IACjB,MAAM,KAAK,SACZ,OAAO,QAAS,WAAiB,KAAK,IACtCA,QAAM,I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