Added logging, changed some directory structure

This commit is contained in:
2018-01-13 21:33:40 -05:00
parent f079a5f067
commit 8e72ffb917
73656 changed files with 35284 additions and 53718 deletions

3
goTorrentWebUI/node_modules/babel-cli/.npmignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
src
test
node_modules

21
goTorrentWebUI/node_modules/babel-cli/README.md generated vendored Normal file
View File

@@ -0,0 +1,21 @@
# babel-cli
> Babel command line.
In addition, various entry point scripts live in the top-level package at `babel-cli/bin`.
There are some shell-executable utility scripts, `babel-external-helpers.js` and `babel-node.js`, and the main Babel cli script, `babel.js`.
## Install
```sh
npm install --save-dev babel-cli
```
## Usage
```sh
babel script.js
```
For more in depth documentation see: http://babeljs.io/docs/usage/cli/

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
throw new Error("babel-doctor has been removed.");

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
require("../lib/babel-external-helpers");

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
require("../lib/babel-node");

3
goTorrentWebUI/node_modules/babel-cli/bin/babel.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
require("../lib/babel");

1
goTorrentWebUI/node_modules/babel-cli/index.js generated vendored Normal file
View File

@@ -0,0 +1 @@
throw new Error("Use the `babel-core` package not `babel`.");

View File

@@ -0,0 +1,185 @@
"use strict";
var _pathIsAbsolute = require("path-is-absolute");
var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute);
var _commander = require("commander");
var _commander2 = _interopRequireDefault(_commander);
var _module2 = require("module");
var _module3 = _interopRequireDefault(_module2);
var _util = require("util");
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _repl = require("repl");
var _repl2 = _interopRequireDefault(_repl);
var _babelCore = require("babel-core");
var babel = _interopRequireWildcard(_babelCore);
var _vm = require("vm");
var _vm2 = _interopRequireDefault(_vm);
require("babel-polyfill");
var _babelRegister = require("babel-register");
var _babelRegister2 = _interopRequireDefault(_babelRegister);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var program = new _commander2.default.Command("babel-node");
program.option("-e, --eval [script]", "Evaluate script");
program.option("-p, --print [code]", "Evaluate script and print result");
program.option("-o, --only [globs]", "");
program.option("-i, --ignore [globs]", "");
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx]");
program.option("-w, --plugins [string]", "", _babelCore.util.list);
program.option("-b, --presets [string]", "", _babelCore.util.list);
var pkg = require("../package.json");
program.version(pkg.version);
program.usage("[options] [ -e script | script.js ] [arguments]");
program.parse(process.argv);
(0, _babelRegister2.default)({
extensions: program.extensions,
ignore: program.ignore,
only: program.only,
plugins: program.plugins,
presets: program.presets
});
var replPlugin = function replPlugin(_ref) {
var t = _ref.types;
return {
visitor: {
ModuleDeclaration: function ModuleDeclaration(path) {
throw path.buildCodeFrameError("Modules aren't supported in the REPL");
},
VariableDeclaration: function VariableDeclaration(path) {
if (path.node.kind !== "var") {
throw path.buildCodeFrameError("Only `var` variables are supported in the REPL");
}
},
Program: function Program(path) {
if (path.get("body").some(function (child) {
return child.isExpressionStatement();
})) return;
path.pushContainer("body", t.expressionStatement(t.identifier("undefined")));
}
}
};
};
var _eval = function _eval(code, filename) {
code = code.trim();
if (!code) return undefined;
code = babel.transform(code, {
filename: filename,
presets: program.presets,
plugins: (program.plugins || []).concat([replPlugin])
}).code;
return _vm2.default.runInThisContext(code, {
filename: filename
});
};
if (program.eval || program.print) {
var code = program.eval;
if (!code || code === true) code = program.print;
global.__filename = "[eval]";
global.__dirname = process.cwd();
var _module = new _module3.default(global.__filename);
_module.filename = global.__filename;
_module.paths = _module3.default._nodeModulePaths(global.__dirname);
global.exports = _module.exports;
global.module = _module;
global.require = _module.require.bind(_module);
var result = _eval(code, global.__filename);
if (program.print) {
var output = typeof result === "string" ? result : (0, _util.inspect)(result);
process.stdout.write(output + "\n");
}
} else {
if (program.args.length) {
var args = process.argv.slice(2);
var i = 0;
var ignoreNext = false;
args.some(function (arg, i2) {
if (ignoreNext) {
ignoreNext = false;
return;
}
if (arg[0] === "-") {
var parsedArg = program[arg.slice(2)];
if (parsedArg && parsedArg !== true) {
ignoreNext = true;
}
} else {
i = i2;
return true;
}
});
args = args.slice(i);
var filename = args[0];
if (!(0, _pathIsAbsolute2.default)(filename)) args[0] = _path2.default.join(process.cwd(), filename);
process.argv = ["node"].concat(args);
process.execArgv.unshift(__filename);
_module3.default.runMain();
} else {
replStart();
}
}
function replStart() {
_repl2.default.start({
prompt: "> ",
input: process.stdin,
output: process.stdout,
eval: replEval,
useGlobal: true
});
}
function replEval(code, context, filename, callback) {
var err = void 0;
var result = void 0;
try {
if (code[0] === "(" && code[code.length - 1] === ")") {
code = code.slice(1, -1);
}
result = _eval(code, filename);
} catch (e) {
err = e;
}
callback(err, result);
}

View File

@@ -0,0 +1,17 @@
"use strict";
var _commander = require("commander");
var _commander2 = _interopRequireDefault(_commander);
var _babelCore = require("babel-core");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_commander2.default.option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", _babelCore.util.list);
_commander2.default.option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");
_commander2.default.usage("[options]");
_commander2.default.parse(process.argv);
console.log((0, _babelCore.buildExternalHelpers)(_commander2.default.whitelist, _commander2.default.outputType));

View File

@@ -0,0 +1,84 @@
"use strict";
var getV8Flags = require("v8flags");
var path = require("path");
var args = [path.join(__dirname, "_babel-node")];
var babelArgs = process.argv.slice(2);
var userArgs = void 0;
var argSeparator = babelArgs.indexOf("--");
if (argSeparator > -1) {
userArgs = babelArgs.slice(argSeparator);
babelArgs = babelArgs.slice(0, argSeparator);
}
function getNormalizedV8Flag(arg) {
var matches = arg.match(/--(.+)/);
if (matches) {
return "--" + matches[1].replace(/-/g, "_");
}
return arg;
}
getV8Flags(function (err, v8Flags) {
babelArgs.forEach(function (arg) {
var flag = arg.split("=")[0];
switch (flag) {
case "-d":
args.unshift("--debug");
break;
case "debug":
case "--debug":
case "--debug-brk":
case "--inspect":
case "--inspect-brk":
args.unshift(arg);
break;
case "-gc":
args.unshift("--expose-gc");
break;
case "--nolazy":
args.unshift(flag);
break;
default:
if (v8Flags.indexOf(getNormalizedV8Flag(flag)) >= 0 || arg.indexOf("--trace") === 0) {
args.unshift(arg);
} else {
args.push(arg);
}
break;
}
});
if (argSeparator > -1) {
args = args.concat(userArgs);
}
try {
var kexec = require("kexec");
kexec(process.argv[0], args);
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
var child_process = require("child_process");
var proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" });
proc.on("exit", function (code, signal) {
process.on("exit", function () {
if (signal) {
process.kill(process.pid, signal);
} else {
process.exit(code);
}
});
});
}
});

97
goTorrentWebUI/node_modules/babel-cli/lib/babel/dir.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
"use strict";
var _stringify = require("babel-runtime/core-js/json/stringify");
var _stringify2 = _interopRequireDefault(_stringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var outputFileSync = require("output-file-sync");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
module.exports = function (commander, filenames) {
function write(src, relative) {
relative = relative.replace(/\.(\w*?)$/, "") + ".js";
var dest = path.join(commander.outDir, relative);
var data = util.compile(src, {
sourceFileName: slash(path.relative(dest + "/..", src)),
sourceMapTarget: path.basename(relative)
});
if (!commander.copyFiles && data.ignored) return;
if (data.map && commander.sourceMaps && commander.sourceMaps !== "inline") {
var mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc);
outputFileSync(mapLoc, (0, _stringify2.default)(data.map));
}
outputFileSync(dest, data.code);
util.chmod(src, dest);
util.log(src + " -> " + dest);
}
function handleFile(src, filename) {
if (util.shouldIgnore(src)) return;
if (util.canCompile(filename, commander.extensions)) {
write(src, filename);
} else if (commander.copyFiles) {
var dest = path.join(commander.outDir, filename);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
}
function handle(filename) {
if (!fs.existsSync(filename)) return;
var stat = fs.statSync(filename);
if (stat.isDirectory(filename)) {
var dirname = filename;
util.readdir(dirname).forEach(function (filename) {
var src = path.join(dirname, filename);
handleFile(src, filename);
});
} else {
write(filename, filename);
}
}
if (!commander.skipInitialBuild) {
filenames.forEach(handle);
}
if (commander.watch) {
var chokidar = util.requireChokidar();
filenames.forEach(function (dirname) {
var watcher = chokidar.watch(dirname, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 50,
pollInterval: 10
}
});
["add", "change"].forEach(function (type) {
watcher.on(type, function (filename) {
var relative = path.relative(dirname, filename) || filename;
try {
handleFile(filename, relative);
} catch (err) {
console.error(err.stack);
}
});
});
});
}
};

188
goTorrentWebUI/node_modules/babel-cli/lib/babel/file.js generated vendored Normal file
View File

@@ -0,0 +1,188 @@
"use strict";
var _stringify = require("babel-runtime/core-js/json/stringify");
var _stringify2 = _interopRequireDefault(_stringify);
var _set = require("babel-runtime/core-js/set");
var _set2 = _interopRequireDefault(_set);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var convertSourceMap = require("convert-source-map");
var sourceMap = require("source-map");
var slash = require("slash");
var path = require("path");
var util = require("./util");
var fs = require("fs");
module.exports = function (commander, filenames, opts) {
if (commander.sourceMaps === "inline") {
opts.sourceMaps = true;
}
var results = [];
var buildResult = function buildResult() {
var map = new sourceMap.SourceMapGenerator({
file: path.basename(commander.outFile || "") || "stdout",
sourceRoot: opts.sourceRoot
});
var code = "";
var offset = 0;
results.forEach(function (result) {
code += result.code + "\n";
if (result.map) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
var sources = new _set2.default();
consumer.eachMapping(function (mapping) {
if (mapping.source != null) sources.add(mapping.source);
map.addMapping({
generated: {
line: mapping.generatedLine + offset,
column: mapping.generatedColumn
},
source: mapping.source,
original: mapping.source == null ? null : {
line: mapping.originalLine,
column: mapping.originalColumn
}
});
});
sources.forEach(function (source) {
var content = consumer.sourceContentFor(source, true);
if (content !== null) {
map.setSourceContent(source, content);
}
});
offset = code.split("\n").length - 1;
}
});
if (commander.sourceMaps === "inline" || !commander.outFile && commander.sourceMaps) {
code += "\n" + convertSourceMap.fromObject(map).toComment();
}
return {
map: map,
code: code
};
};
var output = function output() {
var result = buildResult();
if (commander.outFile) {
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
var mapLoc = commander.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
fs.writeFileSync(mapLoc, (0, _stringify2.default)(result.map));
}
fs.writeFileSync(commander.outFile, result.code);
} else {
process.stdout.write(result.code + "\n");
}
};
var stdin = function stdin() {
var code = "";
process.stdin.setEncoding("utf8");
process.stdin.on("readable", function () {
var chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
process.stdin.on("end", function () {
results.push(util.transform(commander.filename, code, {
sourceFileName: "stdin"
}));
output();
});
};
var walk = function walk() {
var _filenames = [];
results = [];
filenames.forEach(function (filename) {
if (!fs.existsSync(filename)) return;
var stat = fs.statSync(filename);
if (stat.isDirectory()) {
var dirname = filename;
util.readdirFilter(filename).forEach(function (filename) {
_filenames.push(path.join(dirname, filename));
});
} else {
_filenames.push(filename);
}
});
_filenames.forEach(function (filename) {
if (util.shouldIgnore(filename)) return;
var sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(path.dirname(commander.outFile), sourceFilename);
}
sourceFilename = slash(sourceFilename);
var data = util.compile(filename, {
sourceFileName: sourceFilename
});
if (data.ignored) return;
results.push(data);
});
output();
};
var files = function files() {
if (!commander.skipInitialBuild) {
walk();
}
if (commander.watch) {
var chokidar = util.requireChokidar();
chokidar.watch(filenames, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 50,
pollInterval: 10
}
}).on("all", function (type, filename) {
if (util.shouldIgnore(filename) || !util.canCompile(filename, commander.extensions)) return;
if (type === "add" || type === "change") {
util.log(type + " " + filename);
try {
walk();
} catch (err) {
console.error(err.stack);
}
}
});
}
};
if (filenames.length) {
files();
} else {
stdin();
}
};

View File

@@ -0,0 +1,129 @@
#!/usr/bin/env node
"use strict";
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fs = require("fs");
var commander = require("commander");
var kebabCase = require("lodash/kebabCase");
var options = require("babel-core").options;
var util = require("babel-core").util;
var uniq = require("lodash/uniq");
var glob = require("glob");
(0, _keys2.default)(options).forEach(function (key) {
var option = options[key];
if (option.hidden) return;
var arg = kebabCase(key);
if (option.type !== "boolean") {
arg += " [" + (option.type || "string") + "]";
}
if (option.type === "boolean" && option.default === true) {
arg = "no-" + arg;
}
arg = "--" + arg;
if (option.shorthand) {
arg = "-" + option.shorthand + ", " + arg;
}
var desc = [];
if (option.deprecated) desc.push("[DEPRECATED] " + option.deprecated);
if (option.description) desc.push(option.description);
commander.option(arg, desc.join(" "));
});
commander.option("-x, --extensions [extensions]", "List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx]");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("--skip-initial-build", "Do not compile files before watching");
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
commander.option("-q, --quiet", "Don't log anything");
var pkg = require("../../package.json");
commander.version(pkg.version + " (babel-core " + require("babel-core").version + ")");
commander.usage("[options] <files ...>");
commander.parse(process.argv);
if (commander.extensions) {
commander.extensions = util.arrayify(commander.extensions);
}
var errors = [];
var filenames = commander.args.reduce(function (globbed, input) {
var files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
filenames = uniq(filenames);
filenames.forEach(function (filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (commander.skipInitialBuild && !commander.watch) {
errors.push("--skip-initial-build requires --watch");
}
if (errors.length) {
console.error(errors.join(". "));
process.exit(2);
}
var opts = exports.opts = {};
(0, _keys2.default)(options).forEach(function (key) {
var opt = options[key];
if (commander[key] !== undefined && commander[key] !== opt.default) {
opts[key] = commander[key];
}
});
opts.ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.only) {
opts.only = util.arrayify(opts.only, util.regexify);
}
var fn = void 0;
if (commander.outDir) {
fn = require("./dir");
} else {
fn = require("./file");
}
fn(commander, filenames, exports.opts);

View File

@@ -0,0 +1,90 @@
"use strict";
exports.__esModule = true;
exports.chmod = chmod;
exports.readdirFilter = readdirFilter;
exports.shouldIgnore = shouldIgnore;
exports.addSourceMappingUrl = addSourceMappingUrl;
exports.log = log;
exports.transform = transform;
exports.compile = compile;
exports.requireChokidar = requireChokidar;
var commander = require("commander");
var defaults = require("lodash/defaults");
var readdir = require("fs-readdir-recursive");
var index = require("./index");
var babel = require("babel-core");
var util = require("babel-core").util;
var path = require("path");
var fs = require("fs");
function chmod(src, dest) {
fs.chmodSync(dest, fs.statSync(src).mode);
}
function readdirFilter(filename) {
return readdir(filename).filter(function (filename) {
return util.canCompile(filename);
});
}
exports.readdir = readdir;
var canCompile = exports.canCompile = util.canCompile;
function shouldIgnore(loc) {
return util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
}
function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}
function log(msg) {
if (!commander.quiet) console.log(msg);
}
function transform(filename, code, opts) {
opts = defaults(opts || {}, index.opts);
opts.filename = filename;
var result = babel.transform(code, opts);
result.filename = filename;
result.actual = code;
return result;
}
function compile(filename, opts) {
try {
var code = fs.readFileSync(filename, "utf8");
return transform(filename, code, opts);
} catch (err) {
if (commander.watch) {
console.error(toErrorStack(err));
return { ignored: true };
} else {
throw err;
}
}
}
function toErrorStack(err) {
if (err._babel && err instanceof SyntaxError) {
return err.name + ": " + err.message + "\n" + err.codeFrame;
} else {
return err.stack;
}
}
process.on("uncaughtException", function (err) {
console.error(toErrorStack(err));
process.exit(1);
});
function requireChokidar() {
try {
return require("chokidar");
} catch (err) {
console.error("The optional dependency chokidar failed to install and is required for " + "--watch. Chokidar is likely not supported on your platform.");
throw err;
}
}

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../babylon/bin/babylon.js" "$@"
ret=$?
else
node "$basedir/../babylon/bin/babylon.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\babylon\bin\babylon.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\babylon\bin\babylon.js" %*
)

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../jsesc/bin/jsesc" "$@"
ret=$?
else
node "$basedir/../jsesc/bin/jsesc" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\jsesc\bin\jsesc" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\jsesc\bin\jsesc" %*
)

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../json5/lib/cli.js" "$@"
ret=$?
else
node "$basedir/../json5/lib/cli.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\json5\lib\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\json5\lib\cli.js" %*
)

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../loose-envify/cli.js" "$@"
ret=$?
else
node "$basedir/../loose-envify/cli.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\loose-envify\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\loose-envify\cli.js" %*
)

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@"
ret=$?
else
node "$basedir/../mkdirp/bin/cmd.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\mkdirp\bin\cmd.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\mkdirp\bin\cmd.js" %*
)

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../user-home/cli.js" "$@"
ret=$?
else
node "$basedir/../user-home/cli.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\user-home\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\user-home\cli.js" %*
)

View File

@@ -0,0 +1,4 @@
'use strict';
module.exports = function () {
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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 File

@@ -0,0 +1,113 @@
{
"_args": [
[
"ansi-regex@2.1.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "ansi-regex@2.1.1",
"_id": "ansi-regex@2.1.1",
"_inBundle": false,
"_integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
"_location": "/babel-cli/ansi-regex",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "ansi-regex@2.1.1",
"name": "ansi-regex",
"escapedName": "ansi-regex",
"rawSpec": "2.1.1",
"saveSpec": null,
"fetchSpec": "2.1.1"
},
"_requiredBy": [
"/babel-cli/has-ansi",
"/babel-cli/strip-ansi"
],
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
"_spec": "2.1.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "0.17.0",
"xo": "0.16.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/ansi-regex#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"license": "MIT",
"maintainers": [
{
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
{
"name": "Joshua Appelman",
"email": "jappelman@xebia.com",
"url": "jbnicolai.com"
},
{
"name": "JD Ballard",
"email": "i.am.qix@gmail.com",
"url": "github.com/qix-"
}
],
"name": "ansi-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava --verbose",
"view-supported": "node fixtures/view-codes.js"
},
"version": "2.1.1",
"xo": {
"rules": {
"guard-for-in": 0,
"no-loop-func": 0
}
}
}

View File

@@ -0,0 +1,39 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install --save ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001b[4mcake\u001b[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001b[4mcake\u001b[0m'.match(ansiRegex());
//=> ['\u001b[4m', '\u001b[0m']
```
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,65 @@
'use strict';
function assembleStyles () {
var styles = {
modifiers: {
reset: [0, 0],
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
colors: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39]
},
bgColors: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
}
};
// fix humans
styles.colors.grey = styles.colors.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = group[styleName] = {
open: '\u001b[' + style[0] + 'm',
close: '\u001b[' + style[1] + 'm'
};
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
return styles;
}
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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 File

@@ -0,0 +1,94 @@
{
"_args": [
[
"ansi-styles@2.2.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "ansi-styles@2.2.1",
"_id": "ansi-styles@2.2.1",
"_inBundle": false,
"_integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=",
"_location": "/babel-cli/ansi-styles",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "ansi-styles@2.2.1",
"name": "ansi-styles",
"escapedName": "ansi-styles",
"rawSpec": "2.2.1",
"saveSpec": null,
"fetchSpec": "2.2.1"
},
"_requiredBy": [
"/babel-cli/chalk"
],
"_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
"_spec": "2.2.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-styles/issues"
},
"description": "ANSI escape codes for styling strings in the terminal",
"devDependencies": {
"mocha": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/ansi-styles#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"license": "MIT",
"maintainers": [
{
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
{
"name": "Joshua Appelman",
"email": "jappelman@xebia.com",
"url": "jbnicolai.com"
}
],
"name": "ansi-styles",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-styles.git"
},
"scripts": {
"test": "mocha"
},
"version": "2.2.1"
}

View File

@@ -0,0 +1,86 @@
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
![](screenshot.png)
## Install
```
$ npm install --save ansi-styles
```
## Usage
```js
var ansi = require('ansi-styles');
console.log(ansi.green.open + 'Hello world!' + ansi.green.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## Advanced usage
By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.
- `ansi.modifiers`
- `ansi.colors`
- `ansi.bgColors`
###### Example
```js
console.log(ansi.colors.green.open);
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) 2014 Elan Shanker
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,98 @@
anymatch [![Build Status](https://travis-ci.org/es128/anymatch.svg?branch=master)](https://travis-ci.org/es128/anymatch) [![Coverage Status](https://img.shields.io/coveralls/es128/anymatch.svg?branch=master)](https://coveralls.io/r/es128/anymatch?branch=master)
======
Javascript module to match a string against a regular expression, glob, string,
or function that takes the string as an argument and returns a truthy or falsy
value. The matcher can also be an array of any or all of these. Useful for
allowing a very flexible user-defined config to define things like file paths.
[![NPM](https://nodei.co/npm/anymatch.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/anymatch/)
[![NPM](https://nodei.co/npm-dl/anymatch.png?height=3&months=9)](https://nodei.co/npm-dl/anymatch/)
Usage
-----
```sh
npm install anymatch --save
```
#### anymatch (matchers, testString, [returnIndex], [startIndex], [endIndex])
* __matchers__: (_Array|String|RegExp|Function_)
String to be directly matched, string with glob patterns, regular expression
test, function that takes the testString as an argument and returns a truthy
value if it should be matched, or an array of any number and mix of these types.
* __testString__: (_String|Array_) The string to test against the matchers. If
passed as an array, the first element of the array will be used as the
`testString` for non-function matchers, while the entire array will be applied
as the arguments for function matchers.
* __returnIndex__: (_Boolean [optional]_) If true, return the array index of
the first matcher that that testString matched, or -1 if no match, instead of a
boolean result.
* __startIndex, endIndex__: (_Integer [optional]_) Can be used to define a
subset out of the array of provided matchers to test against. Can be useful
with bound matcher functions (see below). When used with `returnIndex = true`
preserves original indexing. Behaves the same as `Array.prototype.slice` (i.e.
includes array members up to, but not including endIndex).
```js
var anymatch = require('anymatch');
var matchers = [
'path/to/file.js',
'path/anyjs/**/*.js',
/foo\.js$/,
function (string) {
return string.indexOf('bar') !== -1 && string.length > 10
}
];
anymatch(matchers, 'path/to/file.js'); // true
anymatch(matchers, 'path/anyjs/baz.js'); // true
anymatch(matchers, 'path/to/foo.js'); // true
anymatch(matchers, 'path/to/bar.js'); // true
anymatch(matchers, 'bar.js'); // false
// returnIndex = true
anymatch(matchers, 'foo.js', true); // 2
anymatch(matchers, 'path/anyjs/foo.js', true); // 1
// skip matchers
anymatch(matchers, 'path/to/file.js', false, 1); // false
anymatch(matchers, 'path/anyjs/foo.js', true, 2, 3); // 2
anymatch(matchers, 'path/to/bar.js', true, 0, 3); // -1
// using globs to match directories and their children
anymatch('node_modules', 'node_modules'); // true
anymatch('node_modules', 'node_modules/somelib/index.js'); // false
anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true
anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false
anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true
```
#### anymatch (matchers)
You can also pass in only your matcher(s) to get a curried function that has
already been bound to the provided matching criteria. This can be used as an
`Array.prototype.filter` callback.
```js
var matcher = anymatch(matchers);
matcher('path/to/file.js'); // true
matcher('path/anyjs/baz.js', true); // 1
matcher('path/anyjs/baz.js', true, 2); // -1
['foo.js', 'bar.js'].filter(matcher); // ['foo.js']
```
Change Log
----------
[See release notes page on GitHub](https://github.com/es128/anymatch/releases)
NOTE: As of v1.2.0, anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch)
for glob pattern matching. The glob matching behavior should be functionally
equivalent to the commonly used [minimatch](https://github.com/isaacs/minimatch)
library (aside from some fixed bugs and greater performance), so a major
version bump wasn't merited. Issues with glob pattern matching should be
reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues).
License
-------
[ISC](https://raw.github.com/es128/anymatch/master/LICENSE)

View File

@@ -0,0 +1,67 @@
'use strict';
var micromatch = require('micromatch');
var normalize = require('normalize-path');
var path = require('path'); // required for tests.
var arrify = function(a) { return a == null ? [] : (Array.isArray(a) ? a : [a]); };
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
criteria = arrify(criteria);
value = arrify(value);
if (arguments.length === 1) {
return anymatch.bind(null, criteria.map(function(criterion) {
return typeof criterion === 'string' && criterion[0] !== '!' ?
micromatch.matcher(criterion) : criterion;
}));
}
startIndex = startIndex || 0;
var string = value[0];
var altString, altValue;
var matched = false;
var matchIndex = -1;
function testCriteria(criterion, index) {
var result;
switch (Object.prototype.toString.call(criterion)) {
case '[object String]':
result = string === criterion || altString && altString === criterion;
result = result || micromatch.isMatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string) || altString && criterion.test(altString);
break;
case '[object Function]':
result = criterion.apply(null, value);
result = result || altValue && criterion.apply(null, altValue);
break;
default:
result = false;
}
if (result) {
matchIndex = index + startIndex;
}
return result;
}
var crit = criteria;
var negGlobs = crit.reduce(function(arr, criterion, index) {
if (typeof criterion === 'string' && criterion[0] === '!') {
if (crit === criteria) {
// make a copy before modifying
crit = crit.slice();
}
crit[index] = null;
arr.push(criterion.substr(1));
}
return arr;
}, []);
if (!negGlobs.length || !micromatch.any(string, negGlobs)) {
if (path.sep === '\\' && typeof string === 'string') {
altString = normalize(string);
altString = altString === string ? null : altString;
if (altString) altValue = [altString].concat(value.slice(1));
}
matched = crit.slice(startIndex, endIndex).some(testCriteria);
}
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;

View File

@@ -0,0 +1,77 @@
{
"_args": [
[
"anymatch@1.3.2",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "anymatch@1.3.2",
"_id": "anymatch@1.3.2",
"_inBundle": false,
"_integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==",
"_location": "/babel-cli/anymatch",
"_optional": true,
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "anymatch@1.3.2",
"name": "anymatch",
"escapedName": "anymatch",
"rawSpec": "1.3.2",
"saveSpec": null,
"fetchSpec": "1.3.2"
},
"_requiredBy": [
"/babel-cli/chokidar"
],
"_resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz",
"_spec": "1.3.2",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Elan Shanker",
"url": "http://github.com/es128"
},
"bugs": {
"url": "https://github.com/es128/anymatch/issues"
},
"dependencies": {
"micromatch": "^2.1.5",
"normalize-path": "^2.0.0"
},
"description": "Matches strings against configurable strings, globs, regular expressions, and/or functions",
"devDependencies": {
"coveralls": "^2.11.2",
"istanbul": "^0.3.13",
"mocha": "^2.2.4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/es128/anymatch",
"keywords": [
"match",
"any",
"string",
"file",
"fs",
"list",
"glob",
"regex",
"regexp",
"regular",
"expression",
"function"
],
"license": "ISC",
"name": "anymatch",
"repository": {
"type": "git",
"url": "git+https://github.com/es128/anymatch.git"
},
"scripts": {
"test": "istanbul cover _mocha && cat ./coverage/lcov.info | coveralls"
},
"version": "1.3.2"
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2015, Jon Schlinkert.
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 File

@@ -0,0 +1,74 @@
# arr-diff [![NPM version](https://img.shields.io/npm/v/arr-diff.svg)](https://www.npmjs.com/package/arr-diff) [![Build Status](https://img.shields.io/travis/jonschlinkert/base.svg)](https://travis-ci.org/jonschlinkert/base)
> Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.
## Install
Install with [npm](https://www.npmjs.com/)
```sh
$ npm i arr-diff --save
```
Install with [bower](http://bower.io/)
```sh
$ bower install arr-diff --save
```
## API
### [diff](index.js#L33)
Return the difference between the first array and additional arrays.
**Params**
* `a` **{Array}**
* `b` **{Array}**
* `returns` **{Array}**
**Example**
```js
var diff = require('arr-diff');
var a = ['a', 'b', 'c', 'd'];
var b = ['b', 'c'];
console.log(diff(a, b))
//=> ['a', 'd']
```
## Related projects
* [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten)
* [array-filter](https://www.npmjs.com/package/array-filter): Array#filter for older browsers. | [homepage](https://github.com/juliangruber/array-filter)
* [array-intersection](https://www.npmjs.com/package/array-intersection): Return an array with the unique values present in _all_ given arrays using strict equality… [more](https://www.npmjs.com/package/array-intersection) | [homepage](https://github.com/jonschlinkert/array-intersection)
## Running tests
Install dev dependencies:
```sh
$ npm i -d && npm test
```
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/arr-diff/issues/new).
## Author
**Jon Schlinkert**
+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
## License
Copyright © 2015 [Jon Schlinkert](https://github.com/jonschlinkert)
Released under the MIT license.
***
_This file was generated by [verb](https://github.com/verbose/verb) on Sat Dec 05 2015 23:24:53 GMT-0500 (EST)._

View File

@@ -0,0 +1,58 @@
/*!
* arr-diff <https://github.com/jonschlinkert/arr-diff>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT License
*/
'use strict';
var flatten = require('arr-flatten');
var slice = [].slice;
/**
* Return the difference between the first array and
* additional arrays.
*
* ```js
* var diff = require('{%= name %}');
*
* var a = ['a', 'b', 'c', 'd'];
* var b = ['b', 'c'];
*
* console.log(diff(a, b))
* //=> ['a', 'd']
* ```
*
* @param {Array} `a`
* @param {Array} `b`
* @return {Array}
* @api public
*/
function diff(arr, arrays) {
var argsLen = arguments.length;
var len = arr.length, i = -1;
var res = [], arrays;
if (argsLen === 1) {
return arr;
}
if (argsLen > 2) {
arrays = flatten(slice.call(arguments, 1));
}
while (++i < len) {
if (!~arrays.indexOf(arr[i])) {
res.push(arr[i]);
}
}
return res;
}
/**
* Expose `diff`
*/
module.exports = diff;

View File

@@ -0,0 +1,85 @@
{
"_args": [
[
"arr-diff@2.0.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "arr-diff@2.0.0",
"_id": "arr-diff@2.0.0",
"_inBundle": false,
"_integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=",
"_location": "/babel-cli/arr-diff",
"_optional": true,
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "arr-diff@2.0.0",
"name": "arr-diff",
"escapedName": "arr-diff",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"/babel-cli/micromatch"
],
"_resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz",
"_spec": "2.0.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/arr-diff/issues"
},
"dependencies": {
"arr-flatten": "^1.0.1"
},
"description": "Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.",
"devDependencies": {
"array-differ": "^1.0.0",
"array-slice": "^0.2.3",
"benchmarked": "^0.1.4",
"chalk": "^1.1.1",
"mocha": "*",
"should": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/arr-diff",
"keywords": [
"arr",
"array",
"diff",
"differ",
"difference"
],
"license": "MIT",
"main": "index.js",
"name": "arr-diff",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/arr-diff.git"
},
"scripts": {
"test": "mocha"
},
"verb": {
"related": {
"list": [
"arr-flatten",
"array-filter",
"array-intersection"
]
}
},
"version": "2.0.0"
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert.
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 File

@@ -0,0 +1,86 @@
# arr-flatten [![NPM version](https://img.shields.io/npm/v/arr-flatten.svg?style=flat)](https://www.npmjs.com/package/arr-flatten) [![NPM monthly downloads](https://img.shields.io/npm/dm/arr-flatten.svg?style=flat)](https://npmjs.org/package/arr-flatten) [![NPM total downloads](https://img.shields.io/npm/dt/arr-flatten.svg?style=flat)](https://npmjs.org/package/arr-flatten) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/arr-flatten.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/arr-flatten) [![Windows Build Status](https://img.shields.io/appveyor/ci/jonschlinkert/arr-flatten.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/jonschlinkert/arr-flatten)
> Recursively flatten an array or arrays.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save arr-flatten
```
## Install
Install with [bower](https://bower.io/)
```sh
$ bower install arr-flatten --save
```
## Usage
```js
var flatten = require('arr-flatten');
flatten(['a', ['b', ['c']], 'd', ['e']]);
//=> ['a', 'b', 'c', 'd', 'e']
```
## Why another flatten utility?
I wanted the fastest implementation I could find, with implementation choices that should work for 95% of use cases, but no cruft to cover the other 5%.
## About
### Related projects
* [arr-filter](https://www.npmjs.com/package/arr-filter): Faster alternative to javascript's native filter method. | [homepage](https://github.com/jonschlinkert/arr-filter "Faster alternative to javascript's native filter method.")
* [arr-union](https://www.npmjs.com/package/arr-union): Combines a list of arrays, returning a single array with unique values, using strict equality… [more](https://github.com/jonschlinkert/arr-union) | [homepage](https://github.com/jonschlinkert/arr-union "Combines a list of arrays, returning a single array with unique values, using strict equality for comparisons.")
* [array-each](https://www.npmjs.com/package/array-each): Loop over each item in an array and call the given function on every element. | [homepage](https://github.com/jonschlinkert/array-each "Loop over each item in an array and call the given function on every element.")
* [array-unique](https://www.npmjs.com/package/array-unique): Remove duplicate values from an array. Fastest ES5 implementation. | [homepage](https://github.com/jonschlinkert/array-unique "Remove duplicate values from an array. Fastest ES5 implementation.")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 20 | [jonschlinkert](https://github.com/jonschlinkert) |
| 1 | [lukeed](https://github.com/lukeed) |
### Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 05, 2017._

View File

@@ -0,0 +1,22 @@
/*!
* arr-flatten <https://github.com/jonschlinkert/arr-flatten>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
module.exports = function (arr) {
return flat(arr, []);
};
function flat(arr, res) {
var i = 0, cur;
var len = arr.length;
for (; i < len; i++) {
cur = arr[i];
Array.isArray(cur) ? flat(cur, res) : res.push(cur);
}
return res;
}

View File

@@ -0,0 +1,118 @@
{
"_args": [
[
"arr-flatten@1.1.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "arr-flatten@1.1.0",
"_id": "arr-flatten@1.1.0",
"_inBundle": false,
"_integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==",
"_location": "/babel-cli/arr-flatten",
"_optional": true,
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "arr-flatten@1.1.0",
"name": "arr-flatten",
"escapedName": "arr-flatten",
"rawSpec": "1.1.0",
"saveSpec": null,
"fetchSpec": "1.1.0"
},
"_requiredBy": [
"/babel-cli/arr-diff"
],
"_resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz",
"_spec": "1.1.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/arr-flatten/issues"
},
"contributors": [
{
"name": "Jon Schlinkert",
"url": "http://twitter.com/jonschlinkert"
},
{
"name": "Luke Edwards",
"url": "https://lukeed.com"
}
],
"description": "Recursively flatten an array or arrays.",
"devDependencies": {
"ansi-bold": "^0.1.1",
"array-flatten": "^2.1.1",
"array-slice": "^1.0.0",
"benchmarked": "^1.0.0",
"compute-flatten": "^1.0.0",
"flatit": "^1.1.1",
"flatten": "^1.0.2",
"flatten-array": "^1.0.0",
"glob": "^7.1.1",
"gulp-format-md": "^0.1.12",
"just-flatten-it": "^1.1.23",
"lodash.flattendeep": "^4.4.0",
"m_flattened": "^1.0.1",
"mocha": "^3.2.0",
"utils-flatten": "^1.0.0",
"write": "^0.3.3"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/arr-flatten",
"keywords": [
"arr",
"array",
"elements",
"flat",
"flatten",
"nested",
"recurse",
"recursive",
"recursively"
],
"license": "MIT",
"main": "index.js",
"name": "arr-flatten",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/arr-flatten.git"
},
"scripts": {
"test": "mocha"
},
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"arr-filter",
"arr-union",
"array-each",
"array-unique"
]
},
"lint": {
"reflinks": true
}
},
"version": "1.1.0"
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2015, Jon Schlinkert.
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 File

@@ -0,0 +1,51 @@
# array-unique [![NPM version](https://badge.fury.io/js/array-unique.svg)](http://badge.fury.io/js/array-unique) [![Build Status](https://travis-ci.org/jonschlinkert/array-unique.svg)](https://travis-ci.org/jonschlinkert/array-unique)
> Return an array free of duplicate values. Fastest ES5 implementation.
## Install with [npm](npmjs.org)
```bash
npm i array-unique --save
```
## Usage
```js
var unique = require('array-unique');
unique(['a', 'b', 'c', 'c']);
//=> ['a', 'b', 'c']
```
## Related
* [arr-diff](https://github.com/jonschlinkert/arr-diff): Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.
* [arr-union](https://github.com/jonschlinkert/arr-union): Returns an array of unique values using strict equality for comparisons.
* [arr-flatten](https://github.com/jonschlinkert/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten.
* [arr-reduce](https://github.com/jonschlinkert/arr-reduce): Fast array reduce that also loops over sparse elements.
* [arr-map](https://github.com/jonschlinkert/arr-map): Faster, node.js focused alternative to JavaScript's native array map.
* [arr-pluck](https://github.com/jonschlinkert/arr-pluck): Retrieves the value of a specified property from all elements in the collection.
## Run tests
Install dev dependencies.
```bash
npm i -d && npm test
```
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/array-unique/issues)
## Author
**Jon Schlinkert**
+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
## License
Copyright (c) 2015 Jon Schlinkert
Released under the MIT license
***
_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on March 24, 2015._

View File

@@ -0,0 +1,28 @@
/*!
* array-unique <https://github.com/jonschlinkert/array-unique>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
module.exports = function unique(arr) {
if (!Array.isArray(arr)) {
throw new TypeError('array-unique expects an array.');
}
var len = arr.length;
var i = -1;
while (i++ < len) {
var j = i + 1;
for (; j < arr.length; ++j) {
if (arr[i] === arr[j]) {
arr.splice(j--, 1);
}
}
}
return arr;
};

View File

@@ -0,0 +1,67 @@
{
"_args": [
[
"array-unique@0.2.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "array-unique@0.2.1",
"_id": "array-unique@0.2.1",
"_inBundle": false,
"_integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=",
"_location": "/babel-cli/array-unique",
"_optional": true,
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "array-unique@0.2.1",
"name": "array-unique",
"escapedName": "array-unique",
"rawSpec": "0.2.1",
"saveSpec": null,
"fetchSpec": "0.2.1"
},
"_requiredBy": [
"/babel-cli/micromatch"
],
"_resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz",
"_spec": "0.2.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/array-unique/issues"
},
"description": "Return an array free of duplicate values. Fastest ES5 implementation.",
"devDependencies": {
"array-uniq": "^1.0.2",
"benchmarked": "^0.1.3",
"mocha": "*",
"should": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/array-unique",
"license": {
"type": "MIT",
"url": "https://github.com/jonschlinkert/array-unique/blob/master/LICENSE"
},
"main": "index.js",
"name": "array-unique",
"repository": {
"type": "git",
"url": "git://github.com/jonschlinkert/array-unique.git"
},
"scripts": {
"test": "mocha"
},
"version": "0.2.1"
}

View File

@@ -0,0 +1,3 @@
bower.json
component.json
CHANGELOG.md

View File

@@ -0,0 +1,23 @@
# async-each 1.0.0 (26 November 2015)
* Bumped version to 1.0.0 (no functional changes)
# async-each 0.1.6 (5 November 2014)
* Add license to package.json
# async-each 0.1.5 (22 October 2014)
* Clean up package.json to fix npm warning about `repo`
# async-each 0.1.4 (12 November 2013)
* Fixed AMD definition.
# async-each 0.1.3 (25 July 2013)
* Fixed double wrapping of errors.
# async-each 0.1.2 (7 July 2013)
* Fixed behaviour on empty arrays.
# async-each 0.1.1 (14 June 2013)
* Wrapped function in closure, enabled strict mode.
# async-each 0.1.0 (14 June 2013)
* Initial release.

View File

@@ -0,0 +1,38 @@
# async-each
No-bullshit, ultra-simple, 35-lines-of-code async parallel forEach function for JavaScript.
We don't need junky 30K async libs. Really.
For browsers and node.js.
## Installation
* Just include async-each before your scripts.
* `npm install async-each` if youre using node.js.
* `bower install async-each` if youre using [Bower](http://bower.io).
## Usage
* `each(array, iterator, callback);``Array`, `Function`, `(optional) Function`
* `iterator(item, next)` receives current item and a callback that will mark the item as done. `next` callback receives optional `error, transformedItem` arguments.
* `callback(error, transformedArray)` optionally receives first error and transformed result `Array`.
Node.js:
```javascript
var each = require('async-each');
each(['a.js', 'b.js', 'c.js'], fs.readFile, function(error, contents) {
if (error) console.error(error);
console.log('Contents for a, b and c:', contents);
});
```
Browser:
```javascript
window.asyncEach(list, fn, callback);
```
## License
[The MIT License](https://raw.githubusercontent.com/paulmillr/mit/master/README.md)

View File

@@ -0,0 +1,38 @@
// async-each MIT license (by Paul Miller from http://paulmillr.com).
(function(globals) {
'use strict';
var each = function(items, next, callback) {
if (!Array.isArray(items)) throw new TypeError('each() expects array as first argument');
if (typeof next !== 'function') throw new TypeError('each() expects function as second argument');
if (typeof callback !== 'function') callback = Function.prototype; // no-op
if (items.length === 0) return callback(undefined, items);
var transformed = new Array(items.length);
var count = 0;
var returned = false;
items.forEach(function(item, index) {
next(item, function(error, transformedItem) {
if (returned) return;
if (error) {
returned = true;
return callback(error);
}
transformed[index] = transformedItem;
count += 1;
if (count === items.length) return callback(undefined, transformed);
});
});
};
if (typeof define !== 'undefined' && define.amd) {
define([], function() {
return each;
}); // RequireJS
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = each; // CommonJS
} else {
globals.asyncEach = each; // <script>
}
})(this);

View File

@@ -0,0 +1,65 @@
{
"_args": [
[
"async-each@1.0.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "async-each@1.0.1",
"_id": "async-each@1.0.1",
"_inBundle": false,
"_integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=",
"_location": "/babel-cli/async-each",
"_optional": true,
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "async-each@1.0.1",
"name": "async-each",
"escapedName": "async-each",
"rawSpec": "1.0.1",
"saveSpec": null,
"fetchSpec": "1.0.1"
},
"_requiredBy": [
"/babel-cli/chokidar"
],
"_resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz",
"_spec": "1.0.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Paul Miller",
"url": "http://paulmillr.com/"
},
"bugs": {
"url": "https://github.com/paulmillr/async-each/issues"
},
"dependencies": {},
"description": "No-bullshit, ultra-simple, 35-lines-of-code async parallel forEach / map function for JavaScript.",
"homepage": "https://github.com/paulmillr/async-each/",
"keywords": [
"async",
"forEach",
"each",
"map",
"asynchronous",
"iteration",
"iterate",
"loop",
"parallel",
"concurrent",
"array",
"flow",
"control flow"
],
"license": "MIT",
"main": "index.js",
"name": "async-each",
"repository": {
"type": "git",
"url": "git://github.com/paulmillr/async-each.git"
},
"version": "1.0.1"
}

View File

@@ -0,0 +1,3 @@
src
test
node_modules

View File

@@ -0,0 +1,60 @@
# babel-code-frame
> Generate errors that contain a code frame that point to source locations.
## Install
```sh
npm install --save-dev babel-code-frame
```
## Usage
```js
import codeFrame from 'babel-code-frame';
const rawLines = `class Foo {
constructor()
}`;
const lineNumber = 2;
const colNumber = 16;
const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });
console.log(result);
```
```sh
1 | class Foo {
> 2 | constructor()
| ^
3 | }
```
If the column number is not known, you may pass `null` instead.
## Options
### `highlightCode`
`boolean`, defaults to `false`.
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
Adjust the number of lines to show above the error.
### `linesBelow`
`number`, defaults to `3`.
Adjust the number of lines to show below the error.
### `forceColor`
`boolean`, defaults to `false`.
Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.

View File

@@ -0,0 +1,141 @@
"use strict";
exports.__esModule = true;
exports.default = function (rawLines, lineNumber, colNumber) {
var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
colNumber = Math.max(colNumber, 0);
var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor;
var chalk = _chalk2.default;
if (opts.forceColor) {
chalk = new _chalk2.default.constructor({ enabled: true });
}
var maybeHighlight = function maybeHighlight(chalkFn, string) {
return highlighted ? chalkFn(string) : string;
};
var defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
var linesAbove = opts.linesAbove || 2;
var linesBelow = opts.linesBelow || 3;
var lines = rawLines.split(NEWLINE);
var start = Math.max(lineNumber - (linesAbove + 1), 0);
var end = Math.min(lines.length, lineNumber + linesBelow);
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
var numberMaxWidth = String(end).length;
var frame = lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var paddedNumber = (" " + number).slice(-numberMaxWidth);
var gutter = " " + paddedNumber + " | ";
if (number === lineNumber) {
var markerLine = "";
if (colNumber) {
var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " ");
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join("");
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
} else {
return " " + maybeHighlight(defs.gutter, gutter) + line;
}
}).join("\n");
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
};
var _jsTokens = require("js-tokens");
var _jsTokens2 = _interopRequireDefault(_jsTokens);
var _esutils = require("esutils");
var _esutils2 = _interopRequireDefault(_esutils);
var _chalk = require("chalk");
var _chalk2 = _interopRequireDefault(_chalk);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold
};
}
var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
var JSX_TAG = /^[a-z][\w-]*$/i;
var BRACKET = /^[()\[\]{}]$/;
function getTokenType(match) {
var _match$slice = match.slice(-2),
offset = _match$slice[0],
text = _match$slice[1];
var token = (0, _jsTokens.matchToToken)(match);
if (token.type === "name") {
if (_esutils2.default.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
return token.type;
}
function highlight(defs, text) {
return text.replace(_jsTokens2.default, function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var type = getTokenType(args);
var colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(function (str) {
return colorize(str);
}).join("\n");
} else {
return args[0];
}
});
}
module.exports = exports["default"];

View File

@@ -0,0 +1,66 @@
{
"name": "babel-code-frame",
"version": "6.22.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"ansi-regex": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
"integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8="
},
"ansi-styles": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
"integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4="
},
"chalk": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
"integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
"requires": {
"ansi-styles": "2.2.1",
"escape-string-regexp": "1.0.5",
"has-ansi": "2.0.0",
"strip-ansi": "3.0.1",
"supports-color": "2.0.0"
}
},
"escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
"integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ="
},
"esutils": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz",
"integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs="
},
"has-ansi": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz",
"integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=",
"requires": {
"ansi-regex": "2.1.1"
}
},
"js-tokens": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz",
"integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls="
},
"strip-ansi": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
"integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
"requires": {
"ansi-regex": "2.1.1"
}
},
"supports-color": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",
"integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc="
}
}
}

View File

@@ -0,0 +1,51 @@
{
"_args": [
[
"babel-code-frame@6.26.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "babel-code-frame@6.26.0",
"_id": "babel-code-frame@6.26.0",
"_inBundle": false,
"_integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=",
"_location": "/babel-cli/babel-code-frame",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "babel-code-frame@6.26.0",
"name": "babel-code-frame",
"escapedName": "babel-code-frame",
"rawSpec": "6.26.0",
"saveSpec": null,
"fetchSpec": "6.26.0"
},
"_requiredBy": [
"/babel-cli/babel-core",
"/babel-cli/babel-traverse"
],
"_resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz",
"_spec": "6.26.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"dependencies": {
"chalk": "^1.1.3",
"esutils": "^2.0.2",
"js-tokens": "^3.0.2"
},
"description": "Generate errors that contain a code frame that point to source locations.",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "babel-code-frame",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
},
"version": "6.26.0"
}

View File

@@ -0,0 +1,121 @@
# babel-core
> Babel compiler core.
```javascript
var babel = require("babel-core");
import { transform } from 'babel-core';
import * as babel from 'babel-core';
```
All transformations will use your local configuration files (.babelrc or in package.json). See [options](#options) to disable it.
## babel.transform(code: string, [options?](#options): Object)
Transforms the passed in `code`. Returning an object with the generated code,
source map, and AST.
```js
babel.transform(code, options) // => { code, map, ast }
```
**Example**
```js
var result = babel.transform("code();", options);
result.code;
result.map;
result.ast;
```
## babel.transformFile(filename: string, [options?](#options): Object, callback: Function)
Asynchronously transforms the entire contents of a file.
```js
babel.transformFile(filename, options, callback)
```
**Example**
```js
babel.transformFile("filename.js", options, function (err, result) {
result; // => { code, map, ast }
});
```
## babel.transformFileSync(filename: string, [options?](#options): Object)
Synchronous version of `babel.transformFile`. Returns the transformed contents of
the `filename`.
```js
babel.transformFileSync(filename, options) // => { code, map, ast }
```
**Example**
```js
babel.transformFileSync("filename.js", options).code;
```
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object)
Given, an [AST](https://astexplorer.net/), transform it.
```js
const code = "if (true) return;";
const ast = babylon.parse(code, { allowReturnOutsideFunction: true });
const { code, map, ast } = babel.transformFromAst(ast, code, options);
```
## Options
<blockquote class="babel-callout babel-callout-info">
<h4>Babel CLI</h4>
<p>
You can pass these options from the Babel CLI like so:
</p>
<p>
<code>babel --name<span class="o">=</span>value</code>
</p>
</blockquote>
Following is a table of the options you can use:
| Option | Default | Description |
| ------------------------ | -------------------- | ------------------------------- |
| `ast` | `true` | Include the AST in the returned object |
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code. |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code. |
| `babelrc` | `true` | Specify whether or not to use .babelrc and .babelignore files. Not available when using the CLI, [use `--no-babelrc` instead](https://babeljs.io/docs/usage/cli/#babel-ignoring-babelrc). |
| `code` | `true` | Enable code generation |
| `comments` | `true` | Output comments in generated output. |
| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB. |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the environment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` |
| `extends` | `null` | A path to an `.babelrc` file to extend |
| `filename` | `"unknown"` | Filename for use in errors etc. |
| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot`. |
| `generatorOpts` | `{}` | An object containing the options to be passed down to the babel code generator, babel-generator |
| `getModuleId` | `null` | Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used. |
| `highlightCode` | `true` | ANSI highlight syntax error code frames |
| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified. |
| `inputSourceMap` | `null` | A source map object that the output source map will be based on. |
| `minified` | `false` | Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) |
| `moduleId` | `null` | Specify a custom name for module ids. |
| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) |
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. |
| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon |
| `plugins` | `[]` | List of [plugins](https://babeljs.io/docs/plugins/) to load and use. |
| `presets` | `[]` | List of [presets](https://babeljs.io/docs/plugins/#presets) (a set of plugins) to load and use. |
| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) |
| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)`. |
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used. |
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map. |
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option. |
| `sourceMapTarget` | `(filenameRelative)` | Set `file` on returned source map. |
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative. |
| `sourceType` | `"module"` | Indicate the mode the code should be parsed in. Can be either "script" or "module". |
| `wrapPluginVisitorMethod`| `null` | An optional callback that can be used to wrap visitor methods. **NOTE:** This is useful for things like introspection, and not really needed for implementing anything. Called as `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.

View File

@@ -0,0 +1 @@
module.exports = require("./lib/api/node.js");

View File

@@ -0,0 +1,190 @@
"use strict";
exports.__esModule = true;
exports.transformFileSync = exports.transformFile = exports.transformFromAst = exports.transform = exports.analyse = exports.Pipeline = exports.Plugin = exports.OptionManager = exports.traverse = exports.types = exports.messages = exports.util = exports.version = exports.template = exports.buildExternalHelpers = exports.options = exports.File = undefined;
var _node = require("./node");
Object.defineProperty(exports, "File", {
enumerable: true,
get: function get() {
return _node.File;
}
});
Object.defineProperty(exports, "options", {
enumerable: true,
get: function get() {
return _node.options;
}
});
Object.defineProperty(exports, "buildExternalHelpers", {
enumerable: true,
get: function get() {
return _node.buildExternalHelpers;
}
});
Object.defineProperty(exports, "template", {
enumerable: true,
get: function get() {
return _node.template;
}
});
Object.defineProperty(exports, "version", {
enumerable: true,
get: function get() {
return _node.version;
}
});
Object.defineProperty(exports, "util", {
enumerable: true,
get: function get() {
return _node.util;
}
});
Object.defineProperty(exports, "messages", {
enumerable: true,
get: function get() {
return _node.messages;
}
});
Object.defineProperty(exports, "types", {
enumerable: true,
get: function get() {
return _node.types;
}
});
Object.defineProperty(exports, "traverse", {
enumerable: true,
get: function get() {
return _node.traverse;
}
});
Object.defineProperty(exports, "OptionManager", {
enumerable: true,
get: function get() {
return _node.OptionManager;
}
});
Object.defineProperty(exports, "Plugin", {
enumerable: true,
get: function get() {
return _node.Plugin;
}
});
Object.defineProperty(exports, "Pipeline", {
enumerable: true,
get: function get() {
return _node.Pipeline;
}
});
Object.defineProperty(exports, "analyse", {
enumerable: true,
get: function get() {
return _node.analyse;
}
});
Object.defineProperty(exports, "transform", {
enumerable: true,
get: function get() {
return _node.transform;
}
});
Object.defineProperty(exports, "transformFromAst", {
enumerable: true,
get: function get() {
return _node.transformFromAst;
}
});
Object.defineProperty(exports, "transformFile", {
enumerable: true,
get: function get() {
return _node.transformFile;
}
});
Object.defineProperty(exports, "transformFileSync", {
enumerable: true,
get: function get() {
return _node.transformFileSync;
}
});
exports.run = run;
exports.load = load;
function run(code) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new Function((0, _node.transform)(code, opts).code)();
}
function load(url, callback) {
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var hold = arguments[3];
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
var status = xhr.status;
if (status === 0 || status === 200) {
var param = [xhr.responseText, opts];
if (!hold) run(param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
}
};
xhr.send(null);
}
function runScripts() {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
function exec() {
var param = scripts[index];
if (param instanceof Array) {
run(param, index);
index++;
exec();
}
}
function run(script, i) {
var opts = {};
if (script.src) {
load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
}
var _scripts = global.document.getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (var _i = 0; _i < scripts.length; _i++) {
run(scripts[_i], _i);
}
exec();
}
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}

View File

@@ -0,0 +1,153 @@
"use strict";
exports.__esModule = true;
exports.transformFromAst = exports.transform = exports.analyse = exports.Pipeline = exports.OptionManager = exports.traverse = exports.types = exports.messages = exports.util = exports.version = exports.resolvePreset = exports.resolvePlugin = exports.template = exports.buildExternalHelpers = exports.options = exports.File = undefined;
var _file = require("../transformation/file");
Object.defineProperty(exports, "File", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_file).default;
}
});
var _config = require("../transformation/file/options/config");
Object.defineProperty(exports, "options", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_config).default;
}
});
var _buildExternalHelpers = require("../tools/build-external-helpers");
Object.defineProperty(exports, "buildExternalHelpers", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_buildExternalHelpers).default;
}
});
var _babelTemplate = require("babel-template");
Object.defineProperty(exports, "template", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_babelTemplate).default;
}
});
var _resolvePlugin = require("../helpers/resolve-plugin");
Object.defineProperty(exports, "resolvePlugin", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_resolvePlugin).default;
}
});
var _resolvePreset = require("../helpers/resolve-preset");
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_resolvePreset).default;
}
});
var _package = require("../../package");
Object.defineProperty(exports, "version", {
enumerable: true,
get: function get() {
return _package.version;
}
});
exports.Plugin = Plugin;
exports.transformFile = transformFile;
exports.transformFileSync = transformFileSync;
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var _util = require("../util");
var util = _interopRequireWildcard(_util);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _optionManager = require("../transformation/file/options/option-manager");
var _optionManager2 = _interopRequireDefault(_optionManager);
var _pipeline = require("../transformation/pipeline");
var _pipeline2 = _interopRequireDefault(_pipeline);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.util = util;
exports.messages = messages;
exports.types = t;
exports.traverse = _babelTraverse2.default;
exports.OptionManager = _optionManager2.default;
function Plugin(alias) {
throw new Error("The (" + alias + ") Babel 5 plugin is being run with Babel 6.");
}
exports.Pipeline = _pipeline2.default;
var pipeline = new _pipeline2.default();
var analyse = exports.analyse = pipeline.analyse.bind(pipeline);
var transform = exports.transform = pipeline.transform.bind(pipeline);
var transformFromAst = exports.transformFromAst = pipeline.transformFromAst.bind(pipeline);
function transformFile(filename, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = {};
}
opts.filename = filename;
_fs2.default.readFile(filename, function (err, code) {
var result = void 0;
if (!err) {
try {
result = transform(code, opts);
} catch (_err) {
err = _err;
}
}
if (err) {
callback(err);
} else {
callback(null, result);
}
});
}
function transformFileSync(filename) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
opts.filename = filename;
return transform(_fs2.default.readFileSync(filename, "utf8"), opts);
}

View File

@@ -0,0 +1,8 @@
"use strict";
exports.__esModule = true;
exports.default = getPossiblePluginNames;
function getPossiblePluginNames(pluginName) {
return ["babel-plugin-" + pluginName, pluginName];
}
module.exports = exports["default"];

View File

@@ -0,0 +1,18 @@
"use strict";
exports.__esModule = true;
exports.default = getPossiblePresetNames;
function getPossiblePresetNames(presetName) {
var possibleNames = ["babel-preset-" + presetName, presetName];
var matches = presetName.match(/^(@[^/]+)\/(.+)$/);
if (matches) {
var orgName = matches[1],
presetPath = matches[2];
possibleNames.push(orgName + "/babel-preset-" + presetPath);
}
return possibleNames;
}
module.exports = exports["default"];

View File

@@ -0,0 +1,46 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.default = function (dest, src) {
if (!dest || !src) return;
return (0, _mergeWith2.default)(dest, src, function (a, b) {
if (b && Array.isArray(a)) {
var newArray = b.slice(0);
for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var item = _ref;
if (newArray.indexOf(item) < 0) {
newArray.push(item);
}
}
return newArray;
}
});
};
var _mergeWith = require("lodash/mergeWith");
var _mergeWith2 = _interopRequireDefault(_mergeWith);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports["default"];

View File

@@ -0,0 +1,23 @@
"use strict";
exports.__esModule = true;
exports.default = function (ast, comments, tokens) {
if (ast) {
if (ast.type === "Program") {
return t.file(ast, comments || [], tokens || []);
} else if (ast.type === "File") {
return ast;
}
}
throw new Error("Not a valid ast?");
};
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
module.exports = exports["default"];

View File

@@ -0,0 +1,17 @@
"use strict";
exports.__esModule = true;
exports.default = resolveFromPossibleNames;
var _resolve = require("./resolve");
var _resolve2 = _interopRequireDefault(_resolve);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function resolveFromPossibleNames(possibleNames, dirname) {
return possibleNames.reduce(function (accum, curr) {
return accum || (0, _resolve2.default)(curr, dirname);
}, null);
}
module.exports = exports["default"];

View File

@@ -0,0 +1,21 @@
"use strict";
exports.__esModule = true;
exports.default = resolvePlugin;
var _resolveFromPossibleNames = require("./resolve-from-possible-names");
var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames);
var _getPossiblePluginNames = require("./get-possible-plugin-names");
var _getPossiblePluginNames2 = _interopRequireDefault(_getPossiblePluginNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function resolvePlugin(pluginName) {
var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd();
return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePluginNames2.default)(pluginName), dirname);
}
module.exports = exports["default"];

View File

@@ -0,0 +1,21 @@
"use strict";
exports.__esModule = true;
exports.default = resolvePreset;
var _resolveFromPossibleNames = require("./resolve-from-possible-names");
var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames);
var _getPossiblePresetNames = require("./get-possible-preset-names");
var _getPossiblePresetNames2 = _interopRequireDefault(_getPossiblePresetNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function resolvePreset(presetName) {
var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd();
return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePresetNames2.default)(presetName), dirname);
}
module.exports = exports["default"];

View File

@@ -0,0 +1,46 @@
"use strict";
exports.__esModule = true;
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
exports.default = function (loc) {
var relative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd();
if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null;
var relativeMod = relativeModules[relative];
if (!relativeMod) {
relativeMod = new _module2.default();
var filename = _path2.default.join(relative, ".babelrc");
relativeMod.id = filename;
relativeMod.filename = filename;
relativeMod.paths = _module2.default._nodeModulePaths(relative);
relativeModules[relative] = relativeMod;
}
try {
return _module2.default._resolveFilename(loc, relativeMod);
} catch (err) {
return null;
}
};
var _module = require("module");
var _module2 = _interopRequireDefault(_module);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var relativeModules = {};
module.exports = exports["default"];

View File

@@ -0,0 +1,55 @@
"use strict";
exports.__esModule = true;
var _map = require("babel-runtime/core-js/map");
var _map2 = _interopRequireDefault(_map);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Store = function (_Map) {
(0, _inherits3.default)(Store, _Map);
function Store() {
(0, _classCallCheck3.default)(this, Store);
var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this));
_this.dynamicData = {};
return _this;
}
Store.prototype.setDynamic = function setDynamic(key, fn) {
this.dynamicData[key] = fn;
};
Store.prototype.get = function get(key) {
if (this.has(key)) {
return _Map.prototype.get.call(this, key);
} else {
if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) {
var val = this.dynamicData[key]();
this.set(key, val);
return val;
}
}
};
return Store;
}(_map2.default);
exports.default = Store;
module.exports = exports["default"];

View File

@@ -0,0 +1,101 @@
"use strict";
exports.__esModule = true;
exports.default = function (whitelist) {
var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global";
var namespace = t.identifier("babelHelpers");
var builder = function builder(body) {
return buildHelpers(body, namespace, whitelist);
};
var tree = void 0;
var build = {
global: buildGlobal,
umd: buildUmd,
var: buildVar
}[outputType];
if (build) {
tree = build(namespace, builder);
} else {
throw new Error(messages.get("unsupportedOutputType", outputType));
}
return (0, _babelGenerator2.default)(tree).code;
};
var _babelHelpers = require("babel-helpers");
var helpers = _interopRequireWildcard(_babelHelpers);
var _babelGenerator = require("babel-generator");
var _babelGenerator2 = _interopRequireDefault(_babelGenerator);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTemplate = require("babel-template");
var _babelTemplate2 = _interopRequireDefault(_babelTemplate);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var buildUmdWrapper = (0, _babelTemplate2.default)("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n");
function buildGlobal(namespace, builder) {
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))]));
builder(body);
return tree;
}
function buildUmd(namespace, builder) {
var body = [];
body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))]));
builder(body);
return t.program([buildUmdWrapper({
FACTORY_PARAMETERS: t.identifier("global"),
BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])),
COMMON_ARGUMENTS: t.identifier("exports"),
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
FACTORY_BODY: body,
UMD_ROOT: t.identifier("this")
})]);
}
function buildVar(namespace, builder) {
var body = [];
body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))]));
builder(body);
body.push(t.expressionStatement(namespace));
return t.program(body);
}
function buildHelpers(body, namespace, whitelist) {
helpers.list.forEach(function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return;
var key = t.identifier(name);
body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name))));
});
}
module.exports = exports["default"];

View File

@@ -0,0 +1,737 @@
"use strict";
exports.__esModule = true;
exports.File = undefined;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _create = require("babel-runtime/core-js/object/create");
var _create2 = _interopRequireDefault(_create);
var _assign = require("babel-runtime/core-js/object/assign");
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
var _babelHelpers = require("babel-helpers");
var _babelHelpers2 = _interopRequireDefault(_babelHelpers);
var _metadata = require("./metadata");
var metadataVisitor = _interopRequireWildcard(_metadata);
var _convertSourceMap = require("convert-source-map");
var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap);
var _optionManager = require("./options/option-manager");
var _optionManager2 = _interopRequireDefault(_optionManager);
var _pluginPass = require("../plugin-pass");
var _pluginPass2 = _interopRequireDefault(_pluginPass);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _sourceMap = require("source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _babelGenerator = require("babel-generator");
var _babelGenerator2 = _interopRequireDefault(_babelGenerator);
var _babelCodeFrame = require("babel-code-frame");
var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame);
var _defaults = require("lodash/defaults");
var _defaults2 = _interopRequireDefault(_defaults);
var _logger = require("./logger");
var _logger2 = _interopRequireDefault(_logger);
var _store = require("../../store");
var _store2 = _interopRequireDefault(_store);
var _babylon = require("babylon");
var _util = require("../../util");
var util = _interopRequireWildcard(_util);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _resolve = require("../../helpers/resolve");
var _resolve2 = _interopRequireDefault(_resolve);
var _blockHoist = require("../internal-plugins/block-hoist");
var _blockHoist2 = _interopRequireDefault(_blockHoist);
var _shadowFunctions = require("../internal-plugins/shadow-functions");
var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var shebangRegex = /^#!.*/;
var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]];
var errorVisitor = {
enter: function enter(path, state) {
var loc = path.node.loc;
if (loc) {
state.loc = loc;
path.stop();
}
}
};
var File = function (_Store) {
(0, _inherits3.default)(File, _Store);
function File() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var pipeline = arguments[1];
(0, _classCallCheck3.default)(this, File);
var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this));
_this.pipeline = pipeline;
_this.log = new _logger2.default(_this, opts.filename || "unknown");
_this.opts = _this.initOptions(opts);
_this.parserOpts = {
sourceType: _this.opts.sourceType,
sourceFileName: _this.opts.filename,
plugins: []
};
_this.pluginVisitors = [];
_this.pluginPasses = [];
_this.buildPluginsForOptions(_this.opts);
if (_this.opts.passPerPreset) {
_this.perPresetOpts = [];
_this.opts.presets.forEach(function (presetOpts) {
var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_this.opts), presetOpts);
_this.perPresetOpts.push(perPresetOpts);
_this.buildPluginsForOptions(perPresetOpts);
});
}
_this.metadata = {
usedHelpers: [],
marked: [],
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
_this.dynamicImportTypes = {};
_this.dynamicImportIds = {};
_this.dynamicImports = [];
_this.declarations = {};
_this.usedHelpers = {};
_this.path = null;
_this.ast = {};
_this.code = "";
_this.shebang = "";
_this.hub = new _babelTraverse.Hub(_this);
return _this;
}
File.prototype.getMetadata = function getMetadata() {
var has = false;
for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
if (t.isModuleDeclaration(node)) {
has = true;
break;
}
}
if (has) {
this.path.traverse(metadataVisitor, this);
}
};
File.prototype.initOptions = function initOptions(opts) {
opts = new _optionManager2.default(this.log, this.pipeline).init(opts);
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = _path2.default.basename(opts.filename, _path2.default.extname(opts.filename));
opts.ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
(0, _defaults2.default)(opts, {
moduleRoot: opts.sourceRoot
});
(0, _defaults2.default)(opts, {
sourceRoot: opts.moduleRoot
});
(0, _defaults2.default)(opts, {
filenameRelative: opts.filename
});
var basenameRelative = _path2.default.basename(opts.filenameRelative);
(0, _defaults2.default)(opts, {
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative
});
return opts;
};
File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) {
if (!Array.isArray(opts.plugins)) {
return;
}
var plugins = opts.plugins.concat(INTERNAL_PLUGINS);
var currentPluginVisitors = [];
var currentPluginPasses = [];
for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var ref = _ref2;
var plugin = ref[0],
pluginOpts = ref[1];
currentPluginVisitors.push(plugin.visitor);
currentPluginPasses.push(new _pluginPass2.default(this, plugin, pluginOpts));
if (plugin.manipulateOptions) {
plugin.manipulateOptions(opts, this.parserOpts, this);
}
}
this.pluginVisitors.push(currentPluginVisitors);
this.pluginPasses.push(currentPluginPasses);
};
File.prototype.getModuleName = function getModuleName() {
var opts = this.opts;
if (!opts.moduleIds) {
return null;
}
if (opts.moduleId != null && !opts.getModuleId) {
return opts.moduleId;
}
var filenameRelative = opts.filenameRelative;
var moduleName = "";
if (opts.moduleRoot != null) {
moduleName = opts.moduleRoot + "/";
}
if (!opts.filenameRelative) {
return moduleName + opts.filename.replace(/^\//, "");
}
if (opts.sourceRoot != null) {
var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");
moduleName += filenameRelative;
moduleName = moduleName.replace(/\\/g, "/");
if (opts.getModuleId) {
return opts.getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
};
File.prototype.resolveModuleSource = function resolveModuleSource(source) {
var resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
};
File.prototype.addImport = function addImport(source, imported) {
var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : imported;
var alias = source + ":" + imported;
var id = this.dynamicImportIds[alias];
if (!id) {
source = this.resolveModuleSource(source);
id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);
var specifiers = [];
if (imported === "*") {
specifiers.push(t.importNamespaceSpecifier(id));
} else if (imported === "default") {
specifiers.push(t.importDefaultSpecifier(id));
} else {
specifiers.push(t.importSpecifier(id, t.identifier(imported)));
}
var declar = t.importDeclaration(specifiers, t.stringLiteral(source));
declar._blockHoist = 3;
this.path.unshiftContainer("body", declar);
}
return id;
};
File.prototype.addHelper = function addHelper(name) {
var declar = this.declarations[name];
if (declar) return declar;
if (!this.usedHelpers[name]) {
this.metadata.usedHelpers.push(name);
this.usedHelpers[name] = true;
}
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
var res = generator(name);
if (res) return res;
} else if (runtime) {
return t.memberExpression(runtime, t.identifier(name));
}
var ref = (0, _babelHelpers2.default)(name);
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
};
File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) {
var stringIds = raw.elements.map(function (string) {
return string.value;
});
var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(",");
var declar = this.declarations[name];
if (declar) return declar;
var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
var helperId = this.addHelper(helperName);
var init = t.callExpression(helperId, [strings, raw]);
init._compact = true;
this.scope.push({
id: uid,
init: init,
_blockHoist: 1.9 });
return uid;
};
File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) {
var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError;
var loc = node && (node.loc || node._loc);
var err = new Error(msg);
if (loc) {
err.loc = loc.start;
} else {
(0, _babelTraverse2.default)(node, errorVisitor, this.scope, err);
err.message += " (This is an error on an internal node. Probably an internal error";
if (err.loc) {
err.message += ". Location has been estimated.";
}
err.message += ")";
}
return err;
};
File.prototype.mergeSourceMap = function mergeSourceMap(map) {
var inputMap = this.opts.inputSourceMap;
if (inputMap) {
var inputMapConsumer = new _sourceMap2.default.SourceMapConsumer(inputMap);
var outputMapConsumer = new _sourceMap2.default.SourceMapConsumer(map);
var mergedGenerator = new _sourceMap2.default.SourceMapGenerator({
file: inputMapConsumer.file,
sourceRoot: inputMapConsumer.sourceRoot
});
var source = outputMapConsumer.sources[0];
inputMapConsumer.eachMapping(function (mapping) {
var generatedPosition = outputMapConsumer.generatedPositionFor({
line: mapping.generatedLine,
column: mapping.generatedColumn,
source: source
});
if (generatedPosition.column != null) {
mergedGenerator.addMapping({
source: mapping.source,
original: mapping.source == null ? null : {
line: mapping.originalLine,
column: mapping.originalColumn
},
generated: generatedPosition
});
}
});
var mergedMap = mergedGenerator.toJSON();
inputMap.mappings = mergedMap.mappings;
return inputMap;
} else {
return map;
}
};
File.prototype.parse = function parse(code) {
var parseCode = _babylon.parse;
var parserOpts = this.opts.parserOpts;
if (parserOpts) {
parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts);
if (parserOpts.parser) {
if (typeof parserOpts.parser === "string") {
var dirname = _path2.default.dirname(this.opts.filename) || process.cwd();
var parser = (0, _resolve2.default)(parserOpts.parser, dirname);
if (parser) {
parseCode = require(parser).parse;
} else {
throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method " + ("relative to directory " + dirname));
}
} else {
parseCode = parserOpts.parser;
}
parserOpts.parser = {
parse: function parse(source) {
return (0, _babylon.parse)(source, parserOpts);
}
};
}
}
this.log.debug("Parse start");
var ast = parseCode(code, parserOpts || this.parserOpts);
this.log.debug("Parse stop");
return ast;
};
File.prototype._addAst = function _addAst(ast) {
this.path = _babelTraverse.NodePath.get({
hub: this.hub,
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
this.getMetadata();
};
File.prototype.addAst = function addAst(ast) {
this.log.debug("Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
};
File.prototype.transform = function transform() {
for (var i = 0; i < this.pluginPasses.length; i++) {
var pluginPasses = this.pluginPasses[i];
this.call("pre", pluginPasses);
this.log.debug("Start transform traverse");
var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod);
(0, _babelTraverse2.default)(this.ast, visitor, this.scope);
this.log.debug("End transform traverse");
this.call("post", pluginPasses);
}
return this.generate();
};
File.prototype.wrap = function wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return this.makeResult({ code: code, ignored: true });
} else {
return callback();
}
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = this.opts.filename + ": " + err.message;
var loc = err.loc;
if (loc) {
err.codeFrame = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (process.browser) {
err.message = message;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
err.stack = newStack;
}
throw err;
}
};
File.prototype.addCode = function addCode(code) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
};
File.prototype.parseCode = function parseCode() {
this.parseShebang();
var ast = this.parse(this.code);
this.addAst(ast);
};
File.prototype.shouldIgnore = function shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
};
File.prototype.call = function call(key, pluginPasses) {
for (var _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var pass = _ref3;
var plugin = pass.plugin;
var fn = plugin[key];
if (fn) fn.call(pass, this);
}
};
File.prototype.parseInputSourceMap = function parseInputSourceMap(code) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = _convertSourceMap2.default.fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = _convertSourceMap2.default.removeComments(code);
}
}
return code;
};
File.prototype.parseShebang = function parseShebang() {
var shebangMatch = shebangRegex.exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(shebangRegex, "");
}
};
File.prototype.makeResult = function makeResult(_ref4) {
var code = _ref4.code,
map = _ref4.map,
ast = _ref4.ast,
ignored = _ref4.ignored;
var result = {
metadata: null,
options: this.opts,
ignored: !!ignored,
code: null,
ast: null,
map: map || null
};
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
}
return result;
};
File.prototype.generate = function generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast: ast };
if (!opts.code) return this.makeResult(result);
var gen = _babelGenerator2.default;
if (opts.generatorOpts.generator) {
gen = opts.generatorOpts.generator;
if (typeof gen === "string") {
var dirname = _path2.default.dirname(this.opts.filename) || process.cwd();
var generator = (0, _resolve2.default)(gen, dirname);
if (generator) {
gen = require(generator).print;
} else {
throw new Error("Couldn't find generator " + gen + " with \"print\" method relative " + ("to directory " + dirname));
}
}
}
this.log.debug("Generation start");
var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
result.code = this.shebang + "\n" + result.code;
}
if (result.map) {
result.map = this.mergeSourceMap(result.map);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
result.code += "\n" + _convertSourceMap2.default.fromObject(result.map).toComment();
}
if (opts.sourceMaps === "inline") {
result.map = null;
}
return this.makeResult(result);
};
return File;
}(_store2.default);
exports.default = File;
exports.File = File;

View File

@@ -0,0 +1,72 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _node = require("debug/node");
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var verboseDebug = (0, _node2.default)("babel:verbose");
var generalDebug = (0, _node2.default)("babel");
var seenDeprecatedMessages = [];
var Logger = function () {
function Logger(file, filename) {
(0, _classCallCheck3.default)(this, Logger);
this.filename = filename;
this.file = file;
}
Logger.prototype._buildMessage = function _buildMessage(msg) {
var parts = "[BABEL] " + this.filename;
if (msg) parts += ": " + msg;
return parts;
};
Logger.prototype.warn = function warn(msg) {
console.warn(this._buildMessage(msg));
};
Logger.prototype.error = function error(msg) {
var Constructor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error;
throw new Constructor(this._buildMessage(msg));
};
Logger.prototype.deprecate = function deprecate(msg) {
if (this.file.opts && this.file.opts.suppressDeprecationMessages) return;
msg = this._buildMessage(msg);
if (seenDeprecatedMessages.indexOf(msg) >= 0) return;
seenDeprecatedMessages.push(msg);
console.error(msg);
};
Logger.prototype.verbose = function verbose(msg) {
if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg));
};
Logger.prototype.debug = function debug(msg) {
if (generalDebug.enabled) generalDebug(this._buildMessage(msg));
};
Logger.prototype.deopt = function deopt(node, msg) {
this.debug(msg);
};
return Logger;
}();
exports.default = Logger;
module.exports = exports["default"];

View File

@@ -0,0 +1,178 @@
"use strict";
exports.__esModule = true;
exports.ImportDeclaration = exports.ModuleDeclaration = undefined;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.ExportDeclaration = ExportDeclaration;
exports.Scope = Scope;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ModuleDeclaration = exports.ModuleDeclaration = {
enter: function enter(path, file) {
var node = path.node;
if (node.source) {
node.source.value = file.resolveModuleSource(node.source.value);
}
}
};
var ImportDeclaration = exports.ImportDeclaration = {
exit: function exit(path, file) {
var node = path.node;
var specifiers = [];
var imported = [];
file.metadata.modules.imports.push({
source: node.source.value,
imported: imported,
specifiers: specifiers
});
for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var specifier = _ref;
var local = specifier.node.local.name;
if (specifier.isImportDefaultSpecifier()) {
imported.push("default");
specifiers.push({
kind: "named",
imported: "default",
local: local
});
}
if (specifier.isImportSpecifier()) {
var importedName = specifier.node.imported.name;
imported.push(importedName);
specifiers.push({
kind: "named",
imported: importedName,
local: local
});
}
if (specifier.isImportNamespaceSpecifier()) {
imported.push("*");
specifiers.push({
kind: "namespace",
local: local
});
}
}
}
};
function ExportDeclaration(path, file) {
var node = path.node;
var source = node.source ? node.source.value : null;
var exports = file.metadata.modules.exports;
var declar = path.get("declaration");
if (declar.isStatement()) {
var bindings = declar.getBindingIdentifiers();
for (var name in bindings) {
exports.exported.push(name);
exports.specifiers.push({
kind: "local",
local: name,
exported: path.isExportDefaultDeclaration() ? "default" : name
});
}
}
if (path.isExportNamedDeclaration() && node.specifiers) {
for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var specifier = _ref2;
var exported = specifier.exported.name;
exports.exported.push(exported);
if (t.isExportDefaultSpecifier(specifier)) {
exports.specifiers.push({
kind: "external",
local: exported,
exported: exported,
source: source
});
}
if (t.isExportNamespaceSpecifier(specifier)) {
exports.specifiers.push({
kind: "external-namespace",
exported: exported,
source: source
});
}
var local = specifier.local;
if (!local) continue;
if (source) {
exports.specifiers.push({
kind: "external",
local: local.name,
exported: exported,
source: source
});
}
if (!source) {
exports.specifiers.push({
kind: "local",
local: local.name,
exported: exported
});
}
}
}
if (path.isExportAllDeclaration()) {
exports.specifiers.push({
kind: "external-all",
source: source
});
}
}
function Scope(path) {
path.skip();
}

View File

@@ -0,0 +1,215 @@
"use strict";
exports.__esModule = true;
var _assign = require("babel-runtime/core-js/object/assign");
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
exports.default = buildConfigChain;
var _resolve = require("../../../helpers/resolve");
var _resolve2 = _interopRequireDefault(_resolve);
var _json = require("json5");
var _json2 = _interopRequireDefault(_json);
var _pathIsAbsolute = require("path-is-absolute");
var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var existsCache = {};
var jsonCache = {};
var BABELIGNORE_FILENAME = ".babelignore";
var BABELRC_FILENAME = ".babelrc";
var PACKAGE_FILENAME = "package.json";
function exists(filename) {
var cached = existsCache[filename];
if (cached == null) {
return existsCache[filename] = _fs2.default.existsSync(filename);
} else {
return cached;
}
}
function buildConfigChain() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var log = arguments[1];
var filename = opts.filename;
var builder = new ConfigChainBuilder(log);
if (opts.babelrc !== false) {
builder.findConfigs(filename);
}
builder.mergeConfig({
options: opts,
alias: "base",
dirname: filename && _path2.default.dirname(filename)
});
return builder.configs;
}
var ConfigChainBuilder = function () {
function ConfigChainBuilder(log) {
(0, _classCallCheck3.default)(this, ConfigChainBuilder);
this.resolvedConfigs = [];
this.configs = [];
this.log = log;
}
ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) {
if (!loc) return;
if (!(0, _pathIsAbsolute2.default)(loc)) {
loc = _path2.default.join(process.cwd(), loc);
}
var foundConfig = false;
var foundIgnore = false;
while (loc !== (loc = _path2.default.dirname(loc))) {
if (!foundConfig) {
var configLoc = _path2.default.join(loc, BABELRC_FILENAME);
if (exists(configLoc)) {
this.addConfig(configLoc);
foundConfig = true;
}
var pkgLoc = _path2.default.join(loc, PACKAGE_FILENAME);
if (!foundConfig && exists(pkgLoc)) {
foundConfig = this.addConfig(pkgLoc, "babel", JSON);
}
}
if (!foundIgnore) {
var ignoreLoc = _path2.default.join(loc, BABELIGNORE_FILENAME);
if (exists(ignoreLoc)) {
this.addIgnoreConfig(ignoreLoc);
foundIgnore = true;
}
}
if (foundIgnore && foundConfig) return;
}
};
ConfigChainBuilder.prototype.addIgnoreConfig = function addIgnoreConfig(loc) {
var file = _fs2.default.readFileSync(loc, "utf8");
var lines = file.split("\n");
lines = lines.map(function (line) {
return line.replace(/#(.*?)$/, "").trim();
}).filter(function (line) {
return !!line;
});
if (lines.length) {
this.mergeConfig({
options: { ignore: lines },
alias: loc,
dirname: _path2.default.dirname(loc)
});
}
};
ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) {
var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _json2.default;
if (this.resolvedConfigs.indexOf(loc) >= 0) {
return false;
}
this.resolvedConfigs.push(loc);
var content = _fs2.default.readFileSync(loc, "utf8");
var options = void 0;
try {
options = jsonCache[content] = jsonCache[content] || json.parse(content);
if (key) options = options[key];
} catch (err) {
err.message = loc + ": Error while parsing JSON - " + err.message;
throw err;
}
this.mergeConfig({
options: options,
alias: loc,
dirname: _path2.default.dirname(loc)
});
return !!options;
};
ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) {
var options = _ref.options,
alias = _ref.alias,
loc = _ref.loc,
dirname = _ref.dirname;
if (!options) {
return false;
}
options = (0, _assign2.default)({}, options);
dirname = dirname || process.cwd();
loc = loc || alias;
if (options.extends) {
var extendsLoc = (0, _resolve2.default)(options.extends, dirname);
if (extendsLoc) {
this.addConfig(extendsLoc);
} else {
if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias);
}
delete options.extends;
}
this.configs.push({
options: options,
alias: alias,
loc: loc,
dirname: dirname
});
var envOpts = void 0;
var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development";
if (options.env) {
envOpts = options.env[envKey];
delete options.env;
}
this.mergeConfig({
options: envOpts,
alias: alias + ".env." + envKey,
dirname: dirname
});
};
return ConfigChainBuilder;
}();
module.exports = exports["default"];

View File

@@ -0,0 +1,211 @@
"use strict";
module.exports = {
filename: {
type: "filename",
description: "filename to use when reading from stdin - this will be used in source-maps, errors etc",
default: "unknown",
shorthand: "f"
},
filenameRelative: {
hidden: true,
type: "string"
},
inputSourceMap: {
hidden: true
},
env: {
hidden: true,
default: {}
},
mode: {
description: "",
hidden: true
},
retainLines: {
type: "boolean",
default: false,
description: "retain line numbers - will result in really ugly code"
},
highlightCode: {
description: "enable/disable ANSI syntax highlighting of code frames (on by default)",
type: "boolean",
default: true
},
suppressDeprecationMessages: {
type: "boolean",
default: false,
hidden: true
},
presets: {
type: "list",
description: "",
default: []
},
plugins: {
type: "list",
default: [],
description: ""
},
ignore: {
type: "list",
description: "list of glob paths to **not** compile",
default: []
},
only: {
type: "list",
description: "list of glob paths to **only** compile"
},
code: {
hidden: true,
default: true,
type: "boolean"
},
metadata: {
hidden: true,
default: true,
type: "boolean"
},
ast: {
hidden: true,
default: true,
type: "boolean"
},
extends: {
type: "string",
hidden: true
},
comments: {
type: "boolean",
default: true,
description: "write comments to generated output (true by default)"
},
shouldPrintComment: {
hidden: true,
description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored"
},
wrapPluginVisitorMethod: {
hidden: true,
description: "optional callback to wrap all visitor methods"
},
compact: {
type: "booleanString",
default: "auto",
description: "do not include superfluous whitespace characters and line terminators [true|false|auto]"
},
minified: {
type: "boolean",
default: false,
description: "save as much bytes when printing [true|false]"
},
sourceMap: {
alias: "sourceMaps",
hidden: true
},
sourceMaps: {
type: "booleanString",
description: "[true|false|inline]",
default: false,
shorthand: "s"
},
sourceMapTarget: {
type: "string",
description: "set `file` on returned source map"
},
sourceFileName: {
type: "string",
description: "set `sources[0]` on returned source map"
},
sourceRoot: {
type: "filename",
description: "the root from which all sources are relative"
},
babelrc: {
description: "Whether or not to look up .babelrc and .babelignore files",
type: "boolean",
default: true
},
sourceType: {
description: "",
default: "module"
},
auxiliaryCommentBefore: {
type: "string",
description: "print a comment before any injected non-user code"
},
auxiliaryCommentAfter: {
type: "string",
description: "print a comment after any injected non-user code"
},
resolveModuleSource: {
hidden: true
},
getModuleId: {
hidden: true
},
moduleRoot: {
type: "filename",
description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"
},
moduleIds: {
type: "boolean",
default: false,
shorthand: "M",
description: "insert an explicit id for modules"
},
moduleId: {
description: "specify a custom name for module ids",
type: "string"
},
passPerPreset: {
description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.",
type: "boolean",
default: false,
hidden: true
},
parserOpts: {
description: "Options to pass into the parser, or to change parsers (parserOpts.parser)",
default: false
},
generatorOpts: {
description: "Options to pass into the generator, or to change generators (generatorOpts.generator)",
default: false
}
};

View File

@@ -0,0 +1,38 @@
"use strict";
exports.__esModule = true;
exports.config = undefined;
exports.normaliseOptions = normaliseOptions;
var _parsers = require("./parsers");
var parsers = _interopRequireWildcard(_parsers);
var _config = require("./config");
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
exports.config = _config2.default;
function normaliseOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
for (var key in options) {
var val = options[key];
if (val == null) continue;
var opt = _config2.default[key];
if (opt && opt.alias) opt = _config2.default[opt.alias];
if (!opt) continue;
var parser = parsers[opt.type];
if (parser) val = parser(val);
options[key] = val;
}
return options;
}

View File

@@ -0,0 +1,383 @@
"use strict";
exports.__esModule = true;
var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties");
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _stringify = require("babel-runtime/core-js/json/stringify");
var _stringify2 = _interopRequireDefault(_stringify);
var _assign = require("babel-runtime/core-js/object/assign");
var _assign2 = _interopRequireDefault(_assign);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _node = require("../../../api/node");
var context = _interopRequireWildcard(_node);
var _plugin2 = require("../../plugin");
var _plugin3 = _interopRequireDefault(_plugin2);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _index = require("./index");
var _resolvePlugin = require("../../../helpers/resolve-plugin");
var _resolvePlugin2 = _interopRequireDefault(_resolvePlugin);
var _resolvePreset = require("../../../helpers/resolve-preset");
var _resolvePreset2 = _interopRequireDefault(_resolvePreset);
var _cloneDeepWith = require("lodash/cloneDeepWith");
var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
var _merge = require("../../../helpers/merge");
var _merge2 = _interopRequireDefault(_merge);
var _config2 = require("./config");
var _config3 = _interopRequireDefault(_config2);
var _removed = require("./removed");
var _removed2 = _interopRequireDefault(_removed);
var _buildConfigChain = require("./build-config-chain");
var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var OptionManager = function () {
function OptionManager(log) {
(0, _classCallCheck3.default)(this, OptionManager);
this.resolvedConfigs = [];
this.options = OptionManager.createBareOptions();
this.log = log;
}
OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) {
for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var cache = _ref;
if (cache.container === fn) return cache.plugin;
}
var obj = void 0;
if (typeof fn === "function") {
obj = fn(context);
} else {
obj = fn;
}
if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === "object") {
var _plugin = new _plugin3.default(obj, alias);
OptionManager.memoisedPlugins.push({
container: fn,
plugin: _plugin
});
return _plugin;
} else {
throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i);
}
};
OptionManager.createBareOptions = function createBareOptions() {
var opts = {};
for (var _key in _config3.default) {
var opt = _config3.default[_key];
opts[_key] = (0, _clone2.default)(opt.default);
}
return opts;
};
OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) {
plugin = plugin.__esModule ? plugin.default : plugin;
if (!(plugin instanceof _plugin3.default)) {
if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") {
plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias);
} else {
throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)));
}
}
plugin.init(loc, i);
return plugin;
};
OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) {
return plugins.map(function (val, i) {
var plugin = void 0,
options = void 0;
if (!val) {
throw new TypeError("Falsy value found in plugins");
}
if (Array.isArray(val)) {
plugin = val[0];
options = val[1];
} else {
plugin = val;
}
var alias = typeof plugin === "string" ? plugin : loc + "$" + i;
if (typeof plugin === "string") {
var pluginLoc = (0, _resolvePlugin2.default)(plugin, dirname);
if (pluginLoc) {
plugin = require(pluginLoc);
} else {
throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname));
}
}
plugin = OptionManager.normalisePlugin(plugin, loc, i, alias);
return [plugin, options];
});
};
OptionManager.prototype.mergeOptions = function mergeOptions(_ref2) {
var _this = this;
var rawOpts = _ref2.options,
extendingOpts = _ref2.extending,
alias = _ref2.alias,
loc = _ref2.loc,
dirname = _ref2.dirname;
alias = alias || "foreign";
if (!rawOpts) return;
if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) {
this.log.error("Invalid options type for " + alias, TypeError);
}
var opts = (0, _cloneDeepWith2.default)(rawOpts, function (val) {
if (val instanceof _plugin3.default) {
return val;
}
});
dirname = dirname || process.cwd();
loc = loc || alias;
for (var _key2 in opts) {
var option = _config3.default[_key2];
if (!option && this.log) {
if (_removed2.default[_key2]) {
this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2.default[_key2].message, ReferenceError);
} else {
var unknownOptErr = "Unknown option: " + alias + "." + _key2 + ". Check out http://babeljs.io/docs/usage/options/ for more information about options.";
var presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.";
this.log.error(unknownOptErr + "\n\n" + presetConfigErr, ReferenceError);
}
}
}
(0, _index.normaliseOptions)(opts);
if (opts.plugins) {
opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins);
}
if (opts.presets) {
if (opts.passPerPreset) {
opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) {
_this.mergeOptions({
options: preset,
extending: preset,
alias: presetLoc,
loc: presetLoc,
dirname: dirname
});
});
} else {
this.mergePresets(opts.presets, dirname);
delete opts.presets;
}
}
if (rawOpts === extendingOpts) {
(0, _assign2.default)(extendingOpts, opts);
} else {
(0, _merge2.default)(extendingOpts || this.options, opts);
}
};
OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) {
var _this2 = this;
this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) {
_this2.mergeOptions({
options: presetOpts,
alias: presetLoc,
loc: presetLoc,
dirname: _path2.default.dirname(presetLoc || "")
});
});
};
OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) {
return presets.map(function (val) {
var options = void 0;
if (Array.isArray(val)) {
if (val.length > 2) {
throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset.");
}
var _val = val;
val = _val[0];
options = _val[1];
}
var presetLoc = void 0;
try {
if (typeof val === "string") {
presetLoc = (0, _resolvePreset2.default)(val, dirname);
if (!presetLoc) {
throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname));
}
val = require(presetLoc);
}
if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) {
if (val.default) {
val = val.default;
} else {
var _val2 = val,
__esModule = _val2.__esModule,
rest = (0, _objectWithoutProperties3.default)(_val2, ["__esModule"]);
val = rest;
}
}
if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset;
if (typeof val !== "function" && options !== undefined) {
throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options.");
}
if (typeof val === "function") val = val(context, options, { dirname: dirname });
if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") {
throw new Error("Unsupported preset format: " + val + ".");
}
onResolve && onResolve(val, presetLoc);
} catch (e) {
if (presetLoc) {
e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")";
}
throw e;
}
return val;
});
};
OptionManager.prototype.normaliseOptions = function normaliseOptions() {
var opts = this.options;
for (var _key3 in _config3.default) {
var option = _config3.default[_key3];
var val = opts[_key3];
if (!val && option.optional) continue;
if (option.alias) {
opts[option.alias] = opts[option.alias] || val;
} else {
opts[_key3] = val;
}
}
};
OptionManager.prototype.init = function init() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref3;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref3 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref3 = _i2.value;
}
var _config = _ref3;
this.mergeOptions(_config);
}
this.normaliseOptions(opts);
return this.options;
};
return OptionManager;
}();
exports.default = OptionManager;
OptionManager.memoisedPlugins = [];
module.exports = exports["default"];

View File

@@ -0,0 +1,33 @@
"use strict";
exports.__esModule = true;
exports.filename = undefined;
exports.boolean = boolean;
exports.booleanString = booleanString;
exports.list = list;
var _slash = require("slash");
var _slash2 = _interopRequireDefault(_slash);
var _util = require("../../../util");
var util = _interopRequireWildcard(_util);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var filename = exports.filename = _slash2.default;
function boolean(val) {
return !!val;
}
function booleanString(val) {
return util.booleanify(val);
}
function list(val) {
return util.list(val);
}

View File

@@ -0,0 +1,50 @@
"use strict";
module.exports = {
"auxiliaryComment": {
"message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"
},
"blacklist": {
"message": "Put the specific transforms you want in the `plugins` option"
},
"breakConfig": {
"message": "This is not a necessary option in Babel 6"
},
"experimental": {
"message": "Put the specific transforms you want in the `plugins` option"
},
"externalHelpers": {
"message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"
},
"extra": {
"message": ""
},
"jsxPragma": {
"message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/"
},
"loose": {
"message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."
},
"metadataUsedHelpers": {
"message": "Not required anymore as this is enabled by default"
},
"modules": {
"message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules"
},
"nonStandard": {
"message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"
},
"optional": {
"message": "Put the specific transforms you want in the `plugins` option"
},
"sourceMapName": {
"message": "Use the `sourceMapTarget` option"
},
"stage": {
"message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"
},
"whitelist": {
"message": "Put the specific transforms you want in the `plugins` option"
}
};

View File

@@ -0,0 +1,45 @@
"use strict";
exports.__esModule = true;
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _sortBy = require("lodash/sortBy");
var _sortBy2 = _interopRequireDefault(_sortBy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = new _plugin2.default({
name: "internal.blockHoist",
visitor: {
Block: {
exit: function exit(_ref) {
var node = _ref.node;
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true;
break;
}
}
if (!hasChange) return;
node.body = (0, _sortBy2.default)(node.body, function (bodyNode) {
var priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
return -1 * priority;
});
}
}
}
});
module.exports = exports["default"];

View File

@@ -0,0 +1,132 @@
"use strict";
exports.__esModule = true;
var _symbol = require("babel-runtime/core-js/symbol");
var _symbol2 = _interopRequireDefault(_symbol);
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound");
var superVisitor = {
CallExpression: function CallExpression(path) {
if (!path.get("callee").isSuper()) return;
var node = path.node;
if (node[SUPER_THIS_BOUND]) return;
node[SUPER_THIS_BOUND] = true;
path.replaceWith(t.assignmentExpression("=", this.id, node));
}
};
exports.default = new _plugin2.default({
name: "internal.shadowFunctions",
visitor: {
ThisExpression: function ThisExpression(path) {
remap(path, "this");
},
ReferencedIdentifier: function ReferencedIdentifier(path) {
if (path.node.name === "arguments") {
remap(path, "arguments");
}
}
}
});
function shouldShadow(path, shadowPath) {
if (path.is("_forceShadow")) {
return true;
} else {
return shadowPath;
}
}
function remap(path, key) {
var shadowPath = path.inShadow(key);
if (!shouldShadow(path, shadowPath)) return;
var shadowFunction = path.node._shadowedFunctionLiteral;
var currentFunction = void 0;
var passedShadowFunction = false;
var fnPath = path.find(function (innerPath) {
if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") {
return true;
}
if (path === innerPath) return false;
if (innerPath.isProgram() || innerPath.isFunction()) {
currentFunction = currentFunction || innerPath;
}
if (innerPath.isProgram()) {
passedShadowFunction = true;
return true;
} else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) {
if (shadowFunction) {
if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true;
} else {
if (!innerPath.is("shadow")) return true;
}
passedShadowFunction = true;
return false;
}
return false;
});
if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) {
fnPath = path.findParent(function (p) {
return p.isProgram() || p.isFunction();
});
}
if (fnPath === currentFunction) return;
if (!passedShadowFunction) return;
var cached = fnPath.getData(key);
if (cached) return path.replaceWith(cached);
var id = path.scope.generateUidIdentifier(key);
fnPath.setData(key, id);
var classPath = fnPath.findParent(function (p) {
return p.isClass();
});
var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass);
if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) {
fnPath.scope.push({ id: id });
fnPath.traverse(superVisitor, { id: id });
} else {
var init = key === "this" ? t.thisExpression() : t.identifier(key);
if (shadowFunction) init._shadowedFunctionLiteral = shadowFunction;
fnPath.scope.push({ id: id, init: init });
}
return path.replaceWith(id);
}
module.exports = exports["default"];

View File

@@ -0,0 +1,81 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _normalizeAst = require("../helpers/normalize-ast");
var _normalizeAst2 = _interopRequireDefault(_normalizeAst);
var _plugin = require("./plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _file = require("./file");
var _file2 = _interopRequireDefault(_file);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Pipeline = function () {
function Pipeline() {
(0, _classCallCheck3.default)(this, Pipeline);
}
Pipeline.prototype.lint = function lint(code) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
opts.code = false;
opts.mode = "lint";
return this.transform(code, opts);
};
Pipeline.prototype.pretransform = function pretransform(code, opts) {
var file = new _file2.default(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file;
});
};
Pipeline.prototype.transform = function transform(code, opts) {
var file = new _file2.default(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file.transform();
});
};
Pipeline.prototype.analyse = function analyse(code) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var visitor = arguments[2];
opts.code = false;
if (visitor) {
opts.plugins = opts.plugins || [];
opts.plugins.push(new _plugin2.default({ visitor: visitor }));
}
return this.transform(code, opts).metadata;
};
Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) {
ast = (0, _normalizeAst2.default)(ast);
var file = new _file2.default(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.addAst(ast);
return file.transform();
});
};
return Pipeline;
}();
exports.default = Pipeline;
module.exports = exports["default"];

View File

@@ -0,0 +1,71 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
var _store = require("../store");
var _store2 = _interopRequireDefault(_store);
var _file5 = require("./file");
var _file6 = _interopRequireDefault(_file5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PluginPass = function (_Store) {
(0, _inherits3.default)(PluginPass, _Store);
function PluginPass(file, plugin) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
(0, _classCallCheck3.default)(this, PluginPass);
var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this));
_this.plugin = plugin;
_this.key = plugin.key;
_this.file = file;
_this.opts = options;
return _this;
}
PluginPass.prototype.addHelper = function addHelper() {
var _file;
return (_file = this.file).addHelper.apply(_file, arguments);
};
PluginPass.prototype.addImport = function addImport() {
var _file2;
return (_file2 = this.file).addImport.apply(_file2, arguments);
};
PluginPass.prototype.getModuleName = function getModuleName() {
var _file3;
return (_file3 = this.file).getModuleName.apply(_file3, arguments);
};
PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() {
var _file4;
return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments);
};
return PluginPass;
}(_store2.default);
exports.default = PluginPass;
module.exports = exports["default"];

View File

@@ -0,0 +1,163 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
var _optionManager = require("./file/options/option-manager");
var _optionManager2 = _interopRequireDefault(_optionManager);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _store = require("../store");
var _store2 = _interopRequireDefault(_store);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _assign = require("lodash/assign");
var _assign2 = _interopRequireDefault(_assign);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var GLOBAL_VISITOR_PROPS = ["enter", "exit"];
var Plugin = function (_Store) {
(0, _inherits3.default)(Plugin, _Store);
function Plugin(plugin, key) {
(0, _classCallCheck3.default)(this, Plugin);
var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this));
_this.initialized = false;
_this.raw = (0, _assign2.default)({}, plugin);
_this.key = _this.take("name") || key;
_this.manipulateOptions = _this.take("manipulateOptions");
_this.post = _this.take("post");
_this.pre = _this.take("pre");
_this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {});
return _this;
}
Plugin.prototype.take = function take(key) {
var val = this.raw[key];
delete this.raw[key];
return val;
};
Plugin.prototype.chain = function chain(target, key) {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
var fns = [target[key], this[key]];
return function () {
var val = void 0;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var fn = _ref;
if (fn) {
var ret = fn.apply(this, args);
if (ret != null) val = ret;
}
}
return val;
};
};
Plugin.prototype.maybeInherit = function maybeInherit(loc) {
var inherits = this.take("inherits");
if (!inherits) return;
inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits");
this.manipulateOptions = this.chain(inherits, "manipulateOptions");
this.post = this.chain(inherits, "post");
this.pre = this.chain(inherits, "pre");
this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]);
};
Plugin.prototype.init = function init(loc, i) {
if (this.initialized) return;
this.initialized = true;
this.maybeInherit(loc);
for (var key in this.raw) {
throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
}
};
Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) {
for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var key = _ref2;
if (visitor[key]) {
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " + "Please target individual nodes.");
}
}
_babelTraverse2.default.explode(visitor);
return visitor;
};
return Plugin;
}(_store2.default);
exports.default = Plugin;
module.exports = exports["default"];

View File

@@ -0,0 +1,184 @@
"use strict";
exports.__esModule = true;
exports.inspect = exports.inherits = undefined;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _util = require("util");
Object.defineProperty(exports, "inherits", {
enumerable: true,
get: function get() {
return _util.inherits;
}
});
Object.defineProperty(exports, "inspect", {
enumerable: true,
get: function get() {
return _util.inspect;
}
});
exports.canCompile = canCompile;
exports.list = list;
exports.regexify = regexify;
exports.arrayify = arrayify;
exports.booleanify = booleanify;
exports.shouldIgnore = shouldIgnore;
var _escapeRegExp = require("lodash/escapeRegExp");
var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp);
var _startsWith = require("lodash/startsWith");
var _startsWith2 = _interopRequireDefault(_startsWith);
var _minimatch = require("minimatch");
var _minimatch2 = _interopRequireDefault(_minimatch);
var _includes = require("lodash/includes");
var _includes2 = _interopRequireDefault(_includes);
var _isRegExp = require("lodash/isRegExp");
var _isRegExp2 = _interopRequireDefault(_isRegExp);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _slash = require("slash");
var _slash2 = _interopRequireDefault(_slash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function canCompile(filename, altExts) {
var exts = altExts || canCompile.EXTENSIONS;
var ext = _path2.default.extname(filename);
return (0, _includes2.default)(exts, ext);
}
canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];
function list(val) {
if (!val) {
return [];
} else if (Array.isArray(val)) {
return val;
} else if (typeof val === "string") {
return val.split(",");
} else {
return [val];
}
}
function regexify(val) {
if (!val) {
return new RegExp(/.^/);
}
if (Array.isArray(val)) {
val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i");
}
if (typeof val === "string") {
val = (0, _slash2.default)(val);
if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2);
if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3);
var regex = _minimatch2.default.makeRe(val, { nocase: true });
return new RegExp(regex.source.slice(1, -1), "i");
}
if ((0, _isRegExp2.default)(val)) {
return val;
}
throw new TypeError("illegal type for regexify");
}
function arrayify(val, mapFn) {
if (!val) return [];
if (typeof val === "boolean") return arrayify([val], mapFn);
if (typeof val === "string") return arrayify(list(val), mapFn);
if (Array.isArray(val)) {
if (mapFn) val = val.map(mapFn);
return val;
}
return [val];
}
function booleanify(val) {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
function shouldIgnore(filename) {
var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var only = arguments[2];
filename = filename.replace(/\\/g, "/");
if (only) {
for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var pattern = _ref;
if (_shouldIgnore(pattern, filename)) return false;
}
return true;
} else if (ignore.length) {
for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _pattern = _ref2;
if (_shouldIgnore(_pattern, filename)) return true;
}
}
return false;
}
function _shouldIgnore(pattern, filename) {
if (typeof pattern === "function") {
return pattern(filename);
} else {
return pattern.test(filename);
}
}

View File

@@ -0,0 +1,88 @@
{
"name": "babel-core",
"version": "6.25.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"babylon": {
"version": "6.18.0",
"resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz",
"integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ=="
},
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c="
},
"brace-expansion": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz",
"integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=",
"requires": {
"balanced-match": "1.0.0",
"concat-map": "0.0.1"
}
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
},
"convert-source-map": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.0.tgz",
"integrity": "sha1-ms1whRxtXf3ZPZKC5e35SgP/RrU="
},
"debug": {
"version": "2.6.8",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.8.tgz",
"integrity": "sha1-5zFTHKLt4n0YgiJCfaF4IdaP9Pw=",
"requires": {
"ms": "2.0.0"
}
},
"json5": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz",
"integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE="
},
"lodash": {
"version": "4.17.4",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz",
"integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4="
},
"minimatch": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"requires": {
"brace-expansion": "1.1.8"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18="
},
"private": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/private/-/private-0.1.7.tgz",
"integrity": "sha1-aM5eih7woju1cMwoU3tTMqumPvE="
},
"slash": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz",
"integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU="
},
"source-map": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz",
"integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI="
}
}
}

View File

@@ -0,0 +1,90 @@
{
"_args": [
[
"babel-core@6.26.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_development": true,
"_from": "babel-core@6.26.0",
"_id": "babel-core@6.26.0",
"_inBundle": false,
"_integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=",
"_location": "/babel-cli/babel-core",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "babel-core@6.26.0",
"name": "babel-core",
"escapedName": "babel-core",
"rawSpec": "6.26.0",
"saveSpec": null,
"fetchSpec": "6.26.0"
},
"_requiredBy": [
"/babel-cli",
"/babel-cli/babel-register"
],
"_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz",
"_spec": "6.26.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"dependencies": {
"babel-code-frame": "^6.26.0",
"babel-generator": "^6.26.0",
"babel-helpers": "^6.24.1",
"babel-messages": "^6.23.0",
"babel-register": "^6.26.0",
"babel-runtime": "^6.26.0",
"babel-template": "^6.26.0",
"babel-traverse": "^6.26.0",
"babel-types": "^6.26.0",
"babylon": "^6.18.0",
"convert-source-map": "^1.5.0",
"debug": "^2.6.8",
"json5": "^0.5.1",
"lodash": "^4.17.4",
"minimatch": "^3.0.4",
"path-is-absolute": "^1.0.1",
"private": "^0.1.7",
"slash": "^1.0.0",
"source-map": "^0.5.6"
},
"description": "Babel compiler core.",
"devDependencies": {
"babel-helper-fixtures": "^6.26.0",
"babel-helper-transform-fixture-test-runner": "^6.26.0",
"babel-polyfill": "^6.26.0"
},
"homepage": "https://babeljs.io/",
"keywords": [
"6to5",
"babel",
"classes",
"const",
"es6",
"harmony",
"let",
"modules",
"transpile",
"transpiler",
"var",
"babel-core",
"compiler"
],
"license": "MIT",
"name": "babel-core",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-core"
},
"scripts": {
"bench": "make bench",
"test": "make test"
},
"version": "6.26.0"
}

View File

@@ -0,0 +1,3 @@
/* eslint max-len: 0 */
// TODO: eventually deprecate this console.trace("use the `babel-register` package instead of `babel-core/register`");
module.exports = require("babel-register");

View File

@@ -0,0 +1,81 @@
# babel-generator
> Turns an AST into code.
## Install
```sh
npm install --save-dev babel-generator
```
## Usage
```js
import {parse} from 'babylon';
import generate from 'babel-generator';
const code = 'class Example {}';
const ast = parse(code);
const output = generate(ast, { /* options */ }, code);
```
## Options
Options for formatting output:
name | type | default | description
-----------------------|----------|-----------------|--------------------------------------------------------------------------
auxiliaryCommentBefore | string | | Optional string to add as a block comment at the start of the output file
auxiliaryCommentAfter | string | | Optional string to add as a block comment at the end of the output file
shouldPrintComment | function | `opts.comments` | Function that takes a comment (as a string) and returns `true` if the comment should be included in the output. By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment contains `@preserve` or `@license`
retainLines | boolean | `false` | Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces)
retainFunctionParens | boolean | `false` | Retain parens around function expressions (could be used to change engine parsing behavior)
comments | boolean | `true` | Should comments be included in output
compact | boolean or `'auto'` | `opts.minified` | Set to `true` to avoid adding whitespace for formatting
minified | boolean | `false` | Should the output be minified
concise | boolean | `false` | Set to `true` to reduce whitespace (but not as much as `opts.compact`)
quotes | `'single'` or `'double'` | autodetect based on `ast.tokens` | The type of quote to use in the output
filename | string | | Used in warning messages
flowCommaSeparator | boolean | `false` | Set to `true` to use commas instead of semicolons as Flow property separators
jsonCompatibleStrings | boolean | `false` | Set to true to run `jsesc` with "json": true to print "\u00A9" vs. "©";
Options for source maps:
name | type | default | description
-----------------------|----------|-----------------|--------------------------------------------------------------------------
sourceMaps | boolean | `false` | Enable generating source maps
sourceMapTarget | string | | The filename of the generated code that the source map will be associated with
sourceRoot | string | | A root for all relative URLs in the source map
sourceFileName | string | | The filename for the source code (i.e. the code in the `code` argument). This will only be used if `code` is a string.
## AST from Multiple Sources
In most cases, Babel does a 1:1 transformation of input-file to output-file. However,
you may be dealing with AST constructed from multiple sources - JS files, templates, etc.
If this is the case, and you want the sourcemaps to reflect the correct sources, you'll need
to pass an object to `generate` as the `code` parameter. Keys
should be the source filenames, and values should be the source content.
Here's an example of what that might look like:
```js
import {parse} from 'babylon';
import generate from 'babel-generator';
const a = 'var a = 1;';
const b = 'var b = 2;';
const astA = parse(a, { sourceFilename: 'a.js' });
const astB = parse(b, { sourceFilename: 'b.js' });
const ast = {
type: 'Program',
body: [].concat(astA.program.body, astB.program.body)
};
const { code, map } = generate(ast, { sourceMaps: true }, {
'a.js': a,
'b.js': b
});
// Sourcemap will point to both a.js and b.js where appropriate.
```

View File

@@ -0,0 +1,202 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _trimRight = require("trim-right");
var _trimRight2 = _interopRequireDefault(_trimRight);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var SPACES_RE = /^[ \t]+$/;
var Buffer = function () {
function Buffer(map) {
(0, _classCallCheck3.default)(this, Buffer);
this._map = null;
this._buf = [];
this._last = "";
this._queue = [];
this._position = {
line: 1,
column: 0
};
this._sourcePosition = {
identifierName: null,
line: null,
column: null,
filename: null
};
this._map = map;
}
Buffer.prototype.get = function get() {
this._flush();
var map = this._map;
var result = {
code: (0, _trimRight2.default)(this._buf.join("")),
map: null,
rawMappings: map && map.getRawMappings()
};
if (map) {
Object.defineProperty(result, "map", {
configurable: true,
enumerable: true,
get: function get() {
return this.map = map.get();
},
set: function set(value) {
Object.defineProperty(this, "map", { value: value, writable: true });
}
});
}
return result;
};
Buffer.prototype.append = function append(str) {
this._flush();
var _sourcePosition = this._sourcePosition,
line = _sourcePosition.line,
column = _sourcePosition.column,
filename = _sourcePosition.filename,
identifierName = _sourcePosition.identifierName;
this._append(str, line, column, identifierName, filename);
};
Buffer.prototype.queue = function queue(str) {
if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) {
this._queue.shift();
}var _sourcePosition2 = this._sourcePosition,
line = _sourcePosition2.line,
column = _sourcePosition2.column,
filename = _sourcePosition2.filename,
identifierName = _sourcePosition2.identifierName;
this._queue.unshift([str, line, column, identifierName, filename]);
};
Buffer.prototype._flush = function _flush() {
var item = void 0;
while (item = this._queue.pop()) {
this._append.apply(this, item);
}
};
Buffer.prototype._append = function _append(str, line, column, identifierName, filename) {
if (this._map && str[0] !== "\n") {
this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename);
}
this._buf.push(str);
this._last = str[str.length - 1];
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this._position.line++;
this._position.column = 0;
} else {
this._position.column++;
}
}
};
Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() {
if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift();
};
Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() {
if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift();
};
Buffer.prototype.endsWith = function endsWith(suffix) {
if (suffix.length === 1) {
var last = void 0;
if (this._queue.length > 0) {
var str = this._queue[0][0];
last = str[str.length - 1];
} else {
last = this._last;
}
return last === suffix;
}
var end = this._last + this._queue.reduce(function (acc, item) {
return item[0] + acc;
}, "");
if (suffix.length <= end.length) {
return end.slice(-suffix.length) === suffix;
}
return false;
};
Buffer.prototype.hasContent = function hasContent() {
return this._queue.length > 0 || !!this._last;
};
Buffer.prototype.source = function source(prop, loc) {
if (prop && !loc) return;
var pos = loc ? loc[prop] : null;
this._sourcePosition.identifierName = loc && loc.identifierName || null;
this._sourcePosition.line = pos ? pos.line : null;
this._sourcePosition.column = pos ? pos.column : null;
this._sourcePosition.filename = loc && loc.filename || null;
};
Buffer.prototype.withSource = function withSource(prop, loc, cb) {
if (!this._map) return cb();
var originalLine = this._sourcePosition.line;
var originalColumn = this._sourcePosition.column;
var originalFilename = this._sourcePosition.filename;
var originalIdentifierName = this._sourcePosition.identifierName;
this.source(prop, loc);
cb();
this._sourcePosition.line = originalLine;
this._sourcePosition.column = originalColumn;
this._sourcePosition.filename = originalFilename;
this._sourcePosition.identifierName = originalIdentifierName;
};
Buffer.prototype.getCurrentColumn = function getCurrentColumn() {
var extra = this._queue.reduce(function (acc, item) {
return item[0] + acc;
}, "");
var lastIndex = extra.lastIndexOf("\n");
return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex;
};
Buffer.prototype.getCurrentLine = function getCurrentLine() {
var extra = this._queue.reduce(function (acc, item) {
return item[0] + acc;
}, "");
var count = 0;
for (var i = 0; i < extra.length; i++) {
if (extra[i] === "\n") count++;
}
return this._position.line + count;
};
return Buffer;
}();
exports.default = Buffer;
module.exports = exports["default"];

View File

@@ -0,0 +1,62 @@
"use strict";
exports.__esModule = true;
exports.File = File;
exports.Program = Program;
exports.BlockStatement = BlockStatement;
exports.Noop = Noop;
exports.Directive = Directive;
var _types = require("./types");
Object.defineProperty(exports, "DirectiveLiteral", {
enumerable: true,
get: function get() {
return _types.StringLiteral;
}
});
function File(node) {
this.print(node.program, node);
}
function Program(node) {
this.printInnerComments(node, false);
this.printSequence(node.directives, node);
if (node.directives && node.directives.length) this.newline();
this.printSequence(node.body, node);
}
function BlockStatement(node) {
this.token("{");
this.printInnerComments(node);
var hasDirectives = node.directives && node.directives.length;
if (node.body.length || hasDirectives) {
this.newline();
this.printSequence(node.directives, node, { indent: true });
if (hasDirectives) this.newline();
this.printSequence(node.body, node, { indent: true });
this.removeTrailingNewline();
this.source("end", node.loc);
if (!this.endsWith("\n")) this.newline();
this.rightBrace();
} else {
this.source("end", node.loc);
this.token("}");
}
}
function Noop() {}
function Directive(node) {
this.print(node.value, node);
this.semicolon();
}

View File

@@ -0,0 +1,96 @@
"use strict";
exports.__esModule = true;
exports.ClassDeclaration = ClassDeclaration;
exports.ClassBody = ClassBody;
exports.ClassProperty = ClassProperty;
exports.ClassMethod = ClassMethod;
function ClassDeclaration(node) {
this.printJoin(node.decorators, node);
this.word("class");
if (node.id) {
this.space();
this.print(node.id, node);
}
this.print(node.typeParameters, node);
if (node.superClass) {
this.space();
this.word("extends");
this.space();
this.print(node.superClass, node);
this.print(node.superTypeParameters, node);
}
if (node.implements) {
this.space();
this.word("implements");
this.space();
this.printList(node.implements, node);
}
this.space();
this.print(node.body, node);
}
exports.ClassExpression = ClassDeclaration;
function ClassBody(node) {
this.token("{");
this.printInnerComments(node);
if (node.body.length === 0) {
this.token("}");
} else {
this.newline();
this.indent();
this.printSequence(node.body, node);
this.dedent();
if (!this.endsWith("\n")) this.newline();
this.rightBrace();
}
}
function ClassProperty(node) {
this.printJoin(node.decorators, node);
if (node.static) {
this.word("static");
this.space();
}
if (node.computed) {
this.token("[");
this.print(node.key, node);
this.token("]");
} else {
this._variance(node);
this.print(node.key, node);
}
this.print(node.typeAnnotation, node);
if (node.value) {
this.space();
this.token("=");
this.space();
this.print(node.value, node);
}
this.semicolon();
}
function ClassMethod(node) {
this.printJoin(node.decorators, node);
if (node.static) {
this.word("static");
this.space();
}
if (node.kind === "constructorCall") {
this.word("call");
this.space();
}
this._method(node);
}

View File

@@ -0,0 +1,241 @@
"use strict";
exports.__esModule = true;
exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined;
exports.UnaryExpression = UnaryExpression;
exports.DoExpression = DoExpression;
exports.ParenthesizedExpression = ParenthesizedExpression;
exports.UpdateExpression = UpdateExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.NewExpression = NewExpression;
exports.SequenceExpression = SequenceExpression;
exports.ThisExpression = ThisExpression;
exports.Super = Super;
exports.Decorator = Decorator;
exports.CallExpression = CallExpression;
exports.Import = Import;
exports.EmptyStatement = EmptyStatement;
exports.ExpressionStatement = ExpressionStatement;
exports.AssignmentPattern = AssignmentPattern;
exports.AssignmentExpression = AssignmentExpression;
exports.BindExpression = BindExpression;
exports.MemberExpression = MemberExpression;
exports.MetaProperty = MetaProperty;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _node = require("../node");
var n = _interopRequireWildcard(_node);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function UnaryExpression(node) {
if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") {
this.word(node.operator);
this.space();
} else {
this.token(node.operator);
}
this.print(node.argument, node);
}
function DoExpression(node) {
this.word("do");
this.space();
this.print(node.body, node);
}
function ParenthesizedExpression(node) {
this.token("(");
this.print(node.expression, node);
this.token(")");
}
function UpdateExpression(node) {
if (node.prefix) {
this.token(node.operator);
this.print(node.argument, node);
} else {
this.print(node.argument, node);
this.token(node.operator);
}
}
function ConditionalExpression(node) {
this.print(node.test, node);
this.space();
this.token("?");
this.space();
this.print(node.consequent, node);
this.space();
this.token(":");
this.space();
this.print(node.alternate, node);
}
function NewExpression(node, parent) {
this.word("new");
this.space();
this.print(node.callee, node);
if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return;
this.token("(");
this.printList(node.arguments, node);
this.token(")");
}
function SequenceExpression(node) {
this.printList(node.expressions, node);
}
function ThisExpression() {
this.word("this");
}
function Super() {
this.word("super");
}
function Decorator(node) {
this.token("@");
this.print(node.expression, node);
this.newline();
}
function commaSeparatorNewline() {
this.token(",");
this.newline();
if (!this.endsWith("\n")) this.space();
}
function CallExpression(node) {
this.print(node.callee, node);
this.token("(");
var isPrettyCall = node._prettyCall;
var separator = void 0;
if (isPrettyCall) {
separator = commaSeparatorNewline;
this.newline();
this.indent();
}
this.printList(node.arguments, node, { separator: separator });
if (isPrettyCall) {
this.newline();
this.dedent();
}
this.token(")");
}
function Import() {
this.word("import");
}
function buildYieldAwait(keyword) {
return function (node) {
this.word(keyword);
if (node.delegate) {
this.token("*");
}
if (node.argument) {
this.space();
var terminatorState = this.startTerminatorless();
this.print(node.argument, node);
this.endTerminatorless(terminatorState);
}
};
}
var YieldExpression = exports.YieldExpression = buildYieldAwait("yield");
var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await");
function EmptyStatement() {
this.semicolon(true);
}
function ExpressionStatement(node) {
this.print(node.expression, node);
this.semicolon();
}
function AssignmentPattern(node) {
this.print(node.left, node);
if (node.left.optional) this.token("?");
this.print(node.left.typeAnnotation, node);
this.space();
this.token("=");
this.space();
this.print(node.right, node);
}
function AssignmentExpression(node, parent) {
var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent);
if (parens) {
this.token("(");
}
this.print(node.left, node);
this.space();
if (node.operator === "in" || node.operator === "instanceof") {
this.word(node.operator);
} else {
this.token(node.operator);
}
this.space();
this.print(node.right, node);
if (parens) {
this.token(")");
}
}
function BindExpression(node) {
this.print(node.object, node);
this.token("::");
this.print(node.callee, node);
}
exports.BinaryExpression = AssignmentExpression;
exports.LogicalExpression = AssignmentExpression;
function MemberExpression(node) {
this.print(node.object, node);
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
var computed = node.computed;
if (t.isLiteral(node.property) && typeof node.property.value === "number") {
computed = true;
}
if (computed) {
this.token("[");
this.print(node.property, node);
this.token("]");
} else {
this.token(".");
this.print(node.property, node);
}
}
function MetaProperty(node) {
this.print(node.meta, node);
this.token(".");
this.print(node.property, node);
}

View File

@@ -0,0 +1,504 @@
"use strict";
exports.__esModule = true;
exports.TypeParameterDeclaration = exports.StringLiteralTypeAnnotation = exports.NumericLiteralTypeAnnotation = exports.GenericTypeAnnotation = exports.ClassImplements = undefined;
exports.AnyTypeAnnotation = AnyTypeAnnotation;
exports.ArrayTypeAnnotation = ArrayTypeAnnotation;
exports.BooleanTypeAnnotation = BooleanTypeAnnotation;
exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation;
exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation;
exports.DeclareClass = DeclareClass;
exports.DeclareFunction = DeclareFunction;
exports.DeclareInterface = DeclareInterface;
exports.DeclareModule = DeclareModule;
exports.DeclareModuleExports = DeclareModuleExports;
exports.DeclareTypeAlias = DeclareTypeAlias;
exports.DeclareOpaqueType = DeclareOpaqueType;
exports.DeclareVariable = DeclareVariable;
exports.DeclareExportDeclaration = DeclareExportDeclaration;
exports.ExistentialTypeParam = ExistentialTypeParam;
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
exports.FunctionTypeParam = FunctionTypeParam;
exports.InterfaceExtends = InterfaceExtends;
exports._interfaceish = _interfaceish;
exports._variance = _variance;
exports.InterfaceDeclaration = InterfaceDeclaration;
exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation;
exports.MixedTypeAnnotation = MixedTypeAnnotation;
exports.EmptyTypeAnnotation = EmptyTypeAnnotation;
exports.NullableTypeAnnotation = NullableTypeAnnotation;
var _types = require("./types");
Object.defineProperty(exports, "NumericLiteralTypeAnnotation", {
enumerable: true,
get: function get() {
return _types.NumericLiteral;
}
});
Object.defineProperty(exports, "StringLiteralTypeAnnotation", {
enumerable: true,
get: function get() {
return _types.StringLiteral;
}
});
exports.NumberTypeAnnotation = NumberTypeAnnotation;
exports.StringTypeAnnotation = StringTypeAnnotation;
exports.ThisTypeAnnotation = ThisTypeAnnotation;
exports.TupleTypeAnnotation = TupleTypeAnnotation;
exports.TypeofTypeAnnotation = TypeofTypeAnnotation;
exports.TypeAlias = TypeAlias;
exports.OpaqueType = OpaqueType;
exports.TypeAnnotation = TypeAnnotation;
exports.TypeParameter = TypeParameter;
exports.TypeParameterInstantiation = TypeParameterInstantiation;
exports.ObjectTypeAnnotation = ObjectTypeAnnotation;
exports.ObjectTypeCallProperty = ObjectTypeCallProperty;
exports.ObjectTypeIndexer = ObjectTypeIndexer;
exports.ObjectTypeProperty = ObjectTypeProperty;
exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty;
exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier;
exports.UnionTypeAnnotation = UnionTypeAnnotation;
exports.TypeCastExpression = TypeCastExpression;
exports.VoidTypeAnnotation = VoidTypeAnnotation;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function AnyTypeAnnotation() {
this.word("any");
}
function ArrayTypeAnnotation(node) {
this.print(node.elementType, node);
this.token("[");
this.token("]");
}
function BooleanTypeAnnotation() {
this.word("boolean");
}
function BooleanLiteralTypeAnnotation(node) {
this.word(node.value ? "true" : "false");
}
function NullLiteralTypeAnnotation() {
this.word("null");
}
function DeclareClass(node, parent) {
if (!t.isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.word("class");
this.space();
this._interfaceish(node);
}
function DeclareFunction(node, parent) {
if (!t.isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.word("function");
this.space();
this.print(node.id, node);
this.print(node.id.typeAnnotation.typeAnnotation, node);
this.semicolon();
}
function DeclareInterface(node) {
this.word("declare");
this.space();
this.InterfaceDeclaration(node);
}
function DeclareModule(node) {
this.word("declare");
this.space();
this.word("module");
this.space();
this.print(node.id, node);
this.space();
this.print(node.body, node);
}
function DeclareModuleExports(node) {
this.word("declare");
this.space();
this.word("module");
this.token(".");
this.word("exports");
this.print(node.typeAnnotation, node);
}
function DeclareTypeAlias(node) {
this.word("declare");
this.space();
this.TypeAlias(node);
}
function DeclareOpaqueType(node, parent) {
if (!t.isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.OpaqueType(node);
}
function DeclareVariable(node, parent) {
if (!t.isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.word("var");
this.space();
this.print(node.id, node);
this.print(node.id.typeAnnotation, node);
this.semicolon();
}
function DeclareExportDeclaration(node) {
this.word("declare");
this.space();
this.word("export");
this.space();
if (node.default) {
this.word("default");
this.space();
}
FlowExportDeclaration.apply(this, arguments);
}
function FlowExportDeclaration(node) {
if (node.declaration) {
var declar = node.declaration;
this.print(declar, node);
if (!t.isStatement(declar)) this.semicolon();
} else {
this.token("{");
if (node.specifiers.length) {
this.space();
this.printList(node.specifiers, node);
this.space();
}
this.token("}");
if (node.source) {
this.space();
this.word("from");
this.space();
this.print(node.source, node);
}
this.semicolon();
}
}
function ExistentialTypeParam() {
this.token("*");
}
function FunctionTypeAnnotation(node, parent) {
this.print(node.typeParameters, node);
this.token("(");
this.printList(node.params, node);
if (node.rest) {
if (node.params.length) {
this.token(",");
this.space();
}
this.token("...");
this.print(node.rest, node);
}
this.token(")");
if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") {
this.token(":");
} else {
this.space();
this.token("=>");
}
this.space();
this.print(node.returnType, node);
}
function FunctionTypeParam(node) {
this.print(node.name, node);
if (node.optional) this.token("?");
this.token(":");
this.space();
this.print(node.typeAnnotation, node);
}
function InterfaceExtends(node) {
this.print(node.id, node);
this.print(node.typeParameters, node);
}
exports.ClassImplements = InterfaceExtends;
exports.GenericTypeAnnotation = InterfaceExtends;
function _interfaceish(node) {
this.print(node.id, node);
this.print(node.typeParameters, node);
if (node.extends.length) {
this.space();
this.word("extends");
this.space();
this.printList(node.extends, node);
}
if (node.mixins && node.mixins.length) {
this.space();
this.word("mixins");
this.space();
this.printList(node.mixins, node);
}
this.space();
this.print(node.body, node);
}
function _variance(node) {
if (node.variance === "plus") {
this.token("+");
} else if (node.variance === "minus") {
this.token("-");
}
}
function InterfaceDeclaration(node) {
this.word("interface");
this.space();
this._interfaceish(node);
}
function andSeparator() {
this.space();
this.token("&");
this.space();
}
function IntersectionTypeAnnotation(node) {
this.printJoin(node.types, node, { separator: andSeparator });
}
function MixedTypeAnnotation() {
this.word("mixed");
}
function EmptyTypeAnnotation() {
this.word("empty");
}
function NullableTypeAnnotation(node) {
this.token("?");
this.print(node.typeAnnotation, node);
}
function NumberTypeAnnotation() {
this.word("number");
}
function StringTypeAnnotation() {
this.word("string");
}
function ThisTypeAnnotation() {
this.word("this");
}
function TupleTypeAnnotation(node) {
this.token("[");
this.printList(node.types, node);
this.token("]");
}
function TypeofTypeAnnotation(node) {
this.word("typeof");
this.space();
this.print(node.argument, node);
}
function TypeAlias(node) {
this.word("type");
this.space();
this.print(node.id, node);
this.print(node.typeParameters, node);
this.space();
this.token("=");
this.space();
this.print(node.right, node);
this.semicolon();
}
function OpaqueType(node) {
this.word("opaque");
this.space();
this.word("type");
this.space();
this.print(node.id, node);
this.print(node.typeParameters, node);
if (node.supertype) {
this.token(":");
this.space();
this.print(node.supertype, node);
}
if (node.impltype) {
this.space();
this.token("=");
this.space();
this.print(node.impltype, node);
}
this.semicolon();
}
function TypeAnnotation(node) {
this.token(":");
this.space();
if (node.optional) this.token("?");
this.print(node.typeAnnotation, node);
}
function TypeParameter(node) {
this._variance(node);
this.word(node.name);
if (node.bound) {
this.print(node.bound, node);
}
if (node.default) {
this.space();
this.token("=");
this.space();
this.print(node.default, node);
}
}
function TypeParameterInstantiation(node) {
this.token("<");
this.printList(node.params, node, {});
this.token(">");
}
exports.TypeParameterDeclaration = TypeParameterInstantiation;
function ObjectTypeAnnotation(node) {
var _this = this;
if (node.exact) {
this.token("{|");
} else {
this.token("{");
}
var props = node.properties.concat(node.callProperties, node.indexers);
if (props.length) {
this.space();
this.printJoin(props, node, {
addNewlines: function addNewlines(leading) {
if (leading && !props[0]) return 1;
},
indent: true,
statement: true,
iterator: function iterator() {
if (props.length !== 1) {
if (_this.format.flowCommaSeparator) {
_this.token(",");
} else {
_this.semicolon();
}
_this.space();
}
}
});
this.space();
}
if (node.exact) {
this.token("|}");
} else {
this.token("}");
}
}
function ObjectTypeCallProperty(node) {
if (node.static) {
this.word("static");
this.space();
}
this.print(node.value, node);
}
function ObjectTypeIndexer(node) {
if (node.static) {
this.word("static");
this.space();
}
this._variance(node);
this.token("[");
this.print(node.id, node);
this.token(":");
this.space();
this.print(node.key, node);
this.token("]");
this.token(":");
this.space();
this.print(node.value, node);
}
function ObjectTypeProperty(node) {
if (node.static) {
this.word("static");
this.space();
}
this._variance(node);
this.print(node.key, node);
if (node.optional) this.token("?");
this.token(":");
this.space();
this.print(node.value, node);
}
function ObjectTypeSpreadProperty(node) {
this.token("...");
this.print(node.argument, node);
}
function QualifiedTypeIdentifier(node) {
this.print(node.qualification, node);
this.token(".");
this.print(node.id, node);
}
function orSeparator() {
this.space();
this.token("|");
this.space();
}
function UnionTypeAnnotation(node) {
this.printJoin(node.types, node, { separator: orSeparator });
}
function TypeCastExpression(node) {
this.token("(");
this.print(node.expression, node);
this.print(node.typeAnnotation, node);
this.token(")");
}
function VoidTypeAnnotation() {
this.word("void");
}

View File

@@ -0,0 +1,124 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.JSXAttribute = JSXAttribute;
exports.JSXIdentifier = JSXIdentifier;
exports.JSXNamespacedName = JSXNamespacedName;
exports.JSXMemberExpression = JSXMemberExpression;
exports.JSXSpreadAttribute = JSXSpreadAttribute;
exports.JSXExpressionContainer = JSXExpressionContainer;
exports.JSXSpreadChild = JSXSpreadChild;
exports.JSXText = JSXText;
exports.JSXElement = JSXElement;
exports.JSXOpeningElement = JSXOpeningElement;
exports.JSXClosingElement = JSXClosingElement;
exports.JSXEmptyExpression = JSXEmptyExpression;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function JSXAttribute(node) {
this.print(node.name, node);
if (node.value) {
this.token("=");
this.print(node.value, node);
}
}
function JSXIdentifier(node) {
this.word(node.name);
}
function JSXNamespacedName(node) {
this.print(node.namespace, node);
this.token(":");
this.print(node.name, node);
}
function JSXMemberExpression(node) {
this.print(node.object, node);
this.token(".");
this.print(node.property, node);
}
function JSXSpreadAttribute(node) {
this.token("{");
this.token("...");
this.print(node.argument, node);
this.token("}");
}
function JSXExpressionContainer(node) {
this.token("{");
this.print(node.expression, node);
this.token("}");
}
function JSXSpreadChild(node) {
this.token("{");
this.token("...");
this.print(node.expression, node);
this.token("}");
}
function JSXText(node) {
this.token(node.value);
}
function JSXElement(node) {
var open = node.openingElement;
this.print(open, node);
if (open.selfClosing) return;
this.indent();
for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var child = _ref;
this.print(child, node);
}
this.dedent();
this.print(node.closingElement, node);
}
function spaceSeparator() {
this.space();
}
function JSXOpeningElement(node) {
this.token("<");
this.print(node.name, node);
if (node.attributes.length > 0) {
this.space();
this.printJoin(node.attributes, node, { separator: spaceSeparator });
}
if (node.selfClosing) {
this.space();
this.token("/>");
} else {
this.token(">");
}
}
function JSXClosingElement(node) {
this.token("</");
this.print(node.name, node);
this.token(">");
}
function JSXEmptyExpression() {}

View File

@@ -0,0 +1,111 @@
"use strict";
exports.__esModule = true;
exports.FunctionDeclaration = undefined;
exports._params = _params;
exports._method = _method;
exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _params(node) {
var _this = this;
this.print(node.typeParameters, node);
this.token("(");
this.printList(node.params, node, {
iterator: function iterator(node) {
if (node.optional) _this.token("?");
_this.print(node.typeAnnotation, node);
}
});
this.token(")");
if (node.returnType) {
this.print(node.returnType, node);
}
}
function _method(node) {
var kind = node.kind;
var key = node.key;
if (kind === "method" || kind === "init") {
if (node.generator) {
this.token("*");
}
}
if (kind === "get" || kind === "set") {
this.word(kind);
this.space();
}
if (node.async) {
this.word("async");
this.space();
}
if (node.computed) {
this.token("[");
this.print(key, node);
this.token("]");
} else {
this.print(key, node);
}
this._params(node);
this.space();
this.print(node.body, node);
}
function FunctionExpression(node) {
if (node.async) {
this.word("async");
this.space();
}
this.word("function");
if (node.generator) this.token("*");
if (node.id) {
this.space();
this.print(node.id, node);
} else {
this.space();
}
this._params(node);
this.space();
this.print(node.body, node);
}
exports.FunctionDeclaration = FunctionExpression;
function ArrowFunctionExpression(node) {
if (node.async) {
this.word("async");
this.space();
}
var firstParam = node.params[0];
if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) {
this.print(firstParam, node);
} else {
this._params(node);
}
this.space();
this.token("=>");
this.space();
this.print(node.body, node);
}
function hasTypes(node, param) {
return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments;
}

Some files were not shown because too many files have changed in this diff Show More