Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

remove node_modules from git project

  • Loading branch information...
commit 4e619f801059650a6fac5c6cb6cf708b56d1664a 1 parent bda6231
@dylang authored
Showing with 0 additions and 3,555 deletions.
  1. +0 −196 node_modules/cli/README.md
  2. +0 −1,125 node_modules/cli/cli.js
  3. +0 −17 node_modules/cli/examples/cat.js
  4. +0 −16 node_modules/cli/examples/command.js
  5. +0 −54 node_modules/cli/examples/echo.js
  6. +0 −6 node_modules/cli/examples/glob.js
  7. +0 −20 node_modules/cli/examples/long_desc.js
  8. +0 −11 node_modules/cli/examples/progress.js
  9. +0 −18 node_modules/cli/examples/sort.js
  10. +0 −9 node_modules/cli/examples/spinner.js
  11. +0 −27 node_modules/cli/examples/static.coffee
  12. +0 −25 node_modules/cli/examples/static.js
  13. +0 −1  node_modules/cli/index.js
  14. +0 −23 node_modules/cli/package.json
  15. +0 −55 node_modules/request/LICENSE
  16. +0 −123 node_modules/request/README.md
  17. +0 −150 node_modules/request/cookies.js
  18. +0 −424 node_modules/request/main.js
  19. +0 −146 node_modules/request/mimetypes.js
  20. +0 −14 node_modules/request/package.json
  21. BIN  node_modules/request/tests/googledoodle.png
  22. +0 −45 node_modules/request/tests/server.js
  23. +0 −74 node_modules/request/tests/test-body.js
  24. 0  node_modules/request/tests/test-cookies.js
  25. +0 −30 node_modules/request/tests/test-errors.js
  26. +0 −136 node_modules/request/tests/test-pipes.js
  27. +0 −7 node_modules/request/tests/test-ssl.js
  28. +0 −84 node_modules/request/tests/test-timeout.js
  29. +0 −71 node_modules/step/README.markdown
  30. +0 −154 node_modules/step/lib/step.js
  31. +0 −11 node_modules/step/package.json
  32. +0 −26 node_modules/step/test/callbackTest.js
  33. +0 −27 node_modules/step/test/errorTest.js
  34. +0 −21 node_modules/step/test/fnTest.js
  35. +0 −102 node_modules/step/test/groupTest.js
  36. +0 −17 node_modules/step/test/helper.js
  37. +0 −49 node_modules/step/test/parallelTest.js
  38. +0 −1  node_modules/wordwrap/.npmignore
  39. +0 −54 node_modules/wordwrap/README.markdown
  40. +0 −10 node_modules/wordwrap/example/center.js
  41. +0 −3  node_modules/wordwrap/example/meat.js
  42. +0 −42 node_modules/wordwrap/index.js
  43. +0 −37 node_modules/wordwrap/package.json
  44. +0 −63 node_modules/wordwrap/test/idleness.txt
  45. +0 −31 node_modules/wordwrap/test/wrap.js
View
196 node_modules/cli/README.md
@@ -1,196 +0,0 @@
-**cli is a toolkit for rapidly building command line apps - it includes:**
-
-- Full featured opts/args parser
-- Plugin support for adding common options and switches
-- Helper methods for working with input/output and spawning child processes
-- Output colored/styled messages, [progress bars](https://github.com/chriso/cli/blob/master/examples/progress.js) or [spinners](https://github.com/chriso/cli/blob/master/examples/spinner.js)
-- Command [auto-completion](https://github.com/chriso/cli/blob/master/examples/command.js) and [glob support](https://github.com/chriso/cli/blob/master/examples/glob.js)
-
-Install using `npm install cli` or just bundle [cli.js](https://github.com/chriso/cli/raw/master/cli-min.js) with your app.
-
-## Example apps
-
-### sort.js
-
-```javascript
-#!/usr/bin/env node
-require('cli').withStdinLines(function(lines, newline) {
- this.output(lines.sort().join(newline));
-});
-```
-
-Try it out
-
-```bash
-$ ./sort.js < input.txt
-```
-
-Let's add support for an `-n` switch to use a numeric sort, and a `-r` switch to reverse output - only 5 extra lines of code (!)
-
-```javascript
-var cli = require('cli'), options = cli.parse();
-
-cli.withStdinLines(function(lines, newline) {
- lines.sort(!options.n ? null : function(a, b) {
- return parseInt(a) > parseInt(b);
- });
- if (options.r) lines.reverse();
- this.output(lines.join(newline));
-});
-```
-
-### static.js
-
-Let's create a static file server with daemon support to see the opts parser + plugins in use - note: this requires `npm install creationix daemon`
-
-```javascript
-var cli = require('cli').enable('daemon', 'status'); //Enable 2 plugins
-
-cli.parse({
- log: ['l', 'Enable logging'],
- port: ['p', 'Listen on this port', 'number', 8080],
- serve: [false, 'Serve static files from PATH', 'path', './public']
-});
-
-cli.main(function(args, options) {
- var server, middleware = [];
-
- if (options.log) {
- this.debug('Enabling logging');
- middleware.push(require('creationix/log')());
- }
-
- this.debug('Serving files from ' + options.serve);
- middleware.push(require('creationix/static')('/', options.serve, 'index.html'));
-
- server = this.createServer(middleware).listen(options.port);
-
- this.ok('Listening on port ' + options.port);
-});
-```
-
-To output usage information
-
-```bash
-$ ./static.js --help
-```
-
-To create a daemon that serves files from */tmp*, run
-
-```bash
-$ ./static.js -ld --serve=/tmp
-```
-
-For more examples, see [./examples](https://github.com/chriso/cli/tree/master/examples)
-
-## Helper methods
-
-cli has methods that collect stdin (newline is autodetected as \n or \r\n)
-
-```javascript
-cli.withStdin(callback); //callback receives stdin as a string
-cli.withStdinLines(callback); //callback receives stdin split into an array of lines (lines, newline)
-```
-
-cli also has a lower level method for working with input line by line (see [./examples/cat.js](https://github.com/chriso/cli/blob/master/examples/cat.js) for an example).
-
-```javascript
-cli.withInput(file, function (line, newline, eof) {
- if (!eof) {
- this.output(line + newline);
- }
-});
-```
-
-*Note: `file` can be omitted if you want to work with stdin*
-
-To output a progress bar, call
-
-```javascript
-cli.progress(progress); //Where 0 <= progress <= 1
-```
-
-To spawn a child process, use
-
-```javascript
-cli.exec(cmd, callback); //callback receives the output of the process (split into lines)
-```
-
-cli also comes bundled with kof's [node-natives](https://github.com/kof/node-natives) (access with cli.native) and creationix' [stack](https://github.com/creationix/stack) (access with cli.createServer)
-
-## Plugins
-
-Plugins are a way of adding common opts and can be enabled using
-
-```javascript
-cli.enable(plugin1, [plugin2, ...]); //To disable, use the equivalent disable() method
-```
-
-**help** - *enabled by default*
-
-Adds `-h,--help` to output auto-generated usage information
-
-**version**
-
-Adds `-v,--version` to output version information for the app. cli will attempt to locate and parse a nearby *package.json*
-
-To set your own app name and version, use `cli.setApp(app_name, version)`
-
-**status**
-
-Adds options to show/hide the stylized status messages that are output to the console when using one of these methods
-
-```javascript
-cli.debug(msg); //Only shown when using --debug
-cli.error(msg);
-cli.fatal(msg); //Exits the process after outputting msg
-cli.info(msg);
-cli.ok(msg);
-```
-
-`-k,--no-color` will omit ANSI color escapes from the output
-
-**glob** - *requires* `npm install glob`
-
-Enables glob matching of arguments
-
-**daemon** - *requires* `npm install daemon`
-
-Adds `-d,--daemon ARG` for daemonizing the process and controlling the resulting daemon
-
-`ARG` can be either start (default), stop, restart, pid (outputs the daemon's pid if it's running), or log (output the daemon's stdout+stderr)
-
-**timeout**
-
-Adds `-t,--timeout N` to exit the process after N seconds with an error
-
-**catchall**
-
-Adds `-c,--catch` to catch and output uncaughtExceptions and resume execution
-
-*Note: Plugins are automatically disabled if an option or switch of the same name is already defined*
-
-## LICENSE
-
-(MIT license)
-
-Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>
-
-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.
View
1,125 node_modules/cli/cli.js
@@ -1,1125 +0,0 @@
-/**
- * Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>
- *
- * 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.
- */
-
- //Note: cli includes kof/node-natives and creationix/stack. I couldn't find
- //license information for either - contact me if you want your license added
-
-var cli = exports,
- argv, curr_opt, curr_val, full_opt, is_long,
- short_tags = [], opt_list, parsed = {},
- usage, argv_parsed, command_list, commands,
- daemon, daemon_arg, no_color, show_debug;
-
-cli.app = null;
-cli.version = null;
-cli.argv = [];
-cli.argc = 0;
-
-cli.options = {};
-cli.args = [];
-cli.command;
-
-cli.width = 70;
-cli.option_width = 25;
-
-/**
- * Bind kof's node-natives (https://github.com/kof/node-natives) to `cli.native`
- *
- * Rather than requiring node natives (e.g. var fs = require('fs')), all
- * native modules can be accessed like `cli.native.fs`
- */
-cli.native = {};
-var define_native = function (module) {
- Object.defineProperty(cli.native, module, {
- enumerable: true,
- configurable: true,
- get: function() {
- delete cli.native[module];
- return cli.native[module] = require(module);
- }
- });
-};
-var natives = process.binding('natives');
-for (var module in natives) {
- define_native(module);
-}
-
-cli.output = cli.native.util.print;
-cli.exit = process.exit;
-
-/**
- * Define plugins. Plugins can be enabled and disabled by calling:
- *
- * `cli.enable(plugin1, [plugin2, ...])`
- * `cli.disable(plugin1, [plugin2, ...])`
- *
- * Methods are chainable - `cli.enable(plugin).disable(plugin2)`.
- *
- * The 'help' plugin is enabled by default.
- */
-var enable = {
- help: true, //Adds -h, --help
- version: false, //Adds -v,--version => gets version by parsing a nearby package.json
- daemon: false, //Adds -d,--daemon [ARG] => (see cli.daemon() below)
- status: false, //Adds -k,--no-color & --debug => display plain status messages /display debug messages
- timeout: false, //Adds -t,--timeout N => timeout the process after N seconds
- catchall: false, //Adds -c,--catch => catch and output uncaughtExceptions
- glob: false //Adds glob matching => use cli.glob(arg)
-}
-cli.enable = function (/*plugins*/) {
- Array.prototype.slice.call(arguments).forEach(function (plugin) {
- switch (plugin) {
- case 'daemon':
- try {
- daemon = require('daemon');
- if (typeof daemon.daemonize !== 'function') {
- throw 'Invalid module';
- }
- } catch (e) {
- cli.fatal('daemon.node not installed. Please run `npm install daemon`');
- }
- break;
- case 'catchall':
- process.on('uncaughtException', function (err) {
- cli.error('Uncaught exception: ' + (err.msg || err));
- });
- break;
- case 'help': case 'version': case 'status':
- case 'autocomplete': case 'timeout':
- //Just add switches.
- break;
- case 'glob':
- try {
- glob = require('glob');
- if (typeof glob.glob !== 'function') {
- throw 'Invalid module';
- }
- } catch (e) {
- cli.fatal('glob not installed. Please run `npm install glob`');
- }
- cli.glob = glob.glob;
- cli.globSync = glob.globSync;
- break;
- default:
- cli.fatal('Unknown plugin "' + plugin + '"');
- break;
- }
- enable[plugin] = true;
- });
- return cli;
-}
-cli.disable = function (/*plugins*/) {
- Array.prototype.slice.call(arguments).forEach(function (plugin) {
- if (enable[plugin]) {
- enable[plugin] = false;
- }
- });
- return cli;
-}
-
-/**
- * Sets argv (default is process.argv).
- *
- * @param {Array|String} argv
- * @param {Boolean} keep_arg0 (optional - default is false)
- * @api public
- */
-cli.setArgv = function (arr, keep_arg0) {
- if (typeof arr == 'string') {
- arr = arr.split(' ');
- } else {
- arr = arr.slice();
- }
- cli.app = arr.shift();
- //Strip off argv[0] if it's 'node'
- if (!keep_arg0 && 'node' === cli.native.path.basename(cli.app)) {
- cli.app = arr.shift();
- }
- cli.app = cli.native.path.basename(cli.app);
- argv_parsed = false;
- cli.args = cli.argv = argv = arr;
- cli.argc = argv.length;
-};
-cli.setArgv(process.argv);
-
-/**
- * Returns the next opt, or false if no opts are found.
- *
- * @return {String} opt
- * @api public
- */
-cli.next = function () {
- if (!argv_parsed) {
- cli.args = [];
- argv_parsed = true;
- }
-
- curr_val = null;
-
- //If we're currently in a group of short opts (e.g. -abc), return the next opt
- if (short_tags.length) {
- curr_opt = short_tags.shift();
- full_opt = '-' + curr_opt;
- return curr_opt;
- }
-
- if (!argv.length) {
- return false;
- }
-
- curr_opt = argv.shift();
-
- //If an escape sequence is found (- or --), subsequent opts are ignored
- if (curr_opt === '-' || curr_opt === '--') {
- while (argv.length) {
- cli.args.push(argv.shift());
- }
- return false;
- }
-
- //If the next element in argv isn't an opt, add it to the list of args
- if (curr_opt[0] !== '-') {
- cli.args.push(curr_opt);
- return cli.next();
- } else {
- //Check if the opt is short/long
- is_long = curr_opt[1] === '-';
- curr_opt = curr_opt.substr(is_long ? 2 : 1);
- }
-
- //Accept grouped short opts, e.g. -abc => -a -b -c
- if (!is_long && curr_opt.length > 1) {
- short_tags = curr_opt.split('');
- return cli.next();
- }
-
- var eq, len;
-
- //Check if the long opt is in the form --option=VALUE
- if (is_long && (eq = curr_opt.indexOf('=')) >= 0) {
- curr_val = curr_opt.substr(eq + 1);
- curr_opt = curr_opt.substr(0, eq);
- len = curr_val.length;
- //Allow values to be quoted
- if ((curr_val[0] === '"' && curr_val[len - 1] === '"') ||
- (curr_val[0] === "'" && curr_val[len - 1] === "'"))
- {
- curr_val = curr_val.substr(1, len-2);
- }
- if (curr_val.match(/^[0-9]+$/)) {
- curr_val = parseInt(curr_val, 10);
- }
- }
-
- //Save the opt representation for later
- full_opt = (is_long ? '--' : '-') + curr_opt;
-
- return curr_opt;
-};
-
-/**
- * Parses command line opts.
- *
- * `opts` must be an object with opts defined like:
- * long_tag: [short_tag, description, value_type, default_value];
- *
- * `commands` is an optional array or object for apps that are of the form
- * my_app [OPTIONS] <command> [ARGS]
- * The command list is output with usage information + there is bundled
- * support for auto-completion, etc.
- *
- * See README.md for more information.
- *
- * @param {Object} opts
- * @param {Object} commands (optional)
- * @return {Object} opts (parsed)
- * @api public
- */
-cli.parse = function (opts, command_def) {
- var default_val, i, parsed = cli.options, seen,
- catch_all = !opts;
- opt_list = opts || {};
- commands = command_def;
- command_list = commands || [];
- if (commands && !Array.isArray(commands)) {
- command_list = Object.keys(commands);
- }
- while (o = cli.next()) {
- seen = false;
- for (opt in opt_list) {
- if (!(opt_list[opt] instanceof Array)) {
- continue;
- }
- if (opt_list[opt][0] === false) {
- opt_list[opt][0] = opt;
- }
- if (o === opt || o === opt_list[opt][0]) {
- seen = true;
- if (opt_list[opt].length === 2) {
- parsed[opt] = true;
- break;
- }
- default_val = null;
- if (opt_list[opt].length === 4) {
- default_val = opt_list[opt][3];
- }
- if (opt_list[opt][2] instanceof Array) {
- for (i = 0, l = opt_list[opt][2].length; i < l; i++) {
- if (typeof opt_list[opt][2][i] === 'number') {
- opt_list[opt][2][i] += '';
- }
- }
- parsed[opt] = cli.getArrayValue(opt_list[opt][2], is_long ? null : default_val);
- break;
- }
- if (opt_list[opt][2].toLowerCase) {
- opt_list[opt][2] = opt_list[opt][2].toLowerCase();
- }
- switch (opt_list[opt][2]) {
- case 'string': case 1: case true:
- parsed[opt] = cli.getValue(default_val);
- break;
- case 'int': case 'number': case 'num':
- case 'time': case 'seconds': case 'secs': case 'minutes': case 'mins':
- case 'x': case 'n':
- parsed[opt] = cli.getInt(default_val);
- break;
- case 'float': case 'decimal':
- parsed[opt] = cli.getFloat(default_val);
- break;
- case 'path': case 'file': case 'directory': case 'dir':
- parsed[opt] = cli.getPath(default_val, opt_list[opt][2]);
- break;
- case 'email':
- parsed[opt] = cli.getEmail(default_val);
- break;
- case 'url': case 'uri': case 'domain': case 'host':
- parsed[opt] = cli.getUrl(default_val, opt_list[opt][2]);
- break;
- case 'ip':
- parsed[opt] = cli.getIp(default_val);
- break;
- case 'bool': case 'boolean': case 'on':
- parsed[opt] = true;
- break;
- case 'false': case 'off': case false: case 0:
- parsed[opt] = false;
- break;
- default:
- cli.fatal('Unknown opt type "' + opt_list[opt][2] + '"');
- }
- break;
- }
- }
- if (!seen) {
- if (enable.help && (o === 'h' || o === 'help')) {
- cli.getUsage();
- process.exit();
- } else if (enable.version && (o === 'v' || o === 'version')) {
- if (typeof cli.version === 'undefined') {
- cli.parsePackageJson();
- }
- console.error(cli.app + ' v' + cli.version);
- process.exit();
- } else if (enable.daemon && (o === 'd' || o === 'daemon')) {
- daemon_arg = cli.getArrayValue(['start','stop','restart','pid','log'], is_long ? null : 'start');
- continue;
- } else if (enable.catchall && (o === 'c' || o === 'catch')) {
- continue;
- } else if (enable.status && (o === 'k' || o === 'no-color' || o === 'debug')) {
- no_color = (o === 'k' || o === 'no-color');
- show_debug = o === 'debug';
- continue;
- } else if (enable.timeout && (o === 't' || o === 'timeout')) {
- var secs = cli.getInt();
- setTimeout(function () {
- cli.fatal('Process timed out after ' + secs + 's');
- }, secs * 1000);
- continue;
- } else if (catch_all) {
- parsed[o] = curr_val || true;
- continue;
- }
- cli.fatal('Unknown option ' + full_opt);
- }
- }
- //Fill the remaining options with their default value or null
- for (opt in opt_list) {
- default_val = opt_list[opt].length === 4 ? opt_list[opt][3] : null;
- if (!(opt_list[opt] instanceof Array)) {
- parsed[opt] = opt_list[opt];
- continue;
- } else if (typeof parsed[opt] === 'undefined') {
- parsed[opt] = default_val;
- }
- }
- if (command_list.length) {
- if (cli.args.length === 0) {
- if (enable.help) {
- cli.getUsage();
- } else {
- cli.fatal('A command is required (' + command_list.join(', ') + ').');
- }
- process.exit(1);
- } else {
- cli.command = cli.autocompleteCommand(cli.args.shift());
- }
- }
- cli.argc = cli.args.length;
- return parsed;
-};
-
-/**
- * Helper method for matching a command from the command list.
- *
- * @param {String} command
- * @return {String} full_command
- * @api public
- */
-cli.autocompleteCommand = function (command) {
- var list;
- if (!(command_list instanceof Array)) {
- list = Object.keys(command_list);
- } else {
- list = command_list;
- }
- var i, j = 0, c = command.length, tmp_list;
- if (list.length === 0 || list.indexOf(command) !== -1) {
- return command;
- }
- for (i = 0; i < c; i++) {
- tmp_list = [];
- l = list.length;
- if (l <= 1) break;
- for (j = 0; j < l; j++)
- if (list[j].length >= i && list[j][i] === command[i])
- tmp_list.push(list[j]);
- list = tmp_list;
- }
- l = list.length;
- if (l === 1) {
- return list[0];
- } else if (l === 0) {
- cli.fatal('Unknown command "' + command + '"' + (enable.help ? '. Please see --help for more information' : ''));
- } else {
- list.sort();
- cli.fatal('The command "' + command + '" is ambiguous and could mean "' + list.join('", "') + '"');
- }
-};
-
-/**
- * Adds methods to output styled status messages to stderr.
- *
- * Added methods are cli.info(msg), cli.error(msg), cli.ok(msg), and
- * cli.debug(msg).
- *
- * To control status messages, use the 'status' plugin
- * 1) debug() messages are hidden by default. Display them with
- * the --debug opt.
- * 2) to hide all status messages, use the -s or --silent opt.
- *
- * @api private
- */
-cli.status = function (msg, type) {
- var pre;
- switch (type) {
- case 'info':
- pre = no_color ? 'INFO:' : '\x1B[33mINFO\x1B[0m:';
- break;
- case 'debug':
- pre = no_color ? 'DEBUG:' : '\x1B[36mDEBUG\x1B[0m:';
- break;
- case 'error':
- case 'fatal':
- pre = no_color ? 'ERROR:' : '\x1B[31mERROR\x1B[0m:';
- break;
- case 'ok':
- pre = no_color ? 'OK:' : '\x1B[32mOK\x1B[0m:';
- break;
- }
- msg = pre + ' ' + msg;
- if (type === 'fatal') {
- console.error(msg);
- process.exit(1);
- }
- if (enable.status && !show_debug && type === 'debug') {
- return;
- }
- console.error(msg);
-};
-['info','error','ok','debug','fatal'].forEach(function (type) {
- cli[type] = function (msg) {
- cli.status(msg, type);
- };
-});
-
-/**
- * Sets the app name and version.
- *
- * Usage:
- * setApp('myapp', '0.1.0');
- * setApp('./package.json'); //Pull name/version from package.json
- *
- * @param {String} name
- * @return cli (for chaining)
- * @api public
- */
-cli.setApp = function (name, version) {
- if (name.indexOf('package.json') !== -1) {
- cli.parsePackageJson(name);
- } else {
- cli.app = name;
- cli.version = version;
- }
- return cli;
-};
-
-/**
- * Parses the version number from package.json. If no path is specified, cli
- * will attempt to locate a package.json in ./, ../ or ../../
- *
- * @param {String} path (optional)
- * @api public
- */
-cli.parsePackageJson = function (path) {
- var parse_packagejson = function (path) {
- var packagejson = JSON.parse(cli.native.fs.readFileSync(path, 'utf8'));
- cli.version = packagejson.version;
- cli.app = packagejson.name;
- };
- var try_all = function (arr, func, err) {
- for (var i = 0, l = arr.length; i < l; i++) {
- try {
- func(arr[i]);
- return;
- } catch (e) {
- if (i === l-1) {
- cli.fatal(err);
- }
- }
- }
- };
- try {
- if (path) {
- return parse_packagejson(path);
- }
- try_all([
- __dirname + '/package.json',
- __dirname + '/../package.json',
- __dirname + '/../../package.json'
- ], parse_packagejson);
- } catch (e) {
- cli.fatal('Could not detect ' + cli.app + ' version');
- }
-};
-
-/**
- * Sets the usage string - default is `app [OPTIONS] [ARGS]`.
- *
- * @param {String} u
- * @return cli (for chaining)
- * @api public
- */
-cli.setUsage = function (u) {
- usage = u;
- return cli;
-};
-
-var pad = function (str, len) {
- if (typeof len === 'undefined') {
- len = str;
- str = '';
- }
- if (str.length < len) {
- len -= str.length;
- while (len--) str += ' ';
- }
- return str;
-};
-
-/**
- * Automatically build usage information from the opts list. If the help
- * plugin is enabled (default), this info is displayed with -h, --help.
- *
- * @api public
- */
-cli.getUsage = function () {
- var short, desc, optional, line, seen_opts = [],
- switch_pad = cli.option_width;
-
- var trunc_desc = function (pref, desc, len) {
- var pref_len = pref.length,
- desc_len = cli.width - pref_len,
- truncated = '';
- if (desc.length <= desc_len) {
- return desc;
- }
- var desc_words = (desc+'').split(' '), chars = 0, word;
- while (desc_words.length) {
- truncated += (word = desc_words.shift()) + ' ';
- chars += word.length;
- if (desc_words.length && chars + desc_words[0].length > desc_len) {
- truncated += '\n' + pad(pref_len);
- chars = 0;
- }
- }
- return truncated;
- };
-
- usage = usage || cli.app + ' [OPTIONS]' + (command_list ? ' <command>' : '') + ' [ARGS]';
- console.error('\x1b[1mUsage\x1b[0m:\n ' + usage);
- console.error('\n\x1b[1mOptions\x1b[0m: ');
- for (opt in opt_list) {
-
- if (opt.length === 1) {
- long = opt_list[opt][0];
- short = opt;
- } else {
- long = opt;
- short = opt_list[opt][0];
- }
-
- //Parse opt_list
- desc = opt_list[opt][1].trim();
- type = opt_list[opt].length >= 3 ? opt_list[opt][2] : null;
- optional = opt_list[opt].length === 4 ? opt_list[opt][3] : null;
-
- //Build usage line
- if (short === long) {
- if (short.length === 1) {
- line = ' -' + short;
- } else {
- line = ' --' + long;
- }
- } else {
- line = ' -' + short + ', --' + long;
- }
- line += ' ';
-
- if (type) {
- if (type instanceof Array) {
- desc += '. VALUE must be either [' + type.join('|') + ']';
- type = 'VALUE';
- }
- if (type === true || type === 1) {
- type = long.toUpperCase();
- }
- type = type.toUpperCase();
- if (type === 'FLOAT' || type === 'INT') {
- type = 'NUMBER';
- }
- line += optional ? '[' + type + ']' : type;
- }
- line = pad(line, switch_pad);
- line += trunc_desc(line, desc);
- line += optional ? ' (Default is ' + optional + ')' : '';
- console.error(line.replace('%s', '%\0s'));
-
- seen_opts.push(short);
- seen_opts.push(long);
- }
- if (enable.timeout && seen_opts.indexOf('t') === -1 && seen_opts.indexOf('timeout') === -1) {
- console.error(pad(' -t, --timeout N', switch_pad) + 'Exit if the process takes longer than N seconds');
- }
- if (enable.status) {
- if (seen_opts.indexOf('k') === -1 && seen_opts.indexOf('no-color') === -1) {
- console.error(pad(' -k, --no-color', switch_pad) + 'Omit color from output');
- }
- if (seen_opts.indexOf('debug') === -1) {
- console.error(pad(' --debug', switch_pad) + 'Show debug information');
- }
- }
- if (enable.catchall && seen_opts.indexOf('c') === -1 && seen_opts.indexOf('catch') === -1) {
- console.error(pad(' -c, --catch', switch_pad) + 'Catch unanticipated errors');
- }
- if (enable.daemon && seen_opts.indexOf('d') === -1 && seen_opts.indexOf('daemon') === -1) {
- console.error(pad(' -d, --daemon [ARG]', switch_pad) + 'Daemonize the process. Control the daemon using [start, stop, restart, log, pid]');
- }
- if (enable.version && seen_opts.indexOf('v') === -1 && seen_opts.indexOf('version') === -1) {
- console.error(pad(' -v, --version', switch_pad) + 'Display the current version');
- }
- if (enable.help && seen_opts.indexOf('h') === -1 && seen_opts.indexOf('help') === -1) {
- console.error(pad(' -h, --help', switch_pad) + 'Display help and usage details');
- }
- if (command_list.length) {
- console.error('\n\x1b[1mCommands\x1b[0m: ');
- if (!Array.isArray(commands)) {
- for (var c in commands) {
- line = ' ' + pad(c, switch_pad - 2);
- line += trunc_desc(line, commands[c]);
- console.error(line);
- }
- } else {
- command_list.sort();
- console.error(' ' + trunc_desc(' ', command_list.join(', ')));
- }
- }
- process.exit();
-};
-
-/**
- * Generates an error message when an opt is incorrectly used.
- *
- * @param {String} expects (e.g. 'a value')
- * @param {String} type (e.g. 'VALUE')
- * @api public
- */
-cli.getOptError = function (expects, type) {
- var err = full_opt + ' expects ' + expects
- + '. Use `' + cli.app + ' ' + full_opt + (is_long ? '=' : ' ') + type + '`';
- return err;
-};
-
-/**
- * Gets the next opt value and validates it with an optional validation
- * function. If validation fails or no value can be obtained, this method
- * will return the default value (if specified) or exit with err_msg.
- *
- * @param {String} default_val
- * @param {Function} validate_func
- * @param {String} err_msg
- * @api public
- */
-cli.getValue = function (default_val, validate_func, err_msg) {
- err_msg = err_msg || cli.getOptError('a value', 'VALUE');
-
- var value;
-
- try {
- if (curr_val) {
- if (validate_func) {
- curr_val = validate_func(curr_val);
- }
- return curr_val;
- }
-
- //Grouped short opts aren't allowed to have values
- if (short_tags.length) {
- throw 'Short tags';
- }
-
- //If there's no args left or the next arg is an opt, return the
- //default value (if specified) - otherwise fail
- if (!argv.length || argv[0][0] === '-') {
- throw 'No value';
- }
-
- value = argv.shift();
-
- if (value.match(/^[0-9]+$/)) {
- value = parseInt(value, 10);
- }
-
- //Run the value through a validation/transformation function if specified
- if (validate_func) {
- value = validate_func(value);
- }
- } catch (e) {
-
- //The value didn't pass the validation/transformation. Unshift the value and
- //return the default value (if specified)
- if (value) {
- argv.unshift(value);
- }
- return default_val != null ? default_val : cli.fatal(err_msg);
- }
- return value;
-};
-
-cli.getInt = function (default_val) {
- return cli.getValue(default_val, function (value) {
- if (typeof value === 'number') return value;
- if (!value.match(/^(?:-?(?:0|[1-9][0-9]*))$/)) {
- throw 'Invalid int';
- }
- return parseInt(value);
- }, cli.getOptError('a number', 'NUMBER'));
-}
-
-cli.getFloat = function (default_val) {
- return cli.getValue(default_val, function (value) {
- if (!value.match(/^(?:-?(?:0|[1-9][0-9]*))?(?:\.[0-9]*)?$/)) {
- throw 'Invalid float';
- }
- return parseFloat(value, 10);
- }, cli.getOptError('a number', 'NUMBER'));
-}
-
-cli.getUrl = function (default_val, identifier) {
- identifier = identifier || 'url';
- return cli.getValue(default_val, function (value) {
- if (!value.match(/^(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2})?)|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?$/)) {
- throw 'Invalid URL';
- }
- return value;
- }, cli.getOptError('a ' + identifier, identifier.toUpperCase()));
-}
-
-cli.getEmail = function (default_val) {
- return cli.getValue(default_val, function (value) {
- if (!value.match(/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[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]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/)) {
- throw 'Invalid email';
- }
- return value;
- }, cli.getOptError('an email', 'EMAIL'));
-}
-
-cli.getIp = function (default_val) {
- return cli.getValue(default_val, function (value) {
- if (!value.match(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/)) {
- throw 'Invalid IP';
- }
- return value;
- }, cli.getOptError('an IP', 'IP'));
-}
-
-cli.getPath = function (default_val, identifier) {
- identifier = identifier || 'path';
- return cli.getValue(default_val, function (value) {
- if (value.match(/[?*:;{}]/)) {
- throw 'Invalid path';
- }
- return value;
- }, cli.getOptError('a ' + identifier, identifier.toUpperCase()));
-}
-
-cli.getArrayValue = function (arr, default_val) {
- return cli.getValue(default_val, function (value) {
- if (arr.indexOf(value) === -1) {
- throw 'Unexpected value';
- }
- return value;
- }, cli.getOptError('either [' + arr.join('|') + ']', 'VALUE'));
-}
-
-/**
- * Gets all data from STDIN (with optional encoding) and sends it to callback.
- *
- * @param {String} encoding (optional - default is 'utf8')
- * @param {Function} callback
- * @api public
- */
-cli.withStdin = function (encoding, callback) {
- if (typeof encoding === 'function') {
- callback = encoding;
- encoding = 'utf8';
- }
- var stream = process.openStdin(), data = '';
- stream.setEncoding(encoding);
- stream.on('data', function (chunk) {
- data += chunk;
- });
- stream.on('end', function () {
- callback.apply(cli, [data]);
- });
-};
-
-/**
- * Gets all data from STDIN, splits the data into lines and sends it
- * to callback (callback isn't called until all of STDIN is read. To
- * process each line as it's received, see the method below
- *
- * @param {Function} callback
- * @api public
- */
-cli.withStdinLines = function (callback) {
- cli.withStdin(function (data) {
- var sep = data.indexOf('\r\n') !== -1 ? '\r\n' : '\n';
- callback.apply(cli, [data.split(sep), sep]);
- });
-};
-
-/**
- * Asynchronously reads a file line by line. When a line is received,
- * callback is called with (line, sep) - when EOF is reached, callback
- * receives (null, null, true)
- *
- * @param {String} file (optional - default is 'stdin')
- * @param {String} encoding (optional - default is 'utf8')
- * @param {Function} callback (line, sep, eof)
- * @api public
- */
-cli.withInput = function (file, encoding, callback) {
- if (typeof encoding === 'function') {
- callback = encoding;
- encoding = 'utf8';
- } else if (typeof file === 'function') {
- callback = file;
- encoding = 'utf8';
- file = 'stdin';
- }
- if (file === 'stdin') {
- file = process.openStdin();
- } else {
- try {
- file = cli.native.fs.createReadStream(file);
- file.on('error', cli.fatal);
- } catch (e) {
- return cli.fatal(e);
- }
- }
- file.setEncoding(encoding);
- var lines = [], data = '', eof, sep;
- file.on('data', function (chunk) {
- if (eof) return;
- data += chunk;
- if (!sep) {
- if (data.indexOf('\r\n') !== -1) {
- sep = '\r\n';
- } else if (data.indexOf('\n') !== -1) {
- sep = '\n';
- } else {
- last_line = data;
- return;
- }
- }
- lines = data.split(sep);
- data = eof ? null : lines.pop();
- while (lines.length) {
- callback.apply(cli, [lines.shift(), sep, false]);
- }
- });
- file.on('end', function () {
- eof = true;
- if (data.length) {
- callback.apply(cli, [data, sep || '', false]);
- }
- callback.apply(cli, [null, null, true]);
- });
-};
-
-/**
- * A method for creating and controlling a daemon.
- *
- * `arg` can be:
- * start = daemonizes the process
- * stop = stops the daemon if it is running
- * restart = alias for stop -> start
- * pid = outputs the daemon's PID if it is running
- * log = outputs the daemon's log file (stdout + stderr)
- *
- * @param {String} arg (Optional - default is 'start')
- * @param {Function} callback
- * @api public
- */
-cli.daemon = function (arg, callback) {
- if (typeof daemon === 'undefined') {
- cli.fatal('Daemon is not initialized');
- }
-
- if (typeof arg === 'function') {
- callback = arg;
- arg = 'start';
- }
-
- var lock_file = '/tmp/' + cli.app + '.pid',
- log_file = '/tmp/' + cli.app + '.log';
-
- var start = function () {
- daemon.daemonize(log_file, lock_file, function (err) {
- if (err) return cli.error('Error starting daemon: ' + err);
- callback();
- });
- };
-
- var stop = function () {
- try {
- cli.native.fs.readFileSync(lock_file);
- } catch (e) {
- return cli.error('Daemon is not running');
- };
- daemon.kill(lock_file, function (err, pid) {
- if (err && err.errno === 3) {
- return cli.error('Daemon is not running');
- } else if (err) {
- return cli.error('Error stopping daemon: ' + err.errno);
- }
- cli.ok('Successfully stopped daemon with pid: ' + pid);
- });
- };
-
- switch(arg) {
- case 'stop':
- stop();
- break;
- case 'restart':
- daemon.stop(lock_file, function () {
- start();
- });
- break;
- case 'log':
- try {
- cli.native.fs.createReadStream(log_file, {encoding: 'utf8'}).pipe(process.stdout);
- } catch (e) {
- return cli.error('No daemon log file');
- };
- break;
- case 'pid':
- try {
- var pid = cli.native.fs.readFileSync(lock_file, 'utf8');
- cli.native.fs.statSync('/proc/' + pid);
- cli.info(pid);
- } catch (e) {
- return cli.error('Daemon is not running');
- };
- break;
- default:
- start();
- break;
- }
-}
-
-/**
- * The main entry method. Calling cli.main() is only necessary in
- * scripts that have daemon support enabled. `callback` receives (args, options)
- *
- * @param {Function} callback
- * @api public
- */
-cli.main = function (callback) {
- var after = function () {
- callback.apply(cli, [cli.args, cli.options]);
- };
- if (enable.daemon && daemon_arg) {
- cli.daemon(daemon_arg, after);
- } else {
- after();
- }
-}
-
-/**
- * Bind creationix's stack (https://github.com/creationix/stack).
- *
- * Create a simple middleware stack by calling:
- *
- * cli.createServer(middleware).listen(port);
- *
- * @return {Server} server
- * @api public
- */
-cli.createServer = function(/*layers*/) {
- var defaultStackErrorHandler = function (req, res, err) {
- if (err) {
- console.error(err.stack);
- res.writeHead(500, {"Content-Type": "text/plain"});
- return res.end(err.stack + "\n");
- }
- res.writeHead(404, {"Content-Type": "text/plain"});
- res.end("Not Found\n");
- };
- var handle = error = defaultStackErrorHandler,
- layers = Array.prototype.slice.call(arguments);
-
- //Allow createServer(a,b,c) and createServer([a,b,c])
- if (layers.length && layers[0] instanceof Array) {
- layers = layers[0];
- }
- layers.reverse().forEach(function (layer) {
- var child = handle;
- handle = function (req, res) {
- try {
- layer(req, res, function (err) {
- if (err) return error(req, res, err);
- child(req, res);
- });
- } catch (err) {
- error(req, res, err);
- }
- };
- });
- return cli.native.http.createServer(handle);
-};
-
-/**
- * A wrapper for child_process.exec().
- *
- * If the child_process exits successfully, `callback` receives an array of
- * stdout lines. The current process exits if the child process has an error
- * and `errback` isn't defined.
- *
- * @param {String} cmd
- * @param {Function} callback (optional)
- * @param {Function} errback (optional)
- * @api public
- */
-cli.exec = function (cmd, callback, errback) {
- cli.native.child_process.exec(cmd, function (err, stdout, stderr) {
- err = err || stderr;
- if (err) {
- if (errback) {
- return errback(err);
- }
- return cli.fatal('exec() failed\n' + err);
- }
- if (callback) {
- callback(stdout.split('\n'));
- }
- });
-};
-
-/**
- * Helper method for outputting a progress bar to the console.
- *
- * @param {Number} progress (0 <= progress <= 1)
- * @api public
- */
-var last_progress_call, progress_len = 74;
-cli.progress = function (progress) {
- if (progress < 0 || progress > 1 || isNaN(progress)) return;
- var now = (new Date()).getTime();
- if (last_progress_call && (now - last_progress_call) < 100 && progress !== 1) {
- return; //Throttle progress calls
- }
- last_progress_call = now;
-
-
- var barLength = Math.floor(progress_len * progress),
- str = '';
- if (barLength == 0 && progress > 0) {
- barLength = 1;
- }
- for (var i = 1; i <= progress_len; i++) {
- str += i <= barLength ? '#' : ' ';
- }
- cli.native.util.print('[' + str + '] ' + Math.floor(progress * 100) + '%' + (progress === 1 ? '\n' : '\u000D'));
-};
-
-/**
- * Helper method for outputting a spinner to the console.
- *
- * @param {String|Boolean} prefix (optional)
- * @api public
- */
-var spinnerInterval;
-cli.spinner = function (prefix, end) {
- if (end) {
- cli.native.util.print('\u000D' + prefix);
- return clearInterval(spinnerInterval);
- }
- prefix = prefix + ' ' || '';
- var spinner = ['-','\\','|','/'], i = 0, l = spinner.length;
- spinnerInterval = setInterval(function () {
- cli.native.util.print('\u000D' + prefix + spinner[i++]);
- if (i == l) i = 0;
- }, 200);
-};
View
17 node_modules/cli/examples/cat.js
@@ -1,17 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli');
-
-var output_file = function (file) {
- cli.withInput(file, function (line, sep, eof) {
- if (!eof) {
- cli.output(line + sep);
- } else if (cli.args.length) {
- output_file(cli.args.shift());
- }
- });
-};
-
-if (cli.args.length) {
- output_file(cli.args.shift());
-}
View
16 node_modules/cli/examples/command.js
@@ -1,16 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli');
-
-//The second (optional) argument of cli.parse() is a command list
-//Type `./command.js --help` for usage info
-
-//cli enables auto-completion of commands (similiar to npm), e.g. all of
-//the following are equivalent and result in "Command is: install":
-// $ ./command.js install
-// $ ./command.js inst
-// $ ./command.js i
-
-cli.parse(null, ['install', 'test', 'edit', 'remove', 'uninstall', 'ls']);
-
-console.log('Command is: ' + cli.command);
View
54 node_modules/cli/examples/echo.js
@@ -1,54 +0,0 @@
-#!/usr/bin/env node
-
-/* All of the following commands are equivalent and write `foo\tbar foo` to out.txt
- $ ./echo.js -n -e --output=out.txt "foo\tbar" "foo"
- $ ./echo.js --newline --escape --output "out.txt" "foo\tbar" "foo"
- $ ./echo.js -ne --output=out.txt "foo\tbar" "foo"
- $ ./echo.js -en --output="out.txt" "foo\tbar" "foo"
-*/
-
-var cli = require('cli');
-
-cli.parse({
- newline: ['n', 'Do not output the trailing newline'],
- escape: ['e', 'Enable interpretation of backslash escapes'],
- separator: ['s', 'Separate arguments using this value', 'string', ' '],
- output: [false, 'Write to FILE rather than the console', 'file']
-});
-
-cli.main(function (args, options) {
- var output = '', i, j, l, output_stream;
-
- if (this.argc) {
- if (options.escape) {
- var replace = {'\\n':'\n','\\r':'\r','\\t':'\t','\\e':'\e','\\v':'\v','\\f':'\f','\\c':'\c','\\b':'\b','\\a':'\a','\\\\':'\\'};
- var escape = function (str) {
- string += '';
- for (j in replace) {
- string = string.replace(i, replace[i]);
- }
- return string;
- }
- for (i = 0, l = this.argc; i < l; i++) {
- args[i] = escape(args[i]);
- }
- options.separator = escape(options.separator);
- }
- output += args.join(options.separator);
- }
-
- if (!options.newline) {
- output += '\n';
- }
-
- try {
- if (options.output) {
- output_stream = this.native.fs.createWriteStream(options.output)
- } else {
- output_stream = process.stdout;
- }
- output_stream.write(output);
- } catch (e) {
- this.fatal('Could not write to output stream');
- }
-});
View
6 node_modules/cli/examples/glob.js
@@ -1,6 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli').enable('glob');
-
-//Running `./glob.js *.js` will output a list of .js files in this directory
-console.log(cli.args);
View
20 node_modules/cli/examples/long_desc.js
@@ -1,20 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('../');
-
-//You can (optionally) boost the width of output with:
-//cli.width = 120;
-
-//You can also adjust the width of the options/command definitions
-//cli.option_width = 25;
-
-var long_desc = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s '
- + 'standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make'
- + ' a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, '
- + 'remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing '
- + 'Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions'
- + ' of Lorem Ipsum.';
-
-cli.parse({
- foo: ['f', long_desc]
-});
View
11 node_modules/cli/examples/progress.js
@@ -1,11 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli');
-
-var i = 0, interval = setInterval(function () {
- cli.progress(++i / 100);
- if (i === 100) {
- clearInterval(interval);
- cli.ok('Finished!');
- }
-}, 50);
View
18 node_modules/cli/examples/sort.js
@@ -1,18 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli');
-
-var options = cli.parse({
- numeric: ['n', 'Compare using a numeric sort'],
- reverse: ['r', 'Reverse the results']
-});
-
-cli.withStdinLines(function (lines, newline) {
- lines.sort(!options.numeric ? null : function (a, b) {
- return parseInt(a) > parseInt(b);
- });
- if (options.reverse) {
- lines.reverse();
- }
- this.output(lines.join(newline));
-});
View
9 node_modules/cli/examples/spinner.js
@@ -1,9 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli');
-
-cli.spinner('Working..');
-
-setTimeout(function () {
- cli.spinner('Working.. done!', true); //End the spinner
-}, 3000);
View
27 node_modules/cli/examples/static.coffee
@@ -1,27 +0,0 @@
-#!/usr/bin/env coffee
-
-cli = require 'cli'
-
-cli.enable('daemon','status')
- .setUsage('static.coffee [OPTIONS]')
-
-cli.parse {
- log: ['l', 'Enable logging']
- port: ['p', 'Listen on this port', 'number', 8080]
- serve: [false, 'Serve static files from PATH', 'path', './public']
-}
-
-middleware = []
-
-cli.main (args, options) ->
-
- if options.log
- @debug 'Enabling logging'
- middleware.push require('creationix/log')()
-
- @debug 'Serving files from ' + options.serve
- middleware.push require('creationix/static')('/', options.serve, 'index.html')
-
- server = @createServer(middleware).listen options.port
-
- @ok 'Listening on port ' + options.port
View
25 node_modules/cli/examples/static.js
@@ -1,25 +0,0 @@
-#!/usr/bin/env node
-
-var cli = require('cli').enable('status', 'daemon');
-
-cli.parse({
- log: ['l', 'Enable logging'],
- port: ['p', 'Listen on this port', 'number', 8080],
- serve: [false, 'Serve static files from PATH', 'path', './public']
-});
-
-cli.main(function (args, options) {
- var server, middleware = [];
-
- if (options.log) {
- this.debug('Enabling logging');
- middleware.push(require('creationix/log')());
- }
-
- this.debug('Serving files from ' + options.serve);
- middleware.push(require('creationix/static')('/', options.serve, 'index.html'));
-
- server = this.createServer(middleware).listen(options.port);
-
- this.ok('Listening on port ' + options.port);
-});
View
1  node_modules/cli/index.js
@@ -1 +0,0 @@
-module.exports = require('./cli');
View
23 node_modules/cli/package.json
@@ -1,23 +0,0 @@
-{ "name" : "cli",
- "description" : "A tool for rapidly building command line apps",
- "version" : "0.3.7",
- "homepage" : "http://github.com/chriso/cli",
- "keywords" : ["cli","command line","opts","parseopt","opt","args","console","argsparse","optparse","daemon","autocomplete","command","autocompletion"],
- "author" : "Chris O'Hara <cohara87@gmail.com>",
- "main" : "cli.js",
- "bugs": {
- "mail": "cohara87@gmail.com",
- "web": "http://github.com/chriso/cli/issues"
- },
- "repository": {
- "type": "git",
- "url": "http://github.com/chriso/cli.git"
- },
- "contributors": [
- { "name": "Douglas Meyer", "github": "https://github.com/DouglasMeyer" }
- ],
- "engines": { "node": ">=0.2.5" },
- "licenses": [{
- "type": "MIT"
- }]
-}
View
55 node_modules/request/LICENSE
@@ -1,55 +0,0 @@
-Apache License
-
-Version 2.0, January 2004
-
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-
-"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of this License; and
-
-You must cause any modified files to carry prominent notices stating that You changed the files; and
-
-You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
-
-If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
View
123 node_modules/request/README.md
@@ -1,123 +0,0 @@
-# Request -- Simplified HTTP request method
-
-## Install
-
-<pre>
- npm install request
-</pre>
-
-Or from source:
-
-<pre>
- git clone git://github.com/mikeal/request.git
- cd request
- npm link .
-</pre>
-
-## Super simple to use
-
-Request is designed to be the simplest way possible to make http calls. It support HTTPS and follows redirects by default.
-
-<pre>
- var request = require('request');
- request({uri:'http://www.google.com'}, function (error, response, body) {
- if (!error && response.statusCode == 200) {
- sys.puts(body) // Print the google web page.
- }
- })
-</pre>
-
-#### request(options, callback)
-
-The first argument is an options object. The only required option is uri, all others are optional.
-
-* `uri` || `url` - fully qualified uri or a parsed url object from url.parse()
-* `method` - http method, defaults to GET
-* `headers` - http headers, defaults to {}
-* `body` - entity body for POST and PUT requests. Must be buffer or string.
-* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header.
-* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.
-* `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true.
-* `maxRedirects` - the maximum number of redirects to follow, defaults to 10.
-* `onResponse` - If true the callback will be fired on the "response" event instead of "end". If a function it will be called on "response" and not effect the regular semantics of the main callback on "end".
-* `encoding` - Encoding to be used on response.setEncoding when buffering the response data.
-* `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets.
-* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool.
-* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request
-
-The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body buffer.
-
-Examples:
-
-<pre>
- var request = require('request');
- var rand = Math.floor(Math.random()*100000000).toString();
- request(
- { method: 'PUT'
- , uri: 'http://mikeal.couchone.com/testjs/' + rand
- , multipart:
- [ { 'content-type': 'application/json'
- , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
- }
- , { body: 'I am an attachment' }
- ]
- }
- , function (error, response, body) {
- if(response.statusCode == 201){
- console.log('document saved as: http://mikeal.couchone.com/testjs/'+ rand);
- } else {
- console.log('error: '+ response.statusCode);
- console.log(body);
- }
- }
- )
-</pre>
-
-**Notice for 2.0**
-
-You should no longer recycle mutations in the options object. Because node 0.4.0 has an internal pooling mechanism the preferred way of sharing a connection is using agents which request simplifies with it's new pool API. Therefor options.client and some other mutations have been deprecated.
-
-requestBodyStream and responseBodyStream are also deprecated in favor of a more standard pipe interface documented below.
-
-### stream.pipe(request(options)) and request(options).pipe(stream)
-
-Previous versions of request had no return value and only accepted callbacks and streams for pumping in the options object.
-
-Node has solidified it's Stream interface and request 2.0 is now compliant with that interface.
-
-The return value of request() is now a Request object, which is a valid stream.
-
-As a writable stream it accepts the body of an HTTP request. As a readable stream it emits the data events for the response.
-
-<pre>
- var r = request(
- { url: "http://mysite.com/image.png"
- , method: 'PUT'
- , headers: {'content-type': 'image/png'}
- }
- )
- fs.createReadStream('image.png').pipe(r)
- r.pipe(fs.createWriteStream('pushlog.txt'))
-</pre>
-
-# Convenience methods
-
-### request.defaults(options)
-
-This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.
-
-### request.put
-
-Same as request() but defaults to `method: "PUT"`.
-
-### request.post
-
-Same as request() but defaults to `method: "POST"`.
-
-### request.head
-
-Same as request() but defaults to `method: "HEAD"`.
-
-### request.get
-
-Alias to normal request method for uniformity.
View
150 node_modules/request/cookies.js
@@ -1,150 +0,0 @@
-
-var cookie_str_splitter=/[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g
-
-function stringify (cookie) {
- var str=[cookie.name+"="+cookie.value];
- if(cookie.expiration_date !== Infinity) {
- str.push("expires="+(new Date(cookie.expiration_date)).toGMTString());
- }
- if(cookie.domain) {
- str.push("domain="+cookie.domain);
- }
- if(cookie.path) {
- str.push("path="+cookie.path);
- }
- if(cookie.secure) {
- str.push("secure");
- }
- if(cookie.noscript) {
- str.push("httponly");
- }
- return str.join("; ");
-}
-
-function Jar () {
- this.cookies = []
-}
-Jar.prototype.setCookies = function (cookieString) {
-
-}
-Jar.prototype.getHeader = function (host, path) {
-
-}
-Jar.prototype.getCookies = function (access_info) {
- var matches=[];
- for(var cookie_name in cookies) {
- var cookie=this.getCookie(cookie_name,access_info);
- if (cookie) {
- matches.push(cookie);
- }
- }
- matches.toString=function toString(){return matches.join(":");}
- return matches;
-}
-
-Jar.prototype.getCookie = function (host, path) {
- var cookies_list = self.cookies[cookie_name];
- for(var i=0;i<cookies_list.length;i++) {
- var cookie = cookies_list[i];
- if(cookie.expiration_date <= Date.now()) {
- if(cookies_list.length===0) {
- delete cookies[cookie.name]
- }
- continue;
- }
- if(cookie.matches(access_info)) {
- return cookie;
- }
- }
-}
-Jar.prototype.setCookie = function (){}
-Jar.prototype.parseCookie = function (str) {
- var cookies = str.split(cookie_str_splitter)
- , successful = []
- , self = this
- ;
- cookies.forEach(function (cookie) {
- self.parseCookie(cookie);
- })
-}
-
-Jar.prototype.parseCookie = function (str) {
- var parts = str.split(";")
- , pai r= parts[0].match(/([^=]+)=((?:.|\n)*)/)
- , key = pair[1]
- , value = pair[2]
- , cookie =
- { name: null
- , value: value
- , expiration_date: = Infinity
- , path: '/'
- , domain: null
- , secure: false
- , noscript: false
- }
- ;
-
- cookie.name = key;
- cookie.value = value;
-
- for(var i=1;i<parts.length;i++) {
- var pair = parts[i].match(/([^=]+)=((?:.|\n)*)/)
- , key = pair[1].trim().toLowerCase()
- , value = pair[2]
- ;
- switch(key) {
- case "httponly":
- cookie.noscript = true;
- break;
- case "expires":
- cookie.expiration_date = value
- ? Number(Date.parse(value))
- : Infinity;
- break;
- case "path":
- cookie.path = value
- ? value.trim()
- : "";
- break;
- case "domain":
- cookie.domain = value
- ? value.trim()
- : "";
- break;
- case "secure":
- cookie.secure = true;
- break
- }
- }
-
- if(cookie.name in this.cookies) {
- var cookies_list = this.cookies[cookie.name];
- for(var i=0;i<this.cookies_list.length;i++) {
- var collidable_cookie = cookies_list[i];
- if(collidable_cookie.collidesWith(cookie)) {
- if(remove) {
- cookies_list.splice(i,1);
- if(cookies_list.length===0) {
- delete this.cookies[cookie.name]
- }
- return false;
- }
- else {
- return cookies_list[i]=cookie;
- }
- }
- }
- if(remove) {
- return false;
- }
- cookies_list.push(cookie);
- return cookie;
- }
- else if(remove){
- return false;
- }
- else {
- return this.cookies[cookie.name]=[cookie];
- }
-
-}
View
424 node_modules/request/main.js
@@ -1,424 +0,0 @@
-// Copyright 2010-2011 Mikeal Rogers
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-var http = require('http')
- , https = false
- , tls = false
- , url = require('url')
- , util = require('util')
- , stream = require('stream')
- , qs = require('querystring')
- , mimetypes = require('./mimetypes')
- ;
-
-try {
- https = require('https');
-} catch (e) {}
-
-try {
- tls = require('tls');
-} catch (e) {}
-
-var toBase64 = function(str) {
- return (new Buffer(str || "", "ascii")).toString("base64");
-};
-
-// Hacky fix for pre-0.4.4 https
-if (https && !https.Agent) {
- https.Agent = function (options) {
- http.Agent.call(this, options);
- }
- util.inherits(https.Agent, http.Agent);
-
- https.Agent.prototype._getConnection = function(host, port, cb) {
- var s = tls.connect(port, host, this.options, function() {
- // do other checks here?
- if (cb) cb();
- });
-
- return s;
- };
-}
-
-var isReadStream = function (rs) {
- if (rs.readable && rs.path && rs.mode) {
- return true;
- }
-}
-
-var isUrl = /^https?:/;
-
-var globalPool = {};
-
-var Request = function (options) {
- stream.Stream.call(this);
- this.readable = true;
- this.writable = true;
-
- if (typeof options === 'string') {
- options = {uri:options};
- }
-
- for (i in options) {
- this[i] = options[i];
- }
- if (!this.pool) this.pool = globalPool;
- this.dests = [];
- this.__isRequestRequest = true;
-}
-util.inherits(Request, stream.Stream);
-Request.prototype.getAgent = function (host, port) {
- if (!this.pool[host+':'+port]) {
- this.pool[host+':'+port] = new this.httpModule.Agent({host:host, port:port});
- }
- return this.pool[host+':'+port];
-}
-Request.prototype.request = function () {
- var options = this;
- if (options.url) {
- // People use this property instead all the time so why not just support it.
- options.uri = options.url;
- delete options.url;
- }
-
- if (!options.uri) {
- throw new Error("options.uri is a required argument");
- } else {
- if (typeof options.uri == "string") options.uri = url.parse(options.uri);
- }
- if (options.proxy) {
- if (typeof options.proxy == 'string') options.proxy = url.parse(options.proxy);
- }
-
- options._redirectsFollowed = options._redirectsFollowed || 0;
- options.maxRedirects = (options.maxRedirects !== undefined) ? options.maxRedirects : 10;
- options.followRedirect = (options.followRedirect !== undefined) ? options.followRedirect : true;
-
- options.headers = options.headers || {};
-
- var setHost = false;
- if (!options.headers.host) {
- options.headers.host = options.uri.hostname;
- if (options.uri.port) {
- if ( !(options.uri.port === 80 && options.uri.protocol === 'http:') &&
- !(options.uri.port === 443 && options.uri.protocol === 'https:') )
- options.headers.host += (':'+options.uri.port);
- }
- setHost = true;
- }
-
- if (!options.uri.pathname) {options.uri.pathname = '/';}
- if (!options.uri.port) {
- if (options.uri.protocol == 'http:') {options.uri.port = 80;}
- else if (options.uri.protocol == 'https:') {options.uri.port = 443;}
- }
-
- if (options.bodyStream || options.responseBodyStream) {
- console.error('options.bodyStream and options.responseBodyStream is deprecated. You should now send the request object to stream.pipe()');
- this.pipe(options.responseBodyStream || options.bodyStream)
- }
-
- if (options.proxy) {
- options.port = options.proxy.port;
- options.host = options.proxy.hostname;
- } else {
- options.port = options.uri.port;
- options.host = options.uri.hostname;
- }
-
- if (options.onResponse === true) {
- options.onResponse = options.callback;
- delete options.callback;
- }
-
- var clientErrorHandler = function (error) {
- if (setHost) delete options.headers.host;
- options.emit('error', error);
- };
- if (options.onResponse) options.on('error', function (e) {options.onResponse(e)});
- if (options.callback) options.on('error', function (e) {options.callback(e)});
-
-
- if (options.uri.auth && !options.headers.authorization) {
- options.headers.authorization = "Basic " + toBase64(options.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':'));
- }
- if (options.proxy && options.proxy.auth && !options.headers['proxy-authorization']) {
- options.headers.authorization = "Basic " + toBase64(options.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':'));
- }
-
- options.path = options.uri.href.replace(options.uri.protocol + '//' + options.uri.host, '');
- if (options.path.length === 0) options.path = '/';
-
- if (options.proxy) options.path = (options.uri.protocol + '//' + options.uri.host + options.path);
-
- if (options.json) {
- options.headers['content-type'] = 'application/json';
- options.body = JSON.stringify(options.json);
- } else if (options.multipart) {
- options.body = '';
- options.headers['content-type'] = 'multipart/related;boundary="frontier"';
-
- if (!options.multipart.forEach) throw new Error('Argument error, options.multipart.');
- options.multipart.forEach(function (part) {
- var body = part.body;
- if(!body) throw Error('Body attribute missing in multipart.');
- delete part.body;
- options.body += '--frontier\r\n';
- Object.keys(part).forEach(function(key){
- options.body += key + ': ' + part[key] + '\r\n'
- })
- options.body += '\r\n' + body + '\r\n';
- })
- options.body += '--frontier--'
- }
-
- if (options.body) {
- if (!Buffer.isBuffer(options.body)) {
- options.body = new Buffer(options.body);
- }
- if (options.body.length) {
- options.headers['content-length'] = options.body.length;
- } else {
- throw new Error('Argument error, options.body.');
- }
- }
-
- options.httpModule =
- {"http:":http, "https:":https}[options.proxy ? options.proxy.protocol : options.uri.protocol]
-
- if (!options.httpModule) throw new Error("Invalid protocol");
-
- if (options.pool === false) {
- options.agent = false;
- } else {
- if (options.maxSockets) {
- // Don't use our pooling if node has the refactored client
- options.agent = options.httpModule.globalAgent || options.getAgent(options.host, options.port);
- options.agent.maxSockets = options.maxSockets;
- }
- if (options.pool.maxSockets) {
- // Don't use our pooling if node has the refactored client
- options.agent = options.httpModule.globalAgent || options.getAgent(options.host, options.port);
- options.agent.maxSockets = options.pool.maxSockets;
- }
- }
-
- options.start = function () {
- options._started = true;
-
- options.method = options.method || 'GET';
-
- options.req = options.httpModule.request(options, function (response) {
- options.response = response;
- response.request = options;
- if (setHost) delete options.headers.host;
- if (options.timeout && options.timeoutTimer) clearTimeout(options.timeoutTimer);
-
- if (response.statusCode >= 300 &&
- response.statusCode < 400 &&
- options.followRedirect &&
- options.method !== 'PUT' &&
- options.method !== 'POST' &&
- response.headers.location) {
- if (options._redirectsFollowed >= options.maxRedirects) {
- options.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop."));
- return;
- }
- options._redirectsFollowed += 1;
- if (!isUrl.test(response.headers.location)) {
- response.headers.location = url.resolve(options.uri.href, response.headers.location);
- }
- options.uri = response.headers.location;
- delete options.req;
- delete options.agent;
- delete options._started;
- if (options.headers) {
- delete options.headers.host;
- }
- request(options, options.callback);
- return; // Ignore the rest of the response
- } else {
- options._redirectsFollowed = 0;
- // Be a good stream and emit end when the response is finished.
- // Hack to emit end on close because of a core bug that never fires end
- response.on('close', function () {options.response.emit('end')})
-
- if (options.encoding) {
- if (options.dests.length !== 0) {
- console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.");
- } else {
- response.setEncoding(options.encoding);
- }
- }
-
- options.dests.forEach(function (dest) {
- if (dest.headers) {
- dest.headers['content-type'] = response.headers['content-type'];
- if (response.headers['content-length']) {
- dest.headers['content-length'] = response.headers['content-length'];
- }
- }
- if (dest.setHeader) {
- for (i in response.headers) {
- dest.setHeader(i, response.headers[i])
- }
- dest.statusCode = response.statusCode;
- }
- })
-
- response.on("data", function (chunk) {options.emit("data", chunk)});
- response.on("end", function (chunk) {options.emit("end", chunk)});
- response.on("close", function () {options.emit("close")});
-
- if (options.onResponse) {
- options.onResponse(null, response);
- }
- if (options.callback) {