|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +const acorn = require('acorn-node'); |
| 21 | +const walk = require('acorn-node/walk'); |
| 22 | + |
| 23 | +function find(source, opts) { |
| 24 | + const ast = acorn.parse(source, { |
| 25 | + // to parse ESM |
| 26 | + sourceType: 'module', |
| 27 | + // top level await |
| 28 | + allowAwaitOutsideFunction: true, |
| 29 | + }); |
| 30 | + |
| 31 | + const modules = []; |
| 32 | + |
| 33 | + // TODO: walk the AST and return the list of modues in |
| 34 | + // `strings` property |
| 35 | + walk.recursive(ast, null, { |
| 36 | + // import { a, b, c } from 'module'; |
| 37 | + ImportDeclaration(node) { |
| 38 | + modules.push(node.source.value); |
| 39 | + }, |
| 40 | + // export { a, b, c } from 'module'; |
| 41 | + ExportNamedDeclaration(node) { |
| 42 | + modules.push(node.source.value); |
| 43 | + }, |
| 44 | + // const x = await import('module'); |
| 45 | + ExpressionStatement(node) { |
| 46 | + if ( |
| 47 | + node.expression.type === 'AwaitExpression' && |
| 48 | + node.expression.argument.type === 'CallExpression' && |
| 49 | + node.expression.argument.callee.type === 'Import' |
| 50 | + ) { |
| 51 | + modules.push(node.expression.argument.arguments[0].value); |
| 52 | + } |
| 53 | + }, |
| 54 | + }); |
| 55 | + |
| 56 | + // Cleanup `node:` prefix for built-in modules |
| 57 | + return modules.map((m) => m.replace(/^node:/, '')); |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = function (src, opts) { |
| 61 | + return find(src, opts); |
| 62 | +}; |
0 commit comments