@docusaurus/utils 2.0.0-beta.6f366f4b4 → 2.0.0-beta.7

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.
package/src/index.ts CHANGED
@@ -23,6 +23,11 @@ import resolvePathnameUnsafe from 'resolve-pathname';
23
23
 
24
24
  import {posixPath as posixPathImport} from './posixPath';
25
25
  import {simpleHash, docuHash} from './hashUtils';
26
+ import {normalizeUrl} from './normalizeUrl';
27
+
28
+ export * from './mdxUtils';
29
+ export * from './normalizeUrl';
30
+ export * from './tags';
26
31
 
27
32
  export const posixPath = posixPathImport;
28
33
 
@@ -190,80 +195,6 @@ export function getSubFolder(file: string, refDir: string): string | null {
190
195
  return match && match[1];
191
196
  }
192
197
 
193
- export function normalizeUrl(rawUrls: string[]): string {
194
- const urls = [...rawUrls];
195
- const resultArray = [];
196
-
197
- let hasStartingSlash = false;
198
- let hasEndingSlash = false;
199
-
200
- // If the first part is a plain protocol, we combine it with the next part.
201
- if (urls[0].match(/^[^/:]+:\/*$/) && urls.length > 1) {
202
- const first = urls.shift();
203
- urls[0] = first + urls[0];
204
- }
205
-
206
- // There must be two or three slashes in the file protocol,
207
- // two slashes in anything else.
208
- const replacement = urls[0].match(/^file:\/\/\//) ? '$1:///' : '$1://';
209
- urls[0] = urls[0].replace(/^([^/:]+):\/*/, replacement);
210
-
211
- // eslint-disable-next-line
212
- for (let i = 0; i < urls.length; i++) {
213
- let component = urls[i];
214
-
215
- if (typeof component !== 'string') {
216
- throw new TypeError(`Url must be a string. Received ${typeof component}`);
217
- }
218
-
219
- if (component === '') {
220
- if (i === urls.length - 1 && hasEndingSlash) {
221
- resultArray.push('/');
222
- }
223
- // eslint-disable-next-line
224
- continue;
225
- }
226
-
227
- if (component !== '/') {
228
- if (i > 0) {
229
- // Removing the starting slashes for each component but the first.
230
- component = component.replace(
231
- /^[/]+/,
232
- // Special case where the first element of rawUrls is empty ["", "/hello"] => /hello
233
- component[0] === '/' && !hasStartingSlash ? '/' : '',
234
- );
235
- }
236
-
237
- hasEndingSlash = component[component.length - 1] === '/';
238
- // Removing the ending slashes for each component but the last.
239
- // For the last component we will combine multiple slashes to a single one.
240
- component = component.replace(/[/]+$/, i < urls.length - 1 ? '' : '/');
241
- }
242
-
243
- hasStartingSlash = true;
244
- resultArray.push(component);
245
- }
246
-
247
- let str = resultArray.join('/');
248
- // Each input component is now separated by a single slash
249
- // except the possible first plain protocol part.
250
-
251
- // Remove trailing slash before parameters or hash.
252
- str = str.replace(/\/(\?|&|#[^!])/g, '$1');
253
-
254
- // Replace ? in parameters with &.
255
- const parts = str.split('?');
256
- str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
257
-
258
- // Dedupe forward slashes in the entire path, avoiding protocol slashes.
259
- str = str.replace(/([^:]\/)\/+/g, '$1');
260
-
261
- // Dedupe forward slashes at the beginning of the path.
262
- str = str.replace(/^\/+/g, '/');
263
-
264
- return str;
265
- }
266
-
267
198
  /**
268
199
  * Alias filepath relative to site directory, very useful so that we
269
200
  * don't expose user's site structure.
@@ -497,9 +428,7 @@ export function updateTranslationFileMessages(
497
428
 
498
429
  // Input: ## Some heading {#some-heading}
499
430
  // Output: {text: "## Some heading", id: "some-heading"}
500
- export function parseMarkdownHeadingId(
501
- heading: string,
502
- ): {
431
+ export function parseMarkdownHeadingId(heading: string): {
503
432
  text: string;
504
433
  id?: string;
505
434
  } {
@@ -5,7 +5,7 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {resolve} from 'url';
8
+ import path from 'path';
9
9
  import {aliasedSitePath} from './index';
10
10
 
11
11
  export type ContentPaths = {
@@ -63,16 +63,27 @@ export function replaceMarkdownLinks<T extends ContentPaths>({
63
63
  // Replace it to correct html link.
64
64
  const mdLink = mdMatch[1];
65
65
 
66
- const aliasedSource = (source: string) =>
67
- aliasedSitePath(source, siteDir);
66
+ const sourcesToTry = [
67
+ path.resolve(path.dirname(filePath), decodeURIComponent(mdLink)),
68
+ `${contentPathLocalized}/${decodeURIComponent(mdLink)}`,
69
+ `${contentPath}/${decodeURIComponent(mdLink)}`,
70
+ ];
68
71
 
69
- const permalink: string | undefined =
70
- sourceToPermalink[aliasedSource(resolve(filePath, mdLink))] ||
71
- sourceToPermalink[aliasedSource(`${contentPathLocalized}/${mdLink}`)] ||
72
- sourceToPermalink[aliasedSource(`${contentPath}/${mdLink}`)];
72
+ const aliasedSourceMatch = sourcesToTry
73
+ .map((source) => aliasedSitePath(source, siteDir))
74
+ .find((source) => sourceToPermalink[source]);
75
+
76
+ const permalink: string | undefined = aliasedSourceMatch
77
+ ? sourceToPermalink[aliasedSourceMatch]
78
+ : undefined;
73
79
 
74
80
  if (permalink) {
75
- modifiedLine = modifiedLine.replace(mdLink, permalink);
81
+ // MDX won't be happy if the permalink contains a space, we need to convert it to %20
82
+ const encodedPermalink = permalink
83
+ .split('/')
84
+ .map((part) => part.replace(/\s/g, '%20'))
85
+ .join('/');
86
+ modifiedLine = modifiedLine.replace(mdLink, encodedPermalink);
76
87
  } else {
77
88
  const brokenMarkdownLink: BrokenMarkdownLink<T> = {
78
89
  contentPaths,
@@ -18,6 +18,7 @@ export function createExcerpt(fileString: string): string | undefined {
18
18
  // Remove Markdown alternate title
19
19
  .replace(/^[^\n]*\n[=]+/g, '')
20
20
  .split('\n');
21
+ let inCode = false;
21
22
 
22
23
  /* eslint-disable no-continue */
23
24
  // eslint-disable-next-line no-restricted-syntax
@@ -32,6 +33,14 @@ export function createExcerpt(fileString: string): string | undefined {
32
33
  continue;
33
34
  }
34
35
 
36
+ // Skip code block line.
37
+ if (fileLine.trim().startsWith('```')) {
38
+ inCode = !inCode;
39
+ continue;
40
+ } else if (inCode) {
41
+ continue;
42
+ }
43
+
35
44
  const cleanedLine = fileLine
36
45
  // Remove HTML tags.
37
46
  .replace(/<[^>]*>/g, '')
@@ -67,9 +76,7 @@ export function createExcerpt(fileString: string): string | undefined {
67
76
  return undefined;
68
77
  }
69
78
 
70
- export function parseFrontMatter(
71
- markdownFileContent: string,
72
- ): {
79
+ export function parseFrontMatter(markdownFileContent: string): {
73
80
  frontMatter: Record<string, unknown>;
74
81
  content: string;
75
82
  } {
@@ -98,10 +105,11 @@ export function parseMarkdownContentTitle(
98
105
 
99
106
  const content = contentUntrimmed.trim();
100
107
 
101
- const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/
102
- .source;
103
- const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/
104
- .source;
108
+ const IMPORT_STATEMENT =
109
+ /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/.source;
110
+ const REGULAR_TITLE =
111
+ /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/
112
+ .source;
105
113
  const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source;
106
114
 
107
115
  const regularTitleMatch = new RegExp(
@@ -141,9 +149,8 @@ export function parseMarkdownString(
141
149
  options?: {removeContentTitle?: boolean},
142
150
  ): ParsedMarkdown {
143
151
  try {
144
- const {frontMatter, content: contentWithoutFrontMatter} = parseFrontMatter(
145
- markdownFileContent,
146
- );
152
+ const {frontMatter, content: contentWithoutFrontMatter} =
153
+ parseFrontMatter(markdownFileContent);
147
154
 
148
155
  const {content, contentTitle} = parseMarkdownContentTitle(
149
156
  contentWithoutFrontMatter,
@@ -174,7 +181,7 @@ export async function parseMarkdownFile(
174
181
  const markdownString = await fs.readFile(source, 'utf-8');
175
182
  try {
176
183
  return parseMarkdownString(markdownString, options);
177
- } catch (e) {
184
+ } catch (e: any) {
178
185
  throw new Error(
179
186
  `Error while parsing Markdown file ${source}: "${e.message}".`,
180
187
  );
@@ -0,0 +1,32 @@
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 React from 'react';
9
+ import ReactDOMServer from 'react-dom/server';
10
+ import MDX from '@mdx-js/runtime';
11
+ import removeImports from 'remark-mdx-remove-imports';
12
+ import removeExports from 'remark-mdx-remove-exports';
13
+
14
+ /**
15
+ * Transform mdx text to plain html text
16
+ * Initially created to convert MDX blog posts to HTML for the RSS feed
17
+ * without import/export nodes
18
+ *
19
+ * TODO not ideal implementation, won't work well with MDX elements!
20
+ * TODO theme+global site config should be able to declare MDX comps in scope for rendering the RSS feeds
21
+ * see also https://github.com/facebook/docusaurus/issues/4625
22
+ */
23
+ export function mdxToHtml(
24
+ mdxStr: string,
25
+ // TODO allow providing components/scope here, see https://github.com/mdx-js/mdx/tree/v1.6.13/packages/runtime
26
+ ): string {
27
+ return ReactDOMServer.renderToString(
28
+ React.createElement(MDX, {remarkPlugins: [removeImports, removeExports]}, [
29
+ mdxStr,
30
+ ]),
31
+ );
32
+ }
@@ -0,0 +1,80 @@
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
+ export function normalizeUrl(rawUrls: string[]): string {
9
+ const urls = [...rawUrls];
10
+ const resultArray = [];
11
+
12
+ let hasStartingSlash = false;
13
+ let hasEndingSlash = false;
14
+
15
+ // If the first part is a plain protocol, we combine it with the next part.
16
+ if (urls[0].match(/^[^/:]+:\/*$/) && urls.length > 1) {
17
+ const first = urls.shift();
18
+ urls[0] = first + urls[0];
19
+ }
20
+
21
+ // There must be two or three slashes in the file protocol,
22
+ // two slashes in anything else.
23
+ const replacement = urls[0].match(/^file:\/\/\//) ? '$1:///' : '$1://';
24
+ urls[0] = urls[0].replace(/^([^/:]+):\/*/, replacement);
25
+
26
+ // eslint-disable-next-line
27
+ for (let i = 0; i < urls.length; i++) {
28
+ let component = urls[i];
29
+
30
+ if (typeof component !== 'string') {
31
+ throw new TypeError(`Url must be a string. Received ${typeof component}`);
32
+ }
33
+
34
+ if (component === '') {
35
+ if (i === urls.length - 1 && hasEndingSlash) {
36
+ resultArray.push('/');
37
+ }
38
+ // eslint-disable-next-line
39
+ continue;
40
+ }
41
+
42
+ if (component !== '/') {
43
+ if (i > 0) {
44
+ // Removing the starting slashes for each component but the first.
45
+ component = component.replace(
46
+ /^[/]+/,
47
+ // Special case where the first element of rawUrls is empty ["", "/hello"] => /hello
48
+ component[0] === '/' && !hasStartingSlash ? '/' : '',
49
+ );
50
+ }
51
+
52
+ hasEndingSlash = component[component.length - 1] === '/';
53
+ // Removing the ending slashes for each component but the last.
54
+ // For the last component we will combine multiple slashes to a single one.
55
+ component = component.replace(/[/]+$/, i < urls.length - 1 ? '' : '/');
56
+ }
57
+
58
+ hasStartingSlash = true;
59
+ resultArray.push(component);
60
+ }
61
+
62
+ let str = resultArray.join('/');
63
+ // Each input component is now separated by a single slash
64
+ // except the possible first plain protocol part.
65
+
66
+ // Remove trailing slash before parameters or hash.
67
+ str = str.replace(/\/(\?|&|#[^!])/g, '$1');
68
+
69
+ // Replace ? in parameters with &.
70
+ const parts = str.split('?');
71
+ str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
72
+
73
+ // Dedupe forward slashes in the entire path, avoiding protocol slashes.
74
+ str = str.replace(/([^:]\/)\/+/g, '$1');
75
+
76
+ // Dedupe forward slashes at the beginning of the path.
77
+ str = str.replace(/^\/+/g, '/');
78
+
79
+ return str;
80
+ }
package/src/tags.ts ADDED
@@ -0,0 +1,100 @@
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 {kebabCase, uniq, uniqBy} from 'lodash';
9
+ import {normalizeUrl} from './normalizeUrl';
10
+
11
+ export type Tag = {
12
+ label: string;
13
+ permalink: string;
14
+ };
15
+
16
+ export type FrontMatterTag = string | Tag;
17
+
18
+ export function normalizeFrontMatterTag(
19
+ tagsPath: string,
20
+ frontMatterTag: FrontMatterTag,
21
+ ): Tag {
22
+ function toTagObject(tagString: string): Tag {
23
+ return {
24
+ label: tagString,
25
+ permalink: kebabCase(tagString),
26
+ };
27
+ }
28
+
29
+ // TODO maybe make ensure the permalink is valid url path?
30
+ function normalizeTagPermalink(permalink: string): string {
31
+ // note: we always apply tagsPath on purpose
32
+ // for versioned docs, v1/doc.md and v2/doc.md tags with custom permalinks don't lead to the same created page
33
+ // tagsPath is different for each doc version
34
+ return normalizeUrl([tagsPath, permalink]);
35
+ }
36
+
37
+ const tag: Tag =
38
+ typeof frontMatterTag === 'string'
39
+ ? toTagObject(frontMatterTag)
40
+ : frontMatterTag;
41
+
42
+ return {
43
+ label: tag.label,
44
+ permalink: normalizeTagPermalink(tag.permalink),
45
+ };
46
+ }
47
+
48
+ export function normalizeFrontMatterTags(
49
+ tagsPath: string,
50
+ frontMatterTags: FrontMatterTag[] | undefined,
51
+ ): Tag[] {
52
+ const tags =
53
+ frontMatterTags?.map((tag) => normalizeFrontMatterTag(tagsPath, tag)) ?? [];
54
+
55
+ return uniqBy(tags, (tag) => tag.permalink);
56
+ }
57
+
58
+ export type TaggedItemGroup<Item> = {
59
+ tag: Tag;
60
+ items: Item[];
61
+ };
62
+
63
+ // Permits to group docs/blogPosts by tag (provided by FrontMatter)
64
+ // Note: groups are indexed by permalink, because routes must be unique in the end
65
+ // Labels may vary on 2 md files but they are normalized.
66
+ // Docs with label='some label' and label='some-label' should end-up in the same group/page in the end
67
+ // We can't create 2 routes /some-label because one would override the other
68
+ export function groupTaggedItems<Item>(
69
+ items: Item[],
70
+ getItemTags: (item: Item) => Tag[],
71
+ ): Record<string, TaggedItemGroup<Item>> {
72
+ const result: Record<string, TaggedItemGroup<Item>> = {};
73
+
74
+ function handleItemTag(item: Item, tag: Tag) {
75
+ // Init missing tag groups
76
+ // TODO: it's not really clear what should be the behavior if 2 items have the same tag but the permalink is different for each
77
+ // For now, the first tag found wins
78
+ result[tag.permalink] = result[tag.permalink] ?? {
79
+ tag,
80
+ items: [],
81
+ };
82
+
83
+ // Add item to group
84
+ result[tag.permalink].items.push(item);
85
+ }
86
+
87
+ items.forEach((item) => {
88
+ getItemTags(item).forEach((tag) => {
89
+ handleItemTag(item, tag);
90
+ });
91
+ });
92
+
93
+ // If user add twice the same tag to a md doc (weird but possible),
94
+ // we don't want the item to appear twice in the list...
95
+ Object.values(result).forEach((group) => {
96
+ group.items = uniq(group.items);
97
+ });
98
+
99
+ return result;
100
+ }