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
|
/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-restricted-syntax, no-invalid-this, no-underscore-dangle */
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var readline = require( 'readline' ).createInterface;
var resolve = require( 'path' ).resolve;
var logger = require( 'debug' );
var inherit = require( '@stdlib/utils/inherit' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var isConfigurableProperty = require( '@stdlib/assert/is-configurable-property' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var properties = require( '@stdlib/utils/properties' );
var append = require( '@stdlib/utils/append' );
var cwd = require( '@stdlib/process/cwd' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
var reEOL = require( '@stdlib/regexp/eol' );
var fifo = require( '@stdlib/utils/fifo' );
var nextTick = require( '@stdlib/utils/next-tick' );
var validate = require( './validate.js' );
var defaults = require( './defaults.js' );
var setAliases = require( './set_aliases.js' );
var setAliasesGlobal = require( './set_aliases_global.js' );
var setCommands = require( './set_commands.js' );
var setCommandsGlobal = require( './set_commands_global.js' );
var propertyComparator = require( './property_comparator.js' );
var createEvalContext = require( './create_evaluation_context.js' );
var commands = require( './commands.js' );
var displayPrompt = require( './display_prompt.js' );
var inputPrompt = require( './input_prompt.js' );
var processLine = require( './process_line.js' );
var completer = require( './completer.js' );
var ALIAS_OVERRIDES = require( './alias_overrides.js' );
// VARIABLES //
var debug = logger( 'repl' );
// MAIN //
/**
* REPL constructor.
*
* @constructor
* @param {Options} options - constructor options
* @param {string} [options.inputPrompt='In [%d]: '] - input prompt
* @param {string} [options.outputPrompt='Out[%d]: '] - output prompt
* @param {ReadableStream} [options.input=process.stdin] - input stream
* @param {WritableStream} [options.output=process.stdout] - output stream
* @param {boolean} [options.sandbox=true] - boolean indicating whether to run a REPL in a sandboxed context
* @param {PositiveInteger} [options.timeout=4294967295] - number of milliseconds to execute a command before terminating execution
* @param {boolean} [options.isTTY] - boolean indicating whether the input and output streams should be treated like a TTY (terminal) and whether the REPL should use ANSI/VT100 escape codes when writing to the output stream
* @param {string} [options.welcome] - welcome message
* @param {NonNegativeInteger} [options.padding=1] - number of empty lines between successive commands
* @param {string} [options.load] - file path specifying a JavaScript file to load and evaluate line-by-line (e.g., a previous REPL history file)
* @param {string} [options.save] - file path specifying where to save REPL command history
* @param {string} [options.log] - file path specifying where to save REPL commands and printed output
* @param {string} [options.quiet=false] - boolean indicating whether log information, confirmation messages, and other possible REPL diagnostics should be silenced
* @throws {Error} must provide valid options
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* function onExit() {
* console.log( 'REPL closed.' );
* }
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
* repl.on( 'exit', onExit );
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
function REPL( options ) {
var opts;
var self;
var err;
if ( !( this instanceof REPL ) ) {
if ( arguments.length ) {
return new REPL( options );
}
return new REPL();
}
self = this;
opts = defaults();
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
opts.isTTY = ( opts.isTTY === void 0 ) ? opts.output.isTTY : opts.isTTY;
debug( 'Options: %s', JSON.stringify({
'input': '<readable_stream>',
'output': '<writable_stream>',
'sandbox': opts.sandbox,
'timeout': opts.timeout,
'isTTY': opts.isTTY,
'inputPrompt': opts.inputPrompt,
'outputPrompt': opts.outputPrompt,
'padding': opts.padding,
'welcome': opts.welcome,
'load': opts.load,
'save': opts.save,
'log': opts.log,
'quiet': opts.quiet
}));
// Call the parent constructor:
EventEmitter.call( this );
// Cache references to the input and output streams:
setNonEnumerableReadOnly( this, '_istream', opts.input );
setNonEnumerableReadOnly( this, '_ostream', opts.output );
// Cache options:
setNonEnumerableReadOnly( this, '_inputPrompt', opts.inputPrompt );
setNonEnumerableReadOnly( this, '_outputPrompt', opts.outputPrompt );
setNonEnumerableReadOnly( this, '_padding', opts.padding );
setNonEnumerableReadOnly( this, '_timeout', opts.timeout );
setNonEnumerableReadOnly( this, '_isTTY', opts.isTTY );
setNonEnumerableReadOnly( this, '_sandbox', opts.sandbox );
setNonEnumerable( this, '_quiet', opts.quiet ); // allow this to be internally toggled
// Initialize an internal data store:
setNonEnumerableReadOnly( this, '_internal', {} );
setNonEnumerableReadOnly( this._internal, 'presentation', {} );
setNonEnumerableReadOnly( this._internal.presentation, 'cache', {} );
setNonEnumerable( this._internal.presentation, 'counter', 0 );
// Initialize an internal command queue:
setNonEnumerableReadOnly( this, '_queue', fifo() );
// Initialize a strided internal buffer for storing the command history:
setNonEnumerableReadOnly( this, '_history', [] );
// Initialize an internal buffer for storing the current command:
setNonEnumerableReadOnly( this, '_cmd', [] );
// Initialize a executed command counter:
setNonEnumerable( this, '_count', -1 );
// Initialize an internal buffer for saving regular expression matches between command evaluations:
setNonEnumerableReadOnly( this, '_regexp', [ '', '', '', '', '', '', '', '', '', '' ] );
// Initialize a strided internal cache of context globals:
setNonEnumerableReadOnly( this, '_contextVars', [] );
// For non-sandboxed REPLs, initialize an internal buffer for storing a (unique) sorted list of "built-in" REPL global variables/properties which need to be deleted upon closing a REPL in order to allow garbage collection and prevent memory leaks:
setNonEnumerableReadOnly( this, '_globalVars', ( this._sandbox ) ? null : [] );
// Initialize a strided internal cache of resolved global variables/properties in order to allow, e.g., help text look-up based on object reference, not just alias name (note: members alternate between `'<string_alias>'` and `<resolved_value>`):
setNonEnumerableReadOnly( this, '_aliases', [] );
// Initialize a strided internal buffer for storing user-defined documentation:
setNonEnumerableReadOnly( this, '_userdocs', [] );
// Initialize an internal buffer for storing a (unique) sorted list of workspace global variables/properties which were *initially* introduced during a REPL session (note: this overlaps with `_globalVars`, but more accurately represents a snapshot of the `global` state *before* a user begins entering commands, which is useful when wanting determine what variables/identifiers a user has introduced during a REPL session):
setNonEnumerableReadOnly( this, '_workspace', [] );
// Initialize a strided internal buffer for caching "base" workspace variables:
setNonEnumerableReadOnly( this, '_workspaces', {} );
setReadOnly( this._workspaces, 'base', [] );
// Define the current workspace:
setNonEnumerable( this, '_currentWorkspace', 'base' );
// Initialize an internal flag indicating whether a user is entering a multi-line command:
setNonEnumerable( this, '_multiline_mode', false );
// Initialize an internal flag indicating whether the REPL has been closed:
setNonEnumerable( this, '_closed', false );
// Initialize an internal flag indicating whether the REPL is currently busy with asynchronous processing:
setNonEnumerable( this, '_busy', false );
// Initialize an internal flag indicating whether we've received a `SIGINT` signal:
setNonEnumerable( this, '_SIGINT', false );
// Initialize an internal variable for caching the result of the last successfully evaluated command:
setNonEnumerable( this, '_ans', void 0 );
// Initialize an internal variable for setting a command callback:
setNonEnumerable( this, '_done', void 0 );
// Create a REPL execution context:
setNonEnumerable( this, '_context', this.createContext() );
// Create an internal readline interface:
debug( 'Creating readline interface...' );
setNonEnumerableReadOnly( this, '_rli', readline({
'input': this._istream,
'output': this._ostream,
'terminal': opts.isTTY,
'prompt': opts.inputPrompt,
'completer': completer( this )
}));
this._rli.on( 'close', onClose );
this._rli.on( 'line', onLine );
this._rli.on( 'SIGINT', onSIGINT );
// Add listener for "command" events:
this.on( 'command', onCommand );
// Write a welcome message:
this._ostream.write( opts.welcome );
// TODO: check whether to synchronously initialize a REPL history file
// TODO: check whether to synchronously initialize a REPL log file
// Check whether to load and execute a JavaScript file (e.g., prior REPL history) upon startup...
if ( opts.load ) {
this.load( opts.load );
} else {
displayPrompt( this, false );
this._count += 1;
}
return this;
/**
* Callback invoked upon a readline interface "line" event.
*
* @private
* @param {string} line - line data
*/
function onLine( line ) {
self._SIGINT = false; // reset flag
if ( self._closed === false ) {
processLine( self, line );
}
}
/**
* Callback invoked upon a readline interface "close" event.
*
* @private
*/
function onClose() {
debug( 'Readline interface closed.' );
debug( 'Exiting REPL...' );
self.emit( 'exit' );
}
/**
* Callback invoked upon receiving a "SIGINT" event (e.g., Ctrl-C).
*
* @private
* @returns {void}
*/
function onSIGINT() {
var isEmpty;
debug( 'Received a SIGINT event.' );
// If the REPL is currently busy executing a command, stop waiting for it to finish:
if ( self._busy ) {
self._done( new Error( 'command execution terminated.' ) );
return;
}
// Check whether the user has entered any characters:
isEmpty = ( self._rli.line.length === 0 );
// Clear the current line:
self.clearLine();
// In the absence of any entered partial and/or unevaluated commands, determine whether we should close the REPL...
if ( self._cmd.length === 0 && isEmpty ) {
if ( self._SIGINT ) {
self._SIGINT = false;
self.close();
return;
}
self._ostream.write( 'To exit, enter ^D or ^C again or enter quit().\n' );
self._SIGINT = true;
} else {
self._SIGINT = false;
}
// Reset the command queue:
self._queue.clear();
// Clear any command which has been buffered but not yet executed:
self.clearCommand();
// Display a new prompt:
displayPrompt( self, false );
}
/**
* Callback invoked upon executing a command.
*
* @private
* @param {string} cmd - command
* @param {boolean} success - boolean indicating whether the command successfully executed
*/
function onCommand( cmd, success ) {
self._count += 1;
debug( 'Command count: %d', self._count );
// Update the internal command history buffer: [..., <id>, <cmd>, <success>, ...]
self._history.push( self._count, cmd, success );
// TODO: if successful and if necessary, (asynchronously?) write the command to a history file (question: do we only want to write successful commands to the history file? maybe we need to option for limiting to successful commands?)
// TODO: if necessary, (asynchronously?) write the command and result to a log file (JSON serialization?)
}
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( REPL, EventEmitter );
/**
* Displays a command prompt.
*
* @private
* @name _displayPrompt
* @memberof REPL.prototype
* @type {Function}
* @param {boolean} [preserveCursor=false] - boolean indicating whether to preserve the cursor position
* @returns {REPL} REPL instance
*/
setNonEnumerableReadOnly( REPL.prototype, '_displayPrompt', function showPrompt( preserveCursor ) {
displayPrompt( this, Boolean( preserveCursor ) );
return this;
});
/**
* Returns the current command prompt.
*
* @private
* @name _prompt
* @memberof REPL.prototype
* @type {Function}
* @returns {string} command prompt
*/
setNonEnumerableReadOnly( REPL.prototype, '_prompt', function prompt() {
return inputPrompt( this._inputPrompt, this._count );
});
/**
* Creates a REPL context.
*
* @name createContext
* @memberof REPL.prototype
* @type {Function}
* @returns {Object} REPL context
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // Return a new REPL context:
* var ctx = repl.createContext();
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'createContext', function createContext() {
var context;
var cmds;
debug( 'Creating REPL execution context...' );
// Create an evaluation context:
context = createEvalContext( this._contextVars, this._ostream, this._sandbox ); // eslint-disable-line max-len
// Add project APIs...
if ( this._sandbox ) {
setAliases( this._aliases, context, ALIAS_OVERRIDES );
} else {
setAliasesGlobal( this._globalVars, this._aliases, context, ALIAS_OVERRIDES ); // eslint-disable-line max-len
}
// Get the list of REPL-specific commands:
cmds = commands( this );
// Add commands requiring privileged access to internal instance variables...
if ( this._sandbox ) {
setCommands( context, cmds );
} else {
setCommandsGlobal( this._globalVars, context, cmds );
}
// NOTE: the context should not be augmented **after** this point, except as done by the user when declaring variables and functions!
// Sort the list of global variables:
if ( this._sandbox === false ) {
this._globalVars.sort( propertyComparator );
}
// Capture a snapshot of the current global workspace:
append( this._workspace, properties( context ).sort( propertyComparator ) );
return context;
});
/**
* Resets a REPL's context.
*
* @name resetContext
* @memberof REPL.prototype
* @type {Function}
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Reset the REPL context:
* repl.resetContext();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'resetContext', function resetContext() {
var tmp;
var key;
var o;
var i;
var j;
debug( 'Resetting REPL execution context...' );
// Before creating a new execution context in a non-sandboxed environment, remove current workspace variables in order to allow garbage collection and avoid memory leaks (e.g., variables/functions declared during a REPL session which might remain bound to the environment `global` after clearing a REPL):
if ( this._sandbox === false ) {
// WARNING: in a non-sandboxed environment, if a global variable is externally introduced during a REPL session (i.e., introduced via a mechanism outside of the REPL environment), we will delete that global variable, which means the following logic may introduce unintended side-effects for this particular edge case (e.g., application code may expect the presence of the subsequently deleted global variable). While not ideal, (a) user applications should not be introducing globals to begin with and (b) the probability of a user running a REPL session, a user clearing that REPL session, AND a global variable being introduced between starting a REPL and clearing the REPL should be negligible.
tmp = this._context.vars();
for ( i = 0; i < tmp.length; i++ ) {
if ( isConfigurableProperty( this._context, tmp[ i ] ) ) {
delete this._context[ tmp[ i ] ];
}
}
// Remove REPL globals:
for ( i = 0; i < this._globalVars.length; i++ ) {
o = this._context;
key = this._globalVars[ i ].split( '.' ); // Note: this addresses nested key paths (e.g., `a.b.c`)
for ( j = 0; j < key.length-1; j++ ) {
if ( !hasOwnProp( o, key[ j ] ) ) {
o = null;
break;
}
o = o[ key[ j ] ];
}
if ( o && isConfigurableProperty( o, key[ j ] ) ) {
delete o[ key[ j ] ];
}
}
}
// Reset internal buffers for storing context data:
if ( this._sandbox === false ) {
this._globalVars.length = 0;
}
this._aliases.length = 0;
this._workspace.length = 0;
this._contextVars.length = 0;
// Create a new execution context...
this._context = this.createContext();
this.emit( 'reset', this._context ); // note: emitting the context allows REPL wrappers to extend the newly created context
return this;
});
/**
* Clears a REPL's history.
*
* @name clearHistory
* @memberof REPL.prototype
* @type {Function}
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Clear the REPL history:
* repl.clearHistory();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'clearHistory', function clearHistory() {
debug( 'Resetting REPL history...' );
this._history.length = 0;
return this;
});
/**
* Clears user-defined documentation.
*
* @name clearUserDocs
* @memberof REPL.prototype
* @type {Function}
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Clear the user defined documentation:
* repl.clearUserDocs();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'clearUserDocs', function clearUserDocs() {
debug( 'Resetting REPL user-defined documentation...' );
this._userdocs.length = 0;
return this;
});
/**
* Loads and evaluates a JavaScript file line-by-line.
*
* @name load
* @memberof REPL.prototype
* @type {Function}
* @param {string} fpath - file path
* @param {Function} clbk - callback
* @throws {Error} cannot load a file into a closed REPL
* @throws {TypeError} first argument must be a string
* @throws {TypeError} second argument must be a function
* @returns {void}
*
* @example
* // TODO
*/
setNonEnumerableReadOnly( REPL.prototype, 'load', function load( fpath, clbk ) {
var self;
var file;
var len;
var i;
if ( this._closed ) {
throw new Error( 'invalid operation. Cannot load a file into a REPL which has already closed.' );
}
if ( !isString( fpath ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `' + fpath + '`.' );
}
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `' + clbk + '`.' );
}
// Resolve the provided path to an absolute file path:
fpath = resolve( cwd(), fpath );
debug( 'Loading filepath: %s', fpath );
// Attempt to synchronously read the file:
file = readFileSync( fpath, 'utf8' );
if ( file instanceof Error ) {
debug( 'Error: %s', file.message );
clbk( file );
return;
}
self = this;
// Split the file content into individual lines:
file = file.split( reEOL.REGEXP );
// Forward each line to the REPL readline interface in order to mimic user input...
len = file.length;
i = -1;
nextTick( next );
/**
* Callback invoked after draining the command queue.
*
* @private
* @param {string} cmd - command
* @param {boolean} success - boolean indicating whether the command successfully executed
*/
function next() {
i += 1;
if ( i < len ) {
if ( file[ i ] ) {
self._rli.write( file[ i ]+'\n' );
self.once( 'drain', next );
} else {
nextTick( next );
}
} else {
nextTick( clbk );
}
}
});
/**
* Resets a REPL.
*
* @name reset
* @memberof REPL.prototype
* @type {Function}
* @throws {Error} cannot reset a closed REPL
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Reset the REPL:
* repl.reset();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'reset', function onReset() {
if ( this._closed ) {
throw new Error( 'invalid operation. Cannot reset a REPL which has already closed.' );
}
debug( 'Resetting REPL...' );
// Reset the command queue:
this._queue.clear();
// Clear any command which has been buffered but not yet executed:
this.clearCommand();
// Clear the command history:
this.clearHistory();
// Reset the execution context:
this.resetContext();
// Clear an output TTY stream of any previous commands and output:
this.clear();
// Display the command prompt:
displayPrompt( this, false );
return this;
});
/**
* Clears the entire REPL screen and scrollback history.
*
* ## Notes
*
* - This method is only applicable for TTY REPLs. In non-TTY REPLs, this method is a non-operation.
*
* @name clear
* @memberof REPL.prototype
* @type {Function}
* @throws {Error} cannot clear a closed REPL
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Clear the REPL:
* repl.clear();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'clear', function onClear() {
if ( this._closed ) {
throw new Error( 'invalid operation. Cannot clear a REPL which has already closed.' );
}
if ( this._isTTY ) {
/*
* [ANSI escape sequences][1]:
*
* - `\u001b`: ESC, the escape character
* - `[H`: move cursor to upper left corner
* - `[2J`: clear the entire screen
* - `[3J`: clear the entire screen and delete all lines in the scrollback buffer (note: possible portability issues)
*
* [1]: https://en.wikipedia.org/wiki/ANSI_escape_code
*/
this._ostream.write( '\u001b[2J\u001b[H\u001b[2J\u001b[3J' );
}
return this;
});
/**
* Clears the current line.
*
* ## Notes
*
* - This method is only applicable for TTY REPLs. In non-TTY REPLs, this method is a non-operation.
*
* @name clearLine
* @memberof REPL.prototype
* @type {Function}
* @throws {Error} cannot clear the current line a closed REPL
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Clear the current line:
* repl.clearLine();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'clearLine', function onClearLine() {
if ( this._closed ) {
throw new Error( 'invalid operation. Cannot clear the line of a REPL which has already closed.' );
}
if ( this._isTTY ) {
this._rli.clearLine();
}
return this;
});
/**
* Clears the REPL command buffer.
*
* @name clearCommand
* @memberof REPL.prototype
* @type {Function}
* @throws {Error} cannot clear the command buffer of a closed REPL
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Clear the command buffer:
* repl.clearCommand();
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'clearCommand', function onClearCommand() {
if ( this._closed ) {
throw new Error( 'invalid operation. Cannot clear the command buffer of a REPL which has already closed.' );
}
// Clear any command which has been buffered but not yet executed:
this._cmd.length = 0;
return this;
});
/**
* Closes a REPL.
*
* @name close
* @memberof REPL.prototype
* @type {Function}
* @returns {REPL} REPL instance
*
* @example
* var debug = require( '@stdlib/streams/node/debug-sink' );
*
* // Create a new REPL:
* var repl = new REPL({
* 'output': debug()
* });
*
* // ...
*
* // Close the REPL:
* repl.close();
*/
setNonEnumerableReadOnly( REPL.prototype, 'close', function close() {
var self;
if ( this._closed ) {
debug( 'Attempted to close an already closed REPL.' );
return this;
}
self = this;
this._closed = true;
// Clear the command queue:
this._queue.clear();
// TODO: ensure REPL history is saved (flushed) to file before closing the REPL (see https://github.com/nodejs/node/blob/b21e7c7bcf23a2715951e4cd96180e4dbf1dcd4d/lib/repl.js#L805)
// TODO: ensure REPL log is saved (flushed) to file before closing the REPL
nextTick( onTick );
return this;
/**
* Callback invoked upon the next tick of the event loop.
*
* @private
*/
function onTick() {
var tmp;
var key;
var o;
var i;
var j;
debug( 'Closing readline interface...' );
self._rli.close();
// If this is a non-sandboxed REPL, remove global variables/properties which were introduced during context creation and by a user during a REPL session...
if ( self._sandbox === false ) {
// WARNING: in a non-sandboxed environment, if a global variable is externally introduced during a REPL session (i.e., introduced via a mechanism outside of the REPL environment), we will delete that global variable, which means the following logic may introduce unintended side-effects for this particular edge case (e.g., application code may expect the presence of the subsequently deleted global variable). While not ideal, (a) user applications should not be introducing globals to begin with and (b) the probability of a user running a REPL session, a user closing that REPL session, AND a global variable being introduced between starting a REPL and closing the REPL should be negligible.
tmp = self._context.vars(); // current workspace variables
for ( i = 0; i < tmp.length; i++ ) {
if ( isConfigurableProperty( self._context, tmp[ i ] ) ) {
delete self._context[ tmp[ i ] ];
}
}
// Remove REPL globals:
for ( i = 0; i < self._globalVars.length; i++ ) {
o = self._context;
key = self._globalVars[ i ].split( '.' ); // Note: this addresses nested key paths (e.g., `a.b.c`)
for ( j = 0; j < key.length-1; j++ ) {
if ( !hasOwnProp( o, key[ j ] ) ) {
o = null;
break;
}
o = o[ key[ j ] ];
}
if ( o && isConfigurableProperty( o, key[ j ] ) ) {
delete o[ key[ j ] ];
}
}
}
}
});
// EXPORTS //
module.exports = REPL;
|