/
package.js
746 lines (639 loc) · 20.9 KB
/
package.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
/*
* package.js: Utilities for working with package.json files.
*
* (C) 2010, Nodejitsu Inc.
*
*/
var fs = require('fs'),
path = require('path'),
existsSync = fs.existsSync || path.existsSync,
util = require('util'),
spawnCommand = require('spawn-command'),
zlib = require('zlib'),
async = require('flatiron').common.async,
analyzer = require('require-analyzer'),
semver = require('semver'),
jitsu = require('../jitsu'),
fstream = require('fstream'),
fstreamNpm = require('fstream-npm'),
tar = require('tar');
var package = exports;
//
// ### function get (dir, callback)
// #### @dir {string} Directory to get the package.json from
// #### @options {object} Ignored
// #### @callback {function} Continuation to respond to when complete
// Attempts to read the package.json from the specified `dir`. If it is
// unable to do, walks the user through creating a new one from scratch.
//
package.get = function (dir, options, callback) {
if (!callback) {
callback = options;
options = {};
}
package.read(dir, function (err, pkg) {
if (err) {
if (err.toString() === "Error: Invalid package.json file") {
jitsu.log.error(err.toString())
return callback(
'Please make sure ' + (path.join(dir, '/package.json')).grey + ' is valid JSON',
false,
false
);
}
return package.create(dir, callback);
}
package.validate(pkg, dir, options, function (err, updated) {
return err ? callback(err) : callback(null, updated);
});
});
};
//
// ### function read (dir, callback)
// #### @dir {string} Directory to read the package.json from
// #### @callback {function} Continuation to pass control to when complete
// Attempts to read the package.json file out of the specified directory.
//
package.read = function (dir, callback) {
var file = path.resolve(path.join(dir, 'package.json'));
fs.readFile(file, function (err, data) {
if (err) {
return callback(err);
}
data = data.toString();
if (!data.length) {
return callback(new Error('package.json is empty'));
}
try {
data = JSON.parse(data.toString());
}
catch (ex) {
return callback(new Error('Invalid package.json file'));
}
callback(null, data);
});
};
//
// ### function tryRead (dir, callback, success)
// #### @dir {string} Directory to try to read the package.json from.
// #### @callback {function} Continuation to respond to on error.
// #### @success {function} Continuation to respond to on success.
// Attempts to read the package.json file from the specified `dir`; responds
// to `callback` on error and `success` if the read operation worked.
//
package.tryRead = function (dir, callback, success) {
package.read(dir, function (err, pkg) {
return err ? callback(new Error('No package found at ' + (dir + '/package.json').grey), true) : success(pkg);
});
};
//
// ### function createPackage (dir, callback)
// #### @dir {string} Directory to create the package.json in
// #### @callback {function} Continuation to respond to when complete
// Walks the user through creating a simple package.json in the specified
// `dir` then writes to file and responds to `callback`.
//
package.create = function (dir, callback) {
var help = [
'',
'A package.json stores meta-data about your application',
'In order to continue we\'ll need to gather some information about your app',
'',
'Press ^C at any time to quit.',
'to select a default value, press ENTER'
];
jitsu.log.warn('There is no package.json file in ' + dir.grey);
jitsu.log.warn('Creating package.json at ' + (path.join(dir, '/package.json')).grey);
help.forEach(function (line) {
jitsu.log.help(line);
});
fillPackage(null, dir, function (err, pkg) {
if (err) {
return callback(err);
}
package.write(pkg, dir, true, function (err, pkg) {
if (err) {
return callback(err);
}
tryAnalyze(pkg, dir, callback);
});
});
};
//
// ### function validate (pkg, dir, callback)
// #### @pkg {Object} Parsed package.json to validate
// #### @dir {string} Directory containing the package.json file
// #### @options {object} Ignored
// #### @callback {function} Continuation to respond to when complete
// Validates the specified `pkg` against the properties list
// returned from `package.properties(dir)`.
// Also prompts the user if there are any missing properties.
//
package.validate = function (pkg, dir, options, callback) {
if (!callback) {
callback = options;
options = {};
}
var properties = package.properties(dir),
missing = [],
invalid = [];
function checkProperty (desc, next) {
var nested = desc.name.split('.'),
value = pkg[nested[0]];
if (nested.length > 1 && value) {
value = value[nested[1]];
}
// Handle missing values
if (!value) {
missing.push(desc);
}
// handle invalid values
function isValid(desc) {
if (desc.validator) {
if (desc.validator instanceof RegExp) {
return !desc.validator.test(value);
}
return !desc.validator(value);
}
return false;
}
if (value && isValid(desc)) {
if (nested.length > 1) {
delete pkg[nested[0]][nested[1]];
}
else {
delete pkg[nested[0]];
}
invalid.push(desc);
}
next();
}
async.forEach(properties, checkProperty, function () {
if (missing.length <= 0 && invalid.length <= 0) {
return tryAnalyze(pkg, dir, callback);
}
var help,
missingNames = missing.map(function (prop) {
return ' ' + (prop.message || prop.name).grey;
}),
invalidNames = invalid.map(function (prop) {
return ' ' + (prop.message || prop.name).grey;
});
help = [
''
];
if (missingNames.length) {
help = help.concat([
'Your package.json file is missing required fields:',
'',
missingNames.join(', '),
''
]);
}
if (invalidNames.length) {
help = help.concat([
'Your package.json file has invalid required fields:',
'',
invalidNames.join(', '),
''
]);
}
help = help.concat([
'Prompting user for required fields.',
'Press ^C at any time to quit.',
''
]);
help.forEach(function (line) {
jitsu.log.warn(line);
});
fillPackage(pkg, dir, function (err, pkg) {
if (err) {
return callback(err);
}
package.write(pkg, dir, true, function (err, pkg) {
return err
? callback(err)
: tryAnalyze(pkg, dir, callback);
});
});
});
};
//
// ### function writePackage (pkg, dir, callback)
// #### @pkg {Object} Data for the package.json
// #### @dir {string} Directory to write the package.json in
// #### @callback {function} Continuation to respond to when complete
// Prompts the user about writing the new package.json file. If the user
// OKs the operation, attempts to write to file. Otherwise restarts the
// create operation in the specified `dir`.
//
package.write = function (pkg, dir, create, callback) {
if (!callback) {
callback = create;
create = null;
}
delete pkg.analyzed;
jitsu.log.warn('About to write ' + path.join(dir, 'package.json').magenta);
//
// analyze and throw warnings if any dependencies have version of '*'
//
policeDependencies(pkg)
jitsu.inspect.putObject(pkg, 2);
jitsu.prompt.get([{
name: 'answer',
message: 'Is this ' + 'ok?'.green.bold,
default: 'yes'
}], function (err, result) {
if (result.answer !== 'yes' && result.answer !== 'y') {
return create ? package.create(dir, callback) : callback(new Error('Save package.json cancelled.'));
}
fs.writeFile(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2), function (err) {
return err ? callback(err) : callback(null, pkg, dir);
})
});
};
//
// ### function analyzeDependencies (pkg, dir, callback)
// #### @pkg {Object} Parsed package.json to check dependencies for.
// #### @dir {string} Directory containing the package.json file.
// #### @callback {function} Continuation to respond to when complete.
// Analyzes the dependencies in `pkg` using the `require-analyzer` module.
//
package.analyzeDependencies = function (pkg, dir, callback) {
jitsu.log.info('Analyzing your application dependencies in ' + pkg.scripts.start.magenta);
analyzer.analyze({ target: path.join(dir, pkg.scripts.start) }, function (err, pkgs) {
//
// Create a hash of `'package': '>= version'` for the new dependencies
//
var versions = analyzer.extractVersions(pkgs),
updates;
if (package.newDependencies(pkg.dependencies, versions)) {
//
// If there are new dependencies, indicate this to the user.
//
jitsu.log.info('Found new dependencies. They will be added automatically');
//
// Extract, merge, and display the updates found by `require-analyzer`
//
updates = analyzer.updates(pkg.dependencies, versions);
updates = analyzer.merge({}, updates.added, updates.updated);
jitsu.inspect.putObject(updates);
//
// Update the package.json dependencies
//
pkg.dependencies = analyzer.merge({}, pkg.dependencies || {}, updates);
}
callback(null, pkg, updates);
});
};
//
// ### function createPackage (dir, callback)
// #### @dir {string} Directory to create the package *.tgz file from
// #### @version {string} Optional version to name saved file.
// #### @callback {function} Continuation to pass control to when complete
// Creates a *.tgz package file from the specified directory `dir`.
//
package.createTarball = function (dir, version, callback) {
if (!callback) {
callback = version;
version = null;
}
package.read(dir, function (err, pkg) {
if (err) {
return callback(err);
}
if (dir.slice(-1) === '/') {
dir = dir.slice(0, -1);
}
var name = [jitsu.config.get('username'), pkg.name, version || pkg.version].join('-') + '.tgz',
tarball = path.join(jitsu.config.get('tmproot'), name);
fstreamNpm({ path: dir })
.on('error', callback)
.pipe(tar.Pack())
.on('error', callback)
.pipe(zlib.Gzip())
.on('error', callback)
.pipe(fstream.Writer({ type: "File", path: tarball }))
.on('close', function () {
callback(null, pkg, tarball);
});
});
};
//
// ### function updateTarball (version, pkg, existing, callback)
// #### @version {string} **Optional** Version to use for the updated tarball
// #### @pkg {Object} Current package.json file on disk
// #### @existing {Object} Remote package.json stored at Nodejitsu
// #### @callback {function} Continuation to respond to when complete.
//
//
package.updateTarball = function (version, pkg, existing, firstSnapshot, callback) {
if (!callback) {
callback = firstSnapshot;
firstSnapshot = false;
}
function executeCreate (err) {
if (err) {
return callback(err, true);
}
version = version || pkg.version;
jitsu.package.createTarball(process.cwd(), version, function (err, ign, filename) {
if (err) {
return callback(err, true)
}
jitsu.log.info('Creating snapshot ' + version.grey);
jitsu.log.silly('Filename: ' + filename);
fs.stat(filename, function (err, stat) {
if (err) return callback(err);
// XXX Is 50mb enough? Please warning message
if (stat.size > 50 * 1024 * 1024) {
jitsu.log.warn('You\'re trying to upload snapshot larger than ' + '50M'.magenta + '.');
jitsu.log.warn('This is not recommended practice.');
}
jitsu.snapshots.create(pkg.name, version, filename, function (err, snapshots) {
jitsu.log.silly('Done creating snapshot ' + version.magenta);
return err ? callback(err) : callback(null, version, pkg);
});
});
});
}
var old = false;
if (!firstSnapshot) {
jitsu.log.silly('Existing version: ' + existing.version.magenta);
jitsu.log.silly('Local version: ' + pkg.version.magenta);
var old = semver.gte(existing.version, pkg.version);
if (old) {
//
// If the existing version is greater than the version in the
// package.json file on disk, update it and then write back to disk.
//
jitsu.log.warn('Local version appears to be old');
jitsu.log.warn('Your ' + 'package.json'.grey + ' version will be incremented for you automatically');
//
// Check for release args then .jitsuconf or default to 'build'
//
var release = jitsu.argv.release || jitsu.config.get('release') || 'build';
//
// Pattern matching to see if release is version number or type
// If is version number, set release to version number specified
//
if (jitsu.argv.release) {
if(typeof(jitsu.argv.release) == 'string') {
var releaseIsVersionNumber = jitsu.argv.release.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)/g);
if (releaseIsVersionNumber) {
pkg.version = jitsu.argv.release;
} else {
pkg.version = semver.inc(existing.version, release);
}
}
//
// if no release argument specified use .jitsuconf
//
} else {
pkg.version = semver.inc(existing.version, release);
}
//
// Default to build if user inputs as -r arg something ridiculous
//
if (pkg.version == null) {
pkg.version = semver.inc(existing.version, jitsu.config.get('release') || 'build');
}
}
}
return old
? package.write(pkg, process.cwd(), executeCreate)
: executeCreate();
};
//
// ### function newDependencies (current, updated)
// #### @current {Object} Set of current dependencies
// #### @updated {Object} Set of updated dependencies
// Returns a value indicating if there are any new dependencies
// in `updated` as compared to `current`.
//
package.newDependencies = function (current, updated) {
var updates = analyzer.updates(current, updated);
return Object.keys(updates.added).length > 0 || Object.keys(updates.updated).length > 0;
};
//
// ### function properties (dir)
// #### @dir {string} Directory in which the package.json properties are being used
// Returns a new set of properties to be consumed by `jitsu.prompt` to walk a user
// through creating a new `package.json` file.
//
package.properties = function (dir) {
return [
{
name: 'name',
unique: true,
message: 'App name',
validator: /[\w|\-]+/,
default: path.basename(dir)
},
{
name: 'subdomain',
unique: true,
validator: /[\w|\-|\_]+/,
help: [
'',
'The ' + 'subdomain '.grey + 'is where your application will reside.',
'Your application will then become accessible at: http://' + 'yourdomain'.grey + '.jit.su',
''
],
default: jitsu.config.get('username') + '.' + path.basename(dir)
},
{
name: 'scripts.start',
message: 'scripts.start',
conform: function (script) {
//
// Support `scripts.start` starting with executable (`node` or `coffee`).
//
var split = script.split(' ');
if (~['node', 'coffee'].indexOf(split[0])) {
script = split.slice(1).join(' ');
}
try {
fs.statSync(path.join(dir, script));
return true;
}
catch (ex) {
return false;
}
},
warning: 'Start script was not found in ' + dir.magenta,
default: searchStartScript(dir)
},
{
name: 'version',
unique: false,
conform: semver.valid,
default: '0.0.0'
},
{
name: 'engines.node',
unique: false,
message: 'engines',
conform: semver.validRange,
default: (function () {
//
// Use `process.version` to determine the most suitable node version.
// Strip 'v' from the first part (`process.version` begins with 'v'),
// return stable version not greater than current version, wildcard
// patch version.
//
var v = process.version.split('.'),
main = v[0].substr(1),
minor = '6',//v[1] % 2 === 0 ? v[1] : v[1] - 1,
patch = 'x';
return [main, minor, patch].join('.');
})()
}
];
};
//
// ### function available (pkg, dir, callback, createPackage)
// #### @pkg {Object} Current package.json file on disk
// #### @dir {string} Directory in which the package.json properties are being used
// #### @callback {function} Continuation to respond to when complete.
// #### @createPackage {function} Function needed to make it recursive
// Prompts for appname and subdomain until the combination is available
//
package.available = function (pkg, dir, callback, createPackage) {
jitsu.apps.available(pkg, function (err, isAvailable) {
var props, fields = [];
if (err) {
jitsu.log.error('There was an error while checking app name / subdomain availability.');
return callback(err);
}
if (!isAvailable.available) {
if (isAvailable.appname === false) {
delete pkg.name;
fields.push('name');
}
if (isAvailable.subdomain === false) {
delete pkg.subdomain;
fields.push('subdomain');
}
props = package.properties(dir).filter(function (p) {
return fields.indexOf(p.name) !== -1;
});
//
// auto-suggest a new domain field based on username
//
for (var p in props) {
if(props[p].name === 'subdomain') {
props[p].default = props[p].default + '.' + jitsu.config.get('username');
}
}
if (fields.indexOf('name') !== -1) {
jitsu.log.error('The application name you have requested is already in use.');
}
if (fields.indexOf('subdomain') !== -1) {
jitsu.log.error('The subdomain you have requested is already in use.');
}
jitsu.prompt.addProperties(pkg, props, createPackage);
return;
}
callback(null, pkg);
});
}
package.runScript = function (pkg, action, callback) {
var command = pkg.scripts[action];
if (!command) {
//
// If there's no such script, it's all fine.
//
return callback();
}
var child = spawnCommand(command, {
customFds: [0, 1, 2]
});
child.on('exit', function (code) {
if (code !== 0) {
return callback(new Error('`' + command + '` exited with code ' + code));
}
callback();
});
};
function searchStartScript(dir) {
var scripts = ['server.js', 'bin/server', 'app.js', 'index.js'];
for (i in scripts) {
if (existsSync(path.join(dir, scripts[i]))) {
return scripts[i];
}
}
}
function tryAnalyze (target, dir, callback) {
if (target.analyzed) {
return callback(null, target);
}
var noanalyze = !((jitsu.config.get('analyze') === 'true')
|| (jitsu.config.get('analyze') === true))
|| ((jitsu.config.get('noanalyze') === 'true')
|| (jitsu.config.get('noanalyze') === true))
|| ((target.analyze === 'false')
|| (target.analyze === false));
if (noanalyze) {
jitsu.log.info('Skipping require-analyzer because ' + 'noanalyze'.magenta + ' option is set');
return callback(null, target);
}
package.analyzeDependencies(target, dir, function (err, addedDeps, updates) {
if (err) {
return callback(err);
}
target.analyzed = true;
return updates
? package.write(addedDeps, dir, true, callback)
: callback(null, addedDeps);
});
}
function policeDependencies (pkg) {
dependencies = pkg.dependencies;
for (var key in dependencies) {
if (dependencies[key].toString().match(/(\*)/)) {
jitsu.log.warn('Using \'*\' as version for dependencies may eventually cause issues.');
jitsu.log.warn('Please use specific versions for dependencies to avoid future problems.');
return false;
}
}
}
function fillPackage (base, dir, callback) {
base = base || {};
var subdomain, descriptors, missing;
missing = ['name', 'subdomain', 'version'].filter(function (prop) {
return !base[prop]
});
if (!(base.scripts && base.scripts.start)) {
missing.push('scripts.start');
}
if (!(base.engines && base.engines.node)){
missing.push('engines.node');
}
descriptors = package.properties(dir).filter(function (descriptor) {
if (descriptor.name == 'subdomain') {
subdomain = descriptor;
}
return missing.indexOf(descriptor.name) !== -1;
});
jitsu.prompt.addProperties(base, descriptors, function createPackage (err, result) {
if (err) {
//
// TODO: Something here...
//
jitsu.log.error('Unable to add properties to package description.');
jitsu.log.error(require('util').inspect(err));
return callback(err);
}
var isUnique = descriptors.filter(function (descriptor) {
return descriptor.unique;
}).length;
result.scripts = result.scripts || {};
if (isUnique) {
package.available(result, dir, callback, createPackage);
}
else {
callback(null, result); // TODO
}
});
}