@prunellejs/content 0.0.0-stage → 0.7.2
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/LICENSE +21 -0
- package/llms.txt +83 -0
- package/package.json +24 -4
- package/src/app.ts +15 -0
- package/src/collection.ts +67 -0
- package/src/components.ts +577 -0
- package/src/entry.ts +171 -0
- package/src/file-collection.ts +308 -0
- package/src/frontmatter.ts +56 -0
- package/src/index.ts +215 -0
- package/src/loader-collection.ts +333 -0
- package/src/markdown.ts +218 -0
- package/src/registry.ts +147 -0
- package/src/rss.ts +105 -0
- package/src/service.ts +88 -0
- package/src/tracking.ts +80 -0
- package/src/types.ts +202 -0
- package/README.md +0 -3
package/src/entry.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Shared entry construction, lazy Markdown render-config resolution, sorting, and filtering helpers.
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
BaseCollectionOptions,
|
|
5
|
+
CollectionRenderConfig,
|
|
6
|
+
ContentEntry,
|
|
7
|
+
RenderedMarkdown,
|
|
8
|
+
RenderMarkdownOptions,
|
|
9
|
+
} from './types'
|
|
10
|
+
import { devFromEnv } from 'prunelle/internal/server'
|
|
11
|
+
import { currentApp } from './app'
|
|
12
|
+
import { renderMarkdown } from './markdown'
|
|
13
|
+
import { shouldWrapCmsBody, wrapCmsBodyHtml } from './tracking'
|
|
14
|
+
|
|
15
|
+
export interface RenderConfigLoader {
|
|
16
|
+
ensureSync: () => RenderMarkdownOptions
|
|
17
|
+
ensureAsync: () => Promise<RenderMarkdownOptions>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type RenderConfigOptions = Pick<
|
|
21
|
+
BaseCollectionOptions<never>,
|
|
22
|
+
'highlight' | 'components' | 'headingLinks' | 'resolveImage' | 'trusted' | 'render'
|
|
23
|
+
>
|
|
24
|
+
|
|
25
|
+
export function createRenderConfigLoader(
|
|
26
|
+
label: string,
|
|
27
|
+
options: RenderConfigOptions,
|
|
28
|
+
): RenderConfigLoader {
|
|
29
|
+
const baseRenderOpts: RenderMarkdownOptions = {
|
|
30
|
+
highlight: options.highlight,
|
|
31
|
+
components: options.components,
|
|
32
|
+
headingLinks: options.headingLinks,
|
|
33
|
+
resolveImage: options.resolveImage,
|
|
34
|
+
trusted: options.trusted,
|
|
35
|
+
}
|
|
36
|
+
let resolvedRenderOpts: RenderMarkdownOptions | undefined = options.render === undefined ? baseRenderOpts : undefined
|
|
37
|
+
let pendingRenderOpts: Promise<RenderMarkdownOptions> | undefined
|
|
38
|
+
|
|
39
|
+
function mergeRenderConfig(cfg: CollectionRenderConfig): RenderMarkdownOptions {
|
|
40
|
+
return {
|
|
41
|
+
highlight: cfg.highlight ?? baseRenderOpts.highlight,
|
|
42
|
+
components: cfg.components ?? baseRenderOpts.components,
|
|
43
|
+
headingLinks: cfg.headingLinks ?? baseRenderOpts.headingLinks,
|
|
44
|
+
resolveImage: cfg.resolveImage !== undefined ? cfg.resolveImage : baseRenderOpts.resolveImage,
|
|
45
|
+
trusted: cfg.trusted !== undefined ? cfg.trusted : baseRenderOpts.trusted,
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function ensureSync(): RenderMarkdownOptions {
|
|
50
|
+
if (resolvedRenderOpts !== undefined)
|
|
51
|
+
return resolvedRenderOpts
|
|
52
|
+
const loaded = options.render!()
|
|
53
|
+
if (loaded instanceof Promise) {
|
|
54
|
+
pendingRenderOpts ??= loaded.then((cfg) => {
|
|
55
|
+
resolvedRenderOpts = mergeRenderConfig(cfg)
|
|
56
|
+
return resolvedRenderOpts
|
|
57
|
+
}).catch((err) => {
|
|
58
|
+
pendingRenderOpts = undefined
|
|
59
|
+
throw err
|
|
60
|
+
})
|
|
61
|
+
throw new Error(
|
|
62
|
+
`@prunellejs/content: collection "${label}" uses an async "render" loader; call \`await entry.render()\` (e.g. in \`load()\`) before reading \`entry.html\` or \`entry.headings\`.`,
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
resolvedRenderOpts = mergeRenderConfig(loaded)
|
|
66
|
+
return resolvedRenderOpts
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function ensureAsync(): Promise<RenderMarkdownOptions> {
|
|
70
|
+
if (resolvedRenderOpts !== undefined)
|
|
71
|
+
return resolvedRenderOpts
|
|
72
|
+
pendingRenderOpts ??= Promise.resolve(options.render!()).then((cfg) => {
|
|
73
|
+
resolvedRenderOpts = mergeRenderConfig(cfg)
|
|
74
|
+
return resolvedRenderOpts
|
|
75
|
+
}).catch((err) => {
|
|
76
|
+
pendingRenderOpts = undefined
|
|
77
|
+
throw err
|
|
78
|
+
})
|
|
79
|
+
return pendingRenderOpts
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { ensureSync, ensureAsync }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface BuildContentEntryParams<TData> {
|
|
86
|
+
slug: string
|
|
87
|
+
locale?: string | undefined
|
|
88
|
+
file: string
|
|
89
|
+
data: TData
|
|
90
|
+
body: string
|
|
91
|
+
renderLoader: RenderConfigLoader
|
|
92
|
+
/** Set for file-backed collections so dev inline CMS can anchor rendered Markdown bodies. */
|
|
93
|
+
collectionName?: string | undefined
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function buildContentEntry<TData>(params: BuildContentEntryParams<TData>): ContentEntry<TData> {
|
|
97
|
+
const { slug, locale, file, data, body, renderLoader, collectionName } = params
|
|
98
|
+
const wordCount = body.trim().split(/\s+/).filter(Boolean).length
|
|
99
|
+
const readingMinutes = Math.max(1, Math.ceil(wordCount / 220))
|
|
100
|
+
let renderedCache: RenderedMarkdown | undefined
|
|
101
|
+
|
|
102
|
+
const getRenderedSync = (): RenderedMarkdown => {
|
|
103
|
+
renderedCache ??= renderMarkdown(body, { ...renderLoader.ensureSync(), locale, file })
|
|
104
|
+
return renderedCache
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const renderAsync = async (): Promise<RenderedMarkdown> => {
|
|
108
|
+
if (renderedCache === undefined) {
|
|
109
|
+
const opts = await renderLoader.ensureAsync()
|
|
110
|
+
renderedCache ??= renderMarkdown(body, { ...opts, locale, file })
|
|
111
|
+
}
|
|
112
|
+
if (shouldWrapCmsBody(collectionName)) {
|
|
113
|
+
return {
|
|
114
|
+
...renderedCache,
|
|
115
|
+
html: wrapCmsBodyHtml(collectionName, slug, locale, renderedCache.html),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return renderedCache
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
slug,
|
|
123
|
+
...(locale !== undefined ? { locale } : {}),
|
|
124
|
+
file,
|
|
125
|
+
data,
|
|
126
|
+
body,
|
|
127
|
+
get html() {
|
|
128
|
+
const raw = getRenderedSync().html
|
|
129
|
+
return shouldWrapCmsBody(collectionName)
|
|
130
|
+
? wrapCmsBodyHtml(collectionName, slug, locale, raw)
|
|
131
|
+
: raw
|
|
132
|
+
},
|
|
133
|
+
get headings() {
|
|
134
|
+
return getRenderedSync().headings
|
|
135
|
+
},
|
|
136
|
+
wordCount,
|
|
137
|
+
readingMinutes,
|
|
138
|
+
render: renderAsync,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function isDevMode(): boolean {
|
|
143
|
+
return currentApp.dev() ?? devFromEnv()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function isDraft(data: unknown): boolean {
|
|
147
|
+
return data !== null && typeof data === 'object' && (data as Record<string, unknown>).draft === true
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function defaultSort<T>(a: ContentEntry<T>, b: ContentEntry<T>): number {
|
|
151
|
+
const ad = a.data !== null && typeof a.data === 'object' ? (a.data as Record<string, unknown>).date : undefined
|
|
152
|
+
const bd = b.data !== null && typeof b.data === 'object' ? (b.data as Record<string, unknown>).date : undefined
|
|
153
|
+
const at = ad instanceof Date ? ad.getTime() : (typeof ad === 'string' || typeof ad === 'number' ? Date.parse(String(ad)) : Number.NaN)
|
|
154
|
+
const bt = bd instanceof Date ? bd.getTime() : (typeof bd === 'string' || typeof bd === 'number' ? Date.parse(String(bd)) : Number.NaN)
|
|
155
|
+
if (!Number.isNaN(at) && !Number.isNaN(bt) && at !== bt)
|
|
156
|
+
return bt - at
|
|
157
|
+
return a.slug.localeCompare(b.slug)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function filterByTag<T>(entries: readonly ContentEntry<T>[], tag: string): ContentEntry<T>[] {
|
|
161
|
+
const needle = tag.toLowerCase()
|
|
162
|
+
return entries.filter((e) => {
|
|
163
|
+
const tags = e.data !== null && typeof e.data === 'object' ? (e.data as Record<string, unknown>).tags : undefined
|
|
164
|
+
return Array.isArray(tags) && tags.some(t => String(t).toLowerCase() === needle)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function formatPaths<T>(entries: readonly ContentEntry<T>[], prefix = ''): string[] {
|
|
169
|
+
const base = prefix.replace(/\/$/, '')
|
|
170
|
+
return entries.map(e => `${base}/${e.slug}`)
|
|
171
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// YAML frontmatter parsing (via Bun.YAML) and source line lookup for diagnostics.
|
|
2
|
+
|
|
3
|
+
const CLOSING_LINE_RE = /^---[ \t]*$/
|
|
4
|
+
|
|
5
|
+
// The YAML between the opening `---` line and the first line that is exactly `---` (the empty block included), and where the body starts.
|
|
6
|
+
function splitFrontmatter(normalized: string): { yaml: string, bodyStart: number } | undefined {
|
|
7
|
+
if (!normalized.startsWith('---\n'))
|
|
8
|
+
return undefined
|
|
9
|
+
let lineStart = 4
|
|
10
|
+
while (lineStart <= normalized.length) {
|
|
11
|
+
const newline = normalized.indexOf('\n', lineStart)
|
|
12
|
+
const lineEnd = newline === -1 ? normalized.length : newline
|
|
13
|
+
if (CLOSING_LINE_RE.test(normalized.slice(lineStart, lineEnd)))
|
|
14
|
+
return { yaml: normalized.slice(4, lineStart - 1), bodyStart: lineEnd + 1 }
|
|
15
|
+
if (newline === -1)
|
|
16
|
+
return undefined
|
|
17
|
+
lineStart = newline + 1
|
|
18
|
+
}
|
|
19
|
+
return undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Parses full nested YAML frontmatter using Bun's native Zig `Bun.YAML.parse`. */
|
|
23
|
+
export function parseFrontmatter(source: string): { data: Record<string, unknown>, body: string } {
|
|
24
|
+
const normalized = source.replace(/\r\n/g, '\n')
|
|
25
|
+
const split = splitFrontmatter(normalized)
|
|
26
|
+
if (split === undefined)
|
|
27
|
+
return { data: {}, body: normalized }
|
|
28
|
+
|
|
29
|
+
const rawYaml = split.yaml
|
|
30
|
+
const body = normalized.slice(split.bodyStart)
|
|
31
|
+
|
|
32
|
+
const parsed = rawYaml.trim() === '' ? {} : Bun.YAML.parse(rawYaml)
|
|
33
|
+
const data = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
34
|
+
? (parsed as Record<string, unknown>)
|
|
35
|
+
: {}
|
|
36
|
+
return { data, body }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Finds the 1-based line number of a top-level frontmatter key for `prunelle check` diagnostics. */
|
|
40
|
+
export function findFrontmatterFieldLine(rawSource: string, fieldPath: string | undefined): number {
|
|
41
|
+
const normalized = rawSource.replace(/\r\n/g, '\n')
|
|
42
|
+
const split = splitFrontmatter(normalized)
|
|
43
|
+
if (split === undefined)
|
|
44
|
+
return 1
|
|
45
|
+
if (!fieldPath)
|
|
46
|
+
return 2
|
|
47
|
+
const topKey = fieldPath.split('.')[0] ?? fieldPath
|
|
48
|
+
const escaped = topKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
49
|
+
const keyRe = new RegExp(`^\\s*${escaped}\\s*:`)
|
|
50
|
+
const lines = split.yaml.split('\n')
|
|
51
|
+
for (let i = 0; i < lines.length; i++) {
|
|
52
|
+
if (keyRe.test(lines[i]!))
|
|
53
|
+
return i + 2
|
|
54
|
+
}
|
|
55
|
+
return 2
|
|
56
|
+
}
|