@prunellejs/content 0.0.0-stage → 0.6.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.
@@ -0,0 +1,309 @@
1
+ // HTML allow-list sanitizer applied to rendered Markdown: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
2
+
3
+ const DROP_CONTENT_TAGS = new Set([
4
+ 'script',
5
+ 'style',
6
+ 'iframe',
7
+ 'object',
8
+ 'applet',
9
+ 'noscript',
10
+ 'template',
11
+ ])
12
+
13
+ const ALLOWED_MD_TAGS = new Set([
14
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
15
+ 'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
16
+ 'a', 'img', 'picture', 'source',
17
+ 'pre', 'code', 'kbd', 'samp', 'var',
18
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
19
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
20
+ 'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
21
+ 'details', 'summary', 'figure', 'figcaption',
22
+ 'input',
23
+ ])
24
+
25
+ // Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
26
+ const GLOBAL_ALLOWED_ATTRS = new Set([
27
+ 'class',
28
+ 'title',
29
+ 'lang',
30
+ 'dir',
31
+ 'role',
32
+ 'aria-label',
33
+ 'aria-hidden',
34
+ 'aria-current',
35
+ 'aria-expanded',
36
+ 'aria-level',
37
+ 'aria-description',
38
+ 'aria-roledescription',
39
+ ])
40
+
41
+ const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
42
+ a: new Set(['href', 'rel', 'target', 'hreflang']),
43
+ img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
44
+ source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
45
+ blockquote: new Set(['cite']),
46
+ q: new Set(['cite']),
47
+ del: new Set(['cite', 'datetime']),
48
+ ins: new Set(['cite', 'datetime']),
49
+ time: new Set(['datetime']),
50
+ ol: new Set(['start', 'reversed', 'type']),
51
+ li: new Set(['value']),
52
+ th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
53
+ td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
54
+ col: new Set(['span', 'align']),
55
+ colgroup: new Set(['span', 'align']),
56
+ details: new Set(['open']),
57
+ }
58
+
59
+ const URL_ATTRS = new Set(['href', 'src', 'cite'])
60
+ const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
61
+ const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
62
+ const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
63
+
64
+ function decodeHtmlEntities(rawVal: string): string {
65
+ return rawVal
66
+ .replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
67
+ const cp = Number.parseInt(hex, 16)
68
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
69
+ })
70
+ .replace(/&#([0-9]+);?/g, (_, dec: string) => {
71
+ const cp = Number.parseInt(dec, 10)
72
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
73
+ })
74
+ .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
75
+ const lower = name.toLowerCase()
76
+ if (lower === 'colon') return ':'
77
+ if (lower === 'tab') return '\t'
78
+ if (lower === 'newline') return '\n'
79
+ return '&'
80
+ })
81
+ }
82
+
83
+ function isSafeUrl(val: string): boolean {
84
+ const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
85
+ if (cleaned === '')
86
+ return true
87
+ if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
88
+ return true
89
+ if (HAS_SCHEME_RE.test(cleaned))
90
+ return false
91
+ return true
92
+ }
93
+
94
+ function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
95
+ const attrs: Array<{ name: string, value: string | null }> = []
96
+ let i = 0
97
+ const len = attrSrc.length
98
+ while (i < len) {
99
+ while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
100
+ if (i >= len) break
101
+ const nameStart = i
102
+ while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
103
+ const name = attrSrc.slice(nameStart, i).toLowerCase()
104
+ if (!name) {
105
+ i++
106
+ continue
107
+ }
108
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
109
+ if (attrSrc[i] !== '=') {
110
+ attrs.push({ name, value: null })
111
+ continue
112
+ }
113
+ i++ // skip '='
114
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
115
+ if (i >= len) {
116
+ attrs.push({ name, value: '' })
117
+ break
118
+ }
119
+ const quote = attrSrc[i]!
120
+ if (quote === '"' || quote === '\'') {
121
+ i++
122
+ const valStart = i
123
+ while (i < len && attrSrc[i] !== quote) i++
124
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
125
+ if (i < len) i++
126
+ }
127
+ else {
128
+ const valStart = i
129
+ while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
130
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
131
+ }
132
+ }
133
+ return attrs
134
+ }
135
+
136
+ function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
137
+ const typeAttr = rawAttrs.find(a => a.name === 'type')
138
+ if (typeAttr?.value?.toLowerCase() !== 'checkbox')
139
+ return ''
140
+ const safeParts = ['type="checkbox"']
141
+ for (const a of rawAttrs) {
142
+ if (a.name === 'class' && a.value !== null)
143
+ safeParts.push(`class="${a.value.replaceAll('"', '&quot;')}"`)
144
+ else if (a.name === 'disabled')
145
+ safeParts.push('disabled')
146
+ else if (a.name === 'checked')
147
+ safeParts.push('checked')
148
+ }
149
+ return `<input ${safeParts.join(' ')}>`
150
+ }
151
+
152
+ type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
153
+
154
+ function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
155
+ if (value === null || allowed === undefined)
156
+ return false
157
+ if (typeof allowed === 'string')
158
+ return value.startsWith(allowed)
159
+ for (const prefix of allowed) {
160
+ if (value.startsWith(prefix))
161
+ return true
162
+ }
163
+ return false
164
+ }
165
+
166
+ function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
167
+ if (tagName === 'div' && name === 'data-pru-md-slot')
168
+ return matchesSlotPrefix(value, slotPrefixes)
169
+ return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
170
+ }
171
+
172
+ function sanitizeAttributes(
173
+ tagName: string,
174
+ rawAttrs: Array<{ name: string, value: string | null }>,
175
+ slotPrefixes: AllowedSlotPrefixes,
176
+ ): string[] {
177
+ const safeParts: string[] = []
178
+ for (const a of rawAttrs) {
179
+ if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
180
+ continue
181
+ if (URL_ATTRS.has(a.name)) {
182
+ if (a.value === null || !isSafeUrl(a.value))
183
+ continue
184
+ }
185
+ else if (a.name === 'srcset' && a.value !== null) {
186
+ const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
187
+ if (!candidates.every(isSafeUrl))
188
+ continue
189
+ }
190
+ if (a.value === null)
191
+ safeParts.push(a.name)
192
+ else
193
+ safeParts.push(`${a.name}="${a.value.replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')}"`)
194
+ }
195
+ return safeParts
196
+ }
197
+
198
+ function findTagEndOffset(html: string, start: number): number {
199
+ let tagEnd = start
200
+ const len = html.length
201
+ let inQuote: string | null = null
202
+ while (tagEnd < len) {
203
+ const c = html[tagEnd]!
204
+ if (inQuote !== null) {
205
+ if (c === inQuote)
206
+ inQuote = null
207
+ }
208
+ else if (c === '"' || c === '\'') {
209
+ inQuote = c
210
+ }
211
+ else if (c === '>') {
212
+ return tagEnd
213
+ }
214
+ tagEnd++
215
+ }
216
+ return -1
217
+ }
218
+
219
+ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
220
+ let out = ''
221
+ let i = 0
222
+ const len = html.length
223
+
224
+ while (i < len) {
225
+ const lt = html.indexOf('<', i)
226
+ if (lt === -1) {
227
+ out += html.slice(i)
228
+ break
229
+ }
230
+ out += html.slice(i, lt)
231
+
232
+ // Strip HTML comments (including HTML5 `--!>` closer)
233
+ if (html.startsWith('<!--', lt)) {
234
+ const endStd = html.indexOf('-->', lt + 4)
235
+ const endBang = html.indexOf('--!>', lt + 4)
236
+ if (endStd === -1 && endBang === -1)
237
+ i = len
238
+ else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
239
+ i = endBang + 4
240
+ else
241
+ i = endStd + 3
242
+ continue
243
+ }
244
+
245
+ let pos = lt + 1
246
+ const isClosing = html[pos] === '/'
247
+ if (isClosing)
248
+ pos++
249
+
250
+ const nameStart = pos
251
+ while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
252
+ const tagName = html.slice(nameStart, pos).toLowerCase()
253
+ if (!tagName) {
254
+ out += '&lt;'
255
+ i = lt + 1
256
+ continue
257
+ }
258
+
259
+ const tagEnd = findTagEndOffset(html, pos)
260
+ if (tagEnd === -1)
261
+ break
262
+
263
+ const attrSrc = html.slice(pos, tagEnd)
264
+ const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
265
+ i = tagEnd + 1
266
+
267
+ if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
268
+ if (!selfClosing) {
269
+ const closeRe = new RegExp(`</${tagName}\\b[^>]*>`, 'gi')
270
+ closeRe.lastIndex = i
271
+ const m = closeRe.exec(html)
272
+ i = m ? m.index + m[0].length : len
273
+ }
274
+ continue
275
+ }
276
+
277
+ if (!ALLOWED_MD_TAGS.has(tagName))
278
+ continue
279
+
280
+ if (isClosing) {
281
+ if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
282
+ out += `</${tagName}>`
283
+ continue
284
+ }
285
+
286
+ const rawAttrs = parseTagAttributes(attrSrc)
287
+ if (tagName === 'input') {
288
+ out += sanitizeInputTag(rawAttrs)
289
+ continue
290
+ }
291
+
292
+ const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
293
+ const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
294
+ out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
295
+ }
296
+
297
+ return out
298
+ }
299
+
300
+ export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
301
+ let current = html
302
+ for (let pass = 0; pass < 3; pass++) {
303
+ const next = sanitizePass(current, slotPrefixes)
304
+ if (next === current)
305
+ return next
306
+ current = next
307
+ }
308
+ return current
309
+ }
package/src/service.ts ADDED
@@ -0,0 +1,88 @@
1
+ // `CONTENT_COLLECTIONS_SERVICE` adapter and internal prerender marker service for @prunellejs/content.
2
+
3
+ import type {
4
+ ContentCollectionDescriptor,
5
+ ContentCollectionEntrySummary,
6
+ ContentCollectionsService,
7
+ } from 'prunelle/config'
8
+ import type { ContentEntry, InternalCollection } from './types'
9
+ import { basename } from 'node:path'
10
+ import { serviceKey } from 'prunelle/config'
11
+ import { discoverAppCollections } from './registry'
12
+ import { getAccessedEntries } from './tracking'
13
+ import { COLLECTION_DIR_FOR_ROOT_KEY, COLLECTION_META_KEY } from './types'
14
+
15
+ /** Internal build-time marker provided on the prerender server's AppRuntimeContext so loaded collections cache across prerendered pages. */
16
+ export const CONTENT_PRERENDER_SERVICE = serviceKey<boolean>('prunelle.content.prerender')
17
+
18
+ function toEntrySummary(entry: ContentEntry<unknown>): ContentCollectionEntrySummary {
19
+ const data = entry.data !== null && typeof entry.data === 'object'
20
+ ? entry.data as Record<string, unknown>
21
+ : {}
22
+ return {
23
+ slug: entry.slug,
24
+ ...(entry.locale !== undefined ? { locale: entry.locale } : {}),
25
+ file: entry.file,
26
+ data,
27
+ body: entry.body,
28
+ }
29
+ }
30
+
31
+ export function toCollectionDescriptor(
32
+ col: InternalCollection,
33
+ options: { root?: string | undefined, linkPrefix?: string | undefined } = {},
34
+ ): ContentCollectionDescriptor {
35
+ const meta = col[COLLECTION_META_KEY]?.(options.root)
36
+ const dir = meta !== undefined ? meta.dir : (col[COLLECTION_DIR_FOR_ROOT_KEY]?.(options.root) ?? col.dir)
37
+ const name = meta?.name ?? col.name ?? (dir !== undefined ? (basename(dir) || 'collection') : 'collection')
38
+ const localized = meta?.localized ?? false
39
+ const defaultLocale = meta?.defaultLocale ?? 'en'
40
+ const locales = meta?.locales
41
+ const schema = meta?.schema
42
+
43
+ return {
44
+ name,
45
+ ...(options.linkPrefix !== undefined ? { linkPrefix: options.linkPrefix } : {}),
46
+ ...(dir !== undefined ? { dir } : {}),
47
+ localized,
48
+ defaultLocale,
49
+ ...(locales !== undefined ? { locales } : {}),
50
+ ...(schema !== undefined ? { schema } : {}),
51
+ all(locale?: string): readonly ContentCollectionEntrySummary[] | Promise<readonly ContentCollectionEntrySummary[]> {
52
+ const res = col.all(locale)
53
+ if (res instanceof Promise)
54
+ return res.then(list => list.map(toEntrySummary))
55
+ return res.map(toEntrySummary)
56
+ },
57
+ get(slug: string, locale?: string): ContentCollectionEntrySummary | undefined | Promise<ContentCollectionEntrySummary | undefined> {
58
+ const res = col.get(slug, locale)
59
+ if (res instanceof Promise)
60
+ return res.then(entry => (entry !== undefined ? toEntrySummary(entry) : undefined))
61
+ return res !== undefined ? toEntrySummary(res) : undefined
62
+ },
63
+ clearCache() {
64
+ col.clearCache()
65
+ },
66
+ }
67
+ }
68
+
69
+ export function createCollectionsService(
70
+ getActive: (root?: string) => InternalCollection[],
71
+ linkPrefixFor: (col: InternalCollection) => string | undefined,
72
+ ): ContentCollectionsService {
73
+ const mapAll = (root?: string): ContentCollectionDescriptor[] =>
74
+ getActive(root).map(col => toCollectionDescriptor(col, { root, linkPrefix: linkPrefixFor(col) }))
75
+
76
+ return {
77
+ list(root?: string) {
78
+ return mapAll(root)
79
+ },
80
+ async discover(root: string) {
81
+ await discoverAppCollections(root)
82
+ return mapAll(root)
83
+ },
84
+ accessedEntries(ctx) {
85
+ return getAccessedEntries(ctx)
86
+ },
87
+ }
88
+ }
@@ -0,0 +1,80 @@
1
+ // Dev-only per-request entry tracking and zero-impact HTML comment anchors for @prunellejs/cms in-page editing.
2
+
3
+ import type { AccessedContentEntry } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import { currentRequest } from 'prunelle/internal/server'
6
+ import { currentApp } from './app'
7
+
8
+ const MAX_TRACKED_ENTRIES = 50
9
+
10
+ interface RequestEntryBucket {
11
+ readonly primary: Map<string, AccessedContentEntry>
12
+ readonly secondary: Map<string, AccessedContentEntry>
13
+ }
14
+
15
+ const ACCESSED_STORAGE_KEY = Symbol.for('pru.content.accessedByRequest')
16
+ // Shared across bundled server routes and the host plugin instance; WeakMap releases entries once the request ends.
17
+ const accessedByRequest: WeakMap<RequestContext, RequestEntryBucket> = ((globalThis as Record<symbol, WeakMap<RequestContext, RequestEntryBucket> | undefined>)[ACCESSED_STORAGE_KEY] ??= new WeakMap())
18
+
19
+ function entryKey(entry: AccessedContentEntry): string {
20
+ return `${entry.collection}\0${entry.locale ?? ''}\0${entry.slug}`
21
+ }
22
+
23
+ function encodeCmsAnchorPart(value: string): string {
24
+ // Encode `-` as `%2D` so `--` can never appear inside an HTML5 comment node.
25
+ return encodeURIComponent(value).replaceAll('-', '%2D')
26
+ }
27
+
28
+ function isDevActive(): boolean {
29
+ return currentApp.dev() ?? (process.env.PRUNELLE_DEV === '1')
30
+ }
31
+
32
+ /** Records a file-backed entry read during the active dev request (`primary: true` for `.get()`, `false` for `.all()`). */
33
+ export function recordAccessedEntry(entry: AccessedContentEntry, primary: boolean): void {
34
+ if (!isDevActive())
35
+ return
36
+ const reqCtx = currentRequest()?.ctx
37
+ if (reqCtx === undefined)
38
+ return
39
+ let bucket = accessedByRequest.get(reqCtx)
40
+ if (bucket === undefined) {
41
+ bucket = { primary: new Map(), secondary: new Map() }
42
+ accessedByRequest.set(reqCtx, bucket)
43
+ }
44
+ const key = entryKey(entry)
45
+ if (primary) {
46
+ bucket.secondary.delete(key)
47
+ if (!bucket.primary.has(key) && bucket.primary.size < MAX_TRACKED_ENTRIES)
48
+ bucket.primary.set(key, entry)
49
+ }
50
+ else if (!bucket.primary.has(key) && !bucket.secondary.has(key) && bucket.secondary.size < MAX_TRACKED_ENTRIES) {
51
+ bucket.secondary.set(key, entry)
52
+ }
53
+ }
54
+
55
+ /** Returns file-backed entries accessed during `ctx`, with direct `.get()` reads ordered before `.all()` reads. */
56
+ export function getAccessedEntries(ctx: RequestContext): readonly AccessedContentEntry[] {
57
+ const bucket = accessedByRequest.get(ctx)
58
+ if (bucket === undefined)
59
+ return []
60
+ return [...bucket.primary.values(), ...bucket.secondary.values()]
61
+ }
62
+
63
+ /** True only when rendering a file-backed entry during an active dev request with `@prunellejs/cms` inline mode enabled. */
64
+ export function shouldWrapCmsBody(collectionName: string | undefined): collectionName is string {
65
+ return collectionName !== undefined
66
+ && isDevActive()
67
+ && currentApp.cmsInline()
68
+ && currentRequest() !== undefined
69
+ }
70
+
71
+ /** Wraps rendered Markdown HTML in zero-impact HTML comment anchors for in-page CMS body editing. */
72
+ export function wrapCmsBodyHtml(
73
+ collection: string,
74
+ slug: string,
75
+ locale: string | undefined,
76
+ html: string,
77
+ ): string {
78
+ const token = `${encodeCmsAnchorPart(collection)}:${encodeCmsAnchorPart(slug)}:${encodeCmsAnchorPart(locale ?? '')}:__body`
79
+ return `<!--pru-cms:${token}-->${html}<!--/pru-cms-->`
80
+ }
package/src/types.ts ADDED
@@ -0,0 +1,198 @@
1
+ // Shared public and internal types and symbol keys for @prunellejs/content.
2
+
3
+ import type { ContentImageResolver, ContentImageResult } from 'prunelle/config'
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+
6
+ export const COLLECTION_VERSION_KEY = Symbol.for('pru.content.collectionVersion')
7
+ export const COLLECTION_VALIDATE_KEY = Symbol.for('pru.content.validateAll')
8
+ export const COLLECTION_DIR_FOR_ROOT_KEY = Symbol.for('pru.content.dirForRoot')
9
+ export const COLLECTION_OWNER_ROOT_KEY = Symbol.for('pru.content.ownerRoot')
10
+ export const COLLECTION_META_KEY = Symbol.for('pru.content.meta')
11
+
12
+ export interface InternalCollectionMeta {
13
+ readonly name: string
14
+ readonly dir?: string | undefined
15
+ readonly localized: boolean
16
+ readonly defaultLocale: string
17
+ readonly locales?: readonly string[] | undefined
18
+ readonly schema?: StandardSchemaV1 | undefined
19
+ readonly isAsync: boolean
20
+ }
21
+
22
+ export interface ContentHeading {
23
+ level: number
24
+ id: string
25
+ text: string
26
+ }
27
+
28
+ export interface RenderedMarkdown {
29
+ readonly html: string
30
+ readonly headings: readonly ContentHeading[]
31
+ readonly wordCount: number
32
+ readonly readingMinutes: number
33
+ }
34
+
35
+ export interface ContentEntry<TData = Record<string, unknown>> {
36
+ readonly slug: string
37
+ readonly locale?: string | undefined
38
+ readonly file: string
39
+ readonly data: TData
40
+ readonly body: string
41
+ readonly html: string
42
+ readonly headings: readonly ContentHeading[]
43
+ readonly wordCount: number
44
+ readonly readingMinutes: number
45
+ /** Lazily resolves async collection renderers (`highlight`, `components`) and renders Markdown once. */
46
+ render(): Promise<RenderedMarkdown>
47
+ }
48
+
49
+ export type MarkdownComponent = (props: never) => unknown
50
+ export type CodeHighlighter = (code: string, language: string | undefined) => string
51
+ export type MarkdownImageResult = ContentImageResult
52
+ export type MarkdownImageResolver = ContentImageResolver
53
+
54
+ export interface CollectionRenderConfig {
55
+ /** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
56
+ highlight?: CodeHighlighter | undefined
57
+ /** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
58
+ components?: Record<string, MarkdownComponent> | undefined
59
+ /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
60
+ headingLinks?: boolean | undefined
61
+ /** Optional image resolver (set to `false` to disable automatic `@prunellejs/images` optimization). */
62
+ resolveImage?: MarkdownImageResolver | false | undefined
63
+ /** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
64
+ trusted?: boolean | undefined
65
+ }
66
+
67
+ export interface RenderMarkdownOptions {
68
+ highlight?: CodeHighlighter | undefined
69
+ components?: Record<string, MarkdownComponent> | undefined
70
+ /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
71
+ headingLinks?: boolean | undefined
72
+ /** Active locale passed into embedded components as `props.locale`. */
73
+ locale?: string | undefined
74
+ /** Optional image resolver for rewriting `<img src="...">` (defaults to auto-wired `@prunellejs/images` when active; `false` disables). */
75
+ resolveImage?: MarkdownImageResolver | false | undefined
76
+ /** Source file path passed to `resolveImage`. */
77
+ file?: string | undefined
78
+ /** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
79
+ trusted?: boolean | undefined
80
+ }
81
+
82
+ export interface CollectionLoadContext {
83
+ /** Requested locale when `localized: true`; `undefined` otherwise. */
84
+ readonly locale?: string | undefined
85
+ }
86
+
87
+ export interface LoadedEntryInput {
88
+ /** Entry slug used for `.get(slug)` and `.paths(prefix)`. */
89
+ readonly slug: string
90
+ /** Raw entry metadata validated against `schema` when configured. */
91
+ readonly data: unknown
92
+ /** Optional Markdown body rendered through the standard content pipeline. */
93
+ readonly body?: string | undefined
94
+ /** Optional locale tag; when `localized: true`, entries with a non-matching locale are filtered out. */
95
+ readonly locale?: string | undefined
96
+ /** Optional upstream identifier (e.g. CMS record ID) surfaced as `entry.file`. */
97
+ readonly id?: string | undefined
98
+ }
99
+
100
+ export type CollectionLoader = (
101
+ ctx?: CollectionLoadContext,
102
+ ) => LoadedEntryInput[] | Promise<LoadedEntryInput[]>
103
+
104
+ export interface BaseCollectionOptions<TData = Record<string, unknown>> {
105
+ /** Collection identifier for diagnostics, CMS, and search (defaults to `dir` basename or `'collection'`). */
106
+ name?: string | undefined
107
+ /** When true, queries are scoped by locale. */
108
+ localized?: boolean | undefined
109
+ /** Default locale when `localized: true` and no locale is passed (default: app defaultLocale or `'en'`). */
110
+ defaultLocale?: string | undefined
111
+ /** Known locales for localized collections (used by `prunelle check`, search, and CMS). */
112
+ locales?: readonly string[] | undefined
113
+ /** Optional Standard Schema (Zod, Valibot, ArkType, custom) to validate entry metadata. */
114
+ schema?: StandardSchemaV1<unknown, TData> | undefined
115
+ /** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
116
+ highlight?: CodeHighlighter | undefined
117
+ /** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
118
+ components?: Record<string, MarkdownComponent> | undefined
119
+ /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
120
+ headingLinks?: boolean | undefined
121
+ /** Optional image resolver for rewriting Markdown images (defaults to auto-wired `@prunellejs/images`; `false` disables). */
122
+ resolveImage?: MarkdownImageResolver | false | undefined
123
+ /** Opt out of default Markdown HTML sanitization for fully trusted collections (default: false). */
124
+ trusted?: boolean | undefined
125
+ /** Lazy renderer loader (`async () => ({ highlight, components })`) so config/index/RSS never load Shiki or TSX components. */
126
+ render?: (() => CollectionRenderConfig | Promise<CollectionRenderConfig>) | undefined
127
+ /** Include entries with `draft: true` (default: `true` in dev, `false` in production/build). */
128
+ includeDrafts?: boolean | undefined
129
+ /** Custom comparator for `all()` (defaults to newest `date` first, then alphabetical `slug`). */
130
+ sort?: ((a: ContentEntry<TData>, b: ContentEntry<TData>) => number) | undefined
131
+ }
132
+
133
+ export interface CollectionOptions<TData = Record<string, unknown>> extends BaseCollectionOptions<TData> {
134
+ /** Directory containing `.md` / `.markdown` files (or `<locale>/*.md` when `localized: true`). */
135
+ dir: string
136
+ load?: undefined
137
+ }
138
+
139
+ export interface CollectionOptionsWithSchema<TData> extends Omit<CollectionOptions<TData>, 'schema'> {
140
+ /** Standard Schema (Zod, Valibot, ArkType, custom) validating frontmatter into `TData`. */
141
+ schema: StandardSchemaV1<unknown, TData>
142
+ }
143
+
144
+ export interface CollectionOptionsWithoutSchema extends Omit<CollectionOptions<Record<string, unknown>>, 'schema'> {
145
+ schema?: undefined
146
+ }
147
+
148
+ export interface LoaderCollectionOptions<TData = Record<string, unknown>> extends BaseCollectionOptions<TData> {
149
+ dir?: undefined
150
+ /** Async or sync loader returning entries from a headless CMS, database, or API. */
151
+ load: CollectionLoader
152
+ }
153
+
154
+ export interface LoaderCollectionOptionsWithSchema<TData> extends Omit<LoaderCollectionOptions<TData>, 'schema'> {
155
+ /** Standard Schema (Zod, Valibot, ArkType, custom) validating loaded entry data into `TData`. */
156
+ schema: StandardSchemaV1<unknown, TData>
157
+ }
158
+
159
+ export interface LoaderCollectionOptionsWithoutSchema extends Omit<LoaderCollectionOptions<Record<string, unknown>>, 'schema'> {
160
+ schema?: undefined
161
+ }
162
+
163
+ export interface Collection<TData = Record<string, unknown>> {
164
+ readonly dir: string
165
+ readonly name: string
166
+ all(locale?: string): ContentEntry<TData>[]
167
+ get(slug: string, locale?: string): ContentEntry<TData> | undefined
168
+ byTag(tag: string, locale?: string): ContentEntry<TData>[]
169
+ /** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
170
+ paths(prefix?: string, locale?: string): string[]
171
+ clearCache(): void
172
+ }
173
+
174
+ export interface AsyncCollection<TData = Record<string, unknown>> {
175
+ readonly dir?: undefined
176
+ readonly name: string
177
+ all(locale?: string): Promise<ContentEntry<TData>[]>
178
+ get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined>
179
+ byTag(tag: string, locale?: string): Promise<ContentEntry<TData>[]>
180
+ /** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
181
+ paths(prefix?: string, locale?: string): Promise<string[]>
182
+ clearCache(): void
183
+ }
184
+
185
+ export type AnyCollection<TData = Record<string, unknown>> = Collection<TData> | AsyncCollection<TData>
186
+
187
+ export interface InternalCollection {
188
+ readonly dir?: string | undefined
189
+ readonly name?: string | undefined
190
+ all(locale?: string): ContentEntry<unknown>[] | Promise<ContentEntry<unknown>[]>
191
+ get(slug: string, locale?: string): ContentEntry<unknown> | undefined | Promise<ContentEntry<unknown> | undefined>
192
+ clearCache(): void
193
+ [COLLECTION_VERSION_KEY]?: () => number
194
+ [COLLECTION_VALIDATE_KEY]?: (root: string) => string[] | Promise<string[]>
195
+ [COLLECTION_DIR_FOR_ROOT_KEY]?: (root?: string) => string | undefined
196
+ [COLLECTION_OWNER_ROOT_KEY]?: string | undefined
197
+ [COLLECTION_META_KEY]?: (root?: string) => InternalCollectionMeta
198
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.