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
365
366
367
368
369
370
|
import nodeFs from 'node:fs';
import { extname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dataToEsm } from '@rollup/pluginutils';
import pLimit from 'p-limit';
import { glob } from 'tinyglobby';
import type { Plugin, ViteDevServer } from 'vite';
import { AstroError, AstroErrorData } from '../core/errors/index.js';
import { rootRelativePath } from '../core/viteUtils.js';
import type { AstroSettings } from '../types/astro.js';
import type { AstroPluginMetadata } from '../vite-plugin-astro/index.js';
import { createDefaultAstroMetadata } from '../vite-plugin-astro/metadata.js';
import {
ASSET_IMPORTS_FILE,
ASSET_IMPORTS_RESOLVED_STUB_ID,
ASSET_IMPORTS_VIRTUAL_ID,
CONTENT_FLAG,
CONTENT_RENDER_FLAG,
DATA_FLAG,
DATA_STORE_VIRTUAL_ID,
MODULES_IMPORTS_FILE,
MODULES_MJS_ID,
MODULES_MJS_VIRTUAL_ID,
RESOLVED_DATA_STORE_VIRTUAL_ID,
RESOLVED_VIRTUAL_MODULE_ID,
VIRTUAL_MODULE_ID,
} from './consts.js';
import { getDataStoreFile } from './content-layer.js';
import {
type ContentLookupMap,
getContentEntryIdAndSlug,
getContentPaths,
getDataEntryExts,
getDataEntryId,
getEntryCollectionName,
getEntryConfigByExtMap,
getEntrySlug,
getEntryType,
getExtGlob,
globWithUnderscoresIgnored,
isDeferredModule,
} from './utils.js';
interface AstroContentVirtualModPluginParams {
settings: AstroSettings;
fs: typeof nodeFs;
}
function invalidateDataStore(server: ViteDevServer) {
const module = server.moduleGraph.getModuleById(RESOLVED_DATA_STORE_VIRTUAL_ID);
if (module) {
server.moduleGraph.invalidateModule(module);
}
server.ws.send({
type: 'full-reload',
path: '*',
});
}
export function astroContentVirtualModPlugin({
settings,
fs,
}: AstroContentVirtualModPluginParams): Plugin {
let dataStoreFile: URL;
let devServer: ViteDevServer;
return {
name: 'astro-content-virtual-mod-plugin',
enforce: 'pre',
config(_, env) {
dataStoreFile = getDataStoreFile(settings, env.command === 'serve');
},
buildStart() {
if (devServer) {
// We defer adding the data store file to the watcher until the server is ready
devServer.watcher.add(fileURLToPath(dataStoreFile));
// Manually invalidate the data store to avoid a race condition in file watching
invalidateDataStore(devServer);
}
},
async resolveId(id) {
if (id === VIRTUAL_MODULE_ID) {
return RESOLVED_VIRTUAL_MODULE_ID;
}
if (id === DATA_STORE_VIRTUAL_ID) {
return RESOLVED_DATA_STORE_VIRTUAL_ID;
}
if (isDeferredModule(id)) {
const [, query] = id.split('?');
const params = new URLSearchParams(query);
const fileName = params.get('fileName');
let importPath = undefined;
if (fileName && URL.canParse(fileName, settings.config.root.toString())) {
importPath = fileURLToPath(new URL(fileName, settings.config.root));
}
if (importPath) {
return await this.resolve(`${importPath}?${CONTENT_RENDER_FLAG}`);
}
}
if (id === MODULES_MJS_ID) {
const modules = new URL(MODULES_IMPORTS_FILE, settings.dotAstroDir);
if (fs.existsSync(modules)) {
return fileURLToPath(modules);
}
return MODULES_MJS_VIRTUAL_ID;
}
if (id === ASSET_IMPORTS_VIRTUAL_ID) {
const assetImportsFile = new URL(ASSET_IMPORTS_FILE, settings.dotAstroDir);
if (fs.existsSync(assetImportsFile)) {
return fileURLToPath(assetImportsFile);
}
return ASSET_IMPORTS_RESOLVED_STUB_ID;
}
},
async load(id, args) {
if (id === RESOLVED_VIRTUAL_MODULE_ID) {
const lookupMap = settings.config.legacy.collections
? await generateLookupMap({
settings,
fs,
})
: {};
const isClient = !args?.ssr;
const code = await generateContentEntryFile({
settings,
fs,
lookupMap,
isClient,
});
const astro = createDefaultAstroMetadata();
astro.propagation = 'in-tree';
return {
code,
meta: {
astro,
} satisfies AstroPluginMetadata,
};
}
if (id === RESOLVED_DATA_STORE_VIRTUAL_ID) {
if (!fs.existsSync(dataStoreFile)) {
return 'export default new Map()';
}
const jsonData = await fs.promises.readFile(dataStoreFile, 'utf-8');
try {
const parsed = JSON.parse(jsonData);
return {
code: dataToEsm(parsed, {
compact: true,
}),
map: { mappings: '' },
};
} catch (err) {
const message = 'Could not parse JSON file';
this.error({ message, id, cause: err });
}
}
if (id === ASSET_IMPORTS_RESOLVED_STUB_ID) {
const assetImportsFile = new URL(ASSET_IMPORTS_FILE, settings.dotAstroDir);
if (!fs.existsSync(assetImportsFile)) {
return 'export default new Map()';
}
return fs.readFileSync(assetImportsFile, 'utf-8');
}
if (id === MODULES_MJS_VIRTUAL_ID) {
const modules = new URL(MODULES_IMPORTS_FILE, settings.dotAstroDir);
if (!fs.existsSync(modules)) {
return 'export default new Map()';
}
return fs.readFileSync(modules, 'utf-8');
}
},
configureServer(server) {
devServer = server;
const dataStorePath = fileURLToPath(dataStoreFile);
// If the datastore file changes, invalidate the virtual module
server.watcher.on('add', (addedPath) => {
if (addedPath === dataStorePath) {
invalidateDataStore(server);
}
});
server.watcher.on('change', (changedPath) => {
if (changedPath === dataStorePath) {
invalidateDataStore(server);
}
});
},
};
}
export async function generateContentEntryFile({
settings,
lookupMap,
isClient,
}: {
settings: AstroSettings;
fs: typeof nodeFs;
lookupMap: ContentLookupMap;
isClient: boolean;
}) {
const contentPaths = getContentPaths(settings.config);
const relContentDir = rootRelativePath(settings.config.root, contentPaths.contentDir);
let contentEntryGlobResult = '""';
let dataEntryGlobResult = '""';
let renderEntryGlobResult = '""';
if (settings.config.legacy.collections) {
const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes);
const contentEntryExts = [...contentEntryConfigByExt.keys()];
const dataEntryExts = getDataEntryExts(settings);
const createGlob = (value: string[], flag: string) =>
`import.meta.glob(${JSON.stringify(value)}, { query: { ${flag}: true } })`;
contentEntryGlobResult = createGlob(
globWithUnderscoresIgnored(relContentDir, contentEntryExts),
CONTENT_FLAG,
);
dataEntryGlobResult = createGlob(
globWithUnderscoresIgnored(relContentDir, dataEntryExts),
DATA_FLAG,
);
renderEntryGlobResult = createGlob(
globWithUnderscoresIgnored(relContentDir, contentEntryExts),
CONTENT_RENDER_FLAG,
);
}
let virtualModContents: string;
if (isClient) {
throw new AstroError({
...AstroErrorData.ServerOnlyModule,
message: AstroErrorData.ServerOnlyModule.message('astro:content'),
});
} else {
virtualModContents = nodeFs
.readFileSync(contentPaths.virtualModTemplate, 'utf-8')
.replace('@@CONTENT_DIR@@', relContentDir)
.replace("'@@CONTENT_ENTRY_GLOB_PATH@@'", contentEntryGlobResult)
.replace("'@@DATA_ENTRY_GLOB_PATH@@'", dataEntryGlobResult)
.replace("'@@RENDER_ENTRY_GLOB_PATH@@'", renderEntryGlobResult)
.replace('/* @@LOOKUP_MAP_ASSIGNMENT@@ */', `lookupMap = ${JSON.stringify(lookupMap)};`);
}
return virtualModContents;
}
/**
* Generate a map from a collection + slug to the local file path.
* This is used internally to resolve entry imports when using `getEntry()`.
* @see `templates/content/module.mjs`
*/
export async function generateLookupMap({
settings,
fs,
}: {
settings: AstroSettings;
fs: typeof nodeFs;
}) {
const { root } = settings.config;
const contentPaths = getContentPaths(settings.config);
const relContentDir = rootRelativePath(root, contentPaths.contentDir, false);
const contentEntryConfigByExt = getEntryConfigByExtMap(settings.contentEntryTypes);
const dataEntryExts = getDataEntryExts(settings);
const { contentDir } = contentPaths;
const contentEntryExts = [...contentEntryConfigByExt.keys()];
let lookupMap: ContentLookupMap = {};
const contentGlob = await glob(
`${relContentDir}**/*${getExtGlob([...dataEntryExts, ...contentEntryExts])}`,
{
absolute: true,
cwd: fileURLToPath(root),
expandDirectories: false,
},
);
// Run 10 at a time to prevent `await getEntrySlug` from accessing the filesystem all at once.
// Each await shouldn't take too long for the work to be noticeably slow too.
const limit = pLimit(10);
const promises: Promise<void>[] = [];
for (const filePath of contentGlob) {
promises.push(
limit(async () => {
const entryType = getEntryType(filePath, contentPaths, contentEntryExts, dataEntryExts);
// Globbed ignored or unsupported entry.
// Logs warning during type generation, should ignore in lookup map.
if (entryType !== 'content' && entryType !== 'data') return;
const collection = getEntryCollectionName({ contentDir, entry: pathToFileURL(filePath) });
if (!collection) throw UnexpectedLookupMapError;
if (lookupMap[collection]?.type && lookupMap[collection].type !== entryType) {
throw new AstroError({
...AstroErrorData.MixedContentDataCollectionError,
message: AstroErrorData.MixedContentDataCollectionError.message(collection),
});
}
if (entryType === 'content') {
const contentEntryType = contentEntryConfigByExt.get(extname(filePath));
if (!contentEntryType) throw UnexpectedLookupMapError;
const { id, slug: generatedSlug } = getContentEntryIdAndSlug({
entry: pathToFileURL(filePath),
contentDir,
collection,
});
const slug = await getEntrySlug({
id,
collection,
generatedSlug,
fs,
fileUrl: pathToFileURL(filePath),
contentEntryType,
});
if (lookupMap[collection]?.entries?.[slug]) {
throw new AstroError({
...AstroErrorData.DuplicateContentEntrySlugError,
message: AstroErrorData.DuplicateContentEntrySlugError.message(
collection,
slug,
lookupMap[collection].entries[slug],
rootRelativePath(root, filePath),
),
hint:
slug !== generatedSlug
? `Check the \`slug\` frontmatter property in **${id}**.`
: undefined,
});
}
lookupMap[collection] = {
type: 'content',
entries: {
...lookupMap[collection]?.entries,
[slug]: rootRelativePath(root, filePath),
},
};
} else {
const id = getDataEntryId({ entry: pathToFileURL(filePath), contentDir, collection });
lookupMap[collection] = {
type: 'data',
entries: {
...lookupMap[collection]?.entries,
[id]: rootRelativePath(root, filePath),
},
};
}
}),
);
}
await Promise.all(promises);
return lookupMap;
}
const UnexpectedLookupMapError = new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `Unexpected error while parsing content entry IDs and slugs.`,
});
|