@docusaurus/plugin-content-blog 2.0.0-beta.8e9b829d9 → 2.0.0-beta.9

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.
Files changed (60) hide show
  1. package/lib/.tsbuildinfo +1 -1
  2. package/lib/authors.d.ts +23 -0
  3. package/lib/authors.js +150 -0
  4. package/lib/blogFrontMatter.d.ts +19 -6
  5. package/lib/blogFrontMatter.js +31 -19
  6. package/lib/blogUtils.d.ts +10 -4
  7. package/lib/blogUtils.js +141 -135
  8. package/lib/feed.d.ts +20 -0
  9. package/lib/feed.js +90 -0
  10. package/lib/index.js +86 -85
  11. package/lib/markdownLoader.d.ts +3 -6
  12. package/lib/markdownLoader.js +5 -5
  13. package/lib/pluginOptionSchema.d.ts +3 -27
  14. package/lib/pluginOptionSchema.js +21 -7
  15. package/lib/translations.d.ts +10 -0
  16. package/lib/translations.js +53 -0
  17. package/lib/types.d.ts +52 -14
  18. package/package.json +15 -13
  19. package/src/__tests__/__fixtures__/authorsMapFiles/authors.json +29 -0
  20. package/src/__tests__/__fixtures__/authorsMapFiles/authors.yml +27 -0
  21. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad1.json +5 -0
  22. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad1.yml +3 -0
  23. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad2.json +3 -0
  24. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad2.yml +2 -0
  25. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad3.json +8 -0
  26. package/src/__tests__/__fixtures__/authorsMapFiles/authorsBad3.yml +3 -0
  27. package/src/__tests__/__fixtures__/component/Typography.tsx +6 -0
  28. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathEmpty/empty +0 -0
  29. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathJson1/authors.json +0 -0
  30. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathJson2/authors.json +0 -0
  31. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathNestedYml/sub/folder/authors.yml +0 -0
  32. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathYml1/authors.yml +0 -0
  33. package/src/__tests__/__fixtures__/getAuthorsMapFilePath/contentPathYml2/authors.yml +0 -0
  34. package/src/__tests__/__fixtures__/website/blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  35. package/src/__tests__/__fixtures__/website/blog/authors.yml +4 -0
  36. package/src/__tests__/__fixtures__/website/blog/mdx-blog-post.mdx +36 -0
  37. package/src/__tests__/__fixtures__/website/blog/mdx-require-blog-post.mdx +14 -0
  38. package/src/__tests__/__fixtures__/website/blog/simple-slug.md +4 -0
  39. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md +3 -0
  40. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/authors.yml +5 -0
  41. package/src/__tests__/__fixtures__/website/static/img/docusaurus.png +0 -0
  42. package/src/__tests__/__snapshots__/{generateBlogFeed.test.ts.snap → feed.test.ts.snap} +55 -7
  43. package/src/__tests__/__snapshots__/translations.test.ts.snap +64 -0
  44. package/src/__tests__/authors.test.ts +608 -0
  45. package/src/__tests__/blogFrontMatter.test.ts +93 -16
  46. package/src/__tests__/blogUtils.test.ts +94 -0
  47. package/src/__tests__/{generateBlogFeed.test.ts → feed.test.ts} +32 -8
  48. package/src/__tests__/index.test.ts +73 -12
  49. package/src/__tests__/pluginOptionSchema.test.ts +3 -3
  50. package/src/__tests__/translations.test.ts +92 -0
  51. package/src/authors.ts +202 -0
  52. package/src/blogFrontMatter.ts +73 -33
  53. package/src/blogUtils.ts +201 -180
  54. package/src/feed.ts +129 -0
  55. package/src/index.ts +105 -88
  56. package/src/markdownLoader.ts +8 -12
  57. package/{index.d.ts → src/plugin-content-blog.d.ts} +35 -31
  58. package/src/pluginOptionSchema.ts +24 -9
  59. package/src/translations.ts +63 -0
  60. package/src/types.ts +67 -16
package/src/blogUtils.ts CHANGED
@@ -9,14 +9,14 @@ import fs from 'fs-extra';
9
9
  import chalk from 'chalk';
10
10
  import path from 'path';
11
11
  import readingTime from 'reading-time';
12
- import {Feed} from 'feed';
13
12
  import {keyBy, mapValues} from 'lodash';
14
13
  import {
15
14
  PluginOptions,
16
15
  BlogPost,
17
- DateLink,
18
16
  BlogContentPaths,
19
17
  BlogMarkdownLoaderOptions,
18
+ BlogTags,
19
+ ReadingTimeFunction,
20
20
  } from './types';
21
21
  import {
22
22
  parseMarkdownFile,
@@ -27,9 +27,12 @@ import {
27
27
  posixPath,
28
28
  replaceMarkdownLinks,
29
29
  Globby,
30
+ normalizeFrontMatterTags,
31
+ groupTaggedItems,
30
32
  } from '@docusaurus/utils';
31
33
  import {LoadContext} from '@docusaurus/types';
32
34
  import {validateBlogPostFrontMatter} from './blogFrontMatter';
35
+ import {AuthorsMap, getAuthorsMap, getBlogPostAuthors} from './authors';
33
36
 
34
37
  export function truncate(fileString: string, truncateMarker: RegExp): string {
35
38
  return fileString.split(truncateMarker, 1).shift()!;
@@ -44,15 +47,46 @@ export function getSourceToPermalink(
44
47
  );
45
48
  }
46
49
 
47
- // YYYY-MM-DD-{name}.mdx?
48
- // Prefer named capture, but older Node versions do not support it.
49
- const DATE_FILENAME_PATTERN = /^(\d{4}-\d{1,2}-\d{1,2})-?(.*?).mdx?$/;
50
+ export function getBlogTags(blogPosts: BlogPost[]): BlogTags {
51
+ const groups = groupTaggedItems(
52
+ blogPosts,
53
+ (blogPost) => blogPost.metadata.tags,
54
+ );
55
+ return mapValues(groups, (group) => {
56
+ return {
57
+ name: group.tag.label,
58
+ items: group.items.map((item) => item.id),
59
+ permalink: group.tag.permalink,
60
+ };
61
+ });
62
+ }
50
63
 
51
- function toUrl({date, link}: DateLink) {
52
- return `${date
53
- .toISOString()
54
- .substring(0, '2019-01-01'.length)
55
- .replace(/-/g, '/')}/${link}`;
64
+ const DATE_FILENAME_REGEX =
65
+ /^(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/;
66
+
67
+ type ParsedBlogFileName = {
68
+ date: Date | undefined;
69
+ text: string;
70
+ slug: string;
71
+ };
72
+
73
+ export function parseBlogFileName(
74
+ blogSourceRelative: string,
75
+ ): ParsedBlogFileName {
76
+ const dateFilenameMatch = blogSourceRelative.match(DATE_FILENAME_REGEX);
77
+ if (dateFilenameMatch) {
78
+ const dateString = dateFilenameMatch.groups!.date!;
79
+ const text = dateFilenameMatch.groups!.text!;
80
+ // Always treat dates as UTC by adding the `Z`
81
+ const date = new Date(`${dateString}Z`);
82
+ const slugDate = dateString.replace(/-/g, '/');
83
+ const slug = `/${slugDate}/${text}`;
84
+ return {date, text, slug};
85
+ } else {
86
+ const text = blogSourceRelative.replace(/(\/index)?\.mdx?$/, '');
87
+ const slug = `/${text}`;
88
+ return {date: undefined, text, slug};
89
+ }
56
90
  }
57
91
 
58
92
  function formatBlogPostDate(locale: string, date: Date): string {
@@ -68,206 +102,193 @@ function formatBlogPostDate(locale: string, date: Date): string {
68
102
  }
69
103
  }
70
104
 
71
- export async function generateBlogFeed(
72
- contentPaths: BlogContentPaths,
73
- context: LoadContext,
74
- options: PluginOptions,
75
- ): Promise<Feed | null> {
76
- if (!options.feedOptions) {
77
- throw new Error(
78
- 'Invalid options: "feedOptions" is not expected to be null.',
79
- );
80
- }
81
- const {siteConfig} = context;
82
- const blogPosts = await generateBlogPosts(contentPaths, context, options);
83
- if (!blogPosts.length) {
84
- return null;
85
- }
86
-
87
- const {feedOptions, routeBasePath} = options;
88
- const {url: siteUrl, baseUrl, title, favicon} = siteConfig;
89
- const blogBaseUrl = normalizeUrl([siteUrl, baseUrl, routeBasePath]);
90
-
91
- const updated =
92
- (blogPosts[0] && blogPosts[0].metadata.date) ||
93
- new Date('2015-10-25T16:29:00.000-07:00');
94
-
95
- const feed = new Feed({
96
- id: blogBaseUrl,
97
- title: feedOptions.title || `${title} Blog`,
98
- updated,
99
- language: feedOptions.language,
100
- link: blogBaseUrl,
101
- description: feedOptions.description || `${siteConfig.title} Blog`,
102
- favicon: favicon ? normalizeUrl([siteUrl, baseUrl, favicon]) : undefined,
103
- copyright: feedOptions.copyright,
104
- });
105
-
106
- blogPosts.forEach((post) => {
107
- const {
108
- id,
109
- metadata: {title: metadataTitle, permalink, date, description},
110
- } = post;
111
- feed.addItem({
112
- title: metadataTitle,
113
- id,
114
- link: normalizeUrl([siteUrl, permalink]),
115
- date,
116
- description,
117
- });
105
+ async function parseBlogPostMarkdownFile(blogSourceAbsolute: string) {
106
+ const result = await parseMarkdownFile(blogSourceAbsolute, {
107
+ removeContentTitle: true,
118
108
  });
119
-
120
- return feed;
109
+ return {
110
+ ...result,
111
+ frontMatter: validateBlogPostFrontMatter(result.frontMatter),
112
+ };
121
113
  }
122
114
 
123
- export async function generateBlogPosts(
115
+ const defaultReadingTime: ReadingTimeFunction = ({content, options}) => {
116
+ return readingTime(content, options).minutes;
117
+ };
118
+
119
+ async function processBlogSourceFile(
120
+ blogSourceRelative: string,
124
121
  contentPaths: BlogContentPaths,
125
- {siteConfig, siteDir, i18n}: LoadContext,
122
+ context: LoadContext,
126
123
  options: PluginOptions,
127
- ): Promise<BlogPost[]> {
124
+ authorsMap?: AuthorsMap,
125
+ ): Promise<BlogPost | undefined> {
126
+ const {
127
+ siteConfig: {baseUrl},
128
+ siteDir,
129
+ i18n,
130
+ } = context;
128
131
  const {
129
- include,
130
- exclude,
131
132
  routeBasePath,
133
+ tagsBasePath: tagsRouteBasePath,
132
134
  truncateMarker,
133
135
  showReadingTime,
134
136
  editUrl,
135
137
  } = options;
136
138
 
137
- if (!fs.existsSync(contentPaths.contentPath)) {
138
- return [];
139
- }
139
+ // Lookup in localized folder in priority
140
+ const blogDirPath = await getFolderContainingFile(
141
+ getContentPathList(contentPaths),
142
+ blogSourceRelative,
143
+ );
140
144
 
141
- const {baseUrl = ''} = siteConfig;
142
- const blogSourceFiles = await Globby(include, {
143
- cwd: contentPaths.contentPath,
144
- ignore: exclude,
145
- });
145
+ const blogSourceAbsolute = path.join(blogDirPath, blogSourceRelative);
146
146
 
147
- const blogPosts: BlogPost[] = [];
147
+ const {frontMatter, content, contentTitle, excerpt} =
148
+ await parseBlogPostMarkdownFile(blogSourceAbsolute);
148
149
 
149
- async function processBlogSourceFile(blogSourceFile: string) {
150
- // Lookup in localized folder in priority
151
- const blogDirPath = await getFolderContainingFile(
152
- getContentPathList(contentPaths),
153
- blogSourceFile,
150
+ const aliasedSource = aliasedSitePath(blogSourceAbsolute, siteDir);
151
+
152
+ if (frontMatter.draft && process.env.NODE_ENV === 'production') {
153
+ return undefined;
154
+ }
155
+
156
+ if (frontMatter.id) {
157
+ console.warn(
158
+ chalk.yellow(
159
+ `"id" header option is deprecated in ${blogSourceRelative} file. Please use "slug" option instead.`,
160
+ ),
154
161
  );
162
+ }
155
163
 
156
- const source = path.join(blogDirPath, blogSourceFile);
164
+ const parsedBlogFileName = parseBlogFileName(blogSourceRelative);
157
165
 
158
- const {
159
- frontMatter: unsafeFrontMatter,
160
- content,
161
- contentTitle,
162
- excerpt,
163
- } = await parseMarkdownFile(source, {removeContentTitle: true});
164
- const frontMatter = validateBlogPostFrontMatter(unsafeFrontMatter);
166
+ async function getDate(): Promise<Date> {
167
+ // Prefer user-defined date.
168
+ if (frontMatter.date) {
169
+ return new Date(frontMatter.date);
170
+ } else if (parsedBlogFileName.date) {
171
+ return parsedBlogFileName.date;
172
+ }
173
+ // Fallback to file create time
174
+ return (await fs.stat(blogSourceAbsolute)).birthtime;
175
+ }
165
176
 
166
- const aliasedSource = aliasedSitePath(source, siteDir);
177
+ const date = await getDate();
178
+ const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
167
179
 
168
- const blogFileName = path.basename(blogSourceFile);
180
+ const title = frontMatter.title ?? contentTitle ?? parsedBlogFileName.text;
181
+ const description = frontMatter.description ?? excerpt ?? '';
169
182
 
170
- if (frontMatter.draft && process.env.NODE_ENV === 'production') {
171
- return;
172
- }
183
+ const slug = frontMatter.slug || parsedBlogFileName.slug;
173
184
 
174
- if (frontMatter.id) {
175
- console.warn(
176
- chalk.yellow(
177
- `"id" header option is deprecated in ${blogFileName} file. Please use "slug" option instead.`,
178
- ),
179
- );
180
- }
185
+ const permalink = normalizeUrl([baseUrl, routeBasePath, slug]);
181
186
 
182
- let date: Date | undefined;
183
- // Extract date and title from filename.
184
- const dateFilenameMatch = blogFileName.match(DATE_FILENAME_PATTERN);
185
- let linkName = blogFileName.replace(/\.mdx?$/, '');
187
+ function getBlogEditUrl() {
188
+ const blogPathRelative = path.relative(
189
+ blogDirPath,
190
+ path.resolve(blogSourceAbsolute),
191
+ );
186
192
 
187
- if (dateFilenameMatch) {
188
- const [, dateString, name] = dateFilenameMatch;
189
- // Always treat dates as UTC by adding the `Z`
190
- date = new Date(`${dateString}Z`);
191
- linkName = name;
193
+ if (typeof editUrl === 'function') {
194
+ return editUrl({
195
+ blogDirPath: posixPath(path.relative(siteDir, blogDirPath)),
196
+ blogPath: posixPath(blogPathRelative),
197
+ permalink,
198
+ locale: i18n.currentLocale,
199
+ });
200
+ } else if (typeof editUrl === 'string') {
201
+ const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
202
+ const fileContentPath =
203
+ isLocalized && options.editLocalizedFiles
204
+ ? contentPaths.contentPathLocalized
205
+ : contentPaths.contentPath;
206
+
207
+ const contentPathEditUrl = normalizeUrl([
208
+ editUrl,
209
+ posixPath(path.relative(siteDir, fileContentPath)),
210
+ ]);
211
+
212
+ return getEditUrl(blogPathRelative, contentPathEditUrl);
192
213
  }
214
+ return undefined;
215
+ }
193
216
 
194
- // Prefer user-defined date.
195
- if (frontMatter.date) {
196
- date = new Date(frontMatter.date);
197
- }
217
+ const tagsBasePath = normalizeUrl([
218
+ baseUrl,
219
+ routeBasePath,
220
+ tagsRouteBasePath,
221
+ ]);
222
+ const authors = getBlogPostAuthors({authorsMap, frontMatter});
223
+
224
+ return {
225
+ id: frontMatter.slug ?? title,
226
+ metadata: {
227
+ permalink,
228
+ editUrl: getBlogEditUrl(),
229
+ source: aliasedSource,
230
+ title,
231
+ description,
232
+ date,
233
+ formattedDate,
234
+ tags: normalizeFrontMatterTags(tagsBasePath, frontMatter.tags),
235
+ readingTime: showReadingTime
236
+ ? options.readingTime({
237
+ content,
238
+ frontMatter,
239
+ defaultReadingTime,
240
+ })
241
+ : undefined,
242
+ truncated: truncateMarker?.test(content) || false,
243
+ authors,
244
+ },
245
+ content,
246
+ };
247
+ }
198
248
 
199
- // Use file create time for blog.
200
- date = date ?? (await fs.stat(source)).birthtime;
201
- const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
202
-
203
- const title = frontMatter.title ?? contentTitle ?? linkName;
204
- const description = frontMatter.description ?? excerpt ?? '';
205
-
206
- const slug =
207
- frontMatter.slug ||
208
- (dateFilenameMatch ? toUrl({date, link: linkName}) : linkName);
209
-
210
- const permalink = normalizeUrl([baseUrl, routeBasePath, slug]);
211
-
212
- function getBlogEditUrl() {
213
- const blogPathRelative = path.relative(blogDirPath, path.resolve(source));
214
-
215
- if (typeof editUrl === 'function') {
216
- return editUrl({
217
- blogDirPath: posixPath(path.relative(siteDir, blogDirPath)),
218
- blogPath: posixPath(blogPathRelative),
219
- permalink,
220
- locale: i18n.currentLocale,
221
- });
222
- } else if (typeof editUrl === 'string') {
223
- const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
224
- const fileContentPath =
225
- isLocalized && options.editLocalizedFiles
226
- ? contentPaths.contentPathLocalized
227
- : contentPaths.contentPath;
228
-
229
- const contentPathEditUrl = normalizeUrl([
230
- editUrl,
231
- posixPath(path.relative(siteDir, fileContentPath)),
232
- ]);
233
-
234
- return getEditUrl(blogPathRelative, contentPathEditUrl);
235
- } else {
236
- return undefined;
237
- }
238
- }
249
+ export async function generateBlogPosts(
250
+ contentPaths: BlogContentPaths,
251
+ context: LoadContext,
252
+ options: PluginOptions,
253
+ ): Promise<BlogPost[]> {
254
+ const {include, exclude} = options;
239
255
 
240
- blogPosts.push({
241
- id: frontMatter.slug ?? title,
242
- metadata: {
243
- permalink,
244
- editUrl: getBlogEditUrl(),
245
- source: aliasedSource,
246
- title,
247
- description,
248
- date,
249
- formattedDate,
250
- tags: frontMatter.tags ?? [],
251
- readingTime: showReadingTime ? readingTime(content).minutes : undefined,
252
- truncated: truncateMarker?.test(content) || false,
253
- },
254
- });
256
+ if (!fs.existsSync(contentPaths.contentPath)) {
257
+ return [];
255
258
  }
256
259
 
257
- await Promise.all(
258
- blogSourceFiles.map(async (blogSourceFile: string) => {
259
- try {
260
- return await processBlogSourceFile(blogSourceFile);
261
- } catch (e) {
262
- console.error(
263
- chalk.red(
264
- `Processing of blog source file failed for path "${blogSourceFile}"`,
265
- ),
266
- );
267
- throw e;
268
- }
269
- }),
270
- );
260
+ const blogSourceFiles = await Globby(include, {
261
+ cwd: contentPaths.contentPath,
262
+ ignore: exclude,
263
+ });
264
+
265
+ const authorsMap = await getAuthorsMap({
266
+ contentPaths,
267
+ authorsMapPath: options.authorsMapPath,
268
+ });
269
+
270
+ const blogPosts = (
271
+ await Promise.all(
272
+ blogSourceFiles.map(async (blogSourceFile: string) => {
273
+ try {
274
+ return await processBlogSourceFile(
275
+ blogSourceFile,
276
+ contentPaths,
277
+ context,
278
+ options,
279
+ authorsMap,
280
+ );
281
+ } catch (e) {
282
+ console.error(
283
+ chalk.red(
284
+ `Processing of blog source file failed for path "${blogSourceFile}"`,
285
+ ),
286
+ );
287
+ throw e;
288
+ }
289
+ }),
290
+ )
291
+ ).filter(Boolean) as BlogPost[];
271
292
 
272
293
  blogPosts.sort(
273
294
  (a, b) => b.metadata.date.getTime() - a.metadata.date.getTime(),
package/src/feed.ts ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {Feed, Author as FeedAuthor} from 'feed';
9
+ import {PluginOptions, Author, BlogPost, FeedType} from './types';
10
+ import {normalizeUrl, mdxToHtml} from '@docusaurus/utils';
11
+ import {DocusaurusConfig} from '@docusaurus/types';
12
+ import path from 'path';
13
+ import fs from 'fs-extra';
14
+
15
+ // TODO this is temporary until we handle mdxToHtml better
16
+ // It's hard to convert reliably JSX/require calls to an html feed content
17
+ // See https://github.com/facebook/docusaurus/issues/5664
18
+ function mdxToFeedContent(mdxContent: string): string | undefined {
19
+ try {
20
+ return mdxToHtml(mdxContent);
21
+ } catch (e) {
22
+ // TODO will we need a plugin option to configure how to handle such an error
23
+ // Swallow the error on purpose for now, until we understand better the problem space
24
+ return undefined;
25
+ }
26
+ }
27
+
28
+ export async function generateBlogFeed({
29
+ blogPosts,
30
+ options,
31
+ siteConfig,
32
+ }: {
33
+ blogPosts: BlogPost[];
34
+ options: PluginOptions;
35
+ siteConfig: DocusaurusConfig;
36
+ }): Promise<Feed | null> {
37
+ if (!blogPosts.length) {
38
+ return null;
39
+ }
40
+
41
+ const {feedOptions, routeBasePath} = options;
42
+ const {url: siteUrl, baseUrl, title, favicon} = siteConfig;
43
+ const blogBaseUrl = normalizeUrl([siteUrl, baseUrl, routeBasePath]);
44
+
45
+ const updated =
46
+ (blogPosts[0] && blogPosts[0].metadata.date) ||
47
+ new Date('2015-10-25T16:29:00.000-07:00'); // weird legacy magic date
48
+
49
+ const feed = new Feed({
50
+ id: blogBaseUrl,
51
+ title: feedOptions.title || `${title} Blog`,
52
+ updated,
53
+ language: feedOptions.language,
54
+ link: blogBaseUrl,
55
+ description: feedOptions.description || `${siteConfig.title} Blog`,
56
+ favicon: favicon ? normalizeUrl([siteUrl, baseUrl, favicon]) : undefined,
57
+ copyright: feedOptions.copyright,
58
+ });
59
+
60
+ function toFeedAuthor(author: Author): FeedAuthor {
61
+ // TODO ask author emails?
62
+ // RSS feed requires email to render authors
63
+ return {name: author.name, link: author.url};
64
+ }
65
+
66
+ blogPosts.forEach((post) => {
67
+ const {
68
+ id,
69
+ metadata: {title: metadataTitle, permalink, date, description, authors},
70
+ } = post;
71
+ feed.addItem({
72
+ title: metadataTitle,
73
+ id,
74
+ link: normalizeUrl([siteUrl, permalink]),
75
+ date,
76
+ description,
77
+ content: mdxToFeedContent(post.content),
78
+ author: authors.map(toFeedAuthor),
79
+ });
80
+ });
81
+
82
+ return feed;
83
+ }
84
+
85
+ async function createBlogFeedFile({
86
+ feed,
87
+ feedType,
88
+ filePath,
89
+ }: {
90
+ feed: Feed;
91
+ feedType: FeedType;
92
+ filePath: string;
93
+ }) {
94
+ const feedContent = feedType === 'rss' ? feed.rss2() : feed.atom1();
95
+ try {
96
+ await fs.outputFile(filePath, feedContent);
97
+ } catch (err) {
98
+ throw new Error(`Generating ${feedType} feed failed: ${err}.`);
99
+ }
100
+ }
101
+
102
+ export async function createBlogFeedFiles({
103
+ blogPosts,
104
+ options,
105
+ siteConfig,
106
+ outDir,
107
+ }: {
108
+ blogPosts: BlogPost[];
109
+ options: PluginOptions;
110
+ siteConfig: DocusaurusConfig;
111
+ outDir: string;
112
+ }): Promise<void> {
113
+ const feed = await generateBlogFeed({blogPosts, options, siteConfig});
114
+
115
+ const feedTypes = options.feedOptions.type;
116
+ if (!feed || !feedTypes) {
117
+ return;
118
+ }
119
+
120
+ await Promise.all(
121
+ feedTypes.map(async function (feedType) {
122
+ await createBlogFeedFile({
123
+ feed,
124
+ feedType,
125
+ filePath: path.join(outDir, options.routeBasePath, `${feedType}.xml`),
126
+ });
127
+ }),
128
+ );
129
+ }