|
| 1 | +const {existsSync, readFileSync} = require('fs'); |
| 2 | +const LZString = require('lz-string'); |
| 3 | +const {join} = require('path'); |
| 4 | +const map = require('unist-util-map'); |
| 5 | + |
| 6 | +const PROTOCOL = 'babel-repl://'; |
| 7 | + |
| 8 | +// Matches compression used in Babel REPL |
| 9 | +// https://github.com/babel/website/blob/master/js/repl/UriUtils.js |
| 10 | +const compress = string => |
| 11 | + LZString.compressToBase64(string) |
| 12 | + .replace(/\+/g, '-') // Convert '+' to '-' |
| 13 | + .replace(/\//g, '_') // Convert '/' to '_' |
| 14 | + .replace(/=+$/, ''); // Remove ending '=' |
| 15 | + |
| 16 | +module.exports = ({markdownAST}, {directory}) => { |
| 17 | + map(markdownAST, (node, index, parent) => { |
| 18 | + if (!directory.endsWith('/')) { |
| 19 | + directory += '/'; |
| 20 | + } |
| 21 | + |
| 22 | + if (node.type === 'link' && node.url.startsWith(PROTOCOL)) { |
| 23 | + let filePath = node.url.replace(PROTOCOL, directory); |
| 24 | + if (!filePath.endsWith('.js')) { |
| 25 | + filePath += '.js'; |
| 26 | + } |
| 27 | + filePath = join(__dirname, '../..', filePath); |
| 28 | + |
| 29 | + // Verify that the specified example file exists. |
| 30 | + if (!existsSync(filePath)) { |
| 31 | + console.error( |
| 32 | + `Invalid Babel REPL link specified; no such file "${filePath}"`, |
| 33 | + ); |
| 34 | + process.exit(1); |
| 35 | + } |
| 36 | + |
| 37 | + const code = compress(readFileSync(filePath, 'utf8')); |
| 38 | + const href = `https://babeljs.io/repl/#?presets=react&code_lz=${code}`; |
| 39 | + const text = node.children[0].value; |
| 40 | + |
| 41 | + const anchorOpenNode = { |
| 42 | + type: 'html', |
| 43 | + value: `<a href="${href}" target="_blank">`, |
| 44 | + }; |
| 45 | + |
| 46 | + const textNode = { |
| 47 | + type: 'text', |
| 48 | + value: text, |
| 49 | + }; |
| 50 | + |
| 51 | + const anchorCloseNode = { |
| 52 | + type: 'html', |
| 53 | + value: '</a>', |
| 54 | + }; |
| 55 | + |
| 56 | + parent.children.splice( |
| 57 | + index, |
| 58 | + 1, |
| 59 | + anchorOpenNode, |
| 60 | + textNode, |
| 61 | + anchorCloseNode, |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + // No change |
| 66 | + return node; |
| 67 | + }); |
| 68 | +}; |
0 commit comments