@docusaurus/mdx-loader 2.0.0-beta.2 → 2.0.0-beta.20

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 (77) hide show
  1. package/lib/index.d.ts +33 -0
  2. package/lib/index.d.ts.map +1 -0
  3. package/lib/index.js +11 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/loader.d.ts +39 -0
  6. package/lib/loader.d.ts.map +1 -0
  7. package/lib/loader.js +194 -0
  8. package/lib/loader.js.map +1 -0
  9. package/lib/remark/headings/index.d.ts +9 -0
  10. package/lib/remark/headings/index.d.ts.map +1 -0
  11. package/lib/remark/headings/index.js +58 -0
  12. package/lib/remark/headings/index.js.map +1 -0
  13. package/lib/remark/toc/index.d.ts +13 -0
  14. package/lib/remark/toc/index.d.ts.map +1 -0
  15. package/lib/remark/toc/index.js +81 -0
  16. package/lib/remark/toc/index.js.map +1 -0
  17. package/lib/remark/transformImage/index.d.ts +14 -0
  18. package/lib/remark/transformImage/index.d.ts.map +1 -0
  19. package/lib/remark/transformImage/index.js +109 -0
  20. package/lib/remark/transformImage/index.js.map +1 -0
  21. package/lib/remark/transformLinks/index.d.ts +14 -0
  22. package/lib/remark/transformLinks/index.d.ts.map +1 -0
  23. package/lib/remark/transformLinks/index.js +102 -0
  24. package/lib/remark/transformLinks/index.js.map +1 -0
  25. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts +9 -0
  26. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts.map +1 -0
  27. package/lib/remark/unwrapMdxCodeBlocks/index.js +29 -0
  28. package/lib/remark/unwrapMdxCodeBlocks/index.js.map +1 -0
  29. package/lib/remark/utils/index.d.ts +11 -0
  30. package/lib/remark/utils/index.d.ts.map +1 -0
  31. package/lib/remark/utils/index.js +38 -0
  32. package/lib/remark/utils/index.js.map +1 -0
  33. package/package.json +23 -20
  34. package/src/deps.d.ts +31 -0
  35. package/src/index.ts +35 -0
  36. package/src/loader.ts +253 -0
  37. package/src/remark/headings/{index.js → index.ts} +22 -26
  38. package/src/remark/toc/index.ts +102 -0
  39. package/src/remark/transformImage/index.ts +167 -0
  40. package/src/remark/transformLinks/index.ts +152 -0
  41. package/src/remark/unwrapMdxCodeBlocks/{index.js → index.ts} +14 -15
  42. package/src/remark/utils/index.ts +36 -0
  43. package/src/index.d.ts +0 -19
  44. package/src/index.js +0 -107
  45. package/src/remark/headings/__tests__/index.test.js +0 -315
  46. package/src/remark/toc/__tests__/__snapshots__/index.test.js.snap +0 -85
  47. package/src/remark/toc/__tests__/fixtures/empty-headings.md +0 -5
  48. package/src/remark/toc/__tests__/fixtures/inline-code.md +0 -9
  49. package/src/remark/toc/__tests__/fixtures/insert-below-imports.md +0 -11
  50. package/src/remark/toc/__tests__/fixtures/just-content.md +0 -15
  51. package/src/remark/toc/__tests__/fixtures/name-exist.md +0 -7
  52. package/src/remark/toc/__tests__/fixtures/non-text-content.md +0 -9
  53. package/src/remark/toc/__tests__/index.test.js +0 -212
  54. package/src/remark/toc/index.js +0 -79
  55. package/src/remark/toc/search.js +0 -73
  56. package/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap +0 -31
  57. package/src/remark/transformImage/__tests__/fixtures/fail.md +0 -1
  58. package/src/remark/transformImage/__tests__/fixtures/img.md +0 -17
  59. package/src/remark/transformImage/__tests__/fixtures/img.png +0 -0
  60. package/src/remark/transformImage/__tests__/fixtures/noUrl.md +0 -1
  61. package/src/remark/transformImage/__tests__/fixtures/pathname.md +0 -1
  62. package/src/remark/transformImage/__tests__/index.test.js +0 -59
  63. package/src/remark/transformImage/index.js +0 -106
  64. package/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap +0 -41
  65. package/src/remark/transformLinks/__tests__/fixtures/asset.md +0 -29
  66. package/src/remark/transformLinks/__tests__/fixtures/asset.pdf +0 -0
  67. package/src/remark/transformLinks/__tests__/fixtures/noUrl.md +0 -1
  68. package/src/remark/transformLinks/__tests__/fixtures/pathname.md +0 -1
  69. package/src/remark/transformLinks/__tests__/fixtures/static/staticAsset.pdf +0 -0
  70. package/src/remark/transformLinks/__tests__/fixtures/static/staticAssetImage.png +0 -0
  71. package/src/remark/transformLinks/__tests__/index.test.js +0 -44
  72. package/src/remark/transformLinks/index.js +0 -143
  73. package/src/remark/unwrapMdxCodeBlocks/__tests__/__snapshots__/index.test.js.snap +0 -819
  74. package/src/remark/unwrapMdxCodeBlocks/__tests__/fixtures/has-mdx-code-blocks.mdx +0 -95
  75. package/src/remark/unwrapMdxCodeBlocks/__tests__/index.test.js +0 -38
  76. package/src/remark/utils/index.js +0 -39
  77. package/tsconfig.json +0 -9
@@ -0,0 +1,102 @@
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 = tslib_1.__importDefault(require("unist-util-visit"));
12
+ const path_1 = tslib_1.__importDefault(require("path"));
13
+ const url_1 = tslib_1.__importDefault(require("url"));
14
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
15
+ const escape_html_1 = tslib_1.__importDefault(require("escape-html"));
16
+ const utils_2 = require("../utils");
17
+ const { loaders: { inlineMarkdownLinkFileLoader }, } = (0, utils_1.getFileLoaderUtils)();
18
+ /**
19
+ * Transforms the link node to a JSX `<a>` element with a `require()` call.
20
+ */
21
+ function toAssetRequireNode(node, assetPath, filePath) {
22
+ const jsxNode = node;
23
+ let relativeAssetPath = (0, utils_1.posixPath)(path_1.default.relative(path_1.default.dirname(filePath), assetPath));
24
+ // require("assets/file.pdf") means requiring from a package called assets
25
+ relativeAssetPath = `./${relativeAssetPath}`;
26
+ const parsedUrl = url_1.default.parse(node.url);
27
+ const hash = parsedUrl.hash ?? '';
28
+ const search = parsedUrl.search ?? '';
29
+ const href = `require('${
30
+ // A hack to stop Webpack from using its built-in loader to parse JSON
31
+ path_1.default.extname(relativeAssetPath) === '.json'
32
+ ? `${relativeAssetPath.replace('.json', '.raw')}!=`
33
+ : ''}${inlineMarkdownLinkFileLoader}${(0, utils_1.escapePath)(relativeAssetPath) + search}').default${hash ? ` + '${hash}'` : ''}`;
34
+ const children = (0, utils_2.stringifyContent)(node);
35
+ const title = node.title ? ` title="${(0, escape_html_1.default)(node.title)}"` : '';
36
+ Object.keys(jsxNode).forEach((key) => delete jsxNode[key]);
37
+ jsxNode.type = 'jsx';
38
+ jsxNode.value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
39
+ }
40
+ async function ensureAssetFileExist(assetPath, sourceFilePath) {
41
+ const assetExists = await fs_extra_1.default.pathExists(assetPath);
42
+ if (!assetExists) {
43
+ throw new Error(`Asset ${(0, utils_1.toMessageRelativeFilePath)(assetPath)} used in ${(0, utils_1.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
44
+ }
45
+ }
46
+ async function getAssetAbsolutePath(assetPath, { siteDir, filePath, staticDirs }) {
47
+ if (assetPath.startsWith('@site/')) {
48
+ const assetFilePath = path_1.default.join(siteDir, assetPath.replace('@site/', ''));
49
+ // The @site alias is the only way to believe that the user wants an asset.
50
+ // Everything else can just be a link URL
51
+ await ensureAssetFileExist(assetFilePath, filePath);
52
+ return assetFilePath;
53
+ }
54
+ else if (path_1.default.isAbsolute(assetPath)) {
55
+ const assetFilePath = await (0, utils_1.findAsyncSequential)(staticDirs.map((dir) => path_1.default.join(dir, assetPath)), fs_extra_1.default.pathExists);
56
+ if (assetFilePath) {
57
+ return assetFilePath;
58
+ }
59
+ }
60
+ else {
61
+ const assetFilePath = path_1.default.join(path_1.default.dirname(filePath), assetPath);
62
+ if (await fs_extra_1.default.pathExists(assetFilePath)) {
63
+ return assetFilePath;
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+ async function processLinkNode(node, context) {
69
+ if (!node.url) {
70
+ // Try to improve error feedback
71
+ // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
72
+ const title = node.title || node.children[0]?.value || '?';
73
+ const line = node?.position?.start?.line || '?';
74
+ throw new Error(`Markdown link URL is mandatory in "${(0, utils_1.toMessageRelativeFilePath)(context.filePath)}" file (title: ${title}, line: ${line}).`);
75
+ }
76
+ const parsedUrl = url_1.default.parse(node.url);
77
+ if (parsedUrl.protocol || !parsedUrl.pathname) {
78
+ // Don't process pathname:// here, it's used by the <Link> component
79
+ return;
80
+ }
81
+ const hasSiteAlias = parsedUrl.pathname.startsWith('@site/');
82
+ const hasAssetLikeExtension = path_1.default.extname(parsedUrl.pathname) &&
83
+ !parsedUrl.pathname.match(/\.(?:mdx?|html)(?:#|$)/);
84
+ if (!hasSiteAlias && !hasAssetLikeExtension) {
85
+ return;
86
+ }
87
+ const assetPath = await getAssetAbsolutePath(decodeURIComponent(parsedUrl.pathname), context);
88
+ if (assetPath) {
89
+ toAssetRequireNode(node, assetPath, context.filePath);
90
+ }
91
+ }
92
+ function plugin(options) {
93
+ return async (root, vfile) => {
94
+ const promises = [];
95
+ (0, unist_util_visit_1.default)(root, 'link', (node) => {
96
+ promises.push(processLinkNode(node, { ...options, filePath: vfile.path }));
97
+ });
98
+ await Promise.all(promises);
99
+ };
100
+ }
101
+ exports.default = plugin;
102
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/remark/transformLinks/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,6CAM2B;AAC3B,gFAAqC;AACrC,wDAAwB;AACxB,sDAAsB;AACtB,gEAA0B;AAC1B,sEAAqC;AACrC,oCAA0C;AAI1C,MAAM,EACJ,OAAO,EAAE,EAAC,4BAA4B,EAAC,GACxC,GAAG,IAAA,0BAAkB,GAAE,CAAC;AAWzB;;GAEG;AACH,SAAS,kBAAkB,CAAC,IAAU,EAAE,SAAiB,EAAE,QAAgB;IACzE,MAAM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AAE,IAAI,EAAE,KAAK,EAAE,EAAE;QAC3B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,IAAA,0BAAK,EAAC,IAAI,EAAE,MAAM,EAAE,CAAC,IAAU,EAAE,EAAE;YACjC,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,EAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,IAAK,EAAC,CAAC,CAAC,CAAC;QAC5E,CAAC,CAAC,CAAC;QACH,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;AACJ,CAAC;AARD,yBAQC"}
@@ -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
+ export default function plugin(this: Processor): Transformer;
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/remark/unwrapMdxCodeBlocks/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAC,WAAW,EAAE,SAAS,EAAC,MAAM,SAAS,CAAC;AASpD,MAAM,CAAC,OAAO,UAAU,MAAM,CAAC,IAAI,EAAE,SAAS,GAAG,WAAW,CAe3D"}
@@ -0,0 +1,29 @@
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 = 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
14
+ // with the markup, but the JSX inside such code blocks should still be
15
+ // evaluated as JSX
16
+ // See https://github.com/facebook/docusaurus/pull/4278
17
+ function plugin() {
18
+ return (root) => {
19
+ (0, unist_util_visit_1.default)(root, 'code', (node, index, parent) => {
20
+ if (node.lang === 'mdx-code-block') {
21
+ const newChildren = this.parse(node.value).children;
22
+ // Replace the mdx code block by its content, parsed
23
+ parent.children.splice(parent.children.indexOf(node), 1, ...newChildren);
24
+ }
25
+ });
26
+ };
27
+ }
28
+ exports.default = plugin;
29
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/remark/unwrapMdxCodeBlocks/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,gFAAqC;AAIrC,gFAAgF;AAChF,mEAAmE;AACnE,gFAAgF;AAChF,uEAAuE;AACvE,mBAAmB;AACnB,uDAAuD;AACvD,SAAwB,MAAM;IAC5B,OAAO,CAAC,IAAI,EAAE,EAAE;QACd,IAAA,0BAAK,EAAC,IAAI,EAAE,MAAM,EAAE,CAAC,IAAU,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YAChD,IAAI,IAAI,CAAC,IAAI,KAAK,gBAAgB,EAAE;gBAClC,MAAM,WAAW,GAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAY,CAAC,QAAQ,CAAC;gBAEhE,oDAAoD;gBACpD,MAAO,CAAC,QAAQ,CAAC,MAAM,CACrB,MAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,EAC9B,CAAC,EACD,GAAG,WAAW,CACf,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC;AAfD,yBAeC"}
@@ -0,0 +1,11 @@
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 { PhrasingContent, Heading } from 'mdast';
9
+ export declare function stringifyContent(node: Parent): string;
10
+ export declare function toValue(node: PhrasingContent | Heading): string;
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/remark/utils/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,OAAO,CAAC;AAClC,OAAO,KAAK,EAAC,eAAe,EAAE,OAAO,EAAC,MAAM,OAAO,CAAC;AAEpD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAErD;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,GAAG,MAAM,CAmB/D"}
@@ -0,0 +1,38 @@
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 = tslib_1.__importDefault(require("escape-html"));
12
+ const mdast_util_to_string_1 = tslib_1.__importDefault(require("mdast-util-to-string"));
13
+ function stringifyContent(node) {
14
+ return node.children.map(toValue).join('');
15
+ }
16
+ exports.stringifyContent = stringifyContent;
17
+ function toValue(node) {
18
+ switch (node?.type) {
19
+ case 'text':
20
+ return (0, escape_html_1.default)(node.value);
21
+ case 'heading':
22
+ return stringifyContent(node);
23
+ case 'inlineCode':
24
+ return `<code>${(0, escape_html_1.default)(node.value)}</code>`;
25
+ case 'emphasis':
26
+ return `<em>${stringifyContent(node)}</em>`;
27
+ case 'strong':
28
+ return `<strong>${stringifyContent(node)}</strong>`;
29
+ case 'delete':
30
+ return `<del>${stringifyContent(node)}</del>`;
31
+ case 'link':
32
+ return stringifyContent(node);
33
+ default:
34
+ return (0, mdast_util_to_string_1.default)(node);
35
+ }
36
+ }
37
+ exports.toValue = toValue;
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/remark/utils/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH,sEAAqC;AACrC,wFAA4C;AAI5C,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,OAAQ,IAAI,CAAC,QAA8B,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACpE,CAAC;AAFD,4CAEC;AAED,SAAgB,OAAO,CAAC,IAA+B;IACrD,QAAQ,IAAI,EAAE,IAAI,EAAE;QAClB,KAAK,MAAM;YACT,OAAO,IAAA,qBAAU,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAChC,KAAK,SAAS;YACZ,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAChC,KAAK,YAAY;YACf,OAAO,SAAS,IAAA,qBAAU,EAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;QAClD,KAAK,UAAU;YACb,OAAO,OAAO,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC;QAC9C,KAAK,QAAQ;YACX,OAAO,WAAW,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC;QACtD,KAAK,QAAQ;YACX,OAAO,QAAQ,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC;QAChD,KAAK,MAAM;YACT,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAChC;YACE,OAAO,IAAA,8BAAQ,EAAC,IAAI,CAAC,CAAC;KACzB;AACH,CAAC;AAnBD,0BAmBC"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@docusaurus/mdx-loader",
3
- "version": "2.0.0-beta.2",
3
+ "version": "2.0.0-beta.20",
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": "lib/index.d.ts",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
@@ -18,29 +18,32 @@
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.2",
24
- "@docusaurus/utils": "2.0.0-beta.2",
25
- "@mdx-js/mdx": "^1.6.21",
26
- "@mdx-js/react": "^1.6.21",
21
+ "@babel/parser": "^7.17.10",
22
+ "@babel/traverse": "^7.17.10",
23
+ "@docusaurus/logger": "2.0.0-beta.20",
24
+ "@docusaurus/utils": "2.0.0-beta.20",
25
+ "@mdx-js/mdx": "^1.6.22",
27
26
  "escape-html": "^1.0.3",
28
27
  "file-loader": "^6.2.0",
29
- "fs-extra": "^10.0.0",
30
- "github-slugger": "^1.3.0",
31
- "gray-matter": "^4.0.3",
28
+ "fs-extra": "^10.1.0",
29
+ "image-size": "^1.0.1",
32
30
  "mdast-util-to-string": "^2.0.0",
33
- "remark-emoji": "^2.1.0",
31
+ "remark-emoji": "^2.2.0",
34
32
  "stringify-object": "^3.3.0",
35
- "unist-util-visit": "^2.0.2",
33
+ "tslib": "^2.4.0",
34
+ "unist-util-visit": "^2.0.3",
36
35
  "url-loader": "^4.1.1",
37
- "webpack": "^5.40.0"
36
+ "webpack": "^5.72.0"
38
37
  },
39
38
  "devDependencies": {
40
- "@docusaurus/types": "2.0.0-beta.2",
41
- "remark": "^12.0.0",
39
+ "@docusaurus/types": "2.0.0-beta.20",
40
+ "@types/escape-html": "^1.0.2",
41
+ "@types/mdast": "^3.0.10",
42
+ "@types/stringify-object": "^3.3.1",
43
+ "@types/unist": "^2.0.6",
44
+ "remark": "^12.0.1",
42
45
  "remark-mdx": "^1.6.21",
43
- "to-vfile": "^6.0.0",
46
+ "to-vfile": "^6.1.0",
44
47
  "unist-builder": "^2.0.3",
45
48
  "unist-util-remove-position": "^3.0.0"
46
49
  },
@@ -49,7 +52,7 @@
49
52
  "react-dom": "^16.8.4 || ^17.0.0"
50
53
  },
51
54
  "engines": {
52
- "node": ">=12.13.0"
55
+ "node": ">=14"
53
56
  },
54
- "gitHead": "883f07fddffaf1657407c8e202e370cc436e25f7"
57
+ "gitHead": "ed5cdba401a5948e187e927039b142a0decc702d"
55
58
  }
package/src/deps.d.ts ADDED
@@ -0,0 +1,31 @@
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, Plugin} from 'unified';
11
+
12
+ type MDXPlugin =
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ [Plugin<any[]>, any] | Plugin<any[]>;
15
+
16
+ type Options = {
17
+ filepath?: string;
18
+ skipExport?: boolean;
19
+ wrapExport?: string;
20
+ remarkPlugins?: MDXPlugin[];
21
+ rehypePlugins?: MDXPlugin[];
22
+ };
23
+
24
+ export function sync(content: string, options?: Options): string;
25
+ export function createMdxAstCompiler(options?: Options): Processor;
26
+ export function createCompiler(options?: Options): Processor;
27
+ export default function mdx(
28
+ content: string,
29
+ options?: Options,
30
+ ): Promise<string>;
31
+ }
package/src/index.ts ADDED
@@ -0,0 +1,35 @@
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 {mdxLoader} from './loader';
9
+
10
+ export default mdxLoader;
11
+
12
+ export type TOCItem = {
13
+ readonly value: string;
14
+ readonly id: string;
15
+ readonly level: number;
16
+ };
17
+
18
+ export type LoadedMDXContent<FrontMatter, Metadata, Assets = undefined> = {
19
+ /** As verbatim declared in the MDX document. */
20
+ readonly frontMatter: FrontMatter;
21
+ /** As provided by the content plugin. */
22
+ readonly metadata: Metadata;
23
+ /** A list of TOC items (headings). */
24
+ readonly toc: readonly TOCItem[];
25
+ /** First h1 title before any content. */
26
+ readonly contentTitle: string | undefined;
27
+ /**
28
+ * Usually image assets that may be collocated like `./img/thumbnail.png`.
29
+ * The loader would also bundle these assets and the client should use these
30
+ * in priority.
31
+ */
32
+ readonly assets: Assets;
33
+ (): JSX.Element;
34
+ };
35
+ export type {Options, MDXPlugin, MDXOptions} from './loader';
package/src/loader.ts ADDED
@@ -0,0 +1,253 @@
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 fs from 'fs-extra';
9
+ import {createCompiler} from '@mdx-js/mdx';
10
+ import logger from '@docusaurus/logger';
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 {LoaderContext} from 'webpack';
25
+ import type {Processor, Plugin} from 'unified';
26
+
27
+ const {
28
+ loaders: {inlineMarkdownImageFileLoader},
29
+ } = getFileLoaderUtils();
30
+
31
+ const pragma = `
32
+ /* @jsxRuntime classic */
33
+ /* @jsx mdx */
34
+ /* @jsxFrag mdx.Fragment */
35
+ `;
36
+
37
+ const DEFAULT_OPTIONS: MDXOptions = {
38
+ rehypePlugins: [],
39
+ remarkPlugins: [unwrapMdxCodeBlocks, emoji, headings, toc],
40
+ beforeDefaultRemarkPlugins: [],
41
+ beforeDefaultRehypePlugins: [],
42
+ };
43
+
44
+ const compilerCache = new Map<string | Options, [Processor, Options]>();
45
+
46
+ export type MDXPlugin =
47
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
+ [Plugin<any[]>, any] | Plugin<any[]>;
49
+ export type MDXOptions = {
50
+ remarkPlugins: MDXPlugin[];
51
+ rehypePlugins: MDXPlugin[];
52
+ beforeDefaultRemarkPlugins: MDXPlugin[];
53
+ beforeDefaultRehypePlugins: MDXPlugin[];
54
+ };
55
+
56
+ export type Options = MDXOptions & {
57
+ staticDirs: string[];
58
+ siteDir: string;
59
+ isMDXPartial?: (filePath: string) => boolean;
60
+ isMDXPartialFrontMatterWarningDisabled?: boolean;
61
+ removeContentTitle?: boolean;
62
+ metadataPath?: string | ((filePath: string) => string);
63
+ createAssets?: (metadata: {
64
+ frontMatter: {[key: string]: unknown};
65
+ metadata: {[key: string]: unknown};
66
+ }) => {[key: string]: unknown};
67
+ filepath: string;
68
+ };
69
+
70
+ /**
71
+ * When this throws, it generally means that there's no metadata file associated
72
+ * with this MDX document. It can happen when using MDX partials (usually
73
+ * starting with _). That's why it's important to provide the `isMDXPartial`
74
+ * function in config
75
+ */
76
+ async function readMetadataPath(metadataPath: string) {
77
+ try {
78
+ return await fs.readFile(metadataPath, 'utf8');
79
+ } catch (err) {
80
+ logger.error`MDX loader can't read MDX metadata file path=${metadataPath}. Maybe the isMDXPartial option function was not provided?`;
81
+ throw err;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Converts assets an object with Webpack require calls code.
87
+ * This is useful for mdx files to reference co-located assets using relative
88
+ * paths. Those assets should enter the Webpack assets pipeline and be hashed.
89
+ * For now, we only handle that for images and paths starting with `./`:
90
+ *
91
+ * `{image: "./myImage.png"}` => `{image: require("./myImage.png")}`
92
+ */
93
+ function createAssetsExportCode(assets: {[key: string]: unknown}) {
94
+ if (Object.keys(assets).length === 0) {
95
+ return 'undefined';
96
+ }
97
+
98
+ // TODO implementation can be completed/enhanced
99
+ function createAssetValueCode(assetValue: unknown): string | undefined {
100
+ if (Array.isArray(assetValue)) {
101
+ const arrayItemCodes = assetValue.map(
102
+ (item) => createAssetValueCode(item) ?? 'undefined',
103
+ );
104
+ return `[${arrayItemCodes.join(', ')}]`;
105
+ }
106
+ // Only process string values starting with ./
107
+ // We could enhance this logic and check if file exists on disc?
108
+ if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
109
+ // TODO do we have other use-cases than image assets?
110
+ // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
111
+ const inlineLoader = inlineMarkdownImageFileLoader;
112
+ return `require("${inlineLoader}${escapePath(assetValue)}").default`;
113
+ }
114
+ return undefined;
115
+ }
116
+
117
+ const assetEntries = Object.entries(assets);
118
+
119
+ const codeLines = assetEntries
120
+ .map(([key, value]) => {
121
+ const assetRequireCode = createAssetValueCode(value);
122
+ return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
123
+ })
124
+ .filter(Boolean);
125
+
126
+ return `{\n${codeLines.join('\n')}\n}`;
127
+ }
128
+
129
+ export async function mdxLoader(
130
+ this: LoaderContext<Options>,
131
+ fileString: string,
132
+ ): Promise<void> {
133
+ const callback = this.async();
134
+ const filePath = this.resourcePath;
135
+ const reqOptions = this.getOptions() ?? {};
136
+
137
+ const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
138
+
139
+ const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
140
+ removeContentTitle: reqOptions.removeContentTitle,
141
+ });
142
+
143
+ const hasFrontMatter = Object.keys(frontMatter).length > 0;
144
+
145
+ if (!compilerCache.has(this.query)) {
146
+ const options: Options = {
147
+ ...reqOptions,
148
+ remarkPlugins: [
149
+ ...(reqOptions.beforeDefaultRemarkPlugins ?? []),
150
+ ...DEFAULT_OPTIONS.remarkPlugins,
151
+ [
152
+ transformImage,
153
+ {
154
+ staticDirs: reqOptions.staticDirs,
155
+ siteDir: reqOptions.siteDir,
156
+ },
157
+ ],
158
+ [
159
+ transformLinks,
160
+ {
161
+ staticDirs: reqOptions.staticDirs,
162
+ siteDir: reqOptions.siteDir,
163
+ },
164
+ ],
165
+ ...(reqOptions.remarkPlugins ?? []),
166
+ ],
167
+ rehypePlugins: [
168
+ ...(reqOptions.beforeDefaultRehypePlugins ?? []),
169
+ ...DEFAULT_OPTIONS.rehypePlugins,
170
+ ...(reqOptions.rehypePlugins ?? []),
171
+ ],
172
+ };
173
+ compilerCache.set(this.query, [createCompiler(options), options]);
174
+ }
175
+
176
+ const [compiler, options] = compilerCache.get(this.query)!;
177
+
178
+ let result: string;
179
+ try {
180
+ result = await compiler
181
+ .process({
182
+ contents: content,
183
+ path: this.resourcePath,
184
+ })
185
+ .then((res) => res.toString());
186
+ } catch (err) {
187
+ return callback(err as Error);
188
+ }
189
+
190
+ // MDX partials are MDX files starting with _ or in a folder starting with _
191
+ // Partial are not expected to have associated metadata files or front matter
192
+ const isMDXPartial = options.isMDXPartial?.(filePath);
193
+ if (isMDXPartial && hasFrontMatter) {
194
+ const errorMessage = `Docusaurus MDX partial files should not contain front matter.
195
+ Those partial files use the _ prefix as a convention by default, but this is configurable.
196
+ File at ${filePath} contains front matter that will be ignored:
197
+ ${JSON.stringify(frontMatter, null, 2)}`;
198
+
199
+ if (!options.isMDXPartialFrontMatterWarningDisabled) {
200
+ const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
201
+ if (shouldError) {
202
+ return callback(new Error(errorMessage));
203
+ }
204
+ logger.warn(errorMessage);
205
+ }
206
+ }
207
+
208
+ function getMetadataPath(): string | undefined {
209
+ if (!isMDXPartial) {
210
+ // Read metadata for this MDX and export it.
211
+ if (options.metadataPath && typeof options.metadataPath === 'function') {
212
+ return options.metadataPath(filePath);
213
+ }
214
+ }
215
+ return undefined;
216
+ }
217
+
218
+ const metadataPath = getMetadataPath();
219
+ if (metadataPath) {
220
+ this.addDependency(metadataPath);
221
+ }
222
+
223
+ const metadataJsonString = metadataPath
224
+ ? await readMetadataPath(metadataPath)
225
+ : undefined;
226
+
227
+ const metadata = metadataJsonString
228
+ ? JSON.parse(metadataJsonString)
229
+ : undefined;
230
+
231
+ const assets =
232
+ reqOptions.createAssets && metadata
233
+ ? reqOptions.createAssets({frontMatter, metadata})
234
+ : undefined;
235
+
236
+ const exportsCode = `
237
+ export const frontMatter = ${stringifyObject(frontMatter)};
238
+ export const contentTitle = ${stringifyObject(contentTitle)};
239
+ ${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
240
+ ${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
241
+ `;
242
+
243
+ const code = `
244
+ ${pragma}
245
+ import React from 'react';
246
+ import { mdx } from '@mdx-js/react';
247
+
248
+ ${exportsCode}
249
+ ${result}
250
+ `;
251
+
252
+ return callback(null, code);
253
+ }