diff --git a/z1-prototype/menu.js b/z1-prototype/menu.js new file mode 100644 index 0000000..624789a --- /dev/null +++ b/z1-prototype/menu.js @@ -0,0 +1,34 @@ +const VendingMachine = require('./vendingMachine'); +let vendingMachine = new VendingMachine(); + +const readline = require('readline-sync'); + +function setupMachine() { + vendingMachine.fillMachine(); +} + +function listProducts() { + const products = vendingMachine.getProducts(); + products.forEach((element) => { + if (element.quantity > 0) { + console.log(`${element.id}) ${element.name} - ${element.price}zł`); + } + }); +} + +(async () => { + setupMachine(); + let credit = readline.question(`Insert coins:\n`); + listProducts(); + let id = readline.question(`Choose product from the list:\n`); + let product = vendingMachine.getProductById(id); + if (product.price > credit) { + console.log('Insuficient credit'); + } else { + console.log( + 'Your change ', + vendingMachine.calculateChange(credit - product.price) + ); + console.log('Please take your product'); + } +})(); diff --git a/z1-prototype/node_modules/readline-sync/LICENSE b/z1-prototype/node_modules/readline-sync/LICENSE new file mode 100644 index 0000000..0d289d9 --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 anseki + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/z1-prototype/node_modules/readline-sync/README-Deprecated.md b/z1-prototype/node_modules/readline-sync/README-Deprecated.md new file mode 100644 index 0000000..25128a5 --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/README-Deprecated.md @@ -0,0 +1,89 @@ +# readlineSync + +## Deprecated Methods and Options + +The readlineSync current version is fully compatible with older version. +The following methods and options are deprecated. + +### `setPrint` method + +Use the [`print`](README.md#basic_options-print) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({print: value}); +``` + +instead of: + +```js +readlineSync.setPrint(value); +``` + +### `setPrompt` method + +Use the [`prompt`](README.md#basic_options-prompt) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({prompt: value}); +``` + +instead of: + +```js +readlineSync.setPrompt(value); +``` + +### `setEncoding` method + +Use the [`encoding`](README.md#basic_options-encoding) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({encoding: value}); +``` + +instead of: + +```js +readlineSync.setEncoding(value); +``` + +### `setMask` method + +Use the [`mask`](README.md#basic_options-mask) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({mask: value}); +``` + +instead of: + +```js +readlineSync.setMask(value); +``` + +### `setBufferSize` method + +Use the [`bufferSize`](README.md#basic_options-buffersize) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({bufferSize: value}); +``` + +instead of: + +```js +readlineSync.setBufferSize(value); +``` + +### `noEchoBack` option + +Use [`hideEchoBack`](README.md#basic_options-hideechoback) option instead of it. + +### `noTrim` option + +Use [`keepWhitespace`](README.md#basic_options-keepwhitespace) option instead of it. diff --git a/z1-prototype/node_modules/readline-sync/README.md b/z1-prototype/node_modules/readline-sync/README.md new file mode 100644 index 0000000..4549a51 --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/README.md @@ -0,0 +1,1836 @@ +# readlineSync + +[![npm](https://img.shields.io/npm/v/readline-sync.svg)](https://www.npmjs.com/package/readline-sync) [![GitHub issues](https://img.shields.io/github/issues/anseki/readline-sync.svg)](https://github.com/anseki/readline-sync/issues) [![dependencies](https://img.shields.io/badge/dependencies-No%20dependency-brightgreen.svg)](package.json) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE-MIT) + +Synchronous [Readline](http://nodejs.org/api/readline.html) for interactively running to have a conversation with the user via a console(TTY). + +readlineSync tries to let your script have a conversation with the user via a console, even when the input/output stream is redirected like `your-script bar.log`. + + + +
Basic OptionsUtility MethodsPlaceholders
+ +* Simple case: + +```js +var readlineSync = require('readline-sync'); + +// Wait for user's response. +var userName = readlineSync.question('May I have your name? '); +console.log('Hi ' + userName + '!'); + +// Handle the secret text (e.g. password). +var favFood = readlineSync.question('What is your favorite food? ', { + hideEchoBack: true // The typed text on screen is hidden by `*` (default). +}); +console.log('Oh, ' + userName + ' loves ' + favFood + '!'); +``` + +```console +May I have your name? CookieMonster +Hi CookieMonster! +What is your favorite food? **** +Oh, CookieMonster loves tofu! +``` + +* Get the user's response by a single key without the Enter key: + +```js +var readlineSync = require('readline-sync'); +if (readlineSync.keyInYN('Do you want this module?')) { + // 'Y' key was pressed. + console.log('Installing now...'); + // Do something... +} else { + // Another key was pressed. + console.log('Searching another...'); + // Do something... +} +``` + +* Let the user choose an item from a list: + +```js +var readlineSync = require('readline-sync'), + animals = ['Lion', 'Elephant', 'Crocodile', 'Giraffe', 'Hippo'], + index = readlineSync.keyInSelect(animals, 'Which animal?'); +console.log('Ok, ' + animals[index] + ' goes to your room.'); +``` + +```console +[1] Lion +[2] Elephant +[3] Crocodile +[4] Giraffe +[5] Hippo +[0] CANCEL + +Which animal? [1...5 / 0]: 2 +Ok, Elephant goes to your room. +``` + +* An UI like the Range Slider: +(Press `Z` or `X` key to change a value, and Space Bar to exit) + +```js +var readlineSync = require('readline-sync'), + MAX = 60, MIN = 0, value = 30, key; +console.log('\n\n' + (new Array(20)).join(' ') + + '[Z] <- -> [X] FIX: [SPACE]\n'); +while (true) { + console.log('\x1B[1A\x1B[K|' + + (new Array(value + 1)).join('-') + 'O' + + (new Array(MAX - value + 1)).join('-') + '| ' + value); + key = readlineSync.keyIn('', + {hideEchoBack: true, mask: '', limit: 'zx '}); + if (key === 'z') { if (value > MIN) { value--; } } + else if (key === 'x') { if (value < MAX) { value++; } } + else { break; } +} +console.log('\nA value the user requested: ' + value); +``` + +![sample](screen_03.gif) + +* Handle the commands repeatedly, such as the shell interface: + +```js +readlineSync.promptCLLoop({ + add: function(target, into) { + console.log(target + ' is added into ' + into + '.'); + // Do something... + }, + remove: function(target) { + console.log(target + ' is removed.'); + // Do something... + }, + bye: function() { return true; } +}); +console.log('Exited'); +``` + +```console +> add pic01.png archive +pic01.png is added into archive. +> delete pic01.png +Requested command is not available. +> remove pic01.png +pic01.png is removed. +> bye +Exited +``` + +## Installation + +```console +npm install readline-sync +``` + +## Quick Start + +**How does the user input?** + +- [Type a reply to a question, and press the Enter key](#quick_start-a) (A) +- [Type a keyword like a command in prompt, and press the Enter key](#quick_start-b) (B) +- [Press a single key without the Enter key](#quick_start-c) (C) + +**(A) What does the user input?** + +- [E-mail address](#utility_methods-questionemail) +- [New password](#utility_methods-questionnewpassword) +- [Integer number](#utility_methods-questionint) +- [Floating-point number](#utility_methods-questionfloat) +- [Local file/directory path](#utility_methods-questionpath) +- [Others](#basic_methods-question) + +**(B) What does your script do?** + +- [Receive a parsed command-name and arguments](#utility_methods-promptcl) +- [Receive an input repeatedly](#utility_methods-promptloop) +- [Receive a parsed command-name and arguments repeatedly](#utility_methods-promptclloop) +- [Receive an input with prompt that is similar to that of the user's shell](#utility_methods-promptsimshell) +- [Others](#basic_methods-prompt) + +**(C) What does the user do?** + +- [Say "Yes" or "No"](#utility_methods-keyinyn) +- [Say "Yes" or "No" explicitly](#utility_methods-keyinynstrict) +- [Make the running of script continue when ready](#utility_methods-keyinpause) +- [Choose an item from a list](#utility_methods-keyinselect) +- [Others](#basic_methods-keyin) + +## Basic Methods + +These are used to control details of the behavior. It is recommended to use the [Utility Methods](#utility_methods) instead of Basic Methods if it satisfy your request. + +### `question` + +```js +answer = readlineSync.question([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return the input from the user after it has been typed and the Enter key was pressed. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). **If you let the user input the secret text (e.g. password), you should consider [`hideEchoBack`](#basic_options-hideechoback) option.** + +The `query` may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also) +It can include the [placeholders](#placeholders). + +For example: + +```js +program = readlineSync.question('Which program starts do you want? ', { + defaultInput: 'firefox' +}); +``` + +### `prompt` + +```js +input = readlineSync.prompt([options]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then return the input from the user after it has been typed and the Enter key was pressed. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). + +For example: + +```js +while (true) { + command = readlineSync.prompt(); + // Do something... +} +``` + +### `keyIn` + +```js +pressedKey = readlineSync.keyIn([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return a character as a key immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. ignoring keys except some keys, checking target key, etc.). + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +For example: + +```js +menuId = readlineSync.keyIn('Hit 1...5 key: ', {limit: '$<1-5>'}); +``` + +### `setDefaultOptions` + +```js +currentDefaultOptions = readlineSync.setDefaultOptions([newDefaultOptions]) +``` + +Change the [Default Options](#basic_options) to the values of properties of `newDefaultOptions` Object. +All it takes is to specify options that you want change, because unspecified options are not updated. + +## Basic Options + +[`prompt`](#basic_options-prompt), [`hideEchoBack`](#basic_options-hideechoback), [`mask`](#basic_options-mask), [`limit`](#basic_options-limit), [`limitMessage`](#basic_options-limitmessage), [`defaultInput`](#basic_options-defaultinput), [`trueValue`, `falseValue`](#basic_options-truevalue_falsevalue), [`caseSensitive`](#basic_options-casesensitive), [`keepWhitespace`](#basic_options-keepwhitespace), [`encoding`](#basic_options-encoding), [`bufferSize`](#basic_options-buffersize), [`print`](#basic_options-print), [`history`](#basic_options-history), [`cd`](#basic_options-cd) + +An `options` Object can be specified to the methods to control the behavior of readlineSync. The options that were not specified to the methods are got from the Default Options. You can change the Default Options by [`setDefaultOptions`](#basic_methods-setdefaultoptions) method anytime, and it is kept until a current process is exited. +Specify the options that are often used to the Default Options, and specify temporary options to the methods. + +For example: + +```js +readlineSync.setDefaultOptions({limit: ['green', 'yellow', 'red']}); +a1 = readlineSync.question('Which color of signal? '); // Input is limited to 3 things. +a2 = readlineSync.question('Which color of signal? '); // It's limited yet. +a3 = readlineSync.question('What is your favorite color? ', {limit: null}); // It's unlimited temporarily. +a4 = readlineSync.question('Which color of signal? '); // It's limited again. +readlineSync.setDefaultOptions({limit: ['beef', 'chicken']}); +a5 = readlineSync.question('Beef or Chicken? '); // Input is limited to new 2 things. +a6 = readlineSync.question('And you? '); // It's limited to 2 things yet. +``` + +The Object as `options` can have following properties. + +### `prompt` + +_For `prompt*` methods only_ +*Type:* string or others +*Default:* `'> '` + +Set the prompt-sign that is displayed to the user by `prompt*` methods. For example you see `> ` that is Node.js's prompt-sign when you run `node` on the command line. +This may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string every time (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also) +It can include the [placeholders](#placeholders). + +For example: + +```js +readlineSync.setDefaultOptions({prompt: '$ '}); +``` + +```js +// Display the memory usage always. +readlineSync.setDefaultOptions({ + prompt: { // Simple Object that has toString method. + toString: function() { + var rss = process.memoryUsage().rss; + return '[' + (rss > 1024 ? Math.round(rss / 1024) + 'k' : rss) + 'b]$ '; + } + } +}); +``` + +```console +[13148kb]$ foo +[13160kb]$ bar +[13200kb]$ +``` + +### `hideEchoBack` + +*Type:* boolean +*Default:* `false` + +If `true` is specified, hide the secret text (e.g. password) which is typed by user on screen by the mask characters (see [`mask`](#basic_options-mask) option). + +For example: + +```js +password = readlineSync.question('PASSWORD: ', {hideEchoBack: true}); +console.log('Login ...'); +``` + +```console +PASSWORD: ******** +Login ... +``` + +### `mask` + +*Type:* string +*Default:* `'*'` + +Set the mask characters that are shown instead of the secret text (e.g. password) when `true` is specified to [`hideEchoBack`](#basic_options-hideechoback) option. If you want to show nothing, specify `''`. (But it might be not user friendly in some cases.) +**Note:** In some cases (e.g. when the input stream is redirected on Windows XP), `'*'` or `''` might be used whether other one is specified. + +For example: + +```js +secret = readlineSync.question('Please whisper sweet words: ', { + hideEchoBack: true, + mask: require('chalk').magenta('\u2665') +}); +``` + +![sample](screen_02.gif) + +### `limit` + +Limit the user's input. +The usage differ depending on the method. + +#### For `question*` and `prompt*` methods + +*Type:* string, number, RegExp, function or Array +*Default:* `[]` + +Accept only the input that matches value that is specified to this. If the user input others, display a string that is specified to [`limitMessage`](#basic_options-limitmessage) option, and wait for reinput. + +* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. +* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. +* The RegExp tests the input. +* The function that returns a boolean to indicate whether it matches is called with the input. + +One of above or an Array that includes multiple things (or Array includes Array) can be specified. + +For example: + +```js +command = readlineSync.prompt({limit: ['add', 'remove', /^clear( all)?$/]}); +// ** But `promptCL` method should be used instead of this. ** +``` + +```js +file = readlineSync.question('Text File: ', {limit: /\.txt$/i}); +// ** But `questionPath` method should be used instead of this. ** +``` + +```js +ip = readlineSync.question('IP Address: ', {limit: function(input) { + return require('net').isIP(input); // Valid IP Address +}}); +``` + +```js +availableActions = []; +if (!blockExists()) { availableActions.push('jump'); } +if (isLarge(place)) { availableActions.push('run'); } +if (isNew(shoes)) { availableActions.push('kick'); } +if (isNearby(enemy)) { availableActions.push('punch'); } +action = readlineSync.prompt({limit: availableActions}); +// ** But `promptCL` method should be used instead of this. ** +``` + +#### For `keyIn*` method + +*Type:* string, number or Array +*Default:* `[]` + +Accept only the key that matches value that is specified to this, ignore others. +Specify the characters as the key. All strings or Array of those are decomposed into single characters. For example, `'abcde'` or `['a', 'bc', ['d', 'e']]` are the same as `['a', 'b', 'c', 'd', 'e']`. +These strings are compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. + +The [placeholders](#placeholders) like `'$'` are replaced to an Array that is the character list like `['a', 'b', 'c', 'd', 'e']`. + +For example: + +```js +direction = readlineSync.keyIn('Left or Right? ', {limit: 'lr'}); // 'l' or 'r' +``` + +```js +dice = readlineSync.keyIn('Roll the dice, What will the result be? ', + {limit: '$<1-6>'}); // range of '1' to '6' +``` + +### `limitMessage` + +_For `question*` and `prompt*` methods only_ +*Type:* string +*Default:* `'Input another, please.$<( [)limit(])>'` + +Display this to the user when the [`limit`](#basic_options-limit) option is specified and the user input others. +The [placeholders](#placeholders) can be included. + +For example: + +```js +file = readlineSync.question('Name of Text File: ', { + limit: /\.txt$/i, + limitMessage: 'Sorry, $ is not text file.' +}); +``` + +### `defaultInput` + +_For `question*` and `prompt*` methods only_ +*Type:* string +*Default:* `''` + +If the user input empty text (i.e. pressed the Enter key only), return this. + +For example: + +```js +lang = readlineSync.question('Which language? ', {defaultInput: 'javascript'}); +``` + +### `trueValue`, `falseValue` + +*Type:* string, number, RegExp, function or Array +*Default:* `[]` + +If the input matches `trueValue`, return `true`. If the input matches `falseValue`, return `false`. In any other case, return the input. + +* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. +* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. Note that in `keyIn*` method, the input is every time one character (i.e. the number that is specified must be an integer within the range of `0` to `9`). +* The RegExp tests the input. +* The function that returns a boolean to indicate whether it matches is called with the input. + +One of above or an Array that includes multiple things (or Array includes Array) can be specified. + +For example: + +```js +answer = readlineSync.question('How do you like it? ', { + trueValue: ['yes', 'yeah', 'yep'], + falseValue: ['no', 'nah', 'nope'] +}); +if (answer === true) { + console.log('Let\'s go!'); +} else if (answer === false) { + console.log('Oh... It\'s ok...'); +} else { + console.log('Sorry. What does "' + answer + '" you said mean?'); +} +``` + +### `caseSensitive` + +*Type:* boolean +*Default:* `false` + +By default, the string comparisons are case-insensitive (i.e. `a` equals `A`). If `true` is specified, it is case-sensitive, the cases are not ignored (i.e. `a` is different from `A`). +It affects: [`limit`](#basic_options-limit), [`trueValue`](#basic_options-truevalue_falsevalue), [`falseValue`](#basic_options-truevalue_falsevalue), some [placeholders](#placeholders), and some [Utility Methods](#utility_methods). + +### `keepWhitespace` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `false` + +By default, remove the leading and trailing white spaces from the input text. If `true` is specified, don't remove those. + +### `encoding` + +*Type:* string +*Default:* `'utf8'` + +Set the encoding method of the input and output. + +### `bufferSize` + +_For `question*` and `prompt*` methods only_ +*Type:* number +*Default:* `1024` + +When readlineSync reads from a console directly (without [external program](#note-reading_by_external_program)), use a size `bufferSize` buffer. +Even if the input by user exceeds it, it's usually no problem, because the buffer is used repeatedly. But some platforms's (e.g. Windows) console might not accept input that exceeds it. And set an enough size. +Note that this might be limited by [version of Node.js](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding) and environment running your script (Big buffer size is usually not required). (See also: [issue](https://github.com/nodejs/node/issues/4660), [PR](https://github.com/nodejs/node/pull/4682)) + +### `print` + +*Type:* function or `undefined` +*Default:* `undefined` + +Call the specified function with every output. The function is given two arguments, `display` as an output text, and a value of [`encoding`](#basic_options-encoding) option. + +For example: + +* Pass the plain texts to the Logger (e.g. [log4js](https://github.com/nomiddlename/log4js-node)), after clean the colored texts. + +![sample](screen_01.png) + +```js +var readlineSync = require('readline-sync'), + chalk = require('chalk'), + log4js = require('log4js'), + logger, user, pw, command; + +log4js.configure({appenders: [{type: 'file', filename: 'fooApp.log'}]}); +logger = log4js.getLogger('fooApp'); + +readlineSync.setDefaultOptions({ + print: function(display, encoding) + { logger.info(chalk.stripColor(display)); }, // Remove ctrl-chars. + prompt: chalk.red.bold('> ') +}); + +console.log(chalk.black.bold.bgYellow(' Your Account ')); +user = readlineSync.question(chalk.gray.underline(' USER NAME ') + ' : '); +pw = readlineSync.question(chalk.gray.underline(' PASSWORD ') + ' : ', + {hideEchoBack: true}); +// Authorization ... +console.log(chalk.green('Welcome, ' + user + '!')); +command = readlineSync.prompt(); +``` + +* Output a conversation to a file when an output stream is redirected to record those into a file like `your-script >foo.log`. That is, a conversation isn't outputted to `foo.log` without this code. + +```js +readlineSync.setDefaultOptions({ + print: function(display, encoding) + { process.stdout.write(display, encoding); } +}); +var name = readlineSync.question('May I have your name? '); +var loc = readlineSync.question('Hi ' + name + '! Where do you live? '); +``` + +* Let somebody hear our conversation in real time. +It just uses a fifo with above sample code that was named `conv.js`. + +Another terminal: + +```console +mkfifo /tmp/fifo +cat /tmp/fifo +``` + +My terminal: + +```console +node conv.js >/tmp/fifo +``` + +```console +May I have your name? Oz +Hi Oz! Where do you live? Emerald City +``` + +And then, another terminal shows this synchronously: + +```console +May I have your name? Oz +Hi Oz! Where do you live? Emerald City +``` + +### `history` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `true` + +readlineSync supports a history expansion feature that is similar to that of the shell. If `false` is specified, disable this feature. +*It keeps a previous input only.* That is, only `!!`, `!-1`, `!!:p` and `!-1:p` like bash or zsh etc. are supported. + +* `!!` or `!-1`: Return a previous input. +* `!!:p` or `!-1:p`: Display a previous input but do not return it, and wait for reinput. + +For example: + +```js +while (true) { + input = readlineSync.prompt(); + console.log('-- You said "' + input + '"'); +} +``` + +```console +> hello +-- You said "hello" +> !! +hello +-- You said "hello" +> !!:p +hello +> bye +-- You said "bye" +``` + +### `cd` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `false` + +readlineSync supports the changing the current working directory feature that is similar to the `cd` and `pwd` commands in the shell. If `true` is specified, enable this feature. +This helps the user when you let the user input the multiple local files or directories. +It supports `cd` and `pwd` commands. + +* `cd `: Change the current working directory to ``. The `` can include `~` as the home directory. +* `pwd`: Display the current working directory. + +When these were input, do not return, and wait for reinput. + +For example: + +```js +while (true) { + file = readlineSync.questionPath('File: '); + console.log('-- Specified file is ' + file); +} +``` + +```console +File: cd foo-dir/bar-dir +File: pwd +/path/to/foo-dir/bar-dir +File: file-a.js +-- Specified file is /path/to/foo-dir/bar-dir/file-a.js +File: file-b.png +-- Specified file is /path/to/foo-dir/bar-dir/file-b.png +File: file-c.html +-- Specified file is /path/to/foo-dir/bar-dir/file-c.html +``` + +## Utility Methods + +[`questionEMail`](#utility_methods-questionemail), [`questionNewPassword`](#utility_methods-questionnewpassword), [`questionInt`](#utility_methods-questionint), [`questionFloat`](#utility_methods-questionfloat), [`questionPath`](#utility_methods-questionpath), [`promptCL`](#utility_methods-promptcl), [`promptLoop`](#utility_methods-promptloop), [`promptCLLoop`](#utility_methods-promptclloop), [`promptSimShell`](#utility_methods-promptsimshell), [`keyInYN`](#utility_methods-keyinyn), [`keyInYNStrict`](#utility_methods-keyinynstrict), [`keyInPause`](#utility_methods-keyinpause), [`keyInSelect`](#utility_methods-keyinselect) + +These are convenient methods that are extended [Basic Methods](#basic_methods) to be used easily. + +### `questionEMail` + +```js +email = readlineSync.questionEMail([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid e-mail address, and then return it after the Enter key was pressed. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input e-mail address: '`. + +**Note:** The valid e-mail address requirement is a willful violation of [RFC5322](http://tools.ietf.org/html/rfc5322), this is defined in [HTML5](http://www.w3.org/TR/html5/forms.html). This works enough to prevent the user mistaking. If you want to change it, specify [`limit`](#basic_options-limit) option. + +For example: + +```js +email = readlineSync.questionEMail(); +console.log('-- E-mail is ' + email); +``` + +```console +Input e-mail address: abc +Input valid e-mail address, please. +Input e-mail address: mail@example.com +-- E-mail is mail@example.com +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limit`](#basic_options-limit) | RegExp by [HTML5](http://www.w3.org/TR/html5/forms.html) | +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid e-mail address, please.'` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
maskdefaultInputcaseSensitiveencodingbufferSize
printhistory
+ +### `questionNewPassword` + +```js +password = readlineSync.questionNewPassword([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid password, and then request same one again, and then return it after the Enter key was pressed. +It's the password, or something that is the secret text like the password. +You can specify the valid password requirement to the options. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input new password: '`. + +**Note:** Only the form of password is checked. Check it more if you want. For example, [zxcvbn](https://github.com/dropbox/zxcvbn) is password strength estimation library. + +For example: + +```js +password = readlineSync.questionNewPassword(); +console.log('-- Password is ' + password); +``` + +```console +Input new password: ************ +It can include: 0...9, A...Z, a...z, !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ +And the length must be: 12...24 +Input new password: ************* +Reinput a same one to confirm it: ************* +It differs from first one. Hit only the Enter key if you want to retry from first one. +Reinput a same one to confirm it: ************* +-- Password is _my_password_ +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `true` | +| [`mask`](#basic_options-mask) | `'*'` | +| [`limitMessage`](#basic_options-limitmessage) | `'It can include: $\nAnd the length must be: $'` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`caseSensitive`](#basic_options-casesensitive) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
defaultInputkeepWhitespaceencodingbufferSizeprint
+ +And the following additional options are available. + +##### `charlist` + +*Type:* string +*Default:* `'$'` + +A string as the characters that can be included in the password. For example, if `'abc123'` is specified, the passwords that include any character other than these 6 characters are refused. +The [placeholders](#placeholders) like `'$'` are replaced to the characters like `'abcde'`. + +For example, let the user input a password that is created with alphabet and some symbols: + +```js +password = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); +``` + +##### `min`, `max` + +*Type:* number +*Default:* `min`: `12`, `max`: `24` + +`min`: A number as a minimum length of the password. +`max`: A number as a maximum length of the password. + +##### `confirmMessage` + +*Type:* string or others +*Default:* `'Reinput a same one to confirm it: '` + +A message that lets the user input the same password again. +It can include the [placeholders](#placeholders). +If this is not string, it is converted to string (i.e. `toString` method is called). + +##### `unmatchMessage` + +*Type:* string or others +*Default:* `'It differs from first one. Hit only the Enter key if you want to retry from first one.'` + +A warning message that is displayed when the second input did not match first one. +This is converted the same as the [`confirmMessage`](#utility_methods-questionnewpassword-options-confirmmessage) option. + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `charlist` + +A current value of [`charlist`](#utility_methods-questionnewpassword-options-charlist) option that is converted to human readable if possible. (e.g. `'A...Z'`) + +##### `length` + +A current value of [`min` and `max`](#utility_methods-questionnewpassword-options-min_max) option that is converted to human readable. (e.g. `'12...24'`) + +### `questionInt` + +```js +numInt = readlineSync.questionInt([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as an integer, and then return the number (not string) after the Enter key was pressed. +This parses the input as much as possible by `parseInt()`. For example, it interprets `' 5 '`, `'5.6'`, `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
hideEchoBackmaskdefaultInputencodingbufferSize
printhistory
+ +### `questionFloat` + +```js +numFloat = readlineSync.questionFloat([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as a floating-point number, and then return the number (not string) after the Enter key was pressed. +This parses the input as much as possible by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
hideEchoBackmaskdefaultInputencodingbufferSize
printhistory
+ +### `questionPath` + +```js +path = readlineSync.questionPath([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid local file or directory path, and then return an absolute path after the Enter key was pressed. +The `~` that is input by the user is replaced to the home directory. +You can specify the valid local file or directory path requirement to the options. And you can make it create a new file or directory when it doesn't exist. + +It is recommended to use this method with the [`cd`](#basic_options-cd) option. (Default: `true`) + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input path (you can "cd" and "pwd"): '`. + +For example: + +```js +sourceFile = readlineSync.questionPath('Read from: ', { + isFile: true +}); +console.log('-- sourceFile: ' + sourceFile); + +saveDir = readlineSync.questionPath('Save to: ', { + isDirectory: true, + exists: null, + create: true +}); +console.log('-- saveDir: ' + saveDir); +``` + +```console +Read from: ~/fileA +No such file or directory: /home/user/fileA +Input valid path, please. +Read from: pwd +/path/to/work +Read from: cd ~/project-1 +Read from: fileA +-- sourceFile: /home/user/project-1/fileA +Save to: ~/deploy/data +-- saveDir: /home/user/deploy/data +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'$Input valid path, please.$<( Min:)min>$<( Max:)max>'` | +| [`history`](#basic_options-history) | `true` | +| [`cd`](#basic_options-cd) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
maskdefaultInputencodingbufferSizeprint
+ +And the following additional options are available. + +**Note:** It does not check the coherency about a combination of the options as the path requirement. For example, the `{exists: false, isFile: true}` never check that it is a file because it is limited to the path that does not exist. + +##### `exists` + +*Type:* boolean or others +*Default:* `true` + +If `true` is specified, accept only a file or directory path that exists. If `false` is specified, accept only a file or directory path that does *not* exist. +In any other case, the existence is not checked. + +##### `min`, `max` + +*Type:* number or others +*Default:* `undefined` + +`min`: A number as a minimum size of the file that is accepted. +`max`: A number as a maximum size of the file that is accepted. +If it is not specified or `0` is specified, the size is not checked. (A size of directory is `0`.) + +##### `isFile`, `isDirectory` + +*Type:* boolean +*Default:* `false` + +`isFile`: If `true` is specified, accept only a file path. +`isDirectory`: If `true` is specified, accept only a directory path. + +##### `validate` + +*Type:* function or `undefined` +*Default:* `undefined` + +If a function that returns `true` or an error message is specified, call it with a path that was input, and accept the input when the function returned `true`. +If the function returned a string as an error message, that message is got by the [`error`](#utility_methods-questionpath-additional_placeholders-error) additional [placeholder](#placeholders) parameter. +A path that was input is parsed before it is passed to the function. `~` is replaced to a home directory, and a path is converted to an absolute path. +This is also a return value from this method. + +For example, accept only PNG file or tell it to the user: + +```js +imageFile = readlineSync.questionPath('Image File: ', { + validate: function(path) { return /\.png$/i.test(path) || 'It is not PNG'; } +}); +``` + +##### `create` + +*Type:* boolean +*Default:* `false` + +If `true` is specified, create a file or directory as a path that was input when it doesn't exist. If `true` is specified to the [`isDirectory`](#utility_methods-questionpath-options-isfile_isdirectory) option, create a directory, otherwise a file. +It does not affect the existence check. Therefore, you can get a new file or directory path anytime by specifying: `{exists: false, create: true}` + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `error` + +An error message when the input was not accepted. +This value is set by readlineSync, or the function that was specified to [`validate`](#utility_methods-questionpath-options-validate) option. + +##### `min`, `max` + +A current value of [`min` and `max`](#utility_methods-questionpath-options-min_max) option. + +### `promptCL` + +```js +argsArray = readlineSync.promptCL([commandHandler[, options]]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then consider the input as a command-line and parse it, and then return a result after the Enter key was pressed. +A return value is an Array that includes the tokens that were parsed. It parses the input from the user as the command-line, and it interprets whitespaces, quotes, etc., and it splits it to tokens properly. Usually, a first element of the Array is command-name, and remaining elements are arguments. + +For example: + +```js +argsArray = readlineSync.promptCL(); +console.log(argsArray.join('\n')); +``` + +```console +> command arg "arg" " a r g " "" 'a"r"g' "a""rg" "arg +command +arg +arg + a r g + +a"r"g +arg +arg +``` + +#### `commandHandler` + +By using the `commandHandler` argument, this method will come into its own. Specifying the Object to this argument has the more merit. And it has the more merit for [`promptCLLoop`](#utility_methods-promptclloop) method. + +If a function is specified to `commandHandler` argument, it is just called with a parsed Array as an argument list of the function. And `this` is an original input string, in the function. + +For example, the following 2 codes work same except that `this` is enabled in the second one: + +```js +argsArray = readlineSync.promptCL(); +if (argsArray[0] === 'add') { + console.log(argsArray[1] + ' is added.'); +} else if (argsArray[0] === 'copy') { + console.log(argsArray[1] + ' is copied to ' + argsArray[2] + '.'); +} +``` + +```js +readlineSync.promptCL(function(command, arg1, arg2) { + console.log('You want to: ' + this); // All of command-line. + if (command === 'add') { + console.log(arg1 + ' is added.'); + } else if (command === 'copy') { + console.log(arg1 + ' is copied to ' + arg2 + '.'); + } +}); +``` + +If an Object that has properties named as the command-name is specified, the command-name is interpreted, and a function as the value of matched property is called. A function is chosen properly by handling case of the command-name in accordance with the [`caseSensitive`](#basic_options-casesensitive) option. +The function is called with a parsed Array that excludes a command-name (i.e. first element is removed from the Array) as an argument list of the function. +That is, a structure of the `commandHandler` Object looks like: + +```js +{ + commandA: function(arg) { ... }, // commandA requires one argument. + commandB: function(arg1, arg2) { ... }, // readlineSync doesn't care those. + commandC: function() { ... } // Of course, it can also ignore all. +} +``` + +readlineSync just receives the arguments from the user and passes those to these functions without checking. The functions may have to check whether the required argument was input by the user, and more validate those. + +For example, the following code works same to the above code: + +```js +readlineSync.promptCL({ + add: function(element) { // It's called by also "ADD", "Add", "aDd", etc.. + console.log(element + ' is added.'); + }, + copy: function(from, to) { + console.log(from + ' is copied to ' + to + '.'); + } +}); +``` + +If the matched property is not found in the Object, a `_` property is chosen, and the function as the value of this property is called with a parsed Array as an argument list of the function. Note that this includes a command-name. That is, the function looks like `function(command, arg1, arg2, ...) { ... }`. +And if the Object doesn't have a `_` property, any command that the matched property is not found in the Object is refused. + +For example: + +```js +readlineSync.promptCL({ + copy: function(from, to) { // command-name is not included. + console.log(from + ' is copied to ' + to + '.'); + }, + _: function(command) { // command-name is included. + console.log('Sorry, ' + command + ' is not available.'); + } +}); +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
promptmaskdefaultInputencodingbufferSize
printcd
+ +### `promptLoop` + +```js +readlineSync.promptLoop(inputHandler[, options]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then call `inputHandler` function with the input from the user after it has been typed and the Enter key was pressed. Do these repeatedly until `inputHandler` function returns `true`. + +For example, the following 2 codes work same: + +```js +while (true) { + input = readlineSync.prompt(); + console.log('-- You said "' + input + '"'); + if (input === 'bye') { + break; + } +} +console.log('It\'s exited from loop.'); +``` + +```js +readlineSync.promptLoop(function(input) { + console.log('-- You said "' + input + '"'); + return input === 'bye'; +}); +console.log('It\'s exited from loop.'); +``` + +```console +> hello +-- You said "hello" +> good morning +-- You said "good morning" +> bye +-- You said "bye" +It's exited from loop. +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The other options work as shown in the [Basic Options](#basic_options) section. + +### `promptCLLoop` + +```js +readlineSync.promptCLLoop([commandHandler[, options]]) +``` + +Execute [`promptCL`](#utility_methods-promptcl) method repeatedly until chosen [`commandHandler`](#utility_methods-promptcl-commandhandler) returns `true`. +The [`commandHandler`](#utility_methods-promptcl-commandhandler) may be a function that is called like: + +```js +exit = allCommands(command, arg1, arg2, ...); +``` + +or an Object that has the functions that are called like: + +```js +exit = foundCommand(arg1, arg2, ...); +``` + +See [`promptCL`](#utility_methods-promptcl) method for details. +This method looks like a combination of [`promptCL`](#utility_methods-promptcl) method and [`promptLoop`](#utility_methods-promptloop) method. + +For example: + +```js +readlineSync.promptCLLoop({ + add: function(element) { + console.log(element + ' is added.'); + }, + copy: function(from, to) { + console.log(from + ' is copied to ' + to + '.'); + }, + bye: function() { return true; } +}); +console.log('It\'s exited from loop.'); +``` + +```console +> add "New Hard Disk" +New Hard Disk is added. +> move filesOnOld "New Hard Disk" +Requested command is not available. +> copy filesOnOld "New Hard Disk" +filesOnOld is copied to New Hard Disk. +> bye +It's exited from loop. +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
promptmaskdefaultInputencodingbufferSize
printcd
+ +### `promptSimShell` + +```js +input = readlineSync.promptSimShell([options]) +``` + +Display a prompt-sign that is similar to that of the user's shell to the user, and then return the input from the user after it has been typed and the Enter key was pressed. +This method displays a prompt-sign like: + +On Windows: + +```console +C:\Users\User\Path\To\Directory> +``` + +On others: + +```console +user@host:~/path/to/directory$ +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`history`](#basic_options-history) | `true` | + +The other options other than [`prompt`](#basic_options-prompt) option work as shown in the [Basic Options](#basic_options) section. + +### `keyInYN` + +```js +boolYesOrEmpty = readlineSync.keyInYN([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return a boolean or an empty string immediately a key was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key: + +* `Y`: `true` +* `N`: `false` +* other: `''` + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Are you sure? '`. + +The keys other than `Y` and `N` are also accepted (If you want to know a user's wish explicitly, use [`keyInYNStrict`](#utility_methods-keyinynstrict) method). Therefore, if you let the user make an important decision (e.g. files are removed), check whether the return value is not *falsy*. That is, a default is "No". + +For example: + +```js +if (!readlineSync.keyInYN('Do you want to install this?')) { + // Key that is not `Y` was pressed. + process.exit(); +} +// Do something... +``` + +Or if you let the user stop something that must be done (e.g. something about the security), check whether the return value is `false` explicitly. That is, a default is "Yes". + +For example: + +```js +// Don't use `(!readlineSync.keyInYN())`. +if (readlineSync.keyInYN('Continue virus scan?') === false) { + // `N` key was pressed. + process.exit(); +} +// Continue... +``` + +#### Options + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
encodingprint
+ +And the following additional option is available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string `'[y/n]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. + +For example: + +```js +readlineSync.keyInYN('Do you like me?'); // No colon +readlineSync.keyInYN('Really? :'); // Colon already exists +``` + +```console +Do you like me? [y/n]: y +Really? [y/n]: y +``` + +### `keyInYNStrict` + +```js +boolYes = readlineSync.keyInYNStrict([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only `Y` or `N` key, and then return a boolean immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key: + +* `Y`: `true` +* `N`: `false` + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Are you sure? '`. + +A key other than `Y` and `N` is not accepted. That is, a return value has no default. Therefore, the user has to tell an own wish explicitly. If you want to know a user's wish easily, use [`keyInYN`](#utility_methods-keyinyn) method. + +This method works same to [`keyInYN`](#utility_methods-keyinyn) method except that this accept only `Y` or `N` key (Therefore, a return value is boolean every time). The options also work same to [`keyInYN`](#utility_methods-keyinyn) method. + +### `keyInPause` + +```js +readlineSync.keyInPause([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then just wait for a key to be pressed by the user. +This method works like the `window.alert` method of web browsers. This is used to make the running of script pause and show something to the user, or wait for the user to be ready. +By default, any key is accepted (See: [Note](#utility_methods-keyinpause-note)). You can change this behavior by specifying [`limit`](#basic_options-limit) option (e.g. accept only a Space Bar). + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Continue...'`. + +For example: + +```js +// Have made the preparations for something... +console.log('==== Information of Your Computer ===='); +console.log(info); // This can be `query`. +readlineSync.keyInPause(); +console.log('It\'s executing now...'); +// Do something... +``` + +```console +==== Information of Your Computer ==== +FOO: 123456 +BAR: abcdef +Continue... (Hit any key) +It's executing now... +``` + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limit`](#basic_options-limit) | `null` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
caseSensitiveencodingprint
+ +And the following additional option is available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string `'(Hit any key)'` as guide for the user is added to `query`. + +For example: + +```js +readlineSync.keyInPause('It\'s pausing now...'); +``` + +```console +It's pausing now... (Hit any key) +``` + +#### Note + +Control keys including Enter key are not accepted by `keyIn*` methods. +If you want to wait until the user presses Enter key, use `question*` methods instead of `keyIn*` methods. For example: + +```js +readlineSync.question('Hit Enter key to continue.', {hideEchoBack: true, mask: ''}); +``` + +### `keyInSelect` + +```js +index = readlineSync.keyInSelect(items[, query[, options]]) +``` + +Display the list that was created with the `items` Array, and the `query` to the user if it's specified, and then return the number as an index of the `items` Array immediately it was chosen by pressing a key by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Choose one from list: '`. + +The minimum length of `items` Array is 1 and maximum length is 35. These elements are displayed as item list. A key to let the user choose an item is assigned to each item automatically in sequence like "1, 2, 3 ... 9, A, B, C ...". A number as an index of the `items` Array that corresponds to a chosen item by the user is returned. + +**Note:** Even if the `items` Array has only less than 35 items, a long Array that forces an user to scroll the list may irritate the user. Remember, the user might be in a console environment that doesn't support scrolling the screen. If you want to use a long `items` Array (e.g. more than 10 items), you should consider a "Pagination". (See [example](https://github.com/anseki/readline-sync/issues/60#issuecomment-324533678).) + +For example: + +```js +frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; +index = readlineSync.keyInSelect(frameworks, 'Which framework?'); +console.log(frameworks[index] + ' is enabled.'); +``` + +```console +[1] Express +[2] hapi +[3] flatiron +[4] MEAN.JS +[5] locomotive +[0] CANCEL + +Which framework? [1...5 / 0]: 2 +hapi is enabled. +``` + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
maskencodingprint
+ +And the following additional options are available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string like `'[1...5]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. This is the key list that corresponds to the item list. + +##### `cancel` + +*Type:* boolean, string or others +*Default:* `'CANCEL'` + +If a value other than `false` is specified, an item to let the user tell "cancel" is added to the item list. "[0] CANCEL" (default) is displayed, and if `0` key is pressed, `-1` is returned. +You can specify a label of this item other than `'CANCEL'`. A string such as `'Go back'` (empty string `''` also), something that is converted to string such as `Date`, a string that includes [placeholder](#placeholders) such as `'Next $ items'` are accepted. + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `itemsCount` + +A length of a current `items` Array. + +For example: + +```js +items = ['item-A', 'item-B', 'item-C', 'item-D', 'item-E']; +index = readlineSync.keyInSelect(items, null, + {cancel: 'Show more than $ items'}); +``` + +```console +[1] item-A +[2] item-B +[3] item-C +[4] item-D +[5] item-E +[0] Show more than 5 items +``` + +##### `firstItem` + +A first item in a current `items` Array. + +For example: + +```js +index = readlineSync.keyInSelect(items, 'Choose $ or another: '); +``` + +##### `lastItem` + +A last item in a current `items` Array. + +For example: + +```js +items = ['January', 'February', 'March', 'April', 'May', 'June']; +index = readlineSync.keyInSelect(items, null, + {cancel: 'In after $'}); +``` + +```console +[1] January +[2] February +[3] March +[4] April +[5] May +[6] June +[0] In after June +``` + +## Placeholders + +[`hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue`](#placeholders-parameters-hideechoback_mask_defaultinput_casesensitive_keepwhitespace_encoding_buffersize_history_cd_limit_truevalue_falsevalue), [`limitCount`, `limitCountNotZero`](#placeholders-parameters-limitcount_limitcountnotzero), [`lastInput`](#placeholders-parameters-lastinput), [`history_mN`](#placeholders-parameters-historymn), [`cwd`, `CWD`, `cwdHome`](#placeholders-parameters-cwd_cwd_cwdhome), [`date`, `time`, `localeDate`, `localeTime`](#placeholders-parameters-date_time_localedate_localetime), [`C1-C2`](#placeholders-parameters-c1_c2) + +The placeholders in the text are replaced to another string. + +For example, the [`limitMessage`](#basic_options-limitmessage) option to display a warning message that means that the command the user requested is not available: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: '$ is not available.' +}); +``` + +```console +> delete +delete is not available. +``` + +The placeholders can be included in: + +* `query` argument +* [`prompt`](#basic_options-prompt) and [`limitMessage`](#basic_options-limitmessage) options +* [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method ([`C1-C2`](#placeholders-parameters-c1_c2) parameter only) +* And some additional options for the [Utility Methods](#utility_methods). + +### Syntax + +``` +$ +``` + +Or + +``` +$<(text1)parameter(text2)> +``` + +The placeholder is replaced to a string that is got by a `parameter`. +Both the `(text1)` and `(text2)` are optional. +A more added `'$'` at the left of the placeholder is used as an escape character, it disables a placeholder. For example, `'$$'` is replaced to `'$'`. If you want to put a `'$'` which is *not* an escape character at the left of a placeholder, specify it like `'$<($)bufferSize>'`, then it is replaced to `'$1024'`. + +At the each position of `'(text1)'` and `'(text2)'`, `'text1'` and `'text2'` are put when a string that was got by a `parameter` has more than 0 length. If that got string is `''`, a placeholder with or without `'(text1)'` and `'(text2)'` is replaced to `''`. + +For example, a warning message that means that the command the user requested is not available: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: 'Refused $ you requested. Please input another.' +}); +``` + +```console +> give-me-car +Refused give-me-car you requested. Please input another. +``` + +It looks like no problem. +But when the user input nothing (hit only the Enter key), and then a message is displayed: + +```console +> +Refused you requested. Please input another. +``` + +This goes well: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: 'Refused $. Please input another.' +}); +``` + +```console +> +Refused . Please input another. +``` + +(May be more better: `'$<(Refused )lastInput( you requested. )>Please input another.'`) + +**Note:** The syntax `${parameter}` of older version is still supported, but this should not be used because it may be confused with template string syntax of ES6. And this will not be supported in due course of time. + +### Parameters + +The following parameters are available. And some additional parameters are available in the [Utility Methods](#utility_methods). + +#### `hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue` + +A current value of each option. +It is converted to human readable if possible. The boolean value is replaced to `'on'` or `'off'`, and the Array is replaced to the list of only string and number elements. +And in the `keyIn*` method, the parts of the list as characters sequence are suppressed. For example, when `['a', 'b', 'c', 'd', 'e']` is specified to the [`limit`](#basic_options-limit) option, `'$'` is replaced to `'a...e'`. If `true` is specified to the [`caseSensitive`](#basic_options-casesensitive) option, the characters are converted to lower case. + +For example: + +```js +input = readlineSync.question( + 'Input something or the Enter key as "$": ', + {defaultInput: 'hello'} +); +``` + +```console +Input something or the Enter key as "hello": +``` + +#### `limitCount`, `limitCountNotZero` + +A length of a current value of the [`limit`](#basic_options-limit) option. +When the value of the [`limit`](#basic_options-limit) option is empty, `'$'` is replaced to `'0'`, `'$'` is replaced to `''`. + +For example: + +```js +action = readlineSync.question( + 'Choose action$<( from )limitCountNotZero( actions)>: ', + {limit: availableActions} +); +``` + +```console +Choose action from 5 actions: +``` + +#### `lastInput` + +A last input from the user. +In any case, this is saved. + +For example: + +```js +command = readlineSync.prompt({ + limit: availableCommands, + limitMessage: '$ is not available.' +}); +``` + +```console +> wrong-command +wrong-command is not available. +``` + +#### `history_mN` + +When the history expansion feature is enabled (see [`history`](#basic_options-history) option), a current command line minus `N`. +*This feature keeps the previous input only.* That is, only `history_m1` is supported. + +For example: + +```js +while (true) { + input = readlineSync.question('Something$<( or "!!" as ")history_m1(")>: '); + console.log('-- You said "' + input + '"'); +} +``` + +```console +Something: hello +-- You said "hello" +Something or "!!" as "hello": !! +hello +-- You said "hello" +``` + +#### `cwd`, `CWD`, `cwdHome` + +A current working directory. + +* `cwd`: A full-path +* `CWD`: A directory name +* `cwdHome`: A path that includes `~` as the home directory + +For example, like bash/zsh: + +```js +command = readlineSync.prompt({prompt: '[$]$ '}); +``` + +```console +[~/foo/bar]$ +``` + +#### `date`, `time`, `localeDate`, `localeTime` + +A string as current date or time. + +* `date`: A date portion +* `time`: A time portion +* `localeDate`: A locality sensitive representation of the date portion based on system settings +* `localeTime`: A locality sensitive representation of the time portion based on system settings + +For example: + +```js +command = readlineSync.prompt({prompt: '[$]> '}); +``` + +```console +[04/21/2015]> +``` + +#### `C1-C2` + +_For [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method only_ + +A character list. +`C1` and `C2` are each single character as the start and the end. A sequence in ascending or descending order of characters ranging from `C1` to `C2` is created. For example, `'$'` is replaced to `'abcde'`. `'$<5-1>'` is replaced to `'54321'`. + +For example, let the user input a password that is created with alphabet: + +```js +password = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$'}); +``` + +See also [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method). + +## Special method `getRawInput` + +```js +rawInput = readlineSync.getRawInput() +``` + +Return a raw input data of last method. +When the input was terminated with no data, a `NULL` is inserted to the data. + +This might contain control-codes (e.g. `LF`, `CR`, `EOF`, etc.), therefore, it might be used to get `^D` that was input. But you should understand each environments for that. Or, **you should not use this** if your script is used in multiple environments. +For example, when the user input `EOF` (`^D` in Unix like system, `^Z` in Windows), `x1A` (`EOF`) is returned in Windows, and `x00` (`NULL`) is returned in Unix like system. And `x04` (`EOT`) is returned in Unix like system with raw-mode. And also, when [external program](#note-reading_by_external_program) is used, nothing is returned. See also [Control characters](#note-control_characters). +You may examine each environment and you must test your script very much, if you want to handle the raw input data. + +## With Task Runner + +The easy way to control a flow of the task runner by the input from the user: + +* [Grunt](http://gruntjs.com/) plugin: [grunt-confirm](https://github.com/anseki/grunt-confirm) +* [gulp](http://gulpjs.com/) plugin: [gulp-confirm](https://github.com/anseki/gulp-confirm) + +If you want to control a flow of the task runner (e.g. [Grunt](http://gruntjs.com/)), call readlineSync in a task callback that is called by the task runner. Then a flow of tasks is paused and it is controlled by the user. + +For example, by using [grunt-task-helper](https://github.com/anseki/grunt-task-helper): + +```console +$ grunt +Running "fileCopy" task +Files already exist: + file-a.png + file-b.js +Overwrite? [y/n]: y +file-a.png copied. +file-b.js copied. +Done. +``` + +`Gruntfile.js` + +```js +grunt.initConfig({ + taskHelper: { + fileCopy: { + options: { + handlerByTask: function() { + // Abort the task if user don't want it. + return readlineSync.keyInYN('Overwrite?'); + }, + filesArray: [] + }, + ... + } + }, + copy: { + fileCopy: { + files: '<%= taskHelper.fileCopy.options.filesArray %>' + } + } +}); +``` + +## Note + +### Platforms + +TTY interfaces are different by the platforms. If the platform doesn't support the interactively reading from TTY, an error is thrown. + +```js +try { + answer = readlineSync.question('What is your favorite food? '); +} catch (e) { + console.error(e); + process.exit(1); +} +``` + +### Control characters + +TTY interfaces are different by the platforms. In some environments, ANSI escape sequences might be ignored. For example, in non-POSIX TTY such as Windows CMD does not support it (that of Windows 8 especially has problems). Since readlineSync does not use Node.js library that emulates POSIX TTY (but that is still incomplete), those characters may be not parsed. Then, using ANSI escape sequences is not recommended if you will support more environments. +Also, control characters user input might be not accepted or parsed. That behavior differs depending on the environment. And current Node.js does not support controlling a readline system library. + +### Reading by external program + +readlineSync tries to read from a console by using the external program if it is needed (e.g. when the input stream is redirected on Windows XP). And if the running Node.js doesn't support the [Synchronous Process Execution](http://nodejs.org/api/child_process.html#child_process_synchronous_process_creation) (i.e. Node.js v0.10-), readlineSync uses "piping via files" for the synchronous execution. +As everyone knows, "piping via files" is no good. It blocks the event loop and a process. It might make the your script be slow. + +Why did I choose it? : + +* Good modules (native addon) for the synchronous execution exist, but node-gyp can't compile those in some platforms or Node.js versions. +* I think that the security is important more than the speed. Some modules have problem about security. Those don't protect the data. I think that the speed is not needed usually, because readlineSync is used while user types keys. + +## Deprecated methods and options + +See [README-Deprecated.md](README-Deprecated.md). diff --git a/z1-prototype/node_modules/readline-sync/lib/encrypt.js b/z1-prototype/node_modules/readline-sync/lib/encrypt.js new file mode 100644 index 0000000..d732ce6 --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/lib/encrypt.js @@ -0,0 +1,24 @@ +/* + * readlineSync + * https://github.com/anseki/readline-sync + * + * Copyright (c) 2019 anseki + * Licensed under the MIT license. + */ + +var cipher = require('crypto').createCipher( + process.argv[2] /*algorithm*/, process.argv[3] /*password*/), + stdin = process.stdin, + stdout = process.stdout, + crypted = ''; + +stdin.resume(); +stdin.setEncoding('utf8'); +stdin.on('data', function(d) { + crypted += cipher.update(d, 'utf8', 'hex'); +}); +stdin.on('end', function() { + stdout.write(crypted + cipher.final('hex'), 'binary', function() { + process.exit(0); + }); +}); diff --git a/z1-prototype/node_modules/readline-sync/lib/read.cs.js b/z1-prototype/node_modules/readline-sync/lib/read.cs.js new file mode 100644 index 0000000..cc31801 --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/lib/read.cs.js @@ -0,0 +1,123 @@ +/* jshint wsh:true */ + +/* + * readlineSync + * https://github.com/anseki/readline-sync + * + * Copyright (c) 2019 anseki + * Licensed under the MIT license. + */ + +var + FSO_ForReading = 1, FSO_ForWriting = 2, + PS_MSG = 'Microsoft Windows PowerShell is required.' + + ' https://technet.microsoft.com/en-us/library/hh847837.aspx', + + input = '', fso, tty, + options = (function(conf) { + var options = {}, arg, args =// Array.prototype.slice.call(WScript.Arguments), + (function() { + var args = [], i, iLen; + for (i = 0, iLen = WScript.Arguments.length; i < iLen; i++) + { args.push(WScript.Arguments(i)); } + return args; + })(), + confLc = {}, key; + + function decodeArg(arg) { + return arg.replace(/#(\d+);/g, function(str, charCode) { + return String.fromCharCode(+charCode); + }); + } + + for (key in conf) { + if (conf.hasOwnProperty(key)) + { confLc[key.toLowerCase()] = {key: key, type: conf[key]}; } + } + + while (typeof(arg = args.shift()) === 'string') { + if (!(arg = (arg.match(/^\-+(.+)$/) || [])[1])) { continue; } + arg = arg.toLowerCase(); + if (confLc[arg]) { + options[confLc[arg].key] = + confLc[arg].type === 'boolean' ? true : + confLc[arg].type === 'string' ? args.shift() : null; + } + } + for (key in conf) { + if (conf.hasOwnProperty(key) && conf[key] === 'string') { + if (typeof options[key] !== 'string') { options[key] = ''; } + else { options[key] = decodeArg(options[key]); } + } + } + return options; + })({ + display: 'string', + displayOnly: 'boolean', + keyIn: 'boolean', + hideEchoBack: 'boolean', + mask: 'string' + }); + +if (!options.hideEchoBack && !options.keyIn) { + if (options.display) { writeTTY(options.display); } + if (!options.displayOnly) { input = readByFSO(); } +} else if (options.hideEchoBack && !options.keyIn && !options.mask) { + if (options.display) { writeTTY(options.display); } + if (!options.displayOnly) { input = readByPW(); } +} else { + WScript.StdErr.WriteLine(PS_MSG); + WScript.Quit(1); +} + +WScript.StdOut.Write('\'' + input + '\''); + +WScript.Quit(); + +function writeTTY(text) { + try { + tty = tty || getFso().OpenTextFile('CONOUT$', FSO_ForWriting, true); + tty.Write(text); + } catch (e) { + WScript.StdErr.WriteLine('TTY Write Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } +} + +function readByFSO() { + var text; + try { + text = getFso().OpenTextFile('CONIN$', FSO_ForReading).ReadLine(); + } catch (e) { + WScript.StdErr.WriteLine('TTY Read Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } + return text; +} + +// TTY must be STDIN that is not redirected and not piped. +function readByPW() { + var text; + try { + text = WScript.CreateObject('ScriptPW.Password').GetPassword() + // Bug? Illegal data may be returned when user types before initializing. + .replace(/[\u4000-\u40FF]/g, function(chr) { + var charCode = chr.charCodeAt(0); + return charCode >= 0x4020 && charCode <= 0x407F ? + String.fromCharCode(charCode - 0x4000) : ''; + }); + } catch (e) { + WScript.StdErr.WriteLine('ScriptPW.Password Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } + writeTTY('\n'); + return text; +} + +function getFso() { + if (!fso) { fso = new ActiveXObject('Scripting.FileSystemObject'); } + return fso; +} diff --git a/z1-prototype/node_modules/readline-sync/lib/read.ps1 b/z1-prototype/node_modules/readline-sync/lib/read.ps1 new file mode 100644 index 0000000..ea6f805 --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/lib/read.ps1 @@ -0,0 +1,128 @@ +# readlineSync +# https://github.com/anseki/readline-sync +# +# Copyright (c) 2019 anseki +# Licensed under the MIT license. + +Param( + [string] $display, + [switch] $displayOnly, + [switch] $keyIn, + [switch] $hideEchoBack, + [string] $mask, + [string] $limit, + [switch] $caseSensitive +) + +$ErrorActionPreference = 'Stop' # for cmdlet +trap { + # `throw $_` and `Write-Error $_` return exit-code 0 + $Host.UI.WriteErrorLine($_) + exit 1 +} + +function decodeArg ($arg) { + [Regex]::Replace($arg, '#(\d+);', { [char][int] $args[0].Groups[1].Value }) +} + +$options = @{} +foreach ($arg in @('display', 'displayOnly', 'keyIn', 'hideEchoBack', 'mask', 'limit', 'caseSensitive')) { + $options.Add($arg, (Get-Variable $arg -ValueOnly)) +} +$argList = New-Object string[] $options.Keys.Count +$options.Keys.CopyTo($argList, 0) +foreach ($arg in $argList) { + if ($options[$arg] -is [string] -and $options[$arg]) + { $options[$arg] = decodeArg $options[$arg] } +} + +[string] $inputTTY = '' +[bool] $silent = -not $options.display -and + $options.keyIn -and $options.hideEchoBack -and -not $options.mask +[bool] $isCooked = -not $options.hideEchoBack -and -not $options.keyIn + +# Instant method that opens TTY without CreateFile via P/Invoke in .NET Framework +# **NOTE** Don't include special characters of DOS in $command when $getRes is True. +# [string] $cmdPath = $Env:ComSpec +# [string] $psPath = 'powershell.exe' +function execWithTTY ($command, $getRes = $False, $throwError = $False) { + if ($getRes) { + $res = (cmd.exe /C "CON powershell.exe -Command -" + if ($LastExitCode -ne 0) { + if ($throwError) { throw $LastExitCode } + else { exit $LastExitCode } + } + } +} + +function writeTTY ($text) { + execWithTTY ('Write-Host (''' + + (($text -replace '''', '''''') -replace '[\r\n]', '''+"`n"+''') + ''') -NoNewline') +} + +if ($options.display) { + writeTTY $options.display +} +if ($options.displayOnly) { return "''" } + +if (-not $options.keyIn -and $options.hideEchoBack -and $options.mask -eq '*') { + # It fails when it's not ready. + try { + $inputTTY = execWithTTY ('$text = Read-Host -AsSecureString;' + + '$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($text);' + + '[Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)') $True $True + return '''' + $inputTTY + '''' + } catch {} # ignore +} + +if ($options.keyIn) { $reqSize = 1 } + +if ($options.keyIn -and $options.limit) { + $limitPtn = '[^' + $options.limit + ']' +} + +while ($True) { + if (-not $isCooked) { + $chunk = [char][int] (execWithTTY '[int] [Console]::ReadKey($True).KeyChar' $True) + } else { + $chunk = execWithTTY 'Read-Host' $True + $chunk += "`n" + } + + if ($chunk -and $chunk -match '^(.*?)[\r\n]') { + $chunk = $Matches[1] + $atEol = $True + } else { $atEol = $False } + + # other ctrl-chars + if ($chunk) { $chunk = $chunk -replace '[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '' } + if ($chunk -and $limitPtn) { + if ($options.caseSensitive) { $chunk = $chunk -creplace $limitPtn, '' } + else { $chunk = $chunk -ireplace $limitPtn, '' } + } + + if ($chunk) { + if (-not $isCooked) { + if (-not $options.hideEchoBack) { + writeTTY $chunk + } elseif ($options.mask) { + writeTTY ($options.mask * $chunk.Length) + } + } + $inputTTY += $chunk + } + + if ((-not $options.keyIn -and $atEol) -or + ($options.keyIn -and $inputTTY.Length -ge $reqSize)) { break } +} + +if (-not $isCooked -and -not $silent) { execWithTTY 'Write-Host ''''' } # new line + +return "'$inputTTY'" diff --git a/z1-prototype/node_modules/readline-sync/lib/read.sh b/z1-prototype/node_modules/readline-sync/lib/read.sh new file mode 100644 index 0000000..b41e80c --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/lib/read.sh @@ -0,0 +1,137 @@ +# readlineSync +# https://github.com/anseki/readline-sync +# +# Copyright (c) 2019 anseki +# Licensed under the MIT license. + +# Use perl for compatibility of sed/awk of GNU / POSIX, BSD. (and tr) +# Hide "\n" from shell by "\fNL" + +decode_arg() { + printf '%s' "$(printf '%s' "$1" | perl -pe 's/#(\d+);/sprintf("%c", $1)/ge; s/[\r\n]/\fNL/g')" +} + +# getopt(s) +while [ $# -ge 1 ]; do + arg="$(printf '%s' "$1" | grep -E '^-+[^-]+$' | tr '[A-Z]' '[a-z]' | tr -d '-')" + case "$arg" in + 'display') shift; options_display="$(decode_arg "$1")";; + 'displayonly') options_displayOnly=true;; + 'keyin') options_keyIn=true;; + 'hideechoback') options_hideEchoBack=true;; + 'mask') shift; options_mask="$(decode_arg "$1")";; + 'limit') shift; options_limit="$(decode_arg "$1")";; + 'casesensitive') options_caseSensitive=true;; + esac + shift +done + +reset_tty() { + if [ -n "$save_tty" ]; then + stty --file=/dev/tty "$save_tty" 2>/dev/null || \ + stty -F /dev/tty "$save_tty" 2>/dev/null || \ + stty -f /dev/tty "$save_tty" || exit $? + fi +} +trap 'reset_tty' EXIT +save_tty="$(stty --file=/dev/tty -g 2>/dev/null || stty -F /dev/tty -g 2>/dev/null || stty -f /dev/tty -g || exit $?)" + +[ -z "$options_display" ] && [ "$options_keyIn" = true ] && \ + [ "$options_hideEchoBack" = true ] && [ -z "$options_mask" ] && silent=true +[ "$options_hideEchoBack" != true ] && [ "$options_keyIn" != true ] && is_cooked=true + +write_tty() { + # if [ "$2" = true ]; then + # printf '%b' "$1" >/dev/tty + # else + # printf '%s' "$1" >/dev/tty + # fi + printf '%s' "$1" | perl -pe 's/\fNL/\r\n/g' >/dev/tty +} + +replace_allchars() { ( + text='' + for i in $(seq 1 ${#1}) + do + text="$text$2" + done + printf '%s' "$text" +) } + +if [ -n "$options_display" ]; then + write_tty "$options_display" +fi +if [ "$options_displayOnly" = true ]; then + printf "'%s'" '' + exit 0 +fi + +if [ "$is_cooked" = true ]; then + stty --file=/dev/tty cooked 2>/dev/null || \ + stty -F /dev/tty cooked 2>/dev/null || \ + stty -f /dev/tty cooked || exit $? +else + stty --file=/dev/tty raw -echo 2>/dev/null || \ + stty -F /dev/tty raw -echo 2>/dev/null || \ + stty -f /dev/tty raw -echo || exit $? +fi + +[ "$options_keyIn" = true ] && req_size=1 + +if [ "$options_keyIn" = true ] && [ -n "$options_limit" ]; then + if [ "$options_caseSensitive" = true ]; then + limit_ptn="$options_limit" + else + # Safe list + # limit_ptn="$(printf '%s' "$options_limit" | sed 's/\([a-z]\)/\L\1\U\1/ig')" + limit_ptn="$(printf '%s' "$options_limit" | perl -pe 's/([a-z])/lc($1) . uc($1)/ige')" + fi +fi + +while : +do + if [ "$is_cooked" != true ]; then + # chunk="$(dd if=/dev/tty bs=1 count=1 2>/dev/null)" + chunk="$(dd if=/dev/tty bs=1 count=1 2>/dev/null | perl -pe 's/[\r\n]/\fNL/g')" + else + IFS= read -r chunk ', + hideEchoBack: false, + mask: '*', + limit: [], + limitMessage: 'Input another, please.$<( [)limit(])>', + defaultInput: '', + trueValue: [], + falseValue: [], + caseSensitive: false, + keepWhitespace: false, + encoding: 'utf8', + bufferSize: 1024, + print: void 0, + history: true, + cd: false, + phContent: void 0, + preCheck: void 0 + /* eslint-enable key-spacing */ + }, + + fdR = 'none', + isRawMode = false, + salt = 0, + lastInput = '', + inputHistory = [], + _DBG_useExt = false, + _DBG_checkOptions = false, + _DBG_checkMethod = false, + fdW, ttyR, extHostPath, extHostArgs, tempdir, rawInput; + +function getHostArgs(options) { + // Send any text to crazy Windows shell safely. + function encodeArg(arg) { + return arg.replace(/[^\w\u0080-\uFFFF]/g, function(chr) { + return '#' + chr.charCodeAt(0) + ';'; + }); + } + + return extHostArgs.concat((function(conf) { + var args = []; + Object.keys(conf).forEach(function(optionName) { + if (conf[optionName] === 'boolean') { + if (options[optionName]) { args.push('--' + optionName); } + } else if (conf[optionName] === 'string') { + if (options[optionName]) { + args.push('--' + optionName, encodeArg(options[optionName])); + } + } + }); + return args; + })({ + /* eslint-disable key-spacing */ + display: 'string', + displayOnly: 'boolean', + keyIn: 'boolean', + hideEchoBack: 'boolean', + mask: 'string', + limit: 'string', + caseSensitive: 'boolean' + /* eslint-enable key-spacing */ + })); +} + +// piping via files (for Node.js v0.10-) +function _execFileSync(options, execOptions) { + + function getTempfile(name) { + var suffix = '', + filepath, fd; + tempdir = tempdir || require('os').tmpdir(); + + while (true) { + filepath = pathUtil.join(tempdir, name + suffix); + try { + fd = fs.openSync(filepath, 'wx'); + } catch (e) { + if (e.code === 'EEXIST') { + suffix++; + continue; + } else { + throw e; + } + } + fs.closeSync(fd); + break; + } + return filepath; + } + + var res = {}, + pathStdout = getTempfile('readline-sync.stdout'), + pathStderr = getTempfile('readline-sync.stderr'), + pathExit = getTempfile('readline-sync.exit'), + pathDone = getTempfile('readline-sync.done'), + crypto = require('crypto'), + hostArgs, shellPath, shellArgs, exitCode, extMessage, shasum, decipher, password; + + shasum = crypto.createHash(ALGORITHM_HASH); + shasum.update('' + process.pid + (salt++) + Math.random()); + password = shasum.digest('hex'); + decipher = crypto.createDecipher(ALGORITHM_CIPHER, password); + + hostArgs = getHostArgs(options); + if (IS_WIN) { + shellPath = process.env.ComSpec || 'cmd.exe'; + process.env.Q = '"'; // The quote (") that isn't escaped. + // `()` for ignore space by echo + shellArgs = ['/V:ON', '/S', '/C', + '(%Q%' + shellPath + '%Q% /V:ON /S /C %Q%' + /* ESLint bug? */ // eslint-disable-line no-path-concat + '%Q%' + extHostPath + '%Q%' + + hostArgs.map(function(arg) { return ' %Q%' + arg + '%Q%'; }).join('') + + ' & (echo !ERRORLEVEL!)>%Q%' + pathExit + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' + + ' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' + + ' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' + + ' >%Q%' + pathStdout + '%Q%' + + ' & (echo 1)>%Q%' + pathDone + '%Q%']; + } else { + shellPath = '/bin/sh'; + shellArgs = ['-c', + // Use `()`, not `{}` for `-c` (text param) + '("' + extHostPath + '"' + /* ESLint bug? */ // eslint-disable-line no-path-concat + hostArgs.map(function(arg) { return " '" + arg.replace(/'/g, "'\\''") + "'"; }).join('') + + '; echo $?>"' + pathExit + '") 2>"' + pathStderr + '"' + + ' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' + + ' "' + ALGORITHM_CIPHER + '" "' + password + '"' + + ' >"' + pathStdout + '"' + + '; echo 1 >"' + pathDone + '"']; + } + if (_DBG_checkMethod) { _DBG_checkMethod('_execFileSync', hostArgs); } + try { + childProc.spawn(shellPath, shellArgs, execOptions); + } catch (e) { + res.error = new Error(e.message); + res.error.method = '_execFileSync - spawn'; + res.error.program = shellPath; + res.error.args = shellArgs; + } + + while (fs.readFileSync(pathDone, {encoding: options.encoding}).trim() !== '1') {} // eslint-disable-line no-empty + if ((exitCode = + fs.readFileSync(pathExit, {encoding: options.encoding}).trim()) === '0') { + res.input = + decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}), + 'hex', options.encoding) + + decipher.final(options.encoding); + } else { + extMessage = fs.readFileSync(pathStderr, {encoding: options.encoding}).trim(); + res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : '')); + res.error.method = '_execFileSync'; + res.error.program = shellPath; + res.error.args = shellArgs; + res.error.extMessage = extMessage; + res.error.exitCode = +exitCode; + } + + fs.unlinkSync(pathStdout); + fs.unlinkSync(pathStderr); + fs.unlinkSync(pathExit); + fs.unlinkSync(pathDone); + + return res; +} + +function readlineExt(options) { + var res = {}, + execOptions = {env: process.env, encoding: options.encoding}, + hostArgs, extMessage; + + if (!extHostPath) { + if (IS_WIN) { + if (process.env.PSModulePath) { // Windows PowerShell + extHostPath = 'powershell.exe'; + extHostArgs = ['-ExecutionPolicy', 'Bypass', + '-File', __dirname + '\\read.ps1']; // eslint-disable-line no-path-concat + } else { // Windows Script Host + extHostPath = 'cscript.exe'; + extHostArgs = ['//nologo', __dirname + '\\read.cs.js']; // eslint-disable-line no-path-concat + } + } else { + extHostPath = '/bin/sh'; + extHostArgs = [__dirname + '/read.sh']; // eslint-disable-line no-path-concat + } + } + if (IS_WIN && !process.env.PSModulePath) { // Windows Script Host + // ScriptPW (Win XP and Server2003) needs TTY stream as STDIN. + // In this case, If STDIN isn't TTY, an error is thrown. + execOptions.stdio = [process.stdin]; + } + + if (childProc.execFileSync) { + hostArgs = getHostArgs(options); + if (_DBG_checkMethod) { _DBG_checkMethod('execFileSync', hostArgs); } + try { + res.input = childProc.execFileSync(extHostPath, hostArgs, execOptions); + } catch (e) { // non-zero exit code + extMessage = e.stderr ? (e.stderr + '').trim() : ''; + res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : '')); + res.error.method = 'execFileSync'; + res.error.program = extHostPath; + res.error.args = hostArgs; + res.error.extMessage = extMessage; + res.error.exitCode = e.status; + res.error.code = e.code; + res.error.signal = e.signal; + } + } else { + res = _execFileSync(options, execOptions); + } + if (!res.error) { + res.input = res.input.replace(/^\s*'|'\s*$/g, ''); + options.display = ''; + } + + return res; +} + +/* + display: string + displayOnly: boolean + keyIn: boolean + hideEchoBack: boolean + mask: string + limit: string (pattern) + caseSensitive: boolean + keepWhitespace: boolean + encoding, bufferSize, print +*/ +function _readlineSync(options) { + var input = '', + displaySave = options.display, + silent = !options.display && options.keyIn && options.hideEchoBack && !options.mask; + + function tryExt() { + var res = readlineExt(options); + if (res.error) { throw res.error; } + return res.input; + } + + if (_DBG_checkOptions) { _DBG_checkOptions(options); } + + (function() { // open TTY + var fsB, constants, verNum; + + function getFsB() { + if (!fsB) { + fsB = process.binding('fs'); // For raw device path + constants = process.binding('constants'); + // for v6.3.0+ + constants = constants && constants.fs && typeof constants.fs.O_RDWR === 'number' + ? constants.fs : constants; + } + return fsB; + } + + if (typeof fdR !== 'string') { return; } + fdR = null; + + if (IS_WIN) { + // iojs-v2.3.2+ input stream can't read first line. (#18) + // ** Don't get process.stdin before check! ** + // Fixed v5.1.0 + // Fixed v4.2.4 + // It regressed again in v5.6.0, it is fixed in v6.2.0. + verNum = (function(ver) { // getVerNum + var nums = ver.replace(/^\D+/, '').split('.'); + var verNum = 0; + if ((nums[0] = +nums[0])) { verNum += nums[0] * 10000; } + if ((nums[1] = +nums[1])) { verNum += nums[1] * 100; } + if ((nums[2] = +nums[2])) { verNum += nums[2]; } + return verNum; + })(process.version); + if (!(verNum >= 20302 && verNum < 40204 || verNum >= 50000 && verNum < 50100 || verNum >= 50600 && verNum < 60200) && + process.stdin.isTTY) { + process.stdin.pause(); + fdR = process.stdin.fd; + ttyR = process.stdin._handle; + } else { + try { + // The stream by fs.openSync('\\\\.\\CON', 'r') can't switch to raw mode. + // 'CONIN$' might fail on XP, 2000, 7 (x86). + fdR = getFsB().open('CONIN$', constants.O_RDWR, parseInt('0666', 8)); + ttyR = new TTY(fdR, true); + } catch (e) { /* ignore */ } + } + + if (process.stdout.isTTY) { + fdW = process.stdout.fd; + } else { + try { + fdW = fs.openSync('\\\\.\\CON', 'w'); + } catch (e) { /* ignore */ } + if (typeof fdW !== 'number') { // Retry + try { + fdW = getFsB().open('CONOUT$', constants.O_RDWR, parseInt('0666', 8)); + } catch (e) { /* ignore */ } + } + } + + } else { + if (process.stdin.isTTY) { + process.stdin.pause(); + try { + fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin + ttyR = process.stdin._handle; + } catch (e) { /* ignore */ } + } else { + // Node.js v0.12 read() fails. + try { + fdR = fs.openSync('/dev/tty', 'r'); + ttyR = new TTY(fdR, false); + } catch (e) { /* ignore */ } + } + + if (process.stdout.isTTY) { + fdW = process.stdout.fd; + } else { + try { + fdW = fs.openSync('/dev/tty', 'w'); + } catch (e) { /* ignore */ } + } + } + })(); + + (function() { // try read + var isCooked = !options.hideEchoBack && !options.keyIn, + atEol, limit, buffer, reqSize, readSize, chunk, line; + rawInput = ''; + + // Node.js v0.10- returns an error if same mode is set. + function setRawMode(mode) { + if (mode === isRawMode) { return true; } + if (ttyR.setRawMode(mode) !== 0) { return false; } + isRawMode = mode; + return true; + } + + if (_DBG_useExt || !ttyR || + typeof fdW !== 'number' && (options.display || !isCooked)) { + input = tryExt(); + return; + } + + if (options.display) { + fs.writeSync(fdW, options.display); + options.display = ''; + } + if (options.displayOnly) { return; } + + if (!setRawMode(!isCooked)) { + input = tryExt(); + return; + } + + reqSize = options.keyIn ? 1 : options.bufferSize; + // Check `allocUnsafe` to make sure of the new API. + buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(reqSize) : new Buffer(reqSize); + + if (options.keyIn && options.limit) { + limit = new RegExp('[^' + options.limit + ']', + 'g' + (options.caseSensitive ? '' : 'i')); + } + + while (true) { + readSize = 0; + try { + readSize = fs.readSync(fdR, buffer, 0, reqSize); + } catch (e) { + if (e.code !== 'EOF') { + setRawMode(false); + input += tryExt(); + return; + } + } + if (readSize > 0) { + chunk = buffer.toString(options.encoding, 0, readSize); + rawInput += chunk; + } else { + chunk = '\n'; + rawInput += String.fromCharCode(0); + } + + if (chunk && typeof (line = (chunk.match(/^(.*?)[\r\n]/) || [])[1]) === 'string') { + chunk = line; + atEol = true; + } + + // other ctrl-chars + // eslint-disable-next-line no-control-regex + if (chunk) { chunk = chunk.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ''); } + if (chunk && limit) { chunk = chunk.replace(limit, ''); } + + if (chunk) { + if (!isCooked) { + if (!options.hideEchoBack) { + fs.writeSync(fdW, chunk); + } else if (options.mask) { + fs.writeSync(fdW, (new Array(chunk.length + 1)).join(options.mask)); + } + } + input += chunk; + } + + if (!options.keyIn && atEol || + options.keyIn && input.length >= reqSize) { break; } + } + + if (!isCooked && !silent) { fs.writeSync(fdW, '\n'); } + setRawMode(false); + })(); + + if (options.print && !silent) { + options.print( + displaySave + ( + options.displayOnly ? '' : ( + options.hideEchoBack ? (new Array(input.length + 1)).join(options.mask) : input + ) + '\n' // must at least write '\n' + ), + options.encoding); + } + + return options.displayOnly ? '' : + (lastInput = options.keepWhitespace || options.keyIn ? input : input.trim()); +} + +function flattenArray(array, validator) { + var flatArray = []; + function _flattenArray(array) { + if (array == null) { return; } + if (Array.isArray(array)) { + array.forEach(_flattenArray); + } else if (!validator || validator(array)) { + flatArray.push(array); + } + } + _flattenArray(array); + return flatArray; +} + +function escapePattern(pattern) { + return pattern.replace(/[\x00-\x7f]/g, // eslint-disable-line no-control-regex + function(s) { return '\\x' + ('00' + s.charCodeAt().toString(16)).substr(-2); }); +} + +// margeOptions(options1, options2 ... ) +// margeOptions(true, options1, options2 ... ) +// arg1=true : Start from defaultOptions and pick elements of that. +function margeOptions() { + var optionsList = Array.prototype.slice.call(arguments), + optionNames, fromDefault; + + if (optionsList.length && typeof optionsList[0] === 'boolean') { + fromDefault = optionsList.shift(); + if (fromDefault) { + optionNames = Object.keys(defaultOptions); + optionsList.unshift(defaultOptions); + } + } + + return optionsList.reduce(function(options, optionsPart) { + if (optionsPart == null) { return options; } + + // ======== DEPRECATED ======== + if (optionsPart.hasOwnProperty('noEchoBack') && + !optionsPart.hasOwnProperty('hideEchoBack')) { + optionsPart.hideEchoBack = optionsPart.noEchoBack; + delete optionsPart.noEchoBack; + } + if (optionsPart.hasOwnProperty('noTrim') && + !optionsPart.hasOwnProperty('keepWhitespace')) { + optionsPart.keepWhitespace = optionsPart.noTrim; + delete optionsPart.noTrim; + } + // ======== /DEPRECATED ======== + + if (!fromDefault) { optionNames = Object.keys(optionsPart); } + optionNames.forEach(function(optionName) { + var value; + if (!optionsPart.hasOwnProperty(optionName)) { return; } + value = optionsPart[optionName]; + /* eslint-disable no-multi-spaces */ + switch (optionName) { + // _readlineSync <- * * -> defaultOptions + // ================ string + case 'mask': // * * + case 'limitMessage': // * + case 'defaultInput': // * + case 'encoding': // * * + value = value != null ? value + '' : ''; + if (value && optionName !== 'limitMessage') { value = value.replace(/[\r\n]/g, ''); } + options[optionName] = value; + break; + // ================ number(int) + case 'bufferSize': // * * + if (!isNaN(value = parseInt(value, 10)) && typeof value === 'number') { + options[optionName] = value; // limited updating (number is needed) + } + break; + // ================ boolean + case 'displayOnly': // * + case 'keyIn': // * + case 'hideEchoBack': // * * + case 'caseSensitive': // * * + case 'keepWhitespace': // * * + case 'history': // * + case 'cd': // * + options[optionName] = !!value; + break; + // ================ array + case 'limit': // * * to string for readlineExt + case 'trueValue': // * + case 'falseValue': // * + options[optionName] = flattenArray(value, function(value) { + var type = typeof value; + return type === 'string' || type === 'number' || + type === 'function' || value instanceof RegExp; + }).map(function(value) { + return typeof value === 'string' ? value.replace(/[\r\n]/g, '') : value; + }); + break; + // ================ function + case 'print': // * * + case 'phContent': // * + case 'preCheck': // * + options[optionName] = typeof value === 'function' ? value : void 0; + break; + // ================ other + case 'prompt': // * + case 'display': // * + options[optionName] = value != null ? value : ''; + break; + // no default + } + /* eslint-enable no-multi-spaces */ + }); + return options; + }, {}); +} + +function isMatched(res, comps, caseSensitive) { + return comps.some(function(comp) { + var type = typeof comp; + return type === 'string' + ? (caseSensitive ? res === comp : res.toLowerCase() === comp.toLowerCase()) : + type === 'number' ? parseFloat(res) === comp : + type === 'function' ? comp(res) : + comp instanceof RegExp ? comp.test(res) : false; + }); +} + +function replaceHomePath(path, expand) { + var homePath = pathUtil.normalize( + IS_WIN ? (process.env.HOMEDRIVE || '') + (process.env.HOMEPATH || '') : + process.env.HOME || '').replace(/[/\\]+$/, ''); + path = pathUtil.normalize(path); + return expand ? path.replace(/^~(?=\/|\\|$)/, homePath) : + path.replace(new RegExp('^' + escapePattern(homePath) + + '(?=\\/|\\\\|$)', IS_WIN ? 'i' : ''), '~'); +} + +function replacePlaceholder(text, generator) { + var PTN_INNER = '(?:\\(([\\s\\S]*?)\\))?(\\w+|.-.)(?:\\(([\\s\\S]*?)\\))?', + rePlaceholder = new RegExp('(\\$)?(\\$<' + PTN_INNER + '>)', 'g'), + rePlaceholderCompat = new RegExp('(\\$)?(\\$\\{' + PTN_INNER + '\\})', 'g'); + + function getPlaceholderText(s, escape, placeholder, pre, param, post) { + var text; + return escape || typeof (text = generator(param)) !== 'string' ? placeholder : + text ? (pre || '') + text + (post || '') : ''; + } + + return text.replace(rePlaceholder, getPlaceholderText) + .replace(rePlaceholderCompat, getPlaceholderText); +} + +function array2charlist(array, caseSensitive, collectSymbols) { + var group = [], + groupClass = -1, + charCode = 0, + symbols = '', + values, suppressed; + function addGroup(groups, group) { + if (group.length > 3) { // ellipsis + groups.push(group[0] + '...' + group[group.length - 1]); + suppressed = true; + } else if (group.length) { + groups = groups.concat(group); + } + return groups; + } + + values = array.reduce(function(chars, value) { + return chars.concat((value + '').split('')); + }, []).reduce(function(groups, curChar) { + var curGroupClass, curCharCode; + if (!caseSensitive) { curChar = curChar.toLowerCase(); } + curGroupClass = /^\d$/.test(curChar) ? 1 : + /^[A-Z]$/.test(curChar) ? 2 : /^[a-z]$/.test(curChar) ? 3 : 0; + if (collectSymbols && curGroupClass === 0) { + symbols += curChar; + } else { + curCharCode = curChar.charCodeAt(0); + if (curGroupClass && curGroupClass === groupClass && + curCharCode === charCode + 1) { + group.push(curChar); + } else { + groups = addGroup(groups, group); + group = [curChar]; + groupClass = curGroupClass; + } + charCode = curCharCode; + } + return groups; + }, []); + values = addGroup(values, group); // last group + if (symbols) { values.push(symbols); suppressed = true; } + return {values: values, suppressed: suppressed}; +} + +function joinChunks(chunks, suppressed) { + return chunks.join(chunks.length > 2 ? ', ' : suppressed ? ' / ' : '/'); +} + +function getPhContent(param, options) { + var resCharlist = {}, + text, values, arg; + if (options.phContent) { + text = options.phContent(param, options); + } + if (typeof text !== 'string') { + switch (param) { + case 'hideEchoBack': + case 'mask': + case 'defaultInput': + case 'caseSensitive': + case 'keepWhitespace': + case 'encoding': + case 'bufferSize': + case 'history': + case 'cd': + text = !options.hasOwnProperty(param) ? '' : + typeof options[param] === 'boolean' ? (options[param] ? 'on' : 'off') : + options[param] + ''; + break; + // case 'prompt': + // case 'query': + // case 'display': + // text = options.hasOwnProperty('displaySrc') ? options.displaySrc + '' : ''; + // break; + case 'limit': + case 'trueValue': + case 'falseValue': + values = options[options.hasOwnProperty(param + 'Src') ? param + 'Src' : param]; + if (options.keyIn) { // suppress + resCharlist = array2charlist(values, options.caseSensitive); + values = resCharlist.values; + } else { + values = values.filter(function(value) { + var type = typeof value; + return type === 'string' || type === 'number'; + }); + } + text = joinChunks(values, resCharlist.suppressed); + break; + case 'limitCount': + case 'limitCountNotZero': + text = options[options.hasOwnProperty('limitSrc') ? 'limitSrc' : 'limit'].length; + text = text || param !== 'limitCountNotZero' ? text + '' : ''; + break; + case 'lastInput': + text = lastInput; + break; + case 'cwd': + case 'CWD': + case 'cwdHome': + text = process.cwd(); + if (param === 'CWD') { + text = pathUtil.basename(text); + } else if (param === 'cwdHome') { + text = replaceHomePath(text); + } + break; + case 'date': + case 'time': + case 'localeDate': + case 'localeTime': + text = (new Date())['to' + + param.replace(/^./, function(str) { return str.toUpperCase(); }) + + 'String'](); + break; + default: // with arg + if (typeof (arg = (param.match(/^history_m(\d+)$/) || [])[1]) === 'string') { + text = inputHistory[inputHistory.length - arg] || ''; + } + } + } + return text; +} + +function getPhCharlist(param) { + var matches = /^(.)-(.)$/.exec(param), + text = '', + from, to, code, step; + if (!matches) { return null; } + from = matches[1].charCodeAt(0); + to = matches[2].charCodeAt(0); + step = from < to ? 1 : -1; + for (code = from; code !== to + step; code += step) { text += String.fromCharCode(code); } + return text; +} + +// cmd "arg" " a r g " "" 'a"r"g' "a""rg" "arg +function parseCl(cl) { + var reToken = new RegExp(/(\s*)(?:("|')(.*?)(?:\2|$)|(\S+))/g), + taken = '', + args = [], + matches, part; + cl = cl.trim(); + while ((matches = reToken.exec(cl))) { + part = matches[3] || matches[4] || ''; + if (matches[1]) { + args.push(taken); + taken = ''; + } + taken += part; + } + if (taken) { args.push(taken); } + return args; +} + +function toBool(res, options) { + return ( + (options.trueValue.length && + isMatched(res, options.trueValue, options.caseSensitive)) ? true : + (options.falseValue.length && + isMatched(res, options.falseValue, options.caseSensitive)) ? false : res); +} + +function getValidLine(options) { + var res, forceNext, limitMessage, + matches, histInput, args, resCheck; + + function _getPhContent(param) { return getPhContent(param, options); } + function addDisplay(text) { options.display += (/[^\r\n]$/.test(options.display) ? '\n' : '') + text; } + + options.limitSrc = options.limit; + options.displaySrc = options.display; + options.limit = ''; // for readlineExt + options.display = replacePlaceholder(options.display + '', _getPhContent); + + while (true) { + res = _readlineSync(options); + forceNext = false; + limitMessage = ''; + + if (options.defaultInput && !res) { res = options.defaultInput; } + + if (options.history) { + if ((matches = /^\s*!(?:!|-1)(:p)?\s*$/.exec(res))) { // `!!` `!-1` +`:p` + histInput = inputHistory[0] || ''; + if (matches[1]) { // only display + forceNext = true; + } else { // replace input + res = histInput; + } + // Show it even if it is empty (NL only). + addDisplay(histInput + '\n'); + if (!forceNext) { // Loop may break + options.displayOnly = true; + _readlineSync(options); + options.displayOnly = false; + } + } else if (res && res !== inputHistory[inputHistory.length - 1]) { + inputHistory = [res]; + } + } + + if (!forceNext && options.cd && res) { + args = parseCl(res); + switch (args[0].toLowerCase()) { + case 'cd': + if (args[1]) { + try { + process.chdir(replaceHomePath(args[1], true)); + } catch (e) { + addDisplay(e + ''); + } + } + forceNext = true; + break; + case 'pwd': + addDisplay(process.cwd()); + forceNext = true; + break; + // no default + } + } + + if (!forceNext && options.preCheck) { + resCheck = options.preCheck(res, options); + res = resCheck.res; + if (resCheck.forceNext) { forceNext = true; } // Don't switch to false. + } + + if (!forceNext) { + if (!options.limitSrc.length || + isMatched(res, options.limitSrc, options.caseSensitive)) { break; } + if (options.limitMessage) { + limitMessage = replacePlaceholder(options.limitMessage, _getPhContent); + } + } + + addDisplay((limitMessage ? limitMessage + '\n' : '') + + replacePlaceholder(options.displaySrc + '', _getPhContent)); + } + return toBool(res, options); +} + +// for dev +exports._DBG_set_useExt = function(val) { _DBG_useExt = val; }; +exports._DBG_set_checkOptions = function(val) { _DBG_checkOptions = val; }; +exports._DBG_set_checkMethod = function(val) { _DBG_checkMethod = val; }; +exports._DBG_clearHistory = function() { lastInput = ''; inputHistory = []; }; + +// ------------------------------------ + +exports.setDefaultOptions = function(options) { + defaultOptions = margeOptions(true, options); + return margeOptions(true); // copy +}; + +exports.question = function(query, options) { + /* eslint-disable key-spacing */ + return getValidLine(margeOptions(margeOptions(true, options), { + display: query + })); + /* eslint-enable key-spacing */ +}; + +exports.prompt = function(options) { + var readOptions = margeOptions(true, options); + readOptions.display = readOptions.prompt; + return getValidLine(readOptions); +}; + +exports.keyIn = function(query, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions(margeOptions(true, options), { + display: query, + keyIn: true, + keepWhitespace: true + }); + /* eslint-enable key-spacing */ + + // char list + readOptions.limitSrc = readOptions.limit.filter(function(value) { + var type = typeof value; + return type === 'string' || type === 'number'; + }).map(function(text) { + return replacePlaceholder(text + '', getPhCharlist); + }); + // pattern + readOptions.limit = escapePattern(readOptions.limitSrc.join('')); + + ['trueValue', 'falseValue'].forEach(function(optionName) { + readOptions[optionName] = readOptions[optionName].reduce(function(comps, comp) { + var type = typeof comp; + if (type === 'string' || type === 'number') { + comps = comps.concat((comp + '').split('')); + } else { comps.push(comp); } + return comps; + }, []); + }); + + readOptions.display = replacePlaceholder(readOptions.display + '', + function(param) { return getPhContent(param, readOptions); }); + + return toBool(_readlineSync(readOptions), readOptions); +}; + +// ------------------------------------ + +exports.questionEMail = function(query, options) { + if (query == null) { query = 'Input e-mail address: '; } + /* eslint-disable key-spacing */ + return exports.question(query, margeOptions({ + // -------- default + hideEchoBack: false, + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address + limit: /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, + limitMessage: 'Input valid e-mail address, please.', + trueValue: null, + falseValue: null + }, options, { + // -------- forced + keepWhitespace: false, + cd: false + })); + /* eslint-enable key-spacing */ +}; + +exports.questionNewPassword = function(query, options) { + /* eslint-disable key-spacing */ + var resCharlist, min, max, + readOptions = margeOptions({ + // -------- default + hideEchoBack: true, + mask: '*', + limitMessage: 'It can include: $\n' + + 'And the length must be: $', + trueValue: null, + falseValue: null, + caseSensitive: true + }, options, { + // -------- forced + history: false, + cd: false, + // limit (by charlist etc.), + phContent: function(param) { + return param === 'charlist' ? resCharlist.text : + param === 'length' ? min + '...' + max : null; + } + }), + // added: charlist, min, max, confirmMessage, unmatchMessage + charlist, confirmMessage, unmatchMessage, + limit, limitMessage, res1, res2; + /* eslint-enable key-spacing */ + options = options || {}; + + charlist = replacePlaceholder( + options.charlist ? options.charlist + '' : '$', getPhCharlist); + if (isNaN(min = parseInt(options.min, 10)) || typeof min !== 'number') { min = 12; } + if (isNaN(max = parseInt(options.max, 10)) || typeof max !== 'number') { max = 24; } + limit = new RegExp('^[' + escapePattern(charlist) + + ']{' + min + ',' + max + '}$'); + resCharlist = array2charlist([charlist], readOptions.caseSensitive, true); + resCharlist.text = joinChunks(resCharlist.values, resCharlist.suppressed); + + confirmMessage = options.confirmMessage != null ? options.confirmMessage : + 'Reinput a same one to confirm it: '; + unmatchMessage = options.unmatchMessage != null ? options.unmatchMessage : + 'It differs from first one.' + + ' Hit only the Enter key if you want to retry from first one.'; + + if (query == null) { query = 'Input new password: '; } + + limitMessage = readOptions.limitMessage; + while (!res2) { + readOptions.limit = limit; + readOptions.limitMessage = limitMessage; + res1 = exports.question(query, readOptions); + + readOptions.limit = [res1, '']; + readOptions.limitMessage = unmatchMessage; + res2 = exports.question(confirmMessage, readOptions); + } + + return res1; +}; + +function _questionNum(query, options, parser) { + var validValue; + function getValidValue(value) { + validValue = parser(value); + return !isNaN(validValue) && typeof validValue === 'number'; + } + /* eslint-disable key-spacing */ + exports.question(query, margeOptions({ + // -------- default + limitMessage: 'Input valid number, please.' + }, options, { + // -------- forced + limit: getValidValue, + cd: false + // trueValue, falseValue, caseSensitive, keepWhitespace don't work. + })); + /* eslint-enable key-spacing */ + return validValue; +} +exports.questionInt = function(query, options) { + return _questionNum(query, options, function(value) { return parseInt(value, 10); }); +}; +exports.questionFloat = function(query, options) { + return _questionNum(query, options, parseFloat); +}; + +exports.questionPath = function(query, options) { + /* eslint-disable key-spacing */ + var error = '', + validPath, // before readOptions + readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: '$Input valid path, please.' + + '$<( Min:)min>$<( Max:)max>', + history: true, + cd: true + }, options, { + // -------- forced + keepWhitespace: false, + limit: function(value) { + var exists, stat, res; + value = replaceHomePath(value, true); + error = ''; // for validate + // mkdir -p + function mkdirParents(dirPath) { + dirPath.split(/\/|\\/).reduce(function(parents, dir) { + var path = pathUtil.resolve((parents += dir + pathUtil.sep)); + if (!fs.existsSync(path)) { + fs.mkdirSync(path); + } else if (!fs.statSync(path).isDirectory()) { + throw new Error('Non directory already exists: ' + path); + } + return parents; + }, ''); + } + + try { + exists = fs.existsSync(value); + validPath = exists ? fs.realpathSync(value) : pathUtil.resolve(value); + // options.exists default: true, not-bool: no-check + if (!options.hasOwnProperty('exists') && !exists || + typeof options.exists === 'boolean' && options.exists !== exists) { + error = (exists ? 'Already exists' : 'No such file or directory') + + ': ' + validPath; + return false; + } + if (!exists && options.create) { + if (options.isDirectory) { + mkdirParents(validPath); + } else { + mkdirParents(pathUtil.dirname(validPath)); + fs.closeSync(fs.openSync(validPath, 'w')); // touch + } + validPath = fs.realpathSync(validPath); + } + if (exists && (options.min || options.max || + options.isFile || options.isDirectory)) { + stat = fs.statSync(validPath); + // type check first (directory has zero size) + if (options.isFile && !stat.isFile()) { + error = 'Not file: ' + validPath; + return false; + } else if (options.isDirectory && !stat.isDirectory()) { + error = 'Not directory: ' + validPath; + return false; + } else if (options.min && stat.size < +options.min || + options.max && stat.size > +options.max) { + error = 'Size ' + stat.size + ' is out of range: ' + validPath; + return false; + } + } + if (typeof options.validate === 'function' && + (res = options.validate(validPath)) !== true) { + if (typeof res === 'string') { error = res; } + return false; + } + } catch (e) { + error = e + ''; + return false; + } + return true; + }, + // trueValue, falseValue, caseSensitive don't work. + phContent: function(param) { + return param === 'error' ? error : + param !== 'min' && param !== 'max' ? null : + options.hasOwnProperty(param) ? options[param] + '' : ''; + } + }); + // added: exists, create, min, max, isFile, isDirectory, validate + /* eslint-enable key-spacing */ + options = options || {}; + + if (query == null) { query = 'Input path (you can "cd" and "pwd"): '; } + + exports.question(query, readOptions); + return validPath; +}; + +// props: preCheck, args, hRes, limit +function getClHandler(commandHandler, options) { + var clHandler = {}, + hIndex = {}; + if (typeof commandHandler === 'object') { + Object.keys(commandHandler).forEach(function(cmd) { + if (typeof commandHandler[cmd] === 'function') { + hIndex[options.caseSensitive ? cmd : cmd.toLowerCase()] = commandHandler[cmd]; + } + }); + clHandler.preCheck = function(res) { + var cmdKey; + clHandler.args = parseCl(res); + cmdKey = clHandler.args[0] || ''; + if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); } + clHandler.hRes = + cmdKey !== '_' && hIndex.hasOwnProperty(cmdKey) + ? hIndex[cmdKey].apply(res, clHandler.args.slice(1)) : + hIndex.hasOwnProperty('_') ? hIndex._.apply(res, clHandler.args) : null; + return {res: res, forceNext: false}; + }; + if (!hIndex.hasOwnProperty('_')) { + clHandler.limit = function() { // It's called after preCheck. + var cmdKey = clHandler.args[0] || ''; + if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); } + return hIndex.hasOwnProperty(cmdKey); + }; + } + } else { + clHandler.preCheck = function(res) { + clHandler.args = parseCl(res); + clHandler.hRes = typeof commandHandler === 'function' + ? commandHandler.apply(res, clHandler.args) : true; // true for break loop + return {res: res, forceNext: false}; + }; + } + return clHandler; +} + +exports.promptCL = function(commandHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: 'Requested command is not available.', + caseSensitive: false, + history: true + }, options), + // -------- forced + // trueValue, falseValue, keepWhitespace don't work. + // preCheck, limit (by clHandler) + clHandler = getClHandler(commandHandler, readOptions); + /* eslint-enable key-spacing */ + readOptions.limit = clHandler.limit; + readOptions.preCheck = clHandler.preCheck; + exports.prompt(readOptions); + return clHandler.args; +}; + +exports.promptLoop = function(inputHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + trueValue: null, + falseValue: null, + caseSensitive: false, + history: true + }, options); + /* eslint-enable key-spacing */ + while (true) { if (inputHandler(exports.prompt(readOptions))) { break; } } + // return; // nothing is returned +}; + +exports.promptCLLoop = function(commandHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: 'Requested command is not available.', + caseSensitive: false, + history: true + }, options), + // -------- forced + // trueValue, falseValue, keepWhitespace don't work. + // preCheck, limit (by clHandler) + clHandler = getClHandler(commandHandler, readOptions); + /* eslint-enable key-spacing */ + readOptions.limit = clHandler.limit; + readOptions.preCheck = clHandler.preCheck; + while (true) { + exports.prompt(readOptions); + if (clHandler.hRes) { break; } + } + // return; // nothing is returned +}; + +exports.promptSimShell = function(options) { + /* eslint-disable key-spacing */ + return exports.prompt(margeOptions({ + // -------- default + hideEchoBack: false, + history: true + }, options, { + // -------- forced + prompt: (function() { + return IS_WIN ? '$>' : + // 'user@host:cwd$ ' + (process.env.USER || '') + + (process.env.HOSTNAME ? '@' + process.env.HOSTNAME.replace(/\..*$/, '') : '') + + ':$$ '; + })() + })); + /* eslint-enable key-spacing */ +}; + +function _keyInYN(query, options, limit) { + var res; + if (query == null) { query = 'Are you sure? '; } + if ((!options || options.guide !== false) && (query += '')) { + query = query.replace(/\s*:?\s*$/, '') + ' [y/n]: '; + } + /* eslint-disable key-spacing */ + res = exports.keyIn(query, margeOptions(options, { + // -------- forced + hideEchoBack: false, + limit: limit, + trueValue: 'y', + falseValue: 'n', + caseSensitive: false + // mask doesn't work. + })); + // added: guide + /* eslint-enable key-spacing */ + return typeof res === 'boolean' ? res : ''; +} +exports.keyInYN = function(query, options) { return _keyInYN(query, options); }; +exports.keyInYNStrict = function(query, options) { return _keyInYN(query, options, 'yn'); }; + +exports.keyInPause = function(query, options) { + if (query == null) { query = 'Continue...'; } + if ((!options || options.guide !== false) && (query += '')) { + query = query.replace(/\s+$/, '') + ' (Hit any key)'; + } + /* eslint-disable key-spacing */ + exports.keyIn(query, margeOptions({ + // -------- default + limit: null + }, options, { + // -------- forced + hideEchoBack: true, + mask: '' + })); + // added: guide + /* eslint-enable key-spacing */ + // return; // nothing is returned +}; + +exports.keyInSelect = function(items, query, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false + }, options, { + // -------- forced + trueValue: null, + falseValue: null, + caseSensitive: false, + // limit (by items), + phContent: function(param) { + return param === 'itemsCount' ? items.length + '' : + param === 'firstItem' ? (items[0] + '').trim() : + param === 'lastItem' ? (items[items.length - 1] + '').trim() : null; + } + }), + // added: guide, cancel + keylist = '', + key2i = {}, + charCode = 49 /* '1' */, + display = '\n'; + /* eslint-enable key-spacing */ + if (!Array.isArray(items) || !items.length || items.length > 35) { + throw '`items` must be Array (max length: 35).'; + } + + items.forEach(function(item, i) { + var key = String.fromCharCode(charCode); + keylist += key; + key2i[key] = i; + display += '[' + key + '] ' + (item + '').trim() + '\n'; + charCode = charCode === 57 /* '9' */ ? 97 /* 'a' */ : charCode + 1; + }); + if (!options || options.cancel !== false) { + keylist += '0'; + key2i['0'] = -1; + display += '[0] ' + + (options && options.cancel != null && typeof options.cancel !== 'boolean' + ? (options.cancel + '').trim() : 'CANCEL') + '\n'; + } + readOptions.limit = keylist; + display += '\n'; + + if (query == null) { query = 'Choose one from list: '; } + if ((query += '')) { + if (!options || options.guide !== false) { + query = query.replace(/\s*:?\s*$/, '') + ' [$]: '; + } + display += query; + } + + return key2i[exports.keyIn(display, readOptions).toLowerCase()]; +}; + +exports.getRawInput = function() { return rawInput; }; + +// ======== DEPRECATED ======== +function _setOption(optionName, args) { + var options; + if (args.length) { options = {}; options[optionName] = args[0]; } + return exports.setDefaultOptions(options)[optionName]; +} +exports.setPrint = function() { return _setOption('print', arguments); }; +exports.setPrompt = function() { return _setOption('prompt', arguments); }; +exports.setEncoding = function() { return _setOption('encoding', arguments); }; +exports.setMask = function() { return _setOption('mask', arguments); }; +exports.setBufferSize = function() { return _setOption('bufferSize', arguments); }; diff --git a/z1-prototype/node_modules/readline-sync/package.json b/z1-prototype/node_modules/readline-sync/package.json new file mode 100644 index 0000000..c22921f --- /dev/null +++ b/z1-prototype/node_modules/readline-sync/package.json @@ -0,0 +1,68 @@ +{ + "_from": "readline-sync@^1.4.10", + "_id": "readline-sync@1.4.10", + "_inBundle": false, + "_integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==", + "_location": "/readline-sync", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "readline-sync@^1.4.10", + "name": "readline-sync", + "escapedName": "readline-sync", + "rawSpec": "^1.4.10", + "saveSpec": null, + "fetchSpec": "^1.4.10" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz", + "_shasum": "41df7fbb4b6312d673011594145705bf56d8873b", + "_spec": "readline-sync@^1.4.10", + "_where": "/Users/jacob/Documents/University/Rok_3/Semestr_1/Analiza i projektowanie obiektowe/APO_automat/z1-prototype", + "author": { + "name": "anseki", + "url": "https://github.com/anseki" + }, + "bugs": { + "url": "https://github.com/anseki/readline-sync/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Synchronous Readline for interactively running to have a conversation with the user via a console(TTY).", + "engines": { + "node": ">= 0.8.0" + }, + "files": [ + "lib/*.@(js|ps1|sh)", + "README-Deprecated.md" + ], + "homepage": "https://github.com/anseki/readline-sync", + "keywords": [ + "readline", + "synchronous", + "interactive", + "prompt", + "question", + "password", + "cli", + "tty", + "command", + "repl", + "keyboard", + "wait", + "block" + ], + "license": "MIT", + "main": "./lib/readline-sync.js", + "name": "readline-sync", + "repository": { + "type": "git", + "url": "git://github.com/anseki/readline-sync.git" + }, + "title": "readlineSync", + "version": "1.4.10" +} diff --git a/z1-prototype/package-lock.json b/z1-prototype/package-lock.json new file mode 100644 index 0000000..56ea423 --- /dev/null +++ b/z1-prototype/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "vending-machine", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "readline-sync": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz", + "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==" + } + } +} diff --git a/z1-prototype/package.json b/z1-prototype/package.json new file mode 100644 index 0000000..c623da8 --- /dev/null +++ b/z1-prototype/package.json @@ -0,0 +1,14 @@ +{ + "name": "vending-machine", + "version": "1.0.0", + "description": "", + "main": "menu.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "readline-sync": "^1.4.10" + } +} diff --git a/z1-prototype/product.js b/z1-prototype/product.js new file mode 100644 index 0000000..7c42da8 --- /dev/null +++ b/z1-prototype/product.js @@ -0,0 +1,7 @@ +module.exports = class Product { + constructor(name, quantity, price) { + this.name = name; + this.quantity = quantity; + this.price = price; + } +}; diff --git a/z1-prototype/products.json b/z1-prototype/products.json new file mode 100644 index 0000000..786891c --- /dev/null +++ b/z1-prototype/products.json @@ -0,0 +1,27 @@ +[ + { + "name": "Snickers", + "quantity": 5, + "price": 2.5 + }, + { + "name": "Mars", + "quantity": 3, + "price": 2 + }, + { + "name": "Bounty", + "quantity": 7, + "price": 2.25 + }, + { + "name": "Pepsi", + "quantity": 10, + "price": 3 + }, + { + "name": "Mirinda", + "quantity": 8, + "price": 3 + } +] diff --git a/z1-prototype/vendingMachine.js b/z1-prototype/vendingMachine.js new file mode 100644 index 0000000..92f498c --- /dev/null +++ b/z1-prototype/vendingMachine.js @@ -0,0 +1,79 @@ +const Product = require('./product'); + +module.exports = class VendingMachine { + constructor() { + this.id = Math.floor(Math.random() * 1000); + this.products = []; + } + + addProduct(name, quantity, price) { + if (this.products[name]) { + this.products[name].quantity += quantity; + } else { + if (!price) { + console.error('Price not specified'); + return 0; + } + this.products[name] = new Product(name, quantity, price); + } + return this.products[name]; + } + + buyProduct(id) { + this.products.forEach((product) => { + if (product.id == id) { + product.quantity--; + } + }); + } + + getProducts() { + return this.products; + } + + getProductById(id) { + let product = null; + this.products.forEach((element) => { + if (element.id == id) { + product = element; + } + }); + return product; + } + + fillMachine() { + this.products = require('./products'); + this.enumerateProducts(); + } + + enumerateProducts() { + let id = 1; + this.products.forEach((item) => (item.id = id++)); + } + + calculateChange(ammount) { + const availableCoins = [ + 0.01, + 0.02, + 0.05, + 0.1, + 0.2, + 0.5, + 1, + 2, + 5 + ].reverse(); + let change = []; + let sum = 0; + while (sum < ammount) { + for (let coin of availableCoins) { + if (sum + coin <= ammount) { + change.push(coin); + break; + } + } + sum = change.reduce((acc, curr) => acc + curr); + } + return change; + } +};