@docusaurus/mdx-loader 2.0.0-beta.12faed89d → 2.0.0-beta.13

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 (58) hide show
  1. package/lib/.tsbuildinfo +1 -0
  2. package/lib/index.d.ts +23 -0
  3. package/lib/index.js +167 -0
  4. package/lib/remark/headings/index.d.ts +9 -0
  5. package/lib/remark/headings/index.js +60 -0
  6. package/lib/remark/toc/index.d.ts +12 -0
  7. package/lib/remark/toc/index.js +67 -0
  8. package/lib/remark/toc/search.d.ts +13 -0
  9. package/lib/remark/toc/search.js +66 -0
  10. package/lib/remark/transformImage/index.d.ts +13 -0
  11. package/lib/remark/transformImage/index.js +90 -0
  12. package/lib/remark/transformLinks/index.d.ts +14 -0
  13. package/lib/remark/transformLinks/index.js +106 -0
  14. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts +9 -0
  15. package/lib/remark/unwrapMdxCodeBlocks/index.js +28 -0
  16. package/lib/remark/utils/index.d.ts +10 -0
  17. package/lib/remark/utils/index.js +39 -0
  18. package/package.json +16 -12
  19. package/src/deps.d.ts +29 -0
  20. package/src/index.ts +216 -0
  21. package/src/{index.d.ts → mdx-loader.d.ts} +7 -8
  22. package/src/remark/headings/__tests__/{index.test.js → index.test.ts} +0 -2
  23. package/src/remark/headings/{index.js → index.ts} +21 -16
  24. package/src/remark/toc/__tests__/__snapshots__/{index.test.js.snap → index.test.ts.snap} +20 -10
  25. package/src/remark/toc/__tests__/{index.test.js → index.test.ts} +29 -15
  26. package/src/remark/toc/__tests__/search.test.ts +182 -0
  27. package/src/remark/toc/{index.js → index.ts} +24 -16
  28. package/src/remark/toc/search.ts +82 -0
  29. package/src/remark/transformImage/__tests__/{fixtures → __fixtures__}/fail.md +0 -0
  30. package/src/remark/transformImage/__tests__/__fixtures__/img.md +19 -0
  31. package/src/remark/transformImage/__tests__/{fixtures → __fixtures__}/noUrl.md +0 -0
  32. package/src/remark/transformImage/__tests__/{fixtures → __fixtures__}/pathname.md +0 -0
  33. package/src/remark/transformImage/__tests__/{fixtures → __fixtures__/static}/img.png +0 -0
  34. package/src/remark/{transformLinks/__tests__/fixtures/asset.pdf → transformImage/__tests__/__fixtures__/static2/img2.png} +0 -0
  35. package/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap +33 -0
  36. package/src/remark/transformImage/__tests__/{index.test.js → index.test.ts} +23 -19
  37. package/src/remark/transformImage/{index.js → index.ts} +52 -24
  38. package/src/remark/transformLinks/__tests__/{fixtures → __fixtures__}/asset.md +6 -0
  39. package/src/remark/transformLinks/__tests__/{fixtures/static/staticAsset.pdf → __fixtures__/asset.pdf} +0 -0
  40. package/src/remark/transformLinks/__tests__/{fixtures → __fixtures__}/noUrl.md +0 -0
  41. package/src/remark/transformLinks/__tests__/{fixtures → __fixtures__}/pathname.md +0 -0
  42. package/src/remark/transformLinks/__tests__/__fixtures__/static/staticAsset.pdf +0 -0
  43. package/src/remark/transformLinks/__tests__/{fixtures → __fixtures__}/static/staticAssetImage.png +0 -0
  44. package/src/remark/transformLinks/__tests__/__fixtures__/static2/asset2.pdf +0 -0
  45. package/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap +47 -0
  46. package/src/remark/transformLinks/__tests__/{index.test.js → index.test.ts} +19 -8
  47. package/src/remark/transformLinks/{index.js → index.ts} +66 -44
  48. package/src/remark/unwrapMdxCodeBlocks/__tests__/__snapshots__/{index.test.js.snap → index.test.ts.snap} +0 -0
  49. package/src/remark/unwrapMdxCodeBlocks/__tests__/{index.test.js → index.test.ts} +0 -0
  50. package/src/remark/unwrapMdxCodeBlocks/{index.js → index.ts} +11 -9
  51. package/src/remark/utils/index.ts +39 -0
  52. package/tsconfig.json +5 -5
  53. package/src/index.js +0 -107
  54. package/src/remark/toc/search.js +0 -73
  55. package/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap +0 -31
  56. package/src/remark/transformImage/__tests__/fixtures/img.md +0 -17
  57. package/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap +0 -41
  58. package/src/remark/utils/index.js +0 -39
@@ -0,0 +1,13 @@
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 { Plugin } from 'unified';
8
+ interface PluginOptions {
9
+ filePath: string;
10
+ staticDirs: string[];
11
+ }
12
+ declare const plugin: Plugin<[PluginOptions]>;
13
+ export default plugin;
@@ -0,0 +1,90 @@
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
+ const tslib_1 = require("tslib");
10
+ const unist_util_visit_1 = (0, tslib_1.__importDefault)(require("unist-util-visit"));
11
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
12
+ const url_1 = (0, tslib_1.__importDefault)(require("url"));
13
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
14
+ const escape_html_1 = (0, tslib_1.__importDefault)(require("escape-html"));
15
+ const utils_1 = require("@docusaurus/utils");
16
+ const { loaders: { inlineMarkdownImageFileLoader }, } = (0, utils_1.getFileLoaderUtils)();
17
+ const createJSX = (node, pathUrl) => {
18
+ const jsxNode = node;
19
+ jsxNode.type = 'jsx';
20
+ jsxNode.value = `<img ${node.alt ? `alt={"${(0, escape_html_1.default)(node.alt)}"} ` : ''}${node.url
21
+ ? `src={require("${inlineMarkdownImageFileLoader}${(0, utils_1.escapePath)(pathUrl)}").default}`
22
+ : ''}${node.title ? ` title="${(0, escape_html_1.default)(node.title)}"` : ''} />`;
23
+ if (jsxNode.url) {
24
+ delete jsxNode.url;
25
+ }
26
+ if (jsxNode.alt) {
27
+ delete jsxNode.alt;
28
+ }
29
+ if (jsxNode.title) {
30
+ delete jsxNode.title;
31
+ }
32
+ };
33
+ async function ensureImageFileExist(imagePath, sourceFilePath) {
34
+ const imageExists = await fs_extra_1.default.pathExists(imagePath);
35
+ if (!imageExists) {
36
+ throw new Error(`Image ${(0, utils_1.toMessageRelativeFilePath)(imagePath)} used in ${(0, utils_1.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
37
+ }
38
+ }
39
+ async function findImage(possiblePaths, sourceFilePath) {
40
+ // eslint-disable-next-line no-restricted-syntax
41
+ for (const possiblePath of possiblePaths) {
42
+ if (await fs_extra_1.default.pathExists(possiblePath)) {
43
+ return possiblePath;
44
+ }
45
+ }
46
+ throw new Error(`Image ${possiblePaths
47
+ .map((p) => (0, utils_1.toMessageRelativeFilePath)(p))
48
+ .join(' or ')} used in ${(0, utils_1.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
49
+ }
50
+ async function processImageNode(node, { filePath, staticDirs }) {
51
+ if (!node.url) {
52
+ throw new Error(`Markdown image URL is mandatory in "${(0, utils_1.toMessageRelativeFilePath)(filePath)}" file`);
53
+ }
54
+ const parsedUrl = url_1.default.parse(node.url);
55
+ if (parsedUrl.protocol) {
56
+ // pathname:// is an escape hatch,
57
+ // in case user does not want his images to be converted to require calls going through webpack loader
58
+ // we don't have to document this for now,
59
+ // it's mostly to make next release less risky (2.0.0-alpha.59)
60
+ if (parsedUrl.protocol === 'pathname:') {
61
+ node.url = node.url.replace('pathname://', '');
62
+ }
63
+ }
64
+ // images without protocol
65
+ else if (path_1.default.isAbsolute(node.url)) {
66
+ // absolute paths are expected to exist in the static folder
67
+ const possibleImagePaths = staticDirs.map((dir) => path_1.default.join(dir, node.url));
68
+ const imagePath = await findImage(possibleImagePaths, filePath);
69
+ createJSX(node, (0, utils_1.posixPath)(imagePath));
70
+ }
71
+ // We try to convert image urls without protocol to images with require calls
72
+ // going through webpack ensures that image assets exist at build time
73
+ else {
74
+ // relative paths are resolved against the source file's folder
75
+ const expectedImagePath = path_1.default.join(path_1.default.dirname(filePath), node.url);
76
+ await ensureImageFileExist(expectedImagePath, filePath);
77
+ createJSX(node, node.url.startsWith('./') ? node.url : `./${node.url}`);
78
+ }
79
+ }
80
+ const plugin = (options) => {
81
+ const transformer = async (root) => {
82
+ const promises = [];
83
+ (0, unist_util_visit_1.default)(root, 'image', (node) => {
84
+ promises.push(processImageNode(node, options));
85
+ });
86
+ await Promise.all(promises);
87
+ };
88
+ return transformer;
89
+ };
90
+ exports.default = plugin;
@@ -0,0 +1,14 @@
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 { Plugin } from 'unified';
8
+ interface PluginOptions {
9
+ filePath: string;
10
+ staticDirs: string[];
11
+ siteDir: string;
12
+ }
13
+ declare const plugin: Plugin<[PluginOptions]>;
14
+ export default plugin;
@@ -0,0 +1,106 @@
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
+ const tslib_1 = require("tslib");
10
+ const utils_1 = require("@docusaurus/utils");
11
+ const unist_util_visit_1 = (0, tslib_1.__importDefault)(require("unist-util-visit"));
12
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
13
+ const url_1 = (0, tslib_1.__importDefault)(require("url"));
14
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
15
+ const escape_html_1 = (0, tslib_1.__importDefault)(require("escape-html"));
16
+ const utils_2 = require("../utils");
17
+ const { loaders: { inlineMarkdownLinkFileLoader }, } = (0, utils_1.getFileLoaderUtils)();
18
+ const hashRegex = /#.*$/;
19
+ async function ensureAssetFileExist(fileSystemAssetPath, sourceFilePath) {
20
+ const assetExists = await fs_extra_1.default.pathExists(fileSystemAssetPath);
21
+ if (!assetExists) {
22
+ throw new Error(`Asset ${(0, utils_1.toMessageRelativeFilePath)(fileSystemAssetPath)} used in ${(0, utils_1.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
23
+ }
24
+ }
25
+ // transform the link node to a jsx link with a require() call
26
+ function toAssetRequireNode({ node, filePath, requireAssetPath, }) {
27
+ let relativeRequireAssetPath = (0, utils_1.posixPath)(path_1.default.relative(path_1.default.dirname(filePath), requireAssetPath));
28
+ const hash = hashRegex.test(node.url)
29
+ ? node.url.substr(node.url.indexOf('#'))
30
+ : '';
31
+ // nodejs does not like require("assets/file.pdf")
32
+ relativeRequireAssetPath = relativeRequireAssetPath.startsWith('.')
33
+ ? relativeRequireAssetPath
34
+ : `./${relativeRequireAssetPath}`;
35
+ const href = `require('${inlineMarkdownLinkFileLoader}${(0, utils_1.escapePath)(relativeRequireAssetPath)}').default${hash ? ` + '${hash}'` : ''}`;
36
+ const children = (0, utils_2.stringifyContent)(node);
37
+ const title = node.title ? ` title="${(0, escape_html_1.default)(node.title)}"` : '';
38
+ node.type = 'jsx';
39
+ node.value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
40
+ }
41
+ // If the link looks like an asset link, we'll link to the asset,
42
+ // and use a require("assetUrl") (using webpack url-loader/file-loader)
43
+ // instead of navigating to such link
44
+ async function convertToAssetLinkIfNeeded(node, { filePath, siteDir, staticDirs }) {
45
+ const assetPath = node.url.replace(hashRegex, '');
46
+ const hasSiteAlias = assetPath.startsWith('@site/');
47
+ const hasAssetLikeExtension = path_1.default.extname(assetPath) && !assetPath.match(/#|.md|.mdx|.html/);
48
+ const looksLikeAssetLink = hasSiteAlias || hasAssetLikeExtension;
49
+ if (!looksLikeAssetLink) {
50
+ return;
51
+ }
52
+ function toAssetLinkNode(requireAssetPath) {
53
+ toAssetRequireNode({
54
+ node,
55
+ filePath,
56
+ requireAssetPath,
57
+ });
58
+ }
59
+ if (assetPath.startsWith('@site/')) {
60
+ const fileSystemAssetPath = path_1.default.join(siteDir, assetPath.replace('@site/', ''));
61
+ await ensureAssetFileExist(fileSystemAssetPath, filePath);
62
+ toAssetLinkNode(fileSystemAssetPath);
63
+ }
64
+ else if (path_1.default.isAbsolute(assetPath)) {
65
+ // eslint-disable-next-line no-restricted-syntax
66
+ for (const staticDir of staticDirs) {
67
+ const fileSystemAssetPath = path_1.default.join(staticDir, assetPath);
68
+ if (await fs_extra_1.default.pathExists(fileSystemAssetPath)) {
69
+ toAssetLinkNode(fileSystemAssetPath);
70
+ return;
71
+ }
72
+ }
73
+ }
74
+ else {
75
+ const fileSystemAssetPath = path_1.default.join(path_1.default.dirname(filePath), assetPath);
76
+ if (await fs_extra_1.default.pathExists(fileSystemAssetPath)) {
77
+ toAssetLinkNode(fileSystemAssetPath);
78
+ }
79
+ }
80
+ }
81
+ async function processLinkNode(node, options) {
82
+ var _a, _b, _c;
83
+ if (!node.url) {
84
+ // try to improve error feedback
85
+ // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
86
+ const title = node.title || ((_a = node.children[0]) === null || _a === void 0 ? void 0 : _a.value) || '?';
87
+ const line = ((_c = (_b = node === null || node === void 0 ? void 0 : node.position) === null || _b === void 0 ? void 0 : _b.start) === null || _c === void 0 ? void 0 : _c.line) || '?';
88
+ throw new Error(`Markdown link URL is mandatory in "${(0, utils_1.toMessageRelativeFilePath)(options.filePath)}" file (title: ${title}, line: ${line}).`);
89
+ }
90
+ const parsedUrl = url_1.default.parse(node.url);
91
+ if (parsedUrl.protocol) {
92
+ return;
93
+ }
94
+ await convertToAssetLinkIfNeeded(node, options);
95
+ }
96
+ const plugin = (options) => {
97
+ const transformer = async (root) => {
98
+ const promises = [];
99
+ (0, unist_util_visit_1.default)(root, 'link', (node) => {
100
+ promises.push(processLinkNode(node, options));
101
+ });
102
+ await Promise.all(promises);
103
+ };
104
+ return transformer;
105
+ };
106
+ exports.default = plugin;
@@ -0,0 +1,9 @@
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 { Transformer, Processor } from 'unified';
8
+ declare function plugin(this: Processor): Transformer;
9
+ export default plugin;
@@ -0,0 +1,28 @@
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
+ const tslib_1 = require("tslib");
10
+ const unist_util_visit_1 = (0, tslib_1.__importDefault)(require("unist-util-visit"));
11
+ // This plugin is mostly to help integrating Docusaurus with translation systems
12
+ // that do not support well MDX embedded JSX syntax (like Crowdin)
13
+ // We wrap the JSX syntax in code blocks so that translation tools don't mess-up with the markup
14
+ // But the JSX inside such code blocks should still be evaluated as JSX
15
+ // See https://github.com/facebook/docusaurus/pull/4278
16
+ function plugin() {
17
+ const transformer = (root) => {
18
+ (0, unist_util_visit_1.default)(root, 'code', (node, _index, parent) => {
19
+ if (node.lang === 'mdx-code-block') {
20
+ const newChildren = this.parse(node.value).children;
21
+ // Replace the mdx code block by its content, parsed
22
+ parent.children.splice(parent.children.indexOf(node), 1, ...newChildren);
23
+ }
24
+ });
25
+ };
26
+ return transformer;
27
+ }
28
+ exports.default = plugin;
@@ -0,0 +1,10 @@
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 { Parent } from 'unist';
8
+ import type { StaticPhrasingContent, Heading } from 'mdast';
9
+ export declare function stringifyContent(node: Parent): string;
10
+ export declare function toValue(node: StaticPhrasingContent | Heading): string;
@@ -0,0 +1,39 @@
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.toValue = exports.stringifyContent = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const escape_html_1 = (0, tslib_1.__importDefault)(require("escape-html"));
12
+ const mdast_util_to_string_1 = (0, tslib_1.__importDefault)(require("mdast-util-to-string"));
13
+ function stringifyContent(node) {
14
+ return (node.children || [])
15
+ .map(toValue)
16
+ .join('');
17
+ }
18
+ exports.stringifyContent = stringifyContent;
19
+ function toValue(node) {
20
+ if (node && node.type) {
21
+ switch (node.type) {
22
+ case 'text':
23
+ return (0, escape_html_1.default)(node.value);
24
+ case 'heading':
25
+ return stringifyContent(node);
26
+ case 'inlineCode':
27
+ return `<code>${(0, escape_html_1.default)(node.value)}</code>`;
28
+ case 'emphasis':
29
+ return `<em>${stringifyContent(node)}</em>`;
30
+ case 'strong':
31
+ return `<strong>${stringifyContent(node)}</strong>`;
32
+ case 'delete':
33
+ return `<del>${stringifyContent(node)}</del>`;
34
+ default:
35
+ }
36
+ }
37
+ return (0, mdast_util_to_string_1.default)(node);
38
+ }
39
+ exports.toValue = toValue;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@docusaurus/mdx-loader",
3
- "version": "2.0.0-beta.12faed89d",
3
+ "version": "2.0.0-beta.13",
4
4
  "description": "Docusaurus Loader for MDX",
5
- "main": "src/index.js",
6
- "types": "src/index.d.ts",
5
+ "main": "lib/index.js",
6
+ "types": "src/mdx-loader.d.ts",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
@@ -18,26 +18,30 @@
18
18
  },
19
19
  "license": "MIT",
20
20
  "dependencies": {
21
- "@babel/parser": "^7.12.16",
22
- "@babel/traverse": "^7.12.13",
23
- "@docusaurus/core": "2.0.0-beta.12faed89d",
24
- "@docusaurus/utils": "2.0.0-beta.12faed89d",
21
+ "@babel/parser": "^7.16.4",
22
+ "@babel/traverse": "^7.16.3",
23
+ "@docusaurus/utils": "2.0.0-beta.13",
25
24
  "@mdx-js/mdx": "^1.6.21",
26
25
  "@mdx-js/react": "^1.6.21",
26
+ "chalk": "^4.1.2",
27
27
  "escape-html": "^1.0.3",
28
28
  "file-loader": "^6.2.0",
29
29
  "fs-extra": "^10.0.0",
30
- "github-slugger": "^1.3.0",
31
30
  "gray-matter": "^4.0.3",
32
31
  "mdast-util-to-string": "^2.0.0",
33
32
  "remark-emoji": "^2.1.0",
34
33
  "stringify-object": "^3.3.0",
34
+ "tslib": "^2.3.1",
35
35
  "unist-util-visit": "^2.0.2",
36
36
  "url-loader": "^4.1.1",
37
- "webpack": "^5.40.0"
37
+ "webpack": "^5.61.0"
38
38
  },
39
39
  "devDependencies": {
40
- "@docusaurus/types": "2.0.0-beta.12faed89d",
40
+ "@docusaurus/types": "2.0.0-beta.13",
41
+ "@types/escape-html": "^1.0.1",
42
+ "@types/mdast": "^3.0.7",
43
+ "@types/stringify-object": "^3.3.1",
44
+ "@types/unist": "^2.0.6",
41
45
  "remark": "^12.0.0",
42
46
  "remark-mdx": "^1.6.21",
43
47
  "to-vfile": "^6.0.0",
@@ -49,7 +53,7 @@
49
53
  "react-dom": "^16.8.4 || ^17.0.0"
50
54
  },
51
55
  "engines": {
52
- "node": ">=12.13.0"
56
+ "node": ">=14"
53
57
  },
54
- "gitHead": "1430dbacfbe9da59a17ce395ed29bdbddaf90049"
58
+ "gitHead": "b6ca12aedf10a10c2375f4f8b7e7380cfd7c7202"
55
59
  }
package/src/deps.d.ts ADDED
@@ -0,0 +1,29 @@
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
+ // TODO Types provided by MDX 2.0 https://github.com/mdx-js/mdx/blob/main/packages/mdx/types/index.d.ts
9
+ declare module '@mdx-js/mdx' {
10
+ import type {Processor} from 'unified';
11
+ import type {RemarkOrRehypePlugin} from '@docusaurus/mdx-loader';
12
+
13
+ namespace mdx {
14
+ interface Options {
15
+ filepath?: string;
16
+ skipExport?: boolean;
17
+ wrapExport?: string;
18
+ remarkPlugins?: RemarkOrRehypePlugin[];
19
+ rehypePlugins?: RemarkOrRehypePlugin[];
20
+ }
21
+
22
+ function sync(content: string, options?: Options): string;
23
+ function createMdxAstCompiler(options?: Options): Processor;
24
+ function createCompiler(options?: Options): Processor;
25
+ }
26
+ function mdx(content: string, options?: mdx.Options): Promise<string>;
27
+
28
+ export default mdx;
29
+ }
package/src/index.ts ADDED
@@ -0,0 +1,216 @@
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 {readFile} from 'fs-extra';
9
+ import mdx from '@mdx-js/mdx';
10
+ import chalk from 'chalk';
11
+ import emoji from 'remark-emoji';
12
+ import {
13
+ parseFrontMatter,
14
+ parseMarkdownContentTitle,
15
+ escapePath,
16
+ getFileLoaderUtils,
17
+ } from '@docusaurus/utils';
18
+ import stringifyObject from 'stringify-object';
19
+ import headings from './remark/headings';
20
+ import toc from './remark/toc';
21
+ import unwrapMdxCodeBlocks from './remark/unwrapMdxCodeBlocks';
22
+ import transformImage from './remark/transformImage';
23
+ import transformLinks from './remark/transformLinks';
24
+ import type {RemarkAndRehypePluginOptions} from '@docusaurus/mdx-loader';
25
+ import type {LoaderContext} from 'webpack';
26
+
27
+ const {
28
+ loaders: {inlineMarkdownImageFileLoader},
29
+ } = getFileLoaderUtils();
30
+
31
+ const DEFAULT_OPTIONS: RemarkAndRehypePluginOptions = {
32
+ rehypePlugins: [],
33
+ remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
34
+ beforeDefaultRemarkPlugins: [],
35
+ beforeDefaultRehypePlugins: [],
36
+ };
37
+
38
+ type Options = RemarkAndRehypePluginOptions & {
39
+ staticDirs: string[];
40
+ siteDir: string;
41
+ isMDXPartial?: (filePath: string) => boolean;
42
+ isMDXPartialFrontMatterWarningDisabled?: boolean;
43
+ removeContentTitle?: boolean;
44
+ metadataPath?: string | ((filePath: string) => string);
45
+ createAssets?: (metadata: {
46
+ frontMatter: Record<string, unknown>;
47
+ metadata: Record<string, unknown>;
48
+ }) => Record<string, unknown>;
49
+ filepath: string;
50
+ };
51
+
52
+ // When this throws, it generally means that there's no metadata file associated with this MDX document
53
+ // It can happen when using MDX partials (usually starting with _)
54
+ // That's why it's important to provide the "isMDXPartial" function in config
55
+ async function readMetadataPath(metadataPath: string) {
56
+ try {
57
+ return await readFile(metadataPath, 'utf8');
58
+ } catch (e) {
59
+ throw new Error(
60
+ `MDX loader can't read MDX metadata file for path ${metadataPath}. Maybe the isMDXPartial option function was not provided?`,
61
+ );
62
+ }
63
+ }
64
+
65
+ // Converts assets an object with Webpack require calls code
66
+ // This is useful for mdx files to reference co-located assets using relative paths
67
+ // Those assets should enter the Webpack assets pipeline and be hashed
68
+ // For now, we only handle that for images and paths starting with ./
69
+ // {image: "./myImage.png"} => {image: require("./myImage.png")}
70
+ function createAssetsExportCode(assets: Record<string, unknown>) {
71
+ if (Object.keys(assets).length === 0) {
72
+ return 'undefined';
73
+ }
74
+
75
+ // TODO implementation can be completed/enhanced
76
+ function createAssetValueCode(assetValue: unknown): string | undefined {
77
+ if (Array.isArray(assetValue)) {
78
+ const arrayItemCodes = assetValue.map(
79
+ (item) => createAssetValueCode(item) ?? 'undefined',
80
+ );
81
+ return `[${arrayItemCodes.join(', ')}]`;
82
+ }
83
+ // Only process string values starting with ./
84
+ // We could enhance this logic and check if file exists on disc?
85
+ if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
86
+ // TODO do we have other use-cases than image assets?
87
+ // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
88
+ const inlineLoader = inlineMarkdownImageFileLoader;
89
+ return `require("${inlineLoader}${escapePath(assetValue)}").default`;
90
+ }
91
+ return undefined;
92
+ }
93
+
94
+ const assetEntries = Object.entries(assets);
95
+
96
+ const codeLines = assetEntries
97
+ .map(([key, value]) => {
98
+ const assetRequireCode = createAssetValueCode(value);
99
+ return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
100
+ })
101
+ .filter(Boolean);
102
+
103
+ return `{\n${codeLines.join('\n')}\n}`;
104
+ }
105
+
106
+ export default async function mdxLoader(
107
+ this: LoaderContext<Options>,
108
+ fileString: string,
109
+ ): Promise<void> {
110
+ const callback = this.async();
111
+ const filePath = this.resourcePath;
112
+ const reqOptions = this.getOptions() || {};
113
+
114
+ const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
115
+
116
+ const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
117
+ removeContentTitle: reqOptions.removeContentTitle,
118
+ });
119
+
120
+ const hasFrontMatter = Object.keys(frontMatter).length > 0;
121
+
122
+ const options: Options = {
123
+ ...reqOptions,
124
+ remarkPlugins: [
125
+ ...(reqOptions.beforeDefaultRemarkPlugins || []),
126
+ ...DEFAULT_OPTIONS.remarkPlugins,
127
+ [transformImage, {staticDirs: reqOptions.staticDirs, filePath}],
128
+ [
129
+ transformLinks,
130
+ {
131
+ staticDirs: reqOptions.staticDirs,
132
+ filePath,
133
+ siteDir: reqOptions.siteDir,
134
+ },
135
+ ],
136
+ ...(reqOptions.remarkPlugins || []),
137
+ ],
138
+ rehypePlugins: [
139
+ ...(reqOptions.beforeDefaultRehypePlugins || []),
140
+ ...DEFAULT_OPTIONS.rehypePlugins,
141
+ ...(reqOptions.rehypePlugins || []),
142
+ ],
143
+ filepath: filePath,
144
+ };
145
+
146
+ let result;
147
+ try {
148
+ result = await mdx(content, options);
149
+ } catch (err) {
150
+ return callback(err as Error);
151
+ }
152
+
153
+ // MDX partials are MDX files starting with _ or in a folder starting with _
154
+ // Partial are not expected to have an associated metadata file or frontmatter
155
+ const isMDXPartial = options.isMDXPartial && options.isMDXPartial(filePath);
156
+ if (isMDXPartial && hasFrontMatter) {
157
+ const errorMessage = `Docusaurus MDX partial files should not contain FrontMatter.
158
+ Those partial files use the _ prefix as a convention by default, but this is configurable.
159
+ File at ${filePath} contains FrontMatter that will be ignored:
160
+ ${JSON.stringify(frontMatter, null, 2)}`;
161
+
162
+ if (!options.isMDXPartialFrontMatterWarningDisabled) {
163
+ const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
164
+ if (shouldError) {
165
+ return callback(new Error(errorMessage));
166
+ } else {
167
+ console.warn(chalk.yellow(errorMessage));
168
+ }
169
+ }
170
+ }
171
+
172
+ function getMetadataPath(): string | undefined {
173
+ if (!isMDXPartial) {
174
+ // Read metadata for this MDX and export it.
175
+ if (options.metadataPath && typeof options.metadataPath === 'function') {
176
+ return options.metadataPath(filePath);
177
+ }
178
+ }
179
+ return undefined;
180
+ }
181
+
182
+ const metadataPath = getMetadataPath();
183
+ if (metadataPath) {
184
+ this.addDependency(metadataPath);
185
+ }
186
+
187
+ const metadataJsonString = metadataPath
188
+ ? await readMetadataPath(metadataPath)
189
+ : undefined;
190
+
191
+ const metadata = metadataJsonString
192
+ ? JSON.parse(metadataJsonString)
193
+ : undefined;
194
+
195
+ const assets =
196
+ reqOptions.createAssets && metadata
197
+ ? reqOptions.createAssets({frontMatter, metadata})
198
+ : undefined;
199
+
200
+ const exportsCode = `
201
+ export const frontMatter = ${stringifyObject(frontMatter)};
202
+ export const contentTitle = ${stringifyObject(contentTitle)};
203
+ ${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
204
+ ${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
205
+ `;
206
+
207
+ const code = `
208
+ import React from 'react';
209
+ import { mdx } from '@mdx-js/react';
210
+
211
+ ${exportsCode}
212
+ ${result}
213
+ `;
214
+
215
+ return callback(null, code);
216
+ }
@@ -5,15 +5,14 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- type RemarkOrRehypePlugin =
9
- // eslint-disable-next-line @typescript-eslint/ban-types
10
- [Function, Record<string, unknown>] | Function;
8
+ import type {Plugin} from 'unified';
11
9
 
12
- declare function docusaurusMdxLoader(fileString: string): string;
13
-
14
- export interface RemarkAndRehypePluginOptions {
10
+ export type RemarkOrRehypePlugin =
11
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
+ [Plugin<any[]>, Record<string, unknown>] | Plugin<any[]>;
13
+ export type RemarkAndRehypePluginOptions = {
15
14
  remarkPlugins: RemarkOrRehypePlugin[];
16
- rehypePlugins: string[];
15
+ rehypePlugins: RemarkOrRehypePlugin[];
17
16
  beforeDefaultRemarkPlugins: RemarkOrRehypePlugin[];
18
17
  beforeDefaultRehypePlugins: RemarkOrRehypePlugin[];
19
- }
18
+ };
@@ -7,8 +7,6 @@
7
7
 
8
8
  /* Based on remark-slug (https://github.com/remarkjs/remark-slug) and gatsby-remark-autolink-headers (https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-remark-autolink-headers) */
9
9
 
10
- /* eslint-disable no-param-reassign */
11
-
12
10
  import remark from 'remark';
13
11
  import u from 'unist-builder';
14
12
  import removePosition from 'unist-util-remove-position';