-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathindex.ts
385 lines (345 loc) · 10.6 KB
/
index.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path';
import logger from '@docusaurus/logger';
import {
normalizeUrl,
docuHash,
aliasedSitePath,
getPluginI18nPath,
posixPath,
addTrailingPathSeparator,
createAbsoluteFilePathMatcher,
getContentPathList,
getDataFilePath,
DEFAULT_PLUGIN_ID,
resolveMarkdownLinkPathname,
} from '@docusaurus/utils';
import {getTagsFilePathsToWatch} from '@docusaurus/utils-validation';
import {createMDXLoaderItem} from '@docusaurus/mdx-loader';
import {
getBlogTags,
paginateBlogPosts,
shouldBeListed,
applyProcessBlogPosts,
generateBlogPosts,
reportUntruncatedBlogPosts,
} from './blogUtils';
import footnoteIDFixer from './remark/footnoteIDFixer';
import {translateContent, getTranslationFiles} from './translations';
import {createBlogFeedFiles, createFeedHtmlHeadTags} from './feed';
import {createAllRoutes} from './routes';
import {checkAuthorsMapPermalinkCollisions, getAuthorsMap} from './authorsMap';
import {createContentHelpers} from './contentHelpers';
import type {BlogContentPaths, BlogMarkdownLoaderOptions} from './types';
import type {LoadContext, Plugin} from '@docusaurus/types';
import type {
PluginOptions,
Assets,
BlogTags,
BlogContent,
BlogPaginated,
} from '@docusaurus/plugin-content-blog';
import type {RuleSetRule, RuleSetUseItem} from 'webpack';
const PluginName = 'docusaurus-plugin-content-blog';
export default async function pluginContentBlog(
context: LoadContext,
options: PluginOptions,
): Promise<Plugin<BlogContent>> {
const {
siteDir,
siteConfig,
generatedFilesDir,
localizationDir,
i18n: {currentLocale},
} = context;
const router = siteConfig.future.experimental_router;
const isBlogFeedDisabledBecauseOfHashRouter =
router === 'hash' && !!options.feedOptions.type;
if (isBlogFeedDisabledBecauseOfHashRouter) {
logger.warn(
`${PluginName} feed feature does not support the Hash Router. Feeds won't be generated.`,
);
}
const {onBrokenMarkdownLinks, baseUrl} = siteConfig;
const contentPaths: BlogContentPaths = {
contentPath: path.resolve(siteDir, options.path),
contentPathLocalized: getPluginI18nPath({
localizationDir,
pluginName: PluginName,
pluginId: options.id,
}),
};
const pluginId = options.id ?? DEFAULT_PLUGIN_ID;
const pluginDataDirRoot = path.join(generatedFilesDir, PluginName);
const dataDir = path.join(pluginDataDirRoot, pluginId);
// TODO Docusaurus v4 breaking change
// module aliasing should be automatic
// we should never find local absolute FS paths in the codegen registry
const aliasedSource = (source: string) =>
`~blog/${posixPath(path.relative(pluginDataDirRoot, source))}`;
const authorsMapFilePath = await getDataFilePath({
filePath: options.authorsMapPath,
contentPaths,
});
const contentHelpers = createContentHelpers();
async function createBlogMDXLoaderRule(): Promise<RuleSetRule> {
const {
admonitions,
rehypePlugins,
remarkPlugins,
recmaPlugins,
truncateMarker,
beforeDefaultRemarkPlugins,
beforeDefaultRehypePlugins,
} = options;
const contentDirs = getContentPathList(contentPaths);
const mdxLoaderItem = await createMDXLoaderItem({
useCrossCompilerCache:
siteConfig.future.experimental_faster.mdxCrossCompilerCache,
admonitions,
remarkPlugins,
rehypePlugins,
recmaPlugins,
beforeDefaultRemarkPlugins: [
footnoteIDFixer,
...beforeDefaultRemarkPlugins,
],
beforeDefaultRehypePlugins,
staticDirs: siteConfig.staticDirectories.map((dir) =>
path.resolve(siteDir, dir),
),
siteDir,
isMDXPartial: createAbsoluteFilePathMatcher(options.exclude, contentDirs),
metadataPath: (mdxPath: string) => {
// Note that metadataPath must be the same/in-sync as
// the path from createData for each MDX.
const aliasedPath = aliasedSitePath(mdxPath, siteDir);
return path.join(dataDir, `${docuHash(aliasedPath)}.json`);
},
// For blog posts a title in markdown is always removed
// Blog posts title are rendered separately
removeContentTitle: true,
// createAssets converts relative paths to require() calls
createAssets: ({filePath}: {filePath: string}): Assets => {
const blogPost = contentHelpers.sourceToBlogPost.get(
aliasedSitePath(filePath, siteDir),
)!;
if (!blogPost) {
throw new Error(`Blog post not found for filePath=${filePath}`);
}
return {
image: blogPost.metadata.frontMatter.image as string,
authorsImageUrls: blogPost.metadata.authors.map(
(author) => author.imageURL,
),
};
},
markdownConfig: siteConfig.markdown,
resolveMarkdownLink: ({linkPathname, sourceFilePath}) => {
const permalink = resolveMarkdownLinkPathname(linkPathname, {
sourceFilePath,
sourceToPermalink: contentHelpers.sourceToPermalink,
siteDir,
contentPaths,
});
if (permalink === null) {
logger.report(
onBrokenMarkdownLinks,
)`Blog markdown link couldn't be resolved: (url=${linkPathname}) in source file path=${sourceFilePath}`;
}
return permalink;
},
});
function createBlogMarkdownLoader(): RuleSetUseItem {
const markdownLoaderOptions: BlogMarkdownLoaderOptions = {
truncateMarker,
};
return {
loader: path.resolve(__dirname, './markdownLoader.js'),
options: markdownLoaderOptions,
};
}
return {
test: /\.mdx?$/i,
include: contentDirs
// Trailing slash is important, see https://github.com/facebook/docusaurus/pull/3970
.map(addTrailingPathSeparator),
use: [mdxLoaderItem, createBlogMarkdownLoader()],
};
}
const blogMDXLoaderRule = await createBlogMDXLoaderRule();
return {
name: PluginName,
getPathsToWatch() {
const {include} = options;
const contentMarkdownGlobs = getContentPathList(contentPaths).flatMap(
(contentPath) => include.map((pattern) => `${contentPath}/${pattern}`),
);
const tagsFilePaths = getTagsFilePathsToWatch({
contentPaths,
tags: options.tags,
});
return [
authorsMapFilePath,
...tagsFilePaths,
...contentMarkdownGlobs,
].filter(Boolean) as string[];
},
getTranslationFiles() {
return getTranslationFiles(options);
},
// Fetches blog contents and returns metadata for the necessary routes.
async loadContent() {
const {
postsPerPage: postsPerPageOption,
routeBasePath,
tagsBasePath,
blogDescription,
blogTitle,
blogSidebarTitle,
pageBasePath,
authorsBasePath,
authorsMapPath,
} = options;
const baseBlogUrl = normalizeUrl([baseUrl, routeBasePath]);
const blogTagsListPath = normalizeUrl([baseBlogUrl, tagsBasePath]);
const authorsMap = await getAuthorsMap({
contentPaths,
authorsMapPath,
authorsBaseRoutePath: normalizeUrl([
baseUrl,
routeBasePath,
authorsBasePath,
]),
baseUrl,
});
checkAuthorsMapPermalinkCollisions(authorsMap);
let blogPosts = await generateBlogPosts(
contentPaths,
context,
options,
authorsMap,
);
blogPosts = await applyProcessBlogPosts({
blogPosts,
processBlogPosts: options.processBlogPosts,
});
reportUntruncatedBlogPosts({
blogPosts,
onUntruncatedBlogPosts: options.onUntruncatedBlogPosts,
});
const listedBlogPosts = blogPosts.filter(shouldBeListed);
if (!blogPosts.length) {
return {
blogSidebarTitle,
blogPosts: [],
blogListPaginated: [],
blogTags: {},
blogTagsListPath,
authorsMap,
};
}
// Collocate next and prev metadata.
listedBlogPosts.forEach((blogPost, index) => {
const prevItem = index > 0 ? listedBlogPosts[index - 1] : null;
if (prevItem) {
blogPost.metadata.prevItem = {
title: prevItem.metadata.title,
permalink: prevItem.metadata.permalink,
};
}
const nextItem =
index < listedBlogPosts.length - 1
? listedBlogPosts[index + 1]
: null;
if (nextItem) {
blogPost.metadata.nextItem = {
title: nextItem.metadata.title,
permalink: nextItem.metadata.permalink,
};
}
});
const blogListPaginated: BlogPaginated[] = paginateBlogPosts({
blogPosts: listedBlogPosts,
blogTitle,
blogDescription,
postsPerPageOption,
basePageUrl: baseBlogUrl,
pageBasePath,
});
const blogTags: BlogTags = getBlogTags({
blogPosts,
postsPerPageOption,
blogDescription,
blogTitle,
pageBasePath,
});
return {
blogSidebarTitle,
blogPosts,
blogListPaginated,
blogTags,
blogTagsListPath,
authorsMap,
};
},
async contentLoaded({content, actions}) {
contentHelpers.updateContent(content);
await createAllRoutes({
baseUrl,
content,
actions,
options,
aliasedSource,
});
},
translateContent({content, translationFiles}) {
return translateContent(content, translationFiles);
},
configureWebpack() {
return {
resolve: {
alias: {
'~blog': pluginDataDirRoot,
},
},
module: {
rules: [blogMDXLoaderRule],
},
};
},
async postBuild({outDir, content}) {
if (
!content.blogPosts.length ||
!options.feedOptions.type ||
isBlogFeedDisabledBecauseOfHashRouter
) {
return;
}
await createBlogFeedFiles({
blogPosts: content.blogPosts,
options,
outDir,
siteConfig,
locale: currentLocale,
contentPaths,
});
},
injectHtmlTags({content}) {
if (
!content.blogPosts.length ||
!options.feedOptions.type ||
isBlogFeedDisabledBecauseOfHashRouter
) {
return {};
}
return {headTags: createFeedHtmlHeadTags({context, options})};
},
};
}
export {validateOptions} from './options';