@prunellejs/content 0.1.1 → 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,263 @@
1
+ // Loader-backed async collection implementation (`defineCollection({ load, ... })`) for headless CMSs, databases, and APIs.
2
+
3
+ import type { AppRuntimeContext, RequestContext } from 'prunelle/internal/server'
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+ import type {
6
+ AsyncCollection,
7
+ ContentEntry,
8
+ InternalCollection,
9
+ LoadedEntryInput,
10
+ LoaderCollectionOptions,
11
+ } from './types'
12
+ import { relative } from 'node:path'
13
+ import { currentRequest, getAppContext } from 'prunelle/internal/server'
14
+ import { formatIssuePath, formatSchemaIssues, validateSchema } from 'prunelle/server'
15
+ import { currentApp } from './app'
16
+ import {
17
+ buildContentEntry,
18
+ createRenderConfigLoader,
19
+ defaultSort,
20
+ filterByTag,
21
+ formatPaths,
22
+ isDevMode,
23
+ isDraft,
24
+ } from './entry'
25
+ import { currentDiscoverFile, registerLoadedCollection } from './registry'
26
+ import { CONTENT_PRERENDER_SERVICE } from './service'
27
+ import {
28
+ COLLECTION_DIR_FOR_ROOT_KEY,
29
+ COLLECTION_META_KEY,
30
+ COLLECTION_VALIDATE_KEY,
31
+ COLLECTION_VERSION_KEY,
32
+ } from './types'
33
+
34
+ function cleanSlug(rawSlug: unknown, collectionName: string): string {
35
+ if (typeof rawSlug !== 'string' || rawSlug.trim() === '')
36
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" is missing a non-empty string "slug".`)
37
+ const cleaned = rawSlug.trim().replace(/^\/+|\/+$/g, '')
38
+ if (cleaned === '')
39
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" has an empty "slug".`)
40
+ return cleaned
41
+ }
42
+
43
+ function getOrCreateLocaleMap<K extends object, T>(
44
+ store: WeakMap<K, Map<string, Promise<ContentEntry<T>[]>>>,
45
+ key: K,
46
+ ): Map<string, Promise<ContentEntry<T>[]>> {
47
+ let map = store.get(key)
48
+ if (map === undefined) {
49
+ map = new Map()
50
+ store.set(key, map)
51
+ }
52
+ return map
53
+ }
54
+
55
+ function formatCheckPrefix(root: string, sourceFile: string | undefined): string {
56
+ if (sourceFile === undefined)
57
+ return ''
58
+ const rel = relative(root, sourceFile).replace(/\\/g, '/')
59
+ return `${rel}:1:1: error: `
60
+ }
61
+
62
+ async function validateLoadedEntriesForCheck(params: {
63
+ name: string
64
+ root: string
65
+ sourceFile: string | undefined
66
+ localized: boolean
67
+ defaultLocale: string
68
+ locales: readonly string[] | undefined
69
+ schema: StandardSchemaV1 | undefined
70
+ load: LoaderCollectionOptions<unknown>['load']
71
+ }): Promise<string[]> {
72
+ const { name, root, sourceFile, localized, defaultLocale, locales, schema, load } = params
73
+ const prefix = formatCheckPrefix(root, sourceFile)
74
+ const errors: string[] = []
75
+ const seenEntries = new Set<string>()
76
+
77
+ const configuredLocales = localized ? (locales ?? currentApp.locales()) : undefined
78
+ const runs: Array<{ locale: string | undefined, filterByLocale: boolean }> = !localized
79
+ ? [{ locale: undefined, filterByLocale: false }]
80
+ : configuredLocales !== undefined && configuredLocales.length > 0
81
+ ? [...new Set(configuredLocales)].map(locale => ({ locale, filterByLocale: true }))
82
+ : [{ locale: defaultLocale, filterByLocale: false }]
83
+
84
+ for (const run of runs) {
85
+ let rawEntries: LoadedEntryInput[]
86
+ try {
87
+ rawEntries = await load(localized ? { locale: run.locale } : {})
88
+ }
89
+ catch (err) {
90
+ const msg = err instanceof Error ? err.message : String(err)
91
+ const locNote = run.locale !== undefined ? ` (locale "${run.locale}")` : ''
92
+ errors.push(`${prefix}@prunellejs/content: collection "${name}"${locNote} loader failed: ${msg}`)
93
+ continue
94
+ }
95
+
96
+ for (const raw of rawEntries) {
97
+ if (run.filterByLocale && raw.locale !== undefined && raw.locale !== run.locale)
98
+ continue
99
+ if (typeof raw.slug !== 'string' || raw.slug.trim() === '') {
100
+ errors.push(`${prefix}@prunellejs/content: collection "${name}": entry is missing a non-empty string "slug"`)
101
+ continue
102
+ }
103
+ const slug = raw.slug.trim().replace(/^\/+|\/+$/g, '')
104
+ const entryLocale = localized ? (raw.locale ?? run.locale) : raw.locale
105
+ const dedupeKey = `${entryLocale ?? ''}\0${slug}`
106
+ if (seenEntries.has(dedupeKey))
107
+ continue
108
+ seenEntries.add(dedupeKey)
109
+
110
+ if (schema === undefined)
111
+ continue
112
+ const checked = await validateSchema(schema, raw.data)
113
+ if (!checked.ok) {
114
+ const locSuffix = entryLocale !== undefined ? ` (${entryLocale})` : ''
115
+ for (const issue of checked.issues) {
116
+ const path = formatIssuePath(issue)
117
+ errors.push(`${prefix}@prunellejs/content: collection "${name}" entry "${slug}"${locSuffix}: ${path ? `${path}: ` : ''}${issue.message}`)
118
+ }
119
+ }
120
+ }
121
+ }
122
+ return errors
123
+ }
124
+
125
+ export function createLoaderCollection<TData = Record<string, unknown>>(
126
+ options: LoaderCollectionOptions<TData>,
127
+ ): AsyncCollection<TData> {
128
+ const name = options.name ?? 'collection'
129
+ const localized = options.localized ?? false
130
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
131
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
132
+ const renderLoader = createRenderConfigLoader(name, options)
133
+ const sourceFile = currentDiscoverFile()
134
+
135
+ let buildCache = new WeakMap<AppRuntimeContext, Map<string, Promise<ContentEntry<TData>[]>>>()
136
+ let requestCache = new WeakMap<RequestContext, Map<string, Promise<ContentEntry<TData>[]>>>()
137
+ let lastBuildCtx: WeakRef<AppRuntimeContext> | undefined
138
+ let cacheVersion = 0
139
+
140
+ function resolveCacheMap(): Map<string, Promise<ContentEntry<TData>[]>> | undefined {
141
+ const reqCtx = currentRequest()?.ctx
142
+ const appCtx = getAppContext()
143
+ if (reqCtx === undefined && appCtx !== undefined) {
144
+ lastBuildCtx = new WeakRef(appCtx)
145
+ return getOrCreateLocaleMap(buildCache, appCtx)
146
+ }
147
+ if (reqCtx !== undefined) {
148
+ const buildCtx = lastBuildCtx?.deref()
149
+ if (
150
+ buildCtx !== undefined
151
+ && appCtx !== undefined
152
+ && appCtx.root === buildCtx.root
153
+ && appCtx.outDir === buildCtx.outDir
154
+ )
155
+ return getOrCreateLocaleMap(buildCache, buildCtx)
156
+ if (appCtx?.inject(CONTENT_PRERENDER_SERVICE) === true)
157
+ return getOrCreateLocaleMap(buildCache, appCtx)
158
+ return getOrCreateLocaleMap(requestCache, reqCtx)
159
+ }
160
+ return undefined
161
+ }
162
+
163
+ async function loadValidatedEntries(targetLocale: string | undefined): Promise<ContentEntry<TData>[]> {
164
+ const rawEntries = await options.load(localized ? { locale: targetLocale } : {})
165
+ const entries: ContentEntry<TData>[] = []
166
+ for (const raw of rawEntries) {
167
+ if (localized && raw.locale !== undefined && raw.locale !== targetLocale)
168
+ continue
169
+ const slug = cleanSlug(raw.slug, name)
170
+ let data: TData
171
+ if (options.schema !== undefined) {
172
+ const checked = await validateSchema(options.schema, raw.data)
173
+ if (!checked.ok) {
174
+ throw new Error(
175
+ `@prunellejs/content: invalid entry "${slug}" in collection "${name}": ${formatSchemaIssues(checked.issues)}`,
176
+ )
177
+ }
178
+ data = checked.value
179
+ }
180
+ else {
181
+ data = (raw.data !== null && typeof raw.data === 'object' ? raw.data : {}) as TData
182
+ }
183
+ const entryLocale = localized ? (raw.locale ?? targetLocale) : raw.locale
184
+ const file = raw.id ?? `${name}:${slug}`
185
+ entries.push(buildContentEntry({
186
+ slug,
187
+ locale: entryLocale,
188
+ file,
189
+ data,
190
+ body: raw.body ?? '',
191
+ renderLoader,
192
+ }))
193
+ }
194
+ entries.sort(options.sort ?? defaultSort)
195
+ return entries
196
+ }
197
+
198
+ function loadCached(locale?: string): Promise<ContentEntry<TData>[]> {
199
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
200
+ const cacheKey = targetLocale ?? ''
201
+ const bucket = resolveCacheMap()
202
+ if (bucket !== undefined) {
203
+ const hit = bucket.get(cacheKey)
204
+ if (hit !== undefined)
205
+ return hit
206
+ const pending = loadValidatedEntries(targetLocale).catch((err) => {
207
+ bucket.delete(cacheKey)
208
+ throw err
209
+ })
210
+ bucket.set(cacheKey, pending)
211
+ return pending
212
+ }
213
+ return loadValidatedEntries(targetLocale)
214
+ }
215
+
216
+ async function all(locale?: string): Promise<ContentEntry<TData>[]> {
217
+ const entries = await loadCached(locale)
218
+ return allowsDrafts() ? entries.slice() : entries.filter(e => !isDraft(e.data))
219
+ }
220
+
221
+ async function get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined> {
222
+ const clean = slug.replace(/^\/+|\/+$/g, '')
223
+ const entries = await all(locale)
224
+ return entries.find(e => e.slug === clean)
225
+ }
226
+
227
+ const col: AsyncCollection<TData> & InternalCollection = {
228
+ name,
229
+ all,
230
+ get,
231
+ byTag: async (tag, locale) => filterByTag(await all(locale), tag),
232
+ paths: async (prefix = '', locale) => formatPaths(await all(locale), prefix),
233
+ clearCache() {
234
+ buildCache = new WeakMap()
235
+ requestCache = new WeakMap()
236
+ lastBuildCtx = undefined
237
+ cacheVersion++
238
+ },
239
+ [COLLECTION_VERSION_KEY]: () => cacheVersion,
240
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateLoadedEntriesForCheck({
241
+ name,
242
+ root,
243
+ sourceFile,
244
+ localized,
245
+ defaultLocale: getDefaultLocale(),
246
+ locales: options.locales,
247
+ schema: options.schema,
248
+ load: options.load,
249
+ }),
250
+ [COLLECTION_DIR_FOR_ROOT_KEY]: () => undefined,
251
+ [COLLECTION_META_KEY]: () => ({
252
+ name,
253
+ localized,
254
+ defaultLocale: getDefaultLocale(),
255
+ locales: options.locales ?? (localized ? currentApp.locales() : undefined),
256
+ schema: options.schema,
257
+ isAsync: true,
258
+ }),
259
+ }
260
+
261
+ registerLoadedCollection(col, options.name, localized)
262
+ return col
263
+ }
package/src/markdown.ts CHANGED
@@ -33,7 +33,8 @@ function findDefaultImageResolver(file: string | undefined): MarkdownImageResolv
33
33
  return currentApp.imageResolver()
34
34
  }
35
35
 
36
- const FENCE_RE = /^([`~]{3,})([^\n]*)\n([\s\S]*?)^\1[ \t]*$/gm
36
+ // CommonMark §4.5: backtick fence info strings cannot contain backticks; fences cannot mix ` and ~.
37
+ const FENCE_RE = /^(?:(`{3,})([^`\n]*)|(~{3,})([^\n]*))\n([\s\S]*?)^\1\3[ \t]*$/gm
37
38
  let slotBatchId = 0
38
39
 
39
40
  function renderMarkdownInternal(
@@ -55,7 +56,15 @@ function renderMarkdownInternal(
55
56
 
56
57
  // 1. Extract fenced code blocks before component expansion so `<Tag>` inside ```code``` is never treated as a component
57
58
  if (options.highlight !== undefined || options.components !== undefined) {
58
- processed = processed.replace(FENCE_RE, (full, _fence: string, info: string, code: string) => {
59
+ processed = processed.replace(FENCE_RE, (
60
+ full,
61
+ btFence: string | undefined,
62
+ btInfo: string | undefined,
63
+ _tildeFence: string | undefined,
64
+ tildeInfo: string | undefined,
65
+ code: string,
66
+ ) => {
67
+ const info = btFence !== undefined ? (btInfo ?? '') : (tildeInfo ?? '')
59
68
  if (options.highlight !== undefined) {
60
69
  const lang = info.trim().split(/\s+/)[0] || undefined
61
70
  const idx = slots.length
@@ -64,7 +73,10 @@ function renderMarkdownInternal(
64
73
  }
65
74
  // Protect code fences from component expansion when only components are configured
66
75
  const idx = slots.length
67
- slots.push(Bun.markdown.html(full, { tables: true, strikethrough: true, tasklists: true, autolinks: true }))
76
+ let renderedFence = Bun.markdown.html(full, { tables: true, strikethrough: true, tasklists: true, autolinks: true })
77
+ if (options.trusted !== true)
78
+ renderedFence = sanitizeMarkdownHtml(renderedFence)
79
+ slots.push(renderedFence)
68
80
  return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
69
81
  })
70
82
  }
@@ -0,0 +1,135 @@
1
+ // Process-level collection registry and `src/` file discovery for `prunelle check` and `CONTENT_COLLECTIONS_SERVICE`.
2
+
3
+ import type { InternalCollection } from './types'
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
+ import { isAbsolute, join, resolve } from 'node:path'
6
+ import { currentApp } from './app'
7
+ import { COLLECTION_OWNER_ROOT_KEY, COLLECTION_VALIDATE_KEY } from './types'
8
+
9
+ // Keyed by (ownerRoot, resolved dir or loader identity, localized) so dev reloads replace the prior instance instead of leaking.
10
+ export const registeredCollections = new Map<string, InternalCollection>()
11
+
12
+ let discoverRoot: string | undefined
13
+ let discoverFile: string | undefined
14
+ let discoverIndex = 0
15
+ let anonLoaderSeq = 0
16
+
17
+ export function currentDiscoverFile(): string | undefined {
18
+ return discoverFile
19
+ }
20
+
21
+ function resolveOwnerRoot(rawDir?: string): string | undefined {
22
+ const owner = discoverRoot ?? currentApp.root()
23
+ const explicitOwner = owner !== undefined && owner !== '' ? resolve(owner) : undefined
24
+ if (explicitOwner !== undefined)
25
+ return explicitOwner
26
+ if (rawDir !== undefined && !isAbsolute(rawDir))
27
+ return resolve(process.cwd())
28
+ return undefined
29
+ }
30
+
31
+ export function registerFileCollection(col: InternalCollection, rawDir: string, localized: boolean): void {
32
+ const absOwner = resolveOwnerRoot(rawDir)
33
+ col[COLLECTION_OWNER_ROOT_KEY] = absOwner
34
+ const resolvedKey = isAbsolute(rawDir)
35
+ ? resolve(rawDir)
36
+ : (absOwner !== undefined ? resolve(absOwner, rawDir) : rawDir)
37
+ registeredCollections.set(`${absOwner ?? ''}\0${resolvedKey}\0${localized ? '1' : '0'}`, col)
38
+ }
39
+
40
+ export function registerLoadedCollection(
41
+ col: InternalCollection,
42
+ explicitName: string | undefined,
43
+ localized: boolean,
44
+ ): void {
45
+ const absOwner = resolveOwnerRoot()
46
+ col[COLLECTION_OWNER_ROOT_KEY] = absOwner
47
+ const identity = explicitName !== undefined && explicitName !== ''
48
+ ? `load:name:${explicitName}`
49
+ : discoverFile !== undefined
50
+ ? `load:file:${discoverFile}#${discoverIndex++}`
51
+ : `load:anon:${++anonLoaderSeq}`
52
+ registeredCollections.set(`${absOwner ?? ''}\0${identity}\0${localized ? '1' : '0'}`, col)
53
+ }
54
+
55
+ export function walkCollectionDefFiles(dir: string, out: string[] = []): string[] {
56
+ if (!existsSync(dir))
57
+ return out
58
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
59
+ if (ent.name === 'node_modules' || ent.name === 'dist' || ent.name.startsWith('.'))
60
+ continue
61
+ const full = join(dir, ent.name)
62
+ if (ent.isDirectory())
63
+ walkCollectionDefFiles(full, out)
64
+ else if (ent.isFile() && (ent.name.endsWith('.ts') || ent.name.endsWith('.tsx')) && !ent.name.endsWith('.d.ts') && !/\.(?:test|spec)\.tsx?$/.test(ent.name))
65
+ out.push(full)
66
+ }
67
+ return out
68
+ }
69
+
70
+ export const DEFINE_COLLECTION_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(/
71
+ const REGEXP_SPECIAL_RE = /[.*+?^${}()|[\]\\]/g
72
+
73
+ const prunelleJsxRoots = new Set<string>()
74
+
75
+ // Bun gives a runtime import the JSX source of the working directory's tsconfig, not the app's, so `prunelle check <dir>` run elsewhere would import its routes as React.
76
+ function importAppTsxWithPrunelleJsx(root: string): void {
77
+ if (prunelleJsxRoots.has(root))
78
+ return
79
+ prunelleJsxRoots.add(root)
80
+ const filter = new RegExp(`^${`${root}/`.replace(REGEXP_SPECIAL_RE, '\\$&')}.*\\.tsx$`)
81
+ Bun.plugin({
82
+ name: `@prunellejs/content: prunelle JSX under ${root}`,
83
+ setup(build) {
84
+ // The pragma goes last, where it moves no line of a stack trace.
85
+ build.onLoad({ filter }, async ({ path }) => ({ contents: `${await Bun.file(path).text()}\n/** @jsxImportSource prunelle */\n`, loader: 'tsx' }))
86
+ },
87
+ })
88
+ }
89
+
90
+ export async function discoverAppCollections(root: string): Promise<void> {
91
+ const absRoot = resolve(root)
92
+ const prevDiscoverRoot = discoverRoot
93
+ const prevDiscoverFile = discoverFile
94
+ const prevDiscoverIndex = discoverIndex
95
+ discoverRoot = absRoot
96
+ try {
97
+ importAppTsxWithPrunelleJsx(absRoot)
98
+ const srcDir = resolve(absRoot, 'src')
99
+ for (const file of walkCollectionDefFiles(srcDir)) {
100
+ let text: string
101
+ try {
102
+ text = readFileSync(file, 'utf8')
103
+ }
104
+ catch {
105
+ continue
106
+ }
107
+ if (!DEFINE_COLLECTION_RE.test(text))
108
+ continue
109
+ discoverFile = file
110
+ discoverIndex = 0
111
+ try {
112
+ const mod = await import(file) as Record<string, unknown>
113
+ for (const val of Object.values(mod)) {
114
+ if (val !== null && typeof val === 'object' && COLLECTION_VALIDATE_KEY in val) {
115
+ const col = val as InternalCollection
116
+ if (col[COLLECTION_OWNER_ROOT_KEY] === undefined) {
117
+ col[COLLECTION_OWNER_ROOT_KEY] = absRoot
118
+ const label = col.name ?? `file:${file}#${discoverIndex++}`
119
+ registeredCollections.set(`${absRoot}\0adopted:${file}:${label}`, col)
120
+ }
121
+ }
122
+ }
123
+ }
124
+ catch {
125
+ // Route/TSX files may import virtual modules (~icons) or CSS outside Bun.build; skip unimportable files.
126
+ continue
127
+ }
128
+ }
129
+ }
130
+ finally {
131
+ discoverRoot = prevDiscoverRoot
132
+ discoverFile = prevDiscoverFile
133
+ discoverIndex = prevDiscoverIndex
134
+ }
135
+ }
package/src/rss.ts CHANGED
@@ -1,17 +1,20 @@
1
1
  // RSS 2.0 XML feed generation and ETag matching for @prunellejs/content.
2
2
 
3
- import type { Collection, ContentEntry } from './collection'
3
+ import type { AnyCollection, Collection, ContentEntry } from './types'
4
4
  import { escAttr } from 'prunelle/server'
5
5
  import { currentApp } from './app'
6
6
 
7
- export interface RssFeedConfig<TData = Record<string, unknown>> {
7
+ export interface RssFeedConfig<
8
+ TData = Record<string, unknown>,
9
+ TCol extends AnyCollection<TData> = Collection<TData>,
10
+ > {
8
11
  /** Public path for the RSS XML file (default: '/rss.xml'). */
9
12
  path?: string | undefined
10
13
  title: string
11
14
  description: string
12
15
  /** Public site origin; defaults to `PrunelleConfig.site` when registered via `content()`. */
13
16
  site?: string | undefined
14
- collection: Collection<TData>
17
+ collection: TCol
15
18
  locale?: string | undefined
16
19
  /** URL prefix prepended to each entry's slug (e.g. '/blog'). */
17
20
  linkPrefix?: string | undefined
@@ -28,7 +31,7 @@ export interface ContentFeed {
28
31
  readonly title: string
29
32
  readonly description: string
30
33
  readonly site?: string | undefined
31
- readonly collection: Collection<unknown>
34
+ readonly collection: AnyCollection<unknown>
32
35
  readonly locale?: string | undefined
33
36
  readonly linkPrefix?: string | undefined
34
37
  readonly mapItem?: ((entry: ContentEntry<never>) => {
@@ -46,24 +49,29 @@ function formatPubDate(value: string | Date | undefined): string {
46
49
  return Number.isNaN(date.getTime()) ? '' : `<pubDate>${date.toUTCString()}</pubDate>`
47
50
  }
48
51
 
49
- export function renderRss<TData>(feed: RssFeedConfig<TData>): string {
52
+ function buildRssXml<TData>(
53
+ feed: Pick<RssFeedConfig<TData, AnyCollection<TData>>, 'title' | 'description' | 'site' | 'linkPrefix' | 'mapItem'>,
54
+ entries: readonly ContentEntry<TData>[],
55
+ ): string {
50
56
  const site = (feed.site ?? currentApp.site() ?? '').replace(/\/$/, '')
51
57
  const prefix = (feed.linkPrefix ?? '').replace(/\/$/, '')
52
- const items = feed.collection.all(feed.locale).map((entry) => {
53
- const rawData = entry.data as Record<string, unknown>
54
- const mapped = feed.mapItem
55
- ? feed.mapItem(entry)
56
- : {
57
- title: String(rawData.title ?? entry.slug),
58
- description: typeof rawData.description === 'string' ? rawData.description : undefined,
59
- date: rawData.date as string | Date | undefined,
60
- link: `${site}${prefix}/${entry.slug}`,
61
- }
62
- const link = mapped.link ?? `${site}${prefix}/${entry.slug}`
63
- const pubDate = formatPubDate(mapped.date)
64
- const desc = mapped.description ? `<description>${escAttr(mapped.description)}</description>` : ''
65
- return `<item><title>${escAttr(mapped.title)}</title><link>${escAttr(link)}</link><guid>${escAttr(link)}</guid>${pubDate}${desc}</item>`
66
- }).join('')
58
+ const items = entries
59
+ .filter(entry => entry.data === null || typeof entry.data !== 'object' || (entry.data as Record<string, unknown>).draft !== true)
60
+ .map((entry) => {
61
+ const rawData = (entry.data !== null && typeof entry.data === 'object' ? entry.data : {}) as Record<string, unknown>
62
+ const mapped = feed.mapItem
63
+ ? feed.mapItem(entry)
64
+ : {
65
+ title: String(rawData.title ?? entry.slug),
66
+ description: typeof rawData.description === 'string' ? rawData.description : undefined,
67
+ date: rawData.date as string | Date | undefined,
68
+ link: `${site}${prefix}/${entry.slug}`,
69
+ }
70
+ const link = mapped.link ?? `${site}${prefix}/${entry.slug}`
71
+ const pubDate = formatPubDate(mapped.date)
72
+ const desc = mapped.description ? `<description>${escAttr(mapped.description)}</description>` : ''
73
+ return `<item><title>${escAttr(mapped.title)}</title><link>${escAttr(link)}</link><guid>${escAttr(link)}</guid>${pubDate}${desc}</item>`
74
+ }).join('')
67
75
 
68
76
  return `<?xml version="1.0" encoding="UTF-8"?>`
69
77
  + `<rss version="2.0"><channel>`
@@ -74,6 +82,18 @@ export function renderRss<TData>(feed: RssFeedConfig<TData>): string {
74
82
  + `</channel></rss>`
75
83
  }
76
84
 
85
+ export function renderRss<TData>(feed: RssFeedConfig<TData>): string {
86
+ const entries = feed.collection.all(feed.locale) as ContentEntry<TData>[] | Promise<ContentEntry<TData>[]>
87
+ if (entries instanceof Promise)
88
+ throw new TypeError('@prunellejs/content: renderRss() is synchronous; use `await renderRssAsync()` for loader-backed collections.')
89
+ return buildRssXml(feed, entries)
90
+ }
91
+
92
+ export async function renderRssAsync<TData>(feed: RssFeedConfig<TData, AnyCollection<TData>>): Promise<string> {
93
+ const entries = await feed.collection.all(feed.locale)
94
+ return buildRssXml(feed, entries)
95
+ }
96
+
77
97
  export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
78
98
  if (!ifNoneMatch)
79
99
  return false
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
+ }