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

169
goTorrentWebUI/node_modules/babel-loader/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,169 @@
# Changelog
For changes in version v7.0.0 and up please go to [release](https://github.com/babel/babel-loader/releases)
# Old Changelog
## v6.4.1
### 🐛 Bug Fix
- Fixed reset of BABEL_ENV when options.forceEnv is used (#420) @nikopavlica
## v6.4.0
### 🚀 New Feature
- added metadata passing from babel to webpack, which is currently used by react-intl (#398) @Ognian
## v6.3.2
### 😢 Regression
- `forceEnv` was interfering with regular environment handling
## v6.3.1
### 🐛 Bug Fix
- The new `forceEnv` options wasn't working as expected (#379) @chrisvasz
## v6.3.0
### 🚀 New Feature
- Add new config option `forceEnv` (#368) @moimael
Allow to override BABEL_ENV/NODE_ENV at loader-level. Useful for isomorphic applications which have separate babel config for client and server.
### 🐛 Bug Fix
- Update loader-utils dependency to ^0.2.16 to fix compatibility with webpack 2 (#371) @leonaves
### 💅 Polish
- Improve FS caching to do less sync calls which improves performance slightly (#375) @akx
## v6.2.10
Support for webpack 2.2-rc has been added in this release
### 🐛 Bug Fix
- If cache directory not writable, try to fallback to tmpdir before failing
## v6.2.9
### 😢 Regression
Source maps on windows did not work correctly with v6.2.8.
Thanks @josephst
### 🏠 Internal
- Add AppVeyor to run tests on windows @danez
- Fix tests on windows (#343) @danez
## v6.2.8
### 🐛 Bug Fix
- gzipped files should have `.gz` as the extension, not `.gzip` (#326) @bjornstar
- fix options.sourceFileName gennerate bug (#260) @creeperyang
### 📝 Documentation
- Update README docs for cacheDirectory's actual behaviour (#245) @sohkai
- updates docs re: transform-runtime (#197) @gbrassey
### 🏠 Internal
- Use eslint and nyc (#321) @danez
- Adjust travis config (#320) @danez
- Use babel to compile babel-loader (#319) @danez
## v6.2.7
### 😢 Regression
Fallback to `os.tmpdir()` if no cachedir found (#318) (fixes #317) @danez
Fixes an issue with v6.2.6 when using `babel-loader` as a global package.
## v6.2.6
### 🐛 Bug Fix
- Use standard cache dir as default `cacheDirectory` (#301) @fson
Use the common cache directory, `./node_modules/.cache/babel-loader`, as the default cache directory (when the cacheDirectory setting is enabled).
```js
query: {
cacheDirectory: true
}
```
## v6.2.5
- Don't show the call stack for a Babel error (such as when you have a syntax error)
<img width="415" alt="screenshot 2016-08-15 15 24 37" src="https://cloud.githubusercontent.com/assets/30594/17664401/727ba098-62fc-11e6-9f12-42da0cf47f14.png">
- resolve the .babelrc relative to the file path rather than the cwd (current working directory).
* fix: more concise formatting for Babel errors (#287) (Andrey Popp)
* fix(resolve-rc): resolve-rc relative file path (#253) (Luke Page)
* add babel-core and preset-2015 to dev dependencies (#273) (timse)
* chore(docs): add issue and pr templates (#280) (Joshua Wiens)
* chore(docs): fix badge formatting (Joshua Wiens)
* chore(ci): expand travis testing (#278) (Joshua Wiens)
* Update README: add env vars to cacheIdentifier (#267) (Dominik Ferber)
* add npm badge [skip ci] (Henry Zhu)
* update [skip ci] (Henry Zhu)
* remove jsx references as well [skip ci] (Henry Zhu)
* Save the transform to devDependencies (Ray Booysen)
* Remove 'react' preset (Jake Rios)
* Removed babel-preset-react from README.md (Ben Stephenson)
## v6.2.4
* change allowed peer deps (all webpack 2 beta versions)
## v6.2.3
* change allowed peer deps (2.0.7-beta)
## v6.2.2
* Update peerDependencies to accept webpack 2 [#208](https://github.com/babel/babel-loader/pull/208)
* Remove duplicated dependencies
## v6.2.0
* Pass true filenames [#106](https://github.com/babel/babel-loader/issues/106)
* Remove babel-core from devDependencies
## v6.1.0
* Merge [PR #146](https://github.com/babel/babel-loader/pull/146) Set source file name relative to options.sourceRoot
* Merge [PR #136](https://github.com/babel/babel-loader/pull/136) use container-based infrastructure for faster build
* Merge [PR #121](https://github.com/babel/babel-loader/pull/121) Make babelrc configurable
* Merge [PR #113](https://github.com/babel/babel-loader/pull/113) Include BABEL_ENV || NODE_ENV in cacheIdentifier
## v6.0.1
* Update to babel v6.
## v5.3.1
* Merge [PR #85](https://github.com/babel/babel-loader/pull/85) - Don't override sourcemap if sourcesContent already exists.
## v5.3.1
* Merge [PR #82](https://github.com/babel/babel-loader/pull/82) - Fallback global options to empty object to avoid conflicts with object-assign polyfill.
## v5.3.0
* Merge [PR #79](https://github.com/babel/babel-loader/pull/79) - This should allow babel-loader to work with [enhanced-require](https://github.com/webpack/enhanced-require).
## v5.2.0
* Include `.babelrc` file into the `cacheIdentifier` if it exists

22
goTorrentWebUI/node_modules/babel-loader/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
Copyright (c) 2014-2016 Luís Couto <hello@luiscouto.pt>
MIT License
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.

208
goTorrentWebUI/node_modules/babel-loader/README.md generated vendored Normal file
View File

@@ -0,0 +1,208 @@
[![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader)
[![Build Status](https://travis-ci.org/babel/babel-loader.svg?branch=master)](https://travis-ci.org/babel/babel-loader)
[![Build Status](https://ci.appveyor.com/api/projects/status/vgtpr2i5bykgyuqo/branch/master?svg=true)](https://ci.appveyor.com/project/danez/babel-loader/branch/master)
[![codecov](https://codecov.io/gh/babel/babel-loader/branch/master/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader)
<div align="center">
<a href="https://github.com/babel/babel/">
<img width="200" height="200" src="https://rawgit.com/babel/logo/master/babel.svg">
</a>
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<h1>Babel Loader</h1>
</div>
This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
__Notes:__ Issues with the output should be reported on the babel [issue tracker](https://github.com/babel/babel/issues).
<h2 align="center">Install</h2>
> webpack 1.x | babel-loader <= 6.x
>
> webpack 2.x | babel-loader >= 7.x (recommended) (^6.2.10 will also work, but with deprecation warnings)
>
> webpack 3.x | babel-loader >= 7.1
```bash
yarn add babel-loader babel-core babel-preset-env webpack --dev
```
We recommend using yarn, but you can also still use npm:
```bash
npm install --save-dev babel-loader babel-core babel-preset-env webpack
```
<h2 align="center">Usage</h2>
[Documentation: Using loaders](https://webpack.js.org/loaders/)
Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
```javascript
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
```
### Options
See the `babel` [options](https://babeljs.io/docs/usage/api/#options).
You can pass options to the loader by using the [options property](https://webpack.js.org/configuration/module/#rule-options-rule-query):
```javascript
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: [require('babel-plugin-transform-object-rest-spread')]
}
}
}
]
}
```
This loader also supports the following loader-specific option:
* `cacheDirectory`: Default `false`. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is blank (`loader: 'babel-loader?cacheDirectory'`) or `true` (`loader: babel-loader?cacheDirectory=true`) the loader will use the default cache directory in `node_modules/.cache/babel-loader` or fallback to the default OS temporary file directory if no `node_modules` folder could be found in any root directory.
* `cacheIdentifier`: Default is a string composed by the babel-core's version, the babel-loader's version, the contents of .babelrc file if it exists and the value of the environment variable `BABEL_ENV` with a fallback to the `NODE_ENV` environment variable. This can be set to a custom value to force cache busting if the identifier changes.
* `forceEnv`: Default will resolve BABEL_ENV then NODE_ENV. Allow you to override BABEL_ENV/NODE_ENV at the loader level. Useful for isomorphic applications with different babel configuration for client and server.
__Note:__ The `sourceMap` option is ignored, instead sourceMaps are automatically enabled when webpack is configured to use them (via the `devtool` config option).
## Troubleshooting
### babel-loader is slow!
Make sure you are transforming as few files as possible. Because you are probably
matching `/\.js$/`, you might be transforming the `node_modules` folder or other unwanted
source.
To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above.
You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option.
This will cache transformations to the filesystem.
### babel is injecting helpers into each file and bloating my code!
babel uses very small helpers for common functions such as `_extend`. By default
this will be added to every file that requires it.
You can instead require the babel runtime as a separate module to avoid the duplication.
The following configuration disables automatic per-file runtime injection in babel, instead
requiring `babel-plugin-transform-runtime` and making all helper references use it.
See the [docs](http://babeljs.io/docs/plugins/transform-runtime/) for more information.
**NOTE:** You must run `npm install babel-plugin-transform-runtime --save-dev` to include this in your project and `babel-runtime` itself as a dependency with `npm install babel-runtime --save`.
```javascript
rules: [
// the 'transform-runtime' plugin tells babel to require the runtime
// instead of inlining it.
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: ['transform-runtime']
}
}
}
]
```
#### **NOTE:** transform-runtime & custom polyfills (e.g. Promise library)
Since [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime) includes a polyfill that includes a custom [regenerator runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) and [core.js](https://github.com/zloirock/core-js), the following usual shimming method using `webpack.ProvidePlugin` will not work:
```javascript
// ...
new webpack.ProvidePlugin({
'Promise': 'bluebird'
}),
// ...
```
The following approach will not work either:
```javascript
require('babel-runtime/core-js/promise').default = require('bluebird');
var promise = new Promise;
```
which outputs to (using `runtime`):
```javascript
'use strict';
var _Promise = require('babel-runtime/core-js/promise')['default'];
require('babel-runtime/core-js/promise')['default'] = require('bluebird');
var promise = new _Promise();
```
The previous `Promise` library is referenced and used before it is overridden.
One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
```javascript
// bootstrap.js
require('babel-runtime/core-js/promise').default = require('bluebird');
// ...
require('./app');
```
### The node API for `babel` has been moved to `babel-core`.
If you receive this message it means that you have the npm package `babel` installed and use the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):
```js
{
test: /\.js$/,
loader: 'babel',
}
```
Webpack then tries to load the `babel` package instead of the `babel-loader`.
To fix this you should uninstall the npm package `babel` as it is deprecated in babel v6. (instead install `babel-cli` or `babel-core`)
In the case one of your dependencies is installing `babel` and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:
```js
{
test: /\.js$/,
loader: 'babel-loader',
}
```
## [License](http://couto.mit-license.org/)

View File

@@ -0,0 +1,180 @@
"use strict";
/**
* Filesystem cache
*
* Given a file and a transform function, cache the result into files
* or retrieve the previously cached files if the given file is already known.
*
* @see https://github.com/babel/babel-loader/issues/34
* @see https://github.com/babel/babel-loader/pull/41
*/
var crypto = require("crypto");
var mkdirp = require("mkdirp");
var findCacheDir = require("find-cache-dir");
var fs = require("fs");
var os = require("os");
var path = require("path");
var zlib = require("zlib");
var defaultCacheDirectory = null; // Lazily instantiated when needed
/**
* Read the contents from the compressed file.
*
* @async
* @params {String} filename
* @params {Function} callback
*/
var read = function read(filename, callback) {
return fs.readFile(filename, function (err, data) {
if (err) return callback(err);
return zlib.gunzip(data, function (err, content) {
if (err) return callback(err);
var result = {};
try {
result = JSON.parse(content);
} catch (e) {
return callback(e);
}
return callback(null, result);
});
});
};
/**
* Write contents into a compressed file.
*
* @async
* @params {String} filename
* @params {String} result
* @params {Function} callback
*/
var write = function write(filename, result, callback) {
var content = JSON.stringify(result);
return zlib.gzip(content, function (err, data) {
if (err) return callback(err);
return fs.writeFile(filename, data, callback);
});
};
/**
* Build the filename for the cached file
*
* @params {String} source File source code
* @params {Object} options Options used
*
* @return {String}
*/
var filename = function filename(source, identifier, options) {
var hash = crypto.createHash("SHA1");
var contents = JSON.stringify({
source: source,
options: options,
identifier: identifier
});
hash.end(contents);
return hash.read().toString("hex") + ".json.gz";
};
/**
* Handle the cache
*
* @params {String} directory
* @params {Object} params
* @params {Function} callback
*/
var handleCache = function handleCache(directory, params, callback) {
var source = params.source;
var options = params.options || {};
var transform = params.transform;
var identifier = params.identifier;
var shouldFallback = typeof params.directory !== "string" && directory !== os.tmpdir();
// Make sure the directory exists.
mkdirp(directory, function (err) {
// Fallback to tmpdir if node_modules folder not writable
if (err) return shouldFallback ? handleCache(os.tmpdir(), params, callback) : callback(err);
var file = path.join(directory, filename(source, identifier, options));
return read(file, function (err, content) {
var result = {};
// No errors mean that the file was previously cached
// we just need to return it
if (!err) return callback(null, content);
// Otherwise just transform the file
// return it to the user asap and write it in cache
try {
result = transform(source, options);
} catch (error) {
return callback(error);
}
return write(file, result, function (err) {
// Fallback to tmpdir if node_modules folder not writable
if (err) return shouldFallback ? handleCache(os.tmpdir(), params, callback) : callback(err);
callback(null, result);
});
});
});
};
/**
* Retrieve file from cache, or create a new one for future reads
*
* @async
* @param {Object} params
* @param {String} params.directory Directory to store cached files
* @param {String} params.identifier Unique identifier to bust cache
* @param {String} params.source Original contents of the file to be cached
* @param {Object} params.options Options to be given to the transform fn
* @param {Function} params.transform Function that will transform the
* original file and whose result will be
* cached
*
* @param {Function<err, result>} callback
*
* @example
*
* cache({
* directory: '.tmp/cache',
* identifier: 'babel-loader-cachefile',
* source: *source code from file*,
* options: {
* experimental: true,
* runtime: true
* },
* transform: function(source, options) {
* var content = *do what you need with the source*
* return content;
* }
* }, function(err, result) {
*
* });
*/
module.exports = function (params, callback) {
var directory = void 0;
if (typeof params.directory === "string") {
directory = params.directory;
} else {
if (defaultCacheDirectory === null) {
defaultCacheDirectory = findCacheDir({ name: "babel-loader" }) || os.tmpdir();
}
directory = defaultCacheDirectory;
}
handleCache(directory, params, callback);
};

185
goTorrentWebUI/node_modules/babel-loader/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,185 @@
"use strict";
var babel = require("babel-core");
var loaderUtils = require("loader-utils");
var path = require("path");
var cache = require("./fs-cache.js");
var exists = require("./utils/exists");
var relative = require("./utils/relative");
var read = require("./utils/read");
var resolveRc = require("./resolve-rc.js");
var pkg = require("../package.json");
var fs = require("fs");
/**
* Error thrown by Babel formatted to conform to Webpack reporting.
*/
function BabelLoaderError(name, message, codeFrame, hideStack, error) {
Error.call(this);
this.name = "BabelLoaderError";
this.message = formatMessage(name, message, codeFrame);
this.hideStack = hideStack;
this.error = error;
Error.captureStackTrace(this, BabelLoaderError);
}
BabelLoaderError.prototype = Object.create(Error.prototype);
BabelLoaderError.prototype.constructor = BabelLoaderError;
var STRIP_FILENAME_RE = /^[^:]+: /;
var formatMessage = function formatMessage(name, message, codeFrame) {
return (name ? name + ": " : "") + message + "\n\n" + codeFrame + "\n";
};
var transpile = function transpile(source, options) {
var forceEnv = options.forceEnv;
var tmpEnv = void 0;
delete options.forceEnv;
if (forceEnv) {
tmpEnv = process.env.BABEL_ENV;
process.env.BABEL_ENV = forceEnv;
}
var result = void 0;
try {
result = babel.transform(source, options);
} catch (error) {
if (forceEnv) restoreBabelEnv(tmpEnv);
if (error.message && error.codeFrame) {
var message = error.message;
var name = void 0;
var hideStack = void 0;
if (error instanceof SyntaxError) {
message = message.replace(STRIP_FILENAME_RE, "");
name = "SyntaxError";
hideStack = true;
} else if (error instanceof TypeError) {
message = message.replace(STRIP_FILENAME_RE, "");
hideStack = true;
}
throw new BabelLoaderError(name, message, error.codeFrame, hideStack, error);
} else {
throw error;
}
}
var code = result.code;
var map = result.map;
var metadata = result.metadata;
if (map && (!map.sourcesContent || !map.sourcesContent.length)) {
map.sourcesContent = [source];
}
if (forceEnv) restoreBabelEnv(tmpEnv);
return {
code: code,
map: map,
metadata: metadata
};
};
function restoreBabelEnv(prevValue) {
if (prevValue === undefined) {
delete process.env.BABEL_ENV;
} else {
process.env.BABEL_ENV = prevValue;
}
}
function passMetadata(s, context, metadata) {
if (context[s]) {
context[s](metadata);
}
}
module.exports = function (source, inputSourceMap) {
var _this = this;
// Handle filenames (#106)
var webpackRemainingChain = loaderUtils.getRemainingRequest(this).split("!");
var filename = webpackRemainingChain[webpackRemainingChain.length - 1];
// Handle options
var loaderOptions = loaderUtils.getOptions(this) || {};
var fileSystem = this.fs ? this.fs : fs;
var babelrcPath = null;
if (loaderOptions.babelrc !== false) {
babelrcPath = typeof loaderOptions.babelrc === "string" && exists(fileSystem, loaderOptions.babelrc) ? loaderOptions.babelrc : resolveRc(fileSystem, path.dirname(filename));
}
if (babelrcPath) {
this.addDependency(babelrcPath);
}
var defaultOptions = {
metadataSubscribers: [],
inputSourceMap: inputSourceMap,
sourceRoot: process.cwd(),
filename: filename,
cacheIdentifier: JSON.stringify({
"babel-loader": pkg.version,
"babel-core": babel.version,
babelrc: babelrcPath ? read(fileSystem, babelrcPath) : null,
env: loaderOptions.forceEnv || process.env.BABEL_ENV || process.env.NODE_ENV || "development"
})
};
var options = Object.assign({}, defaultOptions, loaderOptions);
if (loaderOptions.sourceMap === undefined) {
options.sourceMap = this.sourceMap;
}
if (options.sourceFileName === undefined) {
options.sourceFileName = relative(options.sourceRoot, options.filename);
}
var cacheDirectory = options.cacheDirectory;
var cacheIdentifier = options.cacheIdentifier;
var metadataSubscribers = options.metadataSubscribers;
delete options.cacheDirectory;
delete options.cacheIdentifier;
delete options.metadataSubscribers;
if (cacheDirectory) {
var callback = this.async();
return cache({
directory: cacheDirectory,
identifier: cacheIdentifier,
source: source,
options: options,
transform: transpile
}, function (err) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
code = _ref.code,
map = _ref.map,
metadata = _ref.metadata;
if (err) return callback(err);
metadataSubscribers.forEach(function (s) {
return passMetadata(s, _this, metadata);
});
return callback(null, code, map);
});
}
var _transpile = transpile(source, options),
code = _transpile.code,
map = _transpile.map,
metadata = _transpile.metadata;
metadataSubscribers.forEach(function (s) {
return passMetadata(s, _this, metadata);
});
this.callback(null, code, map);
};

View File

@@ -0,0 +1,26 @@
"use strict";
var path = require("path");
var exists = require("./utils/exists");
module.exports = function find(fileSystem, start) {
var _arr = [".babelrc", ".babelrc.js", "package.json"];
for (var _i = 0; _i < _arr.length; _i++) {
var fileName = _arr[_i];
var file = path.join(start, fileName);
if (exists(fileSystem, file)) {
if (fileName !== "package.json" || typeof require(file).babel === "object") {
return file;
}
}
}
var up = path.dirname(start);
// Reached root
if (up !== start) {
return find(fileSystem, up);
}
};

View File

@@ -0,0 +1,13 @@
"use strict";
module.exports = function (fileSystem, filename) {
var exists = false;
try {
exists = fileSystem.statSync(filename).isFile();
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
return exists;
};

View File

@@ -0,0 +1,14 @@
"use strict";
var path = require("path");
module.exports = function readBabelConfig(fileSystem, filename) {
if (path.basename(filename) === "package.json") {
var pkg = require(filename);
return JSON.stringify(pkg.babel);
}
// Webpack `fs` return Buffer
return fileSystem.readFileSync(filename).toString("utf8");
};

View File

@@ -0,0 +1,15 @@
"use strict";
var path = require("path");
module.exports = function relative(sourceRoot, filename) {
var rootPath = sourceRoot.replace(/\\/g, "/").split("/")[1];
var fileRootPath = filename.replace(/\\/g, "/").split("/")[1];
// If the file is in a completely different root folder use the absolute path of file.
if (rootPath && rootPath !== fileRootPath) {
return filename;
}
return path.relative(sourceRoot, filename);
};

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/../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,23 @@
The MIT Expat Licence.
Copyright (c) 2012 Michael Mclaughlin
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,263 @@
# big.js #
A small, fast JavaScript library for arbitrary-precision decimal arithmetic.
The little sister to [bignumber.js](https://github.com/MikeMcl/bignumber.js/).
See also [decimal.js](https://github.com/MikeMcl/decimal.js/), and [here](https://github.com/MikeMcl/big.js/wiki) for the difference between them.
## Features
- Faster, smaller and easier-to-use than JavaScript versions of Java's BigDecimal
- Only 2.7 KB minified and gzipped
- Simple API
- Replicates the `toExponential`, `toFixed` and `toPrecision` methods of JavaScript's Number type
- Includes a `sqrt` method
- Stores values in an accessible decimal floating point format
- No dependencies
- Comprehensive [documentation](http://mikemcl.github.io/big.js/) and test set
## Load
The library is the single JavaScript file *big.js* (or *big.min.js*, which is *big.js* minified).
It can be loaded via a script tag in an HTML document for the browser
<script src='./relative/path/to/big.js'></script>
or as a CommonJS, [Node.js](http://nodejs.org) or AMD module using `require`.
var Big = require('big.js');
For Node.js, the library is available from the npm registry:
$ npm install big.js
## Use
*In all examples below, `var`, semicolons and `toString` calls are not shown.
If a commented-out value is in quotes it means `toString` has been called on the preceding expression.*
The library exports a single function: Big, the constructor of Big number instances.
It accepts a value of type Number, String or Big number Object.
x = new Big(123.4567)
y = Big('123456.7e-3') // 'new' is optional
z = new Big(x)
x.eq(y) && x.eq(z) && y.eq(z) // true
A Big number is immutable in the sense that it is not changed by its methods.
0.3 - 0.1 // 0.19999999999999998
x = new Big(0.3)
x.minus(0.1) // "0.2"
x // "0.3"
The methods that return a Big number can be chained.
x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772')
x.sqrt().div(y).pow(3).gt(y.mod(z)) // true
Like JavaScript's Number type, there are `toExponential`, `toFixed` and `toPrecision` methods.
x = new Big(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
The maximum number of decimal places and the rounding mode used to round the results of the `div`, `sqrt` and `pow`
(with negative exponent) methods is determined by the value of the `DP` and `RM` properties of the `Big` number constructor.
The other methods always give the exact result.
(From *v3.0.0*, multiple Big number constructors can be created, see Change Log below.)
Big.DP = 10
Big.RM = 1
x = new Big(2);
y = new Big(3);
z = x.div(y) // "0.6666666667"
z.sqrt() // "0.8164965809"
z.pow(-3) // "3.3749999995"
z.times(z) // "0.44444444448888888889"
z.times(z).round(10) // "0.4444444445"
The value of a Big number is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
x = new Big(-123.456);
x.c // [1,2,3,4,5,6] coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign
For further information see the [API](http://mikemcl.github.io/big.js/) reference from the *doc* folder.
## Test
The *test* directory contains the test scripts for each Big number method.
The tests can be run with Node or a browser.
To test a single method, from a command-line shell at the *test* directory, use e.g.
$ node toFixed
To test all the methods
$ node every-test
For the browser, see *single-test.html* and *every-test.html* in the *test/browser* directory.
*big-vs-number.html* enables some of the methods of big.js to be compared with those of JavaScript's Number type.
## Performance
The *perf* directory contains two applications and a *lib* directory containing the BigDecimal libraries used by both.
*big-vs-bigdecimal.html* tests the performance of big.js against the JavaScript translations of two versions of BigDecimal, its use should be more or less self-explanatory.
(The GWT version doesn't work in IE 6.)
* GWT: java.math.BigDecimal
<https://github.com/iriscouch/bigdecimal.js>
* ICU4J: com.ibm.icu.math.BigDecimal
<https://github.com/dtrebbien/BigDecimal.js>
The BigDecimal in Node's npm registry is the GWT version. Despite its seeming popularity I have found it to have some serious bugs, see the Node script *perf/lib/bigdecimal_GWT/bugs.js* for examples of flaws in its *remainder*, *divide* and *compareTo* methods.
*bigtime.js* is a Node command-line application which tests the performance of big.js against the GWT version of
BigDecimal from the npm registry.
For example, to compare the time taken by the big.js `plus` method and the BigDecimal `add` method:
$ node bigtime plus 10000 40
This will time 10000 calls to each, using operands of up to 40 random digits and will check that the results match.
For help:
$ node bigtime -h
## Build
I.e. minify.
For Node, if uglify-js is installed globally ( `npm install uglify-js -g` ) then
uglifyjs -o ./big.min.js ./big.js
will create *big.min.js*.
The *big.min.js* already present was created with *Microsoft Ajax Minifier 5.11*.
## TypeScript
The [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) project has a TypeScript [definitions file](https://github.com/borisyankov/DefinitelyTyped/blob/master/big.js/big.js.d.ts) for big.js.
The definitions file can be added to your project via the [big.js.TypeScript.DefinitelyTyped](https://www.nuget.org/packages/big.js.TypeScript.DefinitelyTyped/0.0.1) NuGet package or via [tsd](http://definitelytyped.org/tsd/).
tsd query big.js --action install
Any questions about the TypeScript definitions file should be addressed to the DefinitelyTyped project.
## Feedback
Feedback is welcome.
Bugs/comments/questions?
Open an issue, or email
Michael
<a href="mailto:M8ch88l@gmail.com">M8ch88l@gmail.com</a>
Bitcoin donation to:
**1DppGRQSjVSMgGxuygDEHQuWEdTiVEzJYG**
Thank you
## Licence
See LICENCE.
## Change Log
####3.2.0
* 14/09/17 Aid ES6 import.
####3.1.3
* Minor documentation updates.
####3.1.2
* README typo.
####3.1.1
* API documentation update, including FAQ additions.
####3.1.0
* Renamed and exposed `TO_EXP_NEG` and `TO_EXP_POS` as `Big.E_NEG` and
`Big.E_POS`.
####3.0.2
* Remove *.npmignore*, use `files` field in *package.json* instead.
####3.0.1
* Added `sub`, `add` and `mul` aliases.
* Clean-up after lint.
####3.0.0
* 10/12/14 Added [multiple constructor functionality](http://mikemcl.github.io/big.js/#faq).
* No breaking changes or other additions, but a major code reorganisation,
so *v3* seemed appropriate.
####2.5.2
* 1/11/14 Added bower.json.
####2.5.1
* 8/06/14 Amend README requires.
####2.5.0
* 26/01/14 Added `toJSON` method so serialization uses `toString`.
####2.4.1
* 17/10/13 Conform signed zero to IEEEE 754 (2008).
####2.4.0
* 19/09/13 Throw instances of `Error`.
####2.3.0
* 16/09/13 Added `cmp` method.
####2.2.0
* 11/07/13 Added 'round up' mode.
####2.1.0
* 26/06/13 Allow e.g. `.1` and `2.`.
####2.0.0
* 12/05/13 Added `abs` method and replaced `cmp` with `eq`, `gt`, `gte`, `lt`, and `lte` methods.
####1.0.1
* Changed default value of MAX_DP to 1E6
####1.0.0
* 7/11/2012 Initial release

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
{
"_args": [
[
"big.js@3.2.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "big.js@3.2.0",
"_id": "big.js@3.2.0",
"_inBundle": false,
"_integrity": "sha512-+hN/Zh2D08Mx65pZ/4g5bsmNiZUuChDiQfTUQ7qJr4/kuopCr88xZsAXv6mBoZEsUI4OuGHlX59qE94K2mMW8Q==",
"_location": "/babel-loader/big.js",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "big.js@3.2.0",
"name": "big.js",
"escapedName": "big.js",
"rawSpec": "3.2.0",
"saveSpec": null,
"fetchSpec": "3.2.0"
},
"_requiredBy": [
"/babel-loader/loader-utils"
],
"_resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz",
"_spec": "3.2.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Michael Mclaughlin",
"email": "M8ch88l@gmail.com"
},
"bugs": {
"url": "https://github.com/MikeMcl/big.js/issues"
},
"description": "A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic",
"engines": {
"node": "*"
},
"files": [
"big.js",
"big.min.js"
],
"homepage": "https://github.com/MikeMcl/big.js#readme",
"keywords": [
"arbitrary",
"precision",
"arithmetic",
"big",
"number",
"decimal",
"float",
"biginteger",
"bigdecimal",
"bignumber",
"bigint",
"bignum"
],
"license": "MIT",
"main": "big.js",
"name": "big.js",
"repository": {
"type": "git",
"url": "git+https://github.com/MikeMcl/big.js.git"
},
"scripts": {
"build": "uglifyjs big.js --source-map doc/big.js.map -c -m -o big.min.js --preamble \"/* big.js v3.2.0 https://github.com/MikeMcl/big.js/LICENCE */\"",
"test": "node ./test/every-test.js"
},
"version": "3.2.0"
}

View File

@@ -0,0 +1,24 @@
The MIT License
Copyright (c) 2013 James Halliday (mail@substack.net)
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,3 @@
var commondir = require('../');
var dir = commondir(process.argv.slice(2));
console.log(dir);

View File

@@ -0,0 +1,29 @@
var path = require('path');
module.exports = function (basedir, relfiles) {
if (relfiles) {
var files = relfiles.map(function (r) {
return path.resolve(basedir, r);
});
}
else {
var files = basedir;
}
var res = files.slice(1).reduce(function (ps, file) {
if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
throw new Error('relative path without a basedir');
}
var xs = file.split(/\/+|\\+/);
for (
var i = 0;
ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
i++
);
return ps.slice(0, i);
}, files[0].split(/\/+|\\+/));
// Windows correctly handles paths with forward-slashes
return res.length > 1 ? res.join('/') : '/'
};

View File

@@ -0,0 +1,66 @@
{
"_args": [
[
"commondir@1.0.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "commondir@1.0.1",
"_id": "commondir@1.0.1",
"_inBundle": false,
"_integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=",
"_location": "/babel-loader/commondir",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "commondir@1.0.1",
"name": "commondir",
"escapedName": "commondir",
"rawSpec": "1.0.1",
"saveSpec": null,
"fetchSpec": "1.0.1"
},
"_requiredBy": [
"/babel-loader/find-cache-dir"
],
"_resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
"_spec": "1.0.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/node-commondir/issues"
},
"dependencies": {},
"description": "compute the closest common parent for file paths",
"devDependencies": {
"tape": "^3.5.0"
},
"engine": {
"node": ">=0.4"
},
"homepage": "https://github.com/substack/node-commondir#readme",
"keywords": [
"common",
"path",
"directory",
"file",
"parent",
"root"
],
"license": "MIT",
"main": "index.js",
"name": "commondir",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/substack/node-commondir.git"
},
"scripts": {
"test": "tape test/*.js"
},
"version": "1.0.1"
}

View File

@@ -0,0 +1,48 @@
# commondir
compute the closest common parent directory among an array of directories
# example
``` js
var commondir = require('commondir');
var dir = commondir(process.argv.slice(2))
console.log(dir);
```
output:
```
$ node dir.js /x/y/z /x/y /x/y/w/q
/x/y
$ node ../baz ../../foo/quux ./bizzy
/foo
```
# methods
``` js
var commondir = require('commondir');
```
## commondir(absolutePaths)
Compute the closest common parent directory for an array `absolutePaths`.
## commondir(basedir, relativePaths)
Compute the closest common parent directory for an array `relativePaths` which
will be resolved for each `dir` in `relativePaths` according to:
`path.resolve(basedir, dir)`.
# install
With [npm](https://npmjs.org) do:
```
npm install commondir
```
# license
MIT

View File

@@ -0,0 +1,55 @@
var test = require('tape');
var commondir = require('../');
test('common', function (t) {
t.equal(
commondir([ '/foo', '//foo/bar', '/foo//bar/baz' ]),
'/foo'
);
t.equal(
commondir([ '/a/b/c', '/a/b', '/a/b/c/d/e' ]),
'/a/b'
);
t.equal(
commondir([ '/x/y/z/w', '/xy/z', '/x/y/z' ]),
'/'
);
t.equal(
commondir([ 'X:\\foo', 'X:\\\\foo\\bar', 'X://foo/bar/baz' ]),
'X:/foo'
);
t.equal(
commondir([ 'X:\\a\\b\\c', 'X:\\a\\b', 'X:\\a\\b\\c\\d\\e' ]),
'X:/a/b'
);
t.equal(
commondir([ 'X:\\x\\y\\z\\w', '\\\\xy\\z', '\\x\\y\\z' ]),
'/'
);
t.throws(function () {
commondir([ '/x/y/z/w', 'qrs', '/x/y/z' ]);
});
t.end();
});
test('base', function (t) {
t.equal(
commondir('/foo/bar', [ 'baz', './quux', '../bar/bazzy' ]),
'/foo/bar'
);
t.equal(
commondir('/a/b', [ 'c', '../b/.', '../../a/b/e' ]),
'/a/b'
);
t.equal(
commondir('/a/b/c', [ '..', '../d', '../../a/z/e' ]),
'/a'
);
t.equal(
commondir('/foo/bar', [ 'baz', '.\\quux', '..\\bar\\bazzy' ]),
'/foo/bar'
);
// Tests including X:\ basedirs must wait until path.resolve supports
// Windows-style paths, starting in Node.js v0.5.X
t.end();
});

View File

@@ -0,0 +1,70 @@
<a name="2.1.0"></a>
# 2.1.0 (2016-10-03)
* Fetch new emoji ([7dbe84d](https://github.com/kikobeats/emojis-list/commit/7dbe84d))
<a name="2.0.1"></a>
## 2.0.1 (2016-05-12)
* Fix typo ([3808909](https://github.com/kikobeats/emojis-list/commit/3808909))
<a name="2.0.0"></a>
# 2.0.0 (2016-05-12)
* Add update script ([f846dd6](https://github.com/kikobeats/emojis-list/commit/f846dd6))
* Block dependencies in last version ([1d9e0a5](https://github.com/kikobeats/emojis-list/commit/1d9e0a5))
* Extract main file name ([9ffe7bb](https://github.com/kikobeats/emojis-list/commit/9ffe7bb))
* Remove unnecessary files ([4c34729](https://github.com/kikobeats/emojis-list/commit/4c34729))
* Update docs, special webpack setup is not necessary ([c4aefe9](https://github.com/kikobeats/emojis-list/commit/c4aefe9))
* Update example ([1e2ae03](https://github.com/kikobeats/emojis-list/commit/1e2ae03))
* Update how to generate emojis array ([b56bad9](https://github.com/kikobeats/emojis-list/commit/b56bad9))
* Update main file based in the new interface ([996fccb](https://github.com/kikobeats/emojis-list/commit/996fccb))
<a name="1.0.3"></a>
## 1.0.3 (2016-05-12)
* Add standard as linter ([5e939d6](https://github.com/kikobeats/emojis-list/commit/5e939d6))
* Change interface ([16bc0c0](https://github.com/kikobeats/emojis-list/commit/16bc0c0))
* Generate emoji file ([fbcf8e9](https://github.com/kikobeats/emojis-list/commit/fbcf8e9))
* Remove unnecessary special doc ([2b12bec](https://github.com/kikobeats/emojis-list/commit/2b12bec))
* chore(package): update browserify to version 13.0.1 ([e2c98bf](https://github.com/kikobeats/emojis-list/commit/e2c98bf))
* chore(package): update gulp-header to version 1.8.1 ([28de793](https://github.com/kikobeats/emojis-list/commit/28de793))
<a name="1.0.2"></a>
## 1.0.2 (2016-05-05)
* fixed #2 ([9a6abe7](https://github.com/kikobeats/emojis-list/commit/9a6abe7)), closes [#2](https://github.com/kikobeats/emojis-list/issues/2)
* Fomar using standard ([5202f9f](https://github.com/kikobeats/emojis-list/commit/5202f9f))
* Update badge ([53fad9b](https://github.com/kikobeats/emojis-list/commit/53fad9b))
<a name="1.0.1"></a>
## 1.0.1 (2016-04-13)
* lock versions ([4a5d82e](https://github.com/kikobeats/emojis-list/commit/4a5d82e))
* setup devDependencies ([d1de0fc](https://github.com/kikobeats/emojis-list/commit/d1de0fc))
* update bumped ([9941038](https://github.com/kikobeats/emojis-list/commit/9941038))
* Update package.json ([6c14b74](https://github.com/kikobeats/emojis-list/commit/6c14b74))
* Update README.md ([1d9beeb](https://github.com/kikobeats/emojis-list/commit/1d9beeb))
* Update README.md ([73f215e](https://github.com/kikobeats/emojis-list/commit/73f215e))
* Update tests ([a94f7dc](https://github.com/kikobeats/emojis-list/commit/a94f7dc))
<a name="1.0.0"></a>
# 1.0.0 (2015-05-12)
* first commit ([a65b79d](https://github.com/kikobeats/emojis-list/commit/a65b79d))
* updated ([9f0564c](https://github.com/kikobeats/emojis-list/commit/9f0564c))

View File

@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright © 2015 Kiko Beats
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,48 @@
# emojis-list
[![Dependency status](http://img.shields.io/david/Kikobeats/emojis-list.svg?style=flat-square)](https://david-dm.org/Kikobeats/emojis-list)
[![Dev Dependencies Status](http://img.shields.io/david/dev/Kikobeats/emojis-list.svg?style=flat-square)](https://david-dm.org/Kikobeats/emojis-list#info=devDependencies)
[![NPM Status](http://img.shields.io/npm/dm/emojis-list.svg?style=flat-square)](https://www.npmjs.org/package/emojis-list)
[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg?style=flat-square)](https://paypal.me/kikobeats)
> Complete list of standard Unicode Hex Character Code that represent emojis.
**NOTE**: The lists is related with the Unicode Hex Character Code. The representation of the emoji depend of the system. Will be possible that the system don't have all the representations.
## Install
```bash
npm install emojis-list --save
```
If you want to use in the browser (powered by [Browserify](http://browserify.org/)):
```bash
bower install emojis-list --save
```
and later link in your HTML:
```html
<script src="bower_components/emojis-list/dist/emojis-list.js"></script>
```
## Usage
```
var emojis = require('emojis-list');
console.log(emojis[0]);
// => 🀄
```
## Related
* [emojis-unicode](https://github.com/Kikobeats/emojis-unicode) Complete list of standard Unicode codes that represent emojis.
* [emojis-keywords](https://github.com/Kikobeats/emojis-keywords) Complete list of am emoji shortcuts.
* [is-emoji-keyword](https://github.com/Kikobeats/is-emoji-keyword) Check if a word is a emoji shortcut.
* [is-standard-emoji](https://github.com/kikobeats/is-standard-emoji) Simply way to check if a emoji is a standard emoji.
* [trim-emoji](https://github.com/Kikobeats/trim-emoji) Deletes ':' from the begin and the end of an emoji shortcut.
## License
MIT © [Kiko Beats](http://www.kikobeats.com)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,79 @@
{
"_args": [
[
"emojis-list@2.1.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "emojis-list@2.1.0",
"_id": "emojis-list@2.1.0",
"_inBundle": false,
"_integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=",
"_location": "/babel-loader/emojis-list",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "emojis-list@2.1.0",
"name": "emojis-list",
"escapedName": "emojis-list",
"rawSpec": "2.1.0",
"saveSpec": null,
"fetchSpec": "2.1.0"
},
"_requiredBy": [
"/babel-loader/loader-utils"
],
"_resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz",
"_spec": "2.1.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Kiko Beats",
"email": "josefrancisco.verdu@gmail.com",
"url": "https://github.com/Kikobeats"
},
"bugs": {
"url": "https://github.com/Kikobeats/emojis-list/issues"
},
"description": "Complete list of standard emojis.",
"devDependencies": {
"acho": "latest",
"browserify": "latest",
"cheerio": "latest",
"got": ">=5 <6",
"gulp": "latest",
"gulp-header": "latest",
"gulp-uglify": "latest",
"gulp-util": "latest",
"standard": "latest",
"vinyl-buffer": "latest",
"vinyl-source-stream": "latest"
},
"engines": {
"node": ">= 0.10"
},
"files": [
"index.js"
],
"homepage": "https://github.com/Kikobeats/emojis-list",
"keywords": [
"archive",
"complete",
"emoji",
"list",
"standard"
],
"license": "MIT",
"main": "./index.js",
"name": "emojis-list",
"repository": {
"type": "git",
"url": "git+https://github.com/kikobeats/emojis-list.git"
},
"scripts": {
"pretest": "standard update.js",
"test": "echo 'YOLO'",
"update": "node update"
},
"version": "2.1.0"
}

View File

@@ -0,0 +1,34 @@
'use strict';
const path = require('path');
const commonDir = require('commondir');
const pkgDir = require('pkg-dir');
const makeDir = require('make-dir');
module.exports = options => {
const name = options.name;
let dir = options.cwd;
if (options.files) {
dir = commonDir(dir, options.files);
} else {
dir = dir || process.cwd();
}
dir = pkgDir.sync(dir);
if (dir) {
dir = path.join(dir, 'node_modules', '.cache', name);
if (dir && options.create) {
makeDir.sync(dir);
}
if (options.thunk) {
return function () {
return path.join.apply(path, [dir].concat(Array.prototype.slice.call(arguments)));
};
}
}
return dir;
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) James Talmage <james@talmage.io> (github.com/jamestalmage)
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,82 @@
{
"_args": [
[
"find-cache-dir@1.0.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "find-cache-dir@1.0.0",
"_id": "find-cache-dir@1.0.0",
"_inBundle": false,
"_integrity": "sha1-kojj6ePMN0hxfTnq3hfPcfww7m8=",
"_location": "/babel-loader/find-cache-dir",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "find-cache-dir@1.0.0",
"name": "find-cache-dir",
"escapedName": "find-cache-dir",
"rawSpec": "1.0.0",
"saveSpec": null,
"fetchSpec": "1.0.0"
},
"_requiredBy": [
"/babel-loader"
],
"_resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-1.0.0.tgz",
"_spec": "1.0.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "James Talmage",
"email": "james@talmage.io",
"url": "github.com/jamestalmage"
},
"bugs": {
"url": "https://github.com/avajs/find-cache-dir/issues"
},
"dependencies": {
"commondir": "^1.0.1",
"make-dir": "^1.0.0",
"pkg-dir": "^2.0.0"
},
"description": "My well-made module",
"devDependencies": {
"ava": "^0.19.1",
"coveralls": "^2.11.6",
"del": "^2.2.2",
"nyc": "^10.3.2",
"xo": "^0.18.2"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/avajs/find-cache-dir#readme",
"keywords": [
"cache",
"directory",
"dir",
"caching",
"find",
"search"
],
"license": "MIT",
"name": "find-cache-dir",
"nyc": {
"reporter": [
"lcov",
"text"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/avajs/find-cache-dir.git"
},
"scripts": {
"test": "xo && nyc ava"
},
"version": "1.0.0"
}

View File

@@ -0,0 +1,113 @@
# find-cache-dir [![Build Status](https://travis-ci.org/avajs/find-cache-dir.svg?branch=master)](https://travis-ci.org/avajs/find-cache-dir) [![Coverage Status](https://coveralls.io/repos/github/avajs/find-cache-dir/badge.svg?branch=master)](https://coveralls.io/github/avajs/find-cache-dir?branch=master)
> Finds the common standard cache directory
Recently the [`nyc`](https://github.com/bcoe/nyc) and [`AVA`](https://ava.li) projects decided to standardize on a common directory structure for storing cache information:
```sh
# nyc
./node_modules/.cache/nyc
# ava
./node_modules/.cache/ava
# your-module
./node_modules/.cache/your-module
```
This module makes it easy to correctly locate the cache directory according to this shared spec. If this pattern becomes ubiquitous, clearing the cache for multiple dependencies becomes easy and consistent:
```
rm -rf ./node_modules/.cache
```
If you decide to adopt this pattern, please file a PR adding your name to the list of adopters below.
## Install
```
$ npm install --save find-cache-dir
```
## Usage
```js
const findCacheDir = require('find-cache-dir');
findCacheDir({name: 'unicorns'});
//=> '/user/path/node-modules/.cache/unicorns'
```
## API
### findCacheDir([options])
Finds the cache directory using the supplied options. The algorithm tries to find a `package.json` file, searching every parent directory of the `cwd` specified (or implied from other options). It returns a `string` containing the absolute path to the cache directory, or `null` if `package.json` was never found.
#### options
##### name
*Required*<br>
Type: `string`
Should be the same as your project name in `package.json`.
##### files
Type: `Array` `string
An array of files that will be searched for a common parent directory. This common parent directory will be used in lieu of the `cwd` option below.
##### cwd
Type: `string`<br>
Default `process.cwd()`
Directory to start searching for a `package.json` from.
##### create
Type: `boolean`<br>
Default `false`
If `true`, the directory will be created synchronously before returning.
##### thunk
Type: `boolean`<br>
Default `false`
If `true`, this modifies the return type to be a function that is a thunk for `path.join(theFoundCacheDirectory)`.
```js
const thunk = findCacheDir({name: 'foo', thunk: true});
thunk();
//=> '/some/path/node_modules/.cache/foo'
thunk('bar.js')
//=> '/some/path/node_modules/.cache/foo/bar.js'
thunk('baz', 'quz.js')
//=> '/some/path/node_modules/.cache/foo/baz/quz.js'
```
This is helpful for actually putting actual files in the cache!
## Adopters
- [`AVA`](https://ava.li)
- [`nyc`](https://github.com/bcoe/nyc)
- [`babel-loader`](https://github.com/babel/babel-loader)
- [`eslint-loader`](https://github.com/MoOx/eslint-loader)
- [`Phenomic`](https://phenomic.io)
## License
MIT © [James Talmage](https://github.com/jamestalmage)

View File

@@ -0,0 +1,48 @@
'use strict';
const path = require('path');
const locatePath = require('locate-path');
module.exports = (filename, opts) => {
opts = opts || {};
const startDir = path.resolve(opts.cwd || '');
const root = path.parse(startDir).root;
const filenames = [].concat(filename);
return new Promise(resolve => {
(function find(dir) {
locatePath(filenames, {cwd: dir}).then(file => {
if (file) {
resolve(path.join(dir, file));
} else if (dir === root) {
resolve(null);
} else {
find(path.dirname(dir));
}
});
})(startDir);
});
};
module.exports.sync = (filename, opts) => {
opts = opts || {};
let dir = path.resolve(opts.cwd || '');
const root = path.parse(dir).root;
const filenames = [].concat(filename);
// eslint-disable-next-line no-constant-condition
while (true) {
const file = locatePath.sync(filenames, {cwd: dir});
if (file) {
return path.join(dir, file);
} else if (dir === root) {
return null;
}
dir = path.dirname(dir);
}
};

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,88 @@
{
"_args": [
[
"find-up@2.1.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "find-up@2.1.0",
"_id": "find-up@2.1.0",
"_inBundle": false,
"_integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=",
"_location": "/babel-loader/find-up",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "find-up@2.1.0",
"name": "find-up",
"escapedName": "find-up",
"rawSpec": "2.1.0",
"saveSpec": null,
"fetchSpec": "2.1.0"
},
"_requiredBy": [
"/babel-loader/pkg-dir"
],
"_resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz",
"_spec": "2.1.0",
"_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/sindresorhus/find-up/issues"
},
"dependencies": {
"locate-path": "^2.0.0"
},
"description": "Find a file by walking up parent directories",
"devDependencies": {
"ava": "*",
"tempfile": "^1.1.1",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/find-up#readme",
"keywords": [
"find",
"up",
"find-up",
"findup",
"look-up",
"look",
"file",
"search",
"match",
"package",
"resolve",
"parent",
"parents",
"folder",
"directory",
"dir",
"walk",
"walking",
"path"
],
"license": "MIT",
"name": "find-up",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/find-up.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.1.0",
"xo": {
"esnext": true
}
}

View File

@@ -0,0 +1,85 @@
# find-up [![Build Status: Linux and macOS](https://travis-ci.org/sindresorhus/find-up.svg?branch=master)](https://travis-ci.org/sindresorhus/find-up) [![Build Status: Windows](https://ci.appveyor.com/api/projects/status/l0cyjmvh5lq72vq2/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/find-up/branch/master)
> Find a file by walking up parent directories
## Install
```
$ npm install --save find-up
```
## Usage
```
/
└── Users
└── sindresorhus
├── unicorn.png
└── foo
└── bar
├── baz
└── example.js
```
```js
// example.js
const findUp = require('find-up');
findUp('unicorn.png').then(filepath => {
console.log(filepath);
//=> '/Users/sindresorhus/unicorn.png'
});
findUp(['rainbow.png', 'unicorn.png']).then(filepath => {
console.log(filepath);
//=> '/Users/sindresorhus/unicorn.png'
});
```
## API
### findUp(filename, [options])
Returns a `Promise` for the filepath or `null`.
### findUp([filenameA, filenameB], [options])
Returns a `Promise` for the first filepath found (by respecting the order) or `null`.
### findUp.sync(filename, [options])
Returns a filepath or `null`.
### findUp.sync([filenameA, filenameB], [options])
Returns the first filepath found (by respecting the order) or `null`.
#### filename
Type: `string`
Filename of the file to find.
#### options
##### cwd
Type: `string`<br>
Default: `process.cwd()`
Directory to start from.
## Related
- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module
- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file
- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@@ -0,0 +1,169 @@
### v0.5.1 [[code][c0.5.1], [diff][d0.5.1]]
[c0.5.1]: https://github.com/aseemk/json5/tree/v0.5.1
[d0.5.1]: https://github.com/aseemk/json5/compare/v0.5.0...v0.5.1
This release includes a minor fix for indentations when stringifying empty
arrays.
- Fix: Indents no longer appear in empty arrays when stringified. ([#134])
### v0.5.0 [[code][c0.5.0], [diff][d0.5.0]]
[c0.5.0]: https://github.com/aseemk/json5/tree/v0.5.0
[d0.5.0]: https://github.com/aseemk/json5/compare/v0.4.0...v0.5.0
This release includes major internal changes and public API enhancements.
- **Major:** JSON5 officially supports Node.js v4 LTS and v5. Support for
Node.js v0.6 and v0.8 have been dropped, while support for v0.10 and v0.12
remain.
- Fix: YUI Compressor no longer fails when compressing json5.js. ([#97])
- New: `parse` and the CLI provide line and column numbers when displaying error
messages. ([#101]; awesome work by [@amb26].)
### v0.4.0 [[code][c0.4.0], [diff][d0.4.0]]
[c0.4.0]: https://github.com/aseemk/json5/tree/v0.4.0
[d0.4.0]: https://github.com/aseemk/json5/compare/v0.2.0...v0.4.0
Note that v0.3.0 was tagged, but never published to npm, so this v0.4.0
changelog entry includes v0.3.0 features.
This is a massive release that adds `stringify` support, among other things.
- **Major:** `JSON5.stringify()` now exists!
This method is analogous to the native `JSON.stringify()`;
it just avoids quoting keys where possible.
See the [usage documentation](./README.md#usage) for more.
([#32]; huge thanks and props [@aeisenberg]!)
- New: `NaN` and `-NaN` are now allowed number literals.
([#30]; thanks [@rowanhill].)
- New: Duplicate object keys are now allowed; the last value is used.
This is the same behavior as JSON. ([#57]; thanks [@jordanbtucker].)
- Fix: Properly handle various whitespace and newline cases now.
E.g. JSON5 now properly supports escaped CR and CRLF newlines in strings,
and JSON5 now accepts the same whitespace as JSON (stricter than ES5).
([#58], [#60], and [#63]; thanks [@jordanbtucker].)
- New: Negative hexadecimal numbers (e.g. `-0xC8`) are allowed again.
(They were disallowed in v0.2.0; see below.)
It turns out they *are* valid in ES5, so JSON5 supports them now too.
([#36]; thanks [@jordanbtucker]!)
### v0.2.0 [[code][c0.2.0], [diff][d0.2.0]]
[c0.2.0]: https://github.com/aseemk/json5/tree/v0.2.0
[d0.2.0]: https://github.com/aseemk/json5/compare/v0.1.0...v0.2.0
This release fixes some bugs and adds some more utility features to help you
express data more easily:
- **Breaking:** Negative hexadecimal numbers (e.g. `-0xC8`) are rejected now.
While V8 (e.g. Chrome and Node) supported them, it turns out they're invalid
in ES5. This has been [fixed in V8][v8-hex-fix] (and by extension, Chrome
and Node), so JSON5 officially rejects them now, too. ([#36])
- New: Trailing decimal points in decimal numbers are allowed again.
(They were disallowed in v0.1.0; see below.)
They're allowed by ES5, and differentiating between integers and floats may
make sense on some platforms. ([#16]; thanks [@Midar].)
- New: `Infinity` and `-Infinity` are now allowed number literals.
([#30]; thanks [@pepkin88].)
- New: Plus signs (`+`) in front of numbers are now allowed, since it can
be helpful in some contexts to explicitly mark numbers as positive.
(E.g. when a property represents changes or deltas.)
- Fix: unescaped newlines in strings are rejected now.
([#24]; thanks [@Midar].)
### v0.1.0 [[code][c0.1.0], [diff][d0.1.0]]
[c0.1.0]: https://github.com/aseemk/json5/tree/v0.1.0
[d0.1.0]: https://github.com/aseemk/json5/compare/v0.0.1...v0.1.0
This release tightens JSON5 support and adds helpful utility features:
- New: Support hexadecimal numbers. (Thanks [@MaxNanasy].)
- Fix: Reject octal numbers properly now. Previously, they were accepted but
improperly parsed as base-10 numbers. (Thanks [@MaxNanasy].)
- **Breaking:** Reject "noctal" numbers now (base-10 numbers that begin with a
leading zero). These are disallowed by both JSON5 and JSON, as well as by
ES5's strict mode. (Thanks [@MaxNanasy].)
- New: Support leading decimal points in decimal numbers.
(Thanks [@MaxNanasy].)
- **Breaking:** Reject trailing decimal points in decimal numbers now. These
are disallowed by both JSON5 and JSON. (Thanks [@MaxNanasy].)
- **Breaking:** Reject omitted elements in arrays now. These are disallowed by
both JSON5 and JSON.
- Fix: Throw proper `SyntaxError` instances on errors now.
- New: Add Node.js `require()` hook. Register via `json5/lib/require`.
- New: Add Node.js `json5` executable to compile JSON5 files to JSON.
### v0.0.1 [[code][c0.0.1], [diff][d0.0.1]]
[c0.0.1]: https://github.com/aseemk/json5/tree/v0.0.1
[d0.0.1]: https://github.com/aseemk/json5/compare/v0.0.0...v0.0.1
This was the first implementation of this JSON5 parser.
- Support unquoted object keys, including reserved words. Unicode characters
and escape sequences sequences aren't yet supported.
- Support single-quoted strings.
- Support multi-line strings.
- Support trailing commas in arrays and objects.
- Support comments, both inline and block.
### v0.0.0 [[code](https://github.com/aseemk/json5/tree/v0.0.0)]
Let's consider this to be Douglas Crockford's original [json_parse.js] — a
parser for the regular JSON format.
[json_parse.js]: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
[v8-hex-fix]: http://code.google.com/p/v8/issues/detail?id=2240
[@MaxNanasy]: https://github.com/MaxNanasy
[@Midar]: https://github.com/Midar
[@pepkin88]: https://github.com/pepkin88
[@rowanhill]: https://github.com/rowanhill
[@aeisenberg]: https://github.com/aeisenberg
[@jordanbtucker]: https://github.com/jordanbtucker
[@amb26]: https://github.com/amb26
[#16]: https://github.com/aseemk/json5/issues/16
[#24]: https://github.com/aseemk/json5/issues/24
[#30]: https://github.com/aseemk/json5/issues/30
[#32]: https://github.com/aseemk/json5/issues/32
[#36]: https://github.com/aseemk/json5/issues/36
[#57]: https://github.com/aseemk/json5/issues/57
[#58]: https://github.com/aseemk/json5/pull/58
[#60]: https://github.com/aseemk/json5/pull/60
[#63]: https://github.com/aseemk/json5/pull/63
[#97]: https://github.com/aseemk/json5/pull/97
[#101]: https://github.com/aseemk/json5/pull/101

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2012-2016 Aseem Kishore, and [others](https://github.com/aseemk/json5/contributors).
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,286 @@
# JSON5 Modern JSON
[![Build Status](https://travis-ci.org/json5/json5.svg)](https://travis-ci.org/json5/json5)
JSON is an excellent data format, but we think it can be better.
**JSON5 is a proposed extension to JSON** that aims to make it easier for
*humans to write and maintain* by hand. It does this by adding some minimal
syntax features directly from ECMAScript 5.
JSON5 remains a **strict subset of JavaScript**, adds **no new data types**,
and **works with all existing JSON content**.
JSON5 is *not* an official successor to JSON, and JSON5 content may *not*
work with existing JSON parsers. For this reason, JSON5 files use a new .json5
extension. *(TODO: new MIME type needed too.)*
The code here is a **reference JavaScript implementation** for both Node.js
and all browsers. Its based directly off of Douglas Crockfords own [JSON
implementation][json_parse.js], and its both robust and secure.
## Why
JSON isnt the friendliest to *write*. Keys need to be quoted, objects and
arrays cant have trailing commas, and comments arent allowed — even though
none of these are the case with regular JavaScript today.
That was fine when JSONs goal was to be a great data format, but JSONs usage
has expanded beyond *machines*. JSON is now used for writing [configs][ex1],
[manifests][ex2], even [tests][ex3] — all by *humans*.
[ex1]: http://plovr.com/docs.html
[ex2]: https://www.npmjs.org/doc/files/package.json.html
[ex3]: http://code.google.com/p/fuzztester/wiki/JSONFileFormat
There are other formats that are human-friendlier, like YAML, but changing
from JSON to a completely different format is undesirable in many cases.
JSON5s aim is to remain close to JSON and JavaScript.
## Features
The following is the exact list of additions to JSONs syntax introduced by
JSON5. **All of these are optional**, and **all of these come from ES5**.
### Objects
- Object keys can be unquoted if theyre valid [identifiers][mdn_variables].
Yes, even reserved keywords (like `default`) are valid unquoted keys in ES5
[[§11.1.5](http://es5.github.com/#x11.1.5), [§7.6](http://es5.github.com/#x7.6)].
([More info](https://mathiasbynens.be/notes/javascript-identifiers))
*(TODO: Unicode characters and escape sequences arent yet supported in this
implementation.)*
- Object keys can also be single-quoted.
- Objects can have trailing commas.
[mdn_variables]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Variables
### Arrays
- Arrays can have trailing commas.
### Strings
- Strings can be single-quoted.
- Strings can be split across multiple lines; just prefix each newline with a
backslash. [ES5 [§7.8.4](http://es5.github.com/#x7.8.4)]
### Numbers
- Numbers can be hexadecimal (base 16).
- Numbers can begin or end with a (leading or trailing) decimal point.
- Numbers can include `Infinity`, `-Infinity`, `NaN`, and `-NaN`.
- Numbers can begin with an explicit plus sign.
### Comments
- Both inline (single-line) and block (multi-line) comments are allowed.
## Example
The following is a contrived example, but it illustrates most of the features:
```js
{
foo: 'bar',
while: true,
this: 'is a \
multi-line string',
// this is an inline comment
here: 'is another', // inline comment
/* this is a block comment
that continues on another line */
hex: 0xDEADbeef,
half: .5,
delta: +10,
to: Infinity, // and beyond!
finally: 'a trailing comma',
oh: [
"we shouldn't forget",
'arrays can have',
'trailing commas too',
],
}
```
This implementations own [package.json5](package.json5) is more realistic:
```js
// This file is written in JSON5 syntax, naturally, but npm needs a regular
// JSON file, so compile via `npm run build`. Be sure to keep both in sync!
{
name: 'json5',
version: '0.5.0',
description: 'JSON for the ES5 era.',
keywords: ['json', 'es5'],
author: 'Aseem Kishore <aseem.kishore@gmail.com>',
contributors: [
// TODO: Should we remove this section in favor of GitHub's list?
// https://github.com/aseemk/json5/contributors
'Max Nanasy <max.nanasy@gmail.com>',
'Andrew Eisenberg <andrew@eisenberg.as>',
'Jordan Tucker <jordanbtucker@gmail.com>',
],
main: 'lib/json5.js',
bin: 'lib/cli.js',
files: ["lib/"],
dependencies: {},
devDependencies: {
gulp: "^3.9.1",
'gulp-jshint': "^2.0.0",
jshint: "^2.9.1",
'jshint-stylish': "^2.1.0",
mocha: "^2.4.5"
},
scripts: {
build: 'node ./lib/cli.js -c package.json5',
test: 'mocha --ui exports --reporter spec',
// TODO: Would it be better to define these in a mocha.opts file?
},
homepage: 'http://json5.org/',
license: 'MIT',
repository: {
type: 'git',
url: 'https://github.com/aseemk/json5.git',
},
}
```
## Community
Join the [Google Group](http://groups.google.com/group/json5) if youre
interested in JSON5 news, updates, and general discussion.
Dont worry, its very low-traffic.
The [GitHub wiki](https://github.com/aseemk/json5/wiki) is a good place to track
JSON5 support and usage. Contribute freely there!
[GitHub Issues](https://github.com/aseemk/json5/issues) is the place to
formally propose feature requests and report bugs. Questions and general
feedback are better directed at the Google Group.
## Usage
This JavaScript implementation of JSON5 simply provides a `JSON5` object just
like the native ES5 `JSON` object.
To use from Node:
```sh
npm install json5
```
```js
var JSON5 = require('json5');
```
To use in the browser (adds the `JSON5` object to the global namespace):
```html
<script src="json5.js"></script>
```
Then in both cases, you can simply replace native `JSON` calls with `JSON5`:
```js
var obj = JSON5.parse('{unquoted:"key",trailing:"comma",}');
var str = JSON5.stringify(obj);
```
`JSON5.parse` supports all of the JSON5 features listed above (*TODO: except
Unicode*), as well as the native [`reviver` argument][json-parse].
[json-parse]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
`JSON5.stringify` mainly avoids quoting keys where possible, but we hope to
keep expanding it in the future (e.g. to also output trailing commas).
It supports the native [`replacer` and `space` arguments][json-stringify],
as well. *(TODO: Any implemented `toJSON` methods arent used today.)*
[json-stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
### Extras
If youre running this on Node, you can also register a JSON5 `require()` hook
to let you `require()` `.json5` files just like you can `.json` files:
```js
require('json5/lib/require');
require('./path/to/foo'); // tries foo.json5 after foo.js, foo.json, etc.
require('./path/to/bar.json5');
```
This module also provides a `json5` executable (requires Node) for converting
JSON5 files to JSON:
```sh
json5 -c path/to/foo.json5 # generates path/to/foo.json
```
## Development
```sh
git clone git://github.com/aseemk/json5.git
cd json5
npm install
npm test
```
As the `package.json5` file states, be sure to run `npm run build` on changes
to `package.json5`, since npm requires `package.json`.
Feel free to [file issues](https://github.com/aseemk/json5/issues) and submit
[pull requests](https://github.com/aseemk/json5/pulls) — contributions are
welcome. If you do submit a pull request, please be sure to add or update the
tests, and ensure that `npm test` continues to pass.
## License
MIT. See [LICENSE.md](./LICENSE.md) for details.
## Credits
[Michael Bolin](http://bolinfest.com/) independently arrived at and published
some of these same ideas with awesome explanations and detail.
Recommended reading:
[Suggested Improvements to JSON](http://bolinfest.com/essays/json.html)
[Douglas Crockford](http://www.crockford.com/) of course designed and built
JSON, but his state machine diagrams on the [JSON website](http://json.org/),
as cheesy as it may sound, gave me motivation and confidence that building a
new parser to implement these ideas this was within my reach!
This code is also modeled directly off of Dougs open-source [json_parse.js][]
parser. Im super grateful for that clean and well-documented code.
[json_parse.js]: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
[Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific
supporter, contributing multiple patches and ideas. Thanks Max!
[Andrew Eisenberg](https://github.com/aeisenberg) has contributed the
`stringify` method.
[Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely
with ES5 and is actively maintaining this project.

View File

@@ -0,0 +1,41 @@
#!/usr/bin/env node
// cli.js
// JSON5 command-line interface.
//
// This is pretty minimal for now; just supports compiling files via `-c`.
// TODO More useful functionality, like output path, watch, etc.?
var FS = require('fs');
var JSON5 = require('./json5');
var Path = require('path');
var USAGE = [
'Usage: json5 -c path/to/file.json5 ...',
'Compiles JSON5 files into sibling JSON files with the same basenames.',
].join('\n');
// if valid, args look like [node, json5, -c, file1, file2, ...]
var args = process.argv;
if (args.length < 4 || args[2] !== '-c') {
console.error(USAGE);
process.exit(1);
}
var cwd = process.cwd();
var files = args.slice(3);
// iterate over each file and convert JSON5 files to JSON:
files.forEach(function (file) {
var path = Path.resolve(cwd, file);
var basename = Path.basename(path, '.json5');
var dirname = Path.dirname(path);
var json5 = FS.readFileSync(path, 'utf8');
var obj = JSON5.parse(json5);
var json = JSON.stringify(obj, null, 4); // 4 spaces; TODO configurable?
path = Path.join(dirname, basename + '.json');
FS.writeFileSync(path, json, 'utf8');
});

View File

@@ -0,0 +1,770 @@
// json5.js
// Modern JSON. See README.md for details.
//
// This file is based directly off of Douglas Crockford's json_parse.js:
// https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
var JSON5 = (typeof exports === 'object' ? exports : {});
JSON5.parse = (function () {
"use strict";
// This is a function that can parse a JSON5 text, producing a JavaScript
// data structure. It is a simple, recursive descent parser. It does not use
// eval or regular expressions, so it can be used as a model for implementing
// a JSON5 parser in other languages.
// We are defining the function inside of another function to avoid creating
// global variables.
var at, // The index of the current character
lineNumber, // The current line number
columnNumber, // The current column number
ch, // The current character
escapee = {
"'": "'",
'"': '"',
'\\': '\\',
'/': '/',
'\n': '', // Replace escaped newlines in strings w/ empty string
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t'
},
ws = [
' ',
'\t',
'\r',
'\n',
'\v',
'\f',
'\xA0',
'\uFEFF'
],
text,
renderChar = function (chr) {
return chr === '' ? 'EOF' : "'" + chr + "'";
},
error = function (m) {
// Call error when something is wrong.
var error = new SyntaxError();
// beginning of message suffix to agree with that provided by Gecko - see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
error.message = m + " at line " + lineNumber + " column " + columnNumber + " of the JSON5 data. Still to read: " + JSON.stringify(text.substring(at - 1, at + 19));
error.at = at;
// These two property names have been chosen to agree with the ones in Gecko, the only popular
// environment which seems to supply this info on JSON.parse
error.lineNumber = lineNumber;
error.columnNumber = columnNumber;
throw error;
},
next = function (c) {
// If a c parameter is provided, verify that it matches the current character.
if (c && c !== ch) {
error("Expected " + renderChar(c) + " instead of " + renderChar(ch));
}
// Get the next character. When there are no more characters,
// return the empty string.
ch = text.charAt(at);
at++;
columnNumber++;
if (ch === '\n' || ch === '\r' && peek() !== '\n') {
lineNumber++;
columnNumber = 0;
}
return ch;
},
peek = function () {
// Get the next character without consuming it or
// assigning it to the ch varaible.
return text.charAt(at);
},
identifier = function () {
// Parse an identifier. Normally, reserved words are disallowed here, but we
// only use this for unquoted object keys, where reserved words are allowed,
// so we don't check for those here. References:
// - http://es5.github.com/#x7.6
// - https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Variables
// - http://docstore.mik.ua/orelly/webprog/jscript/ch02_07.htm
// TODO Identifiers can have Unicode "letters" in them; add support for those.
var key = ch;
// Identifiers must start with a letter, _ or $.
if ((ch !== '_' && ch !== '$') &&
(ch < 'a' || ch > 'z') &&
(ch < 'A' || ch > 'Z')) {
error("Bad identifier as unquoted key");
}
// Subsequent characters can contain digits.
while (next() && (
ch === '_' || ch === '$' ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9'))) {
key += ch;
}
return key;
},
number = function () {
// Parse a number value.
var number,
sign = '',
string = '',
base = 10;
if (ch === '-' || ch === '+') {
sign = ch;
next(ch);
}
// support for Infinity (could tweak to allow other words):
if (ch === 'I') {
number = word();
if (typeof number !== 'number' || isNaN(number)) {
error('Unexpected word for number');
}
return (sign === '-') ? -number : number;
}
// support for NaN
if (ch === 'N' ) {
number = word();
if (!isNaN(number)) {
error('expected word to be NaN');
}
// ignore sign as -NaN also is NaN
return number;
}
if (ch === '0') {
string += ch;
next();
if (ch === 'x' || ch === 'X') {
string += ch;
next();
base = 16;
} else if (ch >= '0' && ch <= '9') {
error('Octal literal');
}
}
switch (base) {
case 10:
while (ch >= '0' && ch <= '9' ) {
string += ch;
next();
}
if (ch === '.') {
string += '.';
while (next() && ch >= '0' && ch <= '9') {
string += ch;
}
}
if (ch === 'e' || ch === 'E') {
string += ch;
next();
if (ch === '-' || ch === '+') {
string += ch;
next();
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
}
break;
case 16:
while (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {
string += ch;
next();
}
break;
}
if(sign === '-') {
number = -string;
} else {
number = +string;
}
if (!isFinite(number)) {
error("Bad number");
} else {
return number;
}
},
string = function () {
// Parse a string value.
var hex,
i,
string = '',
delim, // double quote or single quote
uffff;
// When parsing for string values, we must look for ' or " and \ characters.
if (ch === '"' || ch === "'") {
delim = ch;
while (next()) {
if (ch === delim) {
next();
return string;
} else if (ch === '\\') {
next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (ch === '\r') {
if (peek() === '\n') {
next();
}
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break;
}
} else if (ch === '\n') {
// unescaped newlines are invalid; see:
// https://github.com/aseemk/json5/issues/24
// TODO this feels special-cased; are there other
// invalid unescaped chars?
break;
} else {
string += ch;
}
}
}
error("Bad string");
},
inlineComment = function () {
// Skip an inline comment, assuming this is one. The current character should
// be the second / character in the // pair that begins this inline comment.
// To finish the inline comment, we look for a newline or the end of the text.
if (ch !== '/') {
error("Not an inline comment");
}
do {
next();
if (ch === '\n' || ch === '\r') {
next();
return;
}
} while (ch);
},
blockComment = function () {
// Skip a block comment, assuming this is one. The current character should be
// the * character in the /* pair that begins this block comment.
// To finish the block comment, we look for an ending */ pair of characters,
// but we also watch for the end of text before the comment is terminated.
if (ch !== '*') {
error("Not a block comment");
}
do {
next();
while (ch === '*') {
next('*');
if (ch === '/') {
next('/');
return;
}
}
} while (ch);
error("Unterminated block comment");
},
comment = function () {
// Skip a comment, whether inline or block-level, assuming this is one.
// Comments always begin with a / character.
if (ch !== '/') {
error("Not a comment");
}
next('/');
if (ch === '/') {
inlineComment();
} else if (ch === '*') {
blockComment();
} else {
error("Unrecognized comment");
}
},
white = function () {
// Skip whitespace and comments.
// Note that we're detecting comments by only a single / character.
// This works since regular expressions are not valid JSON(5), but this will
// break if there are other valid values that begin with a / character!
while (ch) {
if (ch === '/') {
comment();
} else if (ws.indexOf(ch) >= 0) {
next();
} else {
return;
}
}
},
word = function () {
// true, false, or null.
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return true;
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return false;
case 'n':
next('n');
next('u');
next('l');
next('l');
return null;
case 'I':
next('I');
next('n');
next('f');
next('i');
next('n');
next('i');
next('t');
next('y');
return Infinity;
case 'N':
next( 'N' );
next( 'a' );
next( 'N' );
return NaN;
}
error("Unexpected " + renderChar(ch));
},
value, // Place holder for the value function.
array = function () {
// Parse an array value.
var array = [];
if (ch === '[') {
next('[');
white();
while (ch) {
if (ch === ']') {
next(']');
return array; // Potentially empty array
}
// ES5 allows omitting elements in arrays, e.g. [,] and
// [,null]. We don't allow this in JSON5.
if (ch === ',') {
error("Missing array element");
} else {
array.push(value());
}
white();
// If there's no comma after this value, this needs to
// be the end of the array.
if (ch !== ',') {
next(']');
return array;
}
next(',');
white();
}
}
error("Bad array");
},
object = function () {
// Parse an object value.
var key,
object = {};
if (ch === '{') {
next('{');
white();
while (ch) {
if (ch === '}') {
next('}');
return object; // Potentially empty object
}
// Keys can be unquoted. If they are, they need to be
// valid JS identifiers.
if (ch === '"' || ch === "'") {
key = string();
} else {
key = identifier();
}
white();
next(':');
object[key] = value();
white();
// If there's no comma after this pair, this needs to be
// the end of the object.
if (ch !== ',') {
next('}');
return object;
}
next(',');
white();
}
}
error("Bad object");
};
value = function () {
// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.
white();
switch (ch) {
case '{':
return object();
case '[':
return array();
case '"':
case "'":
return string();
case '-':
case '+':
case '.':
return number();
default:
return ch >= '0' && ch <= '9' ? number() : word();
}
};
// Return the json_parse function. It will have access to all of the above
// functions and variables.
return function (source, reviver) {
var result;
text = String(source);
at = 0;
lineNumber = 1;
columnNumber = 1;
ch = ' ';
result = value();
white();
if (ch) {
error("Syntax error");
}
// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.
return typeof reviver === 'function' ? (function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}({'': result}, '')) : result;
};
}());
// JSON5 stringify will not quote keys where appropriate
JSON5.stringify = function (obj, replacer, space) {
if (replacer && (typeof(replacer) !== "function" && !isArray(replacer))) {
throw new Error('Replacer must be a function or an array');
}
var getReplacedValueOrUndefined = function(holder, key, isTopLevel) {
var value = holder[key];
// Replace the value with its toJSON value first, if possible
if (value && value.toJSON && typeof value.toJSON === "function") {
value = value.toJSON();
}
// If the user-supplied replacer if a function, call it. If it's an array, check objects' string keys for
// presence in the array (removing the key/value pair from the resulting JSON if the key is missing).
if (typeof(replacer) === "function") {
return replacer.call(holder, key, value);
} else if(replacer) {
if (isTopLevel || isArray(holder) || replacer.indexOf(key) >= 0) {
return value;
} else {
return undefined;
}
} else {
return value;
}
};
function isWordChar(c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c === '_' || c === '$';
}
function isWordStart(c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c === '_' || c === '$';
}
function isWord(key) {
if (typeof key !== 'string') {
return false;
}
if (!isWordStart(key[0])) {
return false;
}
var i = 1, length = key.length;
while (i < length) {
if (!isWordChar(key[i])) {
return false;
}
i++;
}
return true;
}
// export for use in tests
JSON5.isWord = isWord;
// polyfills
function isArray(obj) {
if (Array.isArray) {
return Array.isArray(obj);
} else {
return Object.prototype.toString.call(obj) === '[object Array]';
}
}
function isDate(obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
var objStack = [];
function checkForCircular(obj) {
for (var i = 0; i < objStack.length; i++) {
if (objStack[i] === obj) {
throw new TypeError("Converting circular structure to JSON");
}
}
}
function makeIndent(str, num, noNewLine) {
if (!str) {
return "";
}
// indentation no more than 10 chars
if (str.length > 10) {
str = str.substring(0, 10);
}
var indent = noNewLine ? "" : "\n";
for (var i = 0; i < num; i++) {
indent += str;
}
return indent;
}
var indentStr;
if (space) {
if (typeof space === "string") {
indentStr = space;
} else if (typeof space === "number" && space >= 0) {
indentStr = makeIndent(" ", space, true);
} else {
// ignore space parameter
}
}
// Copied from Crokford's implementation of JSON
// See https://github.com/douglascrockford/JSON-js/blob/e39db4b7e6249f04a195e7dd0840e610cc9e941e/json2.js#L195
// Begin
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
function escapeString(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ?
c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
// End
function internalStringify(holder, key, isTopLevel) {
var buffer, res;
// Replace the value, if necessary
var obj_part = getReplacedValueOrUndefined(holder, key, isTopLevel);
if (obj_part && !isDate(obj_part)) {
// unbox objects
// don't unbox dates, since will turn it into number
obj_part = obj_part.valueOf();
}
switch(typeof obj_part) {
case "boolean":
return obj_part.toString();
case "number":
if (isNaN(obj_part) || !isFinite(obj_part)) {
return "null";
}
return obj_part.toString();
case "string":
return escapeString(obj_part.toString());
case "object":
if (obj_part === null) {
return "null";
} else if (isArray(obj_part)) {
checkForCircular(obj_part);
buffer = "[";
objStack.push(obj_part);
for (var i = 0; i < obj_part.length; i++) {
res = internalStringify(obj_part, i, false);
buffer += makeIndent(indentStr, objStack.length);
if (res === null || typeof res === "undefined") {
buffer += "null";
} else {
buffer += res;
}
if (i < obj_part.length-1) {
buffer += ",";
} else if (indentStr) {
buffer += "\n";
}
}
objStack.pop();
if (obj_part.length) {
buffer += makeIndent(indentStr, objStack.length, true)
}
buffer += "]";
} else {
checkForCircular(obj_part);
buffer = "{";
var nonEmpty = false;
objStack.push(obj_part);
for (var prop in obj_part) {
if (obj_part.hasOwnProperty(prop)) {
var value = internalStringify(obj_part, prop, false);
isTopLevel = false;
if (typeof value !== "undefined" && value !== null) {
buffer += makeIndent(indentStr, objStack.length);
nonEmpty = true;
key = isWord(prop) ? prop : escapeString(prop);
buffer += key + ":" + (indentStr ? ' ' : '') + value + ",";
}
}
}
objStack.pop();
if (nonEmpty) {
buffer = buffer.substring(0, buffer.length-1) + makeIndent(indentStr, objStack.length) + "}";
} else {
buffer = '{}';
}
}
return buffer;
default:
// functions and undefined should be ignored
return undefined;
}
}
// special case...when undefined is used inside of
// a compound object/array, return null.
// but when top-level, return undefined
var topLevelHolder = {"":obj};
if (obj === undefined) {
return getReplacedValueOrUndefined(topLevelHolder, '', true);
}
return internalStringify(topLevelHolder, '', true);
};

View File

@@ -0,0 +1,18 @@
// require.js
// Node.js only: adds a require() hook for .json5 files, just like the native
// hook for .json files.
//
// Usage:
// require('json5/require');
// require('./foo'); // will check foo.json5 after foo.js, foo.json, etc.
// require('./bar.json5');
var FS = require('fs');
var JSON5 = require('./json5');
// Modeled off of (v0.6.18 link; check latest too):
// https://github.com/joyent/node/blob/v0.6.18/lib/module.js#L468-L472
require.extensions['.json5'] = function (module, filename) {
var content = FS.readFileSync(filename, 'utf8');
module.exports = JSON5.parse(content);
};

View File

@@ -0,0 +1,83 @@
{
"_args": [
[
"json5@0.5.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "json5@0.5.1",
"_id": "json5@0.5.1",
"_inBundle": false,
"_integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=",
"_location": "/babel-loader/json5",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "json5@0.5.1",
"name": "json5",
"escapedName": "json5",
"rawSpec": "0.5.1",
"saveSpec": null,
"fetchSpec": "0.5.1"
},
"_requiredBy": [
"/babel-loader/loader-utils"
],
"_resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz",
"_spec": "0.5.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Aseem Kishore",
"email": "aseem.kishore@gmail.com"
},
"bin": {
"json5": "lib/cli.js"
},
"bugs": {
"url": "https://github.com/aseemk/json5/issues"
},
"contributors": [
{
"name": "Max Nanasy",
"email": "max.nanasy@gmail.com"
},
{
"name": "Andrew Eisenberg",
"email": "andrew@eisenberg.as"
},
{
"name": "Jordan Tucker",
"email": "jordanbtucker@gmail.com"
}
],
"dependencies": {},
"description": "JSON for the ES5 era.",
"devDependencies": {
"gulp": "^3.9.1",
"gulp-jshint": "^2.0.1",
"jshint": "^2.9.3",
"jshint-stylish": "^2.2.1",
"mocha": "^3.1.0"
},
"files": [
"lib/"
],
"homepage": "http://json5.org/",
"keywords": [
"json",
"es5"
],
"license": "MIT",
"main": "lib/json5.js",
"name": "json5",
"repository": {
"type": "git",
"url": "git+https://github.com/aseemk/json5.git"
},
"scripts": {
"build": "node ./lib/cli.js -c package.json5",
"test": "mocha --ui exports --reporter spec"
},
"version": "0.5.1"
}

View File

@@ -0,0 +1,18 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="1.1.0"></a>
# [1.1.0](https://github.com/webpack/loader-utils/compare/v1.0.4...v1.1.0) (2017-03-16)
### Features
* **automatic-release:** Generation of automatic release ([7484d13](https://github.com/webpack/loader-utils/commit/7484d13))
* **parseQuery:** export parseQuery ([ddf64e4](https://github.com/webpack/loader-utils/commit/ddf64e4))
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

View File

@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
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,229 @@
# loader-utils
## Methods
### `getOptions`
Recommended way to retrieve the options of a loader invocation:
```javascript
// inside your loader
const options = loaderUtils.getOptions(this);
```
1. If `this.query` is a string:
- Tries to parse the query string and returns a new object
- Throws if it's not a valid query string
2. If `this.query` is object-like, it just returns `this.query`
3. In any other case, it just returns `null`
**Please note:** The returned `options` object is *read-only*. It may be re-used across multiple invocations.
If you pass it on to another library, make sure to make a *deep copy* of it:
```javascript
const options = Object.assign(
{},
loaderUtils.getOptions(this), // it is safe to pass null to Object.assign()
defaultOptions
);
// don't forget nested objects or arrays
options.obj = Object.assign({}, options.obj);
options.arr = options.arr.slice();
someLibrary(options);
```
[clone-deep](https://www.npmjs.com/package/clone-deep) is a good library to make a deep copy of the options.
#### Options as query strings
If the loader options have been passed as loader query string (`loader?some&params`), the string is parsed by using [`parseQuery`](#parsequery).
### `parseQuery`
Parses a passed string (e.g. `loaderContext.resourceQuery`) as a query string, and returns an object.
``` javascript
const params = loaderUtils.parseQuery(this.resourceQuery); // resource: `file?param1=foo`
if (params.param1 === "foo") {
// do something
}
```
The string is parsed like this:
``` text
-> Error
? -> {}
?flag -> { flag: true }
?+flag -> { flag: true }
?-flag -> { flag: false }
?xyz=test -> { xyz: "test" }
?xyz=1 -> { xyz: "1" } // numbers are NOT parsed
?xyz[]=a -> { xyz: ["a"] }
?flag1&flag2 -> { flag1: true, flag2: true }
?+flag1,-flag2 -> { flag1: true, flag2: false }
?xyz[]=a,xyz[]=b -> { xyz: ["a", "b"] }
?a%2C%26b=c%2C%26d -> { "a,&b": "c,&d" }
?{data:{a:1},isJSON5:true} -> { data: { a: 1 }, isJSON5: true }
```
### `stringifyRequest`
Turns a request into a string that can be used inside `require()` or `import` while avoiding absolute paths.
Use it instead of `JSON.stringify(...)` if you're generating code inside a loader.
**Why is this necessary?** Since webpack calculates the hash before module paths are translated into module ids, we must avoid absolute paths to ensure
consistent hashes across different compilations.
This function:
- resolves absolute requests into relative requests if the request and the module are on the same hard drive
- replaces `\` with `/` if the request and the module are on the same hard drive
- won't change the path at all if the request and the module are on different hard drives
- applies `JSON.stringify` to the result
```javascript
loaderUtils.stringifyRequest(this, "./test.js");
// "\"./test.js\""
loaderUtils.stringifyRequest(this, ".\\test.js");
// "\"./test.js\""
loaderUtils.stringifyRequest(this, "test");
// "\"test\""
loaderUtils.stringifyRequest(this, "test/lib/index.js");
// "\"test/lib/index.js\""
loaderUtils.stringifyRequest(this, "otherLoader?andConfig!test?someConfig");
// "\"otherLoader?andConfig!test?someConfig\""
loaderUtils.stringifyRequest(this, require.resolve("test"));
// "\"../node_modules/some-loader/lib/test.js\""
loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
// "\"../../test.js\"" (on Windows, in case the module and the request are on the same drive)
loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
// "\"C:\\module\\test.js\"" (on Windows, in case the module and the request are on different drives)
loaderUtils.stringifyRequest(this, "\\\\network-drive\\test.js");
// "\"\\\\network-drive\\\\test.js\"" (on Windows, in case the module and the request are on different drives)
```
### `urlToRequest`
Converts some resource URL to a webpack module request.
```javascript
const url = "path/to/module.js";
const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
```
#### Module URLs
Any URL containing a `~` will be interpreted as a module request. Anything after the `~` will be considered the request path.
```javascript
const url = "~path/to/module.js";
const request = loaderUtils.urlToRequest(url); // "path/to/module.js"
```
#### Root-relative URLs
URLs that are root-relative (start with `/`) can be resolved relative to some arbitrary path by using the `root` parameter:
```javascript
const url = "/path/to/module.js";
const root = "./root";
const request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js"
```
To convert a root-relative URL into a module URL, specify a `root` value that starts with `~`:
```javascript
const url = "/path/to/module.js";
const root = "~";
const request = loaderUtils.urlToRequest(url, root); // "path/to/module.js"
```
### `interpolateName`
Interpolates a filename template using multiple placeholders and/or a regular expression.
The template and regular expression are set as query params called `name` and `regExp` on the current loader's context.
```javascript
const interpolatedName = loaderUtils.interpolateName(loaderContext, name, options);
```
The following tokens are replaced in the `name` parameter:
* `[ext]` the extension of the resource
* `[name]` the basename of the resource
* `[path]` the path of the resource relative to the `context` query parameter or option.
* `[folder]` the folder of the resource is in.
* `[emoji]` a random emoji representation of `options.content`
* `[emoji:<length>]` same as above, but with a customizable number of emojis
* `[hash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md5 hash)
* `[<hashType>:hash:<digestType>:<length>]` optionally one can configure
* other `hashType`s, i. e. `sha1`, `md5`, `sha256`, `sha512`
* other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
* and `length` the length in chars
* `[N]` the N-th match obtained from matching the current file name against `options.regExp`
Examples
``` javascript
// loaderContext.resourcePath = "/app/js/javascript.js"
loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext]", { content: ... });
// => js/9473fdd0d880a43c21b7778d34872157.script.js
// loaderContext.resourcePath = "/app/page.html"
loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... });
// => html-9473fd.html
// loaderContext.resourcePath = "/app/flash.txt"
loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... });
// => c31e9820c001c9c4a86bce33ce43b679
// loaderContext.resourcePath = "/app/img/image.gif"
loaderUtils.interpolateName(loaderContext, "[emoji]", { content: ... });
// => 👍
// loaderContext.resourcePath = "/app/img/image.gif"
loaderUtils.interpolateName(loaderContext, "[emoji:4]", { content: ... });
// => 🙍🏢📤🐝
// loaderContext.resourcePath = "/app/img/image.png"
loaderUtils.interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: ... });
// => 2BKDTjl.png
// use sha512 hash instead of md5 and with only 7 chars of base64
// loaderContext.resourcePath = "/app/img/myself.png"
// loaderContext.query.name =
loaderUtils.interpolateName(loaderContext, "picture.png");
// => picture.png
// loaderContext.resourcePath = "/app/dir/file.png"
loaderUtils.interpolateName(loaderContext, "[path][name].[ext]?[hash]", { content: ... });
// => /app/dir/file.png?9473fdd0d880a43c21b7778d34872157
// loaderContext.resourcePath = "/app/js/page-home.js"
loaderUtils.interpolateName(loaderContext, "script-[1].[ext]", { regExp: "page-(.*)\\.js", content: ... });
// => script-home.js
```
### `getHashDigest`
``` javascript
const digestString = loaderUtils.getHashDigest(buffer, hashType, digestType, maxLength);
```
* `buffer` the content that should be hashed
* `hashType` one of `sha1`, `md5`, `sha256`, `sha512` or any other node.js supported hash type
* `digestType` one of `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
* `maxLength` the maximum length in chars
## License
MIT (http://www.opensource.org/licenses/mit-license.php)

View File

@@ -0,0 +1,13 @@
"use strict";
function getCurrentRequest(loaderContext) {
if(loaderContext.currentRequest)
return loaderContext.currentRequest;
const request = loaderContext.loaders
.slice(loaderContext.loaderIndex)
.map(obj => obj.request)
.concat([loaderContext.resource]);
return request.join("!");
}
module.exports = getCurrentRequest;

View File

@@ -0,0 +1,53 @@
"use strict";
const baseEncodeTables = {
26: "abcdefghijklmnopqrstuvwxyz",
32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
36: "0123456789abcdefghijklmnopqrstuvwxyz",
49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
};
function encodeBufferToBase(buffer, base) {
const encodeTable = baseEncodeTables[base];
if(!encodeTable) throw new Error("Unknown encoding base" + base);
const readLength = buffer.length;
const Big = require("big.js");
Big.RM = Big.DP = 0;
let b = new Big(0);
for(let i = readLength - 1; i >= 0; i--) {
b = b.times(256).plus(buffer[i]);
}
let output = "";
while(b.gt(0)) {
output = encodeTable[b.mod(base)] + output;
b = b.div(base);
}
Big.DP = 20;
Big.RM = 1;
return output;
}
function getHashDigest(buffer, hashType, digestType, maxLength) {
hashType = hashType || "md5";
maxLength = maxLength || 9999;
const hash = require("crypto").createHash(hashType);
hash.update(buffer);
if(digestType === "base26" || digestType === "base32" || digestType === "base36" ||
digestType === "base49" || digestType === "base52" || digestType === "base58" ||
digestType === "base62" || digestType === "base64") {
return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(0, maxLength);
} else {
return hash.digest(digestType || "hex").substr(0, maxLength);
}
}
module.exports = getHashDigest;

View File

@@ -0,0 +1,17 @@
"use strict";
const parseQuery = require("./parseQuery");
function getOptions(loaderContext) {
const query = loaderContext.query;
if(typeof query === "string" && query !== "") {
return parseQuery(loaderContext.query);
}
if(!query || typeof query !== "object") {
// Not object-like queries are not supported.
return null;
}
return query;
}
module.exports = getOptions;

View File

@@ -0,0 +1,13 @@
"use strict";
function getRemainingRequest(loaderContext) {
if(loaderContext.remainingRequest)
return loaderContext.remainingRequest;
const request = loaderContext.loaders
.slice(loaderContext.loaderIndex + 1)
.map(obj => obj.request)
.concat([loaderContext.resource]);
return request.join("!");
}
module.exports = getRemainingRequest;

View File

@@ -0,0 +1,23 @@
"use strict";
const getOptions = require("./getOptions");
const parseQuery = require("./parseQuery");
const stringifyRequest = require("./stringifyRequest");
const getRemainingRequest = require("./getRemainingRequest");
const getCurrentRequest = require("./getCurrentRequest");
const isUrlRequest = require("./isUrlRequest");
const urlToRequest = require("./urlToRequest");
const parseString = require("./parseString");
const getHashDigest = require("./getHashDigest");
const interpolateName = require("./interpolateName");
exports.getOptions = getOptions;
exports.parseQuery = parseQuery;
exports.stringifyRequest = stringifyRequest;
exports.getRemainingRequest = getRemainingRequest;
exports.getCurrentRequest = getCurrentRequest;
exports.isUrlRequest = isUrlRequest;
exports.urlToRequest = urlToRequest;
exports.parseString = parseString;
exports.getHashDigest = getHashDigest;
exports.interpolateName = interpolateName;

View File

@@ -0,0 +1,95 @@
"use strict";
const path = require("path");
const emojisList = require("emojis-list");
const getHashDigest = require("./getHashDigest");
const emojiRegex = /[\uD800-\uDFFF]./;
const emojiList = emojisList.filter(emoji => emojiRegex.test(emoji));
const emojiCache = {};
function encodeStringToEmoji(content, length) {
if(emojiCache[content]) return emojiCache[content];
length = length || 1;
const emojis = [];
do {
const index = Math.floor(Math.random() * emojiList.length);
emojis.push(emojiList[index]);
emojiList.splice(index, 1);
} while(--length > 0);
const emojiEncoding = emojis.join("");
emojiCache[content] = emojiEncoding;
return emojiEncoding;
}
function interpolateName(loaderContext, name, options) {
let filename;
if(typeof name === "function") {
filename = name(loaderContext.resourcePath);
} else {
filename = name || "[hash].[ext]";
}
const context = options.context;
const content = options.content;
const regExp = options.regExp;
let ext = "bin";
let basename = "file";
let directory = "";
let folder = "";
if(loaderContext.resourcePath) {
const parsed = path.parse(loaderContext.resourcePath);
let resourcePath = loaderContext.resourcePath;
if(parsed.ext) {
ext = parsed.ext.substr(1);
}
if(parsed.dir) {
basename = parsed.name;
resourcePath = parsed.dir + path.sep;
}
if(typeof context !== "undefined") {
directory = path.relative(context, resourcePath + "_").replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
directory = directory.substr(0, directory.length - 1);
} else {
directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
}
if(directory.length === 1) {
directory = "";
} else if(directory.length > 1) {
folder = path.basename(directory);
}
}
let url = filename;
if(content) {
// Match hash template
url = url
.replace(
/\[(?:(\w+):)?hash(?::([a-z]+\d*))?(?::(\d+))?\]/ig,
(all, hashType, digestType, maxLength) => getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
)
.replace(
/\[emoji(?::(\d+))?\]/ig,
(all, length) => encodeStringToEmoji(content, length)
);
}
url = url
.replace(/\[ext\]/ig, () => ext)
.replace(/\[name\]/ig, () => basename)
.replace(/\[path\]/ig, () => directory)
.replace(/\[folder\]/ig, () => folder);
if(regExp && loaderContext.resourcePath) {
const match = loaderContext.resourcePath.match(new RegExp(regExp));
match && match.forEach((matched, i) => {
url = url.replace(
new RegExp("\\[" + i + "\\]", "ig"),
matched
);
});
}
if(typeof loaderContext.options === "object" && typeof loaderContext.options.customInterpolateName === "function") {
url = loaderContext.options.customInterpolateName.call(loaderContext, url, name, options);
}
return url;
}
module.exports = interpolateName;

View File

@@ -0,0 +1,14 @@
"use strict";
function isUrlRequest(url, root) {
// An URL is not an request if
// 1. it's a Data Url
// 2. it's an absolute url or and protocol-relative
// 3. it's some kind of url for a template
if(/^data:|^chrome-extension:|^(https?:)?\/\/|^[\{\}\[\]#*;,'§\$%&\(=?`´\^°<>]/.test(url)) return false;
// 4. It's also not an request if root isn't set and it's a root-relative url
if((root === undefined || root === false) && /^\//.test(url)) return false;
return true;
}
module.exports = isUrlRequest;

View File

@@ -0,0 +1,54 @@
"use strict";
const JSON5 = require("json5");
const specialValues = {
"null": null,
"true": true,
"false": false
};
function parseQuery(query) {
if(query.substr(0, 1) !== "?") {
throw new Error("A valid query string passed to parseQuery should begin with '?'");
}
query = query.substr(1);
if(!query) {
return {};
}
if(query.substr(0, 1) === "{" && query.substr(-1) === "}") {
return JSON5.parse(query);
}
const queryArgs = query.split(/[,&]/g);
const result = {};
queryArgs.forEach(arg => {
const idx = arg.indexOf("=");
if(idx >= 0) {
let name = arg.substr(0, idx);
let value = decodeURIComponent(arg.substr(idx + 1));
if(specialValues.hasOwnProperty(value)) {
value = specialValues[value];
}
if(name.substr(-2) === "[]") {
name = decodeURIComponent(name.substr(0, name.length - 2));
if(!Array.isArray(result[name]))
result[name] = [];
result[name].push(value);
} else {
name = decodeURIComponent(name);
result[name] = value;
}
} else {
if(arg.substr(0, 1) === "-") {
result[decodeURIComponent(arg.substr(1))] = false;
} else if(arg.substr(0, 1) === "+") {
result[decodeURIComponent(arg.substr(1))] = true;
} else {
result[decodeURIComponent(arg)] = true;
}
}
});
return result;
}
module.exports = parseQuery;

View File

@@ -0,0 +1,19 @@
"use strict";
function parseString(str) {
try {
if(str[0] === "\"") return JSON.parse(str);
if(str[0] === "'" && str.substr(str.length - 1) === "'") {
return parseString(
str
.replace(/\\.|"/g, x => x === "\"" ? "\\\"" : x)
.replace(/^'|'$/g, "\"")
);
}
return JSON.parse("\"" + str + "\"");
} catch(e) {
return str;
}
}
module.exports = parseString;

View File

@@ -0,0 +1,40 @@
"use strict";
const path = require("path");
const matchRelativePath = /^\.\.?[/\\]/;
function isAbsolutePath(str) {
return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
}
function isRelativePath(str) {
return matchRelativePath.test(str);
}
function stringifyRequest(loaderContext, request) {
const splitted = request.split("!");
const context = loaderContext.context || (loaderContext.options && loaderContext.options.context);
return JSON.stringify(splitted.map(part => {
// First, separate singlePath from query, because the query might contain paths again
const splittedPart = part.match(/^(.*?)(\?.*)/);
let singlePath = splittedPart ? splittedPart[1] : part;
const query = splittedPart ? splittedPart[2] : "";
if(isAbsolutePath(singlePath) && context) {
singlePath = path.relative(context, singlePath);
if(isAbsolutePath(singlePath)) {
// If singlePath still matches an absolute path, singlePath was on a different drive than context.
// In this case, we leave the path platform-specific without replacing any separators.
// @see https://github.com/webpack/loader-utils/pull/14
return singlePath + query;
}
if(isRelativePath(singlePath) === false) {
// Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
singlePath = "./" + singlePath;
}
}
return singlePath.replace(/\\/g, "/") + query;
}).join("!"));
}
module.exports = stringifyRequest;

View File

@@ -0,0 +1,49 @@
"use strict";
// we can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
function urlToRequest(url, root) {
const moduleRequestRegex = /^[^?]*~/;
let request;
if(matchNativeWin32Path.test(url)) {
// absolute windows path, keep it
request = url;
} else if(root !== undefined && root !== false && /^\//.test(url)) {
// if root is set and the url is root-relative
switch(typeof root) {
// 1. root is a string: root is prefixed to the url
case "string":
// special case: `~` roots convert to module request
if(moduleRequestRegex.test(root)) {
request = root.replace(/([^~\/])$/, "$1/") + url.slice(1);
} else {
request = root + url;
}
break;
// 2. root is `true`: absolute paths are allowed
// *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
case "boolean":
request = url;
break;
default:
throw new Error("Unexpected parameters to loader-utils 'urlToRequest': url = " + url + ", root = " + root + ".");
}
} else if(/^\.\.?\//.test(url)) {
// A relative url stays
request = url;
} else {
// every other url is threaded like a relative url
request = "./" + url;
}
// A `~` makes the url an module
if(moduleRequestRegex.test(request)) {
request = request.replace(moduleRequestRegex, "");
}
return request;
}
module.exports = urlToRequest;

View File

@@ -0,0 +1,73 @@
{
"_args": [
[
"loader-utils@1.1.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "loader-utils@1.1.0",
"_id": "loader-utils@1.1.0",
"_inBundle": false,
"_integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=",
"_location": "/babel-loader/loader-utils",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "loader-utils@1.1.0",
"name": "loader-utils",
"escapedName": "loader-utils",
"rawSpec": "1.1.0",
"saveSpec": null,
"fetchSpec": "1.1.0"
},
"_requiredBy": [
"/babel-loader"
],
"_resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz",
"_spec": "1.1.0",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Tobias Koppers @sokra"
},
"bugs": {
"url": "https://github.com/webpack/loader-utils/issues"
},
"dependencies": {
"big.js": "^3.1.3",
"emojis-list": "^2.0.0",
"json5": "^0.5.0"
},
"description": "utils for webpack loaders",
"devDependencies": {
"coveralls": "^2.11.2",
"eslint": "^3.15.0",
"eslint-plugin-node": "^4.0.1",
"istanbul": "^0.3.14",
"mocha": "^1.21.4",
"standard-version": "^4.0.0"
},
"engines": {
"node": ">=4.0.0"
},
"files": [
"lib"
],
"homepage": "https://github.com/webpack/loader-utils#readme",
"license": "MIT",
"main": "lib/index.js",
"name": "loader-utils",
"repository": {
"type": "git",
"url": "git+https://github.com/webpack/loader-utils.git"
},
"scripts": {
"cover": "istanbul cover -x *.runtime.js node_modules/mocha/bin/_mocha",
"lint": "eslint lib test",
"posttest": "npm run lint",
"release": "npm test && standard-version",
"test": "mocha",
"travis": "npm run cover -- --report lcovonly"
},
"version": "1.1.0"
}

View File

@@ -0,0 +1,24 @@
'use strict';
const path = require('path');
const pathExists = require('path-exists');
const pLocate = require('p-locate');
module.exports = (iterable, opts) => {
opts = Object.assign({
cwd: process.cwd()
}, opts);
return pLocate(iterable, el => pathExists(path.resolve(opts.cwd, el)), opts);
};
module.exports.sync = (iterable, opts) => {
opts = Object.assign({
cwd: process.cwd()
}, opts);
for (const el of iterable) {
if (pathExists.sync(path.resolve(opts.cwd, el))) {
return el;
}
}
};

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,82 @@
{
"_args": [
[
"locate-path@2.0.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "locate-path@2.0.0",
"_id": "locate-path@2.0.0",
"_inBundle": false,
"_integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=",
"_location": "/babel-loader/locate-path",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "locate-path@2.0.0",
"name": "locate-path",
"escapedName": "locate-path",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"/babel-loader/find-up"
],
"_resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz",
"_spec": "2.0.0",
"_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/sindresorhus/locate-path/issues"
},
"dependencies": {
"p-locate": "^2.0.0",
"path-exists": "^3.0.0"
},
"description": "Get the first path that exists on disk of multiple paths",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/locate-path#readme",
"keywords": [
"locate",
"path",
"paths",
"file",
"files",
"exists",
"find",
"finder",
"search",
"searcher",
"array",
"iterable",
"iterator"
],
"license": "MIT",
"name": "locate-path",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/locate-path.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0",
"xo": {
"esnext": true
}
}

View File

@@ -0,0 +1,99 @@
# locate-path [![Build Status](https://travis-ci.org/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.org/sindresorhus/locate-path)
> Get the first path that exists on disk of multiple paths
## Install
```
$ npm install --save locate-path
```
## Usage
Here we find the first file that exists on disk, in array order.
```js
const locatePath = require('locate-path');
const files = [
'unicorn.png',
'rainbow.png', // only this one actually exists on disk
'pony.png'
];
locatePath(files).then(foundPath => {
console.log(foundPath);
//=> 'rainbow'
});
```
## API
### locatePath(input, [options])
Returns a `Promise` for the first path that exists or `undefined` if none exists.
#### input
Type: `Iterable<string>`
Paths to check.
#### options
Type: `Object`
##### concurrency
Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`
Number of concurrently pending promises.
##### preserveOrder
Type: `boolean`<br>
Default: `true`
Preserve `input` order when searching.
Disable this to improve performance if you don't care about the order.
##### cwd
Type: `string`<br>
Default: `process.cwd()`
Current working directory.
### locatePath.sync(input, [options])
Returns the first path that exists or `undefined` if none exists.
#### input
Type: `Iterable<string>`
Paths to check.
#### options
Type: `Object`
##### cwd
Same as above.
## Related
- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@@ -0,0 +1,83 @@
'use strict';
const fs = require('fs');
const path = require('path');
const pify = require('pify');
const defaults = {
mode: 0o777 & (~process.umask()),
fs
};
// https://github.com/nodejs/node/issues/8987
// https://github.com/libuv/libuv/pull/1088
const checkPath = pth => {
if (process.platform === 'win32') {
const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''));
if (pathHasInvalidWinCharacters) {
const err = new Error(`Path contains invalid characters: ${pth}`);
err.code = 'EINVAL';
throw err;
}
}
};
module.exports = (input, opts) => Promise.resolve().then(() => {
checkPath(input);
opts = Object.assign({}, defaults, opts);
const fsP = pify(opts.fs);
const make = pth => {
return fsP.mkdir(pth, opts.mode)
.then(() => pth)
.catch(err => {
if (err.code === 'ENOENT') {
if (err.message.includes('null bytes') || path.dirname(pth) === pth) {
throw err;
}
return make(path.dirname(pth)).then(() => make(pth));
}
return fsP.stat(pth)
.then(stats => stats.isDirectory() ? pth : Promise.reject())
.catch(() => {
throw err;
});
});
};
return make(path.resolve(input));
});
module.exports.sync = (input, opts) => {
checkPath(input);
opts = Object.assign({}, defaults, opts);
const make = pth => {
try {
opts.fs.mkdirSync(pth, opts.mode);
} catch (err) {
if (err.code === 'ENOENT') {
if (err.message.includes('null bytes') || path.dirname(pth) === pth) {
throw err;
}
make(path.dirname(pth));
return make(pth);
}
try {
if (!opts.fs.statSync(pth).isDirectory()) {
throw new Error();
}
} catch (_) {
throw err;
}
}
return pth;
};
return make(path.resolve(input));
};

View File

@@ -0,0 +1,9 @@
MIT License
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,89 @@
{
"_args": [
[
"make-dir@1.1.0",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "make-dir@1.1.0",
"_id": "make-dir@1.1.0",
"_inBundle": false,
"_integrity": "sha512-0Pkui4wLJ7rxvmfUvs87skoEaxmu0hCUApF8nonzpl7q//FWp9zu8W61Scz4sd/kUiqDxvUhtoam2efDyiBzcA==",
"_location": "/babel-loader/make-dir",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "make-dir@1.1.0",
"name": "make-dir",
"escapedName": "make-dir",
"rawSpec": "1.1.0",
"saveSpec": null,
"fetchSpec": "1.1.0"
},
"_requiredBy": [
"/babel-loader/find-cache-dir"
],
"_resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.1.0.tgz",
"_spec": "1.1.0",
"_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/sindresorhus/make-dir/issues"
},
"dependencies": {
"pify": "^3.0.0"
},
"description": "Make a directory and its parents if needed - Think `mkdir -p`",
"devDependencies": {
"ava": "*",
"codecov": "^2.1.0",
"graceful-fs": "^4.1.11",
"nyc": "^10.2.0",
"path-type": "^3.0.0",
"tempy": "^0.2.1",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/make-dir#readme",
"keywords": [
"mkdir",
"mkdirp",
"make",
"directories",
"dir",
"dirs",
"folders",
"directory",
"folder",
"path",
"parent",
"parents",
"intermediate",
"recursively",
"recursive",
"create",
"fs",
"filesystem",
"file-system"
],
"license": "MIT",
"name": "make-dir",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/make-dir.git"
},
"scripts": {
"test": "xo && nyc ava"
},
"version": "1.1.0"
}

View File

@@ -0,0 +1,113 @@
# make-dir [![Build Status: macOS & Linux](https://travis-ci.org/sindresorhus/make-dir.svg?branch=master)](https://travis-ci.org/sindresorhus/make-dir) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/e0vtt8y600w91gcs/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/make-dir/branch/master) [![codecov](https://codecov.io/gh/sindresorhus/make-dir/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/make-dir)
> Make a directory and its parents if needed - Think `mkdir -p`
## Advantages over [`mkdirp`](https://github.com/substack/node-mkdirp)
- Promise API *(Async/await ready!)*
- Fixes many `mkdirp` issues: [#96](https://github.com/substack/node-mkdirp/pull/96) [#70](https://github.com/substack/node-mkdirp/issues/70) [#66](https://github.com/substack/node-mkdirp/issues/66)
- 100% test coverage
- CI-tested on macOS, Linux, and Windows
- Actively maintained
- Doesn't bundle a CLI
## Install
```
$ npm install make-dir
```
## Usage
```
$ pwd
/Users/sindresorhus/fun
$ tree
.
```
```js
const makeDir = require('make-dir');
makeDir('unicorn/rainbow/cake').then(path => {
console.log(path);
//=> '/Users/sindresorhus/fun/unicorn/rainbow/cake'
});
```
```
$ tree
.
└── unicorn
└── rainbow
└── cake
```
Multiple directories:
```js
const makeDir = require('make-dir');
Promise.all([
makeDir('unicorn/rainbow')
makeDir('foo/bar')
]).then(paths => {
console.log(paths);
/*
[
'/Users/sindresorhus/fun/unicorn/rainbow',
'/Users/sindresorhus/fun/foo/bar'
]
*/
});
```
## API
### makeDir(path, [options])
Returns a `Promise` for the path to the created directory.
### makeDir.sync(path, [options])
Returns the path to the created directory.
#### path
Type: `string`
Directory to create.
#### options
Type: `Object`
##### mode
Type: `integer`<br>
Default: `0o777 & (~process.umask())`
Directory [permissions](https://x-team.com/blog/file-system-permissions-umask-node-js/).
##### fs
Type: `Object`<br>
Default: `require('fs')`
Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs).
## Related
- [make-dir-cli](https://github.com/sindresorhus/make-dir-cli) - CLI for this module
- [del](https://github.com/sindresorhus/del) - Delete files and directories
- [globby](https://github.com/sindresorhus/globby) - User-friendly glob matching
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- "0.8"
- "0.10"

View File

@@ -0,0 +1,18 @@
This software is released under the MIT license:
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,2 @@
var argv = require('../')(process.argv.slice(2));
console.dir(argv);

View File

@@ -0,0 +1,187 @@
module.exports = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {} };
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
});
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function setArg (key, val) {
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
setArg(m[1], m[2]);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
setArg(key, next);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true');
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next)
continue;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2));
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
setArg(key, args[i+1]);
i++;
}
else if (args[i+1] && /true|false/.test(args[i+1])) {
setArg(key, args[i+1] === 'true');
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true);
}
}
}
else {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
notFlags.forEach(function(key) {
argv._.push(key);
});
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function setKey (obj, keys, value) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
if (o[key] === undefined) o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
function longest (xs) {
return Math.max.apply(null, xs.map(function (x) { return x.length }));
}

View File

@@ -0,0 +1,74 @@
{
"_args": [
[
"minimist@0.0.8",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "minimist@0.0.8",
"_id": "minimist@0.0.8",
"_inBundle": false,
"_integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=",
"_location": "/babel-loader/minimist",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "minimist@0.0.8",
"name": "minimist",
"escapedName": "minimist",
"rawSpec": "0.0.8",
"saveSpec": null,
"fetchSpec": "0.0.8"
},
"_requiredBy": [
"/babel-loader/mkdirp"
],
"_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"_spec": "0.0.8",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/minimist/issues"
},
"description": "parse argument options",
"devDependencies": {
"tap": "~0.4.0",
"tape": "~1.0.4"
},
"homepage": "https://github.com/substack/minimist",
"keywords": [
"argv",
"getopt",
"parser",
"optimist"
],
"license": "MIT",
"main": "index.js",
"name": "minimist",
"repository": {
"type": "git",
"url": "git://github.com/substack/minimist.git"
},
"scripts": {
"test": "tap test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/6..latest",
"ff/5",
"firefox/latest",
"chrome/10",
"chrome/latest",
"safari/5.1",
"safari/latest",
"opera/12"
]
},
"version": "0.0.8"
}

View File

@@ -0,0 +1,73 @@
# minimist
parse argument options
This module is the guts of optimist's argument parser without all the
fanciful decoration.
[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist)
[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist)
# example
``` js
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
```
```
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
```
```
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
```
# methods
``` js
var parseArgs = require('minimist')
```
## var argv = parseArgs(args, opts={})
Return an argument object `argv` populated with the array arguments from `args`.
`argv._` contains all the arguments that didn't have an option associated with
them.
Numeric-looking arguments will be returned as numbers unless `opts.string` or
`opts.boolean` is set for that argument name.
Any arguments after `'--'` will not be parsed and will end up in `argv._`.
options can be:
* `opts.string` - a string or array of strings argument names to always treat as
strings
* `opts.boolean` - a string or array of strings to always treat as booleans
* `opts.alias` - an object mapping string names to strings or arrays of string
argument names to use as aliases
* `opts.default` - an object mapping string argument names to default values
# install
With [npm](https://npmjs.org) do:
```
npm install minimist
```
# license
MIT

View File

@@ -0,0 +1,24 @@
var parse = require('../');
var test = require('tape');
test('-', function (t) {
t.plan(5);
t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] });
t.deepEqual(parse([ '-' ]), { _: [ '-' ] });
t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] });
t.deepEqual(
parse([ '-b', '-' ], { boolean: 'b' }),
{ b: true, _: [ '-' ] }
);
t.deepEqual(
parse([ '-s', '-' ], { string: 's' }),
{ s: '-', _: [] }
);
});
test('-a -- b', function (t) {
t.plan(3);
t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
});

View File

@@ -0,0 +1,20 @@
var test = require('tape');
var parse = require('../');
test('boolean default true', function (t) {
var argv = parse([], {
boolean: 'sometrue',
default: { sometrue: true }
});
t.equal(argv.sometrue, true);
t.end();
});
test('boolean default false', function (t) {
var argv = parse([], {
boolean: 'somefalse',
default: { somefalse: false }
});
t.equal(argv.somefalse, false);
t.end();
});

View File

@@ -0,0 +1,16 @@
var parse = require('../');
var test = require('tape');
test('dotted alias', function (t) {
var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 22);
t.equal(argv.aa.bb, 22);
t.end();
});
test('dotted default', function (t) {
var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 11);
t.equal(argv.aa.bb, 11);
t.end();
});

View File

@@ -0,0 +1,31 @@
var test = require('tape');
var parse = require('../');
test('long opts', function (t) {
t.deepEqual(
parse([ '--bool' ]),
{ bool : true, _ : [] },
'long boolean'
);
t.deepEqual(
parse([ '--pow', 'xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture sp'
);
t.deepEqual(
parse([ '--pow=xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture eq'
);
t.deepEqual(
parse([ '--host', 'localhost', '--port', '555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures sp'
);
t.deepEqual(
parse([ '--host=localhost', '--port=555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures eq'
);
t.end();
});

View File

@@ -0,0 +1,318 @@
var parse = require('../');
var test = require('tape');
test('parse args', function (t) {
t.deepEqual(
parse([ '--no-moo' ]),
{ moo : false, _ : [] },
'no'
);
t.deepEqual(
parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
{ v : ['a','b','c'], _ : [] },
'multi'
);
t.end();
});
test('comprehensive', function (t) {
t.deepEqual(
parse([
'--name=meowmers', 'bare', '-cats', 'woo',
'-h', 'awesome', '--multi=quux',
'--key', 'value',
'-b', '--bool', '--no-meep', '--multi=baz',
'--', '--not-a-flag', 'eek'
]),
{
c : true,
a : true,
t : true,
s : 'woo',
h : 'awesome',
b : true,
bool : true,
key : 'value',
multi : [ 'quux', 'baz' ],
meep : false,
name : 'meowmers',
_ : [ 'bare', '--not-a-flag', 'eek' ]
}
);
t.end();
});
test('nums', function (t) {
var argv = parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789'
]);
t.deepEqual(argv, {
x : 1234,
y : 5.67,
z : 1e7,
w : '10f',
hex : 0xdeadbeef,
_ : [ 789 ]
});
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv.y, 'number');
t.deepEqual(typeof argv.z, 'number');
t.deepEqual(typeof argv.w, 'string');
t.deepEqual(typeof argv.hex, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
test('flag boolean', function (t) {
var argv = parse([ '-t', 'moo' ], { boolean: 't' });
t.deepEqual(argv, { t : true, _ : [ 'moo' ] });
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('flag boolean value', function (t) {
var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], {
boolean: [ 't', 'verbose' ],
default: { verbose: true }
});
t.deepEqual(argv, {
verbose: false,
t: true,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('flag boolean default false', function (t) {
var argv = parse(['moo'], {
boolean: ['t', 'verbose'],
default: { verbose: false, t: false }
});
t.deepEqual(argv, {
verbose: false,
t: false,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('boolean groups', function (t) {
var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], {
boolean: ['x','y','z']
});
t.deepEqual(argv, {
x : true,
y : false,
z : true,
_ : [ 'one', 'two', 'three' ]
});
t.deepEqual(typeof argv.x, 'boolean');
t.deepEqual(typeof argv.y, 'boolean');
t.deepEqual(typeof argv.z, 'boolean');
t.end();
});
test('newlines in params' , function (t) {
var args = parse([ '-s', "X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
// reproduce in bash:
// VALUE="new
// line"
// node program.js --s="$VALUE"
args = parse([ "--s=X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
t.end();
});
test('strings' , function (t) {
var s = parse([ '-s', '0001234' ], { string: 's' }).s;
t.equal(s, '0001234');
t.equal(typeof s, 'string');
var x = parse([ '-x', '56' ], { string: 'x' }).x;
t.equal(x, '56');
t.equal(typeof x, 'string');
t.end();
});
test('stringArgs', function (t) {
var s = parse([ ' ', ' ' ], { string: '_' })._;
t.same(s.length, 2);
t.same(typeof s[0], 'string');
t.same(s[0], ' ');
t.same(typeof s[1], 'string');
t.same(s[1], ' ');
t.end();
});
test('empty strings', function(t) {
var s = parse([ '-s' ], { string: 's' }).s;
t.equal(s, '');
t.equal(typeof s, 'string');
var str = parse([ '--str' ], { string: 'str' }).str;
t.equal(str, '');
t.equal(typeof str, 'string');
var letters = parse([ '-art' ], {
string: [ 'a', 't' ]
});
t.equal(letters.a, '');
t.equal(letters.r, true);
t.equal(letters.t, '');
t.end();
});
test('slashBreak', function (t) {
t.same(
parse([ '-I/foo/bar/baz' ]),
{ I : '/foo/bar/baz', _ : [] }
);
t.same(
parse([ '-xyz/foo/bar/baz' ]),
{ x : true, y : true, z : '/foo/bar/baz', _ : [] }
);
t.end();
});
test('alias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: 'zoom' }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.f, 11);
t.end();
});
test('multiAlias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: [ 'zm', 'zoom' ] }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.z, argv.zm);
t.equal(argv.f, 11);
t.end();
});
test('nested dotted objects', function (t) {
var argv = parse([
'--foo.bar', '3', '--foo.baz', '4',
'--foo.quux.quibble', '5', '--foo.quux.o_O',
'--beep.boop'
]);
t.same(argv.foo, {
bar : 3,
baz : 4,
quux : {
quibble : 5,
o_O : true
}
});
t.same(argv.beep, { boop : true });
t.end();
});
test('boolean and alias with chainable api', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
herp: { alias: 'h', boolean: true }
};
var aliasedArgv = parse(aliased, {
boolean: 'herp',
alias: { h: 'herp' }
});
var propertyArgv = parse(regular, {
boolean: 'herp',
alias: { h: 'herp' }
});
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias with options hash', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
alias: { 'h': 'herp' },
boolean: 'herp'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias using explicit true', function (t) {
var aliased = [ '-h', 'true' ];
var regular = [ '--herp', 'true' ];
var opts = {
alias: { h: 'herp' },
boolean: 'h'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
// regression, see https://github.com/substack/node-optimist/issues/71
test('boolean and --x=true', function(t) {
var parsed = parse(['--boool', '--other=true'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'true');
parsed = parse(['--boool', '--other=false'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'false');
t.end();
});

View File

@@ -0,0 +1,9 @@
var parse = require('../');
var test = require('tape');
test('parse with modifier functions' , function (t) {
t.plan(1);
var argv = parse([ '-b', '123' ], { boolean: 'b' });
t.deepEqual(argv, { b: true, _: ['123'] });
});

View File

@@ -0,0 +1,67 @@
var parse = require('../');
var test = require('tape');
test('numeric short args', function (t) {
t.plan(2);
t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] });
t.deepEqual(
parse([ '-123', '456' ]),
{ 1: true, 2: true, 3: 456, _: [] }
);
});
test('short', function (t) {
t.deepEqual(
parse([ '-b' ]),
{ b : true, _ : [] },
'short boolean'
);
t.deepEqual(
parse([ 'foo', 'bar', 'baz' ]),
{ _ : [ 'foo', 'bar', 'baz' ] },
'bare'
);
t.deepEqual(
parse([ '-cats' ]),
{ c : true, a : true, t : true, s : true, _ : [] },
'group'
);
t.deepEqual(
parse([ '-cats', 'meow' ]),
{ c : true, a : true, t : true, s : 'meow', _ : [] },
'short group next'
);
t.deepEqual(
parse([ '-h', 'localhost' ]),
{ h : 'localhost', _ : [] },
'short capture'
);
t.deepEqual(
parse([ '-h', 'localhost', '-p', '555' ]),
{ h : 'localhost', p : 555, _ : [] },
'short captures'
);
t.end();
});
test('mixed short bool and capture', function (t) {
t.same(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});
test('short and long', function (t) {
t.deepEqual(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});

View File

@@ -0,0 +1,8 @@
var parse = require('../');
var test = require('tape');
test('whitespace should be whitespace' , function (t) {
t.plan(1);
var x = parse([ '-x', '\t' ]).x;
t.equal(x, '\t');
});

View File

@@ -0,0 +1,8 @@
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "iojs"
before_install:
- npm install -g npm@~1.4.6

View File

@@ -0,0 +1,21 @@
Copyright 2010 James Halliday (mail@substack.net)
This project is free software released under the MIT/X11 license:
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,33 @@
#!/usr/bin/env node
var mkdirp = require('../');
var minimist = require('minimist');
var fs = require('fs');
var argv = minimist(process.argv.slice(2), {
alias: { m: 'mode', h: 'help' },
string: [ 'mode' ]
});
if (argv.help) {
fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
return;
}
var paths = argv._.slice();
var mode = argv.mode ? parseInt(argv.mode, 8) : undefined;
(function next () {
if (paths.length === 0) return;
var p = paths.shift();
if (mode === undefined) mkdirp(p, cb)
else mkdirp(p, mode, cb)
function cb (err) {
if (err) {
console.error(err.message);
process.exit(1);
}
else next();
}
})();

View File

@@ -0,0 +1,12 @@
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories that
don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m, --mode If a directory needs to be created, set the mode as an octal
permission string.

View File

@@ -0,0 +1,6 @@
var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!')
});

View File

@@ -0,0 +1,98 @@
var path = require('path');
var fs = require('fs');
var _0777 = parseInt('0777', 8);
module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
function mkdirP (p, opts, f, made) {
if (typeof opts === 'function') {
f = opts;
opts = {};
}
else if (!opts || typeof opts !== 'object') {
opts = { mode: opts };
}
var mode = opts.mode;
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
}
if (!made) made = null;
var cb = f || function () {};
p = path.resolve(p);
xfs.mkdir(p, mode, function (er) {
if (!er) {
made = made || p;
return cb(null, made);
}
switch (er.code) {
case 'ENOENT':
mkdirP(path.dirname(p), opts, function (er, made) {
if (er) cb(er, made);
else mkdirP(p, opts, cb, made);
});
break;
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
xfs.stat(p, function (er2, stat) {
// if the stat fails, then that's super weird.
// let the original error be the failure reason.
if (er2 || !stat.isDirectory()) cb(er, made)
else cb(null, made);
});
break;
}
});
}
mkdirP.sync = function sync (p, opts, made) {
if (!opts || typeof opts !== 'object') {
opts = { mode: opts };
}
var mode = opts.mode;
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
}
if (!made) made = null;
p = path.resolve(p);
try {
xfs.mkdirSync(p, mode);
made = made || p;
}
catch (err0) {
switch (err0.code) {
case 'ENOENT' :
made = sync(path.dirname(p), opts, made);
sync(p, opts, made);
break;
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
var stat;
try {
stat = xfs.statSync(p);
}
catch (err1) {
throw err0;
}
if (!stat.isDirectory()) throw err0;
break;
}
}
return made;
};

View File

@@ -0,0 +1,65 @@
{
"_args": [
[
"mkdirp@0.5.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "mkdirp@0.5.1",
"_id": "mkdirp@0.5.1",
"_inBundle": false,
"_integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"_location": "/babel-loader/mkdirp",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "mkdirp@0.5.1",
"name": "mkdirp",
"escapedName": "mkdirp",
"rawSpec": "0.5.1",
"saveSpec": null,
"fetchSpec": "0.5.1"
},
"_requiredBy": [
"/babel-loader"
],
"_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"_spec": "0.5.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bin": {
"mkdirp": "bin/cmd.js"
},
"bugs": {
"url": "https://github.com/substack/node-mkdirp/issues"
},
"dependencies": {
"minimist": "0.0.8"
},
"description": "Recursively mkdir, like `mkdir -p`",
"devDependencies": {
"mock-fs": "2 >=2.7.0",
"tap": "1"
},
"homepage": "https://github.com/substack/node-mkdirp#readme",
"keywords": [
"mkdir",
"directory"
],
"license": "MIT",
"main": "index.js",
"name": "mkdirp",
"repository": {
"type": "git",
"url": "git+https://github.com/substack/node-mkdirp.git"
},
"scripts": {
"test": "tap test/*.js"
},
"version": "0.5.1"
}

View File

@@ -0,0 +1,100 @@
# mkdirp
Like `mkdir -p`, but in node.js!
[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)
# example
## pow.js
```js
var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!')
});
```
Output
```
pow!
```
And now /tmp/foo/bar/baz exists, huzzah!
# methods
```js
var mkdirp = require('mkdirp');
```
## mkdirp(dir, opts, cb)
Create a new directory and any necessary subdirectories at `dir` with octal
permission string `opts.mode`. If `opts` is a non-object, it will be treated as
the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.
`cb(err, made)` fires with the error or the first directory `made`
that had to be created, if any.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and
`opts.fs.stat(path, cb)`.
## mkdirp.sync(dir, opts)
Synchronously create a new directory and any necessary subdirectories at `dir`
with octal permission string `opts.mode`. If `opts` is a non-object, it will be
treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.
Returns the first directory that had to be created, if any.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and
`opts.fs.statSync(path)`.
# usage
This package also ships with a `mkdirp` command.
```
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories that
don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m, --mode If a directory needs to be created, set the mode as an octal
permission string.
```
# install
With [npm](http://npmjs.org) do:
```
npm install mkdirp
```
to get the library, or
```
npm install -g mkdirp
```
to get the command.
# license
MIT

View File

@@ -0,0 +1,41 @@
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
var _0744 = parseInt('0744', 8);
var ps = [ '', 'tmp' ];
for (var i = 0; i < 25; i++) {
var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
ps.push(dir);
}
var file = ps.join('/');
test('chmod-pre', function (t) {
var mode = _0744
mkdirp(file, mode, function (er) {
t.ifError(er, 'should not error');
fs.stat(file, function (er, stat) {
t.ifError(er, 'should exist');
t.ok(stat && stat.isDirectory(), 'should be directory');
t.equal(stat && stat.mode & _0777, mode, 'should be 0744');
t.end();
});
});
});
test('chmod', function (t) {
var mode = _0755
mkdirp(file, mode, function (er) {
t.ifError(er, 'should not error');
fs.stat(file, function (er, stat) {
t.ifError(er, 'should exist');
t.ok(stat && stat.isDirectory(), 'should be directory');
t.end();
});
});
});

View File

@@ -0,0 +1,38 @@
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
var _0755 = parseInt('0755', 8);
var ps = [ '', 'tmp' ];
for (var i = 0; i < 25; i++) {
var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
ps.push(dir);
}
var file = ps.join('/');
// a file in the way
var itw = ps.slice(0, 3).join('/');
test('clobber-pre', function (t) {
console.error("about to write to "+itw)
fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.');
fs.stat(itw, function (er, stat) {
t.ifError(er)
t.ok(stat && stat.isFile(), 'should be file')
t.end()
})
})
test('clobber', function (t) {
t.plan(2);
mkdirp(file, _0755, function (err) {
t.ok(err);
t.equal(err.code, 'ENOTDIR');
t.end();
});
});

View File

@@ -0,0 +1,28 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('woo', function (t) {
t.plan(5);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/tmp/' + [x,y,z].join('/');
mkdirp(file, _0755, function (err) {
t.ifError(err);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
})
})
});
});

View File

@@ -0,0 +1,29 @@
var mkdirp = require('../');
var path = require('path');
var test = require('tap').test;
var mockfs = require('mock-fs');
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('opts.fs', function (t) {
t.plan(5);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/beep/boop/' + [x,y,z].join('/');
var xfs = mockfs.fs();
mkdirp(file, { fs: xfs, mode: _0755 }, function (err) {
t.ifError(err);
xfs.exists(file, function (ex) {
t.ok(ex, 'created file');
xfs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
});
});
});
});

View File

@@ -0,0 +1,27 @@
var mkdirp = require('../');
var path = require('path');
var test = require('tap').test;
var mockfs = require('mock-fs');
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('opts.fs sync', function (t) {
t.plan(4);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/beep/boop/' + [x,y,z].join('/');
var xfs = mockfs.fs();
mkdirp.sync(file, { fs: xfs, mode: _0755 });
xfs.exists(file, function (ex) {
t.ok(ex, 'created file');
xfs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
});
});
});

View File

@@ -0,0 +1,32 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('async perm', function (t) {
t.plan(5);
var file = '/tmp/' + (Math.random() * (1<<30)).toString(16);
mkdirp(file, _0755, function (err) {
t.ifError(err);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
})
})
});
});
test('async root perm', function (t) {
mkdirp('/tmp', _0755, function (err) {
if (err) t.fail(err);
t.end();
});
t.end();
});

View File

@@ -0,0 +1,36 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('sync perm', function (t) {
t.plan(4);
var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json';
mkdirp.sync(file, _0755);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
});
});
});
test('sync root perm', function (t) {
t.plan(3);
var file = '/tmp';
mkdirp.sync(file, _0755);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.ok(stat.isDirectory(), 'target not a directory');
})
});
});

View File

@@ -0,0 +1,37 @@
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('race', function (t) {
t.plan(10);
var ps = [ '', 'tmp' ];
for (var i = 0; i < 25; i++) {
var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
ps.push(dir);
}
var file = ps.join('/');
var res = 2;
mk(file);
mk(file);
function mk (file, cb) {
mkdirp(file, _0755, function (err) {
t.ifError(err);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
});
})
});
}
});

View File

@@ -0,0 +1,32 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('rel', function (t) {
t.plan(5);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var cwd = process.cwd();
process.chdir('/tmp');
var file = [x,y,z].join('/');
mkdirp(file, _0755, function (err) {
t.ifError(err);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
process.chdir(cwd);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
})
})
});
});

View File

@@ -0,0 +1,25 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
test('return value', function (t) {
t.plan(4);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/tmp/' + [x,y,z].join('/');
// should return the first dir created.
// By this point, it would be profoundly surprising if /tmp didn't
// already exist, since every other test makes things in there.
mkdirp(file, function (err, made) {
t.ifError(err);
t.equal(made, '/tmp/' + x);
mkdirp(file, function (err, made) {
t.ifError(err);
t.equal(made, null);
});
});
});

View File

@@ -0,0 +1,24 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
test('return value', function (t) {
t.plan(2);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/tmp/' + [x,y,z].join('/');
// should return the first dir created.
// By this point, it would be profoundly surprising if /tmp didn't
// already exist, since every other test makes things in there.
// Note that this will throw on failure, which will fail the test.
var made = mkdirp.sync(file);
t.equal(made, '/tmp/' + x);
// making the same file again should have no effect.
made = mkdirp.sync(file);
t.equal(made, null);
});

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