@prunellejs/content 0.1.1 → 0.7.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,308 @@
1
+ // File-backed Markdown collection implementation (`defineCollection({ dir, ... })`).
2
+
3
+ import type { StandardSchemaV1 } from 'prunelle/server'
4
+ import type {
5
+ Collection,
6
+ CollectionOptions,
7
+ ContentEntry,
8
+ InternalCollection,
9
+ } from './types'
10
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
11
+ import { basename, isAbsolute, join, relative, resolve } from 'node:path'
12
+ import { isInside } from 'prunelle/config'
13
+ import { formatIssuePath, formatSchemaIssues, validateSchemaSync } from 'prunelle/server'
14
+ import { currentApp } from './app'
15
+ import {
16
+ buildContentEntry,
17
+ createRenderConfigLoader,
18
+ defaultSort,
19
+ filterByTag,
20
+ formatPaths,
21
+ isDevMode,
22
+ isDraft,
23
+ } from './entry'
24
+ import { findFrontmatterFieldLine, parseFrontmatter } from './frontmatter'
25
+ import { registerFileCollection } from './registry'
26
+ import { recordAccessedEntry } from './tracking'
27
+ import {
28
+ COLLECTION_DIR_FOR_ROOT_KEY,
29
+ COLLECTION_META_KEY,
30
+ COLLECTION_VALIDATE_KEY,
31
+ } from './types'
32
+
33
+ export function resolveCollectionDir(dir: string, explicitRoot?: string): string {
34
+ if (isAbsolute(dir))
35
+ return dir
36
+ const prunelleRoot = explicitRoot ?? currentApp.root()
37
+ if (typeof prunelleRoot === 'string' && prunelleRoot !== '') {
38
+ const candidate = resolve(prunelleRoot, dir)
39
+ if (existsSync(candidate))
40
+ return candidate
41
+ }
42
+ return resolve(dir)
43
+ }
44
+
45
+ function walkMarkdownFiles(dir: string, out: string[] = []): string[] {
46
+ if (!existsSync(dir))
47
+ return out
48
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
49
+ const full = join(dir, ent.name)
50
+ if (ent.isDirectory())
51
+ walkMarkdownFiles(full, out)
52
+ else if (ent.isFile() && (ent.name.endsWith('.md') || ent.name.endsWith('.markdown')))
53
+ out.push(full)
54
+ }
55
+ return out
56
+ }
57
+
58
+ function listLocaleDirs(absDir: string): string[] | undefined {
59
+ if (!existsSync(absDir))
60
+ return undefined
61
+ const locales = readdirSync(absDir, { withFileTypes: true })
62
+ .filter(ent => ent.isDirectory() && !ent.name.startsWith('.'))
63
+ .map(ent => ent.name)
64
+ .sort()
65
+ return locales.length > 0 ? locales : undefined
66
+ }
67
+
68
+ function validateCollectionFiles(
69
+ absDir: string,
70
+ root: string,
71
+ schema: StandardSchemaV1 | undefined,
72
+ ): string[] {
73
+ if (!existsSync(absDir))
74
+ return []
75
+ const errors: string[] = []
76
+ for (const absFile of walkMarkdownFiles(absDir).sort()) {
77
+ const rel = relative(root, absFile).replace(/\\/g, '/')
78
+ const rawSource = readFileSync(absFile, 'utf8')
79
+ let rawData: Record<string, unknown>
80
+ try {
81
+ rawData = parseFrontmatter(rawSource).data
82
+ }
83
+ catch (err) {
84
+ const msg = err instanceof Error ? err.message : String(err)
85
+ errors.push(`${rel}:1:1: error: @prunellejs/content: invalid YAML frontmatter: ${msg}`)
86
+ continue
87
+ }
88
+ if (schema === undefined)
89
+ continue
90
+ const checked = validateSchemaSync(
91
+ schema,
92
+ rawData,
93
+ `@prunellejs/content: async frontmatter schema is not supported (${rel})`,
94
+ )
95
+ if (!checked.ok) {
96
+ for (const issue of checked.issues) {
97
+ const path = formatIssuePath(issue)
98
+ const line = findFrontmatterFieldLine(rawSource, path || undefined)
99
+ errors.push(`${rel}:${line}:1: error: @prunellejs/content: ${path ? `${path}: ` : ''}${issue.message}`)
100
+ }
101
+ }
102
+ }
103
+ return errors
104
+ }
105
+
106
+ // Slugs and locales usually come from URL params: a path built from them must stay inside the collection folder.
107
+ function localeDir(absDir: string, targetLocale: string | undefined): string | undefined {
108
+ if (targetLocale === undefined)
109
+ return absDir
110
+ const scanDir = resolve(absDir, targetLocale)
111
+ return isInside(absDir, scanDir) ? scanDir : undefined
112
+ }
113
+
114
+ function validateFileFrontmatter<TData>(
115
+ schema: StandardSchemaV1<unknown, TData> | undefined,
116
+ rawData: Record<string, unknown>,
117
+ slug: string,
118
+ absFile: string,
119
+ ): TData {
120
+ if (schema === undefined)
121
+ return rawData as TData
122
+ const checked = validateSchemaSync(
123
+ schema,
124
+ rawData,
125
+ `@prunellejs/content: async frontmatter schema is not supported (${slug})`,
126
+ )
127
+ if (!checked.ok)
128
+ throw new Error(`@prunellejs/content: invalid frontmatter in "${absFile}": ${formatSchemaIssues(checked.issues)}`)
129
+ return checked.value
130
+ }
131
+
132
+ function parseFileFrontmatter(rawSource: string, absFile: string): ReturnType<typeof parseFrontmatter> {
133
+ try {
134
+ return parseFrontmatter(rawSource)
135
+ }
136
+ catch (err) {
137
+ throw new Error(`@prunellejs/content: invalid YAML frontmatter in "${absFile}": ${err instanceof Error ? err.message : String(err)}`, { cause: err })
138
+ }
139
+ }
140
+
141
+ function findEntryFileCandidate(scanDir: string, clean: string): string | undefined {
142
+ for (const candidate of [
143
+ join(scanDir, `${clean}.md`),
144
+ join(scanDir, `${clean}.markdown`),
145
+ join(scanDir, clean, 'index.md'),
146
+ join(scanDir, clean, 'index.markdown'),
147
+ ]) {
148
+ if (existsSync(candidate))
149
+ return candidate
150
+ }
151
+ return undefined
152
+ }
153
+
154
+ function trackAccessed<TData>(collectionName: string, entry: ContentEntry<TData>, primary: boolean): void {
155
+ recordAccessedEntry({
156
+ collection: collectionName,
157
+ slug: entry.slug,
158
+ ...(entry.locale !== undefined ? { locale: entry.locale } : {}),
159
+ }, primary)
160
+ }
161
+
162
+ export function createFileCollection<TData = Record<string, unknown>>(
163
+ options: CollectionOptions<TData>,
164
+ ): Collection<TData> {
165
+ const getDir = () => resolveCollectionDir(options.dir)
166
+ const getName = (absDir?: string) => options.name ?? (basename(absDir ?? getDir()) || 'collection')
167
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
168
+ const localized = options.localized ?? false
169
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
170
+ const renderLoader = createRenderConfigLoader(options.dir, options)
171
+
172
+ const cache = new Map<string, { mtimeMs: number, entry: ContentEntry<TData> }>()
173
+ const allCache = new Map<string, ContentEntry<TData>[]>()
174
+ const slugCache = new Map<string, Map<string, ContentEntry<TData>>>()
175
+
176
+ const visible = (entry: ContentEntry<TData>): ContentEntry<TData> | null =>
177
+ !allowsDrafts() && isDraft(entry.data) ? null : entry
178
+
179
+ function loadFile(absFile: string, baseDir: string, collectionName: string, entryLocale?: string): ContentEntry<TData> | null {
180
+ const dev = isDevMode()
181
+ const cached = cache.get(absFile)
182
+ if (!dev && cached !== undefined)
183
+ return visible(cached.entry)
184
+
185
+ const mtimeMs = statSync(absFile).mtimeMs
186
+ if (cached !== undefined && cached.mtimeMs === mtimeMs)
187
+ return visible(cached.entry)
188
+
189
+ const rawSource = readFileSync(absFile, 'utf8')
190
+ const { data: rawData, body } = parseFileFrontmatter(rawSource, absFile)
191
+ const slug = relative(baseDir, absFile)
192
+ .replace(/\\/g, '/')
193
+ .replace(/\.(?:md|markdown)$/, '')
194
+ .replace(/\/index$/, '')
195
+
196
+ const data = validateFileFrontmatter(options.schema, rawData, slug, absFile)
197
+ const entry = buildContentEntry({ slug, locale: entryLocale, file: absFile, data, body, renderLoader, collectionName })
198
+ cache.set(absFile, { mtimeMs, entry })
199
+ return visible(entry)
200
+ }
201
+
202
+ function scanAllEntries(locale?: string): { entries: ContentEntry<TData>[], collectionName: string } {
203
+ const absDir = getDir()
204
+ const collectionName = getName(absDir)
205
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
206
+ const scanDir = localeDir(absDir, targetLocale)
207
+ if (scanDir === undefined)
208
+ return { entries: [], collectionName }
209
+ const dev = isDevMode()
210
+ if (!dev) {
211
+ const hit = allCache.get(scanDir)
212
+ if (hit !== undefined)
213
+ return { entries: hit.slice(), collectionName }
214
+ }
215
+ const entries: ContentEntry<TData>[] = []
216
+ const bySlug = new Map<string, ContentEntry<TData>>()
217
+ for (const f of walkMarkdownFiles(scanDir)) {
218
+ const entry = loadFile(f, scanDir, collectionName, targetLocale)
219
+ if (entry === null)
220
+ continue
221
+ entries.push(entry)
222
+ bySlug.set(entry.slug, entry)
223
+ }
224
+ entries.sort(options.sort ?? defaultSort)
225
+ if (!dev) {
226
+ allCache.set(scanDir, entries)
227
+ slugCache.set(scanDir, bySlug)
228
+ }
229
+ return { entries: entries.slice(), collectionName }
230
+ }
231
+
232
+ function all(locale?: string): ContentEntry<TData>[] {
233
+ const { entries, collectionName } = scanAllEntries(locale)
234
+ for (const entry of entries)
235
+ trackAccessed(collectionName, entry, false)
236
+ return entries
237
+ }
238
+
239
+ function get(slug: string, locale?: string): ContentEntry<TData> | undefined {
240
+ const absDir = getDir()
241
+ const collectionName = getName(absDir)
242
+ const clean = slug.replace(/^\/+|\/+$/g, '')
243
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
244
+ const scanDir = localeDir(absDir, targetLocale)
245
+ if (scanDir === undefined || !isInside(scanDir, resolve(scanDir, clean), { orSame: true }))
246
+ return undefined
247
+ const dev = isDevMode()
248
+ if (!dev) {
249
+ const cachedSlug = slugCache.get(scanDir)?.get(clean)
250
+ if (cachedSlug !== undefined)
251
+ return cachedSlug
252
+ // The scan listed every entry: a slug absent from it has no file, so there is nothing to probe.
253
+ if (allCache.has(scanDir))
254
+ return undefined
255
+ }
256
+ const candidate = findEntryFileCandidate(scanDir, clean)
257
+ let found: ContentEntry<TData> | undefined
258
+ if (candidate !== undefined) {
259
+ found = loadFile(candidate, scanDir, collectionName, targetLocale) ?? undefined
260
+ if (!dev && found !== undefined) {
261
+ let map = slugCache.get(scanDir)
262
+ if (map === undefined) {
263
+ map = new Map()
264
+ slugCache.set(scanDir, map)
265
+ }
266
+ map.set(clean, found)
267
+ }
268
+ }
269
+ found ??= scanAllEntries(locale).entries.find(e => e.slug === clean)
270
+ if (found !== undefined)
271
+ trackAccessed(collectionName, found, true)
272
+ return found
273
+ }
274
+
275
+ const col: Collection<TData> & InternalCollection = {
276
+ get dir() {
277
+ return getDir()
278
+ },
279
+ get name() {
280
+ return getName()
281
+ },
282
+ all,
283
+ get,
284
+ byTag: (tag, locale) => filterByTag(all(locale), tag),
285
+ paths: (prefix = '', locale) => formatPaths(all(locale), prefix),
286
+ clearCache() {
287
+ cache.clear()
288
+ allCache.clear()
289
+ slugCache.clear()
290
+ },
291
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateCollectionFiles(resolveCollectionDir(options.dir, root), root, options.schema),
292
+ [COLLECTION_DIR_FOR_ROOT_KEY]: (root?: string) => resolveCollectionDir(options.dir, root),
293
+ [COLLECTION_META_KEY]: (root?: string) => {
294
+ const absDir = resolveCollectionDir(options.dir, root)
295
+ return {
296
+ name: getName(absDir),
297
+ dir: absDir,
298
+ localized,
299
+ defaultLocale: getDefaultLocale(),
300
+ locales: options.locales ?? (localized ? listLocaleDirs(absDir) : undefined),
301
+ schema: options.schema,
302
+ isAsync: false,
303
+ }
304
+ },
305
+ }
306
+ registerFileCollection(col, options.dir, localized)
307
+ return col
308
+ }
@@ -1,18 +1,39 @@
1
1
  // YAML frontmatter parsing (via Bun.YAML) and source line lookup for diagnostics.
2
2
 
3
- /** Parses full nested YAML frontmatter using Bun's native Zig `Bun.YAML.parse`. */
4
- export function parseFrontmatter(source: string): { data: Record<string, unknown>, body: string } {
5
- const normalized = source.replace(/\r\n/g, '\n')
3
+ const CLOSING_LINE_RE = /^---[ \t]*$/
4
+
5
+ // Strips a leading UTF-8 BOM and normalizes CRLF to LF before frontmatter splitting.
6
+ function normalizeSource(source: string): string {
7
+ const withoutBom = source.charCodeAt(0) === 0xFEFF ? source.slice(1) : source
8
+ return withoutBom.replace(/\r\n/g, '\n')
9
+ }
10
+
11
+ // The YAML between the opening `---` line and the first line that is exactly `---` (the empty block included), and where the body starts.
12
+ function splitFrontmatter(normalized: string): { yaml: string, bodyStart: number } | undefined {
6
13
  if (!normalized.startsWith('---\n'))
7
- return { data: {}, body: normalized }
14
+ return undefined
15
+ let lineStart = 4
16
+ while (lineStart <= normalized.length) {
17
+ const newline = normalized.indexOf('\n', lineStart)
18
+ const lineEnd = newline === -1 ? normalized.length : newline
19
+ if (CLOSING_LINE_RE.test(normalized.slice(lineStart, lineEnd)))
20
+ return { yaml: normalized.slice(4, lineStart - 1), bodyStart: lineEnd + 1 }
21
+ if (newline === -1)
22
+ return undefined
23
+ lineStart = newline + 1
24
+ }
25
+ return undefined
26
+ }
8
27
 
9
- const end = normalized.indexOf('\n---', 4)
10
- if (end === -1)
28
+ /** Parses full nested YAML frontmatter using Bun's native Zig `Bun.YAML.parse`. */
29
+ export function parseFrontmatter(source: string): { data: Record<string, unknown>, body: string } {
30
+ const normalized = normalizeSource(source)
31
+ const split = splitFrontmatter(normalized)
32
+ if (split === undefined)
11
33
  return { data: {}, body: normalized }
12
34
 
13
- const rawYaml = normalized.slice(4, end)
14
- const restStart = normalized.indexOf('\n', end + 4)
15
- const body = restStart === -1 ? '' : normalized.slice(restStart + 1)
35
+ const rawYaml = split.yaml
36
+ const body = normalized.slice(split.bodyStart)
16
37
 
17
38
  const parsed = rawYaml.trim() === '' ? {} : Bun.YAML.parse(rawYaml)
18
39
  const data = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
@@ -23,18 +44,16 @@ export function parseFrontmatter(source: string): { data: Record<string, unknown
23
44
 
24
45
  /** Finds the 1-based line number of a top-level frontmatter key for `prunelle check` diagnostics. */
25
46
  export function findFrontmatterFieldLine(rawSource: string, fieldPath: string | undefined): number {
26
- const normalized = rawSource.replace(/\r\n/g, '\n')
27
- if (!normalized.startsWith('---\n'))
28
- return 1
29
- const end = normalized.indexOf('\n---', 4)
30
- if (end === -1)
47
+ const normalized = normalizeSource(rawSource)
48
+ const split = splitFrontmatter(normalized)
49
+ if (split === undefined)
31
50
  return 1
32
51
  if (!fieldPath)
33
52
  return 2
34
53
  const topKey = fieldPath.split('.')[0] ?? fieldPath
35
54
  const escaped = topKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
36
55
  const keyRe = new RegExp(`^\\s*${escaped}\\s*:`)
37
- const lines = normalized.slice(4, end).split('\n')
56
+ const lines = split.yaml.split('\n')
38
57
  for (let i = 0; i < lines.length; i++) {
39
58
  if (keyRe.test(lines[i]!))
40
59
  return i + 2
package/src/index.ts CHANGED
@@ -1,36 +1,45 @@
1
- // @prunellejs/content — Zero-dependency Bun-native Markdown collections, nested YAML frontmatter (Bun.YAML),
2
- // Shiki/custom highlight hook, MDX-lite embedded TSX components, localized collections, TOC, and RSS (`0 KB` client JS).
1
+ // @prunellejs/content — Zero-dependency Bun-native Markdown collections (file-backed or headless CMS loaders),
2
+ // nested YAML frontmatter (Bun.YAML), Shiki/custom highlight hook, MDX-lite embedded TSX components, localized collections, TOC, and RSS (`0 KB` client JS).
3
3
 
4
4
  import type { PrunellePlugin } from 'prunelle/config'
5
- import type { Collection, InternalCollection } from './collection'
5
+ import type { AnyCollection, InternalCollection } from './types'
6
6
  import type { ContentFeed, RssFeedConfig } from './rss'
7
7
  import { existsSync, readFileSync } from 'node:fs'
8
8
  import { resolve } from 'node:path'
9
- import { definePlugin, isInside } from 'prunelle/config'
9
+ import { CONTENT_COLLECTIONS_SERVICE, definePlugin, isInside } from 'prunelle/config'
10
10
  import { currentApp } from './app'
11
11
  import {
12
12
  COLLECTION_DIR_FOR_ROOT_KEY,
13
13
  COLLECTION_OWNER_ROOT_KEY,
14
14
  COLLECTION_VALIDATE_KEY,
15
- COLLECTION_VERSION_KEY,
15
+
16
16
  DEFINE_COLLECTION_RE,
17
17
  discoverAppCollections,
18
-
19
18
  registeredCollections,
20
19
  walkCollectionDefFiles,
21
20
  } from './collection'
22
- import { etagMatches, renderRss } from './rss'
21
+ import { etagMatches, renderRssAsync } from './rss'
22
+ import { CONTENT_PRERENDER_SERVICE, createCollectionsService } from './service'
23
23
 
24
24
  export { defineCollection } from './collection'
25
25
  export type {
26
+ AnyCollection,
27
+ AsyncCollection,
28
+ BaseCollectionOptions,
26
29
  CodeHighlighter,
27
30
  Collection,
31
+ CollectionLoadContext,
32
+ CollectionLoader,
28
33
  CollectionOptions,
29
34
  CollectionOptionsWithoutSchema,
30
35
  CollectionOptionsWithSchema,
31
36
  CollectionRenderConfig,
32
37
  ContentEntry,
33
38
  ContentHeading,
39
+ LoadedEntryInput,
40
+ LoaderCollectionOptions,
41
+ LoaderCollectionOptionsWithoutSchema,
42
+ LoaderCollectionOptionsWithSchema,
34
43
  MarkdownComponent,
35
44
  MarkdownImageResolver,
36
45
  MarkdownImageResult,
@@ -39,7 +48,7 @@ export type {
39
48
  } from './collection'
40
49
  export { parseFrontmatter } from './frontmatter'
41
50
  export { renderMarkdown } from './markdown'
42
- export { renderRss } from './rss'
51
+ export { renderRss, renderRssAsync } from './rss'
43
52
  export type { ContentFeed, RssFeedConfig } from './rss'
44
53
 
45
54
  const STATIC_COLLECTION_DIR_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(\s*\{[\s\S]*?\bdir\s*:\s*(['"`])([^'"`]+)\1/g
@@ -69,16 +78,29 @@ function discoverStaticCollectionDirs(root: string): string[] {
69
78
  return found
70
79
  }
71
80
 
81
+ function feedFile(feed: ContentFeed): string {
82
+ return (feed.path ?? '/rss.xml').replace(/^\/+/, '')
83
+ }
84
+
72
85
  export function content<const TDataList extends readonly unknown[] = readonly unknown[]>(options?: {
73
- feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K]> } | undefined
74
- collections?: readonly Collection<unknown>[] | undefined
86
+ feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K], AnyCollection<TDataList[K]>> } | undefined
87
+ collections?: readonly AnyCollection<unknown>[] | undefined
75
88
  }): PrunellePlugin
76
- export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly Collection<unknown>[] | undefined } = {}): PrunellePlugin {
89
+ export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly AnyCollection<unknown>[] | undefined } = {}): PrunellePlugin {
77
90
  const feeds = options.feeds ?? []
78
91
  const extraCollections = options.collections ?? []
92
+ const feedLinkPrefixes = new Map<InternalCollection, string>()
93
+ for (const f of feeds) {
94
+ const col = f.collection as InternalCollection
95
+ if (f.linkPrefix !== undefined && !feedLinkPrefixes.has(col))
96
+ feedLinkPrefixes.set(col, f.linkPrefix)
97
+ }
79
98
 
80
- function dirOf(c: InternalCollection, root?: string): string {
81
- return c[COLLECTION_DIR_FOR_ROOT_KEY]?.(root) ?? c.dir
99
+ function dirOf(c: InternalCollection, root?: string): string | undefined {
100
+ const resolver = c[COLLECTION_DIR_FOR_ROOT_KEY]
101
+ if (resolver !== undefined)
102
+ return resolver(root)
103
+ return c.dir
82
104
  }
83
105
 
84
106
  function activeCollections(root?: string): InternalCollection[] {
@@ -93,6 +115,11 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
93
115
  if (owner !== undefined && absRoot !== undefined && owner !== absRoot)
94
116
  continue
95
117
  const dir = dirOf(c, absRoot)
118
+ if (dir === undefined) {
119
+ if (owner !== undefined || absRoot === undefined)
120
+ out.add(c)
121
+ continue
122
+ }
96
123
  if (!existsSync(dir))
97
124
  continue
98
125
  if (absRoot === undefined || isInside(absRoot, dir, { orSame: true }))
@@ -101,13 +128,21 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
101
128
  return [...out]
102
129
  }
103
130
 
131
+ const collectionsService = createCollectionsService(
132
+ activeCollections,
133
+ col => feedLinkPrefixes.get(col),
134
+ )
135
+
104
136
  return definePlugin({
105
137
  name: '@prunellejs/content',
106
138
  after: ['@prunellejs/i18n', '@prunellejs/images'],
107
139
  watchPaths: (root) => {
108
140
  const dirs = new Set<string>()
109
- for (const c of activeCollections(root))
110
- dirs.add(dirOf(c, root))
141
+ for (const c of activeCollections(root)) {
142
+ const dir = dirOf(c, root)
143
+ if (dir !== undefined)
144
+ dirs.add(dir)
145
+ }
111
146
  for (const dir of discoverStaticCollectionDirs(root))
112
147
  dirs.add(dir)
113
148
  return [...dirs]
@@ -119,12 +154,13 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
119
154
  },
120
155
  async check(ctx) {
121
156
  await discoverAppCollections(ctx.root)
157
+ ctx.provide?.(CONTENT_COLLECTIONS_SERVICE, collectionsService)
122
158
  const seen = new Set<string>()
123
159
  for (const c of activeCollections(ctx.root)) {
124
160
  const validate = c[COLLECTION_VALIDATE_KEY]
125
161
  if (validate === undefined)
126
162
  continue
127
- for (const err of validate(ctx.root)) {
163
+ for (const err of await validate(ctx.root)) {
128
164
  if (seen.has(err))
129
165
  continue
130
166
  seen.add(err)
@@ -132,34 +168,44 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
132
168
  }
133
169
  }
134
170
  },
135
- build(ctx) {
171
+ async build(ctx) {
172
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
173
+ const emittedFeeds: string[] = []
136
174
  for (const feed of feeds) {
137
- const rel = (feed.path ?? '/rss.xml').replace(/^\/+/, '')
138
- ctx.emitPublic(rel, renderRss({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown>))
175
+ const rel = feedFile(feed)
176
+ ctx.emitPublic(rel, await renderRssAsync({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown, AnyCollection<unknown>>))
177
+ // A loader-backed feed changes without a rebuild, so it keeps its runtime route over the built file.
178
+ if (feed.collection.dir !== undefined)
179
+ emittedFeeds.push(rel)
139
180
  }
181
+ ctx.setData({ emittedFeeds })
182
+ },
183
+ afterPrerender(ctx) {
184
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
140
185
  },
141
186
  server(api) {
187
+ api.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
188
+ if (api.config?.prerender === true)
189
+ api.provide(CONTENT_PRERENDER_SERVICE, true)
190
+ const emitted = new Set(api.getBuildData<{ emittedFeeds?: string[] }>()?.emittedFeeds ?? [])
142
191
  for (const feed of feeds) {
143
192
  const path = feed.path ?? '/rss.xml'
144
- let memo: { xml: string, etag: string, version: number } | undefined
145
- api.route('GET', path, (ctx) => {
146
- const versionFn = (feed.collection as unknown as Record<symbol, (() => number) | undefined>)[COLLECTION_VERSION_KEY]
147
- const version = versionFn ? versionFn() : -1
148
- if (api.dev || memo === undefined || memo.version !== version) {
149
- const xml = renderRss({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown>)
150
- const etag = `"${Bun.hash(xml).toString(36)}"`
151
- memo = { xml, etag, version }
152
- }
153
- if (etagMatches(ctx.request.headers.get('if-none-match'), memo.etag)) {
193
+ // Plugin routes shadow public files: a production server serves the file the build already wrote.
194
+ if (!api.dev && emitted.has(feedFile(feed)))
195
+ continue
196
+ api.route('GET', path, async (ctx) => {
197
+ const xml = await renderRssAsync({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown, AnyCollection<unknown>>)
198
+ const current = { xml, etag: `"${Bun.hash(xml).toString(36)}"` }
199
+ if (etagMatches(ctx.request.headers.get('if-none-match'), current.etag)) {
154
200
  return new Response(null, {
155
201
  status: 304,
156
- headers: { etag: memo.etag },
202
+ headers: { etag: current.etag },
157
203
  })
158
204
  }
159
- return new Response(memo.xml, {
205
+ return new Response(current.xml, {
160
206
  headers: {
161
207
  'content-type': 'application/rss+xml; charset=utf-8',
162
- 'etag': memo.etag,
208
+ 'etag': current.etag,
163
209
  },
164
210
  })
165
211
  })