/
runtime.ts
364 lines (335 loc) · 10.1 KB
/
runtime.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import type { MarkdownHeading } from '@astrojs/markdown-remark';
import { string as zodString, ZodIssueCode } from 'zod';
import { AstroError, AstroErrorData } from '../core/errors/index.js';
import { prependForwardSlash } from '../core/path.js';
import {
createComponent,
createHeadAndContent,
renderComponent,
renderScriptElement,
renderTemplate,
renderUniqueStylesheet,
unescapeHTML,
type AstroComponentFactory,
} from '../runtime/server/index.js';
import type { ContentLookupMap } from './utils.js';
type LazyImport = () => Promise<any>;
type GlobResult = Record<string, LazyImport>;
type CollectionToEntryMap = Record<string, GlobResult>;
type GetEntryImport = (collection: string, lookupId: string) => Promise<LazyImport>;
export function createCollectionToGlobResultMap({
globResult,
contentDir,
}: {
globResult: GlobResult;
contentDir: string;
}) {
const collectionToGlobResultMap: CollectionToEntryMap = {};
for (const key in globResult) {
const keyRelativeToContentDir = key.replace(new RegExp(`^${contentDir}`), '');
const segments = keyRelativeToContentDir.split('/');
if (segments.length <= 1) continue;
const collection = segments[0];
collectionToGlobResultMap[collection] ??= {};
collectionToGlobResultMap[collection][key] = globResult[key];
}
return collectionToGlobResultMap;
}
const cacheEntriesByCollection = new Map<string, any[]>();
export function createGetCollection({
contentCollectionToEntryMap,
dataCollectionToEntryMap,
getRenderEntryImport,
}: {
contentCollectionToEntryMap: CollectionToEntryMap;
dataCollectionToEntryMap: CollectionToEntryMap;
getRenderEntryImport: GetEntryImport;
}) {
return async function getCollection(collection: string, filter?: (entry: any) => unknown) {
let type: 'content' | 'data';
if (collection in contentCollectionToEntryMap) {
type = 'content';
} else if (collection in dataCollectionToEntryMap) {
type = 'data';
} else {
throw new AstroError({
...AstroErrorData.CollectionDoesNotExistError,
message: AstroErrorData.CollectionDoesNotExistError.message(collection),
});
}
const lazyImports = Object.values(
type === 'content'
? contentCollectionToEntryMap[collection]
: dataCollectionToEntryMap[collection]
);
let entries: any[] = [];
// Cache `getCollection()` calls in production only
// prevents stale cache in development
if (import.meta.env.PROD && cacheEntriesByCollection.has(collection)) {
entries = cacheEntriesByCollection.get(collection)!;
} else {
entries = await Promise.all(
lazyImports.map(async (lazyImport) => {
const entry = await lazyImport();
return type === 'content'
? {
id: entry.id,
slug: entry.slug,
body: entry.body,
collection: entry.collection,
data: entry.data,
async render() {
return render({
collection: entry.collection,
id: entry.id,
renderEntryImport: await getRenderEntryImport(collection, entry.slug),
});
},
}
: {
id: entry.id,
collection: entry.collection,
data: entry.data,
};
})
);
cacheEntriesByCollection.set(collection, entries);
}
if (typeof filter === 'function') {
return entries.filter(filter);
} else {
return entries;
}
};
}
export function createGetEntryBySlug({
getEntryImport,
getRenderEntryImport,
}: {
getEntryImport: GetEntryImport;
getRenderEntryImport: GetEntryImport;
}) {
return async function getEntryBySlug(collection: string, slug: string) {
const entryImport = await getEntryImport(collection, slug);
if (typeof entryImport !== 'function') return undefined;
const entry = await entryImport();
return {
id: entry.id,
slug: entry.slug,
body: entry.body,
collection: entry.collection,
data: entry.data,
async render() {
return render({
collection: entry.collection,
id: entry.id,
renderEntryImport: await getRenderEntryImport(collection, slug),
});
},
};
};
}
export function createGetDataEntryById({
dataCollectionToEntryMap,
}: {
dataCollectionToEntryMap: CollectionToEntryMap;
}) {
return async function getDataEntryById(collection: string, id: string) {
const lazyImport =
dataCollectionToEntryMap[collection]?.[/*TODO: filePathToIdMap*/ id + '.json'];
// TODO: AstroError
if (!lazyImport) throw new Error(`Entry ${collection} → ${id} was not found.`);
const entry = await lazyImport();
return {
id: entry.id,
collection: entry.collection,
data: entry.data,
};
};
}
type ContentEntryResult = {
id: string;
slug: string;
body: string;
collection: string;
data: Record<string, any>;
render(): Promise<RenderResult>;
};
type DataEntryResult = {
id: string;
collection: string;
data: Record<string, any>;
};
type EntryLookupObject = { collection: string; id: string } | { collection: string; slug: string };
export function createGetEntry({
getEntryImport,
getRenderEntryImport,
}: {
getEntryImport: GetEntryImport;
getRenderEntryImport: GetEntryImport;
}) {
return async function getEntry(
// Can either pass collection and identifier as 2 positional args,
// Or pass a single object with the collection and identifier as properties.
// This means the first positional arg can have different shapes.
collectionOrLookupObject: string | EntryLookupObject,
_lookupId?: string
): Promise<ContentEntryResult | DataEntryResult | undefined> {
let collection: string, lookupId: string;
if (typeof collectionOrLookupObject === 'string') {
collection = collectionOrLookupObject;
if (!_lookupId)
throw new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: '`getEntry()` requires an entry identifier as the second argument.',
});
lookupId = _lookupId;
} else {
collection = collectionOrLookupObject.collection;
// Identifier could be `slug` for content entries, or `id` for data entries
lookupId =
'id' in collectionOrLookupObject
? collectionOrLookupObject.id
: collectionOrLookupObject.slug;
}
const entryImport = await getEntryImport(collection, lookupId);
if (typeof entryImport !== 'function') return undefined;
const entry = await entryImport();
if (entry._internal.type === 'content') {
return {
id: entry.id,
slug: entry.slug,
body: entry.body,
collection: entry.collection,
data: entry.data,
async render() {
return render({
collection: entry.collection,
id: entry.id,
renderEntryImport: await getRenderEntryImport(collection, lookupId),
});
},
};
} else if (entry._internal.type === 'data') {
return {
id: entry.id,
collection: entry.collection,
data: entry.data,
};
}
return undefined;
};
}
export function createGetEntries(getEntry: ReturnType<typeof createGetEntry>) {
return async function getEntries(
entries: { collection: string; id: string }[] | { collection: string; slug: string }[]
) {
return Promise.all(entries.map((e) => getEntry(e)));
};
}
type RenderResult = {
Content: AstroComponentFactory;
headings: MarkdownHeading[];
remarkPluginFrontmatter: Record<string, any>;
};
async function render({
collection,
id,
renderEntryImport,
}: {
collection: string;
id: string;
renderEntryImport?: LazyImport;
}): Promise<RenderResult> {
const UnexpectedRenderError = new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `Unexpected error while rendering ${String(collection)} → ${String(id)}.`,
});
if (typeof renderEntryImport !== 'function') throw UnexpectedRenderError;
const baseMod = await renderEntryImport();
if (baseMod == null || typeof baseMod !== 'object') throw UnexpectedRenderError;
const { collectedStyles, collectedLinks, collectedScripts, getMod } = baseMod;
if (typeof getMod !== 'function') throw UnexpectedRenderError;
const mod = await getMod();
if (mod == null || typeof mod !== 'object') throw UnexpectedRenderError;
const Content = createComponent({
factory(result, baseProps, slots) {
let styles = '',
links = '',
scripts = '';
if (Array.isArray(collectedStyles)) {
styles = collectedStyles
.map((style: any) => {
return renderUniqueStylesheet(result, {
type: 'inline',
content: style,
});
})
.join('');
}
if (Array.isArray(collectedLinks)) {
links = collectedLinks
.map((link: any) => {
return renderUniqueStylesheet(result, {
type: 'external',
src: prependForwardSlash(link),
});
})
.join('');
}
if (Array.isArray(collectedScripts)) {
scripts = collectedScripts.map((script: any) => renderScriptElement(script)).join('');
}
let props = baseProps;
// Auto-apply MDX components export
if (id.endsWith('mdx')) {
props = {
components: mod.components ?? {},
...baseProps,
};
}
return createHeadAndContent(
unescapeHTML(styles + links + scripts) as any,
renderTemplate`${renderComponent(result, 'Content', mod.Content, props, slots)}`
);
},
propagation: 'self',
});
return {
Content,
headings: mod.getHeadings?.() ?? [],
remarkPluginFrontmatter: mod.frontmatter ?? {},
};
}
export function createReference({ lookupMap }: { lookupMap: ContentLookupMap }) {
return function reference(collection: string) {
return zodString().transform((lookupId: string, ctx) => {
const flattenedErrorPath = ctx.path.join('.');
if (!lookupMap[collection]) {
ctx.addIssue({
code: ZodIssueCode.custom,
message: `**${flattenedErrorPath}:** Reference to ${collection} invalid. Collection does not exist or is empty.`,
});
return;
}
const { type, entries } = lookupMap[collection];
const entry = entries[lookupId];
if (!entry) {
ctx.addIssue({
code: ZodIssueCode.custom,
message: `**${flattenedErrorPath}**: Reference to ${collection} invalid. Expected ${Object.keys(
entries
)
.map((c) => JSON.stringify(c))
.join(' | ')}. Received ${JSON.stringify(lookupId)}.`,
});
return;
}
// Content is still identified by slugs, so map to a `slug` key for consistency.
if (type === 'content') {
return { slug: lookupId, collection };
}
return { id: lookupId, collection };
});
};
}