-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
executable file
·62 lines (56 loc) · 2.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env node
"use strict";
require("yargs")
.usage('$0 command')
.command('analyse', 'Analyse a JavaScript file and generate a polyfill.io URL based on all the features that are being used from within the JavaScript file.', {
file: {
string: true,
describe: 'The file that should be analysed',
demandOption: true
}
}, async function parseFile(argv) {
const generatePolyfillURL = require('./src/index.js');
const path = require('path');
const babel = require("@babel/core");
const plugin = require('@financial-times/js-features-analyser/src/index.js');
const fs = require('fs');
const os = require('os');
const promisify = require('util').promisify;
const readFile = promisify(fs.readFile);
const mkdtemp = promisify(fs.mkdtemp);
const file = path.join(process.cwd(), argv.file);
const fileContents = await readFile(file, 'utf-8');
const tempFolder = await mkdtemp(path.join(os.tmpdir(), 'js-features-analyser'));
const outputDestination = path.join(tempFolder, 'features.json');
try {
babel.transformSync(fileContents, {
plugins: [
[
plugin, {
outputDestination
}
]
],
filename: file,
ast: false,
code: false
});
console.log(await generatePolyfillURL(JSON.parse(fs.readFileSync(outputDestination, 'utf-8'))));
} catch (error) {
if (error instanceof SyntaxError) {
console.log("Failed to parse the JavaScript from xxx because it has a syntax error.")
delete error.stack;
delete error.code;
delete error.pos;
delete error.loc;
const result = /: (?<errorType>[\w ]+) \((?<position>\d+:\d+)\)/.exec(error.message);
console.log(result.groups.errorType)
error.message = error.message.replace(` ${result.groups.errorType} `, '');
error.message = error.message.replace(`(${result.groups.position})`, result.groups.position);
console.error(error.message);
}
}
})
.help()
.strict()
.argv;