|
| 1 | +/** |
| 2 | + * @fileoverview |
| 3 | + * Replaces imports of `src/config/urls` into references to self.AMP.config.urls |
| 4 | + * This allows us to re-use the value defined by the runtime in extensions. |
| 5 | + * Binaries that don't depend on the runtime should not use this transform, so |
| 6 | + * that they can directly use the values from `src/config/urls`. |
| 7 | + */ |
| 8 | +const {dirname, join, posix, relative, sep} = require('path'); |
| 9 | + |
| 10 | +const importSource = join(process.cwd(), 'src', 'config', 'urls'); |
| 11 | +const reference = 'self.AMP.config.urls'; |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {string} fromFilename |
| 15 | + * @param {string} toModule |
| 16 | + * @return {string} |
| 17 | + */ |
| 18 | +function relativeModule(fromFilename, toModule) { |
| 19 | + const resolved = relative(dirname(fromFilename), toModule); |
| 20 | + const resolvedPosix = resolved.split(sep).join(posix.sep); |
| 21 | + return resolvedPosix.startsWith('.') ? resolvedPosix : `./${resolvedPosix}`; |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {import('@babel/core')} babel |
| 26 | + * @return {import('@babel/core').PluginObj} |
| 27 | + */ |
| 28 | +module.exports = function (babel) { |
| 29 | + let importSourceRelative; |
| 30 | + const {template, types: t} = babel; |
| 31 | + const buildNamespace = template.statement( |
| 32 | + `const name = /* #__PURE__ */ (() => ${reference})()`, |
| 33 | + {preserveComments: true, placeholderPattern: /^name$/} |
| 34 | + ); |
| 35 | + return { |
| 36 | + name: 'amp-config-urls', |
| 37 | + visitor: { |
| 38 | + Program: { |
| 39 | + enter(_, state) { |
| 40 | + const {filename} = state; |
| 41 | + if (!filename) { |
| 42 | + throw new Error( |
| 43 | + 'babel-plugin-amp-config-urls must be called with a filename' |
| 44 | + ); |
| 45 | + } |
| 46 | + importSourceRelative = relativeModule(filename, importSource); |
| 47 | + }, |
| 48 | + }, |
| 49 | + ImportDeclaration(path) { |
| 50 | + const {source} = path.node; |
| 51 | + if (!t.isStringLiteral(source, {value: importSourceRelative})) { |
| 52 | + return; |
| 53 | + } |
| 54 | + for (const specifier of path.get('specifiers')) { |
| 55 | + if (!specifier.isImportNamespaceSpecifier()) { |
| 56 | + throw specifier.buildCodeFrameError( |
| 57 | + `Unresolvable specifier. You must import \`urls\` as a namespace:\n` + |
| 58 | + `\`import * as urls from '${source.value}';\`` |
| 59 | + ); |
| 60 | + } |
| 61 | + const {name} = specifier.node.local; |
| 62 | + path.replaceWith(buildNamespace({name})); |
| 63 | + } |
| 64 | + }, |
| 65 | + }, |
| 66 | + }; |
| 67 | +}; |
0 commit comments