@docusaurus/plugin-content-blog 2.0.0-beta.1ec2c95e3 → 2.0.0-beta.21

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 (57) hide show
  1. package/lib/authors.d.ts +22 -0
  2. package/lib/authors.js +122 -0
  3. package/lib/blogUtils.d.ts +27 -7
  4. package/lib/blogUtils.js +201 -145
  5. package/lib/feed.d.ts +15 -0
  6. package/lib/feed.js +102 -0
  7. package/lib/frontMatter.d.ts +10 -0
  8. package/lib/{blogFrontMatter.js → frontMatter.js} +31 -19
  9. package/lib/index.d.ts +4 -4
  10. package/lib/index.js +166 -192
  11. package/lib/markdownLoader.d.ts +3 -6
  12. package/lib/markdownLoader.js +6 -7
  13. package/lib/options.d.ts +10 -0
  14. package/lib/{pluginOptionSchema.js → options.js} +43 -13
  15. package/lib/remark/footnoteIDFixer.d.ts +14 -0
  16. package/lib/remark/footnoteIDFixer.js +29 -0
  17. package/lib/translations.d.ts +10 -0
  18. package/lib/translations.js +53 -0
  19. package/lib/types.d.ts +4 -109
  20. package/package.json +22 -18
  21. package/src/authors.ts +168 -0
  22. package/src/blogUtils.ts +306 -204
  23. package/{types.d.ts → src/deps.d.ts} +1 -1
  24. package/src/feed.ts +171 -0
  25. package/src/frontMatter.ts +81 -0
  26. package/src/index.ts +227 -256
  27. package/src/markdownLoader.ts +11 -16
  28. package/src/{pluginOptionSchema.ts → options.ts} +56 -15
  29. package/src/plugin-content-blog.d.ts +580 -0
  30. package/src/remark/footnoteIDFixer.ts +29 -0
  31. package/src/translations.ts +69 -0
  32. package/src/types.ts +2 -128
  33. package/index.d.ts +0 -138
  34. package/lib/.tsbuildinfo +0 -1
  35. package/lib/blogFrontMatter.d.ts +0 -28
  36. package/lib/pluginOptionSchema.d.ts +0 -33
  37. package/src/__tests__/__fixtures__/website/blog/2018-12-14-Happy-First-Birthday-Slash.md +0 -5
  38. package/src/__tests__/__fixtures__/website/blog/complex-slug.md +0 -7
  39. package/src/__tests__/__fixtures__/website/blog/date-matter.md +0 -5
  40. package/src/__tests__/__fixtures__/website/blog/draft.md +0 -6
  41. package/src/__tests__/__fixtures__/website/blog/heading-as-title.md +0 -5
  42. package/src/__tests__/__fixtures__/website/blog/simple-slug.md +0 -7
  43. package/src/__tests__/__fixtures__/website/blog-with-ref/2018-12-14-Happy-First-Birthday-Slash.md +0 -5
  44. package/src/__tests__/__fixtures__/website/blog-with-ref/post-with-broken-links.md +0 -11
  45. package/src/__tests__/__fixtures__/website/blog-with-ref/post.md +0 -5
  46. package/src/__tests__/__fixtures__/website/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md +0 -5
  47. package/src/__tests__/__fixtures__/website-blog-without-date/blog/no date.md +0 -1
  48. package/src/__tests__/__snapshots__/generateBlogFeed.test.ts.snap +0 -76
  49. package/src/__tests__/__snapshots__/linkify.test.ts.snap +0 -24
  50. package/src/__tests__/__snapshots__/pluginOptionSchema.test.ts.snap +0 -5
  51. package/src/__tests__/blogFrontMatter.test.ts +0 -317
  52. package/src/__tests__/generateBlogFeed.test.ts +0 -100
  53. package/src/__tests__/index.test.ts +0 -336
  54. package/src/__tests__/linkify.test.ts +0 -93
  55. package/src/__tests__/pluginOptionSchema.test.ts +0 -150
  56. package/src/blogFrontMatter.ts +0 -88
  57. package/tsconfig.json +0 -9
@@ -0,0 +1,22 @@
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
+ import type { BlogContentPaths } from './types';
8
+ import type { Author, BlogPostFrontMatter } from '@docusaurus/plugin-content-blog';
9
+ export declare type AuthorsMap = {
10
+ [authorKey: string]: Author;
11
+ };
12
+ export declare function validateAuthorsMap(content: unknown): AuthorsMap;
13
+ export declare function getAuthorsMap(params: {
14
+ authorsMapPath: string;
15
+ contentPaths: BlogContentPaths;
16
+ }): Promise<AuthorsMap | undefined>;
17
+ declare type AuthorsParam = {
18
+ frontMatter: BlogPostFrontMatter;
19
+ authorsMap: AuthorsMap | undefined;
20
+ };
21
+ export declare function getBlogPostAuthors(params: AuthorsParam): Author[];
22
+ export {};
package/lib/authors.js ADDED
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.getBlogPostAuthors = exports.getAuthorsMap = exports.validateAuthorsMap = void 0;
10
+ const utils_1 = require("@docusaurus/utils");
11
+ const utils_validation_1 = require("@docusaurus/utils-validation");
12
+ const AuthorsMapSchema = utils_validation_1.Joi.object()
13
+ .pattern(utils_validation_1.Joi.string(), utils_validation_1.Joi.object({
14
+ name: utils_validation_1.Joi.string(),
15
+ url: utils_validation_1.URISchema,
16
+ imageURL: utils_validation_1.URISchema,
17
+ title: utils_validation_1.Joi.string(),
18
+ email: utils_validation_1.Joi.string(),
19
+ })
20
+ .rename('image_url', 'imageURL')
21
+ .or('name', 'imageURL')
22
+ .unknown()
23
+ .required()
24
+ .messages({
25
+ 'object.base': '{#label} should be an author object containing properties like name, title, and imageURL.',
26
+ 'any.required': '{#label} cannot be undefined. It should be an author object containing properties like name, title, and imageURL.',
27
+ }))
28
+ .messages({
29
+ 'object.base': "The authors map file should contain an object where each entry contains an author key and the corresponding author's data.",
30
+ });
31
+ function validateAuthorsMap(content) {
32
+ const { error, value } = AuthorsMapSchema.validate(content);
33
+ if (error) {
34
+ throw error;
35
+ }
36
+ return value;
37
+ }
38
+ exports.validateAuthorsMap = validateAuthorsMap;
39
+ async function getAuthorsMap(params) {
40
+ return (0, utils_1.getDataFileData)({
41
+ filePath: params.authorsMapPath,
42
+ contentPaths: params.contentPaths,
43
+ fileType: 'authors map',
44
+ }, validateAuthorsMap);
45
+ }
46
+ exports.getAuthorsMap = getAuthorsMap;
47
+ // Legacy v1/early-v2 front matter fields
48
+ // We may want to deprecate those in favor of using only frontMatter.authors
49
+ function getFrontMatterAuthorLegacy(frontMatter) {
50
+ const name = frontMatter.author;
51
+ const title = frontMatter.author_title ?? frontMatter.authorTitle;
52
+ const url = frontMatter.author_url ?? frontMatter.authorURL;
53
+ const imageURL = frontMatter.author_image_url ?? frontMatter.authorImageURL;
54
+ if (name || title || url || imageURL) {
55
+ return {
56
+ name,
57
+ title,
58
+ url,
59
+ imageURL,
60
+ };
61
+ }
62
+ return undefined;
63
+ }
64
+ function normalizeFrontMatterAuthors(frontMatterAuthors = []) {
65
+ function normalizeAuthor(authorInput) {
66
+ if (typeof authorInput === 'string') {
67
+ // Technically, we could allow users to provide an author's name here, but
68
+ // we only support keys, otherwise, a typo in a key would fallback to
69
+ // becoming a name and may end up unnoticed
70
+ return { key: authorInput };
71
+ }
72
+ return authorInput;
73
+ }
74
+ return Array.isArray(frontMatterAuthors)
75
+ ? frontMatterAuthors.map(normalizeAuthor)
76
+ : [normalizeAuthor(frontMatterAuthors)];
77
+ }
78
+ function getFrontMatterAuthors(params) {
79
+ const { authorsMap } = params;
80
+ const frontMatterAuthors = normalizeFrontMatterAuthors(params.frontMatter.authors);
81
+ function getAuthorsMapAuthor(key) {
82
+ if (key) {
83
+ if (!authorsMap || Object.keys(authorsMap).length === 0) {
84
+ throw new Error(`Can't reference blog post authors by a key (such as '${key}') because no authors map file could be loaded.
85
+ Please double-check your blog plugin config (in particular 'authorsMapPath'), ensure the file exists at the configured path, is not empty, and is valid!`);
86
+ }
87
+ const author = authorsMap[key];
88
+ if (!author) {
89
+ throw Error(`Blog author with key "${key}" not found in the authors map file.
90
+ Valid author keys are:
91
+ ${Object.keys(authorsMap)
92
+ .map((validKey) => `- ${validKey}`)
93
+ .join('\n')}`);
94
+ }
95
+ return author;
96
+ }
97
+ return undefined;
98
+ }
99
+ function toAuthor(frontMatterAuthor) {
100
+ return {
101
+ // Author def from authorsMap can be locally overridden by front matter
102
+ ...getAuthorsMapAuthor(frontMatterAuthor.key),
103
+ ...frontMatterAuthor,
104
+ };
105
+ }
106
+ return frontMatterAuthors.map(toAuthor);
107
+ }
108
+ function getBlogPostAuthors(params) {
109
+ const authorLegacy = getFrontMatterAuthorLegacy(params.frontMatter);
110
+ const authors = getFrontMatterAuthors(params);
111
+ if (authorLegacy) {
112
+ // Technically, we could allow mixing legacy/authors front matter, but do we
113
+ // really want to?
114
+ if (authors.length > 0) {
115
+ throw new Error(`To declare blog post authors, use the 'authors' front matter in priority.
116
+ Don't mix 'authors' with other existing 'author_*' front matter. Choose one or the other, not both at the same time.`);
117
+ }
118
+ return [authorLegacy];
119
+ }
120
+ return authors;
121
+ }
122
+ exports.getBlogPostAuthors = getBlogPostAuthors;
@@ -4,16 +4,36 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { Feed } from 'feed';
8
- import { PluginOptions, BlogPost, BlogContentPaths, BlogMarkdownLoaderOptions } from './types';
9
- import { LoadContext } from '@docusaurus/types';
7
+ import type { LoadContext } from '@docusaurus/types';
8
+ import type { PluginOptions, BlogPost, BlogTags, BlogPaginated } from '@docusaurus/plugin-content-blog';
9
+ import type { BlogContentPaths, BlogMarkdownLoaderOptions } from './types';
10
10
  export declare function truncate(fileString: string, truncateMarker: RegExp): string;
11
- export declare function getSourceToPermalink(blogPosts: BlogPost[]): Record<string, string>;
12
- export declare function generateBlogFeed(contentPaths: BlogContentPaths, context: LoadContext, options: PluginOptions): Promise<Feed | null>;
13
- export declare function generateBlogPosts(contentPaths: BlogContentPaths, { siteConfig, siteDir, i18n }: LoadContext, options: PluginOptions): Promise<BlogPost[]>;
11
+ export declare function getSourceToPermalink(blogPosts: BlogPost[]): {
12
+ [aliasedPath: string]: string;
13
+ };
14
+ export declare function paginateBlogPosts({ blogPosts, basePageUrl, blogTitle, blogDescription, postsPerPageOption, }: {
15
+ blogPosts: BlogPost[];
16
+ basePageUrl: string;
17
+ blogTitle: string;
18
+ blogDescription: string;
19
+ postsPerPageOption: number | 'ALL';
20
+ }): BlogPaginated[];
21
+ export declare function getBlogTags({ blogPosts, ...params }: {
22
+ blogPosts: BlogPost[];
23
+ blogTitle: string;
24
+ blogDescription: string;
25
+ postsPerPageOption: number | 'ALL';
26
+ }): BlogTags;
27
+ declare type ParsedBlogFileName = {
28
+ date: Date | undefined;
29
+ text: string;
30
+ slug: string;
31
+ };
32
+ export declare function parseBlogFileName(blogSourceRelative: string): ParsedBlogFileName;
33
+ export declare function generateBlogPosts(contentPaths: BlogContentPaths, context: LoadContext, options: PluginOptions): Promise<BlogPost[]>;
14
34
  export declare type LinkifyParams = {
15
35
  filePath: string;
16
36
  fileString: string;
17
37
  } & Pick<BlogMarkdownLoaderOptions, 'sourceToPermalink' | 'siteDir' | 'contentPaths' | 'onBrokenMarkdownLink'>;
18
38
  export declare function linkify({ filePath, contentPaths, fileString, siteDir, sourceToPermalink, onBrokenMarkdownLink, }: LinkifyParams): string;
19
- export declare function getContentPathList(contentPaths: BlogContentPaths): string[];
39
+ export {};
package/lib/blogUtils.js CHANGED
@@ -6,187 +6,248 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.getContentPathList = exports.linkify = exports.generateBlogPosts = exports.generateBlogFeed = exports.getSourceToPermalink = exports.truncate = void 0;
9
+ exports.linkify = exports.generateBlogPosts = exports.parseBlogFileName = exports.getBlogTags = exports.paginateBlogPosts = exports.getSourceToPermalink = exports.truncate = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
- const globby_1 = tslib_1.__importDefault(require("globby"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
14
12
  const path_1 = tslib_1.__importDefault(require("path"));
13
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
14
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
15
15
  const reading_time_1 = tslib_1.__importDefault(require("reading-time"));
16
- const feed_1 = require("feed");
17
- const lodash_1 = require("lodash");
18
16
  const utils_1 = require("@docusaurus/utils");
19
- const blogFrontMatter_1 = require("./blogFrontMatter");
17
+ const frontMatter_1 = require("./frontMatter");
18
+ const authors_1 = require("./authors");
20
19
  function truncate(fileString, truncateMarker) {
21
20
  return fileString.split(truncateMarker, 1).shift();
22
21
  }
23
22
  exports.truncate = truncate;
24
23
  function getSourceToPermalink(blogPosts) {
25
- return lodash_1.mapValues(lodash_1.keyBy(blogPosts, (item) => item.metadata.source), (v) => v.metadata.permalink);
24
+ return Object.fromEntries(blogPosts.map(({ metadata: { source, permalink } }) => [source, permalink]));
26
25
  }
27
26
  exports.getSourceToPermalink = getSourceToPermalink;
28
- // YYYY-MM-DD-{name}.mdx?
29
- // Prefer named capture, but older Node versions do not support it.
30
- const DATE_FILENAME_PATTERN = /^(\d{4}-\d{1,2}-\d{1,2})-?(.*?).mdx?$/;
31
- function toUrl({ date, link }) {
32
- return `${date
33
- .toISOString()
34
- .substring(0, '2019-01-01'.length)
35
- .replace(/-/g, '/')}/${link}`;
27
+ function paginateBlogPosts({ blogPosts, basePageUrl, blogTitle, blogDescription, postsPerPageOption, }) {
28
+ const totalCount = blogPosts.length;
29
+ const postsPerPage = postsPerPageOption === 'ALL' ? totalCount : postsPerPageOption;
30
+ const numberOfPages = Math.ceil(totalCount / postsPerPage);
31
+ const pages = [];
32
+ function permalink(page) {
33
+ return page > 0
34
+ ? (0, utils_1.normalizeUrl)([basePageUrl, `page/${page + 1}`])
35
+ : basePageUrl;
36
+ }
37
+ for (let page = 0; page < numberOfPages; page += 1) {
38
+ pages.push({
39
+ items: blogPosts
40
+ .slice(page * postsPerPage, (page + 1) * postsPerPage)
41
+ .map((item) => item.id),
42
+ metadata: {
43
+ permalink: permalink(page),
44
+ page: page + 1,
45
+ postsPerPage,
46
+ totalPages: numberOfPages,
47
+ totalCount,
48
+ previousPage: page !== 0 ? permalink(page - 1) : undefined,
49
+ nextPage: page < numberOfPages - 1 ? permalink(page + 1) : undefined,
50
+ blogDescription,
51
+ blogTitle,
52
+ },
53
+ });
54
+ }
55
+ return pages;
56
+ }
57
+ exports.paginateBlogPosts = paginateBlogPosts;
58
+ function getBlogTags({ blogPosts, ...params }) {
59
+ const groups = (0, utils_1.groupTaggedItems)(blogPosts, (blogPost) => blogPost.metadata.tags);
60
+ return lodash_1.default.mapValues(groups, ({ tag, items: tagBlogPosts }) => ({
61
+ label: tag.label,
62
+ items: tagBlogPosts.map((item) => item.id),
63
+ permalink: tag.permalink,
64
+ pages: paginateBlogPosts({
65
+ blogPosts: tagBlogPosts,
66
+ basePageUrl: tag.permalink,
67
+ ...params,
68
+ }),
69
+ }));
70
+ }
71
+ exports.getBlogTags = getBlogTags;
72
+ const DATE_FILENAME_REGEX = /^(?<folder>.*)(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(?:\/index)?.mdx?$/;
73
+ function parseBlogFileName(blogSourceRelative) {
74
+ const dateFilenameMatch = blogSourceRelative.match(DATE_FILENAME_REGEX);
75
+ if (dateFilenameMatch) {
76
+ const { folder, text, date: dateString } = dateFilenameMatch.groups;
77
+ // Always treat dates as UTC by adding the `Z`
78
+ const date = new Date(`${dateString}Z`);
79
+ const slugDate = dateString.replace(/-/g, '/');
80
+ const slug = `/${slugDate}/${folder}${text}`;
81
+ return { date, text: text, slug };
82
+ }
83
+ const text = blogSourceRelative.replace(/(?:\/index)?\.mdx?$/, '');
84
+ const slug = `/${text}`;
85
+ return { date: undefined, text, slug };
36
86
  }
37
- function formatBlogPostDate(locale, date) {
87
+ exports.parseBlogFileName = parseBlogFileName;
88
+ function formatBlogPostDate(locale, date, calendar) {
38
89
  try {
39
90
  return new Intl.DateTimeFormat(locale, {
40
91
  day: 'numeric',
41
92
  month: 'long',
42
93
  year: 'numeric',
43
94
  timeZone: 'UTC',
95
+ calendar,
44
96
  }).format(date);
45
97
  }
46
- catch (e) {
47
- throw new Error(`Can't format blog post date "${date}"`);
98
+ catch (err) {
99
+ logger_1.default.error `Can't format blog post date "${String(date)}"`;
100
+ throw err;
48
101
  }
49
102
  }
50
- async function generateBlogFeed(contentPaths, context, options) {
51
- if (!options.feedOptions) {
52
- throw new Error('Invalid options: "feedOptions" is not expected to be null.');
103
+ async function parseBlogPostMarkdownFile(blogSourceAbsolute) {
104
+ const markdownString = await fs_extra_1.default.readFile(blogSourceAbsolute, 'utf-8');
105
+ try {
106
+ const result = (0, utils_1.parseMarkdownString)(markdownString, {
107
+ removeContentTitle: true,
108
+ });
109
+ return {
110
+ ...result,
111
+ frontMatter: (0, frontMatter_1.validateBlogPostFrontMatter)(result.frontMatter),
112
+ };
53
113
  }
54
- const { siteConfig } = context;
55
- const blogPosts = await generateBlogPosts(contentPaths, context, options);
56
- if (!blogPosts.length) {
57
- return null;
114
+ catch (err) {
115
+ logger_1.default.error `Error while parsing blog post file path=${blogSourceAbsolute}.`;
116
+ throw err;
58
117
  }
59
- const { feedOptions, routeBasePath } = options;
60
- const { url: siteUrl, baseUrl, title, favicon } = siteConfig;
61
- const blogBaseUrl = utils_1.normalizeUrl([siteUrl, baseUrl, routeBasePath]);
62
- const updated = (blogPosts[0] && blogPosts[0].metadata.date) ||
63
- new Date('2015-10-25T16:29:00.000-07:00');
64
- const feed = new feed_1.Feed({
65
- id: blogBaseUrl,
66
- title: feedOptions.title || `${title} Blog`,
67
- updated,
68
- language: feedOptions.language,
69
- link: blogBaseUrl,
70
- description: feedOptions.description || `${siteConfig.title} Blog`,
71
- favicon: favicon ? utils_1.normalizeUrl([siteUrl, baseUrl, favicon]) : undefined,
72
- copyright: feedOptions.copyright,
73
- });
74
- blogPosts.forEach((post) => {
75
- const { id, metadata: { title: metadataTitle, permalink, date, description }, } = post;
76
- feed.addItem({
77
- title: metadataTitle,
78
- id,
79
- link: utils_1.normalizeUrl([siteUrl, permalink]),
80
- date,
81
- description,
82
- });
83
- });
84
- return feed;
85
118
  }
86
- exports.generateBlogFeed = generateBlogFeed;
87
- async function generateBlogPosts(contentPaths, { siteConfig, siteDir, i18n }, options) {
88
- const { include, routeBasePath, truncateMarker, showReadingTime, editUrl, } = options;
89
- if (!fs_extra_1.default.existsSync(contentPaths.contentPath)) {
90
- return [];
119
+ const defaultReadingTime = ({ content, options }) => (0, reading_time_1.default)(content, options).minutes;
120
+ async function processBlogSourceFile(blogSourceRelative, contentPaths, context, options, authorsMap) {
121
+ const { siteConfig: { baseUrl }, siteDir, i18n, } = context;
122
+ const { routeBasePath, tagsBasePath: tagsRouteBasePath, truncateMarker, showReadingTime, editUrl, } = options;
123
+ // Lookup in localized folder in priority
124
+ const blogDirPath = await (0, utils_1.getFolderContainingFile)((0, utils_1.getContentPathList)(contentPaths), blogSourceRelative);
125
+ const blogSourceAbsolute = path_1.default.join(blogDirPath, blogSourceRelative);
126
+ const { frontMatter, content, contentTitle, excerpt } = await parseBlogPostMarkdownFile(blogSourceAbsolute);
127
+ const aliasedSource = (0, utils_1.aliasedSitePath)(blogSourceAbsolute, siteDir);
128
+ if (frontMatter.draft && process.env.NODE_ENV === 'production') {
129
+ return undefined;
91
130
  }
92
- const { baseUrl = '' } = siteConfig;
93
- const blogSourceFiles = await globby_1.default(include, {
94
- cwd: contentPaths.contentPath,
95
- });
96
- const blogPosts = [];
97
- async function processBlogSourceFile(blogSourceFile) {
98
- var _a, _b, _c, _d, _e, _f;
99
- // Lookup in localized folder in priority
100
- const blogDirPath = await utils_1.getFolderContainingFile(getContentPathList(contentPaths), blogSourceFile);
101
- const source = path_1.default.join(blogDirPath, blogSourceFile);
102
- const { frontMatter: unsafeFrontMatter, content, contentTitle, excerpt, } = await utils_1.parseMarkdownFile(source, { removeContentTitle: true });
103
- const frontMatter = blogFrontMatter_1.validateBlogPostFrontMatter(unsafeFrontMatter);
104
- const aliasedSource = utils_1.aliasedSitePath(source, siteDir);
105
- const blogFileName = path_1.default.basename(blogSourceFile);
106
- if (frontMatter.draft && process.env.NODE_ENV === 'production') {
107
- return;
108
- }
109
- if (frontMatter.id) {
110
- console.warn(chalk_1.default.yellow(`"id" header option is deprecated in ${blogFileName} file. Please use "slug" option instead.`));
111
- }
112
- let date;
113
- // Extract date and title from filename.
114
- const dateFilenameMatch = blogFileName.match(DATE_FILENAME_PATTERN);
115
- let linkName = blogFileName.replace(/\.mdx?$/, '');
116
- if (dateFilenameMatch) {
117
- const [, dateString, name] = dateFilenameMatch;
118
- // Always treat dates as UTC by adding the `Z`
119
- date = new Date(`${dateString}Z`);
120
- linkName = name;
121
- }
131
+ if (frontMatter.id) {
132
+ logger_1.default.warn `name=${'id'} header option is deprecated in path=${blogSourceRelative} file. Please use name=${'slug'} option instead.`;
133
+ }
134
+ const parsedBlogFileName = parseBlogFileName(blogSourceRelative);
135
+ async function getDate() {
122
136
  // Prefer user-defined date.
123
137
  if (frontMatter.date) {
124
- date = frontMatter.date;
125
- }
126
- // Use file create time for blog.
127
- date = date !== null && date !== void 0 ? date : (await fs_extra_1.default.stat(source)).birthtime;
128
- const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
129
- const title = (_b = (_a = frontMatter.title) !== null && _a !== void 0 ? _a : contentTitle) !== null && _b !== void 0 ? _b : linkName;
130
- const description = (_d = (_c = frontMatter.description) !== null && _c !== void 0 ? _c : excerpt) !== null && _d !== void 0 ? _d : '';
131
- const slug = frontMatter.slug ||
132
- (dateFilenameMatch ? toUrl({ date, link: linkName }) : linkName);
133
- const permalink = utils_1.normalizeUrl([baseUrl, routeBasePath, slug]);
134
- function getBlogEditUrl() {
135
- const blogPathRelative = path_1.default.relative(blogDirPath, path_1.default.resolve(source));
136
- if (typeof editUrl === 'function') {
137
- return editUrl({
138
- blogDirPath: utils_1.posixPath(path_1.default.relative(siteDir, blogDirPath)),
139
- blogPath: utils_1.posixPath(blogPathRelative),
140
- permalink,
141
- locale: i18n.currentLocale,
142
- });
143
- }
144
- else if (typeof editUrl === 'string') {
145
- const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
146
- const fileContentPath = isLocalized && options.editLocalizedFiles
147
- ? contentPaths.contentPathLocalized
148
- : contentPaths.contentPath;
149
- const contentPathEditUrl = utils_1.normalizeUrl([
150
- editUrl,
151
- utils_1.posixPath(path_1.default.relative(siteDir, fileContentPath)),
152
- ]);
153
- return utils_1.getEditUrl(blogPathRelative, contentPathEditUrl);
154
- }
155
- else {
156
- return undefined;
138
+ if (typeof frontMatter.date === 'string') {
139
+ // Always treat dates as UTC by adding the `Z`
140
+ return new Date(`${frontMatter.date}Z`);
157
141
  }
142
+ // YAML only converts YYYY-MM-DD to dates and leaves others as strings.
143
+ return frontMatter.date;
158
144
  }
159
- blogPosts.push({
160
- id: (_e = frontMatter.slug) !== null && _e !== void 0 ? _e : title,
161
- metadata: {
145
+ else if (parsedBlogFileName.date) {
146
+ return parsedBlogFileName.date;
147
+ }
148
+ try {
149
+ const result = (0, utils_1.getFileCommitDate)(blogSourceAbsolute, {
150
+ age: 'oldest',
151
+ includeAuthor: false,
152
+ });
153
+ return result.date;
154
+ }
155
+ catch (err) {
156
+ logger_1.default.warn(err);
157
+ return (await fs_extra_1.default.stat(blogSourceAbsolute)).birthtime;
158
+ }
159
+ }
160
+ const date = await getDate();
161
+ const formattedDate = formatBlogPostDate(i18n.currentLocale, date, i18n.localeConfigs[i18n.currentLocale].calendar);
162
+ const title = frontMatter.title ?? contentTitle ?? parsedBlogFileName.text;
163
+ const description = frontMatter.description ?? excerpt ?? '';
164
+ const slug = frontMatter.slug ?? parsedBlogFileName.slug;
165
+ const permalink = (0, utils_1.normalizeUrl)([baseUrl, routeBasePath, slug]);
166
+ function getBlogEditUrl() {
167
+ const blogPathRelative = path_1.default.relative(blogDirPath, path_1.default.resolve(blogSourceAbsolute));
168
+ if (typeof editUrl === 'function') {
169
+ return editUrl({
170
+ blogDirPath: (0, utils_1.posixPath)(path_1.default.relative(siteDir, blogDirPath)),
171
+ blogPath: (0, utils_1.posixPath)(blogPathRelative),
162
172
  permalink,
163
- editUrl: getBlogEditUrl(),
164
- source: aliasedSource,
165
- title,
166
- description,
167
- date,
168
- formattedDate,
169
- tags: (_f = frontMatter.tags) !== null && _f !== void 0 ? _f : [],
170
- readingTime: showReadingTime ? reading_time_1.default(content).minutes : undefined,
171
- truncated: (truncateMarker === null || truncateMarker === void 0 ? void 0 : truncateMarker.test(content)) || false,
172
- },
173
- });
173
+ locale: i18n.currentLocale,
174
+ });
175
+ }
176
+ else if (typeof editUrl === 'string') {
177
+ const isLocalized = blogDirPath === contentPaths.contentPathLocalized;
178
+ const fileContentPath = isLocalized && options.editLocalizedFiles
179
+ ? contentPaths.contentPathLocalized
180
+ : contentPaths.contentPath;
181
+ const contentPathEditUrl = (0, utils_1.normalizeUrl)([
182
+ editUrl,
183
+ (0, utils_1.posixPath)(path_1.default.relative(siteDir, fileContentPath)),
184
+ ]);
185
+ return (0, utils_1.getEditUrl)(blogPathRelative, contentPathEditUrl);
186
+ }
187
+ return undefined;
174
188
  }
175
- await Promise.all(blogSourceFiles.map(async (blogSourceFile) => {
189
+ const tagsBasePath = (0, utils_1.normalizeUrl)([
190
+ baseUrl,
191
+ routeBasePath,
192
+ tagsRouteBasePath,
193
+ ]);
194
+ const authors = (0, authors_1.getBlogPostAuthors)({ authorsMap, frontMatter });
195
+ return {
196
+ id: slug,
197
+ metadata: {
198
+ permalink,
199
+ editUrl: getBlogEditUrl(),
200
+ source: aliasedSource,
201
+ title,
202
+ description,
203
+ date,
204
+ formattedDate,
205
+ tags: (0, utils_1.normalizeFrontMatterTags)(tagsBasePath, frontMatter.tags),
206
+ readingTime: showReadingTime
207
+ ? options.readingTime({
208
+ content,
209
+ frontMatter,
210
+ defaultReadingTime,
211
+ })
212
+ : undefined,
213
+ truncated: truncateMarker.test(content),
214
+ authors,
215
+ frontMatter,
216
+ },
217
+ content,
218
+ };
219
+ }
220
+ async function generateBlogPosts(contentPaths, context, options) {
221
+ const { include, exclude } = options;
222
+ if (!(await fs_extra_1.default.pathExists(contentPaths.contentPath))) {
223
+ return [];
224
+ }
225
+ const blogSourceFiles = await (0, utils_1.Globby)(include, {
226
+ cwd: contentPaths.contentPath,
227
+ ignore: exclude,
228
+ });
229
+ const authorsMap = await (0, authors_1.getAuthorsMap)({
230
+ contentPaths,
231
+ authorsMapPath: options.authorsMapPath,
232
+ });
233
+ const blogPosts = (await Promise.all(blogSourceFiles.map(async (blogSourceFile) => {
176
234
  try {
177
- return await processBlogSourceFile(blogSourceFile);
235
+ return await processBlogSourceFile(blogSourceFile, contentPaths, context, options, authorsMap);
178
236
  }
179
- catch (e) {
180
- console.error(chalk_1.default.red(`Processing of blog source file failed for path "${blogSourceFile}"`));
181
- throw e;
237
+ catch (err) {
238
+ logger_1.default.error `Processing of blog source file path=${blogSourceFile} failed.`;
239
+ throw err;
182
240
  }
183
- }));
241
+ }))).filter(Boolean);
184
242
  blogPosts.sort((a, b) => b.metadata.date.getTime() - a.metadata.date.getTime());
243
+ if (options.sortPosts === 'ascending') {
244
+ return blogPosts.reverse();
245
+ }
185
246
  return blogPosts;
186
247
  }
187
248
  exports.generateBlogPosts = generateBlogPosts;
188
249
  function linkify({ filePath, contentPaths, fileString, siteDir, sourceToPermalink, onBrokenMarkdownLink, }) {
189
- const { newContent, brokenMarkdownLinks } = utils_1.replaceMarkdownLinks({
250
+ const { newContent, brokenMarkdownLinks } = (0, utils_1.replaceMarkdownLinks)({
190
251
  siteDir,
191
252
  fileString,
192
253
  filePath,
@@ -197,8 +258,3 @@ function linkify({ filePath, contentPaths, fileString, siteDir, sourceToPermalin
197
258
  return newContent;
198
259
  }
199
260
  exports.linkify = linkify;
200
- // Order matters: we look in priority in localized folder
201
- function getContentPathList(contentPaths) {
202
- return [contentPaths.contentPathLocalized, contentPaths.contentPath];
203
- }
204
- exports.getContentPathList = getContentPathList;
package/lib/feed.d.ts ADDED
@@ -0,0 +1,15 @@
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
+ import type { DocusaurusConfig } from '@docusaurus/types';
8
+ import type { PluginOptions, BlogPost } from '@docusaurus/plugin-content-blog';
9
+ export declare function createBlogFeedFiles({ blogPosts, options, siteConfig, outDir, locale, }: {
10
+ blogPosts: BlogPost[];
11
+ options: PluginOptions;
12
+ siteConfig: DocusaurusConfig;
13
+ outDir: string;
14
+ locale: string;
15
+ }): Promise<void>;