@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/src/index.ts ADDED
@@ -0,0 +1,215 @@
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
+
4
+ import type { PrunellePlugin } from 'prunelle/config'
5
+ import type { AnyCollection, InternalCollection } from './types'
6
+ import type { ContentFeed, RssFeedConfig } from './rss'
7
+ import { existsSync, readFileSync } from 'node:fs'
8
+ import { resolve } from 'node:path'
9
+ import { CONTENT_COLLECTIONS_SERVICE, definePlugin, isInside } from 'prunelle/config'
10
+ import { currentApp } from './app'
11
+ import {
12
+ COLLECTION_DIR_FOR_ROOT_KEY,
13
+ COLLECTION_OWNER_ROOT_KEY,
14
+ COLLECTION_VALIDATE_KEY,
15
+
16
+ DEFINE_COLLECTION_RE,
17
+ discoverAppCollections,
18
+ registeredCollections,
19
+ walkCollectionDefFiles,
20
+ } from './collection'
21
+ import { etagMatches, renderRssAsync } from './rss'
22
+ import { CONTENT_PRERENDER_SERVICE, createCollectionsService } from './service'
23
+
24
+ export { defineCollection } from './collection'
25
+ export type {
26
+ AnyCollection,
27
+ AsyncCollection,
28
+ BaseCollectionOptions,
29
+ CodeHighlighter,
30
+ Collection,
31
+ CollectionLoadContext,
32
+ CollectionLoader,
33
+ CollectionOptions,
34
+ CollectionOptionsWithoutSchema,
35
+ CollectionOptionsWithSchema,
36
+ CollectionRenderConfig,
37
+ ContentEntry,
38
+ ContentHeading,
39
+ LoadedEntryInput,
40
+ LoaderCollectionOptions,
41
+ LoaderCollectionOptionsWithoutSchema,
42
+ LoaderCollectionOptionsWithSchema,
43
+ MarkdownComponent,
44
+ MarkdownImageResolver,
45
+ MarkdownImageResult,
46
+ RenderedMarkdown,
47
+ RenderMarkdownOptions,
48
+ } from './collection'
49
+ export { parseFrontmatter } from './frontmatter'
50
+ export { renderMarkdown } from './markdown'
51
+ export { renderRss, renderRssAsync } from './rss'
52
+ export type { ContentFeed, RssFeedConfig } from './rss'
53
+
54
+ const STATIC_COLLECTION_DIR_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(\s*\{[\s\S]*?\bdir\s*:\s*(['"`])([^'"`]+)\1/g
55
+
56
+ function discoverStaticCollectionDirs(root: string): string[] {
57
+ const absRoot = resolve(root)
58
+ const srcDir = resolve(absRoot, 'src')
59
+ const found: string[] = []
60
+ for (const file of walkCollectionDefFiles(srcDir)) {
61
+ let text: string
62
+ try {
63
+ text = readFileSync(file, 'utf8')
64
+ }
65
+ catch {
66
+ continue
67
+ }
68
+ if (!DEFINE_COLLECTION_RE.test(text))
69
+ continue
70
+ STATIC_COLLECTION_DIR_RE.lastIndex = 0
71
+ let m: RegExpExecArray | null
72
+ while ((m = STATIC_COLLECTION_DIR_RE.exec(text)) !== null) {
73
+ const dir = resolve(absRoot, m[2]!)
74
+ if (existsSync(dir) && isInside(absRoot, dir, { orSame: true }))
75
+ found.push(dir)
76
+ }
77
+ }
78
+ return found
79
+ }
80
+
81
+ function feedFile(feed: ContentFeed): string {
82
+ return (feed.path ?? '/rss.xml').replace(/^\/+/, '')
83
+ }
84
+
85
+ export function content<const TDataList extends readonly unknown[] = readonly unknown[]>(options?: {
86
+ feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K], AnyCollection<TDataList[K]>> } | undefined
87
+ collections?: readonly AnyCollection<unknown>[] | undefined
88
+ }): PrunellePlugin
89
+ export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly AnyCollection<unknown>[] | undefined } = {}): PrunellePlugin {
90
+ const feeds = options.feeds ?? []
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
+ }
98
+
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
104
+ }
105
+
106
+ function activeCollections(root?: string): InternalCollection[] {
107
+ const out = new Set<InternalCollection>()
108
+ for (const f of feeds)
109
+ out.add(f.collection as InternalCollection)
110
+ for (const c of extraCollections)
111
+ out.add(c as InternalCollection)
112
+ const absRoot = root !== undefined ? resolve(root) : currentApp.root()
113
+ for (const c of registeredCollections.values()) {
114
+ const owner = c[COLLECTION_OWNER_ROOT_KEY]
115
+ if (owner !== undefined && absRoot !== undefined && owner !== absRoot)
116
+ continue
117
+ const dir = dirOf(c, absRoot)
118
+ if (dir === undefined) {
119
+ if (owner !== undefined || absRoot === undefined)
120
+ out.add(c)
121
+ continue
122
+ }
123
+ if (!existsSync(dir))
124
+ continue
125
+ if (absRoot === undefined || isInside(absRoot, dir, { orSame: true }))
126
+ out.add(c)
127
+ }
128
+ return [...out]
129
+ }
130
+
131
+ const collectionsService = createCollectionsService(
132
+ activeCollections,
133
+ col => feedLinkPrefixes.get(col),
134
+ )
135
+
136
+ return definePlugin({
137
+ name: '@prunellejs/content',
138
+ after: ['@prunellejs/i18n', '@prunellejs/images'],
139
+ watchPaths: (root) => {
140
+ const dirs = new Set<string>()
141
+ for (const c of activeCollections(root)) {
142
+ const dir = dirOf(c, root)
143
+ if (dir !== undefined)
144
+ dirs.add(dir)
145
+ }
146
+ for (const dir of discoverStaticCollectionDirs(root))
147
+ dirs.add(dir)
148
+ return [...dirs]
149
+ },
150
+ requires(ctx) {
151
+ return feeds
152
+ .filter(feed => (feed.site ?? ctx.site) === undefined)
153
+ .map(feed => `the feed at ${feed.path ?? '/rss.xml'} has no \`site\`, so its links are relative and feed readers cannot open them: set \`site\` in \`prunelle.config.ts\` (or on the feed).`)
154
+ },
155
+ async check(ctx) {
156
+ await discoverAppCollections(ctx.root)
157
+ ctx.provide?.(CONTENT_COLLECTIONS_SERVICE, collectionsService)
158
+ const seen = new Set<string>()
159
+ for (const c of activeCollections(ctx.root)) {
160
+ const validate = c[COLLECTION_VALIDATE_KEY]
161
+ if (validate === undefined)
162
+ continue
163
+ for (const err of await validate(ctx.root)) {
164
+ if (seen.has(err))
165
+ continue
166
+ seen.add(err)
167
+ ctx.error(err)
168
+ }
169
+ }
170
+ },
171
+ async build(ctx) {
172
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
173
+ const emittedFeeds: string[] = []
174
+ for (const feed of feeds) {
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)
180
+ }
181
+ ctx.setData({ emittedFeeds })
182
+ },
183
+ afterPrerender(ctx) {
184
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
185
+ },
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 ?? [])
191
+ for (const feed of feeds) {
192
+ const path = feed.path ?? '/rss.xml'
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)) {
200
+ return new Response(null, {
201
+ status: 304,
202
+ headers: { etag: current.etag },
203
+ })
204
+ }
205
+ return new Response(current.xml, {
206
+ headers: {
207
+ 'content-type': 'application/rss+xml; charset=utf-8',
208
+ 'etag': current.etag,
209
+ },
210
+ })
211
+ })
212
+ }
213
+ },
214
+ })
215
+ }
@@ -0,0 +1,333 @@
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
+ } from './types'
32
+
33
+ function cleanSlug(rawSlug: unknown, collectionName: string): string {
34
+ if (typeof rawSlug !== 'string' || rawSlug.trim() === '')
35
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" is missing a non-empty string "slug".`)
36
+ const cleaned = rawSlug.trim().replace(/^\/+|\/+$/g, '')
37
+ if (cleaned === '')
38
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" has an empty "slug".`)
39
+ return cleaned
40
+ }
41
+
42
+ function getOrCreateLocaleMap<K extends object, T>(
43
+ store: WeakMap<K, Map<string, Promise<ContentEntry<T>[]>>>,
44
+ key: K,
45
+ ): Map<string, Promise<ContentEntry<T>[]>> {
46
+ let map = store.get(key)
47
+ if (map === undefined) {
48
+ map = new Map()
49
+ store.set(key, map)
50
+ }
51
+ return map
52
+ }
53
+
54
+ function formatCheckPrefix(root: string, sourceFile: string | undefined): string {
55
+ if (sourceFile === undefined)
56
+ return ''
57
+ const rel = relative(root, sourceFile).replace(/\\/g, '/')
58
+ return `${rel}:1:1: error: `
59
+ }
60
+
61
+ async function validateLoadedEntriesForCheck(params: {
62
+ name: string
63
+ root: string
64
+ sourceFile: string | undefined
65
+ localized: boolean
66
+ defaultLocale: string
67
+ locales: readonly string[] | undefined
68
+ schema: StandardSchemaV1 | undefined
69
+ load: (ctx: { locale?: string | undefined }) => Promise<LoadedEntryInput[]>
70
+ }): Promise<string[]> {
71
+ const { name, root, sourceFile, localized, defaultLocale, locales, schema, load } = params
72
+ const prefix = formatCheckPrefix(root, sourceFile)
73
+ const errors: string[] = []
74
+ const seenEntries = new Set<string>()
75
+
76
+ const configuredLocales = localized ? (locales ?? currentApp.locales()) : undefined
77
+ const runs: Array<{ locale: string | undefined, filterByLocale: boolean }> = !localized
78
+ ? [{ locale: undefined, filterByLocale: false }]
79
+ : configuredLocales !== undefined && configuredLocales.length > 0
80
+ ? [...new Set(configuredLocales)].map(locale => ({ locale, filterByLocale: true }))
81
+ : [{ locale: defaultLocale, filterByLocale: false }]
82
+
83
+ for (const run of runs) {
84
+ let rawEntries: LoadedEntryInput[]
85
+ try {
86
+ rawEntries = await load(localized ? { locale: run.locale } : {})
87
+ }
88
+ catch (err) {
89
+ const msg = err instanceof Error ? err.message : String(err)
90
+ const locNote = run.locale !== undefined ? ` (locale "${run.locale}")` : ''
91
+ errors.push(`${prefix}@prunellejs/content: collection "${name}"${locNote} loader failed: ${msg}`)
92
+ continue
93
+ }
94
+
95
+ for (const raw of rawEntries) {
96
+ if (run.filterByLocale && raw.locale !== undefined && raw.locale !== run.locale)
97
+ continue
98
+ if (typeof raw.slug !== 'string' || raw.slug.trim() === '') {
99
+ errors.push(`${prefix}@prunellejs/content: collection "${name}": entry is missing a non-empty string "slug"`)
100
+ continue
101
+ }
102
+ const slug = raw.slug.trim().replace(/^\/+|\/+$/g, '')
103
+ const entryLocale = localized ? (raw.locale ?? run.locale) : raw.locale
104
+ const dedupeKey = `${entryLocale ?? ''}\0${slug}`
105
+ if (seenEntries.has(dedupeKey))
106
+ continue
107
+ seenEntries.add(dedupeKey)
108
+
109
+ if (schema === undefined)
110
+ continue
111
+ const checked = await validateSchema(schema, raw.data)
112
+ if (!checked.ok) {
113
+ const locSuffix = entryLocale !== undefined ? ` (${entryLocale})` : ''
114
+ for (const issue of checked.issues) {
115
+ const path = formatIssuePath(issue)
116
+ errors.push(`${prefix}@prunellejs/content: collection "${name}" entry "${slug}"${locSuffix}: ${path ? `${path}: ` : ''}${issue.message}`)
117
+ }
118
+ }
119
+ }
120
+ }
121
+ return errors
122
+ }
123
+
124
+ const DEFAULT_TIMEOUT_MS = 30_000
125
+
126
+ function checkDurations(name: string, { ttlMs, timeoutMs }: { ttlMs?: number | undefined, timeoutMs?: number | undefined }): void {
127
+ if (ttlMs !== undefined && !(ttlMs >= 0))
128
+ throw new Error(`@prunellejs/content: collection "${name}" has ttlMs ${ttlMs}: give 0 or a positive number of milliseconds.`)
129
+ if (timeoutMs !== undefined && !(Number.isFinite(timeoutMs) && timeoutMs > 0))
130
+ throw new Error(`@prunellejs/content: collection "${name}" has timeoutMs ${timeoutMs}: give a positive number of milliseconds.`)
131
+ }
132
+
133
+ interface SharedLoad<TData> {
134
+ pending: Promise<ContentEntry<TData>[]>
135
+ // When the load finished, once it did: from then on it is reused for ttlMs.
136
+ doneAt?: number
137
+ }
138
+
139
+ // Runs a collection's loader with a signal, and fails when the signal aborts even if the loader ignores it.
140
+ function createLoadRunner(name: string, timeoutMs: number, load: LoaderCollectionOptions<unknown>['load']) {
141
+ const running = new Set<AbortController>()
142
+ async function run(ctx: { locale?: string | undefined }): Promise<LoadedEntryInput[]> {
143
+ const controller = new AbortController()
144
+ running.add(controller)
145
+ const timer = setTimeout(() => controller.abort(new Error(`@prunellejs/content: collection "${name}" loader took over ${timeoutMs} ms: raise timeoutMs, or make the source answer sooner.`)), timeoutMs)
146
+ try {
147
+ return await new Promise<LoadedEntryInput[]>((resolve, reject) => {
148
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true })
149
+ Promise.resolve(load({ ...ctx, signal: controller.signal })).then(resolve, reject)
150
+ })
151
+ }
152
+ finally {
153
+ clearTimeout(timer)
154
+ running.delete(controller)
155
+ }
156
+ }
157
+ function cancelAll(): void {
158
+ for (const controller of running)
159
+ controller.abort(new Error(`@prunellejs/content: collection "${name}" load was cancelled: its cache was cleared.`))
160
+ }
161
+ return { run, cancelAll }
162
+ }
163
+
164
+ // At runtime, per locale, the load every request shares while it runs and for ttlMs after.
165
+ function createSharedLoads<TData>(ttlMs: number) {
166
+ let shared = new Map<string, SharedLoad<TData>>()
167
+ function get(key: string, start: () => Promise<ContentEntry<TData>[]>): Promise<ContentEntry<TData>[]> {
168
+ const hit = shared.get(key)
169
+ if (hit !== undefined && (hit.doneAt === undefined || Date.now() - hit.doneAt < ttlMs))
170
+ return hit.pending
171
+ // A load cleared while it ran forgets itself from its own map, never from the one that replaced it.
172
+ const map = shared
173
+ const load: SharedLoad<TData> = { pending: start() }
174
+ const forget = (): void => {
175
+ map.delete(key)
176
+ }
177
+ map.set(key, load)
178
+ load.pending.then(() => {
179
+ if (ttlMs > 0)
180
+ load.doneAt = Date.now()
181
+ else
182
+ forget()
183
+ }, forget)
184
+ return load.pending
185
+ }
186
+ return { get, clear: () => { shared = new Map() } }
187
+ }
188
+
189
+ export function createLoaderCollection<TData = Record<string, unknown>>(
190
+ options: LoaderCollectionOptions<TData>,
191
+ ): AsyncCollection<TData> {
192
+ const name = options.name ?? 'collection'
193
+ checkDurations(name, options)
194
+ const ttlMs = options.ttlMs ?? 0
195
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
196
+ const localized = options.localized ?? false
197
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
198
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
199
+ const renderLoader = createRenderConfigLoader(name, options)
200
+ const sourceFile = currentDiscoverFile()
201
+
202
+ let buildCache = new WeakMap<AppRuntimeContext, Map<string, Promise<ContentEntry<TData>[]>>>()
203
+ let requestCache = new WeakMap<RequestContext, Map<string, Promise<ContentEntry<TData>[]>>>()
204
+ let lastBuildCtx: WeakRef<AppRuntimeContext> | undefined
205
+ const runner = createLoadRunner(name, timeoutMs, options.load)
206
+ const shared = createSharedLoads<TData>(ttlMs)
207
+
208
+ // The cache of the build, or of the request (`runtime`), the current code runs in.
209
+ function resolveCacheMap(): { bucket: Map<string, Promise<ContentEntry<TData>[]>>, runtime: boolean } | undefined {
210
+ const reqCtx = currentRequest()?.ctx
211
+ const appCtx = getAppContext()
212
+ if (reqCtx === undefined && appCtx !== undefined) {
213
+ lastBuildCtx = new WeakRef(appCtx)
214
+ return { bucket: getOrCreateLocaleMap(buildCache, appCtx), runtime: false }
215
+ }
216
+ if (reqCtx !== undefined) {
217
+ const buildCtx = lastBuildCtx?.deref()
218
+ if (
219
+ buildCtx !== undefined
220
+ && appCtx !== undefined
221
+ && appCtx.root === buildCtx.root
222
+ && appCtx.outDir === buildCtx.outDir
223
+ )
224
+ return { bucket: getOrCreateLocaleMap(buildCache, buildCtx), runtime: false }
225
+ if (appCtx?.inject(CONTENT_PRERENDER_SERVICE) === true)
226
+ return { bucket: getOrCreateLocaleMap(buildCache, appCtx), runtime: false }
227
+ return { bucket: getOrCreateLocaleMap(requestCache, reqCtx), runtime: true }
228
+ }
229
+ return undefined
230
+ }
231
+
232
+
233
+ async function loadValidatedEntries(targetLocale: string | undefined): Promise<ContentEntry<TData>[]> {
234
+ const rawEntries = await runner.run(localized ? { locale: targetLocale } : {})
235
+ const entries: ContentEntry<TData>[] = []
236
+ for (const raw of rawEntries) {
237
+ if (localized && raw.locale !== undefined && raw.locale !== targetLocale)
238
+ continue
239
+ const slug = cleanSlug(raw.slug, name)
240
+ let data: TData
241
+ if (options.schema !== undefined) {
242
+ const checked = await validateSchema(options.schema, raw.data)
243
+ if (!checked.ok) {
244
+ throw new Error(
245
+ `@prunellejs/content: invalid entry "${slug}" in collection "${name}": ${formatSchemaIssues(checked.issues)}`,
246
+ )
247
+ }
248
+ data = checked.value
249
+ }
250
+ else {
251
+ data = (raw.data !== null && typeof raw.data === 'object' ? raw.data : {}) as TData
252
+ }
253
+ const entryLocale = localized ? (raw.locale ?? targetLocale) : raw.locale
254
+ const file = raw.id ?? `${name}:${slug}`
255
+ entries.push(buildContentEntry({
256
+ slug,
257
+ locale: entryLocale,
258
+ file,
259
+ data,
260
+ body: raw.body ?? '',
261
+ renderLoader,
262
+ }))
263
+ }
264
+ entries.sort(options.sort ?? defaultSort)
265
+ return entries
266
+ }
267
+
268
+ function loadCached(locale?: string): Promise<ContentEntry<TData>[]> {
269
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
270
+ const cacheKey = targetLocale ?? ''
271
+ const scope = resolveCacheMap()
272
+ if (scope === undefined)
273
+ return loadValidatedEntries(targetLocale)
274
+ const { bucket, runtime } = scope
275
+ const hit = bucket.get(cacheKey)
276
+ if (hit !== undefined)
277
+ return hit
278
+ const pending = (runtime ? shared.get(cacheKey, () => loadValidatedEntries(targetLocale)) : loadValidatedEntries(targetLocale)).catch((err) => {
279
+ bucket.delete(cacheKey)
280
+ throw err
281
+ })
282
+ bucket.set(cacheKey, pending)
283
+ return pending
284
+ }
285
+
286
+ async function all(locale?: string): Promise<ContentEntry<TData>[]> {
287
+ const entries = await loadCached(locale)
288
+ return allowsDrafts() ? entries.slice() : entries.filter(e => !isDraft(e.data))
289
+ }
290
+
291
+ async function get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined> {
292
+ const clean = slug.replace(/^\/+|\/+$/g, '')
293
+ const entries = await all(locale)
294
+ return entries.find(e => e.slug === clean)
295
+ }
296
+
297
+ const col: AsyncCollection<TData> & InternalCollection = {
298
+ name,
299
+ all,
300
+ get,
301
+ byTag: async (tag, locale) => filterByTag(await all(locale), tag),
302
+ paths: async (prefix = '', locale) => formatPaths(await all(locale), prefix),
303
+ clearCache() {
304
+ buildCache = new WeakMap()
305
+ requestCache = new WeakMap()
306
+ lastBuildCtx = undefined
307
+ shared.clear()
308
+ runner.cancelAll()
309
+ },
310
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateLoadedEntriesForCheck({
311
+ name,
312
+ root,
313
+ sourceFile,
314
+ localized,
315
+ defaultLocale: getDefaultLocale(),
316
+ locales: options.locales,
317
+ schema: options.schema,
318
+ load: runner.run,
319
+ }),
320
+ [COLLECTION_DIR_FOR_ROOT_KEY]: () => undefined,
321
+ [COLLECTION_META_KEY]: () => ({
322
+ name,
323
+ localized,
324
+ defaultLocale: getDefaultLocale(),
325
+ locales: options.locales ?? (localized ? currentApp.locales() : undefined),
326
+ schema: options.schema,
327
+ isAsync: true,
328
+ }),
329
+ }
330
+
331
+ registerLoadedCollection(col, options.name, localized)
332
+ return col
333
+ }