This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
utils-node.js
600 lines (519 loc) · 16.7 KB
/
utils-node.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
'use strict';
/**
* This file contains all Node.js version of utils functions.
* Since we're stil in the progress to migrate to Node.js, the
* missing functions in this file should be in the 'utils-xpc.js'
*
* About documents:
* Users can find comments in the 'utils-xpc.js',
* which contains the complete functions used in 'utils.js'
*/
var utils = require('./utils.js');
var path = require('path');
var childProcess = require('child_process');
var fs = require('fs-extra');
var JSZip = require('jszip');
var Q = require('q');
var os = require('os');
var vm = require('vm');
var http = require('http');
var https = require('https');
var url = require('url');
var dive = require('diveSync');
var nodeUUID = require('node-uuid');
var jsdom = require('jsdom-nogyp');
var esprima = require('esprima');
var procRunning = require('is-running');
var mime = require('mime');
// Our gecko will transfer .opus file to audio/ogg datauri type.
mime.define({'audio/ogg': ['opus']});
// jsdom-nogyp has not defined Setter for outerHTML, so we need to set it by
// ourselves.
jsdom.dom.level3.html.Element.prototype.__defineSetter__('outerHTML',
function(html) {
var parentNode = this.parentNode, el;
var all = this.ownerDocument.createElement('div');
all.innerHTML = html;
while (el === all.firstChild) {
parentNode.insertBefore(el, this);
}
parentNode.removeChild(this);
});
module.exports = {
Q: Q,
scriptParser: esprima,
log: function() {
var args = Array.prototype.slice.call(arguments);
if (!args.length) {
console.log('\n');
return;
}
console.log('[' + args[0] + '] ' + args.slice(1).join(' '));
},
normalizePath: function(string) {
return path.normalize(string);
},
joinPath: function() {
return path.join.apply(path, arguments);
},
getOsType: function() {
var type = os.type();
return type === 'Windows_NT' ? 'WINNT' : type;
},
relativePath: function(from, to) {
return path.relative(from, to);
},
getFile: function() {
var self = module.exports;
var src = path.join.apply(path, arguments);
var fileStat;
try {
fileStat = fs.statSync(src);
} catch (e) {
// In order to have compability with xpcshell interface,
// we just simply let fileStat undefined and don't need
// to do anything here.
}
return {
exists: function() {
return self.fileExists(src);
},
remove: function() {
fs.removeSync(src);
},
isDirectory: function() {
return !!fileStat && fileStat.isDirectory();
},
isFile: function() {
return !!fileStat && fileStat.isFile();
},
isHidden: function() {
return /^\./.test(path.basename(src));
},
path: src,
leafName: path.basename(src)
};
},
getFileContent: function(file, type) {
if (file.exists() && file.isFile()) {
return fs.readFileSync(file.path, { encoding: type || 'utf8' });
}
},
Commander: function(cmd) {
this.initPath = function() {};
this.run = function(args, callback) {
var q = Q.defer();
var cmds = args.join(' ');
// In *nix and OSX version commands are run via sh -c YOUR_COMMAND,
// but in Windows commands are run via cmd /C YOUR_COMMAND,
// so, we just let execSync module to handle the difference.
if (cmd === 'sh') {
cmds = cmds.replace(/^-c/, '');
} else {
cmds = cmd + ' ' + cmds;
}
console.log(cmds);
// XXX: Most cmds should run synchronously, we should use either promise
// pattern inside each script or find a sync module which doesn't
// require recompile again since TPBL doesn't support that.
childProcess.exec(cmds,
{ maxBuffer: (4096 * 1024) },
function(err, stdout) {
if (err === null && typeof callback === 'function') {
callback(stdout);
}
q.resolve();
});
return q.promise;
};
},
readZipManifest: function(file) {
var zipPath = this.joinPath(file.path, 'application.zip');
if (!this.fileExists(zipPath)) {
return;
}
var manifest = new JSZip(fs.readFileSync(zipPath)).file('manifest.webapp');
if (!manifest) {
throw new Error('manifest.webapp not found in ' + zipPath);
}
return JSON.parse(manifest.asText());
},
killAppByPid: function(appName) {
childProcess.exec('adb shell b2g-ps', function(err, stdout) {
if (!err && stdout) {
var psMap = utils.psParser(stdout);
if (psMap[appName] && psMap[appName].PID) {
childProcess.exec('adb shell kill ' + psMap[appName].PID);
}
}
});
},
spawnProcess: function(module, appOptions) {
this.exitCode = null;
var args = [
'--harmony',
'-e', 'require("' + module + '").execute("' + JSON.stringify(appOptions)
.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '");'
];
var proc = childProcess.spawn('node', args);
proc.on('close', function(code) {
this.exitCode = code;
}.bind(this));
return proc;
},
processIsRunning: function(proc) {
return procRunning(proc.pid);
},
getProcessExitCode: function() {
return this.exitCode;
},
resolve: function(relativePath, gaiaDir) {
var absPath;
if (relativePath[0] === '/') {
absPath = relativePath;
} else {
absPath = path.join(gaiaDir, relativePath);
}
return this.getFile(absPath);
},
getFileAsDataURI: function(file) {
var data = this.getFileContent(file, 'base64');
return 'data:' + mime.lookup(file.path) + ';base64,' + data;
},
getJSON: function(file) {
var content = this.getFileContent(file);
try {
return JSON.parse(content);
} catch (error) {
console.log('Invalid JSON file : ' + file.path + '\n');
if (content) {
console.log('Content of JSON file:\n' + content + '\n');
}
throw error;
}
},
getDocument: function(content) {
// In order to use document.querySelector, we have to pass level for
// jsdom-nogyp.
return jsdom.jsdom(content, jsdom.level(3, 'core'));
},
getXML: function(file) {
return jsdom.jsdom(this.getFileContent(file));
},
getEnv: function(name) {
return process.env[name];
},
setEnv: function(name, value) {
process.env[name] = value;
},
getEnvPath: function() {
return process.env.PATH.split(path.delimiter);
},
getTempFolder: function(dirName) {
var tmpPath = path.join(os.tmpdir(), dirName);
fs.mkdirpSync(tmpPath);
return this.getFile(tmpPath);
},
ensureFolderExists: function(file) {
fs.mkdirpSync(file.path);
},
normalizeString: function(appname) {
return appname.replace(' ', '-').toLowerCase().replace(/\W/g, '');
},
ls: function(dir, recursive) {
var files = [];
if (!dir || !dir.exists()) {
return [];
}
dive(dir.path, { recursive: recursive }, function(err, filePath) {
if (err) {
// Skip error
return;
}
files.push(this.getFile(filePath));
}.bind(this));
return files;
},
download: function(fileUrl, dest, callback, errorCallback) {
var protocol = url.parse(fileUrl).protocol;
var request = (protocol === 'http:') ? http : https;
var file = fs.createWriteStream(dest);
request.get(fileUrl, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(callback);
});
}).on('error', function(err) {
fs.unlinkSync(dest);
if (errorCallback) {
errorCallback();
}
});
},
downloadJSON: function(fileUrl, callback) {
var protocol = url.parse(fileUrl).protocol;
var request = (protocol === 'http:') ? http : https;
request.get(fileUrl, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
if (callback) {
callback(JSON.parse(body));
}
});
}).on('error', function(e) {
throw new Error('Download JSON with error: ' + e);
});
},
readJSONFromPath: function(path) {
return require(path);
},
concatenatedScripts: function(scriptsPaths, targetPath) {
var concatedScript = scriptsPaths.map(function(path) {
return this.getFileContent(this.getFile(path));
}, this).join('\n');
var targetFile = this.getFile(targetPath);
this.ensureFolderExists(targetFile.parent);
this.writeContent(targetFile, concatedScript);
},
getDistributionFileContent: function(name, defaultContent, distDir) {
if (distDir) {
let distributionFile = this.getFile(distDir, name + '.json');
if (distributionFile.exists()) {
return this.getFileContent(distributionFile);
}
}
return JSON.stringify(defaultContent, null, ' ');
},
getUUIDMapping: function(config) {
var UUIDMapping = this.UUIDMapping;
if (UUIDMapping) {
return UUIDMapping;
}
this.UUIDMapping = UUIDMapping = {};
// Try to retrieve it from $GAIA_DISTRIBUTION_DIR/uuid.json if exists.
try {
var uuidFile = this.getFile(config.GAIA_DISTRIBUTION_DIR, 'uuid.json');
if (uuidFile.exists()) {
console.log('uuid.json in GAIA_DISTRIBUTION_DIR found.');
UUIDMapping = JSON.parse(this.getFileContent(uuidFile));
}
} catch (e) {
// ignore exception if GAIA_DISTRIBUTION_DIR does not exist.
}
return UUIDMapping;
},
getWebapp: function(app, config) {
let appDir = this.getFile(app);
if (!appDir.exists()) {
throw new Error(' -*- build/utils.js: file not found (' + app + ')\n');
}
let manifestFile = appDir.path + '/manifest.webapp';
let updateFile = appDir.path + '/update.webapp';
// Ignore directories without manifest
if (!this.fileExists(manifestFile) && !this.fileExists(updateFile)) {
return;
}
let manifest = this.fileExists(manifestFile) ? manifestFile : updateFile;
let manifestJSON = this.getJSON(this.getFile(manifest));
// Use the folder name as the the domain name
let appDomain = appDir.leafName + '.' + config.GAIA_DOMAIN;
if (manifestJSON.origin) {
appDomain = this.getNewURI(manifestJSON.origin).host;
}
let self = this;
let webapp = {
appDirPath: appDir.path,
manifest: manifestJSON,
manifestFilePath: manifest,
url: config.GAIA_SCHEME + appDomain,
domain: appDomain,
sourceDirectoryFilePath: appDir.path,
sourceDirectoryName: appDir.leafName,
sourceAppDirectoryName: self.getFile(appDir.path, '..').leafName
};
// External webapps have a `metadata.json` file
let metaData = this.getFile(webapp.sourceDirectoryFilePath,
'metadata.json');
if (metaData.exists()) {
webapp.pckManifest = this.readZipManifest(appDir);
webapp.metaData = this.getJSON(metaData);
webapp.appStatus = utils.getAppStatus(webapp.metaData.type || 'web');
} else {
webapp.appStatus = utils.getAppStatus(webapp.manifest.type);
}
// Some webapps control their own build
webapp.buildDirectoryFilePath = this.joinPath(config.STAGE_DIR,
webapp.sourceDirectoryName);
webapp.buildManifestFilePath = this.joinPath(webapp.buildDirectoryFilePath,
'manifest.webapp');
// Generate the webapp folder name in the profile. Only if it's privileged
// and it has an origin in its manifest file it'll be able to specify a
// custom folder name. Otherwise, generate an UUID to use as folder name.
var webappTargetDirName;
if (this.isExternalApp(webapp)) {
var type = webapp.appStatus;
var isPackaged = false;
if (webapp.pckManifest) {
isPackaged = true;
if (webapp.metaData.origin) {
throw new Error('External webapp `' + webapp.sourceDirectoryName +
'` can not have origin in metadata because is packaged');
}
}
if (type === 2 && isPackaged && webapp.pckManifest.origin) {
webappTargetDirName = this.getNewURI(webapp.pckManifest.origin).host;
} else {
// uuid is used for webapp directory name, save it for further usage
let mapping = this.getUUIDMapping(config);
var uuid = mapping[webapp.sourceDirectoryName] ||
'{' + nodeUUID.v4() + '}';
mapping[webapp.sourceDirectoryName] = webappTargetDirName = uuid;
}
} else {
webappTargetDirName = webapp.domain;
}
webapp.profileDirectoryFilePath = this.joinPath(config.COREWEBAPPS_DIR,
'webapps',
webappTargetDirName);
return webapp;
},
getNewURI: function(uri) {
var result = url.parse(uri);
result.prePath = result.protocol + '//' + result.host;
return result;
},
isExternalApp: function(webapp) {
if (webapp.metaData && webapp.metaData.external === undefined) {
throw new Error('"external" property in metadata.json is required ' +
'since Firefox OS 2.1, please add it into metadata.json and update ' +
'preload.py if you use this script to perload your apps. If you ' +
'created metadata.json for non-external apps, please set "external" ' +
'to false. metadata.json is in ' + webapp.sourceDirectoryFilePath);
}
if (!webapp.metaData || webapp.metaData.external === false) {
return false;
} else {
return true;
}
},
processEvents: function() {
},
writeContent :function(file, content) {
fs.writeFileSync(file.path, content);
},
createZip: function() {
return new JSZip();
},
getCompression: function(type) {
switch(type) {
case 'none':
return 'STORE';
case 'best':
return 'DEFLATE';
}
},
addFileToZip: function(zip, pathInZip, file, compression) {
if (!file.exists()) {
return;
}
zip.file(pathInZip, fs.readFileSync(file.path), {
compression: compression || 'DEFLATE'
});
},
hasFileInZip: function(zip, pathInZip) {
return zip.file(pathInZip);
},
closeZip: function(zip, zipPath) {
fs.writeFileSync(zipPath, zip.generate({
type: 'nodebuffer',
platform: process.platform
}));
},
getLocaleBasedir: function(src) {
return os.type() === 'Windows_NT' ? src.replace('/', '\\', 'g') : src;
},
deleteFile: function(filePath) {
fs.removeSync(filePath);
},
fileExists: function(path) {
return fs.existsSync(path);
},
listFiles: function(path, type, recursive, exclude) {
var file = (typeof path === 'string' ? this.getFile(path) : path);
if (!file.isDirectory()) {
throw new Error('The path is not a directory.');
}
var files = this.ls(file, recursive === true, exclude);
var detectFunc = (type === 0 ? 'isFile' : 'isDirectory');
// To return simple JavaScript type, We need to put the file path to the
// array instead of nsIFile.
var results = [];
files.forEach(function(file) {
if (file[detectFunc]()) {
results.push(file.path);
}
});
return results;
},
mkdirs: function(path) {
fs.mkdirpSync(path);
},
dirname: function(filePath) {
return path.dirname(filePath);
},
basename: function(filePath) {
return path.basename(filePath);
},
existsInAppDirs: function(appDirs, appName) {
var apps = appDirs.split(' ');
var exists = apps.some(function (appPath) {
let appFile = this.getFile(appPath);
return (appName === appFile.leafName);
}, this);
return exists;
},
copyFileTo: function(filePath, toParent, name) {
var file = ((typeof filePath === 'string') ?
this.getFile(filePath) : filePath);
fs.copySync(file.path, path.join(toParent, name));
},
copyDirTo: function(filePath, toParent, name) {
var file = ((typeof filePath === 'string') ?
this.getFile(filePath) : filePath);
fs.copySync(file.path, path.join(toParent, name));
},
copyToStage: function(options) {
var appDir = this.getFile(options.APP_DIR);
this.copyDirTo(appDir, options.STAGE_DIR, appDir.leafName);
},
exit: function(code) {
process.exit(code);
},
scriptLoader: {
scripts: {},
load: function(filePath, exportObj, withoutCache) {
if (!withoutCache && this.scripts[filePath]) {
return;
}
var doc = jsdom.jsdom();
var win = doc.defaultView;
exportObj.Promise = Q;
global.addEventListener = win.addEventListener;
global.dispatchEvent = win.dispatchEvent;
for (let key in exportObj) {
global[key] = exportObj[key];
}
try {
var script = fs.readFileSync(filePath, { encoding: 'utf8' });
vm.runInThisContext(script, filePath);
this.scripts[filePath] = true;
} catch(error) {
delete this.scripts[filePath];
throw error;
}
}
}
};