1 | 'use strict';
|
2 |
|
3 | const t = require('babel-types');
|
4 | const path = require('path');
|
5 | const generate = require('babel-generator').default;
|
6 | const vm = require('vm');
|
7 |
|
8 | const canEvaluate = require('./canEvaluate');
|
9 | const canEvaluateObject = require('./canEvaluateObject');
|
10 | const getSourceModule = require('./getSourceModule');
|
11 |
|
12 | function getStaticBindingsForScope(scope, whitelist = [], sourceFileName) {
|
13 | const bindings = scope.getAllBindings();
|
14 | const ret = {};
|
15 |
|
16 | const sourceDir = path.dirname(sourceFileName);
|
17 |
|
18 | for (const k in bindings) {
|
19 | const binding = bindings[k];
|
20 |
|
21 |
|
22 | const sourceModule = getSourceModule(k, binding);
|
23 | if (sourceModule) {
|
24 | let moduleName = sourceModule.sourceModule;
|
25 |
|
26 |
|
27 | if (
|
28 | sourceModule.sourceModule.startsWith('.') ||
|
29 | sourceModule.sourceModule.startsWith('/')
|
30 | ) {
|
31 |
|
32 | if (path.extname(moduleName) === '') {
|
33 | moduleName += '.js';
|
34 | }
|
35 |
|
36 | moduleName = path.resolve(sourceDir, moduleName);
|
37 | }
|
38 |
|
39 | if (whitelist.indexOf(moduleName) > -1) {
|
40 | const src = require(moduleName);
|
41 | if (sourceModule.destructured) {
|
42 | ret[k] = src[sourceModule.imported];
|
43 | } else {
|
44 |
|
45 |
|
46 | if (src && src.__esModule) {
|
47 | ret[k] = src.default;
|
48 | } else {
|
49 | ret[k] = src;
|
50 | }
|
51 | }
|
52 | }
|
53 | continue;
|
54 | } else if (
|
55 | t.isVariableDeclaration(binding.path.parent) &&
|
56 | binding.path.parent.kind === 'const'
|
57 | ) {
|
58 |
|
59 | const dec = binding.path.parent.declarations.find(
|
60 | d => t.isIdentifier(d.id) && d.id.name === k
|
61 | );
|
62 |
|
63 | if (!dec) continue;
|
64 |
|
65 | if (
|
66 | canEvaluate(null, dec.init) ||
|
67 |
|
68 |
|
69 |
|
70 | (binding.path.parentPath.parentPath.type === 'Program' &&
|
71 | canEvaluateObject(null, dec.init))
|
72 | ) {
|
73 | ret[k] = vm.runInNewContext('(' + generate(dec.init).code + ')');
|
74 | }
|
75 | }
|
76 | }
|
77 |
|
78 | return ret;
|
79 | }
|
80 |
|
81 | module.exports = getStaticBindingsForScope;
|