|
| 1 | +const fs = require('fs-extra'); |
| 2 | +const path = require('path'); |
| 3 | +const { createMacro } = require('babel-plugin-macros'); |
| 4 | +const babelPresetReactApp = require('babel-preset-react-app'); |
| 5 | +const findCacheDir = require('find-cache-dir'); |
| 6 | +const revHash = require('rev-hash'); |
| 7 | +const mdx = require('@mdx-js/mdx'); |
| 8 | +const parse = require('@babel/parser').parse; |
| 9 | +const traverse = require('babel-traverse').default; |
| 10 | + |
| 11 | +const cacheDir = findCacheDir({ name: 'mdx.macro' }); |
| 12 | +const renamedSymbol = Symbol('renamed'); |
| 13 | + |
| 14 | +function writeTempFile(name, content) { |
| 15 | + let nameParts = path.basename(name).split('.'); |
| 16 | + nameParts.splice(1, 0, revHash(content)); |
| 17 | + nameParts.push('js'); |
| 18 | + let pathname = path.resolve(cacheDir, nameParts.join('.')); |
| 19 | + fs.ensureDirSync(cacheDir); |
| 20 | + fs.writeFileSync(pathname, content); |
| 21 | + |
| 22 | + // Remove the path up to and including `node_modules`, so that |
| 23 | + // create-react-app won't complain about the file being somewhere else. |
| 24 | + return pathname.replace(/^.*\/node_modules\//, ''); |
| 25 | +} |
| 26 | + |
| 27 | +function mdxMacro({ babel, references, state }) { |
| 28 | + let { importMDX = [], mdx = [] } = references; |
| 29 | + |
| 30 | + importMDX.forEach((referencePath) => { |
| 31 | + if (referencePath.parentPath.type === 'CallExpression') { |
| 32 | + importAsync({ referencePath, state, babel }); |
| 33 | + } else if (referencePath.parentPath.type === 'MemberExpression' && referencePath.parentPath.node.property.name === 'sync') { |
| 34 | + hasSyncReferences = true; |
| 35 | + importSync({ referencePath, state, babel }); |
| 36 | + } else { |
| 37 | + throw new Error(`This is not supported: \`${referencePath.findParent(babel.types.isExpression).getSource()}\`. Please see the mdx.macro documentation`); |
| 38 | + } |
| 39 | + }); |
| 40 | + |
| 41 | + let hasInlineMDX = false; |
| 42 | + mdx.forEach((referencePath) => { |
| 43 | + hasInlineMDX = true; |
| 44 | + inlineMDX({ referencePath, state, babel }); |
| 45 | + }); |
| 46 | + |
| 47 | + if (hasInlineMDX) { |
| 48 | + let program = state.file.path; |
| 49 | + let mdxTagImport = babel.transformSync(`import { MDXTag } from '@mdx-js/tag'`, { |
| 50 | + ast: true, |
| 51 | + filename: 'mdx.macro/mdxTagImport.js' |
| 52 | + }); |
| 53 | + program.node.body.unshift(mdxTagImport.ast.program.body[0]); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +function importAsync({ babel, referencePath, state }) { |
| 58 | + let { types: t } = babel; |
| 59 | + let { |
| 60 | + file: { |
| 61 | + opts: { filename } |
| 62 | + } |
| 63 | + } = state; |
| 64 | + let documentFilename = referencePath.parentPath.node.arguments[0].value; |
| 65 | + |
| 66 | + let pathname = transform({ babel, filename, documentFilename }); |
| 67 | + |
| 68 | + // Replace the `importMDX.async()` call with a dynamic import() |
| 69 | + referencePath.parentPath.replaceWith(t.callExpression(t.import(), [t.stringLiteral(pathname)])); |
| 70 | +} |
| 71 | + |
| 72 | +function importSync({ babel, referencePath, state }) { |
| 73 | + let { types: t } = babel; |
| 74 | + let { |
| 75 | + file: { |
| 76 | + opts: { filename } |
| 77 | + } |
| 78 | + } = state; |
| 79 | + let documentFilename = referencePath.parentPath.parentPath.node.arguments[0].value; |
| 80 | + |
| 81 | + let pathname = transform({ babel, filename, documentFilename }); |
| 82 | + let id = referencePath.scope.generateUidIdentifier(pathname); |
| 83 | + |
| 84 | + // Add an import statement |
| 85 | + let program = state.file.path; |
| 86 | + program.node.body.unshift(t.importDeclaration([t.importDefaultSpecifier(id)], t.stringLiteral(pathname))); |
| 87 | + |
| 88 | + // Replace the `importMDX.sync()` call with the imported binding |
| 89 | + referencePath.parentPath.parentPath.replaceWith(id); |
| 90 | +} |
| 91 | + |
| 92 | +// Find the import filename, |
| 93 | +function transform({ babel, filename, documentFilename }) { |
| 94 | + if (!filename) { |
| 95 | + throw new Error(`You must pass a filename to importMDX(). Please see the mdx.macro documentation`); |
| 96 | + } |
| 97 | + let documentPath = path.join(filename, '..', documentFilename); |
| 98 | + let imports = `import React from 'react'\nimport { MDXTag } from '@mdx-js/tag'\n`; |
| 99 | + |
| 100 | + // In development mode, we want to import the original document so that |
| 101 | + // changes will be picked up and cause a re-build. |
| 102 | + // Note: this relies on files with macros *not* being cached by babel. |
| 103 | + if (process.env.NODE_ENV === 'development') { |
| 104 | + imports += `import '${documentPath.replace(/\\/g, '\\\\')}' // ${documentPath}\n`; |
| 105 | + } |
| 106 | + |
| 107 | + let source = fs.readFileSync(documentPath, 'utf8'); |
| 108 | + let transformedSource = babel.transformSync(imports + mdx.sync(source), { |
| 109 | + presets: [babelPresetReactApp], |
| 110 | + filename: documentPath |
| 111 | + }).code; |
| 112 | + |
| 113 | + return writeTempFile(documentPath, transformedSource); |
| 114 | +} |
| 115 | + |
| 116 | +function inlineMDX({ babel, referencePath, state }) { |
| 117 | + let { |
| 118 | + file: { |
| 119 | + opts: { filename } |
| 120 | + } |
| 121 | + } = state; |
| 122 | + let program = state.file.path; |
| 123 | + |
| 124 | + let rawCode = referencePath.parent.quasi.quasis[0].value.raw; |
| 125 | + let transformedSource = mdx.sync(rawCode).replace('export default', ''); |
| 126 | + |
| 127 | + // Need to parse the transformed source this way instead of |
| 128 | + // with babel.parse or babel.transform, as otherwise the |
| 129 | + // generated code has errors. I'm not sure why. |
| 130 | + let ast = parse(transformedSource, { |
| 131 | + plugins: ['jsx', 'objectRestSpread'], |
| 132 | + sourceType: 'module', |
| 133 | + sourceFilename: filename |
| 134 | + }); |
| 135 | + |
| 136 | + function visitImport(path) { |
| 137 | + let name = path.node.local.name; |
| 138 | + var binding = path.scope.getBinding(name); |
| 139 | + if (!binding) { |
| 140 | + return; |
| 141 | + } |
| 142 | + if (binding[renamedSymbol]) { |
| 143 | + return; |
| 144 | + } |
| 145 | + |
| 146 | + path.scope.rename(name, referencePath.scope.generateUidIdentifier(name).name); |
| 147 | + binding[renamedSymbol] = true; |
| 148 | + } |
| 149 | + |
| 150 | + // Rename any imports to unique identifiers to prevent |
| 151 | + // collisions between import names across multiple mdx tags |
| 152 | + traverse(ast, { |
| 153 | + ImportNamespaceSpecifier: visitImport, |
| 154 | + ImportDefaultSpecifier: visitImport, |
| 155 | + ImportSpecifier: visitImport |
| 156 | + }); |
| 157 | + |
| 158 | + ast.program.body.slice(0, -1).forEach((node) => program.node.body.unshift(node)); |
| 159 | + referencePath.parentPath.replaceWith(ast.program.body[ast.program.body.length - 1]); |
| 160 | +} |
| 161 | + |
| 162 | +module.exports = createMacro(mdxMacro); |
0 commit comments