UNPKG

2.36 kBJavaScriptView Raw
1var fs = require( 'fs' );
2var path = require( 'path' );
3var crypto = require( 'crypto' );
4var homedir = require( 'os-homedir' );
5var buble = require( './' );
6
7var original = require.extensions[ '.js' ];
8var nodeModulesPattern = path.sep === '/' ? /\/node_modules\// : /\\node_modules\\/;
9
10var nodeVersion = /(?:0\.)?\d+/.exec( process.version )[0];
11var versions = [ '0.10', '0.12', '4', '5', '6' ];
12
13if ( !~versions.indexOf( nodeVersion ) ) {
14 if ( +nodeVersion > 6 ) {
15 nodeVersion = '6';
16 } else {
17 throw new Error( 'Unsupported version (' + nodeVersion + '). Please raise an issue at https://gitlab.com/Rich-Harris/buble/issues' );
18 }
19}
20
21var options = {
22 target: {
23 node: nodeVersion
24 }
25};
26
27function mkdirp ( dir ) {
28 var parent = path.dirname( dir );
29 if ( dir === parent ) return;
30 mkdirp( parent );
31
32 try {
33 fs.mkdirSync( dir );
34 } catch ( err ) {
35 if ( err.code !== 'EEXIST' ) throw err;
36 }
37}
38
39var home = homedir();
40if ( home ) {
41 var cachedir = path.join( home, '.buble-cache', String(nodeVersion) );
42 mkdirp( cachedir );
43 fs.writeFileSync( path.join( home, '.buble-cache/README.txt' ), 'These files enable a faster startup when using buble/register. You can safely delete this folder at any time. See https://buble.surge.sh/guide/ for more information.' );
44}
45
46var optionsStringified = JSON.stringify( options );
47
48require.extensions[ '.js' ] = function ( m, filename ) {
49 if ( nodeModulesPattern.test( filename ) ) return original( m, filename );
50
51 var source = fs.readFileSync( filename, 'utf-8' );
52 var hash = crypto.createHash( 'sha256' );
53 hash.update( buble.VERSION );
54 hash.update( optionsStringified );
55 hash.update( source );
56 var key = hash.digest( 'hex' ) + '.json';
57 var cachepath = path.join( cachedir, key );
58
59 var compiled;
60
61 if ( cachedir ) {
62 try {
63 compiled = JSON.parse( fs.readFileSync( cachepath, 'utf-8' ) );
64 } catch ( err ) {
65 // noop
66 }
67 }
68
69 if ( !compiled ) {
70 try {
71 compiled = buble.transform( source, options );
72
73 if ( cachedir ) {
74 fs.writeFileSync( cachepath, JSON.stringify( compiled ) );
75 }
76 } catch ( err ) {
77 if ( err.snippet ) {
78 console.log( 'Error compiling ' + filename + ':\n---' );
79 console.log( err.snippet );
80 console.log( err.message );
81 console.log( '' )
82 process.exit( 1 );
83 }
84
85 throw err;
86 }
87 }
88
89 m._compile( '"use strict";\n' + compiled.code, filename );
90};