-
Notifications
You must be signed in to change notification settings - Fork 0
/
babel.js
68 lines (58 loc) · 1.67 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
'use strict'
var crypto = require('crypto')
var path = require('path')
var defaultOptions = require('../static/babelrc.json')
var babel = null
var babelVersionDirectory = null
var PREFIXES = [
'/** @babel */',
'"use babel"',
'\'use babel\'',
'/* @flow */'
]
var PREFIX_LENGTH = Math.max.apply(Math, PREFIXES.map(function (prefix) {
return prefix.length
}))
exports.shouldCompile = function (sourceCode) {
var start = sourceCode.substr(0, PREFIX_LENGTH)
return PREFIXES.some(function (prefix) {
return start.indexOf(prefix) === 0
})
}
exports.getCachePath = function (sourceCode) {
if (babelVersionDirectory == null) {
var 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')
var Logger = require('babel-core/lib/transformation/file/logger')
var noop = function () {}
Logger.prototype.debug = noop
Logger.prototype.verbose = noop
}
var options = {filename: filePath}
for (var 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')
}