@docusaurus/mdx-loader 2.0.0-beta.15d451942 → 2.0.0-beta.18

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 (72) hide show
  1. package/lib/index.d.ts +30 -0
  2. package/lib/index.d.ts.map +1 -0
  3. package/lib/index.js +178 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/remark/headings/index.d.ts +9 -0
  6. package/lib/remark/headings/index.d.ts.map +1 -0
  7. package/lib/remark/headings/index.js +60 -0
  8. package/lib/remark/headings/index.js.map +1 -0
  9. package/lib/remark/toc/index.d.ts +13 -0
  10. package/lib/remark/toc/index.d.ts.map +1 -0
  11. package/lib/remark/toc/index.js +81 -0
  12. package/lib/remark/toc/index.js.map +1 -0
  13. package/lib/remark/transformImage/index.d.ts +14 -0
  14. package/lib/remark/transformImage/index.d.ts.map +1 -0
  15. package/lib/remark/transformImage/index.js +109 -0
  16. package/lib/remark/transformImage/index.js.map +1 -0
  17. package/lib/remark/transformLinks/index.d.ts +14 -0
  18. package/lib/remark/transformLinks/index.d.ts.map +1 -0
  19. package/lib/remark/transformLinks/index.js +100 -0
  20. package/lib/remark/transformLinks/index.js.map +1 -0
  21. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts +9 -0
  22. package/lib/remark/unwrapMdxCodeBlocks/index.d.ts.map +1 -0
  23. package/lib/remark/unwrapMdxCodeBlocks/index.js +29 -0
  24. package/lib/remark/unwrapMdxCodeBlocks/index.js.map +1 -0
  25. package/lib/remark/utils/index.d.ts +11 -0
  26. package/lib/remark/utils/index.d.ts.map +1 -0
  27. package/lib/remark/utils/index.js +38 -0
  28. package/lib/remark/utils/index.js.map +1 -0
  29. package/package.json +19 -16
  30. package/src/deps.d.ts +30 -0
  31. package/src/index.ts +225 -0
  32. package/src/{index.d.ts → mdx-loader.d.ts} +7 -8
  33. package/src/remark/headings/{index.js → index.ts} +22 -23
  34. package/src/remark/toc/index.ts +102 -0
  35. package/src/remark/transformImage/index.ts +167 -0
  36. package/src/remark/transformLinks/index.ts +150 -0
  37. package/src/remark/unwrapMdxCodeBlocks/{index.js → index.ts} +14 -15
  38. package/src/remark/utils/index.ts +36 -0
  39. package/src/index.js +0 -104
  40. package/src/remark/headings/__tests__/index.test.js +0 -315
  41. package/src/remark/toc/__tests__/__snapshots__/index.test.js.snap +0 -85
  42. package/src/remark/toc/__tests__/fixtures/empty-headings.md +0 -5
  43. package/src/remark/toc/__tests__/fixtures/inline-code.md +0 -9
  44. package/src/remark/toc/__tests__/fixtures/insert-below-imports.md +0 -11
  45. package/src/remark/toc/__tests__/fixtures/just-content.md +0 -15
  46. package/src/remark/toc/__tests__/fixtures/name-exist.md +0 -7
  47. package/src/remark/toc/__tests__/fixtures/non-text-content.md +0 -9
  48. package/src/remark/toc/__tests__/index.test.js +0 -212
  49. package/src/remark/toc/index.js +0 -79
  50. package/src/remark/toc/search.js +0 -73
  51. package/src/remark/transformImage/__tests__/__snapshots__/index.test.js.snap +0 -31
  52. package/src/remark/transformImage/__tests__/fixtures/fail.md +0 -1
  53. package/src/remark/transformImage/__tests__/fixtures/img.md +0 -17
  54. package/src/remark/transformImage/__tests__/fixtures/img.png +0 -0
  55. package/src/remark/transformImage/__tests__/fixtures/noUrl.md +0 -1
  56. package/src/remark/transformImage/__tests__/fixtures/pathname.md +0 -1
  57. package/src/remark/transformImage/__tests__/index.test.js +0 -59
  58. package/src/remark/transformImage/index.js +0 -106
  59. package/src/remark/transformLinks/__tests__/__snapshots__/index.test.js.snap +0 -41
  60. package/src/remark/transformLinks/__tests__/fixtures/asset.md +0 -29
  61. package/src/remark/transformLinks/__tests__/fixtures/asset.pdf +0 -0
  62. package/src/remark/transformLinks/__tests__/fixtures/noUrl.md +0 -1
  63. package/src/remark/transformLinks/__tests__/fixtures/pathname.md +0 -1
  64. package/src/remark/transformLinks/__tests__/fixtures/static/staticAsset.pdf +0 -0
  65. package/src/remark/transformLinks/__tests__/fixtures/static/staticAssetImage.png +0 -0
  66. package/src/remark/transformLinks/__tests__/index.test.js +0 -44
  67. package/src/remark/transformLinks/index.js +0 -143
  68. package/src/remark/unwrapMdxCodeBlocks/__tests__/__snapshots__/index.test.js.snap +0 -819
  69. package/src/remark/unwrapMdxCodeBlocks/__tests__/fixtures/has-mdx-code-blocks.mdx +0 -95
  70. package/src/remark/unwrapMdxCodeBlocks/__tests__/index.test.js +0 -38
  71. package/src/remark/utils/index.js +0 -39
  72. package/tsconfig.json +0 -9
@@ -0,0 +1,100 @@
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
+ // transform the link node to a jsx link with a require() call
19
+ function toAssetRequireNode(node, assetPath, filePath) {
20
+ const jsxNode = node;
21
+ let relativeAssetPath = (0, utils_1.posixPath)(path_1.default.relative(path_1.default.dirname(filePath), assetPath));
22
+ // require("assets/file.pdf") means requiring from a package called assets
23
+ relativeAssetPath = `./${relativeAssetPath}`;
24
+ const parsedUrl = url_1.default.parse(node.url);
25
+ const hash = parsedUrl.hash ?? '';
26
+ const search = parsedUrl.search ?? '';
27
+ const href = `require('${
28
+ // A hack to stop Webpack from using its built-in loader to parse JSON
29
+ path_1.default.extname(relativeAssetPath) === '.json'
30
+ ? `${relativeAssetPath.replace('.json', '.raw')}!=`
31
+ : ''}${inlineMarkdownLinkFileLoader}${(0, utils_1.escapePath)(relativeAssetPath) + search}').default${hash ? ` + '${hash}'` : ''}`;
32
+ const children = (0, utils_2.stringifyContent)(node);
33
+ const title = node.title ? ` title="${(0, escape_html_1.default)(node.title)}"` : '';
34
+ Object.keys(jsxNode).forEach((key) => delete jsxNode[key]);
35
+ jsxNode.type = 'jsx';
36
+ jsxNode.value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
37
+ }
38
+ async function ensureAssetFileExist(assetPath, sourceFilePath) {
39
+ const assetExists = await fs_extra_1.default.pathExists(assetPath);
40
+ if (!assetExists) {
41
+ throw new Error(`Asset ${(0, utils_1.toMessageRelativeFilePath)(assetPath)} used in ${(0, utils_1.toMessageRelativeFilePath)(sourceFilePath)} not found.`);
42
+ }
43
+ }
44
+ async function getAssetAbsolutePath(assetPath, { siteDir, filePath, staticDirs }) {
45
+ if (assetPath.startsWith('@site/')) {
46
+ const assetFilePath = path_1.default.join(siteDir, assetPath.replace('@site/', ''));
47
+ // The @site alias is the only way to believe that the user wants an asset.
48
+ // Everything else can just be a link URL
49
+ await ensureAssetFileExist(assetFilePath, filePath);
50
+ return assetFilePath;
51
+ }
52
+ else if (path_1.default.isAbsolute(assetPath)) {
53
+ const assetFilePath = await (0, utils_1.findAsyncSequential)(staticDirs.map((dir) => path_1.default.join(dir, assetPath)), fs_extra_1.default.pathExists);
54
+ if (assetFilePath) {
55
+ return assetFilePath;
56
+ }
57
+ }
58
+ else {
59
+ const assetFilePath = path_1.default.join(path_1.default.dirname(filePath), assetPath);
60
+ if (await fs_extra_1.default.pathExists(assetFilePath)) {
61
+ return assetFilePath;
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+ async function processLinkNode(node, context) {
67
+ if (!node.url) {
68
+ // try to improve error feedback
69
+ // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
70
+ const title = node.title || node.children[0]?.value || '?';
71
+ const line = node?.position?.start?.line || '?';
72
+ throw new Error(`Markdown link URL is mandatory in "${(0, utils_1.toMessageRelativeFilePath)(context.filePath)}" file (title: ${title}, line: ${line}).`);
73
+ }
74
+ const parsedUrl = url_1.default.parse(node.url);
75
+ if (parsedUrl.protocol || !parsedUrl.pathname) {
76
+ // Don't process pathname:// here, it's used by the <Link> component
77
+ return;
78
+ }
79
+ const hasSiteAlias = parsedUrl.pathname.startsWith('@site/');
80
+ const hasAssetLikeExtension = path_1.default.extname(parsedUrl.pathname) &&
81
+ !parsedUrl.pathname.match(/\.(?:mdx?|html)(?:#|$)/);
82
+ if (!hasSiteAlias && !hasAssetLikeExtension) {
83
+ return;
84
+ }
85
+ const assetPath = await getAssetAbsolutePath(decodeURIComponent(parsedUrl.pathname), context);
86
+ if (assetPath) {
87
+ toAssetRequireNode(node, assetPath, context.filePath);
88
+ }
89
+ }
90
+ function plugin(options) {
91
+ return async (root, vfile) => {
92
+ const promises = [];
93
+ (0, unist_util_visit_1.default)(root, 'link', (node) => {
94
+ promises.push(processLinkNode(node, { ...options, filePath: vfile.path }));
95
+ });
96
+ await Promise.all(promises);
97
+ };
98
+ }
99
+ exports.default = plugin;
100
+ //# 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,8DAA8D;AAC9D,SAAS,kBAAkB,CAAC,IAAU,EAAE,SAAiB,EAAE,QAAgB;IACzE,MAAM,OAAO,GAAG,IAA+B,CAAC;IAChD,IAAI,iBAAiB,GAAG,IAAA,iBAAS,EAC/B,cAAI,CAAC,QAAQ,CAAC,cAAI,CAAC,OAAO,CAAC,QA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AAC,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.15d451942",
3
+ "version": "2.0.0-beta.18",
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,29 @@
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.15d451942",
24
- "@docusaurus/utils": "2.0.0-beta.15d451942",
25
- "@mdx-js/mdx": "^1.6.21",
26
- "@mdx-js/react": "^1.6.21",
21
+ "@babel/parser": "^7.17.8",
22
+ "@babel/traverse": "^7.17.3",
23
+ "@docusaurus/logger": "2.0.0-beta.18",
24
+ "@docusaurus/utils": "2.0.0-beta.18",
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.0.1",
29
+ "image-size": "^1.0.1",
32
30
  "mdast-util-to-string": "^2.0.0",
33
31
  "remark-emoji": "^2.1.0",
34
32
  "stringify-object": "^3.3.0",
33
+ "tslib": "^2.3.1",
35
34
  "unist-util-visit": "^2.0.2",
36
35
  "url-loader": "^4.1.1",
37
- "webpack": "^5.37.0"
36
+ "webpack": "^5.70.0"
38
37
  },
39
38
  "devDependencies": {
40
- "@docusaurus/types": "2.0.0-beta.15d451942",
39
+ "@docusaurus/types": "2.0.0-beta.18",
40
+ "@types/escape-html": "^1.0.1",
41
+ "@types/mdast": "^3.0.10",
42
+ "@types/stringify-object": "^3.3.1",
43
+ "@types/unist": "^2.0.6",
41
44
  "remark": "^12.0.0",
42
45
  "remark-mdx": "^1.6.21",
43
46
  "to-vfile": "^6.0.0",
@@ -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": "dfceae8bd3e8b42ba8fc14f1449d861046c26143"
57
+ "gitHead": "1a945d06993d53376e61bed2c942799fe07dc336"
55
58
  }
package/src/deps.d.ts ADDED
@@ -0,0 +1,30 @@
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
+ export default function mdx(
27
+ content: string,
28
+ options?: mdx.Options,
29
+ ): Promise<string>;
30
+ }
package/src/index.ts ADDED
@@ -0,0 +1,225 @@
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 mdx 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 {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: {[key: string]: unknown};
47
+ metadata: {[key: string]: unknown};
48
+ }) => {[key: string]: unknown};
49
+ filepath: string;
50
+ };
51
+
52
+ /**
53
+ * When this throws, it generally means that there's no metadata file associated
54
+ * with this MDX document. It can happen when using MDX partials (usually
55
+ * starting with _). That's why it's important to provide the `isMDXPartial`
56
+ * function in config
57
+ */
58
+ async function readMetadataPath(metadataPath: string) {
59
+ try {
60
+ return await fs.readFile(metadataPath, 'utf8');
61
+ } catch (err) {
62
+ logger.error`MDX loader can't read MDX metadata file path=${metadataPath}. Maybe the isMDXPartial option function was not provided?`;
63
+ throw err;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Converts assets an object with Webpack require calls code.
69
+ * This is useful for mdx files to reference co-located assets using relative
70
+ * paths. Those assets should enter the Webpack assets pipeline and be hashed.
71
+ * For now, we only handle that for images and paths starting with `./`:
72
+ *
73
+ * `{image: "./myImage.png"}` => `{image: require("./myImage.png")}`
74
+ */
75
+ function createAssetsExportCode(assets: {[key: string]: unknown}) {
76
+ if (Object.keys(assets).length === 0) {
77
+ return 'undefined';
78
+ }
79
+
80
+ // TODO implementation can be completed/enhanced
81
+ function createAssetValueCode(assetValue: unknown): string | undefined {
82
+ if (Array.isArray(assetValue)) {
83
+ const arrayItemCodes = assetValue.map(
84
+ (item) => createAssetValueCode(item) ?? 'undefined',
85
+ );
86
+ return `[${arrayItemCodes.join(', ')}]`;
87
+ }
88
+ // Only process string values starting with ./
89
+ // We could enhance this logic and check if file exists on disc?
90
+ if (typeof assetValue === 'string' && assetValue.startsWith('./')) {
91
+ // TODO do we have other use-cases than image assets?
92
+ // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708)
93
+ const inlineLoader = inlineMarkdownImageFileLoader;
94
+ return `require("${inlineLoader}${escapePath(assetValue)}").default`;
95
+ }
96
+ return undefined;
97
+ }
98
+
99
+ const assetEntries = Object.entries(assets);
100
+
101
+ const codeLines = assetEntries
102
+ .map(([key, value]) => {
103
+ const assetRequireCode = createAssetValueCode(value);
104
+ return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined;
105
+ })
106
+ .filter(Boolean);
107
+
108
+ return `{\n${codeLines.join('\n')}\n}`;
109
+ }
110
+
111
+ export default async function mdxLoader(
112
+ this: LoaderContext<Options>,
113
+ fileString: string,
114
+ ): Promise<void> {
115
+ const callback = this.async();
116
+ const filePath = this.resourcePath;
117
+ const reqOptions = this.getOptions() ?? {};
118
+
119
+ const {frontMatter, content: contentWithTitle} = parseFrontMatter(fileString);
120
+
121
+ const {content, contentTitle} = parseMarkdownContentTitle(contentWithTitle, {
122
+ removeContentTitle: reqOptions.removeContentTitle,
123
+ });
124
+
125
+ const hasFrontMatter = Object.keys(frontMatter).length > 0;
126
+
127
+ const options: Options = {
128
+ ...reqOptions,
129
+ remarkPlugins: [
130
+ ...(reqOptions.beforeDefaultRemarkPlugins ?? []),
131
+ ...DEFAULT_OPTIONS.remarkPlugins,
132
+ [
133
+ transformImage,
134
+ {
135
+ staticDirs: reqOptions.staticDirs,
136
+ siteDir: reqOptions.siteDir,
137
+ },
138
+ ],
139
+ [
140
+ transformLinks,
141
+ {
142
+ staticDirs: reqOptions.staticDirs,
143
+ siteDir: reqOptions.siteDir,
144
+ },
145
+ ],
146
+ ...(reqOptions.remarkPlugins ?? []),
147
+ ],
148
+ rehypePlugins: [
149
+ ...(reqOptions.beforeDefaultRehypePlugins ?? []),
150
+ ...DEFAULT_OPTIONS.rehypePlugins,
151
+ ...(reqOptions.rehypePlugins ?? []),
152
+ ],
153
+ filepath: filePath,
154
+ };
155
+
156
+ let result: string;
157
+ try {
158
+ result = await mdx(content, options);
159
+ } catch (err) {
160
+ return callback(err as Error);
161
+ }
162
+
163
+ // MDX partials are MDX files starting with _ or in a folder starting with _
164
+ // Partial are not expected to have associated metadata files or front matter
165
+ const isMDXPartial = options.isMDXPartial?.(filePath);
166
+ if (isMDXPartial && hasFrontMatter) {
167
+ const errorMessage = `Docusaurus MDX partial files should not contain FrontMatter.
168
+ Those partial files use the _ prefix as a convention by default, but this is configurable.
169
+ File at ${filePath} contains FrontMatter that will be ignored:
170
+ ${JSON.stringify(frontMatter, null, 2)}`;
171
+
172
+ if (!options.isMDXPartialFrontMatterWarningDisabled) {
173
+ const shouldError = process.env.NODE_ENV === 'test' || process.env.CI;
174
+ if (shouldError) {
175
+ return callback(new Error(errorMessage));
176
+ }
177
+ logger.warn(errorMessage);
178
+ }
179
+ }
180
+
181
+ function getMetadataPath(): string | undefined {
182
+ if (!isMDXPartial) {
183
+ // Read metadata for this MDX and export it.
184
+ if (options.metadataPath && typeof options.metadataPath === 'function') {
185
+ return options.metadataPath(filePath);
186
+ }
187
+ }
188
+ return undefined;
189
+ }
190
+
191
+ const metadataPath = getMetadataPath();
192
+ if (metadataPath) {
193
+ this.addDependency(metadataPath);
194
+ }
195
+
196
+ const metadataJsonString = metadataPath
197
+ ? await readMetadataPath(metadataPath)
198
+ : undefined;
199
+
200
+ const metadata = metadataJsonString
201
+ ? JSON.parse(metadataJsonString)
202
+ : undefined;
203
+
204
+ const assets =
205
+ reqOptions.createAssets && metadata
206
+ ? reqOptions.createAssets({frontMatter, metadata})
207
+ : undefined;
208
+
209
+ const exportsCode = `
210
+ export const frontMatter = ${stringifyObject(frontMatter)};
211
+ export const contentTitle = ${stringifyObject(contentTitle)};
212
+ ${metadataJsonString ? `export const metadata = ${metadataJsonString};` : ''}
213
+ ${assets ? `export const assets = ${createAssetsExportCode(assets)};` : ''}
214
+ `;
215
+
216
+ const code = `
217
+ import React from 'react';
218
+ import { mdx } from '@mdx-js/react';
219
+
220
+ ${exportsCode}
221
+ ${result}
222
+ `;
223
+
224
+ return callback(null, code);
225
+ }
@@ -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[]>, any] | 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,29 +7,32 @@
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
- const {parseMarkdownHeadingId} = require('@docusaurus/utils');
11
- const visit = require('unist-util-visit');
12
- const toString = require('mdast-util-to-string');
13
- const slugs = require('github-slugger')();
10
+ import {parseMarkdownHeadingId, createSlugger} from '@docusaurus/utils';
11
+ import visit from 'unist-util-visit';
12
+ import toString from 'mdast-util-to-string';
13
+ import type {Transformer} from 'unified';
14
+ import type {Parent} from 'unist';
15
+ import type {Heading, Text} from 'mdast';
14
16
 
15
- function headings() {
16
- const transformer = (ast) => {
17
- slugs.reset();
18
-
19
- function visitor(headingNode) {
20
- const data = headingNode.data || (headingNode.data = {}); // eslint-disable-line
21
- const properties = data.hProperties || (data.hProperties = {});
17
+ export default function plugin(): Transformer {
18
+ return (root) => {
19
+ const slugs = createSlugger();
20
+ visit(root, 'heading', (headingNode: Heading) => {
21
+ const data = headingNode.data || (headingNode.data = {});
22
+ const properties = (data.hProperties || (data.hProperties = {})) as {
23
+ id: string;
24
+ };
22
25
  let {id} = properties;
23
26
 
24
27
  if (id) {
25
- id = slugs.slug(id, true);
28
+ id = slugs.slug(id, {maintainCase: true});
26
29
  } else {
27
30
  const headingTextNodes = headingNode.children.filter(
28
31
  ({type}) => !['html', 'jsx'].includes(type),
29
32
  );
30
33
  const heading = toString(
31
34
  headingTextNodes.length > 0
32
- ? {children: headingTextNodes}
35
+ ? ({children: headingTextNodes} as Parent)
33
36
  : headingNode,
34
37
  );
35
38
 
@@ -40,10 +43,12 @@ function headings() {
40
43
 
41
44
  if (parsedHeading.id) {
42
45
  // When there's an id, it is always in the last child node
43
- // Sometimes heading is in multiple "parts" (** syntax creates a child node):
46
+ // Sometimes heading is in multiple "parts" (** syntax creates a child
47
+ // node):
44
48
  // ## part1 *part2* part3 {#id}
45
- const lastNode =
46
- headingNode.children[headingNode.children.length - 1];
49
+ const lastNode = headingNode.children[
50
+ headingNode.children.length - 1
51
+ ] as Text;
47
52
 
48
53
  if (headingNode.children.length > 1) {
49
54
  const lastNodeText = parseMarkdownHeadingId(lastNode.value).text;
@@ -63,12 +68,6 @@ function headings() {
63
68
 
64
69
  data.id = id;
65
70
  properties.id = id;
66
- }
67
-
68
- visit(ast, 'heading', visitor);
71
+ });
69
72
  };
70
-
71
- return transformer;
72
73
  }
73
-
74
- module.exports = headings;