@prunellejs/content 0.7.3 → 0.8.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.
- package/llms.txt +2 -1
- package/package.json +2 -2
- package/src/entry.ts +16 -5
- package/src/markdown.ts +124 -61
- package/src/rss.ts +8 -3
package/llms.txt
CHANGED
|
@@ -17,7 +17,7 @@ Shared options:
|
|
|
17
17
|
- `schema`: optional Standard Schema v1 (`Zod`, `Valibot`, `ArkType`, custom) validating frontmatter / loaded `data` into `entry.data` (file-backed is synchronous; loader-backed supports both sync and async validators).
|
|
18
18
|
- `localized`: `true` reads `<dir>/<locale>/<slug>.md` for file collections, or passes `{ locale }` to `load()` and filters entries whose `entry.locale` is set for loaded collections; `defaultLocale` defaults to the app's i18n default or `'en'`; `locales` lists known locales for `prunelle check`, search, and CMS.
|
|
19
19
|
- `render`: lazy async factory `async () => ({ highlight, components, headingLinks, resolveImage, trusted })` so index pages, config, and RSS never import Shiki or TSX components until `await entry.render()` runs.
|
|
20
|
-
- Direct options: `highlight(code, lang)`, `components` (MDX-lite TSX components usable inside Markdown; a non-literal prop like `tone={someVar}` and an unregistered `<Foo />` tag throw naming the file, and `__proto__`, `constructor` and `prototype` props are dropped), `headingLinks` (`true` wraps `h2`–`h6` in `#id` anchor links), `resolveImage` (auto-wired with `@prunellejs/images`; pass `false` to disable; the first image gets `loading="eager"`, the others `lazy`, unless it returns a `loading`), `trusted` (default `false`; HTML is sanitized unless `true`), `includeDrafts` (defaults to `true` in `prunelle dev` / `testApp({ dev: true })` and `false` in `prunelle build` / production; RSS feeds always leave drafts out), `sort(a, b)` (default newest `date` first, then `slug`).
|
|
20
|
+
- Direct options: `highlight(code, lang)`, `components` (MDX-lite TSX components usable inside Markdown; a non-literal prop like `tone={someVar}` and an unregistered `<Foo />` tag throw naming the file, and `__proto__`, `constructor` and `prototype` props are dropped), `headingLinks` (`true` wraps `h2`–`h6` in `#id` anchor links), `resolveImage` (auto-wired with `@prunellejs/images`; pass `false` to disable; the first image gets `loading="eager"`, the others `lazy`, unless it returns a `loading`), `trusted` (default `false`; HTML is sanitized unless `true`), `includeDrafts` (defaults to `true` in `prunelle dev` / `testApp({ dev: true })` and `false` in `prunelle build` / production; RSS feeds always leave drafts out), `sort(a, b)` (default newest `date` first, undated last, then `slug`).
|
|
21
21
|
|
|
22
22
|
## Caching (Loader-Backed Collections)
|
|
23
23
|
|
|
@@ -35,6 +35,7 @@ Shared options:
|
|
|
35
35
|
- `col.paths(prefix?, locale?)`: URL list for `export const prerender = true; export const paths = () => col.paths('/blog')`.
|
|
36
36
|
- `col.clearCache()`: drops cached entries.
|
|
37
37
|
- `ContentEntry<TData>`: `slug`, `locale`, `file`, `data`, `body`, `html`, `headings` (`{ level, id, text }[]`), `wordCount`, `readingMinutes`, and `await entry.render()` (memoized).
|
|
38
|
+
- Markdown tables render with `scope="col"` header cells, the first cell of each body row as `<th scope="row">` when the table has two columns or more, and `style="text-align:…"` in place of `align` (RGAA 5.6, 5.7, 10.1).
|
|
38
39
|
|
|
39
40
|
## Plugin Setup (`content({ feeds?, collections? })`)
|
|
40
41
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/content",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Zero-dependency Bun.markdown collections, YAML frontmatter, TOC, and RSS plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-content"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.8.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/entry.ts
CHANGED
|
@@ -147,12 +147,23 @@ export function isDraft(data: unknown): boolean {
|
|
|
147
147
|
return data !== null && typeof data === 'object' && (data as Record<string, unknown>).draft === true
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
+
function entryTimestamp(data: unknown): number {
|
|
151
|
+
const raw = data !== null && typeof data === 'object' ? (data as Record<string, unknown>).date : undefined
|
|
152
|
+
if (raw instanceof Date)
|
|
153
|
+
return raw.getTime()
|
|
154
|
+
if (typeof raw === 'string' || typeof raw === 'number')
|
|
155
|
+
return Date.parse(String(raw))
|
|
156
|
+
return Number.NaN
|
|
157
|
+
}
|
|
158
|
+
|
|
150
159
|
export function defaultSort<T>(a: ContentEntry<T>, b: ContentEntry<T>): number {
|
|
151
|
-
const
|
|
152
|
-
const
|
|
153
|
-
const
|
|
154
|
-
const
|
|
155
|
-
if (
|
|
160
|
+
const at = entryTimestamp(a.data)
|
|
161
|
+
const bt = entryTimestamp(b.data)
|
|
162
|
+
const aDated = !Number.isNaN(at)
|
|
163
|
+
const bDated = !Number.isNaN(bt)
|
|
164
|
+
if (aDated !== bDated)
|
|
165
|
+
return aDated ? -1 : 1
|
|
166
|
+
if (aDated && bDated && at !== bt)
|
|
156
167
|
return bt - at
|
|
157
168
|
return a.slug.localeCompare(b.slug)
|
|
158
169
|
}
|
package/src/markdown.ts
CHANGED
|
@@ -6,25 +6,126 @@ import { escAttr } from 'prunelle/server'
|
|
|
6
6
|
import { currentApp } from './app'
|
|
7
7
|
import { expandComponents } from './components'
|
|
8
8
|
|
|
9
|
+
const HTML_ENTITY_RE = /&(?:#x([0-9a-f]+)|#(\d+)|(amp|lt|gt|quot|apos));/gi
|
|
10
|
+
const NAMED_ENTITIES: Readonly<Record<string, string>> = {
|
|
11
|
+
amp: '&',
|
|
12
|
+
lt: '<',
|
|
13
|
+
gt: '>',
|
|
14
|
+
quot: '"',
|
|
15
|
+
apos: '\'',
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function decodeHtmlEntities(text: string): string {
|
|
19
|
+
return text.replace(HTML_ENTITY_RE, (m, hex: string | undefined, dec: string | undefined, named: string | undefined) => {
|
|
20
|
+
if (named !== undefined)
|
|
21
|
+
return NAMED_ENTITIES[named.toLowerCase()] ?? m
|
|
22
|
+
const code = hex !== undefined ? Number.parseInt(hex, 16) : Number.parseInt(dec!, 10)
|
|
23
|
+
return Number.isFinite(code) && code >= 0 && code <= 0x10FFFF ? String.fromCodePoint(code) : m
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const MD_TABLE_RE = /<table>[\s\S]*?<\/table>/g
|
|
28
|
+
const HEADER_CELL_RE = /<th( align="\w+")?>/g
|
|
29
|
+
const FIRST_BODY_CELL_RE = /<tr><td( align="\w+")?>([\s\S]*?)<\/td>/g
|
|
30
|
+
const ALIGN_ATTR_RE = / align="(left|center|right)"/g
|
|
31
|
+
|
|
32
|
+
// Bun's GFM tables give bare `<th>` and an `align` attribute: RGAA 5.7 wants headers scoped, 5.6 the first column of a wider table as row headers, and 10.1 no presentation attribute.
|
|
33
|
+
function scopeTableHeaders(html: string): string {
|
|
34
|
+
return html.replace(MD_TABLE_RE, (table) => {
|
|
35
|
+
let out = table.replace(HEADER_CELL_RE, '<th scope="col"$1>')
|
|
36
|
+
if (out.indexOf('<th scope="col"') !== out.lastIndexOf('<th scope="col"'))
|
|
37
|
+
out = out.replace(FIRST_BODY_CELL_RE, '<tr><th scope="row"$1>$2</th>')
|
|
38
|
+
return out.replace(ALIGN_ATTR_RE, ' style="text-align:$1"')
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
9
42
|
function slugifyHeading(text: string): string {
|
|
10
43
|
return text
|
|
11
|
-
.
|
|
44
|
+
.replace(/<[^>]+>/g, '')
|
|
12
45
|
.normalize('NFKD')
|
|
13
46
|
.replace(/[\u0300-\u036F]/g, '')
|
|
14
|
-
.
|
|
15
|
-
.
|
|
47
|
+
.normalize('NFC')
|
|
48
|
+
.toLowerCase()
|
|
49
|
+
.replace(/[^\p{L}\p{M}\p{N}]+/gu, '-')
|
|
16
50
|
.replace(/^-+|-+$/g, '') || 'section'
|
|
17
51
|
}
|
|
18
52
|
|
|
19
53
|
function stripTags(html: string): string {
|
|
20
|
-
return html
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.
|
|
26
|
-
|
|
27
|
-
|
|
54
|
+
return decodeHtmlEntities(html.replace(/<[^>]+>/g, '')).trim()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function allocateHeadingId(base: string, usedIds: Set<string>): string {
|
|
58
|
+
if (!usedIds.has(base)) {
|
|
59
|
+
usedIds.add(base)
|
|
60
|
+
return base
|
|
61
|
+
}
|
|
62
|
+
let n = 1
|
|
63
|
+
while (usedIds.has(`${base}-${n}`))
|
|
64
|
+
n++
|
|
65
|
+
const id = `${base}-${n}`
|
|
66
|
+
usedIds.add(id)
|
|
67
|
+
return id
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function assignHeadingIds(
|
|
71
|
+
html: string,
|
|
72
|
+
headingLinks: boolean | undefined,
|
|
73
|
+
): { html: string, headings: ContentHeading[] } {
|
|
74
|
+
const headings: ContentHeading[] = []
|
|
75
|
+
const usedIds = new Set<string>()
|
|
76
|
+
for (const m of html.matchAll(/<h[1-6]\b[^>]*\bid="([^"]+)"/gi))
|
|
77
|
+
usedIds.add(m[1]!)
|
|
78
|
+
|
|
79
|
+
const nextHtml = html.replace(/<h([1-6])>([\s\S]*?)<\/h\1>/g, (_match, levelStr: string, inner: string) => {
|
|
80
|
+
const level = Number(levelStr)
|
|
81
|
+
const text = stripTags(inner)
|
|
82
|
+
const id = allocateHeadingId(slugifyHeading(text), usedIds)
|
|
83
|
+
headings.push({ level, id, text })
|
|
84
|
+
if (headingLinks && level >= 2 && !/<a\b/i.test(inner))
|
|
85
|
+
return `<h${level} id="${id}"><a href="#${id}">${inner}</a></h${level}>`
|
|
86
|
+
return `<h${level} id="${id}">${inner}</h${level}>`
|
|
87
|
+
})
|
|
88
|
+
return { html: nextHtml, headings }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function rewriteMarkdownImages(
|
|
92
|
+
html: string,
|
|
93
|
+
resolveImageFn: MarkdownImageResolver,
|
|
94
|
+
file: string | undefined,
|
|
95
|
+
): string {
|
|
96
|
+
// The first image is often the page's largest paint, which lazy loading would hold back.
|
|
97
|
+
let seen = 0
|
|
98
|
+
return html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
|
|
99
|
+
const first = seen++ === 0
|
|
100
|
+
const srcMatch = /(?:^|\s)src="([^"]+)"/i.exec(attrs)
|
|
101
|
+
if (!srcMatch)
|
|
102
|
+
return full
|
|
103
|
+
const resolved = resolveImageFn(decodeHtmlEntities(srcMatch[1]!), file)
|
|
104
|
+
if (!resolved)
|
|
105
|
+
return full
|
|
106
|
+
const info: MarkdownImageResult = typeof resolved === 'string' ? { src: resolved } : resolved
|
|
107
|
+
const altMatch = /(?:^|\s)alt="([^"]*)"/i.exec(attrs)
|
|
108
|
+
const alt = altMatch ? altMatch[1]! : ''
|
|
109
|
+
const titleMatch = /(?:^|\s)title="([^"]*)"/i.exec(attrs)
|
|
110
|
+
const parts = [`src="${escAttr(info.src)}"`, `alt="${alt}"`]
|
|
111
|
+
if (titleMatch !== null && titleMatch[1] !== '')
|
|
112
|
+
parts.push(`title="${titleMatch[1]!}"`)
|
|
113
|
+
if (info.srcset)
|
|
114
|
+
parts.push(`srcset="${escAttr(info.srcset)}"`)
|
|
115
|
+
if (info.sizes)
|
|
116
|
+
parts.push(`sizes="${escAttr(info.sizes)}"`)
|
|
117
|
+
if (info.width !== undefined && info.width > 0)
|
|
118
|
+
parts.push(`width="${info.width}"`)
|
|
119
|
+
if (info.height !== undefined && info.height > 0)
|
|
120
|
+
parts.push(`height="${info.height}"`)
|
|
121
|
+
parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
|
|
122
|
+
const imgTag = `<img ${parts.join(' ')}>`
|
|
123
|
+
if (info.avifSrcset) {
|
|
124
|
+
const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
|
|
125
|
+
return `<picture><source type="image/avif" srcset="${escAttr(info.avifSrcset)}"${sizesAttr}>${imgTag}</picture>`
|
|
126
|
+
}
|
|
127
|
+
return imgTag
|
|
128
|
+
})
|
|
28
129
|
}
|
|
29
130
|
|
|
30
131
|
function findDefaultImageResolver(file: string | undefined): MarkdownImageResolver | undefined {
|
|
@@ -98,60 +199,14 @@ function renderMarkdownInternal(
|
|
|
98
199
|
// Runs before splicing developer-supplied highlight/component slots so custom components remain intact.
|
|
99
200
|
if (options.trusted !== true)
|
|
100
201
|
html = sanitizeMarkdownHtml(html, allowedSlotPrefixes)
|
|
202
|
+
html = scopeTableHeaders(html)
|
|
101
203
|
|
|
102
|
-
// 4.
|
|
103
|
-
const headings: ContentHeading[] = []
|
|
104
|
-
const usedIds = new Map<string, number>()
|
|
105
|
-
|
|
106
|
-
html = html.replace(/<h([1-6])>([\s\S]*?)<\/h\1>/g, (_match, levelStr: string, inner: string) => {
|
|
107
|
-
const level = Number(levelStr)
|
|
108
|
-
const text = stripTags(inner)
|
|
109
|
-
const base = slugifyHeading(text)
|
|
110
|
-
const count = usedIds.get(base) ?? 0
|
|
111
|
-
usedIds.set(base, count + 1)
|
|
112
|
-
const id = count === 0 ? base : `${base}-${count}`
|
|
113
|
-
headings.push({ level, id, text })
|
|
114
|
-
if (options.headingLinks && level >= 2 && !/<a\b/i.test(inner))
|
|
115
|
-
return `<h${level} id="${id}"><a href="#${id}">${inner}</a></h${level}>`
|
|
116
|
-
return `<h${level} id="${id}">${inner}</h${level}>`
|
|
117
|
-
})
|
|
118
|
-
|
|
119
|
-
// 4b. Image rewriting (explicit resolveImage or auto-wired @prunellejs/images; `false` disables)
|
|
204
|
+
// 4. Image rewriting (explicit resolveImage or auto-wired @prunellejs/images; `false` disables)
|
|
120
205
|
const resolveImageFn = options.resolveImage === false
|
|
121
206
|
? undefined
|
|
122
207
|
: (options.resolveImage ?? findDefaultImageResolver(options.file))
|
|
123
|
-
if (resolveImageFn !== undefined)
|
|
124
|
-
|
|
125
|
-
let seen = 0
|
|
126
|
-
html = html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
|
|
127
|
-
const first = seen++ === 0
|
|
128
|
-
const srcMatch = /\bsrc="([^"]+)"/i.exec(attrs)
|
|
129
|
-
if (!srcMatch)
|
|
130
|
-
return full
|
|
131
|
-
const resolved = resolveImageFn(srcMatch[1]!, options.file)
|
|
132
|
-
if (!resolved)
|
|
133
|
-
return full
|
|
134
|
-
const info: MarkdownImageResult = typeof resolved === 'string' ? { src: resolved } : resolved
|
|
135
|
-
const altMatch = /\balt="([^"]*)"/i.exec(attrs)
|
|
136
|
-
const alt = altMatch ? altMatch[1]! : ''
|
|
137
|
-
const parts = [`src="${escAttr(info.src)}"`, `alt="${alt}"`]
|
|
138
|
-
if (info.srcset)
|
|
139
|
-
parts.push(`srcset="${escAttr(info.srcset)}"`)
|
|
140
|
-
if (info.sizes)
|
|
141
|
-
parts.push(`sizes="${escAttr(info.sizes)}"`)
|
|
142
|
-
if (info.width !== undefined && info.width > 0)
|
|
143
|
-
parts.push(`width="${info.width}"`)
|
|
144
|
-
if (info.height !== undefined && info.height > 0)
|
|
145
|
-
parts.push(`height="${info.height}"`)
|
|
146
|
-
parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
|
|
147
|
-
const imgTag = `<img ${parts.join(' ')}>`
|
|
148
|
-
if (info.avifSrcset) {
|
|
149
|
-
const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
|
|
150
|
-
return `<picture><source type="image/avif" srcset="${escAttr(info.avifSrcset)}"${sizesAttr}>${imgTag}</picture>`
|
|
151
|
-
}
|
|
152
|
-
return imgTag
|
|
153
|
-
})
|
|
154
|
-
}
|
|
208
|
+
if (resolveImageFn !== undefined)
|
|
209
|
+
html = rewriteMarkdownImages(html, resolveImageFn, options.file)
|
|
155
210
|
|
|
156
211
|
// 5. Splice this batch's highlighted code blocks & embedded TSX components back in (loop handles components wrapping code fences)
|
|
157
212
|
if (slots.length > 0) {
|
|
@@ -163,6 +218,14 @@ function renderMarkdownInternal(
|
|
|
163
218
|
}
|
|
164
219
|
}
|
|
165
220
|
|
|
221
|
+
// 6. Add unique heading IDs & collect TOC in document order on the top-level render (including headings inside component children)
|
|
222
|
+
let headings: ContentHeading[] = []
|
|
223
|
+
if (inheritedSlotPrefixes === undefined) {
|
|
224
|
+
const assigned = assignHeadingIds(html, options.headingLinks)
|
|
225
|
+
html = assigned.html
|
|
226
|
+
headings = assigned.headings
|
|
227
|
+
}
|
|
228
|
+
|
|
166
229
|
const words = body.trim().split(/\s+/).filter(Boolean).length
|
|
167
230
|
const readingMinutes = Math.max(1, Math.ceil(words / 220))
|
|
168
231
|
return { html, headings, wordCount: words, readingMinutes }
|
package/src/rss.ts
CHANGED
|
@@ -49,25 +49,30 @@ function formatPubDate(value: string | Date | undefined): string {
|
|
|
49
49
|
return Number.isNaN(date.getTime()) ? '' : `<pubDate>${date.toUTCString()}</pubDate>`
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
function encodePathSegments(path: string): string {
|
|
53
|
+
return path.split('/').map(seg => encodeURIComponent(seg)).join('/')
|
|
54
|
+
}
|
|
55
|
+
|
|
52
56
|
function buildRssXml<TData>(
|
|
53
57
|
feed: Pick<RssFeedConfig<TData, AnyCollection<TData>>, 'title' | 'description' | 'site' | 'linkPrefix' | 'mapItem'>,
|
|
54
58
|
entries: readonly ContentEntry<TData>[],
|
|
55
59
|
): string {
|
|
56
60
|
const site = (feed.site ?? currentApp.site() ?? '').replace(/\/$/, '')
|
|
57
|
-
const prefix = (feed.linkPrefix ?? '').replace(/\/$/, '')
|
|
61
|
+
const prefix = encodePathSegments((feed.linkPrefix ?? '').replace(/\/$/, ''))
|
|
58
62
|
const items = entries
|
|
59
63
|
.filter(entry => entry.data === null || typeof entry.data !== 'object' || (entry.data as Record<string, unknown>).draft !== true)
|
|
60
64
|
.map((entry) => {
|
|
61
65
|
const rawData = (entry.data !== null && typeof entry.data === 'object' ? entry.data : {}) as Record<string, unknown>
|
|
66
|
+
const defaultLink = `${site}${prefix}/${encodePathSegments(entry.slug)}`
|
|
62
67
|
const mapped = feed.mapItem
|
|
63
68
|
? feed.mapItem(entry)
|
|
64
69
|
: {
|
|
65
70
|
title: String(rawData.title ?? entry.slug),
|
|
66
71
|
description: typeof rawData.description === 'string' ? rawData.description : undefined,
|
|
67
72
|
date: rawData.date as string | Date | undefined,
|
|
68
|
-
link:
|
|
73
|
+
link: defaultLink,
|
|
69
74
|
}
|
|
70
|
-
const link = mapped.link ??
|
|
75
|
+
const link = mapped.link ?? defaultLink
|
|
71
76
|
const pubDate = formatPubDate(mapped.date)
|
|
72
77
|
const desc = mapped.description ? `<description>${escXml(mapped.description)}</description>` : ''
|
|
73
78
|
return `<item><title>${escXml(mapped.title)}</title><link>${escXml(link)}</link><guid>${escXml(link)}</guid>${pubDate}${desc}</item>`
|