-
Notifications
You must be signed in to change notification settings - Fork 58
/
build.js
353 lines (285 loc) · 9.16 KB
/
build.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
var fs = require( 'fs' );
var { rollup } = require( 'rollup' );
var buble = require( '@rollup/plugin-buble' );
var UglifyJS = require( 'uglify-js' );
var UglifyES = require( 'uglify-es' );
var replace = require( 'rollup-plugin-replace' );
var commonjs = require( 'rollup-plugin-commonjs' );
var nodeResolve = require( 'rollup-plugin-node-resolve' );
var program = require( 'commander' );
var version = require('./package.json').version;
program
.version( version )
.option('-b, --browser', 'generate browser version (node is default)' )
.option('-e, --es6', 'export es6 code' )
.option('-m, --minify', 'minify output' )
.option('-u, --umd', 'export UMD Bundle (optional for es6 builds)' )
.option('-p, --polyfill', 'add polyfills (for Promise and Object.assign)' )
.parse( process.argv );
var env = program.browser ? 'browser' : 'node';
var isBrowser = env === 'browser';
var es5Build = ! program.es6 || env === 'node';
var minifyBuild = !! program.minify;
var bundleUMD = !! program.umd;
var polyfill = !! program.polyfill;
var globalPath = 'src/';
var buildPaths = [ 'dist/' ];
var minifyExtension = 'min';
var es6Extension = 'es6';
var umdExtension = 'umd';
var moduleName = 'glitch';
var fileName = 'glitch-canvas-{APPENDIX}';
var mainFilePath = isBrowser ? 'browser.js' : 'index.js';
if ( isBrowser ) {
buildPaths.push( 'glitch-canvas-browser/' );
}
var stringsToReplace = {
browser: {
"import Canvas from './node-canvas.js'": "import Canvas from './browser.js'",
"// PROMISE_POLYFILL_HERE": ''
},
node: {
"import Canvas from 'canvas'": "var Canvas = require( 'canvas' );"
}
};
if ( polyfill ) {
stringsToReplace.browser[ 'const objectAssign = Object.assign' ] = "import objectAssign from 'object-assign'";
var promisePolyfillStr = `
import p from 'es6-promise';
p.polyfill();
`;
stringsToReplace.browser[ '// PROMISE_POLYFILL_HERE' ] = promisePolyfillStr;
}
console.log( 'building with options: env:', env, 'es6:', ! es5Build, 'minify:', minifyBuild, 'umd', bundleUMD );
buildPaths.forEach( buildPath => {
createES6Bundle( globalPath + mainFilePath, buildPath )
.then( fileContent => {
console.log( 'build complete. file saved to ' + buildPath + getOutputFileName( mainFilePath ) );
} );
} );
function createES6Bundle ( filePath, buildPath ) {
const format = ( es5Build || bundleUMD ) ? 'umd' : 'es';
return processES6File( filePath, format, moduleName )
.then( fileContent => {
return processFileContent( fileContent );
} )
.then( fileContent => {
return saveFile( buildPath + getOutputFileName( mainFilePath ), fileContent );
} );
}
function processES6File ( filePath, format = 'es', moduleName ) {
const rollupPlugins = [ ];
if ( stringsToReplace[env] && Object.keys( stringsToReplace[env] ).length ) {
const replaceOptions = {
values: stringsToReplace[env],
delimiters: [ '', '' ]
};
rollupPlugins.push( replace( replaceOptions ) );
}
rollupPlugins.push(
nodeResolve(),
commonjs()
);
if ( es5Build ) {
rollupPlugins.push( buble() );
}
const rollupOptions = {
input: filePath,
plugins: rollupPlugins
};
return rollup( rollupOptions )
.then( bundle => {
const bundleOpts = { format };
if ( moduleName ) {
bundleOpts.name = moduleName;
}
return bundle.generate( bundleOpts )
.then( bundleData => {
return bundleData.output[0].code;
} );
} );
}
function processFileContent ( fileContent ) {
return replaceImportedScripts ( fileContent )
.then( fileContent => {
return isBrowser ? workersToBlobURL( fileContent ) : workersToWorkerFunction( fileContent );
} )
.then( fileContent => {
if ( minifyBuild ) {
return compressFileContent( fileContent );
} else {
return fileContent;
}
} );
}
function loadFile ( path ) {
return new Promise( function ( resolve, reject ) {
fs.readFile( path, 'utf8', ( err, data ) => {
if ( err ) {
reject( err );
} else {
resolve( data );
}
} );
} );
}
function saveFile ( filePath, fileContent ) {
return new Promise( function ( resolve, reject ) {
fs.writeFile( filePath, fileContent, 'utf8', ( err, res ) => {
if ( err ) {
reject( err );
} else {
resolve( fileContent );
}
} );
} );
}
function compressFileContent ( fileContent ) {
let res;
if ( es5Build ) {
res = UglifyJS.minify( fileContent );
} else {
res = UglifyES.minify( fileContent );
}
if ( res.error ) {
console.log( res.error );
}
return res.code;
}
function replaceImportedScripts ( fileContent ) {
let scriptPaths = getImportedScriptPaths( fileContent );
let loadScripts = scriptPaths.map( ( scriptPath ) => {
return loadFile( globalPath + scriptPath );
} );
return Promise.all( loadScripts )
.then( ( scriptContents, scriptIndex ) => {
return scriptContents.reduce( ( fileContent, scriptContent, scriptContentIndex ) => {
return replaceImportedScript ( fileContent, scriptPaths[scriptContentIndex], scriptContent );
}, fileContent );
} );
}
function workersToBlobURL ( fileContent ) {
const workerPaths = getWorkerPaths( fileContent );
return Promise.all( workerPaths.map( ( workerPath ) => {
const p = workerPath.indexOf( globalPath ) === 0 ? workerPath : globalPath + workerPath;
return processES6File( p );
// return processWorkerFile( p );
} ) )
.then( ( workerContents ) => {
return workerContents.map( ( workerContent, index ) => {
return fileToBlobURL( workerContent );
} );
} )
.then( ( blobURLs ) => {
return blobURLs.reduce( ( fileContent, blobUrl, workerIndex ) => {
let sanitizedScriptPath = sanitizePathForRegEx( workerPaths[workerIndex] );
let pattern = "[\'\"]" + sanitizedScriptPath + '[\'\"]';
let regex = new RegExp( pattern, 'mig' );
return fileContent.replace( regex, blobUrl );
}, fileContent );
} );
}
function workersToWorkerFunction ( fileContent ) {
const workerPaths = getWorkerPaths( fileContent );
return Promise.all( workerPaths.map( ( workerPath ) => {
const p = workerPath.indexOf( globalPath ) === 0 ? workerPath : globalPath + workerPath;
return processES6File( p );
} ) )
.then( ( workerContents ) => {
return workerContents.map( ( workerContent, index ) => {
return fileToWorkerFunction( workerContent );
} );
} )
.then( ( workerFunctionStrings ) => {
return workerFunctionStrings.reduce( ( fileContent, workerFunctionString, workerIndex ) => {
let sanitizedScriptPath = sanitizePathForRegEx( workerPaths[workerIndex] );
let pattern = "[\'\"]" + sanitizedScriptPath + '[\'\"]';
let regex = new RegExp( pattern, 'mig' );
return fileContent.replace( regex, workerFunctionString );
}, fileContent );
} );
}
function fileToBlobURL ( fileContent, type = 'text/javascript' ) {
if ( minifyBuild ) {
fileContent = compressFileContent( fileContent );
}
const fileContentStr = JSON.stringify( fileContent );
return "URL.createObjectURL(new Blob([" + fileContentStr + "],{type:'" + type + "'}))";
}
function fileToWorkerFunction ( fileContent ) {
if ( minifyBuild ) {
fileContent = compressFileContent( fileContent );
}
return "function(){\n" + fileContent + "\n}";
}
function getWorkerPaths ( fileContent ) {
// let regex = /[\'\”](.*Worker.js)[\'\”]/mig;
const regex = /new Worker\s?\(\s?([\"\'][a-zA-Z0-9\/.+=-]+)[\"\']\s?\)/g;
let matches;
let result = [ ];
while ( ( matches = regex.exec( fileContent ) ) !== null ) {
// This is necessary to avoid infinite loops with zero-width matches
if ( matches.index === regex.lastIndex ) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
matches.forEach( ( match, groupIndex ) => {
if ( groupIndex === 1 ) {
result.push( match );
}
} );
}
return result.map( path => {
return path.replace( /[\'\"]/g, '' );
});
}
function getImportedScriptPaths ( fileContent ) {
// let regex = /(importScripts|\(|"|')([a-zA-Z0-9\/\_\-]*\.js)/mig;
let regex = /importScripts\([\"\'\s]+([a-zA-Z0-9\/\_\-]*\.js)[\"\'\s]+\)/mig;
let matches;
let result = [ ];
while ( ( matches = regex.exec( fileContent ) ) !== null ) {
// This is necessary to avoid infinite loops with zero-width matches
if ( matches.index === regex.lastIndex ) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
matches.forEach( ( match, groupIndex ) => {
if ( groupIndex === 1 ) {
result.push( match );
}
} );
}
return result;
}
function replaceImportedScript ( fileContent, scriptPath, scriptContent ) {
let sanitizedScriptPath = sanitizePathForRegEx( scriptPath );
let pattern = 'importScripts.*' + sanitizedScriptPath + '*.*\;';
let regex = new RegExp( pattern, 'mig' );
let res = fileContent.replace( regex, scriptContent );
return res;
}
function sanitizePathForRegEx ( path ) {
return path
.replace( /\//g, '\\/' )
.replace( /\-/g, '\\-' )
.replace( /\(/g, '\\(' )
.replace( /\"/g, '\\"' )
.replace( /\./g, '\\.' );
}
function getOutputFileName ( filePath ) {
let appendix = env;
if ( polyfill ) {
appendix += '-with-polyfills';
}
if ( ! es5Build && es6Extension && es6Extension.length ) {
appendix += '.' + es6Extension;
}
if ( bundleUMD && ! es5Build ) {
appendix += '.' + umdExtension;
}
if ( minifyBuild ) {
appendix += '.' + minifyExtension;
}
return fileName.replace( '{APPENDIX}', appendix ) + '.js';
}