forked from atom/atom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabel.js
80 lines (69 loc) · 1.87 KB
/
babel.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
const crypto = require('crypto');
const path = require('path');
const defaultOptions = require('../static/babelrc.json');
let babel = null;
let babelVersionDirectory = null;
const PREFIXES = [
'/** @babel */',
'"use babel"',
"'use babel'",
'/* @flow */',
'// @flow'
];
const PREFIX_LENGTH = Math.max.apply(
Math,
PREFIXES.map(function(prefix) {
return prefix.length;
})
);
exports.shouldCompile = function(sourceCode) {
const start = sourceCode.substr(0, PREFIX_LENGTH);
return PREFIXES.some(function(prefix) {
return start.indexOf(prefix) === 0;
});
};
exports.getCachePath = function(sourceCode) {
if (babelVersionDirectory == null) {
const babelVersion = require('babel-core/package.json').version;
babelVersionDirectory = path.join(
'js',
'babel',
createVersionAndOptionsDigest(babelVersion, defaultOptions)
);
}
return path.join(
babelVersionDirectory,
crypto
.createHash('sha1')
.update(sourceCode, 'utf8')
.digest('hex') + '.js'
);
};
exports.compile = function(sourceCode, filePath) {
if (!babel) {
babel = require('babel-core');
const Logger = require('babel-core/lib/transformation/file/logger');
const noop = function() {};
Logger.prototype.debug = noop;
Logger.prototype.verbose = noop;
}
if (process.platform === 'win32') {
filePath = 'file:///' + path.resolve(filePath).replace(/\\/g, '/');
}
const options = { filename: filePath };
for (const key in defaultOptions) {
options[key] = defaultOptions[key];
}
return babel.transform(sourceCode, options).code;
};
function createVersionAndOptionsDigest(version, options) {
return crypto
.createHash('sha1')
.update('babel-core', 'utf8')
.update('\0', 'utf8')
.update(version, 'utf8')
.update('\0', 'utf8')
.update(JSON.stringify(options), 'utf8')
.digest('hex');
}