@prunellejs/cms 0.0.0-stage → 0.5.3

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.
@@ -0,0 +1,150 @@
1
+ // Self-contained Markdown preview renderer and strict HTML allowlist sanitizer for @prunellejs/cms.
2
+
3
+ const STRIP_BLOCK_RE = /<(script|style|iframe|object|embed|applet|noscript|template|svg|math|form)(?=[\s/>])[^>]*>[\s\S]*?<\/\1(?:[\s/][^>]*)?>/gi
4
+ const STRIP_VOID_DANGEROUS_RE = /<(script|style|iframe|object|embed|applet|noscript|template|svg|math|form|base|link|meta)(?=[\s/>])[^>]*\/?>/gi
5
+ const COMMENT_RE = /<!--[\s\S]*?(?:--!?>|$)/g
6
+
7
+ const SAFE_TAGS = new Set([
8
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
9
+ 'p', 'br', 'hr', 'blockquote', 'pre', 'code',
10
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
11
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
12
+ 'a', 'img', 'strong', 'em', 'b', 'i', 'u', 's', 'del', 'ins',
13
+ 'sup', 'sub', 'kbd', 'mark', 'abbr', 'small', 'time',
14
+ 'details', 'summary', 'figure', 'figcaption', 'div', 'span', 'input',
15
+ ])
16
+
17
+ const ALLOWED_ATTRS_BY_TAG: Readonly<Record<string, ReadonlySet<string>>> = {
18
+ a: new Set(['href', 'title', 'rel', 'target']),
19
+ img: new Set(['src', 'alt', 'title', 'width', 'height']),
20
+ th: new Set(['colspan', 'rowspan', 'scope', 'align']),
21
+ td: new Set(['colspan', 'rowspan', 'align']),
22
+ ol: new Set(['start', 'reversed']),
23
+ li: new Set(['value']),
24
+ details: new Set(['open']),
25
+ time: new Set(['datetime']),
26
+ input: new Set(['type', 'checked', 'disabled']),
27
+ code: new Set(['class']),
28
+ pre: new Set(['class']),
29
+ }
30
+
31
+ const URL_PROTOCOL_OK = /^(?:https?:|mailto:|tel:|#|\/|\.)/i
32
+ const SAFE_DATA_IMG = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
33
+ const SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/i
34
+
35
+ function safeCodePoint(raw: string, radix: number): string {
36
+ const cp = Number.parseInt(raw, radix)
37
+ return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
38
+ }
39
+
40
+ function escapeAttrValue(val: string): string {
41
+ return val
42
+ .replaceAll('"', '&quot;')
43
+ .replaceAll('\'', '&#39;')
44
+ .replaceAll('<', '&lt;')
45
+ .replaceAll('>', '&gt;')
46
+ }
47
+
48
+ function isUrlAllowed(raw: string): boolean {
49
+ const decoded = raw
50
+ .replace(/&#x([0-9a-f]+);?/gi, (_, h: string) => safeCodePoint(h, 16))
51
+ .replace(/&#(\d+);?/g, (_, d: string) => safeCodePoint(d, 10))
52
+ .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
53
+ const lower = name.toLowerCase()
54
+ if (lower === 'colon') return ':'
55
+ if (lower === 'tab') return '\t'
56
+ if (lower === 'newline') return '\n'
57
+ return '&'
58
+ })
59
+ .replace(/[\u0000-\u0020\u007F]+/g, '')
60
+ .trim()
61
+ if (decoded === '')
62
+ return true
63
+ if (URL_PROTOCOL_OK.test(decoded) || SAFE_DATA_IMG.test(decoded))
64
+ return true
65
+ return !SCHEME_PREFIX.test(decoded)
66
+ }
67
+
68
+ const ATTR_PAIR_RE = /([a-zA-Z_:][a-zA-Z0-9_.:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g
69
+
70
+ function filterTagAttributes(tag: string, rawAttrs: string): string {
71
+ const allowed = ALLOWED_ATTRS_BY_TAG[tag]
72
+ if (allowed === undefined || rawAttrs.trim() === '')
73
+ return ''
74
+
75
+ const kept: string[] = []
76
+ ATTR_PAIR_RE.lastIndex = 0
77
+ let match = ATTR_PAIR_RE.exec(rawAttrs)
78
+ while (match !== null) {
79
+ const attrName = match[1]!.toLowerCase()
80
+ const attrVal = match[2] ?? match[3] ?? match[4] ?? null
81
+ if (allowed.has(attrName)) {
82
+ if (tag === 'input' && attrName === 'type' && attrVal?.toLowerCase() !== 'checkbox') {
83
+ match = ATTR_PAIR_RE.exec(rawAttrs)
84
+ continue
85
+ }
86
+ if ((attrName === 'href' || attrName === 'src') && attrVal !== null && !isUrlAllowed(attrVal)) {
87
+ match = ATTR_PAIR_RE.exec(rawAttrs)
88
+ continue
89
+ }
90
+ kept.push(attrVal === null ? attrName : `${attrName}="${escapeAttrValue(attrVal)}"`)
91
+ }
92
+ match = ATTR_PAIR_RE.exec(rawAttrs)
93
+ }
94
+
95
+ if (tag === 'input') {
96
+ if (!kept.some(entry => entry.startsWith('type=')))
97
+ return ''
98
+ if (!kept.includes('disabled'))
99
+ kept.push('disabled')
100
+ }
101
+
102
+ return kept.length > 0 ? ` ${kept.join(' ')}` : ''
103
+ }
104
+
105
+ function sanitizePreviewPass(html: string): string {
106
+ const withoutDangerous = html
107
+ .replace(COMMENT_RE, '')
108
+ .replace(STRIP_BLOCK_RE, '')
109
+ .replace(STRIP_VOID_DANGEROUS_RE, '')
110
+
111
+ return withoutDangerous.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([\s/][^>]*?)?(\/?)>/g, (_whole, slash: string, rawTag: string, rawAttrs: string | undefined, selfClose: string) => {
112
+ const tag = rawTag.toLowerCase()
113
+ if (!SAFE_TAGS.has(tag))
114
+ return ''
115
+ if (slash === '/')
116
+ return `</${tag}>`
117
+ const raw = rawAttrs ?? ''
118
+ const isSelfClose = selfClose === '/' || /\/\s*$/.test(raw)
119
+ const cleanedRaw = selfClose === '' && isSelfClose ? raw.replace(/\/\s*$/, '') : raw
120
+ const attrs = filterTagAttributes(tag, cleanedRaw)
121
+ if (tag === 'input' && attrs === '')
122
+ return ''
123
+ return `<${tag}${attrs}${isSelfClose ? ' /' : ''}>`
124
+ })
125
+ }
126
+
127
+ /** Sanitizes HTML rendered from Markdown using a strict element and attribute allowlist. */
128
+ export function sanitizePreviewHtml(html: string): string {
129
+ let current = html
130
+ for (let pass = 0; pass < 3; pass++) {
131
+ const next = sanitizePreviewPass(current)
132
+ if (next === current)
133
+ return next
134
+ current = next
135
+ }
136
+ return current
137
+ }
138
+
139
+ /** Renders Markdown to sanitized HTML using Bun's native Zig Markdown engine. */
140
+ export function renderMarkdownPreview(markdown: string): string {
141
+ if (markdown.trim() === '')
142
+ return ''
143
+ const rawHtml = Bun.markdown.html(markdown, {
144
+ tables: true,
145
+ strikethrough: true,
146
+ tasklists: true,
147
+ autolinks: true,
148
+ })
149
+ return sanitizePreviewHtml(rawHtml)
150
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,487 @@
1
+ // JSON Schema extraction and field-model builder for @prunellejs/cms.
2
+ // Maps Standard Schema JSON Schema output into typed form fields and reports unsupported constructs in `prunelle check`.
3
+
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+
6
+ export type CmsFieldKind =
7
+ | 'text'
8
+ | 'textarea'
9
+ | 'date'
10
+ | 'datetime'
11
+ | 'email'
12
+ | 'url'
13
+ | 'number'
14
+ | 'integer'
15
+ | 'boolean'
16
+ | 'enum'
17
+ | 'tags'
18
+ | 'object'
19
+ | 'object-array'
20
+
21
+ export interface CmsField {
22
+ readonly key: string
23
+ readonly path: string
24
+ readonly label: string
25
+ readonly kind: CmsFieldKind
26
+ readonly required: boolean
27
+ readonly nullable: boolean
28
+ readonly description?: string | undefined
29
+ readonly defaultValue?: unknown
30
+ readonly min?: number | undefined
31
+ readonly max?: number | undefined
32
+ readonly step?: string | undefined
33
+ readonly minLength?: number | undefined
34
+ readonly maxLength?: number | undefined
35
+ readonly pattern?: string | undefined
36
+ readonly options?: readonly (string | number)[] | undefined
37
+ readonly enumType?: 'string' | 'number' | undefined
38
+ readonly fields?: readonly CmsField[] | undefined
39
+ }
40
+
41
+ export interface CmsSchemaIssue {
42
+ readonly path: string
43
+ readonly message: string
44
+ }
45
+
46
+ export interface ParsedCmsSchema {
47
+ readonly fields: readonly CmsField[]
48
+ readonly issues: readonly CmsSchemaIssue[]
49
+ }
50
+
51
+ interface JsonSchemaLike {
52
+ type?: string | readonly string[] | undefined
53
+ format?: string | undefined
54
+ title?: string | undefined
55
+ description?: string | undefined
56
+ default?: unknown
57
+ enum?: readonly unknown[] | undefined
58
+ const?: unknown
59
+ contentMediaType?: string | undefined
60
+ minimum?: number | undefined
61
+ maximum?: number | undefined
62
+ minLength?: number | undefined
63
+ maxLength?: number | undefined
64
+ pattern?: string | undefined
65
+ properties?: Record<string, unknown> | undefined
66
+ required?: readonly string[] | undefined
67
+ items?: unknown
68
+ anyOf?: readonly unknown[] | undefined
69
+ oneOf?: readonly unknown[] | undefined
70
+ allOf?: readonly unknown[] | undefined
71
+ $ref?: string | undefined
72
+ $defs?: Record<string, unknown> | undefined
73
+ definitions?: Record<string, unknown> | undefined
74
+ }
75
+
76
+ interface SchemaCandidate {
77
+ '~standard'?: {
78
+ jsonSchema?: {
79
+ input?: (opts: { target: string }) => unknown
80
+ } | undefined
81
+ } | undefined
82
+ toJSONSchema?: (() => unknown) | undefined
83
+ jsonSchema?: unknown
84
+ }
85
+
86
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
87
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
88
+ }
89
+
90
+ /** Extracts a raw JSON Schema object from a Standard Schema, returning `undefined` when unavailable. */
91
+ export function extractJsonSchema(schema: StandardSchemaV1): Record<string, unknown> | undefined {
92
+ const candidate = schema as unknown as SchemaCandidate
93
+ const stdInput = candidate['~standard']?.jsonSchema?.input
94
+ if (typeof stdInput === 'function') {
95
+ for (const target of ['draft-2020-12', 'draft-07']) {
96
+ let result: unknown
97
+ try {
98
+ result = stdInput({ target })
99
+ }
100
+ catch (err) {
101
+ result = err instanceof Error ? undefined : undefined
102
+ }
103
+ if (isPlainRecord(result))
104
+ return result
105
+ }
106
+ }
107
+
108
+ if (typeof candidate.toJSONSchema === 'function') {
109
+ let result: unknown
110
+ try {
111
+ result = candidate.toJSONSchema()
112
+ }
113
+ catch (err) {
114
+ result = err instanceof Error ? undefined : undefined
115
+ }
116
+ if (isPlainRecord(result))
117
+ return result
118
+ }
119
+
120
+ if (isPlainRecord(candidate.jsonSchema))
121
+ return candidate.jsonSchema
122
+
123
+ return undefined
124
+ }
125
+
126
+ /** Formats a property key into a readable label (e.g. `publishedAt` -> `Published At`, `seo_title` -> `Seo Title`). */
127
+ export function humanizeKey(key: string): string {
128
+ const spaced = key
129
+ .replace(/[_-]+/g, ' ')
130
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
131
+ .trim()
132
+ if (spaced.length === 0)
133
+ return key
134
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
135
+ }
136
+
137
+ function isNullSchema(node: unknown): boolean {
138
+ return isPlainRecord(node) && (node.type === 'null' || node.const === null)
139
+ }
140
+
141
+ function resolveRef(ref: string, root: JsonSchemaLike): JsonSchemaLike | undefined {
142
+ if (!ref.startsWith('#/'))
143
+ return undefined
144
+ const parts = ref.slice(2).split('/')
145
+ let cur: unknown = root
146
+ for (const part of parts) {
147
+ if (!isPlainRecord(cur))
148
+ return undefined
149
+ cur = cur[part.replace(/~1/g, '/').replace(/~0/g, '~')]
150
+ }
151
+ return isPlainRecord(cur) ? (cur as JsonSchemaLike) : undefined
152
+ }
153
+
154
+ interface UnwrapResult {
155
+ schema?: JsonSchemaLike | undefined
156
+ nullable: boolean
157
+ error?: string | undefined
158
+ }
159
+
160
+ function unwrapSchema(raw: unknown, root: JsonSchemaLike, seenRefs: Set<string>): UnwrapResult {
161
+ if (!isPlainRecord(raw))
162
+ return { nullable: false, error: 'schema definition is not an object' }
163
+
164
+ let node = raw as JsonSchemaLike
165
+ let nullable = false
166
+
167
+ if (typeof node.$ref === 'string') {
168
+ if (seenRefs.has(node.$ref))
169
+ return { nullable: false, error: `recursive $ref "${node.$ref}" is not supported` }
170
+ const resolved = resolveRef(node.$ref, root)
171
+ if (resolved === undefined)
172
+ return { nullable: false, error: `unresolvable $ref "${node.$ref}"` }
173
+ const nextRefs = new Set(seenRefs)
174
+ nextRefs.add(node.$ref)
175
+ const inner = unwrapSchema(resolved, root, nextRefs)
176
+ if (inner.error !== undefined || inner.schema === undefined)
177
+ return inner
178
+ node = {
179
+ ...inner.schema,
180
+ ...(node.title !== undefined ? { title: node.title } : {}),
181
+ ...(node.description !== undefined ? { description: node.description } : {}),
182
+ ...(node.default !== undefined ? { default: node.default } : {}),
183
+ }
184
+ nullable = nullable || inner.nullable
185
+ }
186
+
187
+ const union = node.anyOf ?? node.oneOf
188
+ if (Array.isArray(union)) {
189
+ const keyword = node.anyOf !== undefined ? 'anyOf' : 'oneOf'
190
+ const nonNull = union.filter(branch => !isNullSchema(branch))
191
+ if (nonNull.length < union.length)
192
+ nullable = true
193
+ if (nonNull.length !== 1)
194
+ return { nullable, error: `unsupported ${keyword} union with ${nonNull.length} non-null branches` }
195
+ const inner = unwrapSchema(nonNull[0], root, seenRefs)
196
+ if (inner.error !== undefined || inner.schema === undefined)
197
+ return inner
198
+ node = {
199
+ ...inner.schema,
200
+ ...(node.title !== undefined ? { title: node.title } : {}),
201
+ ...(node.description !== undefined ? { description: node.description } : {}),
202
+ ...(node.default !== undefined ? { default: node.default } : {}),
203
+ }
204
+ nullable = nullable || inner.nullable
205
+ }
206
+
207
+ if (Array.isArray(node.allOf)) {
208
+ if (node.allOf.length !== 1)
209
+ return { nullable, error: `unsupported allOf intersection with ${node.allOf.length} branches` }
210
+ const inner = unwrapSchema(node.allOf[0], root, seenRefs)
211
+ if (inner.error !== undefined || inner.schema === undefined)
212
+ return inner
213
+ node = { ...inner.schema, ...(node.title !== undefined ? { title: node.title } : {}), ...(node.description !== undefined ? { description: node.description } : {}) }
214
+ nullable = nullable || inner.nullable
215
+ }
216
+
217
+ if (Array.isArray(node.type)) {
218
+ const nonNull = node.type.filter(t => t !== 'null')
219
+ if (nonNull.length < node.type.length)
220
+ nullable = true
221
+ if (nonNull.length !== 1)
222
+ return { nullable, error: `unsupported multi-type union [${node.type.join(', ')}]` }
223
+ node = { ...node, type: nonNull[0] }
224
+ }
225
+
226
+ return { schema: node, nullable }
227
+ }
228
+
229
+ function resolveStringKind(node: JsonSchemaLike): CmsFieldKind {
230
+ if (node.contentMediaType === 'text/markdown')
231
+ return 'textarea'
232
+ if (node.format === 'date')
233
+ return 'date'
234
+ if (node.format === 'date-time')
235
+ return 'datetime'
236
+ if (node.format === 'email')
237
+ return 'email'
238
+ if (node.format === 'uri' || node.format === 'url')
239
+ return 'url'
240
+ return 'text'
241
+ }
242
+
243
+ function buildEnumField(
244
+ key: string,
245
+ path: string,
246
+ node: JsonSchemaLike,
247
+ required: boolean,
248
+ nullable: boolean,
249
+ issues: CmsSchemaIssue[],
250
+ ): CmsField | undefined {
251
+ const rawValues = node.enum ?? (node.const !== undefined ? [node.const] : [])
252
+ const nonNull = rawValues.filter(v => v !== null)
253
+ const isNullable = nullable || nonNull.length < rawValues.length
254
+ if (nonNull.length === 0) {
255
+ issues.push({ path, message: 'enum has no selectable values' })
256
+ return undefined
257
+ }
258
+ const allStrings = nonNull.every(v => typeof v === 'string')
259
+ const allNumbers = nonNull.every(v => typeof v === 'number' && Number.isFinite(v))
260
+ if (!allStrings && !allNumbers) {
261
+ issues.push({ path, message: 'enum must contain only strings or only finite numbers' })
262
+ return undefined
263
+ }
264
+ return {
265
+ key,
266
+ path,
267
+ label: typeof node.title === 'string' && node.title.length > 0 ? node.title : humanizeKey(key),
268
+ kind: 'enum',
269
+ required,
270
+ nullable: isNullable,
271
+ description: typeof node.description === 'string' ? node.description : undefined,
272
+ defaultValue: node.default,
273
+ options: nonNull as (string | number)[],
274
+ enumType: allNumbers ? 'number' : 'string',
275
+ }
276
+ }
277
+
278
+ function buildArrayField(
279
+ key: string,
280
+ path: string,
281
+ node: JsonSchemaLike,
282
+ required: boolean,
283
+ nullable: boolean,
284
+ root: JsonSchemaLike,
285
+ seenRefs: Set<string>,
286
+ issues: CmsSchemaIssue[],
287
+ depth: number,
288
+ ): CmsField | undefined {
289
+ if (node.items === undefined || Array.isArray(node.items)) {
290
+ issues.push({ path, message: 'array field must declare a single `items` schema (tuples are unsupported)' })
291
+ return undefined
292
+ }
293
+ const itemUnwrap = unwrapSchema(node.items, root, seenRefs)
294
+ if (itemUnwrap.error !== undefined || itemUnwrap.schema === undefined) {
295
+ issues.push({ path, message: `array item schema is unsupported (${itemUnwrap.error ?? 'unknown'})` })
296
+ return undefined
297
+ }
298
+ const item = itemUnwrap.schema
299
+ const label = typeof node.title === 'string' && node.title.length > 0 ? node.title : humanizeKey(key)
300
+ const description = typeof node.description === 'string' ? node.description : undefined
301
+
302
+ if (item.type === 'string' || (Array.isArray(item.enum) && item.enum.every(v => typeof v === 'string'))) {
303
+ return {
304
+ key,
305
+ path,
306
+ label,
307
+ kind: 'tags',
308
+ required,
309
+ nullable,
310
+ description,
311
+ defaultValue: node.default,
312
+ }
313
+ }
314
+
315
+ if (item.type === 'object' && isPlainRecord(item.properties)) {
316
+ if (depth > 0) {
317
+ issues.push({ path, message: 'nested arrays of objects are not supported' })
318
+ return undefined
319
+ }
320
+ const childFields = parseObjectProperties(item, `${path}[]`, root, seenRefs, issues, depth + 1)
321
+ return {
322
+ key,
323
+ path,
324
+ label,
325
+ kind: 'object-array',
326
+ required,
327
+ nullable,
328
+ description,
329
+ defaultValue: node.default,
330
+ fields: childFields,
331
+ }
332
+ }
333
+
334
+ const itemDesc = typeof item.type === 'string' ? `array of ${item.type}` : 'array of unsupported items'
335
+ issues.push({ path, message: `${itemDesc} is not supported (only string[] and object[] with properties are supported)` })
336
+ return undefined
337
+ }
338
+
339
+ function buildField(
340
+ key: string,
341
+ path: string,
342
+ rawProp: unknown,
343
+ required: boolean,
344
+ root: JsonSchemaLike,
345
+ seenRefs: Set<string>,
346
+ issues: CmsSchemaIssue[],
347
+ depth: number,
348
+ ): CmsField | undefined {
349
+ const unwrapped = unwrapSchema(rawProp, root, seenRefs)
350
+ if (unwrapped.error !== undefined || unwrapped.schema === undefined) {
351
+ issues.push({ path, message: unwrapped.error ?? 'unsupported schema construct' })
352
+ return undefined
353
+ }
354
+ const node = unwrapped.schema
355
+ const { nullable } = unwrapped
356
+ const label = typeof node.title === 'string' && node.title.length > 0 ? node.title : humanizeKey(key)
357
+ const description = typeof node.description === 'string' ? node.description : undefined
358
+
359
+ if (Array.isArray(node.enum) || node.const !== undefined)
360
+ return buildEnumField(key, path, node, required, nullable, issues)
361
+
362
+ if (node.type === 'string') {
363
+ return {
364
+ key,
365
+ path,
366
+ label,
367
+ kind: resolveStringKind(node),
368
+ required,
369
+ nullable,
370
+ description,
371
+ defaultValue: node.default,
372
+ minLength: typeof node.minLength === 'number' ? node.minLength : undefined,
373
+ maxLength: typeof node.maxLength === 'number' ? node.maxLength : undefined,
374
+ pattern: typeof node.pattern === 'string' ? node.pattern : undefined,
375
+ }
376
+ }
377
+
378
+ if (node.type === 'boolean') {
379
+ return {
380
+ key,
381
+ path,
382
+ label,
383
+ kind: 'boolean',
384
+ required,
385
+ nullable,
386
+ description,
387
+ defaultValue: node.default,
388
+ }
389
+ }
390
+
391
+ if (node.type === 'number' || node.type === 'integer') {
392
+ return {
393
+ key,
394
+ path,
395
+ label,
396
+ kind: node.type,
397
+ required,
398
+ nullable,
399
+ description,
400
+ defaultValue: node.default,
401
+ min: typeof node.minimum === 'number' ? node.minimum : undefined,
402
+ max: typeof node.maximum === 'number' ? node.maximum : undefined,
403
+ step: node.type === 'integer' ? '1' : 'any',
404
+ }
405
+ }
406
+
407
+ if (node.type === 'array')
408
+ return buildArrayField(key, path, node, required, nullable, root, seenRefs, issues, depth)
409
+
410
+ if (node.type === 'object' || isPlainRecord(node.properties)) {
411
+ if (!isPlainRecord(node.properties)) {
412
+ issues.push({ path, message: 'object field must declare explicit `properties`' })
413
+ return undefined
414
+ }
415
+ const childFields = parseObjectProperties(node, path, root, seenRefs, issues, depth)
416
+ return {
417
+ key,
418
+ path,
419
+ label,
420
+ kind: 'object',
421
+ required,
422
+ nullable,
423
+ description,
424
+ defaultValue: node.default,
425
+ fields: childFields,
426
+ }
427
+ }
428
+
429
+ issues.push({ path, message: `unsupported or untyped field schema (type: ${String(node.type ?? 'none')})` })
430
+ return undefined
431
+ }
432
+
433
+ function parseObjectProperties(
434
+ node: JsonSchemaLike,
435
+ prefix: string,
436
+ root: JsonSchemaLike,
437
+ seenRefs: Set<string>,
438
+ issues: CmsSchemaIssue[],
439
+ depth: number,
440
+ ): CmsField[] {
441
+ const props = isPlainRecord(node.properties) ? node.properties : {}
442
+ const requiredSet = new Set(Array.isArray(node.required) ? node.required.filter((r): r is string => typeof r === 'string') : [])
443
+ const fields: CmsField[] = []
444
+ for (const [key, rawProp] of Object.entries(props)) {
445
+ const fieldPath = prefix === '' ? key : `${prefix}.${key}`
446
+ const field = buildField(key, fieldPath, rawProp, requiredSet.has(key), root, seenRefs, issues, depth)
447
+ if (field !== undefined)
448
+ fields.push(field)
449
+ }
450
+ return fields
451
+ }
452
+
453
+ /** Parses a root JSON Schema object into CMS fields and collects any unsupported construct issues. */
454
+ export function parseJsonSchemaFields(rawSchema: Record<string, unknown>): ParsedCmsSchema {
455
+ const issues: CmsSchemaIssue[] = []
456
+ const root = rawSchema as JsonSchemaLike
457
+ const unwrapped = unwrapSchema(root, root, new Set())
458
+ if (unwrapped.error !== undefined || unwrapped.schema === undefined) {
459
+ issues.push({ path: '$', message: unwrapped.error ?? 'root schema is invalid' })
460
+ return { fields: [], issues }
461
+ }
462
+ const node = unwrapped.schema
463
+ if (node.type !== undefined && node.type !== 'object') {
464
+ issues.push({ path: '$', message: `root frontmatter schema must be an object (got "${String(node.type)}")` })
465
+ return { fields: [], issues }
466
+ }
467
+ if (!isPlainRecord(node.properties)) {
468
+ issues.push({ path: '$', message: 'root frontmatter schema must declare `properties`' })
469
+ return { fields: [], issues }
470
+ }
471
+ const fields = parseObjectProperties(node, '', root, new Set(), issues, 0)
472
+ return { fields, issues }
473
+ }
474
+
475
+ /** Validates a collection's Standard Schema for CMS compatibility, returning human-readable errors naming collection & field. */
476
+ export function checkCollectionSchema(collectionName: string, schema: StandardSchemaV1): string[] {
477
+ const jsonSchema = extractJsonSchema(schema)
478
+ if (jsonSchema === undefined) {
479
+ return [
480
+ `prunelle check (@prunellejs/cms): collection "${collectionName}" schema does not expose JSON Schema output (~standard.jsonSchema, toJSONSchema(), or jsonSchema). Use a Standard JSON Schema validator (Zod 4, Valibot, ArkType) or attach a jsonSchema object.`,
481
+ ]
482
+ }
483
+ const { issues } = parseJsonSchemaFields(jsonSchema)
484
+ return issues.map(issue =>
485
+ `prunelle check (@prunellejs/cms): collection "${collectionName}" field "${issue.path}" is not supported by the CMS: ${issue.message}.`,
486
+ )
487
+ }