-
Notifications
You must be signed in to change notification settings - Fork 134
/
vantage.js
executable file
·1214 lines (1054 loc) · 30.5 KB
/
vantage.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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Module dependencies.
*/
var _ = require("lodash")
, EventEmitter = require("events").EventEmitter
, Command = require("./command")
, VantageServer = require("./server")
, VantageClient = require("./client")
, VantageUtil = require("./util")
, intercept = require("./intercept")
, commons = require("./vantage-commons")
, inquirer = require("inquirer")
, minimist = require("minimist")
;
/**
* Vantage prototype.
*/
var vantage = Vantage.prototype;
/**
* Expose `Vantage`.
*/
exports = module.exports = Vantage;
/**
* Extend Vantage prototype as an event emitter.
*/
Vantage.prototype.__proto__ = EventEmitter.prototype;
/**
* Initialize a new `Vantage` instance.
*
* @return {Vantage}
* @api public
*/
function Vantage() {
if (!(this instanceof Vantage)) return new Vantage;
// Program version
// Exposed through vantage.version(str);
this._version = "";
// Registered `vantage.command` commands and
// their options.
this.commands = [];
// Prompt delimiter.
// Exposed through vantage.delimiter(str).
this._delimiter = "local~$";
this._origdelimiter = "local~$";
// Prompt Command History
// Histctr moves based on number of times "up" (+= ctr)
// or "down" (-= ctr) was pressed in traversing
// command history.
this._hist = [];
this._histCtr = 0;
// Hook to reference active inquirer prompt.
this._activePrompt;
// Determines whether or not to show a prompt on the
// local Vantage server terminal. Exposed through
// Vantage.show();
this._isSilent = true;
// Banner to display on login to a system. If null,
// doesn't display a banner.
this._banner = void 0;
// Fail-safe to ensure there is no double
// prompt in odd situations.
this._midPrompt = false;
// Vantage client connects to other instances
// of Vantage.
this.client = new VantageClient(this);
// Vantage server receives connections from
// other vantages. Activated by vantage.listen();
this.server = new VantageServer(this);
// If one uses vantage to connect
// into another session, they are a 'client'.
// If Vantage is receiving a client and piping the
// response through to it, it is a 'server'.
// A Vantage instance can be both a client and
// server in the instance that one is double-hopping
// through Vantage instances.
// Exposed through vantage.is('client/server', [setter]).
this._isClient = false;
this._isServer = false;
this._isTerminable = false;
// Handle for inquirer's prompt.
this.inquirer = inquirer;
// Middleware for piping stdout through.
this._pipeFn = void 0;
// Queue of IP requests, executed async, in sync.
// Yeah, that doesn't make much sense. But it works.
this._queue = [];
// Current command being executed.
this._command = void 0;
// Whether a prompt is currently in cancel mode.
this._cancelled = false;
// Whether all stdout is being hooked through a function.
this._hooked = false;
// Expose common utilities, like padding.
this.util = VantageUtil;
this._id = parseFloat(Math.round(Math.random()*1000000));
this._init();
return this;
}
/**
* Extension to `constructor`.
* @api private
*/
Vantage.prototype._init = function() {
var self = this;
// Hook in to steal inquirer's keypress.
inquirer.prompt.prompts.input.prototype.onKeypress = function(e) {
self.emit('client_keypress', e);
return self._keypressHandler(e, this);
};
// Extend the render function to steal the active prompt object,
// as inquirer doesn't expose it and we need it.
(function(render){
inquirer.prompt.prompts.input.prototype.render = function() {
self._activePrompt = this;
return render.call(this)
}
})(inquirer.prompt.prompts.input.prototype.render)
var pointless = 1;
setInterval(function(){
pointless = pointless + 1 / 2;
}, 10000)
self.use(commons);
}
/**
* Sets version of your application's API.
*
* @param {String} version
* @return {Vantage}
* @api public
*/
vantage.version = function(version) {
this._version = version;
return this;
};
/**
* Sets the permanent delimiter for this
* Vantage server instance.
*
* @param {String} str
* @return {Vantage}
* @api public
*/
vantage.delimiter = function(str) {
var slf = this;
this._delimiter = String(str).trim() + " ";
this._origdelimiter = String(str).trim() + " ";
inquirer.prompt.prompts.input.prototype.prefix = function() {
return slf._delimiter;
}
return this;
};
/**
* Sets the temporarily delimiter based
* on the delimiter provided by another
* vantage server to this instance's client
* upon the establishment of a session.
*
* @param {String} str
* @api private
*/
vantage._tempDelimiter = function(str) {
var self = this;
this._delimiter = String(str || "").trim() + " ";
inquirer.prompt.prompts.input.prototype.prefix = function() {
return self._delimiter;
}
if (this._midPrompt) {
this._refresh();
}
};
/**
* Getter / Setter for Vantage's role, i.e.
* a client, server, proxy, etc.
*
* @param {String} role
* @param {Boolean} setter
* @api private
*/
vantage.is = function(role, setter) {
this._isClient = (role == "client" && setter !== undefined) ? setter : this._isClient;
this._isServer = (role == "server" && setter !== undefined) ? setter : this._isServer;
this._isTerminable = (role == "terminable" && setter !== undefined) ? setter : this._isTerminable;
var response =
(role == "terminable" && this._isTerminable) ? true :
(role == "local" && (!this._isServer && !this._isClient)) ? true :
(role == "local" && (this._isClient && this._isTerminable)) ? true :
(role == "local") ? false :
(role == "proxy" && this._isClient && this._isServer) ? true :
(role == "proxy") ? false :
(role == "client") ? this._isClient :
(role == "server") ? this._isServer : false;
return response;
};
/**
* Programatically connect to another server
* instance running Vantage.
*
* @param {Server} server
* @param {Integer} port
* @param {Object} options
* @param {Function} cb
* @return {Promise}
* @api public
*/
vantage.connect = function(server, port, options, cb) {
this._isSilent = false;
return this.client.connect.call(this.client, server, port, options, cb);
};
/**
* Imports a library of Vantage API commands
* from another Node module as an extension
* of Vantage.
*
* @param {Array} commands
* @return {Vantage}
* @api public
*/
vantage.use = function(commands, options) {
if (!commands) { return this; }
if (_.isFunction(commands)) {
commands.call(this, this, options);
} else if (_.isString(commands)) {
return this.use(require(commands), options);
} else {
commands = _.isArray(commands) ? commands : [commands];
for (var i = 0; i < commands.length; ++i) {
var cmd = commands[i];
if (cmd.command) {
var command = this.command(cmd.command);
if (cmd.description) {
command.description(cmd.description);
}
if (cmd.options) {
cmd.options = _.isArray(cmd.options) ? cmd.options : [cmd.options];
for (var j = 0; j < cmd.options.length; ++j) {
command.option(cmd.options[j][0], cmd.options[j][1]);
}
}
if (cmd.action) {
command.action(cmd.action);
}
}
}
}
return this;
};
/**
* Returns the appropriate command history
* string based on an 'Up' or 'Down' arrow
* key pressed by the user.
*
* @param {String} direction
* @return {String}
* @api private
*/
vantage._getHistory = function(direction) {
if (direction == "up") {
this._histCtr++;
this._histCtr = (this._histCtr > this._hist.length) ? this._hist.length : this._histCtr;
} else if (direction == "down") {
this._histCtr--;
this._histCtr = (this._histCtr < 1) ? 1 : this._histCtr;
}
return this._hist[this._hist.length-(this._histCtr)];
};
/**
* Handles tab-completion. Takes a partial
* string as "he" and fills it in to "help", etc.
* Works the same as a linux terminal's auto-complete.
*
* @param {String} str
* @return {String}
* @api private
*/
vantage._getAutocomplete = function(str) {
var names = _.pluck(this.commands, "_name");
var auto = this._autocomplete(str, names);
return auto;
};
/**
* Independent / stateless auto-complete function.
* Parses an array of strings for the best match.
*
* @param {String} str
* @param {Array} arr
* @return {String}
* @api private
*/
vantage._autocomplete = function(str, arr) {
arr.sort();
var arrX = _.clone(arr);
var strX = String(str);
var go = function() {
var matches = [];
for (var i = 0; i < arrX.length; i++) {
if (arrX[i].slice(0, strX.length).toLowerCase() == strX.toLowerCase()) {
matches.push(arrX[i]);
}
}
if (matches.length == 1) {
return matches[0] + " ";
} else if (matches.length == 0) {
return void 0;
} else {
var furthest = strX;
for (var i = strX.length; i < matches[0].length; ++i) {
var curr = String(matches[0].slice(0, i)).toLowerCase();
var same = 0;
for (var j = 0; j < matches.length; ++j) {
var sliced = String(matches[j].slice(0, curr.length)).toLowerCase();
if (sliced == curr) {
same++;
}
}
if (same == matches.length) {
furthest = curr;
continue;
} else {
break;
}
}
if (furthest != strX) {
return furthest;
} else {
return void 0;
}
}
}
return go();
};
/**
* Redraws the inquirer prompt with a new string.
*
* @param {Prompt} prompt
* @param {String} str
* @return {Vantage}
* @api private
*/
vantage._redraw = function(prompt, str) {
prompt.rl.line = str;
prompt.rl.cursor = str.length;
prompt.cacheCursorPos();
prompt.clean().render().write( prompt.rl.line );
prompt.restoreCursorPos();
return this;
};
/**
* Write a banner on remote login.
*
* @param {String} banner
* @return {Vantage}
* @api public
*/
vantage.banner = function(banner) {
this._banner = banner || void 0;
return this;
};
/**
* Writes to console or, if `vantage.pipe` is
* called, pipes out to a function first.
*
* @param {String} log
* @return {Vantage}
* @api public
*/
vantage.log = function(log) {
var self = this;
log = (_.isArray(log)) ? log : [log];
for (var i = 0; i < log.length; ++i) {
if (this._pipeFn !== undefined) {
// If the user has declared a pipe function,
// pass the data through the pipe, and if
// the user returned text, log it.
var result = this._pipeFn.call(this, log[i]);
if (result) {
self._log(result);
}
} else {
// Otherwise, just log the data.
self._log(log[i]);
}
}
return this;
};
/**
* Pauses prompt while logging, and then
* resumes prompt once the data is logged.
*
* @param {String} log
* @return {Vantage}
* @api private
*/
vantage._log = function(log) {
var self = this;
var data = self._pause();
console.log(log);
if (data !== false) {
self._resume(data);
}
return this;
};
/**
* Intercepts all logging through `vantage.log`
* and runs it through the function declared by
* `vantage.pipe()`.
*
* @param {Function} fn
* @return {Vantage}
* @api public
*/
vantage.pipe = function(fn){
this._pipeFn = fn;
return this;
};
/**
* Registers a new command in the vantage API.
*
* @param {String} name
* @param {String} desc
* @param {Object} opts
* @return {Command}
* @api public
*/
vantage.command = function(name, desc, opts) {
opts = opts || {};
name = String(name);
var args =
(name.indexOf("[") > -1) ? name.split("[") :
(name.indexOf("<") > -1) ? name.split("<") : [name];
if (args[1]) {
args[1] = (String(args[1]).indexOf("]") > -1) ? "[" + args[1] : args[1];
args[1] = (String(args[1]).indexOf(">") > -1) ? "<" + args[1] : args[1];
}
var cmd = new Command(String(args.shift()).trim(), exports);
if (desc) {
cmd.description(desc);
this.executables = true;
}
cmd._noHelp = !!opts.noHelp;
this.commands.push(cmd);
cmd._parseExpectedArgs(args);
cmd.parent = this;
if (desc) return this;
return cmd;
};
/**
* If Vantage is the local terminal,
* hook all stdout, through a fn.
*
* @return {Vantage}
* @api private
*/
vantage.hook = function() {
var self = this;
if (this.is('local')) {
this._hook(function(str){
return str;
});
}
};
/**
* Unhooks stdout capture.
*
* @return {Vantage}
* @api public
*/
vantage._unhook = function() {
if (this._hooked && this._unhook !== undefined) {
this._unhook();
this._hooked = false;
}
return this;
},
/**
* Hooks all stdout through a given function.
*
* @param {Function} fn
* @return {Vantage}
* @api public
*/
vantage._hook = function(fn) {
if (this._hooked && this._unhook != undefined) {
this._unhook();
}
this._unhook = intercept(fn);
this._hooked = true;
return this;
};
/**
* Enables the vantage prompt on the
* local terminal.
*
* @return {Vantage}
* @api public
*/
vantage.show = function() {
this._isSilent = false;
if (this._banner) {
console.log(this._banner);
}
this.hook();
this._prompt();
return this;
};
/**
* Disables the vantage prompt on the
* local terminal.
*
* @return {Vantage}
* @api public
*/
vantage.hide = function() {
this._isSilent = true;
return this;
};
/**
* For use in vantage API commands, sends
* a prompt command downstream to the local
* terminal. Executes a prompt and returns
* the response upstream to the API command.
*
* @param {Object} options
* @param {Function} cb
* @return {Vantage}
* @api public
*/
vantage.prompt = function(options, cb) {
var self = this;
options = options || {}
if (self.is('local')) {
self._tempDelimiter((options.message) ? options.message : self._delimiter);
inquirer.prompt(options, function(result) {
self._tempDelimiter(self._origdelimiter);
cb(result);
});
} else {
self.on("vantage-prompt-upstream", function(data){
var response = data.value;
cb(response);
});
self._send("vantage-prompt-downstream", "downstream", { options: options, value: void 0 });
}
return self;
};
vantage._refresh = function() {
if (!this._activePrompt) { return }
if (!this._midPrompt) { return false; }
this._activePrompt.clean();
this._midPrompt = false;
this._cancelled = true;
if (this._activePrompt.status != "answered") {
this._activePrompt.status = "answered";
this._activePrompt.done();
}
this._prompt();
return this;
},
vantage._pause = function() {
if (!this._activePrompt) { return false; }
if (!this._midPrompt) { return false; }
var val = this._activePrompt.rl.line;
this._activePrompt.clean();
this._midPrompt = false;
this._cancelled = true;
this._activePrompt.status = "answered";
this._activePrompt.done();
return val;
},
vantage._resume = function(val) {
val = val || "";
if (!this._activePrompt) { return }
if (this._midPrompt) { return }
this._prompt();
this._activePrompt.rl.line = val;
this._activePrompt.rl.cursor = val.length;
this._activePrompt.cacheCursorPos();
this._activePrompt.clean().render().write( this._activePrompt.rl.line );
this._activePrompt.restoreCursorPos();
return this;
},
/**
* Renders the CLI prompt or sends the
* request to do so downstream.
*
* @return {Vantage}
* @api private
*/
vantage._prompt = function() {
var self = this;
// If we somehow got to _prompt and aren't the
// local client, send the command downstream.
if (this.is("server")) {
this._send("vantage-resume-downstream", "downstream");
return;
}
// ... we just don't show prompts - for automation.
if (self._isSilent === true) {
console.log('Chilling because we are silent.')
return;
}
// If we double up on a prompt, chill out.
if (this._midPrompt) { return; }
this._midPrompt = true;
var ui = inquirer.prompt({
type: "input",
name: "command",
message: this._delimiter,
}, function(result){
self._midPrompt = false;
if (self._cancelled == true) { self._cancelled = false; return; }
var str = String(result.command).trim();
self.emit("client_prompt_submit", str);
if (str == "") { self._prompt(); return; }
self.exec(str, function(){
self._prompt();
});
});
return self;
};
/**
* Executes a vantage API command and
* returns the response either through a
* callback or Promise in the absence
* of a callback.
*
* A little black magic here - because
* we sometimes have to send commands 10
* miles upstream through 80 other instances
* of vantage and we aren't going to send
* the callback / promise with us on that
* trip, we store the command, callback,
* resolve and reject objects (as they apply)
* in a local vantage._command variable.
*
* When the command eventually comes back
* downstream, we dig up the callbacks and
* finally resolve or reject the promise, etc.
*
* Lastly, to add some more complexity, we throw
* command and callbacks into a queue that will
* be unearthed and sent in due time.
*
* @param {String} cmd
* @param {Function} cb
* @return {Promise or Vantage}
* @api public
*/
vantage.exec = function(cmd, cb) {
var self = this;
var command = {
command: cmd,
callback: cb,
}
if (cb !== undefined) {
self._queue.push(command);
self._queueHandler.call(self);
return self;
} else {
return new Promise(function(resolve, reject) {
command.resolve = resolve;
command.reject = reject;
self._queue.push(command);
self._queueHandler.call(self);
});
}
};
/**
* Commands issued to Vantage server
* are executed in sequence. Called once
* when a command is inserted or completes,
* shifts the next command in the queue
* and sends it to `vantage._execQueueItem`.
*
* @api private
*/
vantage._queueHandler = function() {
if (this._queue.length > 0 && this._command === undefined) {
var item = this._queue.shift();
this._execQueueItem(item);
}
};
/**
* Fires off execution of a command - either
* calling upstream or executing locally.
*
* @param {Object} cmd
* @api private
*/
vantage._execQueueItem = function(cmd) {
var self = this;
if (self.is('local')) {
this._exec(cmd);
} else {
self._command = cmd;
self._send('vantage-command-upstream', 'upstream', { command: cmd.command, completed: false });
};
};
/**
* Executes a vantage API command.
* Warning: Dragons lie beyond this point.
*
* @param {String} item
* @api private
*/
vantage._exec = function(item) {
item = item || {}
item.command = item.command || "";
var self = this;
var parts = item.command.split(" ");
var path = [];
var match = false;
var args;
// History for our "up" and "down" arrows.
this._hist.push(item.command);
// Reverse drill-down the string until you find the
// first command match.
for (var i = 0; i < parts.length; ++i) {
var subcommand = String(parts.slice(0, parts.length-i).join(' ')).trim().toLowerCase();
match = _.findWhere(this.commands, { _name: subcommand }) || match;
if (match) {
args = parts.slice(parts.length-i, parts.length).join(' ');
break;
}
}
// This basically makes the arguments human readable.
var parsedArgs = minimist(VantageUtil.parseArgs(args));
parsedArgs['_'] = parsedArgs['_'] || [];
var args = {}
// Match means we found a suitable command.
if (match) {
var fn = match._fn;
var origArgs = match._args;
var origOptions = match.options;
args.options = {}
// Looks for a help arg and throws help if any.
if (parsedArgs.help || parsedArgs.h || parsedArgs['_'].indexOf('/?') > -1) {
self.log(match.helpInformation());
item.callback(); return;
}
// looks for ommitted required args
// and throws help.
for (var i = 0; i < origArgs.length; ++i) {
var exists = parsedArgs._[i];
if (!exists && origArgs[i].required === true) {
self.log(" ");
self.log(" Missing required argument. Showing Help:");
self.log(match.helpInformation());
item.callback(); return;
}
if (exists) {
args[origArgs[i].name] = exists;
}
}
// Looks for ommitted required options
// and throws help.
for (var i = 0; i < origOptions.length; ++i) {
var o = origOptions[i];
var short = String(o.short || "").replace(/-/g, "");
var long = String(o.long || "").replace(/--no-/g, "").replace(/-/g, "");
var flag = String(o.flags).slice(Math.abs(o.required), o.flags.length).replace('>', "").trim();
var exists = parsedArgs[short] || parsedArgs[long];
if (exists === undefined && o.required !== 0) {
self.log(" ");
self.log(" Missing required option. Showing Help:");
self.log(match.helpInformation());
item.callback('Missing required option.');
return;
}
if (exists !== undefined) {
args.options[long || short] = exists;
}
}
// Warning: Do not touch unless you have a
// really good understand of callbacks and
// Promises (I don't).
// So what I think I made this do, is call the
// function declared in the command's .action()
// method.
// If calling it seems to return a Promise, we
// are going to guess they didn't call the
// callback we passed in.
// If the 'action' function didn't throw an
// error, call the `exec`'s callback if it
// exists, and call it's `resolve` if its a
// Promise.
// If the `action` function threw an error,
// callback with the error or reject the Promise.
// Call the vantage API function.
var res = fn.call(this, args, function(a, b, c, d, e, f, g) {
self.emit('client_command_executed', { command: item.command });
if (item.callback) {
item.callback.call(self, a, b, c, d, e, f, g);
} else if (item.resolve !== undefined) {
return item.resolve(a, b, c, d, e, f, g);
}
});
// If the Vantage API function as declared by the user
// returns a promise, then we do this.
if (res && _.isFunction(res.then)) {
return res.then(function(data){
if (self.is('local')) {
self.emit('client_command_executed', { command: item.command });
}
if (item.callback !== undefined) {
item.callback(data);
} else if (item.resolve !== undefined) {
return item.resolve(data);
}
}).catch(function(err) {
self.log(["", ' Error: '.red + err, '']);
if (self.is('local')) {
self.emit('client_command_error', { command: item.command, error: err });
}
if (item.callback !== undefined) {
item.callback(err);
} else if (item.reject !== undefined) {
item.reject(err);
}
});
}
} else {
// If no command match, just return.
self.log(this._commandHelp(item.command));
// To do - if `exec` uses Promises,
// I think we need to return a promise here...
item.callback();
}
};
/**
* Returns help string for a given command.
*
* @param {String} command
* @api private
*/
vantage._commandHelp = function(command) {
if (!this.commands.length) return "";
var self = this;
var matches = [];
var singleMatches = [];
command = (command) ? String(command).trim().toLowerCase() : void 0;
for (var i = 0; i < this.commands.length; ++i) {
var parts = String(this.commands[i]._name).split(' ');
if (parts.length == 1 && parts[0] == command) { singleMatches.push(command) }
var str = "";
for (var j = 0; j < parts.length; ++j) {
str = String(str + ' ' + parts[j]).trim();
if (str == command) {
matches.push(this.commands[i]);
break;
}
}
}
var invalidString =
(command && matches.length == 0 && singleMatches.length == 0)
? ["", " Invalid Command. Showing Help:", ""].join('\n')
: "";
var commandMatch = (matches.length > 0) ? true : false;
var commandMatchLength = (commandMatch) ? String(command).trim().split(' ').length+1 : 1;
matches = (matches.length == 0) ? this.commands : matches;