@nocode-factory/sanity-kit 2.49.0 → 2.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +2 -1
  2. package/bin/ncf-kit.mjs +15 -0
  3. package/dist/{aiJsonLd-DiYeDzou.js → aiJsonLd-BFyxgYen.js} +15 -3
  4. package/dist/aiJsonLd-BFyxgYen.js.map +1 -0
  5. package/dist/{finalUrl-C1kzYMzQ.js → finalUrl-CaFXmYvm.js} +3 -2
  6. package/dist/finalUrl-CaFXmYvm.js.map +1 -0
  7. package/dist/{fixCrossLanguageReferences-BZk9CkdI.js → fixCrossLanguageReferences-BeXywAAU.js} +2 -2
  8. package/dist/{fixCrossLanguageReferences-BZk9CkdI.js.map → fixCrossLanguageReferences-BeXywAAU.js.map} +1 -1
  9. package/dist/{fixCrossLanguageReferences-CjL_Xy0U.d.ts → fixCrossLanguageReferences-w3whO9xM.d.ts} +4 -2
  10. package/dist/index.d.ts +237 -6
  11. package/dist/index.js +1648 -159
  12. package/dist/index.js.map +1 -1
  13. package/dist/jsonld.js +14 -7
  14. package/dist/jsonld.js.map +1 -1
  15. package/dist/schema.d.ts +1 -1
  16. package/dist/schema.js +2 -2
  17. package/package.json +3 -1
  18. package/src/config/defaults.ts +1 -0
  19. package/src/config/types.ts +3 -1
  20. package/src/context/KitContext.tsx +15 -1
  21. package/src/form/JsonLdInput.tsx +21 -6
  22. package/src/hooks/useAssetMeta.ts +166 -0
  23. package/src/hooks/useAssets.ts +23 -0
  24. package/src/hooks/useOccurrences.ts +4 -2
  25. package/src/hooks/usePageBuilder.ts +22 -0
  26. package/src/hooks/usePageContents.ts +8 -1
  27. package/src/hooks/usePages.ts +5 -1
  28. package/src/index.ts +50 -1
  29. package/src/lib/assets.ts +161 -0
  30. package/src/lib/schemaTypes.ts +105 -0
  31. package/src/schema/assetMeta.ts +65 -0
  32. package/src/schema/boardLayout.ts +3 -1
  33. package/src/tools/assets/AssetCard.tsx +86 -0
  34. package/src/tools/assets/AssetDetail.tsx +150 -0
  35. package/src/tools/assets/AssetTable.tsx +122 -0
  36. package/src/tools/assets/AssetsTool.tsx +212 -0
  37. package/src/tools/assets/AssetsToolbar.tsx +98 -0
  38. package/src/tools/assets/FolderSidebar.tsx +177 -0
  39. package/src/tools/createToolComponent.tsx +39 -10
  40. package/src/version.ts +1 -1
  41. package/dist/aiJsonLd-DiYeDzou.js.map +0 -1
  42. package/dist/finalUrl-C1kzYMzQ.js.map +0 -1
@@ -0,0 +1,177 @@
1
+ import {useState} from 'react'
2
+ import {Box, Button, Dialog, Flex, Stack, Text, TextInput} from '@sanity/ui'
3
+ import {AddIcon} from '@sanity/icons/Add'
4
+ import {FolderIcon} from '@sanity/icons/Folder'
5
+ import {EditIcon} from '@sanity/icons/Edit'
6
+ import {TrashIcon} from '@sanity/icons/Trash'
7
+ import type {AssetFolder, FolderSelection} from '../../lib/assets'
8
+ import {TABULAR} from '../../ui/tokens'
9
+
10
+ export interface FolderSidebarProps {
11
+ folders: AssetFolder[]
12
+ counts: Map<string, number>
13
+ total: number
14
+ selection: FolderSelection
15
+ onSelect: (selection: FolderSelection) => void
16
+ onCreate: (name: string) => void
17
+ onRename: (id: string, name: string) => void
18
+ onDelete: (id: string) => void
19
+ }
20
+
21
+ function Row(props: {label: string; count?: number; active: boolean; onClick: () => void; icon?: React.ReactNode; actions?: React.ReactNode}) {
22
+ return (
23
+ <Flex align="center" gap={1}>
24
+ <Button
25
+ mode={props.active ? 'default' : 'bleed'}
26
+ tone={props.active ? 'primary' : 'default'}
27
+ onClick={props.onClick}
28
+ justify="flex-start"
29
+ style={{flex: 1, minWidth: 0}}
30
+ padding={2}
31
+ fontSize={1}
32
+ >
33
+ <Flex align="center" gap={2} style={{width: '100%'}}>
34
+ {props.icon ? <Text size={1}>{props.icon}</Text> : null}
35
+ <Text size={1} textOverflow="ellipsis" style={{flex: 1, textAlign: 'left'}}>
36
+ {props.label}
37
+ </Text>
38
+ {typeof props.count === 'number' ? (
39
+ <Text size={0} muted style={{...TABULAR, flex: 'none'}}>
40
+ {props.count}
41
+ </Text>
42
+ ) : null}
43
+ </Flex>
44
+ </Button>
45
+ {props.actions ? <Box style={{flex: 'none'}}>{props.actions}</Box> : null}
46
+ </Flex>
47
+ )
48
+ }
49
+
50
+ export function FolderSidebar(props: FolderSidebarProps) {
51
+ const {folders, counts, total, selection, onSelect, onCreate, onRename, onDelete} = props
52
+ const [creating, setCreating] = useState(false)
53
+ const [renaming, setRenaming] = useState<AssetFolder | null>(null)
54
+ const [deleting, setDeleting] = useState<AssetFolder | null>(null)
55
+ const [name, setName] = useState('')
56
+
57
+ const openCreate = () => {
58
+ setName('')
59
+ setCreating(true)
60
+ }
61
+ const openRename = (folder: AssetFolder) => {
62
+ setName(folder.name)
63
+ setRenaming(folder)
64
+ }
65
+
66
+ return (
67
+ <Stack gap={2}>
68
+ <Flex align="center" justify="space-between">
69
+ <Text size={1} weight="semibold" muted>
70
+ Dossiers
71
+ </Text>
72
+ <Button icon={AddIcon} mode="bleed" fontSize={1} padding={2} title="Nouveau dossier" aria-label="Nouveau dossier" onClick={openCreate} />
73
+ </Flex>
74
+
75
+ <Stack gap={1}>
76
+ <Row label="Tous les médias" count={total} active={selection === null} onClick={() => onSelect(null)} />
77
+ <Row label="Non classés" count={counts.get('') ?? 0} active={selection === ''} onClick={() => onSelect('')} />
78
+ {folders.map((folder) => (
79
+ <Row
80
+ key={folder.id}
81
+ label={folder.name}
82
+ count={counts.get(folder.id) ?? 0}
83
+ active={selection === folder.id}
84
+ onClick={() => onSelect(folder.id)}
85
+ icon={<FolderIcon />}
86
+ actions={
87
+ <Flex gap={1}>
88
+ <Button icon={EditIcon} mode="bleed" fontSize={0} padding={2} title="Renommer" aria-label="Renommer" onClick={() => openRename(folder)} />
89
+ <Button icon={TrashIcon} mode="bleed" tone="critical" fontSize={0} padding={2} title="Supprimer" aria-label="Supprimer" onClick={() => setDeleting(folder)} />
90
+ </Flex>
91
+ }
92
+ />
93
+ ))}
94
+ </Stack>
95
+
96
+ {creating || renaming ? (
97
+ <Dialog
98
+ id="asset-folder-dialog"
99
+ header={renaming ? 'Renommer le dossier' : 'Nouveau dossier'}
100
+ onClose={() => {
101
+ setCreating(false)
102
+ setRenaming(null)
103
+ }}
104
+ width={0}
105
+ footer={
106
+ <Flex justify="flex-end" gap={2} padding={2}>
107
+ <Button
108
+ text="Annuler"
109
+ mode="bleed"
110
+ onClick={() => {
111
+ setCreating(false)
112
+ setRenaming(null)
113
+ }}
114
+ />
115
+ <Button
116
+ text={renaming ? 'Renommer' : 'Créer'}
117
+ tone="primary"
118
+ disabled={!name.trim()}
119
+ onClick={() => {
120
+ if (renaming) onRename(renaming.id, name)
121
+ else onCreate(name)
122
+ setCreating(false)
123
+ setRenaming(null)
124
+ }}
125
+ />
126
+ </Flex>
127
+ }
128
+ >
129
+ <Box padding={4}>
130
+ <TextInput
131
+ value={name}
132
+ autoFocus
133
+ placeholder="Nom du dossier"
134
+ onChange={(event) => setName(event.currentTarget.value)}
135
+ onKeyDown={(event) => {
136
+ if (event.key === 'Enter' && name.trim()) {
137
+ if (renaming) onRename(renaming.id, name)
138
+ else onCreate(name)
139
+ setCreating(false)
140
+ setRenaming(null)
141
+ }
142
+ }}
143
+ />
144
+ </Box>
145
+ </Dialog>
146
+ ) : null}
147
+
148
+ {deleting ? (
149
+ <Dialog
150
+ id="asset-folder-delete"
151
+ header="Supprimer le dossier"
152
+ onClose={() => setDeleting(null)}
153
+ width={0}
154
+ footer={
155
+ <Flex justify="flex-end" gap={2} padding={2}>
156
+ <Button text="Annuler" mode="bleed" onClick={() => setDeleting(null)} />
157
+ <Button
158
+ text="Supprimer"
159
+ tone="critical"
160
+ onClick={() => {
161
+ onDelete(deleting.id)
162
+ setDeleting(null)
163
+ }}
164
+ />
165
+ </Flex>
166
+ }
167
+ >
168
+ <Box padding={4}>
169
+ <Text size={1}>
170
+ Supprimer « {deleting.name} » ? Les médias qu'il contient ne sont pas supprimés : ils redeviennent « Non classés ».
171
+ </Text>
172
+ </Box>
173
+ </Dialog>
174
+ ) : null}
175
+ </Stack>
176
+ )
177
+ }
@@ -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.49.0'
6
+ export const KIT_VERSION = '2.50.0'
@@ -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;E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Y,IAAI,OAAO,aAAc,YAAY,UAAU,KAAK,GAAG,OAAO,UAAU,KAAK;CACjH,OAAO;AACT;ACtEA,MAAM,WAAmC;CACvC,aAAa;CACb,kBAAkB;CAClB,SAAS;CACT,gBAAgB;CAChB,UAAU;CACV,eAAe;CACf,aAAa;AACf;;;;;;AAOA,eAAsB,eAAe,SAAwB,OAAwD;CACnH,IAAM,WAAW,MAAM,MAAM,GAAG,QAAQ,SAAS,UAAU;EACzD,QAAQ;EACR,SAAS,EAAC,gBAAgB,mBAAkB;EAC5C,MAAM,KAAK,UAAU;GACnB,KAAK,QAAQ;GACb,KAAK,MAAM;GACX,QAAQ,MAAM,UAAU;GACxB,MAAM,MAAM,QAAQ;GACpB,OAAO,MAAM,SAAS;GACtB,SAAS,MAAM;EACjB,CAAC;CACH,CAAC,GACK,OAAQ,MAAM,SAAS,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;CACpD,IAAI,CAAC,SAAS,MAAM,CAAC,KAAK,UAAU,OAAO,KAAK,UAAW,UACzD,MAAU,MAAM,SAAS,KAAK,SAAS,OAAO,+BAA+B,KAAK,SAAS,SAAS,OAAO,GAAG;CAChH,OAAO,KAAK;AACd"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"finalUrl-C1kzYMzQ.js","names":[],"sources":["../src/config/defaults.ts","../src/config/resolve.ts","../src/lib/paths.ts","../src/lib/finalUrl.ts"],"sourcesContent":["import type {\n NcfBoardTag,\n NcfInternalField,\n NcfComponentPreviewConfig,\n NcfI18nConfig,\n NcfToolsConfig,\n} from './types'\n\nexport const DEFAULT_PAGE_BUILDER_FIELD = 'sections'\nexport const DEFAULT_SLUG_FIELD = 'slug'\nexport const DEFAULT_TITLE_FIELD = 'title'\nexport const DEFAULT_BLOCK_NAMESPACE = ''\n\n/**\n * Chemins essayés pour savoir si une page est indexable. Le premier\n * correspond à la convention du starter (`seo.noindex`), le second couvre les\n * schémas qui portent le drapeau à la racine.\n */\nexport const DEFAULT_NOINDEX_FIELDS = ['seo.noindex', 'noindex']\n\n// Aucune langue par défaut : la langue principale (master) vient TOUJOURS du projet\n// (`defaultLocale`, sinon la première de `locales`). Un site peut avoir le français,\n// l'anglais ou toute autre langue comme master.\nexport const DEFAULT_I18N: Omit<Required<NcfI18nConfig>, 'defaultsSourceLocale' | 'defaultLocale'> = {\n field: 'language',\n locales: [],\n}\n\n/**\n * Convention NoCode Factory : page `/design-system` dans le front, captures\n * dans `/sections/<nom>.png` générées au push par GitHub Actions.\n */\nexport const DEFAULT_COMPONENT_PREVIEW: Required<NcfComponentPreviewConfig> = {\n provider: 'designSystemPage',\n path: '/design-system',\n anchor: '{name}',\n thumbnail: '/sections/{name}.png',\n defaultsType: 'componentDefaults',\n live: '/design-system/composant?type={name}',\n}\n\nexport const DEFAULT_TOOLS: Required<NcfToolsConfig> = {\n pages: true,\n components: true,\n history: true,\n designSystem: true,\n}\n\n/**\n * Outils rangés dans « Plus » : Vision (console GROQ) et la planification\n * (« Scheduled drafts » quand les Releases sont désactivées, « Releases » sinon :\n * le même outil, nommé `releases` ; `schedules` couvre les anciennes versions).\n */\nexport const DEFAULT_TOOLBAR_MORE = ['vision', 'releases', 'schedules']\n\n/**\n * Étiquettes de suivi par défaut : l'avancement d'une refonte, pas un statut\n * de publication. Elles vivent dans le document de disposition du kit, donc\n * aucun schéma client n'est modifié.\n */\nexport const DEFAULT_BOARD_TAGS: NcfBoardTag[] = [\n {id: 'en-cours', label: 'In progress', color: '#f5a623'},\n {id: 'fait', label: 'Done', color: '#43d675'},\n {id: 'a-relire', label: 'To review', color: '#2276fc'},\n {id: 'a-refondre', label: 'To rework', color: '#f03e3e'},\n]\n\n/**\n * Colonnes de gestion interne par défaut. Volontairement peu nombreuses : ce\n * sont celles qu'on redemande sur tous les projets. `internalFields` les\n * remplace entièrement.\n */\nexport const DEFAULT_INTERNAL_FIELDS: NcfInternalField[] = [\n {id: 'owner', label: 'Owner', type: 'text'},\n {id: 'audience', label: 'Audience', type: 'text'},\n {id: 'role', label: 'Page role', type: 'text'},\n]\n\n/**\n * Service du kit, hébergé par NoCode Factory.\n *\n * Renseigné d'office pour qu'un Studio n'ait rien à configurer : il se\n * signale au démarrage, et c'est ce qui permet de savoir quels projets\n * utilisent le kit. `endpoint` le remplace pour une instance privée.\n */\nexport const DEFAULT_SERVICE_ENDPOINT = 'https://dkoxgivytgsmvqmjvmjt.supabase.co/functions/v1'\n","import {\n DEFAULT_BLOCK_NAMESPACE,\n DEFAULT_BOARD_TAGS,\n DEFAULT_INTERNAL_FIELDS,\n DEFAULT_SERVICE_ENDPOINT,\n DEFAULT_COMPONENT_PREVIEW,\n DEFAULT_I18N,\n DEFAULT_NOINDEX_FIELDS,\n DEFAULT_PAGE_BUILDER_FIELD,\n DEFAULT_SLUG_FIELD,\n DEFAULT_TITLE_FIELD,\n DEFAULT_TOOLBAR_MORE, DEFAULT_TOOLS,\n} from './defaults'\nimport type {\n NcfEnvironment,\n NcfKitConfig,\n NcfPageTypeConfig,\n ResolvedKitConfig,\n ResolvedPageType,\n} from './types'\n\nconst trimTrailingSlash = (url: string) => url.replace(/\\/+$/, '')\n\n/** Garantit un chemin absolu ('accueil' -> '/accueil', '' -> '/'). */\nexport const normalizePath = (path: string): string => {\n const trimmed = path.trim()\n if (!trimmed || trimmed === '/') return '/'\n const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`\n return withSlash.length > 1 ? trimTrailingSlash(withSlash) : withSlash\n}\n\nfunction resolvePageType(\n entry: NcfPageTypeConfig,\n defaults: {slugField: string; titleField: string},\n): ResolvedPageType {\n if (typeof entry === 'string') {\n return {\n type: entry.trim(),\n slugField: defaults.slugField,\n path: null,\n pathPrefix: null,\n localizedPrefixes: null,\n titleField: defaults.titleField,\n }\n }\n\n // `path` gagne sur `slugField` : une page à chemin fixe (l'accueil) n'a pas\n // de slug à lire, même si le type en porte un par ailleurs.\n const path = typeof entry.path === 'string' ? normalizePath(entry.path) : null\n const slugField =\n entry.slugField === null ? null : (entry.slugField?.trim() || defaults.slugField)\n\n // Un préfixe vide ou '/' vaut « à la racine » : pas de préfixe.\n const prefix = typeof entry.pathPrefix === 'string' ? normalizePath(entry.pathPrefix) : '/'\n\n return {\n type: (entry.type ?? '').trim(),\n slugField: path ? null : slugField,\n path,\n // Conservé même avec `path` (qui gagne au calcul du chemin) : la validation\n // peut ainsi signaler le préfixe inutile.\n pathPrefix: prefix === '/' ? null : prefix,\n localizedPrefixes: entry.localizedPrefixes\n ? Object.fromEntries(Object.entries(entry.localizedPrefixes).map(([l, p]) => [l, normalizePath(p) === '/' ? '' : normalizePath(p)]))\n : null,\n titleField: entry.titleField?.trim() || defaults.titleField,\n }\n}\n\n/** Applique les valeurs par défaut. Ne valide rien : voir `validateConfig`. */\nexport function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {\n const slugField = input.slugField?.trim() || DEFAULT_SLUG_FIELD\n const titleField = input.titleField?.trim() || DEFAULT_TITLE_FIELD\n\n const pageTypes = (Array.isArray(input.pageTypes) ? input.pageTypes : []).map((entry) =>\n resolvePageType(entry, {slugField, titleField}),\n )\n\n const i18n =\n input.i18n === false || input.i18n === undefined\n ? null\n : (() => {\n const locales = (input.i18n.locales ?? DEFAULT_I18N.locales).map((l) => l.trim()).filter(Boolean)\n // Master : `defaultLocale`, sinon la première langue. Jamais une langue écrite\n // dans le kit (absente : signalé par validateConfig).\n const defaultLocale = input.i18n.defaultLocale?.trim() || locales[0] || ''\n return {\n field: input.i18n.field?.trim() || DEFAULT_I18N.field,\n defaultLocale,\n locales,\n // Valeurs par défaut des composants : écrites dans la langue master,\n // traduites vers les autres (sauf choix explicite du projet).\n defaultsSourceLocale: input.i18n.defaultsSourceLocale?.trim() || defaultLocale,\n }\n })()\n\n return {\n pageTypes,\n codedPages: (input.siteRoutes?.fixed ?? [])\n .filter((f) => f.pageSlug && !f.homePage && !f.system && !f.notFound)\n .map((f) => ({pageSlug: f.pageSlug as string, path: normalizePath(f.path), localized: f.localized ?? null})),\n redirectType: input.redirectType?.trim() || 'redirect',\n pageTypeNames: pageTypes.map((p) => p.type).filter(Boolean),\n pageBuilderField: input.pageBuilderField?.trim() || DEFAULT_PAGE_BUILDER_FIELD,\n blockNamespace: input.blockNamespace ?? DEFAULT_BLOCK_NAMESPACE,\n noindexFields: input.noindexField\n ? [input.noindexField].flat().map((field) => field.trim()).filter(Boolean)\n : DEFAULT_NOINDEX_FIELDS,\n previewUrl: input.previewUrl ? trimTrailingSlash(input.previewUrl.trim()) : null,\n environments: resolveEnvironments(input),\n pageThumbnail: input.pageThumbnail?.trim() || null,\n i18n,\n componentPreview: {\n provider: input.componentPreview?.provider ?? DEFAULT_COMPONENT_PREVIEW.provider,\n path: input.componentPreview?.path ?? DEFAULT_COMPONENT_PREVIEW.path,\n anchor: input.componentPreview?.anchor ?? DEFAULT_COMPONENT_PREVIEW.anchor,\n thumbnail: input.componentPreview?.thumbnail ?? DEFAULT_COMPONENT_PREVIEW.thumbnail,\n defaultsType: input.componentPreview?.defaultsType ?? DEFAULT_COMPONENT_PREVIEW.defaultsType,\n live: input.componentPreview?.live ?? DEFAULT_COMPONENT_PREVIEW.live,\n },\n serviceEndpoint:\n input.serviceEndpoint === false\n ? null\n : trimTrailingSlash((input.serviceEndpoint || DEFAULT_SERVICE_ENDPOINT).trim()),\n history: input.history?.projectKey?.trim()\n ? {\n projectKey: input.history.projectKey.trim(),\n endpoint: trimTrailingSlash(\n (input.history.endpoint || input.serviceEndpoint || DEFAULT_SERVICE_ENDPOINT).trim(),\n ),\n }\n : null,\n // Le JSON-LD IA s'appuie sur le même service que la traduction : sans\n // `history.projectKey`, il n'y a pas d'IA à brancher.\n jsonLd:\n input.jsonLd?.enabled && input.history?.projectKey?.trim()\n ? {field: input.jsonLd.field?.trim() || 'jsonLd'}\n : null,\n tools: {...DEFAULT_TOOLS, ...input.tools},\n moreTools: input.moreTools === false ? [] : (input.moreTools ?? DEFAULT_TOOLBAR_MORE),\n boardTags: input.boardTags?.length ? input.boardTags : DEFAULT_BOARD_TAGS,\n internalFields: input.internalFields?.length\n ? input.internalFields\n : DEFAULT_INTERNAL_FIELDS,\n // Additif : le schéma du client fournit déjà l'essentiel, ceci ne sert\n // qu'à ce qu'un parcours de schéma ne sait pas exprimer.\n documentColumns: (input.documentColumns ?? []).map((column) => ({\n key: column.key.trim(),\n label: column.label?.trim() || column.key.trim(),\n paths: [column.path].flat().map((path) => path.trim()).filter(Boolean),\n type: column.type ?? 'text',\n })),\n }\n}\n\n\n/**\n * Préproduction déduite de la production, par convention.\n *\n * NoCode Factory assigne à chaque projet un domaine Vercel **fixe** pour la\n * branche `preprod`, de la forme `preview-<projet>.vercel.app`. Fixe parce\n * qu'un lien de partage doit survivre au commit suivant : une URL de\n * déploiement change à chaque poussée, un domaine assigné non.\n *\n * La déduire évite de la déclarer neuf fois. Elle n'est proposée que pour un\n * hôte Vercel — ailleurs la convention ne s'applique pas — et `environments`\n * la remplace dès qu'on la déclare explicitement.\n */\nexport function conventionalPreprodUrl(previewUrl: string | null): string | null {\n if (!previewUrl) return null\n try {\n const url = new URL(previewUrl)\n if (!url.hostname.endsWith('.vercel.app')) return null\n // Une préproduction ne se dérive pas d'une préproduction.\n if (url.hostname.startsWith('preview-')) return null\n return `${url.protocol}//preview-${url.hostname}`\n } catch {\n return null\n }\n}\n\n/**\n * Environnements d'aperçu.\n *\n * `previewUrl` en fournit toujours un, nommé « Production » : un projet qui\n * n'en déclare pas d'autres doit quand même pouvoir basculer entre brouillons\n * et contenu en ligne.\n *\n * Quand `environments` mentionne déjà `previewUrl`, on ne le double pas.\n */\nfunction resolveEnvironments(input: NcfKitConfig): NcfEnvironment[] {\n const declared = (input.environments ?? [])\n .map((environment) => ({\n id: environment.id.trim(),\n label: environment.label?.trim() || environment.id.trim(),\n url: trimTrailingSlash((environment.url ?? '').trim()),\n }))\n .filter((environment) => environment.id && environment.url)\n\n const preview = input.previewUrl ? trimTrailingSlash(input.previewUrl.trim()) : null\n if (!preview) return declared\n\n const production = declared.some((environment) => environment.url === preview)\n ? []\n : [{id: 'production', label: 'Production', url: preview}]\n\n // La préproduction conventionnelle complète la liste, sauf si le projet en\n // a déjà déclaré une — sa déclaration explicite fait foi.\n //\n // On compare l'identifiant autant que l'URL : un projet dont le domaine ne\n // suit pas exactement la convention déclare bien un `preprod`, à une autre\n // adresse. En n'écartant que par l'URL, on en ajoutait un second portant le\n // même identifiant, et la configuration devenait invalide.\n const conventional = conventionalPreprodUrl(preview)\n const hasPreprod =\n declared.some(\n (environment) => environment.url === conventional || environment.id === 'preprod',\n ) || input.preprodUrl === false\n\n const preprod =\n conventional && !hasPreprod\n ? [{id: 'preprod', label: 'Staging', url: conventional}]\n : []\n\n return [...production, ...preprod, ...declared]\n}\n","import {normalizePath} from '../config/resolve'\nimport type {ResolvedI18n, ResolvedPageType} from '../config/types'\n\nexport interface PathInput {\n /** Valeur du champ slug (`slug.current`). Peut contenir des `/`. */\n slug?: string | null\n /** Chemin fixe du type de page, s'il en a un. */\n path?: string | null\n /** Préfixe d'URL du type de page ('/blog'), devant le slug. */\n pathPrefix?: string | null\n /** Préfixe par langue (dossiers traduits) : celui de `locale` gagne sur `pathPrefix`. */\n localizedPrefixes?: Record<string, string> | null\n /** Langue du document. */\n locale?: string | null\n}\n\n/**\n * Chemin d'une page sur le site. Le chemin fixe l'emporte sur le slug, le\n * préfixe du type se place devant le slug ('/blog' + 'mon-article'), et la\n * langue par défaut n'est pas préfixée (convention Next.js du starter).\n */\nexport function toPath(input: PathInput, i18n: ResolvedI18n | null): string | null {\n const localized = input.locale ? input.localizedPrefixes?.[input.locale] : undefined\n const raw = localized !== undefined ? localized : input.pathPrefix\n const prefix = typeof raw === 'string' && raw ? normalizePath(raw) : '/'\n const base =\n typeof input.path === 'string' && input.path\n ? normalizePath(input.path)\n : input.slug\n ? normalizePath(prefix === '/' ? input.slug : `${prefix}/${input.slug.replace(/^\\/+/, '')}`)\n : null\n\n if (base === null) return null\n if (!i18n || !input.locale || input.locale === i18n.defaultLocale) return base\n return base === '/' ? `/${input.locale}` : `/${input.locale}${base}`\n}\n\n/** URL absolue d'une page, ou `null` si le front n'est pas configuré. */\nexport function toUrl(previewUrl: string | null, path: string | null): string | null {\n if (!previewUrl || path === null) return null\n return path === '/' ? previewUrl : `${previewUrl}${path}`\n}\n\n/** Segments d'un chemin : '/services/plomberie' -> ['services', 'plomberie']. */\nexport function segments(path: string): string[] {\n return path.split('/').filter(Boolean)\n}\n\n/** Profondeur dans l'arborescence. '/' vaut 0. */\nexport function depth(path: string): number {\n return segments(path).length\n}\n\n/**\n * Chemin du parent, ou `null` à la racine. Sert au placement automatique du\n * board : '/services/plomberie' -> '/services'.\n */\nexport function parentPath(path: string): string | null {\n const parts = segments(path)\n if (parts.length === 0) return null\n if (parts.length === 1) return '/'\n return `/${parts.slice(0, -1).join('/')}`\n}\n\n/** Le type de page correspondant à un document. */\nexport function pageTypeFor(\n type: string,\n pageTypes: ResolvedPageType[],\n): ResolvedPageType | undefined {\n return pageTypes.find((p) => p.type === type)\n}\n","import type {ResolvedKitConfig, ResolvedPageType} from '../config/types'\nimport {toPath} from './paths'\n\n/** Clé de comparaison des redirections (comme le site) : minuscules, sans « / » final, sans ? ni #. */\nexport const redirectKey = (path: string) => {\n const clean = (path.trim().split(/[?#]/)[0] ?? '').toLowerCase()\n return clean.length > 1 ? clean.replace(/\\/+$/, '') : clean\n}\n\n/** Table des redirections du Studio : départ (normalisé) -> destination. */\nexport type RedirectMap = Map<string, string>\n\nexport function redirectMapOf(rows: readonly {from?: string | null; to?: string | null}[]): RedirectMap {\n const map: RedirectMap = new Map()\n for (const r of rows) {\n if (!r.from?.startsWith('/') || !r.to) continue\n const key = redirectKey(r.from)\n if (key !== redirectKey(r.to) && !map.has(key)) map.set(key, r.to.trim())\n }\n return map\n}\n\n/** Destination finale d'une adresse (chaîne de redirections suivie, boucles ignorées). */\nexport function followRedirects(path: string, redirects: RedirectMap | null | undefined): string {\n if (!redirects?.size) return path\n let current = path\n const seen = new Set<string>()\n for (let hop = 0; hop < 5; hop++) {\n const next = redirects.get(redirectKey(current))\n if (!next || seen.has(next)) break\n seen.add(next)\n current = next\n }\n return current\n}\n\n/**\n * URL FINALE d'une page (celle qui répond 200, sans redirection) : adresse réelle\n * d'une page codée (registre `siteRoutes`, dossier de la langue), sinon dossier et\n * slug de la langue ; puis destination si l'adresse est le départ d'une redirection\n * du Studio. Affichée partout dans le kit (onglet Pages, board, Presentation, slug).\n */\nexport function finalPath(\n input: {slug: string | null; locale: string | null},\n pageType: ResolvedPageType | null | undefined,\n config: Pick<ResolvedKitConfig, 'i18n' | 'codedPages'>,\n redirects?: RedirectMap | null,\n): string | null {\n if (!pageType) return null\n const atRoot = !pageType.path && !pageType.pathPrefix && !pageType.localizedPrefixes\n const coded = atRoot && input.slug ? config.codedPages.find((c) => c.pageSlug === input.slug) : undefined\n const path = coded\n ? toPath({path: (input.locale && coded.localized?.[input.locale]) || coded.path, locale: input.locale}, config.i18n)\n : toPath(\n {slug: input.slug, path: pageType.path, pathPrefix: pageType.pathPrefix, localizedPrefixes: pageType.localizedPrefixes, locale: input.locale},\n config.i18n,\n )\n return path === null ? null : followRedirects(path, redirects)\n}\n"],"mappings":"AAQA,MAAa,6BAA6B,YAC7B,qBAAqB,QACrB,sBAAsB,SAQtB,yBAAyB,CAAC,eAAe,SAAS,GAKlD,eAAwF;CACnG,OAAO;CACP,SAAS,CAAC;AACZ,GAMa,4BAAiE;CAC5E,UAAU;CACV,MAAM;CACN,QAAQ;CACR,WAAW;CACX,cAAc;CACd,MAAM;AACR,GAEa,gBAA0C;CACrD,OAAO;CACP,YAAY;CACZ,SAAS;CACT,cAAc;AAChB,GAOa,uBAAuB;CAAC;CAAU;CAAY;AAAW,GAOzD,qBAAoC;CAC/C;EAAC,IAAI;EAAY,OAAO;EAAe,OAAO;CAAS;CACvD;EAAC,IAAI;EAAQ,OAAO;EAAQ,OAAO;CAAS;CAC5C;EAAC,IAAI;EAAY,OAAO;EAAa,OAAO;CAAS;CACrD;EAAC,IAAI;EA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