@nocode-factory/sanity-kit 2.48.2 → 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.
@@ -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 scoped = issuesForTool(issues, name)
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
- <Box padding={4} height="fill" overflow="auto">
57
- <Stack gap={4}>
58
- <ConfigIssues issues={scoped} toolTitle={title} />
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
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.48.2'
6
+ export const KIT_VERSION = '2.49.1'
@@ -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,eA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