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
|
import glob from 'fast-glob';
import fsMod from 'node:fs';
import { extname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import pLimit from 'p-limit';
import type { Plugin } from 'vite';
import type { AstroSettings } from '../@types/astro.js';
import { AstroError, AstroErrorData } from '../core/errors/index.js';
import { rootRelativePath } from '../core/util.js';
import { VIRTUAL_MODULE_ID } from './consts.js';
import {
getContentEntryConfigByExtMap,
getContentEntryIdAndSlug,
getContentPaths,
getDataEntryExts,
getDataEntryId,
getEntryCollectionName,
getEntrySlug,
getEntryType,
getExtGlob,
type ContentLookupMap,
type ContentPaths,
} from './utils.js';
interface AstroContentVirtualModPluginParams {
settings: AstroSettings;
}
export function astroContentVirtualModPlugin({
settings,
}: AstroContentVirtualModPluginParams): Plugin {
const contentPaths = getContentPaths(settings.config);
const relContentDir = rootRelativePath(settings.config.root, contentPaths.contentDir);
const contentEntryConfigByExt = getContentEntryConfigByExtMap(settings);
const contentEntryExts = [...contentEntryConfigByExt.keys()];
const dataEntryExts = getDataEntryExts(settings);
const virtualModContents = fsMod
.readFileSync(contentPaths.virtualModTemplate, 'utf-8')
.replace(
'@@COLLECTION_NAME_BY_REFERENCE_KEY@@',
new URL('reference-map.json', contentPaths.cacheDir).pathname
)
.replace('@@CONTENT_DIR@@', relContentDir)
.replace('@@CONTENT_ENTRY_GLOB_PATH@@', `${relContentDir}**/*${getExtGlob(contentEntryExts)}`)
.replace('@@DATA_ENTRY_GLOB_PATH@@', `${relContentDir}**/*${getExtGlob(dataEntryExts)}`)
.replace(
'@@RENDER_ENTRY_GLOB_PATH@@',
`${relContentDir}**/*${getExtGlob(/** Note: data collections excluded */ contentEntryExts)}`
);
const astroContentVirtualModuleId = '\0' + VIRTUAL_MODULE_ID;
return {
name: 'astro-content-virtual-mod-plugin',
resolveId(id) {
if (id === VIRTUAL_MODULE_ID) {
return astroContentVirtualModuleId;
}
},
async load(id) {
if (id === astroContentVirtualModuleId) {
const stringifiedLookupMap = await getStringifiedLookupMap({
fs: fsMod,
contentPaths,
contentEntryConfigByExt,
dataEntryExts,
root: settings.config.root,
});
return {
code: virtualModContents.replace(
'/* @@LOOKUP_MAP_ASSIGNMENT@@ */',
`lookupMap = ${stringifiedLookupMap};`
),
};
}
},
};
}
/**
* Generate a map from a collection + slug to the local file path.
* This is used internally to resolve entry imports when using `getEntry()`.
* @see `src/content/virtual-mod.mjs`
*/
export async function getStringifiedLookupMap({
contentPaths,
contentEntryConfigByExt,
dataEntryExts,
root,
fs,
}: {
contentEntryConfigByExt: ReturnType<typeof getContentEntryConfigByExtMap>;
dataEntryExts: string[];
contentPaths: Pick<ContentPaths, 'contentDir' | 'config'>;
root: URL;
fs: typeof fsMod;
}) {
const { contentDir } = contentPaths;
const relContentDir = rootRelativePath(root, contentDir, false);
const contentEntryExts = [...contentEntryConfigByExt.keys()];
let lookupMap: ContentLookupMap = {};
const contentGlob = await glob(
`${relContentDir}**/*${getExtGlob([...dataEntryExts, ...contentEntryExts])}`,
{
absolute: true,
cwd: fileURLToPath(root),
fs: {
readdir: fs.readdir.bind(fs),
readdirSync: fs.readdirSync.bind(fs),
},
}
);
// 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 noticably 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 } = await getContentEntryIdAndSlug({
entry: pathToFileURL(filePath),
contentDir,
collection,
});
const slug = await getEntrySlug({
id,
collection,
generatedSlug,
fs,
fileUrl: pathToFileURL(filePath),
contentEntryType,
});
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 JSON.stringify(lookupMap);
}
const UnexpectedLookupMapError = new AstroError({
...AstroErrorData.UnknownContentCollectionError,
message: `Unexpected error while parsing content entry IDs and slugs.`,
});
|