@prunellejs/content 0.7.3 → 0.7.4
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 +1 -1
- package/package.json +2 -2
- package/src/entry.ts +16 -5
- package/src/markdown.ts +108 -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
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/content",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
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.7.
|
|
24
|
+
"prunelle": "^0.7.4"
|
|
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,111 @@ 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
|
+
|
|
9
27
|
function slugifyHeading(text: string): string {
|
|
10
28
|
return text
|
|
11
|
-
.
|
|
29
|
+
.replace(/<[^>]+>/g, '')
|
|
12
30
|
.normalize('NFKD')
|
|
13
31
|
.replace(/[\u0300-\u036F]/g, '')
|
|
14
|
-
.
|
|
15
|
-
.
|
|
32
|
+
.normalize('NFC')
|
|
33
|
+
.toLowerCase()
|
|
34
|
+
.replace(/[^\p{L}\p{M}\p{N}]+/gu, '-')
|
|
16
35
|
.replace(/^-+|-+$/g, '') || 'section'
|
|
17
36
|
}
|
|
18
37
|
|
|
19
38
|
function stripTags(html: string): string {
|
|
20
|
-
return html
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
return decodeHtmlEntities(html.replace(/<[^>]+>/g, '')).trim()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function allocateHeadingId(base: string, usedIds: Set<string>): string {
|
|
43
|
+
if (!usedIds.has(base)) {
|
|
44
|
+
usedIds.add(base)
|
|
45
|
+
return base
|
|
46
|
+
}
|
|
47
|
+
let n = 1
|
|
48
|
+
while (usedIds.has(`${base}-${n}`))
|
|
49
|
+
n++
|
|
50
|
+
const id = `${base}-${n}`
|
|
51
|
+
usedIds.add(id)
|
|
52
|
+
return id
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function assignHeadingIds(
|
|
56
|
+
html: string,
|
|
57
|
+
headingLinks: boolean | undefined,
|
|
58
|
+
): { html: string, headings: ContentHeading[] } {
|
|
59
|
+
const headings: ContentHeading[] = []
|
|
60
|
+
const usedIds = new Set<string>()
|
|
61
|
+
for (const m of html.matchAll(/<h[1-6]\b[^>]*\bid="([^"]+)"/gi))
|
|
62
|
+
usedIds.add(m[1]!)
|
|
63
|
+
|
|
64
|
+
const nextHtml = html.replace(/<h([1-6])>([\s\S]*?)<\/h\1>/g, (_match, levelStr: string, inner: string) => {
|
|
65
|
+
const level = Number(levelStr)
|
|
66
|
+
const text = stripTags(inner)
|
|
67
|
+
const id = allocateHeadingId(slugifyHeading(text), usedIds)
|
|
68
|
+
headings.push({ level, id, text })
|
|
69
|
+
if (headingLinks && level >= 2 && !/<a\b/i.test(inner))
|
|
70
|
+
return `<h${level} id="${id}"><a href="#${id}">${inner}</a></h${level}>`
|
|
71
|
+
return `<h${level} id="${id}">${inner}</h${level}>`
|
|
72
|
+
})
|
|
73
|
+
return { html: nextHtml, headings }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function rewriteMarkdownImages(
|
|
77
|
+
html: string,
|
|
78
|
+
resolveImageFn: MarkdownImageResolver,
|
|
79
|
+
file: string | undefined,
|
|
80
|
+
): string {
|
|
81
|
+
// The first image is often the page's largest paint, which lazy loading would hold back.
|
|
82
|
+
let seen = 0
|
|
83
|
+
return html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
|
|
84
|
+
const first = seen++ === 0
|
|
85
|
+
const srcMatch = /(?:^|\s)src="([^"]+)"/i.exec(attrs)
|
|
86
|
+
if (!srcMatch)
|
|
87
|
+
return full
|
|
88
|
+
const resolved = resolveImageFn(decodeHtmlEntities(srcMatch[1]!), file)
|
|
89
|
+
if (!resolved)
|
|
90
|
+
return full
|
|
91
|
+
const info: MarkdownImageResult = typeof resolved === 'string' ? { src: resolved } : resolved
|
|
92
|
+
const altMatch = /(?:^|\s)alt="([^"]*)"/i.exec(attrs)
|
|
93
|
+
const alt = altMatch ? altMatch[1]! : ''
|
|
94
|
+
const titleMatch = /(?:^|\s)title="([^"]*)"/i.exec(attrs)
|
|
95
|
+
const parts = [`src="${escAttr(info.src)}"`, `alt="${alt}"`]
|
|
96
|
+
if (titleMatch !== null && titleMatch[1] !== '')
|
|
97
|
+
parts.push(`title="${titleMatch[1]!}"`)
|
|
98
|
+
if (info.srcset)
|
|
99
|
+
parts.push(`srcset="${escAttr(info.srcset)}"`)
|
|
100
|
+
if (info.sizes)
|
|
101
|
+
parts.push(`sizes="${escAttr(info.sizes)}"`)
|
|
102
|
+
if (info.width !== undefined && info.width > 0)
|
|
103
|
+
parts.push(`width="${info.width}"`)
|
|
104
|
+
if (info.height !== undefined && info.height > 0)
|
|
105
|
+
parts.push(`height="${info.height}"`)
|
|
106
|
+
parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
|
|
107
|
+
const imgTag = `<img ${parts.join(' ')}>`
|
|
108
|
+
if (info.avifSrcset) {
|
|
109
|
+
const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
|
|
110
|
+
return `<picture><source type="image/avif" srcset="${escAttr(info.avifSrcset)}"${sizesAttr}>${imgTag}</picture>`
|
|
111
|
+
}
|
|
112
|
+
return imgTag
|
|
113
|
+
})
|
|
28
114
|
}
|
|
29
115
|
|
|
30
116
|
function findDefaultImageResolver(file: string | undefined): MarkdownImageResolver | undefined {
|
|
@@ -99,59 +185,12 @@ function renderMarkdownInternal(
|
|
|
99
185
|
if (options.trusted !== true)
|
|
100
186
|
html = sanitizeMarkdownHtml(html, allowedSlotPrefixes)
|
|
101
187
|
|
|
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)
|
|
188
|
+
// 4. Image rewriting (explicit resolveImage or auto-wired @prunellejs/images; `false` disables)
|
|
120
189
|
const resolveImageFn = options.resolveImage === false
|
|
121
190
|
? undefined
|
|
122
191
|
: (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
|
-
}
|
|
192
|
+
if (resolveImageFn !== undefined)
|
|
193
|
+
html = rewriteMarkdownImages(html, resolveImageFn, options.file)
|
|
155
194
|
|
|
156
195
|
// 5. Splice this batch's highlighted code blocks & embedded TSX components back in (loop handles components wrapping code fences)
|
|
157
196
|
if (slots.length > 0) {
|
|
@@ -163,6 +202,14 @@ function renderMarkdownInternal(
|
|
|
163
202
|
}
|
|
164
203
|
}
|
|
165
204
|
|
|
205
|
+
// 6. Add unique heading IDs & collect TOC in document order on the top-level render (including headings inside component children)
|
|
206
|
+
let headings: ContentHeading[] = []
|
|
207
|
+
if (inheritedSlotPrefixes === undefined) {
|
|
208
|
+
const assigned = assignHeadingIds(html, options.headingLinks)
|
|
209
|
+
html = assigned.html
|
|
210
|
+
headings = assigned.headings
|
|
211
|
+
}
|
|
212
|
+
|
|
166
213
|
const words = body.trim().split(/\s+/).filter(Boolean).length
|
|
167
214
|
const readingMinutes = Math.max(1, Math.ceil(words / 220))
|
|
168
215
|
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>`
|