progress on migrating to heex templates and font-icons

This commit is contained in:
Adam Piontek 2022-08-13 07:32:36 -04:00
parent d43daafdb7
commit 3eff955672
21793 changed files with 2161968 additions and 16895 deletions

88
assets_old/node_modules/svg-baker/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,88 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
<a name="1.7.0"></a>
# [1.7.0](https://github.com/JetBrains/svg-mixer/tree/v1/compare/svg-baker@1.4.0...svg-baker@1.7.0) (2020-04-08)
### Features
* add clipPath & mask to "move-from-symbol-to-root" transform defaults ([#61](https://github.com/JetBrains/svg-mixer/tree/v1/issues/61)) ([cbad9e8](https://github.com/JetBrains/svg-mixer/tree/v1/commit/cbad9e8))
<a name="1.6.0"></a>
# [1.6.0](https://github.com/JetBrains/svg-mixer/tree/v1/compare/svg-baker@1.4.0...svg-baker@1.6.0) (2020-04-01)
### Features
* add clipPath & mask to "move-from-symbol-to-root" transform defaults ([#61](https://github.com/JetBrains/svg-mixer/tree/v1/issues/61)) ([cbad9e8](https://github.com/JetBrains/svg-mixer/tree/v1/commit/cbad9e8))
<a name="1.5.0"></a>
# [1.5.0](https://github.com/JetBrains/svg-mixer/tree/v1/compare/svg-baker@1.4.0...svg-baker@1.5.0) (2020-01-24)
### Features
* add clipPath & mask to "move-from-symbol-to-root" transform defaults ([#61](https://github.com/JetBrains/svg-mixer/tree/v1/issues/61)) ([cbad9e8](https://github.com/JetBrains/svg-mixer/tree/v1/commit/cbad9e8))
<a name="1.4.1"></a>
## [1.4.1](https://github.com/JetBrains/svg-mixer/tree/v1/compare/svg-baker@1.4.0...svg-baker@1.4.1) (2019-04-27)
**Note:** Version bump only for package svg-baker
<a name="1.4.0"></a>
# [1.4.0](https://github.com/JetBrains/svg-mixer/tree/v1/compare/svg-baker@1.2.12...svg-baker@1.4.0) (2018-10-29)
### Bug Fixes
* **compiler:** move symbols sort from sprite-factory to compiler ([4690c75](https://github.com/JetBrains/svg-mixer/tree/v1/commit/4690c75))
* **sprite-factory:** sort symbols by id to get more determined sprite content ([9132e23](https://github.com/JetBrains/svg-mixer/tree/v1/commit/9132e23))
* make symbol.tree getter immutable ([343dc86](https://github.com/JetBrains/svg-mixer/tree/v1/commit/343dc86))
* preserve `fill` and `stroke` attrs when transform svg to symbol ([51cb3d5](https://github.com/JetBrains/svg-mixer/tree/v1/commit/51cb3d5))
* security vulnerability in merge-options dependency ([0482a12](https://github.com/JetBrains/svg-mixer/tree/v1/commit/0482a12))
* sprite move gradients outside symbol ([c6fcab4](https://github.com/JetBrains/svg-mixer/tree/v1/commit/c6fcab4))
* update package info ([7cc1b95](https://github.com/JetBrains/svg-mixer/tree/v1/commit/7cc1b95))
* upgrade merge-options due to severity vulnerabilities ([0538c60](https://github.com/JetBrains/svg-mixer/tree/v1/commit/0538c60))
### Features
* **sprite-factory:** allow to configure usages and styles rendering ([bc63366](https://github.com/JetBrains/svg-mixer/tree/v1/commit/bc63366))
* **svg-to-symbol-transformation:** preserve fill-* and stroke-* attributes ([edda97d](https://github.com/JetBrains/svg-mixer/tree/v1/commit/edda97d))
* add ARIA attrs to whitelist ([e6dd50d](https://github.com/JetBrains/svg-mixer/tree/v1/commit/e6dd50d))
<a name="1.2.8"></a>
## 1.2.8 (2017-06-15)
### Bug Fixes
* Remove DOCTYPE and xml declaration from source ([a380107](https://github.com/kisenka/svg-baker/commit/a380107))
<a name="1.2.7"></a>
## 1.2.7 (2017-05-13)
### Bug Fixes
* **sprite-factory:** dissapearing use tags when sprite is a part of page DOM ([a8c60ee](https://github.com/kisenka/svg-baker/commit/a8c60ee))

102
assets_old/node_modules/svg-baker/lib/compiler.js generated vendored Normal file
View file

@ -0,0 +1,102 @@
const Promise = require('bluebird');
const merge = require('merge-options');
const FileRequest = require('./request');
const RuleSet = require('./rules');
const Sprite = require('./sprite');
const SpriteSymbol = require('./symbol');
const symbolFactory = require('./symbol-factory');
const spriteFactory = require('./sprite-factory');
const defaultConfig = {
rules: [
{ test: /\.svg$/, value: 'sprite.svg' }
],
symbolFactory,
spriteFactory
};
class Compiler {
static sortSymbols(symbols) {
symbols.sort((leftSymbol, rightSymbol) => {
const leftId = leftSymbol.id;
const rightId = rightSymbol.id;
if (leftId === rightId) {
return 0;
}
return leftId < rightId ? -1 : 1;
});
return symbols;
}
constructor(cfg = {}) {
const config = this.config = merge(defaultConfig, cfg);
this.rules = new RuleSet(config.rules);
this.symbols = [];
}
/**
* @param {string} content
* @param {string} path
* @param {string} [id]
* @return {Promise<SpriteSymbol>}
*/
addSymbol({ path, content, id }) {
const symbols = this.symbols;
const factory = this.config.symbolFactory;
const request = new FileRequest(path);
const options = { id, request, content, factory };
return SpriteSymbol.create(options).then((newSymbol) => {
const existing = symbols.find(s => s.request.equals(request));
if (!existing) {
symbols.push(newSymbol);
Compiler.sortSymbols(symbols);
return newSymbol;
}
const existingIndex = existing ? symbols.indexOf(existing) : -1;
const allExceptCurrent = symbols
.filter(s => s.request.fileEquals(request) && !s.request.queryEquals(request))
.map(symbol => ({ symbol, index: symbols.indexOf(symbol) }));
symbols[existingIndex] = newSymbol;
Compiler.sortSymbols(symbols);
return Promise.map(allExceptCurrent, ({ symbol, index }) => {
const opts = { id: symbol.id, request: symbol.request, content, factory };
return SpriteSymbol.create(opts).then(created => symbols[index] = created);
}).then(() => newSymbol);
});
}
/**
* @return {Promise<Array<Sprite>>}
*/
compile() {
const symbols = this.symbols;
const rules = this.rules.rules;
const factory = this.config.spriteFactory;
return Promise.map(rules, (rule) => {
const spriteSymbols = [];
const filename = rule.uri;
symbols.forEach((symbol) => {
const isMatch = rule.match(symbol.request.file);
if (isMatch) {
spriteSymbols.push(symbol);
}
});
return spriteSymbols.length > 0 ?
Sprite.create({ symbols: spriteSymbols, filename, factory }) :
null;
}).filter(result => result !== null);
}
}
module.exports = Compiler;
module.exports.defaultConfig = defaultConfig;

92
assets_old/node_modules/svg-baker/lib/request.js generated vendored Normal file
View file

@ -0,0 +1,92 @@
const queryUtils = require('query-string');
class FileRequest {
/**
* @param {string} request
*/
constructor(request) {
const { file, query } = FileRequest.parse(request);
this.file = file;
this.query = query;
}
/**
* @param {string} request
* @return {{file: string, query: Object}}
*/
static parse(request) {
const parts = request.split('?');
const file = parts[0];
const query = parts[1] ? queryUtils.parse(parts[1]) : null;
return { file, query };
}
/**
* @return {string}
*/
toString() {
const { file, query } = this;
const queryEncoded = query ? `?${queryUtils.stringify(query)}` : '';
return `${file}${queryEncoded}`;
}
/**
* @return {string}
*/
stringify() {
return this.toString();
}
/**
* @return {string}
*/
stringifyQuery() {
return queryUtils.stringify(this.query);
}
/**
* @param {FileRequest} request
* @return {boolean}
*/
equals(request) {
if (!(request instanceof FileRequest)) {
throw TypeError('request should be instance of FileRequest');
}
return this.toString() === request.toString();
}
/**
* @param {FileRequest} request
* @return {boolean}
*/
fileEquals(request) {
return this.file === request.file;
}
/**
* @param {FileRequest} request
* @return {boolean}
*/
queryEquals(request) {
return this.stringifyQuery() === request.stringifyQuery();
}
/**
* @param {string} param
* @return {boolean}
*/
hasParam(param) {
return this.query && param in this.query;
}
/**
* @param {string} param
* @return {string|null}
*/
getParam(param) {
return this.hasParam(param) ? this.query[param] : null;
}
}
module.exports = FileRequest;

42
assets_old/node_modules/svg-baker/lib/rules.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
class Rule {
constructor({ test, value }) {
if (!(test instanceof RegExp)) {
throw new TypeError('`test` should be a regexp');
}
this.test = test;
this.value = value;
}
/**
* @param {string} value
* @return {boolean}
*/
match(value) {
return this.test.test(value);
}
}
class RuleSet {
/**
* @param {Array<{test: RegExp, uri: string}>} rules
*/
constructor(rules) {
if (!Array.isArray(rules)) {
throw new TypeError('`data` should be an array');
}
this.rules = rules.map(params => new Rule(params));
}
/**
* @param {string} value
* @return {Rule|null}
*/
getMatchedRule(value) {
return this.rules.find(rule => rule.match(value)) || null;
}
}
module.exports = RuleSet;
module.exports.Rule = Rule;

View file

@ -0,0 +1,84 @@
const merge = require('merge-options');
const processor = require('posthtml-svg-mode');
const extractNamespacesToRoot = require('./transformations/extract-namespaces-to-root');
const moveFromSymbolToRoot = require('./transformations/move-from-symbol-to-root');
const { svg, xlink } = require('../namespaces');
const defaultConfig = {
attrs: {
[svg.name]: svg.uri,
[xlink.name]: xlink.uri
},
styles: `
.sprite-symbol-usage {display: none;}
.sprite-symbol-usage:target {display: inline;}
`,
usages: true,
symbols: []
};
/**
* TODO simplify
* @param {Object} [config] {@see defaultConfig}
* @return {Function} PostHTML plugin
*/
function createSprite(config = {}) {
const cfg = merge(defaultConfig, config);
const symbols = cfg.symbols;
const trees = symbols.map(s => s.tree);
let usages = [];
if (cfg.usages) {
usages = symbols.map((symbol) => {
const { id, useId } = symbol;
return {
tag: 'use',
attrs: {
id: useId,
'xlink:href': `#${id}`,
class: 'sprite-symbol-usage'
}
};
});
}
let defsContent = [];
if (cfg.styles !== false) {
defsContent.push({
tag: 'style',
content: cfg.styles
});
}
defsContent = defsContent.concat(trees);
return (tree) => {
tree[0] = {
tag: 'svg',
attrs: cfg.attrs,
content: [{
tag: 'defs',
content: defsContent
}].concat(usages)
};
return tree;
};
}
/**
* @param {Object} options {@see defaultConfig}
* @return {Promise<PostHTMLProcessingResult>}
*/
function spriteFactory(options) {
const plugins = [
createSprite(options),
extractNamespacesToRoot(),
moveFromSymbolToRoot()
];
return processor(plugins).process('');
}
module.exports = spriteFactory;
module.exports.createSprite = createSprite;

30
assets_old/node_modules/svg-baker/lib/sprite.js generated vendored Normal file
View file

@ -0,0 +1,30 @@
const { renderer } = require('posthtml-svg-mode');
const defaultFactory = require('./sprite-factory');
class Sprite {
constructor({ tree, filename }) {
this.tree = tree;
this.filename = filename;
}
/**
* @param {Object} options
* @param {Array<SpriteSymbol>} options.symbols
* @param {string} options.filename Output sprite filename
* @param {Function<Promise<PostHTMLProcessingResult>>} [options.factory]
* @return {Promise<Sprite>}
*/
static create(options) {
const { symbols, filename, factory = defaultFactory } = options;
return factory({ symbols }).then(({ tree }) => new Sprite({ tree, filename }));
}
/**
* @return {string}
*/
render() {
return renderer(this.tree);
}
}
module.exports = Sprite;

View file

@ -0,0 +1,32 @@
const processor = require('posthtml-svg-mode');
const renameId = require('posthtml-rename-id');
const normalizeViewBox = require('./transformations/normalize-viewbox');
const rasterToSVG = require('./transformations/raster-to-svg');
const prefixStyleSelectors = require('./transformations/prefix-style-selectors');
const svgToSymbol = require('./transformations/svg-to-symbol');
/**
* @param {Object} options
* @param {string} [options.id]
* @param {string} options.content
* @param {FileRequest} options.request
* @return {Promise<PostHTMLProcessingResult>}
*/
function symbolFactory(options) {
const { id } = options;
const plugins = [];
// convert raster image to svg
const content = Buffer.isBuffer(options.content)
? rasterToSVG(options.content)
: options.content;
plugins.push(normalizeViewBox());
plugins.push(prefixStyleSelectors(`#${id}`));
plugins.push(renameId(`${id}_[id]`));
plugins.push(svgToSymbol({ id }));
return processor(plugins).process(content);
}
module.exports = symbolFactory;

58
assets_old/node_modules/svg-baker/lib/symbol.js generated vendored Normal file
View file

@ -0,0 +1,58 @@
const { renderer } = require('posthtml-svg-mode');
const { getRoot, getHash } = require('./utils');
const defaultFactory = require('./symbol-factory');
const FileRequest = require('./request');
const clone = require('clone');
class SpriteSymbol {
constructor({ id, tree, request }) {
this.id = id;
this._tree = tree;
this.request = request;
}
/**
* @param {Object} options
* @param {string} options.id
* @param {string} options.content
* @param {string|FileRequest} options.request
* @param {Function<Promise<PostHTMLProcessingResult>>} [options.factory]
* @return {Promise<SpriteSymbol>}
*/
static create(options) {
const { content, factory = defaultFactory } = options;
const request = typeof options.request === 'string' ? new FileRequest(options.request) : options.request;
const id = typeof options.id === 'undefined' ? getHash(`${request.toString()}_${content}`) : options.id;
return factory({ content, request, id })
.then(({ tree }) => new SpriteSymbol({ id, request, tree }));
}
/**
* @return {string}
*/
get viewBox() {
const root = getRoot(this.tree);
return root.attrs ? root.attrs.viewBox : null;
}
get tree() {
return clone(this._tree);
}
/**
* @return {string}
*/
get useId() {
return `${this.id}-usage`;
}
/**
* @return {string}
*/
render() {
return renderer(this.tree);
}
}
module.exports = SpriteSymbol;

View file

@ -0,0 +1,35 @@
const { getRoot } = require('../utils');
/**
* @return {Function} PostHTML plugin
*/
function extractNamespacesToRoot() {
return (tree) => {
const namespaces = {};
tree.match({ tag: /.*/ }, (node) => {
const attrs = node.attrs || {};
Object.keys(attrs).forEach((attr) => {
if (attr.startsWith('xmlns')) {
if (attr in namespaces === false) {
namespaces[attr] = attrs[attr];
}
delete node.attrs[attr];
}
});
return node;
});
const root = getRoot(tree);
root.attrs = root.attrs || {};
Object.keys(namespaces).forEach(name => root.attrs[name] = namespaces[name]);
return tree;
};
}
module.exports = extractNamespacesToRoot;

View file

@ -0,0 +1,38 @@
const traverse = require('traverse');
const clone = require('clone');
// Fixes Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=353575
const defaultConfig = {
tags: ['linearGradient', 'radialGradient', 'pattern', 'clipPath', 'mask']
};
function moveFromSymbolToRoot(config = null) {
const cfg = Object.assign({}, defaultConfig, config);
return (tree) => {
traverse(tree).forEach(function (node) {
if (!this.isLeaf && node.tag && node.tag === 'symbol') {
const symbol = this.parent.node;
const nodesToRemove = [];
traverse(node.content).forEach(function (n) {
if (!this.isLeaf && n.tag && cfg.tags.indexOf(n.tag) !== -1) {
const parent = this.parent.node;
const cloned = clone(this.node);
symbol.push(cloned);
nodesToRemove.push({ parent, node: n });
}
});
nodesToRemove.forEach((item) => {
const nodeIndex = item.parent.indexOf(item.node);
item.parent.splice(nodeIndex, 1);
});
}
});
return tree;
};
}
module.exports = moveFromSymbolToRoot;

View file

@ -0,0 +1,34 @@
const merge = require('merge-options');
const { getRoot } = require('../utils');
const defaultConfig = {
removeDimensions: false
};
/**
* @param {Object} [config] {@see defaultConfig}
* @return {Function} PostHTML plugin
*/
function normalizeViewBox(config = {}) {
const cfg = merge(defaultConfig, config);
return (tree) => {
const root = getRoot(tree);
root.attrs = root.attrs || {};
const attrs = root.attrs;
const { width, height, viewBox } = attrs;
if (!viewBox && width && height) {
attrs.viewBox = `0 0 ${parseFloat(width).toString()} ${parseFloat(height).toString()}`;
if (cfg.removeDimensions) {
delete attrs.width;
delete attrs.height;
}
}
return tree;
};
}
module.exports = normalizeViewBox;

View file

@ -0,0 +1,30 @@
const Promise = require('bluebird');
const decodeEntities = require('he').decode;
const postcss = require('postcss');
const prefixSelectors = require('postcss-prefix-selector');
/**
* @return {Function} PostHTML plugin
*/
function prefixStyleSelectors(prefix) {
return (tree) => {
const styleNodes = [];
tree.match({ tag: 'style' }, (node) => {
styleNodes.push(node);
return node;
});
return Promise.map(styleNodes, (node) => {
const content = node.content ? decodeEntities(node.content.join('')) : '';
return postcss()
.use(prefixSelectors({ prefix }))
.process(content)
.then(prefixedStyles => node.content = prefixedStyles.css);
}).then(() => tree);
};
}
module.exports = prefixStyleSelectors;

View file

@ -0,0 +1,23 @@
const getImageSize = require('image-size');
const { svg, xlink } = require('../../namespaces');
/**
* TODO rasterToSVG#getPixelRatioFromFilename
* @param {Buffer} buffer
* @return {string}
*/
function rasterToSVG(buffer) {
const info = getImageSize(buffer);
const { width, height, type } = info;
const defaultNS = `${svg.name}="${svg.uri}"`;
const xlinkNS = `${xlink.name}="${xlink.uri}"`;
const data = `data:image/${type};base64,${buffer.toString('base64')}`;
return [
`<svg ${defaultNS} ${xlinkNS} width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`,
`<image xlink:href="${data}" width="${width}" height="${height}" />`,
'</svg>'
].join('');
}
module.exports = rasterToSVG;

View file

@ -0,0 +1,52 @@
const micromatch = require('micromatch');
const { getRoot } = require('../utils');
const defaultConfig = {
id: undefined,
preserve: [
'viewBox',
'preserveAspectRatio',
'class',
'overflow',
'stroke?(-*)',
'fill?(-*)',
'xmlns?(:*)',
'role',
'aria-*'
]
};
/**
* @param {Object} [config] {@see defaultConfig}
* @return {Function} PostHTML plugin
*/
function svgToSymbol(config = null) {
const cfg = Object.assign({}, defaultConfig, config);
return (tree) => {
const root = getRoot(tree);
root.tag = 'symbol';
root.attrs = root.attrs || {};
const attrNames = Object.keys(root.attrs);
const attrNamesToPreserve = micromatch(attrNames, cfg.preserve);
attrNames.forEach((name) => {
if (!attrNamesToPreserve.includes(name)) {
delete root.attrs[name];
}
});
if (cfg.id) {
root.attrs.id = cfg.id;
}
// Remove all elements and add symbol node
tree.splice(0, tree.length, root);
return tree;
};
}
module.exports = svgToSymbol;

27
assets_old/node_modules/svg-baker/lib/utils.js generated vendored Normal file
View file

@ -0,0 +1,27 @@
const { interpolateName, getHashDigest } = require('loader-utils');
/**
* @param {PostHTMLTree} tree
* @return {Object} Node
*/
exports.getRoot = function getRoot(tree) {
return tree.find(node => typeof node === 'object' && 'tag' in node);
};
/**
* @param {string|Function} pattern
* @param {string} resourcePath
* @param {Object} [options]
* @param {string} options.context
* @param {string} options.content
* @param {string} options.regExp
*/
exports.interpolate = function interpolate(pattern, resourcePath, options = null) {
const opts = Object.assign({ context: process.cwd() }, options);
return interpolateName({ resourcePath }, pattern, opts);
};
exports.getHash = function getHash(content) {
return getHashDigest(content, 'md5', 'hex', 6);
};

13
assets_old/node_modules/svg-baker/namespaces.js generated vendored Normal file
View file

@ -0,0 +1,13 @@
const namespaces = {
svg: {
name: 'xmlns',
uri: 'http://www.w3.org/2000/svg'
},
xlink: {
name: 'xmlns:xlink',
uri: 'http://www.w3.org/1999/xlink'
}
};
exports.default = namespaces;
module.exports = exports.default;

View file

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

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,64 @@
{
"name": "ansi-regex",
"version": "2.1.1",
"description": "Regular expression for matching ANSI escape codes",
"license": "MIT",
"repository": "chalk/ansi-regex",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
"JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && ava --verbose",
"view-supported": "node fixtures/view-codes.js"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"devDependencies": {
"ava": "0.17.0",
"xo": "0.16.0"
},
"xo": {
"rules": {
"guard-for-in": 0,
"no-loop-func": 0
}
}
}

View file

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

View file

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

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,50 @@
{
"name": "ansi-styles",
"version": "2.2.1",
"description": "ANSI escape codes for styling strings in the terminal",
"license": "MIT",
"repository": "chalk/ansi-styles",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"devDependencies": {
"mocha": "*"
}
}

View file

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

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2018, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,640 @@
# braces [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/braces.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/braces)
> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save braces
```
## Why use braces?
Brace patterns are great for matching ranges. Users (and implementors) shouldn't have to think about whether or not they will break their application (or yours) from accidentally defining an aggressive brace pattern. _Braces is the only library that offers a [solution to this problem](#performance)_.
* **Safe(r)**: Braces isn't vulnerable to DoS attacks like [brace-expansion](https://github.com/juliangruber/brace-expansion), [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) (a different bug than the [other regex DoS bug](https://medium.com/node-security/minimatch-redos-vulnerability-590da24e6d3c#.jew0b6mpc)).
* **Accurate**: complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests)
* **[fast and performant](#benchmarks)**: Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity.
* **Organized code base**: with parser and compiler that are eas(y|ier) to maintain and update when edge cases crop up.
* **Well-tested**: thousands of test assertions. Passes 100% of the [minimatch](https://github.com/isaacs/minimatch) and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests as well (as of the writing of this).
## Usage
The main export is a function that takes one or more brace `patterns` and `options`.
```js
var braces = require('braces');
braces(pattern[, options]);
```
By default, braces returns an optimized regex-source string. To get an array of brace patterns, use `brace.expand()`.
The following section explains the difference in more detail. _(If you're curious about "why" braces does this by default, see [brace matching pitfalls](#brace-matching-pitfalls)_.
### Optimized vs. expanded braces
**Optimized**
By default, patterns are optimized for regex and matching:
```js
console.log(braces('a/{x,y,z}/b'));
//=> ['a/(x|y|z)/b']
```
**Expanded**
To expand patterns the same way as Bash or [minimatch](https://github.com/isaacs/minimatch), use the [.expand](#expand) method:
```js
console.log(braces.expand('a/{x,y,z}/b'));
//=> ['a/x/b', 'a/y/b', 'a/z/b']
```
Or use [options.expand](#optionsexpand):
```js
console.log(braces('a/{x,y,z}/b', {expand: true}));
//=> ['a/x/b', 'a/y/b', 'a/z/b']
```
## Features
* [lists](#lists): Supports "lists": `a/{b,c}/d` => `['a/b/d', 'a/c/d']`
* [sequences](#sequences): Supports alphabetical or numerical "sequences" (ranges): `{1..3}` => `['1', '2', '3']`
* [steps](#steps): Supports "steps" or increments: `{2..10..2}` => `['2', '4', '6', '8', '10']`
* [escaping](#escaping)
* [options](#options)
### Lists
Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric lists:
```js
console.log(braces('a/{foo,bar,baz}/*.js'));
//=> ['a/(foo|bar|baz)/*.js']
console.log(braces.expand('a/{foo,bar,baz}/*.js'));
//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js']
```
### Sequences
Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric ranges (bash "sequences"):
```js
console.log(braces.expand('{1..3}')); // ['1', '2', '3']
console.log(braces.expand('a{01..03}b')); // ['a01b', 'a02b', 'a03b']
console.log(braces.expand('a{1..3}b')); // ['a1b', 'a2b', 'a3b']
console.log(braces.expand('{a..c}')); // ['a', 'b', 'c']
console.log(braces.expand('foo/{a..c}')); // ['foo/a', 'foo/b', 'foo/c']
// supports padded ranges
console.log(braces('a{01..03}b')); //=> [ 'a(0[1-3])b' ]
console.log(braces('a{001..300}b')); //=> [ 'a(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)b' ]
```
### Steps
Steps, or increments, may be used with ranges:
```js
console.log(braces.expand('{2..10..2}'));
//=> ['2', '4', '6', '8', '10']
console.log(braces('{2..10..2}'));
//=> ['(2|4|6|8|10)']
```
When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion.
### Nesting
Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved.
**"Expanded" braces**
```js
console.log(braces.expand('a{b,c,/{x,y}}/e'));
//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e']
console.log(braces.expand('a/{x,{1..5},y}/c'));
//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c']
```
**"Optimized" braces**
```js
console.log(braces('a{b,c,/{x,y}}/e'));
//=> ['a(b|c|/(x|y))/e']
console.log(braces('a/{x,{1..5},y}/c'));
//=> ['a/(x|([1-5])|y)/c']
```
### Escaping
**Escaping braces**
A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_:
```js
console.log(braces.expand('a\\{d,c,b}e'));
//=> ['a{d,c,b}e']
console.log(braces.expand('a{d,c,b\\}e'));
//=> ['a{d,c,b}e']
```
**Escaping commas**
Commas inside braces may also be escaped:
```js
console.log(braces.expand('a{b\\,c}d'));
//=> ['a{b,c}d']
console.log(braces.expand('a{d\\,c,b}e'));
//=> ['ad,ce', 'abe']
```
**Single items**
Following bash conventions, a brace pattern is also not expanded when it contains a single character:
```js
console.log(braces.expand('a{b}c'));
//=> ['a{b}c']
```
## Options
### options.maxLength
**Type**: `Number`
**Default**: `65,536`
**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera.
```js
console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error
```
### options.expand
**Type**: `Boolean`
**Default**: `undefined`
**Description**: Generate an "expanded" brace pattern (this option is unncessary with the `.expand` method, which does the same thing).
```js
console.log(braces('a/{b,c}/d', {expand: true}));
//=> [ 'a/b/d', 'a/c/d' ]
```
### options.optimize
**Type**: `Boolean`
**Default**: `true`
**Description**: Enabled by default.
```js
console.log(braces('a/{b,c}/d'));
//=> [ 'a/(b|c)/d' ]
```
### options.nodupes
**Type**: `Boolean`
**Default**: `true`
**Description**: Duplicates are removed by default. To keep duplicates, pass `{nodupes: false}` on the options
### options.rangeLimit
**Type**: `Number`
**Default**: `250`
**Description**: When `braces.expand()` is used, or `options.expand` is true, brace patterns will automatically be [optimized](#optionsoptimize) when the difference between the range minimum and range maximum exceeds the `rangeLimit`. This is to prevent huge ranges from freezing your application.
You can set this to any number, or change `options.rangeLimit` to `Inifinity` to disable this altogether.
**Examples**
```js
// pattern exceeds the "rangeLimit", so it's optimized automatically
console.log(braces.expand('{1..1000}'));
//=> ['([1-9]|[1-9][0-9]{1,2}|1000)']
// pattern does not exceed "rangeLimit", so it's NOT optimized
console.log(braces.expand('{1..100}'));
//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']
```
### options.transform
**Type**: `Function`
**Default**: `undefined`
**Description**: Customize range expansion.
```js
var range = braces.expand('x{a..e}y', {
transform: function(str) {
return 'foo' + str;
}
});
console.log(range);
//=> [ 'xfooay', 'xfooby', 'xfoocy', 'xfoody', 'xfooey' ]
```
### options.quantifiers
**Type**: `Boolean`
**Default**: `undefined`
**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times.
Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists)
The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists.
**Examples**
```js
var braces = require('braces');
console.log(braces('a/b{1,3}/{x,y,z}'));
//=> [ 'a/b(1|3)/(x|y|z)' ]
console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true}));
//=> [ 'a/b{1,3}/(x|y|z)' ]
console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true}));
//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ]
```
### options.unescape
**Type**: `Boolean`
**Default**: `undefined`
**Description**: Strip backslashes that were used for escaping from the result.
## What is "brace expansion"?
Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs).
In addition to "expansion", braces are also used for matching. In other words:
* [brace expansion](#brace-expansion) is for generating new lists
* [brace matching](#brace-matching) is for filtering existing lists
<details>
<summary><strong>More about brace expansion</strong> (click to expand)</summary>
There are two main types of brace expansion:
1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}`
2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges".
Here are some example brace patterns to illustrate how they work:
**Sets**
```
{a,b,c} => a b c
{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2
```
**Sequences**
```
{1..9} => 1 2 3 4 5 6 7 8 9
{4..-4} => 4 3 2 1 0 -1 -2 -3 -4
{1..20..3} => 1 4 7 10 13 16 19
{a..j} => a b c d e f g h i j
{j..a} => j i h g f e d c b a
{a..z..3} => a d g j m p s v y
```
**Combination**
Sets and sequences can be mixed together or used along with any other strings.
```
{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3
foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar
```
The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases.
## Brace matching
In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching.
For example, the pattern `foo/{1..3}/bar` would match any of following strings:
```
foo/1/bar
foo/2/bar
foo/3/bar
```
But not:
```
baz/1/qux
baz/2/qux
baz/3/qux
```
Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings:
```
foo/1/bar
foo/2/bar
foo/3/bar
baz/1/qux
baz/2/qux
baz/3/qux
```
## Brace matching pitfalls
Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of.
### tldr
**"brace bombs"**
* brace expansion can eat up a huge amount of processing resources
* as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially
* users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!)
For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section.
### The solution
Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries.
### Geometric complexity
At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`.
For example, the following sets demonstrate quadratic (`O(n^2)`) complexity:
```
{1,2}{3,4} => (2X2) => 13 14 23 24
{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246
```
But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity:
```
{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248
249 257 258 259 267 268 269 347 348 349 357
358 359 367 368 369
```
Now, imagine how this complexity grows given that each element is a n-tuple:
```
{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB)
{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB)
```
Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control.
**More information**
Interested in learning more about brace expansion?
* [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion)
* [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion)
* [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)
</details>
## Performance
Braces is not only screaming fast, it's also more accurate the other brace expansion libraries.
### Better algorithms
Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_.
Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently.
**The proof is in the numbers**
Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively.
| **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** |
| --- | --- | --- |
| `{1..9007199254740991}`<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> | `298 B` (5ms 459μs) | N/A (freezes) |
| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) |
| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) |
| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) |
| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) |
| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) |
| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) |
| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) |
| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) |
| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) |
| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) |
| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) |
| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) |
| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) |
| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) |
| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) |
| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) |
### Faster algorithms
When you need expansion, braces is still much faster.
_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_
| **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** |
| --- | --- | --- |
| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) |
| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) |
| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) |
| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) |
| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) |
| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) |
| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) |
| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) |
If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js).
## Benchmarks
### Running benchmarks
Install dev dependencies:
```bash
npm i -d && npm benchmark
```
### Latest results
```bash
Benchmarking: (8 of 8)
· combination-nested
· combination
· escaped
· list-basic
· list-multiple
· no-braces
· sequence-basic
· sequence-multiple
# benchmark/fixtures/combination-nested.js (52 bytes)
brace-expansion x 4,756 ops/sec ±1.09% (86 runs sampled)
braces x 11,202,303 ops/sec ±1.06% (88 runs sampled)
minimatch x 4,816 ops/sec ±0.99% (87 runs sampled)
fastest is braces
# benchmark/fixtures/combination.js (51 bytes)
brace-expansion x 625 ops/sec ±0.87% (87 runs sampled)
braces x 11,031,884 ops/sec ±0.72% (90 runs sampled)
minimatch x 637 ops/sec ±0.84% (88 runs sampled)
fastest is braces
# benchmark/fixtures/escaped.js (44 bytes)
brace-expansion x 163,325 ops/sec ±1.05% (87 runs sampled)
braces x 10,655,071 ops/sec ±1.22% (88 runs sampled)
minimatch x 147,495 ops/sec ±0.96% (88 runs sampled)
fastest is braces
# benchmark/fixtures/list-basic.js (40 bytes)
brace-expansion x 99,726 ops/sec ±1.07% (83 runs sampled)
braces x 10,596,584 ops/sec ±0.98% (88 runs sampled)
minimatch x 100,069 ops/sec ±1.17% (86 runs sampled)
fastest is braces
# benchmark/fixtures/list-multiple.js (52 bytes)
brace-expansion x 34,348 ops/sec ±1.08% (88 runs sampled)
braces x 9,264,131 ops/sec ±1.12% (88 runs sampled)
minimatch x 34,893 ops/sec ±0.87% (87 runs sampled)
fastest is braces
# benchmark/fixtures/no-braces.js (48 bytes)
brace-expansion x 275,368 ops/sec ±1.18% (89 runs sampled)
braces x 9,134,677 ops/sec ±0.95% (88 runs sampled)
minimatch x 3,755,954 ops/sec ±1.13% (89 runs sampled)
fastest is braces
# benchmark/fixtures/sequence-basic.js (41 bytes)
brace-expansion x 5,492 ops/sec ±1.35% (87 runs sampled)
braces x 8,485,034 ops/sec ±1.28% (89 runs sampled)
minimatch x 5,341 ops/sec ±1.17% (87 runs sampled)
fastest is braces
# benchmark/fixtures/sequence-multiple.js (51 bytes)
brace-expansion x 116 ops/sec ±0.77% (77 runs sampled)
braces x 9,445,118 ops/sec ±1.32% (84 runs sampled)
minimatch x 109 ops/sec ±1.16% (76 runs sampled)
fastest is braces
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.")
* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.")
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 188 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) |
| 1 | [es128](https://github.com/es128) |
| 1 | [eush77](https://github.com/eush77) |
| 1 | [hemanth](https://github.com/hemanth) |
### Author
**Jon Schlinkert**
* [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert)
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 17, 2018._
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item">this is the largest safe integer allowed in JavaScript. <a href="#fnref1" class="footnote-backref"></a>
</li>
</ol>
</section>

View file

@ -0,0 +1,318 @@
'use strict';
/**
* Module dependencies
*/
var toRegex = require('to-regex');
var unique = require('array-unique');
var extend = require('extend-shallow');
/**
* Local dependencies
*/
var compilers = require('./lib/compilers');
var parsers = require('./lib/parsers');
var Braces = require('./lib/braces');
var utils = require('./lib/utils');
var MAX_LENGTH = 1024 * 64;
var cache = {};
/**
* Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)).
*
* ```js
* var braces = require('braces');
* console.log(braces('{a,b,c}'));
* //=> ['(a|b|c)']
*
* console.log(braces('{a,b,c}', {expand: true}));
* //=> ['a', 'b', 'c']
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {String}
* @api public
*/
function braces(pattern, options) {
var key = utils.createKey(String(pattern), options);
var arr = [];
var disabled = options && options.cache === false;
if (!disabled && cache.hasOwnProperty(key)) {
return cache[key];
}
if (Array.isArray(pattern)) {
for (var i = 0; i < pattern.length; i++) {
arr.push.apply(arr, braces.create(pattern[i], options));
}
} else {
arr = braces.create(pattern, options);
}
if (options && options.nodupes === true) {
arr = unique(arr);
}
if (!disabled) {
cache[key] = arr;
}
return arr;
}
/**
* Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead.
*
* ```js
* var braces = require('braces');
* console.log(braces.expand('a/{b,c}/d'));
* //=> ['a/b/d', 'a/c/d'];
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.expand = function(pattern, options) {
return braces.create(pattern, extend({}, options, {expand: true}));
};
/**
* Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
*
* ```js
* var braces = require('braces');
* console.log(braces.expand('a/{b,c}/d'));
* //=> ['a/(b|c)/d']
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.optimize = function(pattern, options) {
return braces.create(pattern, options);
};
/**
* Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function.
*
* ```js
* var braces = require('braces');
* console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
* //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.create = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
var maxLength = (options && options.maxLength) || MAX_LENGTH;
if (pattern.length >= maxLength) {
throw new Error('expected pattern to be less than ' + maxLength + ' characters');
}
function create() {
if (pattern === '' || pattern.length < 3) {
return [pattern];
}
if (utils.isEmptySets(pattern)) {
return [];
}
if (utils.isQuotedString(pattern)) {
return [pattern.slice(1, -1)];
}
var proto = new Braces(options);
var result = !options || options.expand !== true
? proto.optimize(pattern, options)
: proto.expand(pattern, options);
// get the generated pattern(s)
var arr = result.output;
// filter out empty strings if specified
if (options && options.noempty === true) {
arr = arr.filter(Boolean);
}
// filter out duplicates if specified
if (options && options.nodupes === true) {
arr = unique(arr);
}
Object.defineProperty(arr, 'result', {
enumerable: false,
value: result
});
return arr;
}
return memoize('create', pattern, options, create);
};
/**
* Create a regular expression from the given string `pattern`.
*
* ```js
* var braces = require('braces');
*
* console.log(braces.makeRe('id-{200..300}'));
* //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
* ```
* @param {String} `pattern` The pattern to convert to regex.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
braces.makeRe = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
var maxLength = (options && options.maxLength) || MAX_LENGTH;
if (pattern.length >= maxLength) {
throw new Error('expected pattern to be less than ' + maxLength + ' characters');
}
function makeRe() {
var arr = braces(pattern, options);
var opts = extend({strictErrors: false}, options);
return toRegex(arr, opts);
}
return memoize('makeRe', pattern, options, makeRe);
};
/**
* Parse the given `str` with the given `options`.
*
* ```js
* var braces = require('braces');
* var ast = braces.parse('a/{b,c}/d');
* console.log(ast);
* // { type: 'root',
* // errors: [],
* // input: 'a/{b,c}/d',
* // nodes:
* // [ { type: 'bos', val: '' },
* // { type: 'text', val: 'a/' },
* // { type: 'brace',
* // nodes:
* // [ { type: 'brace.open', val: '{' },
* // { type: 'text', val: 'b,c' },
* // { type: 'brace.close', val: '}' } ] },
* // { type: 'text', val: '/d' },
* // { type: 'eos', val: '' } ] }
* ```
* @param {String} `pattern` Brace pattern to parse
* @param {Object} `options`
* @return {Object} Returns an AST
* @api public
*/
braces.parse = function(pattern, options) {
var proto = new Braces(options);
return proto.parse(pattern, options);
};
/**
* Compile the given `ast` or string with the given `options`.
*
* ```js
* var braces = require('braces');
* var ast = braces.parse('a/{b,c}/d');
* console.log(braces.compile(ast));
* // { options: { source: 'string' },
* // state: {},
* // compilers:
* // { eos: [Function],
* // noop: [Function],
* // bos: [Function],
* // brace: [Function],
* // 'brace.open': [Function],
* // text: [Function],
* // 'brace.close': [Function] },
* // output: [ 'a/(b|c)/d' ],
* // ast:
* // { ... },
* // parsingErrors: [] }
* ```
* @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
* @param {Object} `options`
* @return {Object} Returns an object that has an `output` property with the compiled string.
* @api public
*/
braces.compile = function(ast, options) {
var proto = new Braces(options);
return proto.compile(ast, options);
};
/**
* Clear the regex cache.
*
* ```js
* braces.clearCache();
* ```
* @api public
*/
braces.clearCache = function() {
cache = braces.cache = {};
};
/**
* Memoize a generated regex or function. A unique key is generated
* from the method name, pattern, and user-defined options. Set
* options.memoize to false to disable.
*/
function memoize(type, pattern, options, fn) {
var key = utils.createKey(type + ':' + pattern, options);
var disabled = options && options.cache === false;
if (disabled) {
braces.clearCache();
return fn(pattern, options);
}
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var res = fn(pattern, options);
cache[key] = res;
return res;
}
/**
* Expose `Braces` constructor and methods
* @type {Function}
*/
braces.Braces = Braces;
braces.compilers = compilers;
braces.parsers = parsers;
braces.cache = cache;
/**
* Expose `braces`
* @type {Function}
*/
module.exports = braces;

View file

@ -0,0 +1,104 @@
'use strict';
var extend = require('extend-shallow');
var Snapdragon = require('snapdragon');
var compilers = require('./compilers');
var parsers = require('./parsers');
var utils = require('./utils');
/**
* Customize Snapdragon parser and renderer
*/
function Braces(options) {
this.options = extend({}, options);
}
/**
* Initialize braces
*/
Braces.prototype.init = function(options) {
if (this.isInitialized) return;
this.isInitialized = true;
var opts = utils.createOptions({}, this.options, options);
this.snapdragon = this.options.snapdragon || new Snapdragon(opts);
this.compiler = this.snapdragon.compiler;
this.parser = this.snapdragon.parser;
compilers(this.snapdragon, opts);
parsers(this.snapdragon, opts);
/**
* Call Snapdragon `.parse` method. When AST is returned, we check to
* see if any unclosed braces are left on the stack and, if so, we iterate
* over the stack and correct the AST so that compilers are called in the correct
* order and unbalance braces are properly escaped.
*/
utils.define(this.snapdragon, 'parse', function(pattern, options) {
var parsed = Snapdragon.prototype.parse.apply(this, arguments);
this.parser.ast.input = pattern;
var stack = this.parser.stack;
while (stack.length) {
addParent({type: 'brace.close', val: ''}, stack.pop());
}
function addParent(node, parent) {
utils.define(node, 'parent', parent);
parent.nodes.push(node);
}
// add non-enumerable parser reference
utils.define(parsed, 'parser', this.parser);
return parsed;
});
};
/**
* Decorate `.parse` method
*/
Braces.prototype.parse = function(ast, options) {
if (ast && typeof ast === 'object' && ast.nodes) return ast;
this.init(options);
return this.snapdragon.parse(ast, options);
};
/**
* Decorate `.compile` method
*/
Braces.prototype.compile = function(ast, options) {
if (typeof ast === 'string') {
ast = this.parse(ast, options);
} else {
this.init(options);
}
return this.snapdragon.compile(ast, options);
};
/**
* Expand
*/
Braces.prototype.expand = function(pattern) {
var ast = this.parse(pattern, {expand: true});
return this.compile(ast, {expand: true});
};
/**
* Optimize
*/
Braces.prototype.optimize = function(pattern) {
var ast = this.parse(pattern, {optimize: true});
return this.compile(ast, {optimize: true});
};
/**
* Expose `Braces`
*/
module.exports = Braces;

View file

@ -0,0 +1,282 @@
'use strict';
var utils = require('./utils');
module.exports = function(braces, options) {
braces.compiler
/**
* bos
*/
.set('bos', function() {
if (this.output) return;
this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];
this.ast.count = 1;
})
/**
* Square brackets
*/
.set('bracket', function(node) {
var close = node.close;
var open = !node.escaped ? '[' : '\\[';
var negated = node.negated;
var inner = node.inner;
inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\');
if (inner === ']-') {
inner = '\\]\\-';
}
if (negated && inner.indexOf('.') === -1) {
inner += '.';
}
if (negated && inner.indexOf('/') === -1) {
inner += '/';
}
var val = open + negated + inner + close;
var queue = node.parent.queue;
var last = utils.arrayify(queue.pop());
queue.push(utils.join(last, val));
queue.push.apply(queue, []);
})
/**
* Brace
*/
.set('brace', function(node) {
node.queue = isEscaped(node) ? [node.val] : [];
node.count = 1;
return this.mapVisit(node.nodes);
})
/**
* Open
*/
.set('brace.open', function(node) {
node.parent.open = node.val;
})
/**
* Inner
*/
.set('text', function(node) {
var queue = node.parent.queue;
var escaped = node.escaped;
var segs = [node.val];
if (node.optimize === false) {
options = utils.extend({}, options, {optimize: false});
}
if (node.multiplier > 1) {
node.parent.count *= node.multiplier;
}
if (options.quantifiers === true && utils.isQuantifier(node.val)) {
escaped = true;
} else if (node.val.length > 1) {
if (isType(node.parent, 'brace') && !isEscaped(node)) {
var expanded = utils.expand(node.val, options);
segs = expanded.segs;
if (expanded.isOptimized) {
node.parent.isOptimized = true;
}
// if nothing was expanded, we probably have a literal brace
if (!segs.length) {
var val = (expanded.val || node.val);
if (options.unescape !== false) {
// unescape unexpanded brace sequence/set separators
val = val.replace(/\\([,.])/g, '$1');
// strip quotes
val = val.replace(/["'`]/g, '');
}
segs = [val];
escaped = true;
}
}
} else if (node.val === ',') {
if (options.expand) {
node.parent.queue.push(['']);
segs = [''];
} else {
segs = ['|'];
}
} else {
escaped = true;
}
if (escaped && isType(node.parent, 'brace')) {
if (node.parent.nodes.length <= 4 && node.parent.count === 1) {
node.parent.escaped = true;
} else if (node.parent.length <= 3) {
node.parent.escaped = true;
}
}
if (!hasQueue(node.parent)) {
node.parent.queue = segs;
return;
}
var last = utils.arrayify(queue.pop());
if (node.parent.count > 1 && options.expand) {
last = multiply(last, node.parent.count);
node.parent.count = 1;
}
queue.push(utils.join(utils.flatten(last), segs.shift()));
queue.push.apply(queue, segs);
})
/**
* Close
*/
.set('brace.close', function(node) {
var queue = node.parent.queue;
var prev = node.parent.parent;
var last = prev.queue.pop();
var open = node.parent.open;
var close = node.val;
if (open && close && isOptimized(node, options)) {
open = '(';
close = ')';
}
// if a close brace exists, and the previous segment is one character
// don't wrap the result in braces or parens
var ele = utils.last(queue);
if (node.parent.count > 1 && options.expand) {
ele = multiply(queue.pop(), node.parent.count);
node.parent.count = 1;
queue.push(ele);
}
if (close && typeof ele === 'string' && ele.length === 1) {
open = '';
close = '';
}
if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {
queue.push(utils.join(open, queue.pop() || ''));
queue = utils.flatten(utils.join(queue, close));
}
if (typeof last === 'undefined') {
prev.queue = [queue];
} else {
prev.queue.push(utils.flatten(utils.join(last, queue)));
}
})
/**
* eos
*/
.set('eos', function(node) {
if (this.input) return;
if (options.optimize !== false) {
this.output = utils.last(utils.flatten(this.ast.queue));
} else if (Array.isArray(utils.last(this.ast.queue))) {
this.output = utils.flatten(this.ast.queue.pop());
} else {
this.output = utils.flatten(this.ast.queue);
}
if (node.parent.count > 1 && options.expand) {
this.output = multiply(this.output, node.parent.count);
}
this.output = utils.arrayify(this.output);
this.ast.queue = [];
});
};
/**
* Multiply the segments in the current brace level
*/
function multiply(queue, n, options) {
return utils.flatten(utils.repeat(utils.arrayify(queue), n));
}
/**
* Return true if `node` is escaped
*/
function isEscaped(node) {
return node.escaped === true;
}
/**
* Returns true if regex parens should be used for sets. If the parent `type`
* is not `brace`, then we're on a root node, which means we should never
* expand segments and open/close braces should be `{}` (since this indicates
* a brace is missing from the set)
*/
function isOptimized(node, options) {
if (node.parent.isOptimized) return true;
return isType(node.parent, 'brace')
&& !isEscaped(node.parent)
&& options.expand !== true;
}
/**
* Returns true if the value in `node` should be wrapped in a literal brace.
* @return {Boolean}
*/
function isLiteralBrace(node, options) {
return isEscaped(node.parent) || options.optimize !== false;
}
/**
* Returns true if the given `node` does not have an inner value.
* @return {Boolean}
*/
function noInner(node, type) {
if (node.parent.queue.length === 1) {
return true;
}
var nodes = node.parent.nodes;
return nodes.length === 3
&& isType(nodes[0], 'brace.open')
&& !isType(nodes[1], 'text')
&& isType(nodes[2], 'brace.close');
}
/**
* Returns true if the given `node` is the given `type`
* @return {Boolean}
*/
function isType(node, type) {
return typeof node !== 'undefined' && node.type === type;
}
/**
* Returns true if the given `node` has a non-empty queue.
* @return {Boolean}
*/
function hasQueue(node) {
return Array.isArray(node.queue) && node.queue.length;
}

View file

@ -0,0 +1,360 @@
'use strict';
var Node = require('snapdragon-node');
var utils = require('./utils');
/**
* Braces parsers
*/
module.exports = function(braces, options) {
braces.parser
.set('bos', function() {
if (!this.parsed) {
this.ast = this.nodes[0] = new Node(this.ast);
}
})
/**
* Character parsers
*/
.set('escape', function() {
var pos = this.position();
var m = this.match(/^(?:\\(.)|\$\{)/);
if (!m) return;
var prev = this.prev();
var last = utils.last(prev.nodes);
var node = pos(new Node({
type: 'text',
multiplier: 1,
val: m[0]
}));
if (node.val === '\\\\') {
return node;
}
if (node.val === '${') {
var str = this.input;
var idx = -1;
var ch;
while ((ch = str[++idx])) {
this.consume(1);
node.val += ch;
if (ch === '\\') {
node.val += str[++idx];
continue;
}
if (ch === '}') {
break;
}
}
}
if (this.options.unescape !== false) {
node.val = node.val.replace(/\\([{}])/g, '$1');
}
if (last.val === '"' && this.input.charAt(0) === '"') {
last.val = node.val;
this.consume(1);
return;
}
return concatNodes.call(this, pos, node, prev, options);
})
/**
* Brackets: "[...]" (basic, this is overridden by
* other parsers in more advanced implementations)
*/
.set('bracket', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/);
if (!m) return;
var prev = this.prev();
var val = m[0];
var negated = m[1] ? '^' : '';
var inner = m[2] || '';
var close = m[3] || '';
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
var esc = this.input.slice(0, 2);
if (inner === '' && esc === '\\]') {
inner += esc;
this.consume(2);
var str = this.input;
var idx = -1;
var ch;
while ((ch = str[++idx])) {
this.consume(1);
if (ch === ']') {
close = ch;
break;
}
inner += ch;
}
}
return pos(new Node({
type: 'bracket',
val: val,
escaped: close !== ']',
negated: negated,
inner: inner,
close: close
}));
})
/**
* Empty braces (we capture these early to
* speed up processing in the compiler)
*/
.set('multiplier', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^\{((?:,|\{,+\})+)\}/);
if (!m) return;
this.multiplier = true;
var prev = this.prev();
var val = m[0];
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
var node = pos(new Node({
type: 'text',
multiplier: 1,
match: m,
val: val
}));
return concatNodes.call(this, pos, node, prev, options);
})
/**
* Open
*/
.set('brace.open', function() {
var pos = this.position();
var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/);
if (!m) return;
var prev = this.prev();
var last = utils.last(prev.nodes);
// if the last parsed character was an extglob character
// we need to _not optimize_ the brace pattern because
// it might be mistaken for an extglob by a downstream parser
if (last && last.val && isExtglobChar(last.val.slice(-1))) {
last.optimize = false;
}
var open = pos(new Node({
type: 'brace.open',
val: m[0]
}));
var node = pos(new Node({
type: 'brace',
nodes: []
}));
node.push(open);
prev.push(node);
this.push('brace', node);
})
/**
* Close
*/
.set('brace.close', function() {
var pos = this.position();
var m = this.match(/^\}/);
if (!m || !m[0]) return;
var brace = this.pop('brace');
var node = pos(new Node({
type: 'brace.close',
val: m[0]
}));
if (!this.isType(brace, 'brace')) {
if (this.options.strict) {
throw new Error('missing opening "{"');
}
node.type = 'text';
node.multiplier = 0;
node.escaped = true;
return node;
}
var prev = this.prev();
var last = utils.last(prev.nodes);
if (last.text) {
var lastNode = utils.last(last.nodes);
if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) {
var open = last.nodes[0];
var text = last.nodes[1];
if (open.type === 'brace.open' && text && text.type === 'text') {
text.optimize = false;
}
}
}
if (brace.nodes.length > 2) {
var first = brace.nodes[1];
if (first.type === 'text' && first.val === ',') {
brace.nodes.splice(1, 1);
brace.nodes.push(first);
}
}
brace.push(node);
})
/**
* Capture boundary characters
*/
.set('boundary', function() {
var pos = this.position();
var m = this.match(/^[$^](?!\{)/);
if (!m) return;
return pos(new Node({
type: 'text',
val: m[0]
}));
})
/**
* One or zero, non-comma characters wrapped in braces
*/
.set('nobrace', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^\{[^,]?\}/);
if (!m) return;
var prev = this.prev();
var val = m[0];
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
return pos(new Node({
type: 'text',
multiplier: 0,
val: val
}));
})
/**
* Text
*/
.set('text', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^((?!\\)[^${}[\]])+/);
if (!m) return;
var prev = this.prev();
var val = m[0];
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
var node = pos(new Node({
type: 'text',
multiplier: 1,
val: val
}));
return concatNodes.call(this, pos, node, prev, options);
});
};
/**
* Returns true if the character is an extglob character.
*/
function isExtglobChar(ch) {
return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';
}
/**
* Combine text nodes, and calculate empty sets (`{,,}`)
* @param {Function} `pos` Function to calculate node position
* @param {Object} `node` AST node
* @return {Object}
*/
function concatNodes(pos, node, parent, options) {
node.orig = node.val;
var prev = this.prev();
var last = utils.last(prev.nodes);
var isEscaped = false;
if (node.val.length > 1) {
var a = node.val.charAt(0);
var b = node.val.slice(-1);
isEscaped = (a === '"' && b === '"')
|| (a === "'" && b === "'")
|| (a === '`' && b === '`');
}
if (isEscaped && options.unescape !== false) {
node.val = node.val.slice(1, node.val.length - 1);
node.escaped = true;
}
if (node.match) {
var match = node.match[1];
if (!match || match.indexOf('}') === -1) {
match = node.match[0];
}
// replace each set with a single ","
var val = match.replace(/\{/g, ',').replace(/\}/g, '');
node.multiplier *= val.length;
node.val = '';
}
var simpleText = last.type === 'text'
&& last.multiplier === 1
&& node.multiplier === 1
&& node.val;
if (simpleText) {
last.val += node.val;
return;
}
prev.push(node);
}

View file

@ -0,0 +1,343 @@
'use strict';
var splitString = require('split-string');
var utils = module.exports;
/**
* Module dependencies
*/
utils.extend = require('extend-shallow');
utils.flatten = require('arr-flatten');
utils.isObject = require('isobject');
utils.fillRange = require('fill-range');
utils.repeat = require('repeat-element');
utils.unique = require('array-unique');
utils.define = function(obj, key, val) {
Object.defineProperty(obj, key, {
writable: true,
configurable: true,
enumerable: false,
value: val
});
};
/**
* Returns true if the given string contains only empty brace sets.
*/
utils.isEmptySets = function(str) {
return /^(?:\{,\})+$/.test(str);
};
/**
* Returns true if the given string contains only empty brace sets.
*/
utils.isQuotedString = function(str) {
var open = str.charAt(0);
if (open === '\'' || open === '"' || open === '`') {
return str.slice(-1) === open;
}
return false;
};
/**
* Create the key to use for memoization. The unique key is generated
* by iterating over the options and concatenating key-value pairs
* to the pattern string.
*/
utils.createKey = function(pattern, options) {
var id = pattern;
if (typeof options === 'undefined') {
return id;
}
var keys = Object.keys(options);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
id += ';' + key + '=' + String(options[key]);
}
return id;
};
/**
* Normalize options
*/
utils.createOptions = function(options) {
var opts = utils.extend.apply(null, arguments);
if (typeof opts.expand === 'boolean') {
opts.optimize = !opts.expand;
}
if (typeof opts.optimize === 'boolean') {
opts.expand = !opts.optimize;
}
if (opts.optimize === true) {
opts.makeRe = true;
}
return opts;
};
/**
* Join patterns in `a` to patterns in `b`
*/
utils.join = function(a, b, options) {
options = options || {};
a = utils.arrayify(a);
b = utils.arrayify(b);
if (!a.length) return b;
if (!b.length) return a;
var len = a.length;
var idx = -1;
var arr = [];
while (++idx < len) {
var val = a[idx];
if (Array.isArray(val)) {
for (var i = 0; i < val.length; i++) {
val[i] = utils.join(val[i], b, options);
}
arr.push(val);
continue;
}
for (var j = 0; j < b.length; j++) {
var bval = b[j];
if (Array.isArray(bval)) {
arr.push(utils.join(val, bval, options));
} else {
arr.push(val + bval);
}
}
}
return arr;
};
/**
* Split the given string on `,` if not escaped.
*/
utils.split = function(str, options) {
var opts = utils.extend({sep: ','}, options);
if (typeof opts.keepQuotes !== 'boolean') {
opts.keepQuotes = true;
}
if (opts.unescape === false) {
opts.keepEscaping = true;
}
return splitString(str, opts, utils.escapeBrackets(opts));
};
/**
* Expand ranges or sets in the given `pattern`.
*
* @param {String} `str`
* @param {Object} `options`
* @return {Object}
*/
utils.expand = function(str, options) {
var opts = utils.extend({rangeLimit: 10000}, options);
var segs = utils.split(str, opts);
var tok = { segs: segs };
if (utils.isQuotedString(str)) {
return tok;
}
if (opts.rangeLimit === true) {
opts.rangeLimit = 10000;
}
if (segs.length > 1) {
if (opts.optimize === false) {
tok.val = segs[0];
return tok;
}
tok.segs = utils.stringifyArray(tok.segs);
} else if (segs.length === 1) {
var arr = str.split('..');
if (arr.length === 1) {
tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;
tok.segs = [];
return tok;
}
if (arr.length === 2 && arr[0] === arr[1]) {
tok.escaped = true;
tok.val = arr[0];
tok.segs = [];
return tok;
}
if (arr.length > 1) {
if (opts.optimize !== false) {
opts.optimize = true;
delete opts.expand;
}
if (opts.optimize !== true) {
var min = Math.min(arr[0], arr[1]);
var max = Math.max(arr[0], arr[1]);
var step = arr[2] || 1;
if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {
throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
}
}
arr.push(opts);
tok.segs = utils.fillRange.apply(null, arr);
if (!tok.segs.length) {
tok.escaped = true;
tok.val = str;
return tok;
}
if (opts.optimize === true) {
tok.segs = utils.stringifyArray(tok.segs);
}
if (tok.segs === '') {
tok.val = str;
} else {
tok.val = tok.segs[0];
}
return tok;
}
} else {
tok.val = str;
}
return tok;
};
/**
* Ensure commas inside brackets and parens are not split.
* @param {Object} `tok` Token from the `split-string` module
* @return {undefined}
*/
utils.escapeBrackets = function(options) {
return function(tok) {
if (tok.escaped && tok.val === 'b') {
tok.val = '\\b';
return;
}
if (tok.val !== '(' && tok.val !== '[') return;
var opts = utils.extend({}, options);
var brackets = [];
var parens = [];
var stack = [];
var val = tok.val;
var str = tok.str;
var i = tok.idx - 1;
while (++i < str.length) {
var ch = str[i];
if (ch === '\\') {
val += (opts.keepEscaping === false ? '' : ch) + str[++i];
continue;
}
if (ch === '(') {
parens.push(ch);
stack.push(ch);
}
if (ch === '[') {
brackets.push(ch);
stack.push(ch);
}
if (ch === ')') {
parens.pop();
stack.pop();
if (!stack.length) {
val += ch;
break;
}
}
if (ch === ']') {
brackets.pop();
stack.pop();
if (!stack.length) {
val += ch;
break;
}
}
val += ch;
}
tok.split = false;
tok.val = val.slice(1);
tok.idx = i;
};
};
/**
* Returns true if the given string looks like a regex quantifier
* @return {Boolean}
*/
utils.isQuantifier = function(str) {
return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);
};
/**
* Cast `val` to an array.
* @param {*} `val`
*/
utils.stringifyArray = function(arr) {
return [utils.arrayify(arr).join('|')];
};
/**
* Cast `val` to an array.
* @param {*} `val`
*/
utils.arrayify = function(arr) {
if (typeof arr === 'undefined') {
return [];
}
if (typeof arr === 'string') {
return [arr];
}
return arr;
};
/**
* Returns true if the given `str` is a non-empty string
* @return {Boolean}
*/
utils.isString = function(str) {
return str != null && typeof str === 'string';
};
/**
* Get the last element from `array`
* @param {Array} `array`
* @return {*}
*/
utils.last = function(arr, n) {
return arr[arr.length - (n || 1)];
};
utils.escapeRegex = function(str) {
return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1');
};

View file

@ -0,0 +1,108 @@
{
"name": "braces",
"description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.",
"version": "2.3.2",
"homepage": "https://github.com/micromatch/braces",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"Brian Woodward (https://twitter.com/doowb)",
"Elan Shanker (https://github.com/es128)",
"Eugene Sharygin (https://github.com/eush77)",
"hemanth.hm (http://h3manth.com)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)"
],
"repository": "micromatch/braces",
"bugs": {
"url": "https://github.com/micromatch/braces/issues"
},
"license": "MIT",
"files": [
"index.js",
"lib"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha",
"benchmark": "node benchmark"
},
"dependencies": {
"arr-flatten": "^1.1.0",
"array-unique": "^0.3.2",
"extend-shallow": "^2.0.1",
"fill-range": "^4.0.0",
"isobject": "^3.0.1",
"repeat-element": "^1.1.2",
"snapdragon": "^0.8.1",
"snapdragon-node": "^2.0.1",
"split-string": "^3.0.2",
"to-regex": "^3.0.1"
},
"devDependencies": {
"ansi-cyan": "^0.1.1",
"benchmarked": "^2.0.0",
"brace-expansion": "^1.1.8",
"cross-spawn": "^5.1.0",
"gulp": "^3.9.1",
"gulp-eslint": "^4.0.0",
"gulp-format-md": "^1.0.0",
"gulp-istanbul": "^1.1.2",
"gulp-mocha": "^3.0.1",
"gulp-unused": "^0.2.1",
"is-windows": "^1.0.1",
"minimatch": "^3.0.4",
"mocha": "^3.2.0",
"noncharacters": "^1.1.0",
"text-table": "^0.2.0",
"time-diff": "^0.3.1",
"yargs-parser": "^8.0.0"
},
"keywords": [
"alpha",
"alphabetical",
"bash",
"brace",
"braces",
"expand",
"expansion",
"filepath",
"fill",
"fs",
"glob",
"globbing",
"letter",
"match",
"matches",
"matching",
"number",
"numerical",
"path",
"range",
"ranges",
"sh"
],
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"lint": {
"reflinks": true
},
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"expand-brackets",
"extglob",
"fill-range",
"micromatch",
"nanomatch"
]
}
}
}

View file

@ -0,0 +1,116 @@
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var stripAnsi = require('strip-ansi');
var hasAnsi = require('has-ansi');
var supportsColor = require('supports-color');
var defineProps = Object.defineProperties;
var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
function Chalk(options) {
// detect mode if not set manually
this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
}
// use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001b[94m';
}
var styles = (function () {
var ret = {};
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build.call(this, this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function chalk() {}, styles);
function build(_styles) {
var builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder.enabled = this.enabled;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
/* eslint-disable no-proto */
builder.__proto__ = proto;
return builder;
}
function applyStyle() {
// support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// don't slice `arguments`, it prevents v8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
ansiStyles.dim.open = '';
}
while (i--) {
var code = ansiStyles[nestedStyles[i]];
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
// Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
ansiStyles.dim.open = originalDim;
return str;
}
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build.call(this, [name]);
}
};
});
return ret;
}
defineProps(Chalk.prototype, init());
module.exports = new Chalk();
module.exports.styles = ansiStyles;
module.exports.hasColor = hasAnsi;
module.exports.stripColor = stripAnsi;
module.exports.supportsColor = supportsColor;

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,50 @@
'use strict';
var argv = process.argv;
var terminator = argv.indexOf('--');
var hasFlag = function (flag) {
flag = '--' + flag;
var pos = argv.indexOf(flag);
return pos !== -1 && (terminator !== -1 ? pos < terminator : true);
};
module.exports = (function () {
if ('FORCE_COLOR' in process.env) {
return true;
}
if (hasFlag('no-color') ||
hasFlag('no-colors') ||
hasFlag('color=false')) {
return false;
}
if (hasFlag('color') ||
hasFlag('colors') ||
hasFlag('color=true') ||
hasFlag('color=always')) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();

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,49 @@
{
"name": "supports-color",
"version": "2.0.0",
"description": "Detect whether a terminal supports color",
"license": "MIT",
"repository": "chalk/supports-color",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)"
],
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"ansi",
"styles",
"tty",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"support",
"supports",
"capability",
"detect"
],
"devDependencies": {
"mocha": "*",
"require-uncached": "^1.0.2"
}
}

View file

@ -0,0 +1,36 @@
# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color)
> Detect whether a terminal supports color
## Install
```
$ npm install --save supports-color
```
## Usage
```js
var supportsColor = require('supports-color');
if (supportsColor) {
console.log('Terminal supports color');
}
```
It obeys the `--color` and `--no-color` CLI flags.
For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
## Related
- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,70 @@
{
"name": "chalk",
"version": "1.1.3",
"description": "Terminal string styling done right. Much color.",
"license": "MIT",
"repository": "chalk/chalk",
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
"JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && mocha",
"bench": "matcha benchmark.js",
"coverage": "nyc npm test && nyc report",
"coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^2.2.1",
"escape-string-regexp": "^1.0.2",
"has-ansi": "^2.0.0",
"strip-ansi": "^3.0.0",
"supports-color": "^2.0.0"
},
"devDependencies": {
"coveralls": "^2.11.2",
"matcha": "^0.6.0",
"mocha": "*",
"nyc": "^3.0.0",
"require-uncached": "^1.0.2",
"resolve-from": "^1.0.0",
"semver": "^4.3.3",
"xo": "*"
},
"xo": {
"envs": [
"node",
"mocha"
]
}
}

View file

@ -0,0 +1,213 @@
<h1 align="center">
<br>
<br>
<img width="360" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
**Chalk is a clean and focused alternative.**
![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
## Why
- Highly performant
- Doesn't extend `String.prototype`
- Expressive API
- Ability to nest styles
- Clean and focused
- Auto-detects color support
- Actively maintained
- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015
## Install
```
$ npm install --save chalk
```
## Usage
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
var chalk = require('chalk');
// style a string
chalk.blue('Hello world!');
// combine styled and normal strings
chalk.blue('Hello') + 'World' + chalk.red('!');
// compose multiple styles using the chainable API
chalk.blue.bgRed.bold('Hello world!');
// pass in multiple arguments
chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
// nest styles
chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
// nest styles of the same type even (color, underline, background)
chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
);
```
Easily define your own themes.
```js
var chalk = require('chalk');
var error = chalk.bold.red;
console.log(error('Error!'));
```
Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
```js
var name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> Hello Sindre
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `Chalk.red.yellow.green` is equivalent to `Chalk.green`.
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, but you can override it by setting the `enabled` property. You should however only do this in your own code as it applies globally to all chalk consumers.
If you need to change this in a reusable module create a new instance:
```js
var ctx = new chalk.constructor({enabled: false});
```
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
### chalk.styles
Exposes the styles as [ANSI escape codes](https://github.com/chalk/ansi-styles).
Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with your own.
```js
var chalk = require('chalk');
console.log(chalk.styles.red);
//=> {open: '\u001b[31m', close: '\u001b[39m'}
console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
```
### chalk.hasColor(string)
Check whether a string [has color](https://github.com/chalk/has-ansi).
### chalk.stripColor(string)
[Strip color](https://github.com/chalk/strip-ansi) from a string.
Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
Example:
```js
var chalk = require('chalk');
var styledString = getText();
if (!chalk.supportsColor) {
styledString = chalk.stripColor(styledString);
}
```
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue` *(on Windows the bright version is used as normal blue is illegible)*
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## 256-colors
Chalk does not support anything other than the base eight colors, which guarantees it will work on all terminals and systems. Some terminals, specifically `xterm` compliant ones, will support the full range of 8-bit colors. For this the lower level [ansi-256-colors](https://github.com/jbnicolai/ansi-256-colors) package can be used.
## Windows
If you're on Windows, do yourself a favor and use [`cmder`](http://bliker.github.io/cmder/) instead of `cmd.exe`.
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles/) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color/) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,250 @@
# fill-range [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range)
> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`
## Table of Contents
- [Install](#install)
- [Usage](#usage)
- [Examples](#examples)
- [Options](#options)
* [options.step](#optionsstep)
* [options.strictRanges](#optionsstrictranges)
* [options.stringify](#optionsstringify)
* [options.toRegex](#optionstoregex)
* [options.transform](#optionstransform)
- [About](#about)
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save fill-range
```
Install with [yarn](https://yarnpkg.com):
```sh
$ yarn add fill-range
```
## Usage
Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_.
```js
var fill = require('fill-range');
fill(from, to[, step, options]);
// examples
console.log(fill('1', '10')); //=> '[ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ]'
console.log(fill('1', '10', {toRegex: true})); //=> [1-9]|10
```
**Params**
* `from`: **{String|Number}** the number or letter to start with
* `to`: **{String|Number}** the number or letter to end with
* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use.
* `options`: **{Object|Function}**: See all available [options](#options)
## Examples
By default, an array of values is returned.
**Alphabetical ranges**
```js
console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e']
console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ]
```
**Numerical ranges**
Numbers can be defined as actual numbers or strings.
```js
console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ]
console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ]
```
**Negative ranges**
Numbers can be defined as actual numbers or strings.
```js
console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ]
console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ]
```
**Steps (increments)**
```js
// numerical ranges with increments
console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ]
console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ]
console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ]
// alphabetical ranges with increments
console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ]
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ]
```
## Options
### options.step
**Type**: `number` (formatted as a string or number)
**Default**: `undefined`
**Description**: The increment to use for the range. Can be used with letters or numbers.
**Example(s)**
```js
// numbers
console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ]
console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ]
console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ]
// letters
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ]
console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ]
```
### options.strictRanges
**Type**: `boolean`
**Default**: `false`
**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges.
**Example(s)**
The following are all invalid:
```js
fill('1.1', '2'); // decimals not supported in ranges
fill('a', '2'); // incompatible range values
fill(1, 10, 'foo'); // invalid "step" argument
```
### options.stringify
**Type**: `boolean`
**Default**: `undefined`
**Description**: Cast all returned values to strings. By default, integers are returned as numbers.
**Example(s)**
```js
console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ]
console.log(fill(1, 5, {stringify: true})); //=> [ '1', '2', '3', '4', '5' ]
```
### options.toRegex
**Type**: `boolean`
**Default**: `undefined`
**Description**: Create a regex-compatible source string, instead of expanding values to an array.
**Example(s)**
```js
// alphabetical range
console.log(fill('a', 'e', {toRegex: true})); //=> '[a-e]'
// alphabetical with step
console.log(fill('a', 'z', 3, {toRegex: true})); //=> 'a|d|g|j|m|p|s|v|y'
// numerical range
console.log(fill('1', '100', {toRegex: true})); //=> '[1-9]|[1-9][0-9]|100'
// numerical range with zero padding
console.log(fill('000001', '100000', {toRegex: true}));
//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000'
```
### options.transform
**Type**: `function`
**Default**: `undefined`
**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_.
**Example(s)**
```js
// increase padding by two
var arr = fill('01', '05', function(val, a, b, step, idx, arr, options) {
return repeat('0', (options.maxLength + 2) - val.length) + val;
});
console.log(arr);
//=> ['0001', '0002', '0003', '0004', '0005']
```
## About
### Related projects
* [braces](https://www.npmjs.com/package/braces): Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces specification, without sacrificing speed.")
* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See the benchmarks. Used by micromatch.")
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
* [to-regex-range](https://www.npmjs.com/package/to-regex-range): Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than… [more](https://github.com/jonschlinkert/to-regex-range) | [homepage](https://github.com/jonschlinkert/to-regex-range "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.87 million test assertions.")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 103 | [jonschlinkert](https://github.com/jonschlinkert) |
| 2 | [paulmillr](https://github.com/paulmillr) |
| 1 | [edorivai](https://github.com/edorivai) |
| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |
### Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 23, 2017._

View file

@ -0,0 +1,208 @@
/*!
* fill-range <https://github.com/jonschlinkert/fill-range>
*
* Copyright (c) 2014-2015, 2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var util = require('util');
var isNumber = require('is-number');
var extend = require('extend-shallow');
var repeat = require('repeat-string');
var toRegex = require('to-regex-range');
/**
* Return a range of numbers or letters.
*
* @param {String} `start` Start of the range
* @param {String} `stop` End of the range
* @param {String} `step` Increment or decrement to use.
* @param {Function} `fn` Custom function to modify each element in the range.
* @return {Array}
*/
function fillRange(start, stop, step, options) {
if (typeof start === 'undefined') {
return [];
}
if (typeof stop === 'undefined' || start === stop) {
// special case, for handling negative zero
var isString = typeof start === 'string';
if (isNumber(start) && !toNumber(start)) {
return [isString ? '0' : 0];
}
return [start];
}
if (typeof step !== 'number' && typeof step !== 'string') {
options = step;
step = undefined;
}
if (typeof options === 'function') {
options = { transform: options };
}
var opts = extend({step: step}, options);
if (opts.step && !isValidNumber(opts.step)) {
if (opts.strictRanges === true) {
throw new TypeError('expected options.step to be a number');
}
return [];
}
opts.isNumber = isValidNumber(start) && isValidNumber(stop);
if (!opts.isNumber && !isValid(start, stop)) {
if (opts.strictRanges === true) {
throw new RangeError('invalid range arguments: ' + util.inspect([start, stop]));
}
return [];
}
opts.isPadded = isPadded(start) || isPadded(stop);
opts.toString = opts.stringify
|| typeof opts.step === 'string'
|| typeof start === 'string'
|| typeof stop === 'string'
|| !opts.isNumber;
if (opts.isPadded) {
opts.maxLength = Math.max(String(start).length, String(stop).length);
}
// support legacy minimatch/fill-range options
if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize;
if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe;
return expand(start, stop, opts);
}
function expand(start, stop, options) {
var a = options.isNumber ? toNumber(start) : start.charCodeAt(0);
var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0);
var step = Math.abs(toNumber(options.step)) || 1;
if (options.toRegex && step === 1) {
return toRange(a, b, start, stop, options);
}
var zero = {greater: [], lesser: []};
var asc = a < b;
var arr = new Array(Math.round((asc ? b - a : a - b) / step));
var idx = 0;
while (asc ? a <= b : a >= b) {
var val = options.isNumber ? a : String.fromCharCode(a);
if (options.toRegex && (val >= 0 || !options.isNumber)) {
zero.greater.push(val);
} else {
zero.lesser.push(Math.abs(val));
}
if (options.isPadded) {
val = zeros(val, options);
}
if (options.toString) {
val = String(val);
}
if (typeof options.transform === 'function') {
arr[idx++] = options.transform(val, a, b, step, idx, arr, options);
} else {
arr[idx++] = val;
}
if (asc) {
a += step;
} else {
a -= step;
}
}
if (options.toRegex === true) {
return toSequence(arr, zero, options);
}
return arr;
}
function toRange(a, b, start, stop, options) {
if (options.isPadded) {
return toRegex(start, stop, options);
}
if (options.isNumber) {
return toRegex(Math.min(a, b), Math.max(a, b), options);
}
var start = String.fromCharCode(Math.min(a, b));
var stop = String.fromCharCode(Math.max(a, b));
return '[' + start + '-' + stop + ']';
}
function toSequence(arr, zeros, options) {
var greater = '', lesser = '';
if (zeros.greater.length) {
greater = zeros.greater.join('|');
}
if (zeros.lesser.length) {
lesser = '-(' + zeros.lesser.join('|') + ')';
}
var res = greater && lesser
? greater + '|' + lesser
: greater || lesser;
if (options.capture) {
return '(' + res + ')';
}
return res;
}
function zeros(val, options) {
if (options.isPadded) {
var str = String(val);
var len = str.length;
var dash = '';
if (str.charAt(0) === '-') {
dash = '-';
str = str.slice(1);
}
var diff = options.maxLength - len;
var pad = repeat('0', diff);
val = (dash + pad + str);
}
if (options.stringify) {
return String(val);
}
return val;
}
function toNumber(val) {
return Number(val) || 0;
}
function isPadded(str) {
return /^-?0\d/.test(str);
}
function isValid(min, max) {
return (isValidNumber(min) || isValidLetter(min))
&& (isValidNumber(max) || isValidLetter(max));
}
function isValidLetter(ch) {
return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch);
}
function isValidNumber(n) {
return isNumber(n) && !/\./.test(n);
}
/**
* Expose `fillRange`
* @type {Function}
*/
module.exports = fillRange;

View file

@ -0,0 +1,82 @@
{
"name": "fill-range",
"description": "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`",
"version": "4.0.0",
"homepage": "https://github.com/jonschlinkert/fill-range",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"<wtgtybhertgeghgtwtg@gmail.com> (https://github.com/wtgtybhertgeghgtwtg)",
"Edo Rivai <edo.rivai@gmail.com> (edo.rivai.nl)",
"Jon Schlinkert <jon.schlinkert@sellside.com> (http://twitter.com/jonschlinkert)",
"Paul Miller <paul+gh@paulmillr.com> (paulmillr.com)"
],
"repository": "jonschlinkert/fill-range",
"bugs": {
"url": "https://github.com/jonschlinkert/fill-range/issues"
},
"license": "MIT",
"files": [
"index.js"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"extend-shallow": "^2.0.1",
"is-number": "^3.0.0",
"repeat-string": "^1.6.1",
"to-regex-range": "^2.1.0"
},
"devDependencies": {
"ansi-cyan": "^0.1.1",
"benchmarked": "^1.0.0",
"gulp-format-md": "^0.1.12",
"minimist": "^1.2.0",
"mocha": "^3.2.0"
},
"keywords": [
"alpha",
"alphabetical",
"array",
"bash",
"brace",
"expand",
"expansion",
"fill",
"glob",
"match",
"matches",
"matching",
"number",
"numerical",
"range",
"ranges",
"regex",
"sh"
],
"verb": {
"related": {
"list": [
"braces",
"expand-range",
"micromatch",
"to-regex-range"
]
},
"toc": true,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
}
}
}

View file

@ -0,0 +1,10 @@
'use strict';
module.exports = function (flag, argv) {
argv = argv || process.argv;
var terminatorPos = argv.indexOf('--');
var prefix = /^--/.test(flag) ? '' : '--';
var pos = argv.indexOf(prefix + flag);
return pos !== -1 && (terminatorPos !== -1 ? pos < terminatorPos : true);
};

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,48 @@
{
"name": "has-flag",
"version": "1.0.0",
"description": "Check if argv has a specific flag",
"license": "MIT",
"repository": "sindresorhus/has-flag",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
"JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "node test.js"
},
"files": [
"index.js"
],
"keywords": [
"has",
"check",
"detect",
"contains",
"find",
"flag",
"cli",
"command-line",
"argv",
"process",
"arg",
"args",
"argument",
"arguments",
"getopt",
"minimist",
"optimist"
],
"devDependencies": {
"ava": "0.0.4"
}
}

View file

@ -0,0 +1,64 @@
# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag)
> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag
Correctly stops looking after an `--` argument terminator.
## Install
```
$ npm install --save has-flag
```
## Usage
```js
// foo.js
var hasFlag = require('has-flag');
hasFlag('unicorn');
//=> true
hasFlag('--unicorn');
//=> true
hasFlag('foo=bar');
//=> true
hasFlag('foo');
//=> false
hasFlag('rainbow');
//=> false
```
```
$ node foo.js --unicorn --foo=bar -- --rainbow
```
## API
### hasFlag(flag, [argv])
Returns a boolean whether the flag exists.
#### flag
Type: `string`
CLI flag to look for. The `--` prefix is optional.
#### argv
Type: `array`
Default: `process.argv`
CLI arguments.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2016, Jon Schlinkert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,115 @@
# is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-number)
> Returns true if the value is a number. comprehensive tests.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save is-number
```
## Usage
To understand some of the rationale behind the decisions made in this library (and to learn about some oddities of number evaluation in JavaScript), [see this gist](https://gist.github.com/jonschlinkert/e30c70c713da325d0e81).
```js
var isNumber = require('is-number');
```
### true
See the [tests](./test.js) for more examples.
```js
isNumber(5e3) //=> 'true'
isNumber(0xff) //=> 'true'
isNumber(-1.1) //=> 'true'
isNumber(0) //=> 'true'
isNumber(1) //=> 'true'
isNumber(1.1) //=> 'true'
isNumber(10) //=> 'true'
isNumber(10.10) //=> 'true'
isNumber(100) //=> 'true'
isNumber('-1.1') //=> 'true'
isNumber('0') //=> 'true'
isNumber('012') //=> 'true'
isNumber('0xff') //=> 'true'
isNumber('1') //=> 'true'
isNumber('1.1') //=> 'true'
isNumber('10') //=> 'true'
isNumber('10.10') //=> 'true'
isNumber('100') //=> 'true'
isNumber('5e3') //=> 'true'
isNumber(parseInt('012')) //=> 'true'
isNumber(parseFloat('012')) //=> 'true'
```
### False
See the [tests](./test.js) for more examples.
```js
isNumber('foo') //=> 'false'
isNumber([1]) //=> 'false'
isNumber([]) //=> 'false'
isNumber(function () {}) //=> 'false'
isNumber(Infinity) //=> 'false'
isNumber(NaN) //=> 'false'
isNumber(new Array('abc')) //=> 'false'
isNumber(new Array(2)) //=> 'false'
isNumber(new Buffer('abc')) //=> 'false'
isNumber(null) //=> 'false'
isNumber(undefined) //=> 'false'
isNumber({abc: 'abc'}) //=> 'false'
```
## About
### Related projects
* [even](https://www.npmjs.com/package/even): Get the even numbered items from an array. | [homepage](https://github.com/jonschlinkert/even "Get the even numbered items from an array.")
* [is-even](https://www.npmjs.com/package/is-even): Return true if the given number is even. | [homepage](https://github.com/jonschlinkert/is-even "Return true if the given number is even.")
* [is-odd](https://www.npmjs.com/package/is-odd): Returns true if the given number is odd. | [homepage](https://github.com/jonschlinkert/is-odd "Returns true if the given number is odd.")
* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ")
* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.")
* [odd](https://www.npmjs.com/package/odd): Get the odd numbered items from an array. | [homepage](https://github.com/jonschlinkert/odd "Get the odd numbered items from an array.")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Building docs
_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_
To generate the readme and API documentation with [verb](https://github.com/verbose/verb):
```sh
$ npm install -g verb verb-generate-readme && verb
```
### Running tests
Install dev dependencies:
```sh
$ npm install -d && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
### License
Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT license](https://github.com/jonschlinkert/is-number/blob/master/LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.30, on September 10, 2016._

View file

@ -0,0 +1,22 @@
/*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var typeOf = require('kind-of');
module.exports = function isNumber(num) {
var type = typeOf(num);
if (type === 'string') {
if (!num.trim()) return false;
} else if (type !== 'number') {
return false;
}
return (num - num + 1) >= 0;
};

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,261 @@
# kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of)
> Get the native type of a value.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save kind-of
```
## Install
Install with [bower](https://bower.io/)
```sh
$ bower install kind-of --save
```
## Usage
> es5, browser and es6 ready
```js
var kindOf = require('kind-of');
kindOf(undefined);
//=> 'undefined'
kindOf(null);
//=> 'null'
kindOf(true);
//=> 'boolean'
kindOf(false);
//=> 'boolean'
kindOf(new Boolean(true));
//=> 'boolean'
kindOf(new Buffer(''));
//=> 'buffer'
kindOf(42);
//=> 'number'
kindOf(new Number(42));
//=> 'number'
kindOf('str');
//=> 'string'
kindOf(new String('str'));
//=> 'string'
kindOf(arguments);
//=> 'arguments'
kindOf({});
//=> 'object'
kindOf(Object.create(null));
//=> 'object'
kindOf(new Test());
//=> 'object'
kindOf(new Date());
//=> 'date'
kindOf([]);
//=> 'array'
kindOf([1, 2, 3]);
//=> 'array'
kindOf(new Array());
//=> 'array'
kindOf(/foo/);
//=> 'regexp'
kindOf(new RegExp('foo'));
//=> 'regexp'
kindOf(function () {});
//=> 'function'
kindOf(function * () {});
//=> 'function'
kindOf(new Function());
//=> 'function'
kindOf(new Map());
//=> 'map'
kindOf(new WeakMap());
//=> 'weakmap'
kindOf(new Set());
//=> 'set'
kindOf(new WeakSet());
//=> 'weakset'
kindOf(Symbol('str'));
//=> 'symbol'
kindOf(new Int8Array());
//=> 'int8array'
kindOf(new Uint8Array());
//=> 'uint8array'
kindOf(new Uint8ClampedArray());
//=> 'uint8clampedarray'
kindOf(new Int16Array());
//=> 'int16array'
kindOf(new Uint16Array());
//=> 'uint16array'
kindOf(new Int32Array());
//=> 'int32array'
kindOf(new Uint32Array());
//=> 'uint32array'
kindOf(new Float32Array());
//=> 'float32array'
kindOf(new Float64Array());
//=> 'float64array'
```
## Benchmarks
Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of).
Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`.
```bash
#1: array
current x 23,329,397 ops/sec ±0.82% (94 runs sampled)
lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled)
lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled)
#2: boolean
current x 27,197,115 ops/sec ±0.85% (94 runs sampled)
lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled)
lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled)
#3: date
current x 20,190,117 ops/sec ±0.86% (92 runs sampled)
lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled)
lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled)
#4: function
current x 23,855,460 ops/sec ±0.60% (97 runs sampled)
lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled)
lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled)
#5: null
current x 27,061,047 ops/sec ±0.97% (96 runs sampled)
lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled)
lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled)
#6: number
current x 25,075,682 ops/sec ±0.53% (99 runs sampled)
lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled)
lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled)
#7: object
current x 3,348,980 ops/sec ±0.49% (99 runs sampled)
lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled)
lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled)
#8: regex
current x 21,284,827 ops/sec ±0.72% (96 runs sampled)
lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled)
lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled)
#9: string
current x 25,379,234 ops/sec ±0.58% (96 runs sampled)
lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled)
lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled)
#10: undef
current x 27,459,221 ops/sec ±1.01% (93 runs sampled)
lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled)
lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled)
```
## Optimizations
In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library:
1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot.
2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it.
3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'`
## About
### Related projects
* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet")
* [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.")
* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 59 | [jonschlinkert](https://github.com/jonschlinkert) |
| 2 | [miguelmota](https://github.com/miguelmota) |
| 1 | [dtothefp](https://github.com/dtothefp) |
| 1 | [ksheedlo](https://github.com/ksheedlo) |
| 1 | [pdehaan](https://github.com/pdehaan) |
| 1 | [laggingreflex](https://github.com/laggingreflex) |
### Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._

View file

@ -0,0 +1,116 @@
var isBuffer = require('is-buffer');
var toString = Object.prototype.toString;
/**
* Get the native `typeof` a value.
*
* @param {*} `val`
* @return {*} Native javascript type
*/
module.exports = function kindOf(val) {
// primitivies
if (typeof val === 'undefined') {
return 'undefined';
}
if (val === null) {
return 'null';
}
if (val === true || val === false || val instanceof Boolean) {
return 'boolean';
}
if (typeof val === 'string' || val instanceof String) {
return 'string';
}
if (typeof val === 'number' || val instanceof Number) {
return 'number';
}
// functions
if (typeof val === 'function' || val instanceof Function) {
return 'function';
}
// array
if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
return 'array';
}
// check for instances of RegExp and Date before calling `toString`
if (val instanceof RegExp) {
return 'regexp';
}
if (val instanceof Date) {
return 'date';
}
// other objects
var type = toString.call(val);
if (type === '[object RegExp]') {
return 'regexp';
}
if (type === '[object Date]') {
return 'date';
}
if (type === '[object Arguments]') {
return 'arguments';
}
if (type === '[object Error]') {
return 'error';
}
// buffer
if (isBuffer(val)) {
return 'buffer';
}
// es6: Map, WeakMap, Set, WeakSet
if (type === '[object Set]') {
return 'set';
}
if (type === '[object WeakSet]') {
return 'weakset';
}
if (type === '[object Map]') {
return 'map';
}
if (type === '[object WeakMap]') {
return 'weakmap';
}
if (type === '[object Symbol]') {
return 'symbol';
}
// typed arrays
if (type === '[object Int8Array]') {
return 'int8array';
}
if (type === '[object Uint8Array]') {
return 'uint8array';
}
if (type === '[object Uint8ClampedArray]') {
return 'uint8clampedarray';
}
if (type === '[object Int16Array]') {
return 'int16array';
}
if (type === '[object Uint16Array]') {
return 'uint16array';
}
if (type === '[object Int32Array]') {
return 'int32array';
}
if (type === '[object Uint32Array]') {
return 'uint32array';
}
if (type === '[object Float32Array]') {
return 'float32array';
}
if (type === '[object Float64Array]') {
return 'float64array';
}
// must be a plain object
return 'object';
};

View file

@ -0,0 +1,90 @@
{
"name": "kind-of",
"description": "Get the native type of a value.",
"version": "3.2.2",
"homepage": "https://github.com/jonschlinkert/kind-of",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"David Fox-Powell (https://dtothefp.github.io/me)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Ken Sheedlo (kensheedlo.com)",
"laggingreflex (https://github.com/laggingreflex)",
"Miguel Mota (https://miguelmota.com)",
"Peter deHaan (http://about.me/peterdehaan)"
],
"repository": "jonschlinkert/kind-of",
"bugs": {
"url": "https://github.com/jonschlinkert/kind-of/issues"
},
"license": "MIT",
"files": [
"index.js"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha",
"prepublish": "browserify -o browser.js -e index.js -s index --bare"
},
"dependencies": {
"is-buffer": "^1.1.5"
},
"devDependencies": {
"ansi-bold": "^0.1.1",
"benchmarked": "^1.0.0",
"browserify": "^14.3.0",
"glob": "^7.1.1",
"gulp-format-md": "^0.1.12",
"mocha": "^3.3.0",
"type-of": "^2.0.1",
"typeof": "^1.0.0"
},
"keywords": [
"arguments",
"array",
"boolean",
"check",
"date",
"function",
"is",
"is-type",
"is-type-of",
"kind",
"kind-of",
"number",
"object",
"of",
"regexp",
"string",
"test",
"type",
"type-of",
"typeof",
"types"
],
"verb": {
"related": {
"list": [
"is-glob",
"is-number",
"is-primitive"
]
},
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"reflinks": [
"verb"
]
}
}

View file

@ -0,0 +1,83 @@
{
"name": "is-number",
"description": "Returns true if the value is a number. comprehensive tests.",
"version": "3.0.0",
"homepage": "https://github.com/jonschlinkert/is-number",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"Charlike Mike Reagent (http://www.tunnckocore.tk)",
"Jon Schlinkert <jon.schlinkert@sellside.com> (http://twitter.com/jonschlinkert)"
],
"repository": "jonschlinkert/is-number",
"bugs": {
"url": "https://github.com/jonschlinkert/is-number/issues"
},
"license": "MIT",
"files": [
"index.js"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"kind-of": "^3.0.2"
},
"devDependencies": {
"benchmarked": "^0.2.5",
"chalk": "^1.1.3",
"gulp-format-md": "^0.1.10",
"mocha": "^3.0.2"
},
"keywords": [
"check",
"coerce",
"coercion",
"integer",
"is",
"is-nan",
"is-num",
"is-number",
"istype",
"kind",
"math",
"nan",
"num",
"number",
"numeric",
"test",
"type",
"typeof",
"value"
],
"verb": {
"related": {
"list": [
"even",
"is-even",
"is-odd",
"is-primitive",
"kind-of",
"odd"
]
},
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"reflinks": [
"verb",
"verb-generate-readme"
]
}
}

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,122 @@
# isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM monthly downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![NPM total downloads](https://img.shields.io/npm/dt/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/isobject)
> Returns true if the value is an object and not an array or null.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save isobject
```
Install with [yarn](https://yarnpkg.com):
```sh
$ yarn add isobject
```
Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install isobject
```
Install with [bower](https://bower.io/)
```sh
$ bower install isobject
```
## Usage
```js
var isObject = require('isobject');
```
**True**
All of the following return `true`:
```js
isObject({});
isObject(Object.create({}));
isObject(Object.create(Object.prototype));
isObject(Object.create(null));
isObject({});
isObject(new Foo);
isObject(/foo/);
```
**False**
All of the following return `false`:
```js
isObject();
isObject(function () {});
isObject(1);
isObject([]);
isObject(undefined);
isObject(null);
```
## About
### Related projects
* [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.")
* [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.")
* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.")
* [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 29 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) |
| 1 | [magnudae](https://github.com/magnudae) |
| 1 | [LeSuisse](https://github.com/LeSuisse) |
| 1 | [tmcw](https://github.com/tmcw) |
### Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 30, 2017._

View file

@ -0,0 +1,5 @@
export = isObject;
declare function isObject(val: any): boolean;
declare namespace isObject {}

View file

@ -0,0 +1,12 @@
/*!
* isobject <https://github.com/jonschlinkert/isobject>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
module.exports = function isObject(val) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
};

View file

@ -0,0 +1,74 @@
{
"name": "isobject",
"description": "Returns true if the value is an object and not an array or null.",
"version": "3.0.1",
"homepage": "https://github.com/jonschlinkert/isobject",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"(https://github.com/LeSuisse)",
"Brian Woodward (https://twitter.com/doowb)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Magnús Dæhlen (https://github.com/magnudae)",
"Tom MacWright (https://macwright.org)"
],
"repository": "jonschlinkert/isobject",
"bugs": {
"url": "https://github.com/jonschlinkert/isobject/issues"
},
"license": "MIT",
"files": [
"index.d.ts",
"index.js"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"dependencies": {},
"devDependencies": {
"gulp-format-md": "^0.1.9",
"mocha": "^2.4.5"
},
"keywords": [
"check",
"is",
"is-object",
"isobject",
"kind",
"kind-of",
"kindof",
"native",
"object",
"type",
"typeof",
"value"
],
"types": "index.d.ts",
"verb": {
"related": {
"list": [
"extend-shallow",
"is-plain-object",
"kind-of",
"merge-deep"
]
},
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"reflinks": [
"verb"
]
}
}

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,342 @@
# kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of)
> Get the native type of a value.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save kind-of
```
Install with [bower](https://bower.io/)
```sh
$ bower install kind-of --save
```
## Why use this?
1. [it's fast](#benchmarks) | [optimizations](#optimizations)
2. [better type checking](#better-type-checking)
## Usage
> es5, browser and es6 ready
```js
var kindOf = require('kind-of');
kindOf(undefined);
//=> 'undefined'
kindOf(null);
//=> 'null'
kindOf(true);
//=> 'boolean'
kindOf(false);
//=> 'boolean'
kindOf(new Boolean(true));
//=> 'boolean'
kindOf(new Buffer(''));
//=> 'buffer'
kindOf(42);
//=> 'number'
kindOf(new Number(42));
//=> 'number'
kindOf('str');
//=> 'string'
kindOf(new String('str'));
//=> 'string'
kindOf(arguments);
//=> 'arguments'
kindOf({});
//=> 'object'
kindOf(Object.create(null));
//=> 'object'
kindOf(new Test());
//=> 'object'
kindOf(new Date());
//=> 'date'
kindOf([]);
//=> 'array'
kindOf([1, 2, 3]);
//=> 'array'
kindOf(new Array());
//=> 'array'
kindOf(/foo/);
//=> 'regexp'
kindOf(new RegExp('foo'));
//=> 'regexp'
kindOf(function () {});
//=> 'function'
kindOf(function * () {});
//=> 'function'
kindOf(new Function());
//=> 'function'
kindOf(new Map());
//=> 'map'
kindOf(new WeakMap());
//=> 'weakmap'
kindOf(new Set());
//=> 'set'
kindOf(new WeakSet());
//=> 'weakset'
kindOf(Symbol('str'));
//=> 'symbol'
kindOf(new Int8Array());
//=> 'int8array'
kindOf(new Uint8Array());
//=> 'uint8array'
kindOf(new Uint8ClampedArray());
//=> 'uint8clampedarray'
kindOf(new Int16Array());
//=> 'int16array'
kindOf(new Uint16Array());
//=> 'uint16array'
kindOf(new Int32Array());
//=> 'int32array'
kindOf(new Uint32Array());
//=> 'uint32array'
kindOf(new Float32Array());
//=> 'float32array'
kindOf(new Float64Array());
//=> 'float64array'
```
## Release history
### v4.0.0
**Added**
* `promise` support
### v5.0.0
**Added**
* `Set Iterator` and `Map Iterator` support
**Fixed**
* Now returns `generatorfunction` for generator functions
## Benchmarks
Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of).
Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`.
```bash
#1: array
current x 23,329,397 ops/sec ±0.82% (94 runs sampled)
lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled)
lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled)
#2: boolean
current x 27,197,115 ops/sec ±0.85% (94 runs sampled)
lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled)
lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled)
#3: date
current x 20,190,117 ops/sec ±0.86% (92 runs sampled)
lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled)
lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled)
#4: function
current x 23,855,460 ops/sec ±0.60% (97 runs sampled)
lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled)
lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled)
#5: null
current x 27,061,047 ops/sec ±0.97% (96 runs sampled)
lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled)
lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled)
#6: number
current x 25,075,682 ops/sec ±0.53% (99 runs sampled)
lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled)
lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled)
#7: object
current x 3,348,980 ops/sec ±0.49% (99 runs sampled)
lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled)
lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled)
#8: regex
current x 21,284,827 ops/sec ±0.72% (96 runs sampled)
lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled)
lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled)
#9: string
current x 25,379,234 ops/sec ±0.58% (96 runs sampled)
lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled)
lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled)
#10: undef
current x 27,459,221 ops/sec ±1.01% (93 runs sampled)
lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled)
lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled)
```
## Optimizations
In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library:
1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot.
2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it.
3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'`
4. There is no reason to make the code in a microlib as terse as possible, just to win points for making it shorter. It's always better to favor performant code over terse code. You will always only be using a single `require()` statement to use the library anyway, regardless of how the code is written.
## Better type checking
kind-of is more correct than other type checking libs I've looked at. For example, here are some differing results from other popular libs:
### [typeof](https://github.com/CodingFu/typeof) lib
Incorrectly tests instances of custom constructors (pretty common):
```js
var typeOf = require('typeof');
function Test() {}
console.log(typeOf(new Test()));
//=> 'test'
```
Returns `object` instead of `arguments`:
```js
function foo() {
console.log(typeOf(arguments)) //=> 'object'
}
foo();
```
### [type-of](https://github.com/ForbesLindesay/type-of) lib
Incorrectly returns `object` for generator functions, buffers, `Map`, `Set`, `WeakMap` and `WeakSet`:
```js
function * foo() {}
console.log(typeOf(foo));
//=> 'object'
console.log(typeOf(new Buffer('')));
//=> 'object'
console.log(typeOf(new Map()));
//=> 'object'
console.log(typeOf(new Set()));
//=> 'object'
console.log(typeOf(new WeakMap()));
//=> 'object'
console.log(typeOf(new WeakSet()));
//=> 'object'
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
<details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
<details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
<details>
### Related projects
You might also be interested in these projects:
* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet")
* [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.")
* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 82 | [jonschlinkert](https://github.com/jonschlinkert) |
| 3 | [aretecode](https://github.com/aretecode) |
| 2 | [miguelmota](https://github.com/miguelmota) |
| 1 | [dtothefp](https://github.com/dtothefp) |
| 1 | [ksheedlo](https://github.com/ksheedlo) |
| 1 | [pdehaan](https://github.com/pdehaan) |
| 1 | [laggingreflex](https://github.com/laggingreflex) |
| 1 | [charlike](https://github.com/charlike) |
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on October 13, 2017._

View file

@ -0,0 +1,147 @@
var toString = Object.prototype.toString;
/**
* Get the native `typeof` a value.
*
* @param {*} `val`
* @return {*} Native javascript type
*/
module.exports = function kindOf(val) {
var type = typeof val;
// primitivies
if (type === 'undefined') {
return 'undefined';
}
if (val === null) {
return 'null';
}
if (val === true || val === false || val instanceof Boolean) {
return 'boolean';
}
if (type === 'string' || val instanceof String) {
return 'string';
}
if (type === 'number' || val instanceof Number) {
return 'number';
}
// functions
if (type === 'function' || val instanceof Function) {
if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') {
return 'generatorfunction';
}
return 'function';
}
// array
if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
return 'array';
}
// check for instances of RegExp and Date before calling `toString`
if (val instanceof RegExp) {
return 'regexp';
}
if (val instanceof Date) {
return 'date';
}
// other objects
type = toString.call(val);
if (type === '[object RegExp]') {
return 'regexp';
}
if (type === '[object Date]') {
return 'date';
}
if (type === '[object Arguments]') {
return 'arguments';
}
if (type === '[object Error]') {
return 'error';
}
if (type === '[object Promise]') {
return 'promise';
}
// buffer
if (isBuffer(val)) {
return 'buffer';
}
// es6: Map, WeakMap, Set, WeakSet
if (type === '[object Set]') {
return 'set';
}
if (type === '[object WeakSet]') {
return 'weakset';
}
if (type === '[object Map]') {
return 'map';
}
if (type === '[object WeakMap]') {
return 'weakmap';
}
if (type === '[object Symbol]') {
return 'symbol';
}
if (type === '[object Map Iterator]') {
return 'mapiterator';
}
if (type === '[object Set Iterator]') {
return 'setiterator';
}
if (type === '[object String Iterator]') {
return 'stringiterator';
}
if (type === '[object Array Iterator]') {
return 'arrayiterator';
}
// typed arrays
if (type === '[object Int8Array]') {
return 'int8array';
}
if (type === '[object Uint8Array]') {
return 'uint8array';
}
if (type === '[object Uint8ClampedArray]') {
return 'uint8clampedarray';
}
if (type === '[object Int16Array]') {
return 'int16array';
}
if (type === '[object Uint16Array]') {
return 'uint16array';
}
if (type === '[object Int32Array]') {
return 'int32array';
}
if (type === '[object Uint32Array]') {
return 'uint32array';
}
if (type === '[object Float32Array]') {
return 'float32array';
}
if (type === '[object Float64Array]') {
return 'float64array';
}
// must be a plain object
return 'object';
};
/**
* If you need to support Safari 5-7 (8-10 yr-old browser),
* take a look at https://github.com/feross/is-buffer
*/
function isBuffer(val) {
return val.constructor
&& typeof val.constructor.isBuffer === 'function'
&& val.constructor.isBuffer(val);
}

View file

@ -0,0 +1,91 @@
{
"name": "kind-of",
"description": "Get the native type of a value.",
"version": "5.1.0",
"homepage": "https://github.com/jonschlinkert/kind-of",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"David Fox-Powell (https://dtothefp.github.io/me)",
"James (https://twitter.com/aretecode)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Ken Sheedlo (kensheedlo.com)",
"laggingreflex (https://github.com/laggingreflex)",
"Miguel Mota (https://miguelmota.com)",
"Peter deHaan (http://about.me/peterdehaan)",
"tunnckoCore (https://i.am.charlike.online)"
],
"repository": "jonschlinkert/kind-of",
"bugs": {
"url": "https://github.com/jonschlinkert/kind-of/issues"
},
"license": "MIT",
"files": [
"index.js"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha",
"prepublish": "browserify -o browser.js -e index.js -s index --bare"
},
"devDependencies": {
"ansi-bold": "^0.1.1",
"benchmarked": "^1.1.1",
"browserify": "^14.4.0",
"gulp-format-md": "^0.1.12",
"matched": "^0.4.4",
"mocha": "^3.4.2",
"type-of": "^2.0.1",
"typeof": "^1.0.0"
},
"keywords": [
"arguments",
"array",
"boolean",
"check",
"date",
"function",
"is",
"is-type",
"is-type-of",
"kind",
"kind-of",
"number",
"object",
"of",
"regexp",
"string",
"test",
"type",
"type-of",
"typeof",
"types"
],
"verb": {
"related": {
"list": [
"is-glob",
"is-number",
"is-primitive"
]
},
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"reflinks": [
"type-of",
"typeof",
"verb"
]
}
}

View file

@ -0,0 +1,37 @@
## History
### key
Changelog entries are classified using the following labels _(from [keep-a-changelog][]_):
- `added`: for new features
- `changed`: for changes in existing functionality
- `deprecated`: for once-stable features removed in upcoming releases
- `removed`: for deprecated features removed in this release
- `fixed`: for any bug fixes
- `bumped`: updated dependencies, only minor or higher will be listed.
### [3.0.0] - 2017-04-11
TODO. There should be no breaking changes. Please report any regressions. I will [reformat these release notes](https://github.com/micromatch/micromatch/pull/76) and add them to the changelog as soon as I have a chance.
### [1.0.1] - 2016-12-12
**Added**
- Support for windows path edge cases where backslashes are used in brackets or other unusual combinations.
### [1.0.0] - 2016-12-12
Stable release.
### [0.1.0] - 2016-10-08
First release.
[Unreleased]: https://github.com/jonschlinkert/micromatch/compare/0.1.0...HEAD
[0.2.0]: https://github.com/jonschlinkert/micromatch/compare/0.1.0...0.2.0
[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,884 @@
'use strict';
/**
* Module dependencies
*/
var util = require('util');
var braces = require('braces');
var toRegex = require('to-regex');
var extend = require('extend-shallow');
/**
* Local dependencies
*/
var compilers = require('./lib/compilers');
var parsers = require('./lib/parsers');
var cache = require('./lib/cache');
var utils = require('./lib/utils');
var MAX_LENGTH = 1024 * 64;
/**
* The main function takes a list of strings and one or more
* glob patterns to use for matching.
*
* ```js
* var mm = require('micromatch');
* mm(list, patterns[, options]);
*
* console.log(mm(['a.js', 'a.txt'], ['*.js']));
* //=> [ 'a.js' ]
* ```
* @param {Array} `list` A list of strings to match
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Array} Returns an array of matches
* @summary false
* @api public
*/
function micromatch(list, patterns, options) {
patterns = utils.arrayify(patterns);
list = utils.arrayify(list);
var len = patterns.length;
if (list.length === 0 || len === 0) {
return [];
}
if (len === 1) {
return micromatch.match(list, patterns[0], options);
}
var omit = [];
var keep = [];
var idx = -1;
while (++idx < len) {
var pattern = patterns[idx];
if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options));
} else {
keep.push.apply(keep, micromatch.match(list, pattern, options));
}
}
var matches = utils.diff(keep, omit);
if (!options || options.nodupes !== false) {
return utils.unique(matches);
}
return matches;
}
/**
* Similar to the main function, but `pattern` must be a string.
*
* ```js
* var mm = require('micromatch');
* mm.match(list, pattern[, options]);
*
* console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
* //=> ['a.a', 'a.aa']
* ```
* @param {Array} `list` Array of strings to match
* @param {String} `pattern` Glob pattern to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Array} Returns an array of matches
* @api public
*/
micromatch.match = function(list, pattern, options) {
if (Array.isArray(pattern)) {
throw new TypeError('expected pattern to be a string');
}
var unixify = utils.unixify(options);
var isMatch = memoize('match', pattern, options, micromatch.matcher);
var matches = [];
list = utils.arrayify(list);
var len = list.length;
var idx = -1;
while (++idx < len) {
var ele = list[idx];
if (ele === pattern || isMatch(ele)) {
matches.push(utils.value(ele, unixify, options));
}
}
// if no options were passed, uniquify results and return
if (typeof options === 'undefined') {
return utils.unique(matches);
}
if (matches.length === 0) {
if (options.failglob === true) {
throw new Error('no matches found for "' + pattern + '"');
}
if (options.nonull === true || options.nullglob === true) {
return [options.unescape ? utils.unescape(pattern) : pattern];
}
}
// if `opts.ignore` was defined, diff ignored list
if (options.ignore) {
matches = micromatch.not(matches, options.ignore, options);
}
return options.nodupes !== false ? utils.unique(matches) : matches;
};
/**
* Returns true if the specified `string` matches the given glob `pattern`.
*
* ```js
* var mm = require('micromatch');
* mm.isMatch(string, pattern[, options]);
*
* console.log(mm.isMatch('a.a', '*.a'));
* //=> true
* console.log(mm.isMatch('a.b', '*.a'));
* //=> false
* ```
* @param {String} `string` String to match
* @param {String} `pattern` Glob pattern to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if the string matches the glob pattern.
* @api public
*/
micromatch.isMatch = function(str, pattern, options) {
if (typeof str !== 'string') {
throw new TypeError('expected a string: "' + util.inspect(str) + '"');
}
if (isEmptyString(str) || isEmptyString(pattern)) {
return false;
}
var equals = utils.equalsPattern(options);
if (equals(str)) {
return true;
}
var isMatch = memoize('isMatch', pattern, options, micromatch.matcher);
return isMatch(str);
};
/**
* Returns true if some of the strings in the given `list` match any of the
* given glob `patterns`.
*
* ```js
* var mm = require('micromatch');
* mm.some(list, patterns[, options]);
*
* console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
* // true
* console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
* // false
* ```
* @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
micromatch.some = function(list, patterns, options) {
if (typeof list === 'string') {
list = [list];
}
for (var i = 0; i < list.length; i++) {
if (micromatch(list[i], patterns, options).length === 1) {
return true;
}
}
return false;
};
/**
* Returns true if every string in the given `list` matches
* any of the given glob `patterns`.
*
* ```js
* var mm = require('micromatch');
* mm.every(list, patterns[, options]);
*
* console.log(mm.every('foo.js', ['foo.js']));
* // true
* console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
* // true
* console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
* // false
* console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
* // false
* ```
* @param {String|Array} `list` The string or array of strings to test.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
micromatch.every = function(list, patterns, options) {
if (typeof list === 'string') {
list = [list];
}
for (var i = 0; i < list.length; i++) {
if (micromatch(list[i], patterns, options).length !== 1) {
return false;
}
}
return true;
};
/**
* Returns true if **any** of the given glob `patterns`
* match the specified `string`.
*
* ```js
* var mm = require('micromatch');
* mm.any(string, patterns[, options]);
*
* console.log(mm.any('a.a', ['b.*', '*.a']));
* //=> true
* console.log(mm.any('a.a', 'b.*'));
* //=> false
* ```
* @param {String|Array} `str` The string to test.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
micromatch.any = function(str, patterns, options) {
if (typeof str !== 'string') {
throw new TypeError('expected a string: "' + util.inspect(str) + '"');
}
if (isEmptyString(str) || isEmptyString(patterns)) {
return false;
}
if (typeof patterns === 'string') {
patterns = [patterns];
}
for (var i = 0; i < patterns.length; i++) {
if (micromatch.isMatch(str, patterns[i], options)) {
return true;
}
}
return false;
};
/**
* Returns true if **all** of the given `patterns` match
* the specified string.
*
* ```js
* var mm = require('micromatch');
* mm.all(string, patterns[, options]);
*
* console.log(mm.all('foo.js', ['foo.js']));
* // true
*
* console.log(mm.all('foo.js', ['*.js', '!foo.js']));
* // false
*
* console.log(mm.all('foo.js', ['*.js', 'foo.js']));
* // true
*
* console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
* // true
* ```
* @param {String|Array} `str` The string to test.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
micromatch.all = function(str, patterns, options) {
if (typeof str !== 'string') {
throw new TypeError('expected a string: "' + util.inspect(str) + '"');
}
if (typeof patterns === 'string') {
patterns = [patterns];
}
for (var i = 0; i < patterns.length; i++) {
if (!micromatch.isMatch(str, patterns[i], options)) {
return false;
}
}
return true;
};
/**
* Returns a list of strings that _**do not match any**_ of the given `patterns`.
*
* ```js
* var mm = require('micromatch');
* mm.not(list, patterns[, options]);
*
* console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
* //=> ['b.b', 'c.c']
* ```
* @param {Array} `list` Array of strings to match.
* @param {String|Array} `patterns` One or more glob pattern to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Array} Returns an array of strings that **do not match** the given patterns.
* @api public
*/
micromatch.not = function(list, patterns, options) {
var opts = extend({}, options);
var ignore = opts.ignore;
delete opts.ignore;
var unixify = utils.unixify(opts);
list = utils.arrayify(list).map(unixify);
var matches = utils.diff(list, micromatch(list, patterns, opts));
if (ignore) {
matches = utils.diff(matches, micromatch(list, ignore));
}
return opts.nodupes !== false ? utils.unique(matches) : matches;
};
/**
* Returns true if the given `string` contains the given pattern. Similar
* to [.isMatch](#isMatch) but the pattern can match any part of the string.
*
* ```js
* var mm = require('micromatch');
* mm.contains(string, pattern[, options]);
*
* console.log(mm.contains('aa/bb/cc', '*b'));
* //=> true
* console.log(mm.contains('aa/bb/cc', '*d'));
* //=> false
* ```
* @param {String} `str` The string to match.
* @param {String|Array} `patterns` Glob pattern to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns true if the patter matches any part of `str`.
* @api public
*/
micromatch.contains = function(str, patterns, options) {
if (typeof str !== 'string') {
throw new TypeError('expected a string: "' + util.inspect(str) + '"');
}
if (typeof patterns === 'string') {
if (isEmptyString(str) || isEmptyString(patterns)) {
return false;
}
var equals = utils.equalsPattern(patterns, options);
if (equals(str)) {
return true;
}
var contains = utils.containsPattern(patterns, options);
if (contains(str)) {
return true;
}
}
var opts = extend({}, options, {contains: true});
return micromatch.any(str, patterns, opts);
};
/**
* Returns true if the given pattern and options should enable
* the `matchBase` option.
* @return {Boolean}
* @api private
*/
micromatch.matchBase = function(pattern, options) {
if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
return options.basename === true || options.matchBase === true;
};
/**
* Filter the keys of the given object with the given `glob` pattern
* and `options`. Does not attempt to match nested keys. If you need this feature,
* use [glob-object][] instead.
*
* ```js
* var mm = require('micromatch');
* mm.matchKeys(object, patterns[, options]);
*
* var obj = { aa: 'a', ab: 'b', ac: 'c' };
* console.log(mm.matchKeys(obj, '*b'));
* //=> { ab: 'b' }
* ```
* @param {Object} `object` The object with keys to filter.
* @param {String|Array} `patterns` One or more glob patterns to use for matching.
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Object} Returns an object with only keys that match the given patterns.
* @api public
*/
micromatch.matchKeys = function(obj, patterns, options) {
if (!utils.isObject(obj)) {
throw new TypeError('expected the first argument to be an object');
}
var keys = micromatch(Object.keys(obj), patterns, options);
return utils.pick(obj, keys);
};
/**
* Returns a memoized matcher function from the given glob `pattern` and `options`.
* The returned function takes a string to match as its only argument and returns
* true if the string is a match.
*
* ```js
* var mm = require('micromatch');
* mm.matcher(pattern[, options]);
*
* var isMatch = mm.matcher('*.!(*a)');
* console.log(isMatch('a.a'));
* //=> false
* console.log(isMatch('a.b'));
* //=> true
* ```
* @param {String} `pattern` Glob pattern
* @param {Object} `options` See available [options](#options) for changing how matches are performed.
* @return {Function} Returns a matcher function.
* @api public
*/
micromatch.matcher = function matcher(pattern, options) {
if (Array.isArray(pattern)) {
return compose(pattern, options, matcher);
}
// if pattern is a regex
if (pattern instanceof RegExp) {
return test(pattern);
}
// if pattern is invalid
if (!utils.isString(pattern)) {
throw new TypeError('expected pattern to be an array, string or regex');
}
// if pattern is a non-glob string
if (!utils.hasSpecialChars(pattern)) {
if (options && options.nocase === true) {
pattern = pattern.toLowerCase();
}
return utils.matchPath(pattern, options);
}
// if pattern is a glob string
var re = micromatch.makeRe(pattern, options);
// if `options.matchBase` or `options.basename` is defined
if (micromatch.matchBase(pattern, options)) {
return utils.matchBasename(re, options);
}
function test(regex) {
var equals = utils.equalsPattern(options);
var unixify = utils.unixify(options);
return function(str) {
if (equals(str)) {
return true;
}
if (regex.test(unixify(str))) {
return true;
}
return false;
};
}
var fn = test(re);
Object.defineProperty(fn, 'result', {
configurable: true,
enumerable: false,
value: re.result
});
return fn;
};
/**
* Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
*
* ```js
* var mm = require('micromatch');
* mm.capture(pattern, string[, options]);
*
* console.log(mm.capture('test/*.js', 'test/foo.js));
* //=> ['foo']
* console.log(mm.capture('test/*.js', 'foo/bar.css'));
* //=> null
* ```
* @param {String} `pattern` Glob pattern to use for matching.
* @param {String} `string` String to match
* @param {Object} `options` See available [options](#options) for changing how matches are performed
* @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
* @api public
*/
micromatch.capture = function(pattern, str, options) {
var re = micromatch.makeRe(pattern, extend({capture: true}, options));
var unixify = utils.unixify(options);
function match() {
return function(string) {
var match = re.exec(unixify(string));
if (!match) {
return null;
}
return match.slice(1);
};
}
var capture = memoize('capture', pattern, options, match);
return capture(str);
};
/**
* Create a regular expression from the given glob `pattern`.
*
* ```js
* var mm = require('micromatch');
* mm.makeRe(pattern[, options]);
*
* console.log(mm.makeRe('*.js'));
* //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
* ```
* @param {String} `pattern` A glob pattern to convert to regex.
* @param {Object} `options` See available [options](#options) for changing how matches are performed.
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
micromatch.makeRe = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected pattern to be a string');
}
if (pattern.length > MAX_LENGTH) {
throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
}
function makeRe() {
var result = micromatch.create(pattern, options);
var asts = [];
var output = result.map(function(obj) {
obj.ast.state = obj.state;
asts.push(obj.ast);
return obj.output;
});
var regex = toRegex(output.join('|'), options);
Object.defineProperty(regex, 'result', {
configurable: true,
enumerable: false,
value: asts
});
return regex;
}
return memoize('makeRe', pattern, options, makeRe);
};
/**
* Expand the given brace `pattern`.
*
* ```js
* var mm = require('micromatch');
* console.log(mm.braces('foo/{a,b}/bar'));
* //=> ['foo/(a|b)/bar']
*
* console.log(mm.braces('foo/{a,b}/bar', {expand: true}));
* //=> ['foo/(a|b)/bar']
* ```
* @param {String} `pattern` String with brace pattern to expand.
* @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
* @return {Array}
* @api public
*/
micromatch.braces = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
function expand() {
if (options && options.nobrace === true) return [pattern];
if (!/\{.*\}/.test(pattern)) return [pattern];
// if (/[!@*?+]\{/.test(pattern)) {
// options = utils.extend({}, options, {expand: true});
// }
return braces(pattern, options);
}
return memoize('braces', pattern, options, expand);
};
/**
* Proxy to the [micromatch.braces](#method), for parity with
* minimatch.
*/
micromatch.braceExpand = function(pattern, options) {
var opts = extend({}, options, {expand: true});
return micromatch.braces(pattern, opts);
};
/**
* Parses the given glob `pattern` and returns an array of abstract syntax
* trees (ASTs), with the compiled `output` and optional source `map` on
* each AST.
*
* ```js
* var mm = require('micromatch');
* mm.create(pattern[, options]);
*
* console.log(mm.create('abc/*.js'));
* // [{ options: { source: 'string', sourcemap: true },
* // state: {},
* // compilers:
* // { ... },
* // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
* // ast:
* // { type: 'root',
* // errors: [],
* // nodes:
* // [ ... ],
* // dot: false,
* // input: 'abc/*.js' },
* // parsingErrors: [],
* // map:
* // { version: 3,
* // sources: [ 'string' ],
* // names: [],
* // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
* // sourcesContent: [ 'abc/*.js' ] },
* // position: { line: 1, column: 28 },
* // content: {},
* // files: {},
* // idx: 6 }]
* ```
* @param {String} `pattern` Glob pattern to parse and compile.
* @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
* @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
* @api public
*/
micromatch.create = function(pattern, options) {
return memoize('create', pattern, options, function() {
function create(str, opts) {
return micromatch.compile(micromatch.parse(str, opts), opts);
}
pattern = micromatch.braces(pattern, options);
var len = pattern.length;
var idx = -1;
var res = [];
while (++idx < len) {
res.push(create(pattern[idx], options));
}
return res;
});
};
/**
* Parse the given `str` with the given `options`.
*
* ```js
* var mm = require('micromatch');
* mm.parse(pattern[, options]);
*
* var ast = mm.parse('a/{b,c}/d');
* console.log(ast);
* // { type: 'root',
* // errors: [],
* // input: 'a/{b,c}/d',
* // nodes:
* // [ { type: 'bos', val: '' },
* // { type: 'text', val: 'a/' },
* // { type: 'brace',
* // nodes:
* // [ { type: 'brace.open', val: '{' },
* // { type: 'text', val: 'b,c' },
* // { type: 'brace.close', val: '}' } ] },
* // { type: 'text', val: '/d' },
* // { type: 'eos', val: '' } ] }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an AST
* @api public
*/
micromatch.parse = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
function parse() {
var snapdragon = utils.instantiate(null, options);
parsers(snapdragon, options);
if (pattern.slice(0, 2) === './') {
pattern = pattern.slice(2);
}
pattern = utils.combineDuplicates(pattern, '\\*\\*\\/|\\/\\*\\*');
var ast = snapdragon.parse(pattern, options);
utils.define(ast, 'snapdragon', snapdragon);
ast.input = pattern;
return ast;
}
return memoize('parse', pattern, options, parse);
};
/**
* Compile the given `ast` or string with the given `options`.
*
* ```js
* var mm = require('micromatch');
* mm.compile(ast[, options]);
*
* var ast = mm.parse('a/{b,c}/d');
* console.log(mm.compile(ast));
* // { options: { source: 'string' },
* // state: {},
* // compilers:
* // { eos: [Function],
* // noop: [Function],
* // bos: [Function],
* // brace: [Function],
* // 'brace.open': [Function],
* // text: [Function],
* // 'brace.close': [Function] },
* // output: [ 'a/(b|c)/d' ],
* // ast:
* // { ... },
* // parsingErrors: [] }
* ```
* @param {Object|String} `ast`
* @param {Object} `options`
* @return {Object} Returns an object that has an `output` property with the compiled string.
* @api public
*/
micromatch.compile = function(ast, options) {
if (typeof ast === 'string') {
ast = micromatch.parse(ast, options);
}
return memoize('compile', ast.input, options, function() {
var snapdragon = utils.instantiate(ast, options);
compilers(snapdragon, options);
return snapdragon.compile(ast, options);
});
};
/**
* Clear the regex cache.
*
* ```js
* mm.clearCache();
* ```
* @api public
*/
micromatch.clearCache = function() {
micromatch.cache.caches = {};
};
/**
* Returns true if the given value is effectively an empty string
*/
function isEmptyString(val) {
return String(val) === '' || String(val) === './';
}
/**
* Compose a matcher function with the given patterns.
* This allows matcher functions to be compiled once and
* called multiple times.
*/
function compose(patterns, options, matcher) {
var matchers;
return memoize('compose', String(patterns), options, function() {
return function(file) {
// delay composition until it's invoked the first time,
// after that it won't be called again
if (!matchers) {
matchers = [];
for (var i = 0; i < patterns.length; i++) {
matchers.push(matcher(patterns[i], options));
}
}
var len = matchers.length;
while (len--) {
if (matchers[len](file) === true) {
return true;
}
}
return false;
};
});
}
/**
* Memoize a generated regex or function. A unique key is generated
* from the `type` (usually method name), the `pattern`, and
* user-defined options.
*/
function memoize(type, pattern, options, fn) {
var key = utils.createKey(type + '=' + pattern, options);
if (options && options.cache === false) {
return fn(pattern, options);
}
if (cache.has(type, key)) {
return cache.get(type, key);
}
var val = fn(pattern, options);
cache.set(type, key, val);
return val;
}
/**
* Expose compiler, parser and cache on `micromatch`
*/
micromatch.compilers = compilers;
micromatch.parsers = parsers;
micromatch.caches = cache.caches;
/**
* Expose `micromatch`
* @type {Function}
*/
module.exports = micromatch;

Binary file not shown.

View file

@ -0,0 +1 @@
module.exports = new (require('fragment-cache'))();

View file

@ -0,0 +1,77 @@
'use strict';
var nanomatch = require('nanomatch');
var extglob = require('extglob');
module.exports = function(snapdragon) {
var compilers = snapdragon.compiler.compilers;
var opts = snapdragon.options;
// register nanomatch compilers
snapdragon.use(nanomatch.compilers);
// get references to some specific nanomatch compilers before they
// are overridden by the extglob and/or custom compilers
var escape = compilers.escape;
var qmark = compilers.qmark;
var slash = compilers.slash;
var star = compilers.star;
var text = compilers.text;
var plus = compilers.plus;
var dot = compilers.dot;
// register extglob compilers or escape exglobs if disabled
if (opts.extglob === false || opts.noext === true) {
snapdragon.compiler.use(escapeExtglobs);
} else {
snapdragon.use(extglob.compilers);
}
snapdragon.use(function() {
this.options.star = this.options.star || function(/*node*/) {
return '[^/]*?';
};
});
// custom micromatch compilers
snapdragon.compiler
// reset referenced compiler
.set('dot', dot)
.set('escape', escape)
.set('plus', plus)
.set('slash', slash)
.set('qmark', qmark)
.set('star', star)
.set('text', text);
};
function escapeExtglobs(compiler) {
compiler.set('paren', function(node) {
var val = '';
visit(node, function(tok) {
if (tok.val) val += '\\' + tok.val;
});
return this.emit(val, node);
});
/**
* Visit `node` with the given `fn`
*/
function visit(node, fn) {
return node.nodes ? mapVisit(node.nodes, fn) : fn(node);
}
/**
* Map visit over array of `nodes`.
*/
function mapVisit(nodes, fn) {
var len = nodes.length;
var idx = -1;
while (++idx < len) {
visit(nodes[idx], fn);
}
}
}

View file

@ -0,0 +1,83 @@
'use strict';
var extglob = require('extglob');
var nanomatch = require('nanomatch');
var regexNot = require('regex-not');
var toRegex = require('to-regex');
var not;
/**
* Characters to use in negation regex (we want to "not" match
* characters that are matched by other parsers)
*/
var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+';
var createNotRegex = function(opts) {
return not || (not = textRegex(TEXT));
};
/**
* Parsers
*/
module.exports = function(snapdragon) {
var parsers = snapdragon.parser.parsers;
// register nanomatch parsers
snapdragon.use(nanomatch.parsers);
// get references to some specific nanomatch parsers before they
// are overridden by the extglob and/or parsers
var escape = parsers.escape;
var slash = parsers.slash;
var qmark = parsers.qmark;
var plus = parsers.plus;
var star = parsers.star;
var dot = parsers.dot;
// register extglob parsers
snapdragon.use(extglob.parsers);
// custom micromatch parsers
snapdragon.parser
.use(function() {
// override "notRegex" created in nanomatch parser
this.notRegex = /^\!+(?!\()/;
})
// reset the referenced parsers
.capture('escape', escape)
.capture('slash', slash)
.capture('qmark', qmark)
.capture('star', star)
.capture('plus', plus)
.capture('dot', dot)
/**
* Override `text` parser
*/
.capture('text', function() {
if (this.isInside('bracket')) return;
var pos = this.position();
var m = this.match(createNotRegex(this.options));
if (!m || !m[0]) return;
// escape regex boundary characters and simple brackets
var val = m[0].replace(/([[\]^$])/g, '\\$1');
return pos({
type: 'text',
val: val
});
});
};
/**
* Create text regex
*/
function textRegex(pattern) {
var notStr = regexNot.create(pattern, {contains: true, strictClose: false});
var prefix = '(?:[\\^]|\\\\|';
return toRegex(prefix + notStr + ')', {strictClose: false});
}

View file

@ -0,0 +1,312 @@
'use strict';
var utils = module.exports;
var path = require('path');
/**
* Module dependencies
*/
var Snapdragon = require('snapdragon');
utils.define = require('define-property');
utils.diff = require('arr-diff');
utils.extend = require('extend-shallow');
utils.pick = require('object.pick');
utils.typeOf = require('kind-of');
utils.unique = require('array-unique');
/**
* Returns true if the platform is windows, or `path.sep` is `\\`.
* This is defined as a function to allow `path.sep` to be set in unit tests,
* or by the user, if there is a reason to do so.
* @return {Boolean}
*/
utils.isWindows = function() {
return path.sep === '\\' || process.platform === 'win32';
};
/**
* Get the `Snapdragon` instance to use
*/
utils.instantiate = function(ast, options) {
var snapdragon;
// if an instance was created by `.parse`, use that instance
if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
snapdragon = ast.snapdragon;
// if the user supplies an instance on options, use that instance
} else if (utils.typeOf(options) === 'object' && options.snapdragon) {
snapdragon = options.snapdragon;
// create a new instance
} else {
snapdragon = new Snapdragon(options);
}
utils.define(snapdragon, 'parse', function(str, options) {
var parsed = Snapdragon.prototype.parse.apply(this, arguments);
parsed.input = str;
// escape unmatched brace/bracket/parens
var last = this.parser.stack.pop();
if (last && this.options.strictErrors !== true) {
var open = last.nodes[0];
var inner = last.nodes[1];
if (last.type === 'bracket') {
if (inner.val.charAt(0) === '[') {
inner.val = '\\' + inner.val;
}
} else {
open.val = '\\' + open.val;
var sibling = open.parent.nodes[1];
if (sibling.type === 'star') {
sibling.loose = true;
}
}
}
// add non-enumerable parser reference
utils.define(parsed, 'parser', this.parser);
return parsed;
});
return snapdragon;
};
/**
* Create the key to use for memoization. The key is generated
* by iterating over the options and concatenating key-value pairs
* to the pattern string.
*/
utils.createKey = function(pattern, options) {
if (utils.typeOf(options) !== 'object') {
return pattern;
}
var val = pattern;
var keys = Object.keys(options);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
val += ';' + key + '=' + String(options[key]);
}
return val;
};
/**
* Cast `val` to an array
* @return {Array}
*/
utils.arrayify = function(val) {
if (typeof val === 'string') return [val];
return val ? (Array.isArray(val) ? val : [val]) : [];
};
/**
* Return true if `val` is a non-empty string
*/
utils.isString = function(val) {
return typeof val === 'string';
};
/**
* Return true if `val` is a non-empty string
*/
utils.isObject = function(val) {
return utils.typeOf(val) === 'object';
};
/**
* Combines duplicate characters in the provided string.
* @param {String} `str`
* @returns {String}
*/
utils.combineDuplicates = function(str, val) {
var re = new RegExp('(' + val + ')(?=(?:' + val + ')*\\1)', 'g');
return str.replace(re, '');
};
/**
* Returns true if the given `str` has special characters
*/
utils.hasSpecialChars = function(str) {
return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str);
};
/**
* Normalize slashes in the given filepath.
*
* @param {String} `filepath`
* @return {String}
*/
utils.toPosixPath = function(str) {
return str.replace(/\\+/g, '/');
};
/**
* Strip backslashes before special characters in a string.
*
* @param {String} `str`
* @return {String}
*/
utils.unescape = function(str) {
return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
};
/**
* Strip the prefix from a filepath
* @param {String} `fp`
* @return {String}
*/
utils.stripPrefix = function(str) {
if (str.charAt(0) !== '.') {
return str;
}
var ch = str.charAt(1);
if (utils.isSlash(ch)) {
return str.slice(2);
}
return str;
};
/**
* Returns true if the given str is an escaped or
* unescaped path character
*/
utils.isSlash = function(str) {
return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
};
/**
* Returns a function that returns true if the given
* pattern matches or contains a `filepath`
*
* @param {String} `pattern`
* @return {Function}
*/
utils.matchPath = function(pattern, options) {
return (options && options.contains)
? utils.containsPattern(pattern, options)
: utils.equalsPattern(pattern, options);
};
/**
* Returns true if the given (original) filepath or unixified path are equal
* to the given pattern.
*/
utils._equals = function(filepath, unixPath, pattern) {
return pattern === filepath || pattern === unixPath;
};
/**
* Returns true if the given (original) filepath or unixified path contain
* the given pattern.
*/
utils._contains = function(filepath, unixPath, pattern) {
return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
};
/**
* Returns a function that returns true if the given
* pattern is the same as a given `filepath`
*
* @param {String} `pattern`
* @return {Function}
*/
utils.equalsPattern = function(pattern, options) {
var unixify = utils.unixify(options);
options = options || {};
return function fn(filepath) {
var equal = utils._equals(filepath, unixify(filepath), pattern);
if (equal === true || options.nocase !== true) {
return equal;
}
var lower = filepath.toLowerCase();
return utils._equals(lower, unixify(lower), pattern);
};
};
/**
* Returns a function that returns true if the given
* pattern contains a `filepath`
*
* @param {String} `pattern`
* @return {Function}
*/
utils.containsPattern = function(pattern, options) {
var unixify = utils.unixify(options);
options = options || {};
return function(filepath) {
var contains = utils._contains(filepath, unixify(filepath), pattern);
if (contains === true || options.nocase !== true) {
return contains;
}
var lower = filepath.toLowerCase();
return utils._contains(lower, unixify(lower), pattern);
};
};
/**
* Returns a function that returns true if the given
* regex matches the `filename` of a file path.
*
* @param {RegExp} `re` Matching regex
* @return {Function}
*/
utils.matchBasename = function(re) {
return function(filepath) {
return re.test(filepath) || re.test(path.basename(filepath));
};
};
/**
* Determines the filepath to return based on the provided options.
* @return {any}
*/
utils.value = function(str, unixify, options) {
if (options && options.unixify === false) {
return str;
}
return unixify(str);
};
/**
* Returns a function that normalizes slashes in a string to forward
* slashes, strips `./` from beginning of paths, and optionally unescapes
* special characters.
* @return {Function}
*/
utils.unixify = function(options) {
options = options || {};
return function(filepath) {
if (utils.isWindows() || options.unixify === true) {
filepath = utils.toPosixPath(filepath);
}
if (options.stripPrefix !== false) {
filepath = utils.stripPrefix(filepath);
}
if (options.unescape === true) {
filepath = utils.unescape(filepath);
}
return filepath;
};
};

View file

@ -0,0 +1,146 @@
{
"name": "micromatch",
"description": "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.",
"version": "3.1.0",
"homepage": "https://github.com/micromatch/micromatch",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"Amila Welihinda (amilajack.com)",
"Bogdan Chadkin (https://github.com/TrySound)",
"Brian Woodward (https://twitter.com/doowb)",
"Elan Shanker (https://github.com/es128)",
"Fabrício Matté (https://ultcombo.js.org)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Martin Kolárik (https://kolarik.sk)",
"Paul Miller (paulmillr.com)",
"Tom Byrer (https://github.com/tomByrer)",
"tunnckoCore (https://i.am.charlike.online)",
"Tyler Akins (http://rumkin.com)",
"(https://github.com/DianeLooney)"
],
"repository": "micromatch/micromatch",
"bugs": {
"url": "https://github.com/micromatch/micromatch/issues"
},
"license": "MIT",
"files": [
"index.js",
"lib"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"arr-diff": "^4.0.0",
"array-unique": "^0.3.2",
"braces": "^2.2.2",
"define-property": "^1.0.0",
"extend-shallow": "^2.0.1",
"extglob": "^2.0.2",
"fragment-cache": "^0.2.1",
"kind-of": "^5.0.2",
"nanomatch": "^1.2.1",
"object.pick": "^1.3.0",
"regex-not": "^1.0.0",
"snapdragon": "^0.8.1",
"to-regex": "^3.0.1"
},
"devDependencies": {
"bash-match": "^1.0.2",
"for-own": "^1.0.0",
"gulp": "^3.9.1",
"gulp-format-md": "^1.0.0",
"gulp-istanbul": "^1.1.2",
"gulp-mocha": "^3.0.1",
"gulp-unused": "^0.2.1",
"is-windows": "^1.0.1",
"minimatch": "^3.0.4",
"minimist": "^1.2.0",
"mocha": "^3.5.0",
"multimatch": "^2.1.0"
},
"keywords": [
"bash",
"expand",
"expansion",
"expression",
"file",
"files",
"filter",
"find",
"glob",
"globbing",
"globs",
"globstar",
"match",
"matcher",
"matches",
"matching",
"micromatch",
"minimatch",
"multimatch",
"path",
"pattern",
"patterns",
"regex",
"regexp",
"regular",
"shell",
"wildcard"
],
"lintDeps": {
"dependencies": {
"options": {
"lock": {
"snapdragon": "^0.8.1"
}
}
},
"devDependencies": {
"files": {
"options": {
"ignore": [
"benchmark/**"
]
}
}
}
},
"verb": {
"toc": "collapsible",
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"helpers": [
"./benchmark/helper.js"
],
"related": {
"list": [
"braces",
"expand-brackets",
"extglob",
"fill-range",
"nanomatch"
]
},
"lint": {
"reflinks": true
},
"reflinks": [
"expand-brackets",
"extglob",
"glob-object",
"minimatch",
"multimatch",
"snapdragon"
]
}
}

View file

@ -0,0 +1,460 @@
# Change Log
This project adheres to [Semantic Versioning](http://semver.org/).
## 5.1.18
* Fix TypeScript definitions for case of multiple PostCSS versions
in `node_modules` (by Chris Eppstein).
## 5.2.17
* Add `postcss-sass` suggestion to syntax error on `.sass` input.
## 5.2.16
* Better error on wrong argument in node constructor.
## 5.2.15
* Fix TypeScript definitions (by bumbleblym).
## 5.2.14
* Fix browser bundle building in webpack (by janschoenherr).
## 5.2.13
* Do not add comment to important raws.
* Fix JSDoc (by Dmitry Semigradsky).
## 5.2.12
* Fix typo in deprecation message (by Garet McKinley).
## 5.2.11
* Fix TypeScript definitions (by Jed Mao).
## 5.2.10
* Fix TypeScript definitions (by Jed Mao).
## 5.2.9
* Update TypeScript definitions (by Jed Mao).
## 5.2.8
* Fix error message (by Ben Briggs).
## 5.2.7
* Better error message on syntax object in plugins list.
## 5.2.6
* Fix `postcss.vendor` for values with spaces (by 刘祺).
## 5.2.5
* Better error message on unclosed string (by Ben Briggs).
## 5.2.4
* Improve terminal CSS syntax highlight (by Simon Lydell).
## 5.2.3
* Better color highlight in syntax error code frame.
* Fix color highlight support in old systems.
## 5.2.2
* Update `Processor#version`.
## 5.2.1
* Fix source map path for CSS without `from` option (by Michele Locati).
## 5.2 “Duke Vapula”
* Add syntax highlight to code frame in syntax error (by Andrey Popp).
* Use Babel code frame style and size in syntax error.
* Add `[` and `]` tokens to parse `[attr=;] {}` correctly.
* Add `ignoreErrors` options to tokenizer (by Andrey Popp).
* Fix error position on tab indent (by Simon Lydell).
## 5.1.2
* Suggests SCSS/Less parsers on parse errors depends on file extension.
## 5.1.1
* Fix TypeScript definitions (by Efremov Alexey).
## 5.1 “King and President Zagan”
* Add URI in source map support (by Mark Finger).
* Add `map.from` option (by Mark Finger).
* Add `<no source>` mappings for nodes without source (by Bogdan Chadkin).
* Add function value support to `map.prev` option (by Chris Montoro).
* Add declaration value type check in shortcut creating (by 刘祺).
* `Result#warn` now returns new created warning.
* Dont call plugin creator in `postcss.plugin` call.
* Add source maps to PostCSS ES5 build.
* Add JSDoc to PostCSS classes.
* Clean npm package from unnecessary docs.
## 5.0.21
* Fix support with input source mao with `utf8` encoding name.
## 5.0.20
* Fix between raw value parsing (by David Clark).
* Update TypeScript definitions (by Jed Mao).
* Clean fake node.source after `append(string)`.
## 5.0.19
* Fix indent-based syntaxes support.
## 5.0.18
* Parse new lines according W3C CSS syntax specification.
## 5.0.17
* Fix options argument in `Node#warn` (by Ben Briggs).
* Fix TypeScript definitions (by Jed Mao).
## 5.0.16
* Fix CSS syntax error position on unclosed quotes.
## 5.0.15
* Fix `Node#clone()` on `null` value somewhere in node.
## 5.0.14
* Allow to use PostCSS in webpack bundle without JSON loader.
## 5.0.13
* Fix `index` and `word` options in `Warning#toString` (by Bogdan Chadkin).
* Fix input source content loading in errors.
* Fix map options on using `LazyResult` as input CSS.
* 100% test coverage.
* Use Babel 6.
## 5.0.12
* Allow passing a previous map with no mappings (by Andreas Lind).
## 5.0.11
* Increase plugins performance by 1.5 times.
## 5.0.10
* Fix warning from nodes without source.
## 5.0.9
* Fix source map type detection (by @asan).
## 5.0.8
* Fixed a missed step in `5.0.7` that caused the module to be published as
ES6 code.
## 5.0.7
* PostCSS now requires that node 0.12 is installed via the engines property
in package.json (by Howard Zuo).
## 5.0.6
* Fix parsing nested at-rule without semicolon (by Matt Drake).
* Trim `Declaration#value` (by Bogdan Chadkin).
## 5.0.5
* Fix multi-tokens property parsing (by Matt Drake).
## 5.0.4
* Fix start position in `Root#source`.
* Fix source map annotation, when CSS uses `\r\n` (by Mohammad Younes).
## 5.0.3
* Fix `url()` parsing.
* Fix using `selectors` in `Rule` constructor.
* Add start source to `Root` node.
## 5.0.2
* Fix `remove(index)` to be compatible with 4.x plugin.
## 5.0.1
* Fix PostCSS 4.x plugins compatibility.
* Fix type definition loading (by Jed Mao).
## 5.0 “President Valac”
* Remove `safe` option. Move Safe Parser to separate project.
* `Node#toString` does not include `before` for root nodes.
* Remove plugin returning `Root` API.
* Remove Promise polyfill for node.js 0.10.
* Deprecate `eachInside`, `eachDecl`, `eachRule`, `eachAtRule` and `eachComment`
in favor of `walk`, `walkDecls`, `walkRules`, `walkAtRules` and `walkComments`
(by Jed Mao).
* Deprecate `Container#remove` and `Node#removeSelf`
in favor of `Container#removeChild` and `Node#remove` (by Ben Briggs).
* Deprecate `Node#replace` in favor of `replaceWith` (by Ben Briggs).
* Deprecate raw properties in favor of `Node#raws` object.
* Deprecate `Node#style` in favor of `raw`.
* Deprecate `CssSyntaxError#generated` in favor of `input`.
* Deprecate `Node#cleanStyles` in favor of `cleanRaws`.
* Deprecate `Root#prevMap` in favor of `Root.source.input.map`.
* Add `syntax`, `parser` and `stringifier` options for Custom Syntaxes.
* Add stringifier option to `Node#toString`.
* Add `Result#content` alias for non-CSS syntaxes.
* Add `plugin.process(css)` shortcut to every plugin function (by Ben Briggs).
* Add multiple nodes support to insert methods (by Jonathan Neal).
* Add `Node#warn` shortcut (by Ben Briggs).
* Add `word` and `index` options to errors and warnings (by David Clark).
* Add `line`, `column` properties to `Warning`.
* Use `supports-color` library to detect color support in error output.
* Add type definitions for TypeScript plugin developers (by Jed Mao).
* `Rule#selectors` setter detects separators.
* Add `postcss.stringify` method.
* Throw descriptive errors for incorrectly formatted plugins.
* Add docs to npm release.
* Fix `url()` parsing.
* Fix Windows support (by Jed Mao).
## 4.1.16
* Fix errors without stack trace.
## 4.1.15
* Allow asynchronous plugins to change processor plugins list (by Ben Briggs).
## 4.1.14
* Fix for plugins packs defined by `postcss.plugin`.
## 4.1.13
* Fix input inlined source maps with UTF-8 encoding.
## 4.1.12
* Update Promise polyfill.
## 4.1.11
* Fix error message on wrong plugin format.
## 4.1.10
* Fix Promise behavior on sync plugin errors.
* Automatically fill `plugin` field in `CssSyntaxError`.
* Fix warning message (by Ben Briggs).
## 4.1.9
* Speed up `node.clone()`.
## 4.1.8
* Accepts `Processor` instance in `postcss()` constructor too.
## 4.1.7
* Speed up `postcss.list` (by Bogdan Chadkin).
## 4.1.6
* Fix Promise behavior on parsing error.
## 4.1.5
* Parse at-words in declaration values.
## 4.1.4
* Fix Promise polyfill dependency (by Anton Yakushev and Matija Marohnić).
## 4.1.3
* Add Promise polyfill for node.js 0.10 and IE.
## 4.1.2
* List helpers can be accessed independently `var space = postcss.list.space`.
## 4.1.1
* Show deprecated message only once.
## 4.1 “Marquis Andras”
* Asynchronous plugin support.
* Add warnings from plugins and `Result#messages`.
* Add `postcss.plugin()` to create plugins with a standard API.
* Insert nodes by CSS string.
* Show version warning message on error from an outdated plugin.
* Send `Result` instance to plugins as the second argument.
* Add `CssSyntaxError#plugin`.
* Add `CssSyntaxError#showSourceCode()`.
* Add `postcss.list` and `postcss.vendor` aliases.
* Add `Processor#version`.
* Parse wrong closing bracket.
* Parse `!important` statement with spaces and comments inside (by Ben Briggs).
* Throw an error on declaration without `prop` or `value` (by Philip Peterson).
* Fix source map mappings position.
* Add indexed source map support.
* Always set `error.generated`.
* Clean all source map annotation comments.
## 4.0.6
* Remove `babel` from released package dependencies (by Andres Suarez).
## 4.0.5
* Fix error message on double colon in declaration.
## 4.0.4
* Fix indent detection in some rare cases.
## 4.0.3
* Faster API with 6to5 Loose mode.
* Fix indexed source maps support.
## 4.0.2
* Do not copy IE hacks to code style.
## 4.0.1
* Add `source.input` to `Root` too.
## 4.0 “Duke Flauros”
* Rename `Container#childs` to `nodes`.
* Rename `PostCSS#processors` to `plugins`.
* Add `Node#replaceValues()` method.
* Add `Node#moveTo()`, `moveBefore()` and `moveAfter()` methods.
* Add `Node#cloneBefore()` and `cloneAfter()` shortcuts.
* Add `Node#next()`, `prev()` and `root()` shortcuts.
* Add `Node#replaceWith()` method.
* Add `Node#error()` method.
* Add `Container#removeAll()` method.
* Add filter argument to `eachDecl()` and `eachAtRule()`.
* Add `Node#source.input` and move `source.file` or `source.id` to `input`.
* Change code indent, when node was moved.
* Better fix code style on `Rule`, `AtRule` and `Comment` nodes changes.
* Allow to create rules and at-rules by hash shortcut in append methods.
* Add class name to CSS syntax error output.
## 3.0.7
* Fix IE filter parsing with multiple commands.
* Safer way to consume PostCSS object as plugin (by Maxime Thirouin).
## 3.0.6
* Fix missing semicolon when comment comes after last declaration.
* Fix Safe Mode declaration parsing on unclosed blocks.
## 3.0.5
* Fix parser to support difficult cases with backslash escape and brackets.
* Add `CssSyntaxError#stack` (by Maxime Thirouin).
## 3.0.4
* Fix Safe Mode on unknown word before declaration.
## 3.0.3
* Increase tokenizer speed (by Roman Dvornov).
## 3.0.2
* Fix empty comment parsing.
* Fix `Root#normalize` in some inserts.
## 3.0.1
* Fix Rhino JS runtime support.
* Typo in deprecated warning (by Maxime Thirouin).
## 3.0 “Marquis Andrealphus”
* New parser, which become the fastest ever CSS parser written in JavaScript.
* Parser can now parse declarations and rules in one parent (like in `@page`)
and nested declarations for plugins like `postcss-nested`.
* Child nodes array is now in `childs` property, instead of `decls` and `rules`.
* `map.inline` and `map.sourcesContent` options are now `true` by default.
* Fix iterators (`each`, `insertAfter`) on children array changes.
* Use previous source map to show origin source of CSS syntax error.
* Use 6to5 ES6 compiler, instead of ES6 Transpiler.
* Use code style for manually added rules from existing rules.
* Use `from` option from previous source map `file` field.
* Set `to` value to `from` if `to` option is missing.
* Use better node source name when missing `from` option.
* Show a syntax error when `;` is missed between declarations.
* Allow to pass `PostCSS` instance or list of plugins to `use()` method.
* Allow to pass `Result` instance to `process()` method.
* Trim Unicode BOM on source maps parsing.
* Parse at-rules without spaces like `@import"file"`.
* Better previous `sourceMappingURL` annotation comment cleaning.
* Do not remove previous `sourceMappingURL` comment on `map.annotation: false`.
* Parse nameless at-rules in Safe Mode.
* Fix source map generation for nodes without source.
* Fix next child `before` if `Root` first child got removed.
## 2.2.6
* Fix map generation for nodes without source (by Josiah Savary).
## 2.2.5
* Fix source map with BOM marker support (by Mohammad Younes).
* Fix source map paths (by Mohammad Younes).
## 2.2.4
* Fix `prepend()` on empty `Root`.
## 2.2.3
* Allow to use object shortcut in `use()` with functions like `autoprefixer`.
## 2.2.2
* Add shortcut to set processors in `use()` via object with `.postcss` property.
## 2.2.1
* Send `opts` from `Processor#process(css, opts)` to processors.
## 2.2 “Marquis Cimeies”
* Use GNU style syntax error messages.
* Add `Node#replace` method.
* Add `CssSyntaxError#reason` property.
## 2.1.2
* Fix UTF-8 support in inline source map.
* Fix source map `sourcesContent` if there is no `from` and `to` options.
## 2.1.1
* Allow to miss `to` and `from` options for inline source maps.
* Add `Node#source.id` if file name is unknown.
* Better detect splitter between rules in CSS concatenation tools.
* Automatically clone node in insert methods.
## 2.1 “King Amdusias”
* Change Traceur ES6 compiler to ES6 Transpiler.
* Show broken CSS line in syntax error.
## 2.0 “King Belial”
* Project was rewritten from CoffeeScript to ES6.
* Add Safe Mode to works with live input or with hacks from legacy code.
* More safer parser to pass all hacks from Browserhacks.com.
* Use real properties instead of magic getter/setter for raw properties.
## 1.0 “Marquis Decarabia”
* Save previous source map for each node to support CSS concatenation
with multiple previous maps.
* Add `map.sourcesContent` option to add origin content to `sourcesContent`
inside map.
* Allow to set different place of output map in annotation comment.
* Allow to use arrays and `Root` in `Container#append` and same methods.
* Add `Root#prevMap` with information about previous map.
* Allow to use latest PostCSS from GitHub by npm.
* `Result` now is lazy and it will generate output CSS only if you use `css`
or `map` property.
* Use separated `map.prev` option to set previous map.
* Rename `inlineMap` option to `map.inline`.
* Rename `mapAnnotation` option to `map.annotation`.
* `Result#map` now return `SourceMapGenerator` object, instead of string.
* Run previous map autodetect only if input CSS contains annotation comment.
* Add `map: 'inline'` shortcut for `map: { inline: true }` option.
* `Node#source.file` now will contains absolute path.
* Clean `Declaration#between` style on node clone.
## 0.3.5
* Allow to use `Root` or `Result` as first argument in `process()`.
* Save parsed AST to `Result#root`.
## 0.3.4
* Better space symbol detect to read UTF-8 BOM correctly.
## 0.3.3
* Remove source map hacks by using new Mozillas `source-map` (by Simon Lydell).
## 0.3.2
* Add URI encoding support for inline source maps.
## 0.3.1
* Fix relative paths from previous source map.
* Safer space split in `Rule#selectors` (by Simon Lydell).
## 0.3 “Prince Seere”
* Add `Comment` node for comments between declarations or rules.
* Add source map annotation comment to output CSS.
* Allow to inline source map to annotation comment by data:uri.
* Fix source maps on Windows.
* Fix source maps for subdirectory (by Dmitry Nikitenko and Simon Lydell).
* Autodetect previous source map.
* Add `first` and `last` shortcuts to container nodes.
* Parse `!important` to separated property in `Declaration`.
* Allow to break iteration by returning `false`.
* Copy code style to new nodes.
* Add `eachInside` method to recursively iterate all nodes.
* Add `selectors` shortcut to get selectors array.
* Add `toResult` method to `Rule` to simplify work with several input files.
* Clean declarations `value`, rules `selector` and at-rules `params`
by storing spaces in `between` property.
## 0.2 “Duke Dantalion”
* Add source map support.
* Add shortcuts to create nodes.
* Method `process()` now returns object with `css` and `map` keys.
* Origin CSS file option was renamed from `file` to `from`.
* Rename `Node#remove()` method to `removeSelf()` to fix name conflict.
* Node source was moved to `source` property with origin file
and node end position.
* You can set own CSS generate function.
## 0.1 “Count Andromalius”
* Initial release.

View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>
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,379 @@
# PostCSS [![Travis Build Status][travis-img]][travis] [![AppVeyor Build Status][appveyor-img]][appveyor] [![Gitter][chat-img]][chat]
<img align="right" width="95" height="95"
title="Philosophers stone, logo of PostCSS"
src="http://postcss.github.io/postcss/logo.svg">
[appveyor-img]: https://img.shields.io/appveyor/ci/ai/postcss.svg?label=windows
[travis-img]: https://img.shields.io/travis/postcss/postcss.svg?label=unix
[chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg
[appveyor]: https://ci.appveyor.com/project/ai/postcss
[travis]: https://travis-ci.org/postcss/postcss
[chat]: https://gitter.im/postcss/postcss
PostCSS is a tool for transforming styles with JS plugins.
These plugins can lint your CSS, support variables and mixins,
transpile future CSS syntax, inline images, and more.
PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
and JetBrains. The [Autoprefixer] PostCSS plugin is one of the most popular
CSS processors.
Twitter account: [@postcss](https://twitter.com/postcss).
VK.com page: [postcss](https://vk.com/postcss).
Support / Discussion: [Gitter](https://gitter.im/postcss/postcss).
For PostCSS commercial support (consulting, improving the front-end culture
of your company, PostCSS plugins), contact [Evil Martians](https://evilmartians.com/?utm_source=postcss)
at <surrender@evilmartians.com>.
[Autoprefixer]: https://github.com/postcss/autoprefixer
<a href="https://evilmartians.com/?utm_source=postcss">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
## Plugins
Currently, PostCSS has more than 200 plugins. You can find all of the plugins
in the [plugins list] or in the [searchable catalog]. Below is a list
of our favorite plugins — the best demonstrations of what can be built
on top of PostCSS.
If you have any new ideas, [PostCSS plugin development] is really easy.
[searchable catalog]: http://postcss.parts
[plugins list]: https://github.com/postcss/postcss/blob/master/docs/plugins.md
### Solve Global CSS Problem
* [`postcss-use`] allows you to explicitly set PostCSS plugins within CSS
and execute them only for the current file.
* [`postcss-modules`] and [`react-css-modules`] automatically isolate
selectors within components.
* [`postcss-autoreset`] is an alternative to using a global reset
that is better for isolatable components.
* [`postcss-initial`] adds `all: initial` support, which resets
all inherited styles.
* [`cq-prolyfill`] adds container query support, allowing styles that respond
to the width of the parent.
### Use Future CSS, Today
* [`autoprefixer`] adds vendor prefixes, using data from Can I Use.
* [`postcss-cssnext`] allows you to use future CSS features today
(includes `autoprefixer`).
* [`postcss-image-set-polyfill`] emulates [`image-set`] function logic for all browsers
### Better CSS Readability
* [`precss`] contains plugins for Sass-like features, like variables, nesting,
and mixins.
* [`postcss-sorting`] sorts the content of rules and at-rules.
* [`postcss-utilities`] includes the most commonly used shortcuts and helpers.
* [`short`] adds and extends numerous shorthand properties.
### Images and Fonts
* [`postcss-assets`] inserts image dimensions and inlines files.
* [`postcss-sprites`] generates image sprites.
* [`font-magician`] generates all the `@font-face` rules needed in CSS.
* [`postcss-inline-svg`] allows you to inline SVG and customize its styles.
* [`postcss-write-svg`] allows you to write simple SVG directly in your CSS.
### Linters
* [`stylelint`] is a modular stylesheet linter.
* [`stylefmt`] is a tool that automatically formats CSS
according `stylelint` rules.
* [`doiuse`] lints CSS for browser support, using data from Can I Use.
* [`colorguard`] helps you maintain a consistent color palette.
### Other
* [`postcss-rtl`] combines both-directional (left-to-right and right-to-left) styles in one CSS file.
* [`cssnano`] is a modular CSS minifier.
* [`lost`] is a feature-rich `calc()` grid system.
* [`rtlcss`] mirrors styles for right-to-left locales.
[PostCSS plugin development]: https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md
[`postcss-inline-svg`]: https://github.com/TrySound/postcss-inline-svg
[`react-css-modules`]: https://github.com/gajus/react-css-modules
[`postcss-autoreset`]: https://github.com/maximkoretskiy/postcss-autoreset
[`postcss-write-svg`]: https://github.com/jonathantneal/postcss-write-svg
[`postcss-utilities`]: https://github.com/ismamz/postcss-utilities
[`postcss-initial`]: https://github.com/maximkoretskiy/postcss-initial
[`postcss-sprites`]: https://github.com/2createStudio/postcss-sprites
[`postcss-modules`]: https://github.com/outpunk/postcss-modules
[`postcss-sorting`]: https://github.com/hudochenkov/postcss-sorting
[`postcss-cssnext`]: http://cssnext.io
[`postcss-image-set-polyfill`]: https://github.com/SuperOl3g/postcss-image-set-polyfill
[`postcss-assets`]: https://github.com/assetsjs/postcss-assets
[`font-magician`]: https://github.com/jonathantneal/postcss-font-magician
[`autoprefixer`]: https://github.com/postcss/autoprefixer
[`cq-prolyfill`]: https://github.com/ausi/cq-prolyfill
[`postcss-rtl`]: https://github.com/vkalinichev/postcss-rtl
[`postcss-use`]: https://github.com/postcss/postcss-use
[`css-modules`]: https://github.com/css-modules/css-modules
[`colorguard`]: https://github.com/SlexAxton/css-colorguard
[`stylelint`]: https://github.com/stylelint/stylelint
[`stylefmt`]: https://github.com/morishitter/stylefmt
[`cssnano`]: http://cssnano.co
[`precss`]: https://github.com/jonathantneal/precss
[`doiuse`]: https://github.com/anandthakker/doiuse
[`rtlcss`]: https://github.com/MohammadYounes/rtlcss
[`short`]: https://github.com/jonathantneal/postcss-short
[`lost`]: https://github.com/peterramsing/lost
[`image-set`]: https://drafts.csswg.org/css-images-3/#image-set-notation
## Syntaxes
PostCSS can transform styles in any syntax, not just CSS.
If there is not yet support for your favorite syntax,
you can write a parser and/or stringifier to extend PostCSS.
* [`sugarss`] is a indent-based syntax like Sass or Stylus.
* [`postcss-scss`] allows you to work with SCSS
*(but does not compile SCSS to CSS)*.
* [`postcss-sass`] allows you to work with Sass
*(but does not compile Sass to CSS)*.
* [`postcss-less`] allows you to work with Less
*(but does not compile LESS to CSS)*.
* [`postcss-less-engine`] allows you to work with Less
*(and DOES compile LESS to CSS using true Less.js evaluation)*.
* [`postcss-js`] allows you to write styles in JS or transform
React Inline Styles, Radium or JSS.
* [`postcss-safe-parser`] finds and fixes CSS syntax errors.
* [`midas`] converts a CSS string to highlighted HTML.
[`sugarss`]: https://github.com/postcss/sugarss
[`postcss-scss`]: https://github.com/postcss/postcss-scss
[`postcss-sass`]: https://github.com/AleshaOleg/postcss-sass
[`postcss-less`]: https://github.com/webschik/postcss-less
[`postcss-less-engine`]: https://github.com/Crunch/postcss-less
[`postcss-js`]: https://github.com/postcss/postcss-js
[`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser
[`midas`]: https://github.com/ben-eb/midas
## Articles
* [Some things you may think about PostCSS… and you might be wrong](http://julian.io/some-things-you-may-think-about-postcss-and-you-might-be-wrong)
* [What PostCSS Really Is; What It Really Does](http://davidtheclark.com/its-time-for-everyone-to-learn-about-postcss)
* [PostCSS Guides](http://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889)
More articles and videos you can find on [awesome-postcss](https://github.com/jjaderg/awesome-postcss) list.
## Books
* [Mastering PostCSS for Web Design](https://www.packtpub.com/web-development/mastering-postcss-web-design) by Alex Libby, Packt. (June 2016)
## Usage
You can start using PostCSS in just two steps:
1. Find and add PostCSS extensions for your build tool.
2. [Select plugins] and add them to your PostCSS process.
[Select plugins]: http://postcss.parts
### Webpack
Use [`postcss-loader`] in `webpack.config.js`:
```js
module.exports = {
module: {
loaders: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 1,
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: 'inline',
}
}
]
}
]
}
}
```
Then create `postcss.config.js`:
```js
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
```
[`postcss-loader`]: https://github.com/postcss/postcss-loader
### Gulp
Use [`gulp-postcss`] and [`gulp-sourcemaps`].
```js
gulp.task('css', function () {
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
return gulp.src('src/**/*.css')
.pipe( sourcemaps.init() )
.pipe( postcss([ require('precss'), require('autoprefixer') ]) )
.pipe( sourcemaps.write('.') )
.pipe( gulp.dest('build/') );
});
```
[`gulp-sourcemaps`]: https://github.com/floridoo/gulp-sourcemaps
[`gulp-postcss`]: https://github.com/postcss/gulp-postcss
### npm run / CLI
To use PostCSS from your command-line interface or with npm scripts
there is [`postcss-cli`].
```sh
postcss --use autoprefixer -c options.json -o main.css css/*.css
```
[`postcss-cli`]: https://github.com/postcss/postcss-cli
### Browser
If you want to compile CSS string in browser (for instance, in live edit
tools like CodePen), just use [Browserify] or [webpack]. They will pack
PostCSS and plugins files into a single file.
To apply PostCSS plugins to React Inline Styles, JSS, Radium
and other [CSS-in-JS], you can use [`postcss-js`] and transforms style objects.
```js
var postcss = require('postcss-js');
var prefixer = postcss.sync([ require('autoprefixer') ]);
prefixer({ display: 'flex' }); //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }
```
[`postcss-js`]: https://github.com/postcss/postcss-js
[Browserify]: http://browserify.org/
[webpack]: https://webpack.github.io/
[CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js
### Runners
* **Grunt**: [`grunt-postcss`](https://github.com/nDmitry/grunt-postcss)
* **HTML**: [`posthtml-postcss`](https://github.com/posthtml/posthtml-postcss)
* **Stylus**: [`poststylus`](https://github.com/seaneking/poststylus)
* **Rollup**: [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss)
* **Brunch**: [`postcss-brunch`](https://github.com/brunch/postcss-brunch)
* **Broccoli**: [`broccoli-postcss`](https://github.com/jeffjewiss/broccoli-postcss)
* **Meteor**: [`postcss`](https://atmospherejs.com/juliancwirko/postcss)
* **ENB**: [`enb-postcss`](https://github.com/awinogradov/enb-postcss)
* **Fly**: [`fly-postcss`](https://github.com/postcss/fly-postcss)
* **Start**: [`start-postcss`](https://github.com/start-runner/postcss)
* **Connect/Express**: [`postcss-middleware`](https://github.com/jedmao/postcss-middleware)
### JS API
For other environments, you can use the JS API:
```js
const fs = require('fs');
const postcss = require('postcss');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
fs.readFile('src/app.css', (err, css) => {
postcss([precss, autoprefixer])
.process(css, { from: 'src/app.css', to: 'dest/app.css' })
.then(result => {
fs.writeFile('dest/app.css', result.css);
if ( result.map ) fs.writeFile('dest/app.css.map', result.map);
});
});
```
Read the [PostCSS API documentation] for more details about the JS API.
All PostCSS runners should pass [PostCSS Runner Guidelines].
[PostCSS Runner Guidelines]: https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md
[PostCSS API documentation]: http://api.postcss.org/postcss.html
### Options
Most PostCSS runners accept two parameters:
* An array of plugins.
* An object of options.
Common options:
* `syntax`: an object providing a syntax parser and a stringifier.
* `parser`: a special syntax parser (for example, [SCSS]).
* `stringifier`: a special syntax output generator (for example, [Midas]).
* `map`: [source map options].
* `from`: the input file name (most runners set it automatically).
* `to`: the output file name (most runners set it automatically).
[source map options]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md
[Midas]: https://github.com/ben-eb/midas
[SCSS]: https://github.com/postcss/postcss-scss
### Node.js 0.10 and the Promise API
If you want to run PostCSS in Node.js 0.10, add the [Promise polyfill]:
```js
require('es6-promise').polyfill();
var postcss = require('postcss');
```
[Promise polyfill]: https://github.com/jakearchibald/es6-promise
## Editors & IDE Integration
### Atom
* [`language-postcss`] adds PostCSS and [SugarSS] highlight.
* [`source-preview-postcss`] previews your output CSS in a separate, live pane.
[SugarSS]: https://github.com/postcss/sugarss
### Sublime Text
* [`Syntax-highlighting-for-PostCSS`] adds PostCSS highlight.
[`Syntax-highlighting-for-PostCSS`]: https://github.com/hudochenkov/Syntax-highlighting-for-PostCSS
[`source-preview-postcss`]: https://atom.io/packages/source-preview-postcss
[`language-postcss`]: https://atom.io/packages/language-postcss
### Vim
* [`postcss.vim`] adds PostCSS highlight.
[`postcss.vim`]: https://github.com/stephenway/postcss.vim
### WebStorm
WebStorm 2016.3 [has] built-in PostCSS support.
[has]: https://blog.jetbrains.com/webstorm/2016/08/webstorm-2016-3-early-access-preview/

View file

@ -0,0 +1,195 @@
# PostCSS Plugin Guidelines
A PostCSS plugin is a function that receives and, usually,
transforms a CSS AST from the PostCSS parser.
The rules below are *mandatory* for all PostCSS plugins.
See also [ClojureWerkzs recommendations] for open source projects.
[ClojureWerkzs recommendations]: http://blog.clojurewerkz.org/blog/2013/04/20/how-to-make-your-open-source-project-really-awesome/
## 1. API
### 1.1 Clear name with `postcss-` prefix
The plugins purpose should be clear just by reading its name.
If you wrote a transpiler for CSS 4 Custom Media, `postcss-custom-media`
would be a good name. If you wrote a plugin to support mixins,
`postcss-mixins` would be a good name.
The prefix `postcss-` shows that the plugin is part of the PostCSS ecosystem.
This rule is not mandatory for plugins that can run as independent tools,
without the user necessarily knowing that it is powered by
PostCSS — for example, [cssnext] and [Autoprefixer].
[Autoprefixer]: https://github.com/postcss/autoprefixer
[cssnext]: http://cssnext.io/
### 1.2. Do one thing, and do it well
Do not create multitool plugins. Several small, one-purpose plugins bundled into
a plugin pack is usually a better solution.
For example, [cssnext] contains many small plugins,
one for each W3C specification. And [cssnano] contains a separate plugin
for each of its optimization.
[cssnext]: http://cssnext.io/
[cssnano]: https://github.com/ben-eb/cssnano
### 1.3. Do not use mixins
Preprocessors libraries like Compass provide an API with mixins.
PostCSS plugins are different.
A plugin cannot be just a set of mixins for [postcss-mixins].
To achieve your goal, consider transforming valid CSS
or using custom at-rules and custom properties.
[postcss-mixins]: https://github.com/postcss/postcss-mixins
### 1.4. Create plugin by `postcss.plugin`
By wrapping your function in this method,
you are hooking into a common plugin API:
```js
module.exports = postcss.plugin('plugin-name', function (opts) {
return function (root, result) {
// Plugin code
};
});
```
## 2. Processing
### 2.1. Plugin must be tested
A CI service like [Travis] is also recommended for testing code in
different environments. You should test in (at least) Node.js [active LTS](https://github.com/nodejs/LTS) and current stable version.
[Travis]: https://travis-ci.org/
### 2.2. Use asynchronous methods whenever possible
For example, use `fs.writeFile` instead of `fs.writeFileSync`:
```js
postcss.plugin('plugin-sprite', function (opts) {
return function (root, result) {
return new Promise(function (resolve, reject) {
var sprite = makeSprite();
fs.writeFile(opts.file, function (err) {
if ( err ) return reject(err);
resolve();
})
});
};
});
```
### 2.3. Set `node.source` for new nodes
Every node must have a relevant `source` so PostCSS can generate
an accurate source map.
So if you add new declaration based on some existing declaration, you should
clone the existing declaration in order to save that original `source`.
```js
if ( needPrefix(decl.prop) ) {
decl.cloneBefore({ prop: '-webkit-' + decl.prop });
}
```
You can also set `source` directly, copying from some existing node:
```js
if ( decl.prop === 'animation' ) {
var keyframe = createAnimationByName(decl.value);
keyframes.source = decl.source;
decl.root().append(keyframes);
}
```
### 2.4. Use only the public PostCSS API
PostCSS plugins must not rely on undocumented properties or methods,
which may be subject to change in any minor release. The public API
is described in [API docs].
[API docs]: http://api.postcss.org/
## 3. Errors
### 3.1. Use `node.error` on CSS relevant errors
If you have an error because of input CSS (like an unknown name
in a mixin plugin) you should use `node.error` to create an error
that includes source position:
```js
if ( typeof mixins[name] === 'undefined' ) {
throw decl.error('Unknown mixin ' + name, { plugin: 'postcss-mixins' });
}
```
### 3.2. Use `result.warn` for warnings
Do not print warnings with `console.log` or `console.warn`,
because some PostCSS runner may not allow console output.
```js
if ( outdated(decl.prop) ) {
result.warn(decl.prop + ' is outdated', { node: decl });
}
```
If CSS input is a source of the warning, the plugin must set the `node` option.
## 4. Documentation
### 4.1. Document your plugin in English
PostCSS plugins must have their `README.md` written in English. Do not be afraid
of your English skills, as the open source community will fix your errors.
Of course, you are welcome to write documentation in other languages;
just name them appropriately (e.g. `README.ja.md`).
### 4.2. Include input and output examples
The plugin's `README.md` must contain example input and output CSS.
A clear example is the best way to describe how your plugin works.
The first section of the `README.md` is a good place to put examples.
See [postcss-opacity](https://github.com/iamvdo/postcss-opacity) for an example.
Of course, this guideline does not apply if your plugin does not
transform the CSS.
### 4.3. Maintain a changelog
PostCSS plugins must describe the changes of all their releases
in a separate file, such as `CHANGELOG.md`, `History.md`, or [GitHub Releases].
Visit [Keep A Changelog] for more information about how to write one of these.
Of course, you should be using [SemVer].
[Keep A Changelog]: http://keepachangelog.com/
[GitHub Releases]: https://help.github.com/articles/creating-releases/
[SemVer]: http://semver.org/
### 4.4. Include `postcss-plugin` keyword in `package.json`
PostCSS plugins written for npm must have the `postcss-plugin` keyword
in their `package.json`. This special keyword will be useful for feedback about
the PostCSS ecosystem.
For packages not published to npm, this is not mandatory, but is recommended
if the package format can contain keywords.

View file

@ -0,0 +1,143 @@
# PostCSS Runner Guidelines
A PostCSS runner is a tool that processes CSS through a user-defined list
of plugins; for example, [`postcss-cli`] or [`gulppostcss`].
These rules are mandatory for any such runners.
For single-plugin tools, like [`gulp-autoprefixer`],
these rules are not mandatory but are highly recommended.
See also [ClojureWerkzs recommendations] for open source projects.
[ClojureWerkzs recommendations]: http://blog.clojurewerkz.org/blog/2013/04/20/how-to-make-your-open-source-project-really-awesome/
[`gulp-autoprefixer`]: https://github.com/sindresorhus/gulp-autoprefixer
[`gulppostcss`]: https://github.com/w0rm/gulp-postcss
[`postcss-cli`]: https://github.com/postcss/postcss-cli
## 1. API
### 1.1. Accept functions in plugin parameters
If your runner uses a config file, it must be written in JavaScript, so that
it can support plugins which accept a function, such as [`postcss-assets`]:
```js
module.exports = [
require('postcss-assets')({
cachebuster: function (file) {
return fs.statSync(file).mtime.getTime().toString(16);
}
})
];
```
[`postcss-assets`]: https://github.com/borodean/postcss-assets
## 2. Processing
### 2.1. Set `from` and `to` processing options
To ensure that PostCSS generates source maps and displays better syntax errors,
runners must specify the `from` and `to` options. If your runner does not handle
writing to disk (for example, a gulp transform), you should set both options
to point to the same file:
```js
processor.process({ from: file.path, to: file.path });
```
### 2.2. Use only the asynchronous API
PostCSS runners must use only the asynchronous API.
The synchronous API is provided only for debugging, is slower,
and cant work with asynchronous plugins.
```js
processor.process(opts).then(function (result) {
// processing is finished
});
```
### 2.3. Use only the public PostCSS API
PostCSS runners must not rely on undocumented properties or methods,
which may be subject to change in any minor release. The public API
is described in [API docs].
[API docs]: http://api.postcss.org/
## 3. Output
### 3.1. Dont show JS stack for `CssSyntaxError`
PostCSS runners must not show a stack trace for CSS syntax errors,
as the runner can be used by developers who are not familiar with JavaScript.
Instead, handle such errors gracefully:
```js
processor.process(opts).catch(function (error) {
if ( error.name === 'CssSyntaxError' ) {
process.stderr.write(error.message + error.showSourceCode());
} else {
throw error;
}
});
```
### 3.2. Display `result.warnings()`
PostCSS runners must output warnings from `result.warnings()`:
```js
result.warnings().forEach(function (warn) {
process.stderr.write(warn.toString());
});
```
See also [postcss-log-warnings] and [postcss-messages] plugins.
[postcss-log-warnings]: https://github.com/davidtheclark/postcss-log-warnings
[postcss-messages]: https://github.com/postcss/postcss-messages
### 3.3. Allow the user to write source maps to different files
PostCSS by default will inline source maps in the generated file; however,
PostCSS runners must provide an option to save the source map in a different
file:
```js
if ( result.map ) {
fs.writeFile(opts.to + '.map', result.map.toString());
}
```
## 4. Documentation
### 4.1. Document your runner in English
PostCSS runners must have their `README.md` written in English. Do not be afraid
of your English skills, as the open source community will fix your errors.
Of course, you are welcome to write documentation in other languages;
just name them appropriately (e.g. `README.ja.md`).
### 4.2. Maintain a changelog
PostCSS runners must describe changes of all releases in a separate file,
such as `ChangeLog.md`, `History.md`, or with [GitHub Releases].
Visit [Keep A Changelog] for more information on how to write one of these.
Of course you should use [SemVer].
[Keep A Changelog]: http://keepachangelog.com/
[GitHub Releases]: https://help.github.com/articles/creating-releases/
[SemVer]: http://semver.org/
### 4.3. `postcss-runner` keyword in `package.json`
PostCSS runners written for npm must have the `postcss-runner` keyword
in their `package.json`. This special keyword will be useful for feedback about
the PostCSS ecosystem.
For packages not published to npm, this is not mandatory, but recommended
if the package format is allowed to contain keywords.

View file

@ -0,0 +1,72 @@
# PostCSS and Source Maps
PostCSS has great [source maps] support. It can read and interpret maps
from previous transformation steps, autodetect the format that you expect,
and output both external and inline maps.
To ensure that you generate an accurate source map, you must indicate the input
and output CSS file paths — using the options `from` and `to`, respectively.
To generate a new source map with the default options, simply set `map: true`.
This will generate an inline source map that contains the source content.
If you dont want the map inlined, you can set `map.inline: false`.
```js
processor
.process(css, {
from: 'app.sass.css',
to: 'app.css',
map: { inline: false },
})
.then(function (result) {
result.map //=> '{ "version":3,
// "file":"app.css",
// "sources":["app.sass"],
// "mappings":"AAAA,KAAI" }'
});
```
If PostCSS finds source maps from a previous transformation,
it will automatically update that source map with the same options.
## Options
If you want more control over source map generation, you can define the `map`
option as an object with the following parameters:
* `inline` boolean: indicates that the source map should be embedded
in the output CSS as a Base64-encoded comment. By default, it is `true`.
But if all previous maps are external, not inline, PostCSS will not embed
the map even if you do not set this option.
If you have an inline source map, the `result.map` property will be empty,
as the source map will be contained within the text of `result.css`.
* `prev` string, object, boolean or function: source map content from
a previous processing step (for example, Sass compilation).
PostCSS will try to read the previous source map automatically
(based on comments within the source CSS), but you can use this option
to identify it manually. If desired, you can omit the previous map
with `prev: false`.
* `sourcesContent` boolean: indicates that PostCSS should set the origin
content (for example, Sass source) of the source map. By default,
it is `true`. But if all previous maps do not contain sources content,
PostCSS will also leave it out even if you do not set this option.
* `annotation` boolean or string: indicates that PostCSS should add annotation
comments to the CSS. By default, PostCSS will always add a comment with a path
to the source map. PostCSS will not add annotations to CSS files that
do not contain any comments.
By default, PostCSS presumes that you want to save the source map as
`opts.to + '.map'` and will use this path in the annotation comment.
A different path can be set by providing a string value for `annotation`.
If you have set `inline: true`, annotation cannot be disabled.
* `from` string: by default, PostCSS will set the `sources` property of the map
to the value of the `from` option. If you want to override this behaviour, you
can use `map.from` to explicitly set the source map's `sources` property.
[source maps]: http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/

View file

@ -0,0 +1,231 @@
# How to Write Custom Syntax
PostCSS can transform styles in any syntax, and is not limited to just CSS.
By writing a custom syntax, you can transform styles in any desired format.
Writing a custom syntax is much harder than writing a PostCSS plugin, but
it is an awesome adventure.
There are 3 types of PostCSS syntax packages:
* **Parser** to parse input string to nodes tree.
* **Stringifier** to generate output string by nodes tree.
* **Syntax** contains both parser and stringifier.
## Syntax
A good example of a custom syntax is [SCSS]. Some users may want to transform
SCSS sources with PostCSS plugins, for example if they need to add vendor
prefixes or change the property order. So this syntax should output SCSS from
an SCSS input.
The syntax API is a very simple plain object, with `parse` & `stringify`
functions:
```js
module.exports = {
parse: require('./parse'),
stringify: require('./stringify')
};
```
[SCSS]: https://github.com/postcss/postcss-scss
## Parser
A good example of a parser is [Safe Parser], which parses malformed/broken CSS.
Because there is no point to generate broken output, this package only provides
a parser.
The parser API is a function which receives a string & returns a [`Root`] node.
The second argument is a function which receives an object with PostCSS options.
```js
var postcss = require('postcss');
module.exports = function (css, opts) {
var root = postcss.root();
// Add other nodes to root
return root;
};
```
[Safe Parser]: https://github.com/postcss/postcss-safe-parser
[`Root`]: http://api.postcss.org/Root.html
### Main Theory
There are many books about parsers; but do not worry because CSS syntax is
very easy, and so the parser will be much simpler than a programming language
parser.
The default PostCSS parser contains two steps:
1. [Tokenizer] which reads input string character by character and builds a
tokens array. For example, it joins space symbols to a `['space', '\n ']`
token, and detects strings to a `['string', '"\"{"']` token.
2. [Parser] which reads the tokens array, creates node instances and
builds a tree.
[Tokenizer]: https://github.com/postcss/postcss/blob/master/lib/tokenize.es6
[Parser]: https://github.com/postcss/postcss/blob/master/lib/parser.es6
### Performance
Parsing input is often the most time consuming task in CSS processors. So it
is very important to have a fast parser.
The main rule of optimization is that there is no performance without a
benchmark. You can look at [PostCSS benchmarks] to build your own.
Of parsing tasks, the tokenize step will often take the most time, so its
performance should be prioritized. Unfortunately, classes, functions and
high level structures can slow down your tokenizer. Be ready to write dirty
code with repeated statements. This is why it is difficult to extend the
default [PostCSS tokenizer]; copy & paste will be a necessary evil.
Second optimization is using character codes instead of strings.
```js
// Slow
string[i] === '{';
// Fast
const OPEN_CURLY = 123; // `{'
string.charCodeAt(i) === OPEN_CURLY;
```
Third optimization is “fast jumps”. If you find open quotes, you can find
next closing quote much faster by `indexOf`:
```js
// Simple jump
next = string.indexOf('"', currentPosition + 1);
// Jump by RegExp
regexp.lastIndex = currentPosion + 1;
regexp.text(string);
next = regexp.lastIndex;
```
The parser can be a well written class. There is no need in copy-paste and
hardcore optimization there. You can extend the default [PostCSS parser].
[PostCSS benchmarks]: https://github.com/postcss/benchmark
[PostCSS tokenizer]: https://github.com/postcss/postcss/blob/master/lib/tokenize.es6
[PostCSS parser]: https://github.com/postcss/postcss/blob/master/lib/parser.es6
### Node Source
Every node should have `source` property to generate correct source map.
This property contains `start` and `end` properties with `{ line, column }`,
and `input` property with an [`Input`] instance.
Your tokenizer should save the original position so that you can propagate
the values to the parser, to ensure that the source map is correctly updated.
[`Input`]: https://github.com/postcss/postcss/blob/master/lib/input.es6
### Raw Values
A good PostCSS parser should provide all information (including spaces symbols)
to generate byte-to-byte equal output. It is not so difficult, but respectful
for user input and allow integration smoke tests.
A parser should save all additional symbols to `node.raws` object.
It is an open structure for you, you can add additional keys.
For example, [SCSS parser] saves comment types (`/* */` or `//`)
in `node.raws.inline`.
The default parser cleans CSS values from comments and spaces.
It saves the original value with comments to `node.raws.value.raw` and uses it,
if the node value was not changed.
[SCSS parser]: https://github.com/postcss/postcss-scss
### Tests
Of course, all parsers in the PostCSS ecosystem must have tests.
If your parser just extends CSS syntax (like [SCSS] or [Safe Parser]),
you can use the [PostCSS Parser Tests]. It contains unit & integration tests.
[PostCSS Parser Tests]: https://github.com/postcss/postcss-parser-tests
## Stringifier
A style guide generator is a good example of a stringifier. It generates output
HTML which contains CSS components. For this use case, a parser isn't necessary,
so the package should just contain a stringifier.
The Stringifier API is little bit more complicated, than the parser API.
PostCSS generates a source map, so a stringifier cant just return a string.
It must link every substring with its source node.
A Stringifier is a function which receives [`Root`] node and builder callback.
Then it calls builder with every nodes string and node instance.
```js
module.exports = function (root, builder) {
// Some magic
var string = decl.prop + ':' + decl.value + ';';
builder(string, decl);
// Some science
};
```
### Main Theory
PostCSS [default stringifier] is just a class with a method for each node type
and many methods to detect raw properties.
In most cases it will be enough just to extend this class,
like in [SCSS stringifier].
[default stringifier]: https://github.com/postcss/postcss/blob/master/lib/stringifier.es6
[SCSS stringifier]: https://github.com/postcss/postcss-scss/blob/master/lib/scss-stringifier.es6
### Builder Function
A builder function will be passed to `stringify` function as second argument.
For example, the default PostCSS stringifier class saves it
to `this.builder` property.
Builder receives output substring and source node to append this substring
to the final output.
Some nodes contain other nodes in the middle. For example, a rule has a `{`
at the beginning, many declarations inside and a closing `}`.
For these cases, you should pass a third argument to builder function:
`'start'` or `'end'` string:
```js
this.builder(rule.selector + '{', rule, 'start');
// Stringify declarations inside
this.builder('}', rule, 'end');
```
### Raw Values
A good PostCSS custom syntax saves all symbols and provide byte-to-byte equal
output if there were no changes.
This is why every node has `node.raws` object to store space symbol, etc.
Be careful, because sometimes these raw properties will not be present; some
nodes may be built manually, or may lose their indentation when they are moved
to another parent node.
This is why the default stringifier has a `raw()` method to autodetect raw
properties by other nodes. For example, it will look at other nodes to detect
indent size and them multiply it with the current node depth.
### Tests
A stringifier must have tests too.
You can use unit and integration test cases from [PostCSS Parser Tests].
Just compare input CSS with CSS after your parser and stringifier.
[PostCSS Parser Tests]: https://github.com/postcss/postcss-parser-tests

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,89 @@
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _warnOnce = require('./warn-once');
var _warnOnce2 = _interopRequireDefault(_warnOnce);
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
_inherits(Comment, _Node);
function Comment(defaults) {
_classCallCheck(this, Comment);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'comment';
return _this;
}
_createClass(Comment, [{
key: 'left',
get: function get() {
(0, _warnOnce2.default)('Comment#left was deprecated. Use Comment#raws.left');
return this.raws.left;
},
set: function set(val) {
(0, _warnOnce2.default)('Comment#left was deprecated. Use Comment#raws.left');
this.raws.left = val;
}
}, {
key: 'right',
get: function get() {
(0, _warnOnce2.default)('Comment#right was deprecated. Use Comment#raws.right');
return this.raws.right;
},
set: function set(val) {
(0, _warnOnce2.default)('Comment#right was deprecated. Use Comment#raws.right');
this.raws.right = val;
}
/**
* @memberof Comment#
* @member {string} text - the comments text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comments text.
* * `right`: the space symbols between the comments text.
*/
}]);
return Comment;
}(_node2.default);
exports.default = Comment;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvbW1lbnQuZXM2Il0sIm5hbWVzIjpbIkNvbW1lbnQiLCJkZWZhdWx0cyIsInR5cGUiLCJyYXdzIiwibGVmdCIsInZhbCIsInJpZ2h0Il0sIm1hcHBpbmdzIjoiOzs7Ozs7QUFBQTs7OztBQUNBOzs7Ozs7Ozs7Ozs7QUFFQTs7Ozs7Ozs7SUFRTUEsTzs7O0FBRUYscUJBQVlDLFFBQVosRUFBc0I7QUFBQTs7QUFBQSxxREFDbEIsaUJBQU1BLFFBQU4sQ0FEa0I7O0FBRWxCLGNBQUtDLElBQUwsR0FBWSxTQUFaO0FBRmtCO0FBR3JCOzs7OzRCQUVVO0FBQ1Asb0NBQVMsb0RBQVQ7QUFDQSxtQkFBTyxLQUFLQyxJQUFMLENBQVVDLElBQWpCO0FBQ0gsUzswQkFFUUMsRyxFQUFLO0FBQ1Ysb0NBQVMsb0RBQVQ7QUFDQSxpQkFBS0YsSUFBTCxDQUFVQyxJQUFWLEdBQWlCQyxHQUFqQjtBQUNIOzs7NEJBRVc7QUFDUixvQ0FBUyxzREFBVDtBQUNBLG1CQUFPLEtBQUtGLElBQUwsQ0FBVUcsS0FBakI7QUFDSCxTOzBCQUVTRCxHLEVBQUs7QUFDWCxvQ0FBUyxzREFBVDtBQUNBLGlCQUFLRixJQUFMLENBQVVHLEtBQVYsR0FBa0JELEdBQWxCO0FBQ0g7O0FBRUQ7Ozs7O0FBS0E7Ozs7Ozs7Ozs7Ozs7Ozs7OztrQkFjV0wsTyIsImZpbGUiOiJjb21tZW50LmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHdhcm5PbmNlIGZyb20gJy4vd2Fybi1vbmNlJztcbmltcG9ydCBOb2RlICAgICBmcm9tICcuL25vZGUnO1xuXG4vKipcbiAqIFJlcHJlc2VudHMgYSBjb21tZW50IGJldHdlZW4gZGVjbGFyYXRpb25zIG9yIHN0YXRlbWVudHMgKHJ1bGUgYW5kIGF0LXJ1bGVzKS5cbiAqXG4gKiBDb21tZW50cyBpbnNpZGUgc2VsZWN0b3JzLCBhdC1ydWxlIHBhcmFtZXRlcnMsIG9yIGRlY2xhcmF0aW9uIHZhbHVlc1xuICogd2lsbCBiZSBzdG9yZWQgaW4gdGhlIGByYXdzYCBwcm9wZXJ0aWVzIGV4cGxhaW5lZCBhYm92ZS5cbiAqXG4gKiBAZXh0ZW5kcyBOb2RlXG4gKi9cbmNsYXNzIENvbW1lbnQgZXh0ZW5kcyBOb2RlIHtcblxuICAgIGNvbnN0cnVjdG9yKGRlZmF1bHRzKSB7XG4gICAgICAgIHN1cGVyKGRlZmF1bHRzKTtcbiAgICAgICAgdGhpcy50eXBlID0gJ2NvbW1lbnQnO1xuICAgIH1cblxuICAgIGdldCBsZWZ0KCkge1xuICAgICAgICB3YXJuT25jZSgnQ29tbWVudCNsZWZ0IHdhcyBkZXByZWNhdGVkLiBVc2UgQ29tbWVudCNyYXdzLmxlZnQnKTtcbiAgICAgICAgcmV0dXJuIHRoaXMucmF3cy5sZWZ0O1xuICAgIH1cblxuICAgIHNldCBsZWZ0KHZhbCkge1xuICAgICAgICB3YXJuT25jZSgnQ29tbWVudCNsZWZ0IHdhcyBkZXByZWNhdGVkLiBVc2UgQ29tbWVudCNyYXdzLmxlZnQnKTtcbiAgICAgICAgdGhpcy5yYXdzLmxlZnQgPSB2YWw7XG4gICAgfVxuXG4gICAgZ2V0IHJpZ2h0KCkge1xuICAgICAgICB3YXJuT25jZSgnQ29tbWVudCNyaWdodCB3YXMgZGVwcmVjYXRlZC4gVXNlIENvbW1lbnQjcmF3cy5yaWdodCcpO1xuICAgICAgICByZXR1cm4gdGhpcy5yYXdzLnJpZ2h0O1xuICAgIH1cblxuICAgIHNldCByaWdodCh2YWwpIHtcbiAgICAgICAgd2Fybk9uY2UoJ0NvbW1lbnQjcmlnaHQgd2FzIGRlcHJlY2F0ZWQuIFVzZSBDb21tZW50I3Jhd3MucmlnaHQnKTtcbiAgICAgICAgdGhpcy5yYXdzLnJpZ2h0ID0gdmFsO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBtZW1iZXJvZiBDb21tZW50I1xuICAgICAqIEBtZW1iZXIge3N0cmluZ30gdGV4dCAtIHRoZSBjb21tZW504oCZcyB0ZXh0XG4gICAgICovXG5cbiAgICAvKipcbiAgICAgKiBAbWVtYmVyb2YgQ29tbWVudCNcbiAgICAgKiBAbWVtYmVyIHtvYmplY3R9IHJhd3MgLSBJbmZvcm1hdGlvbiB0byBnZW5lcmF0ZSBieXRlLXRvLWJ5dGUgZXF1YWxcbiAgICAgKiAgICAgICAgICAgICAgICAgICAgICAgICBub2RlIHN0cmluZyBhcyBpdCB3YXMgaW4gdGhlIG9yaWdpbiBpbnB1dC5cbiAgICAgKlxuICAgICAqIEV2ZXJ5IHBhcnNlciBzYXZlcyBpdHMgb3duIHByb3BlcnRpZXMsXG4gICAgICogYnV0IHRoZSBkZWZhdWx0IENTUyBwYXJzZXIgdXNlczpcbiAgICAgKlxuICAgICAqICogYGJlZm9yZWA6IHRoZSBzcGFjZSBzeW1ib2xzIGJlZm9yZSB0aGUgbm9kZS5cbiAgICAgKiAqIGBsZWZ0YDogdGhlIHNwYWNlIHN5bWJvbHMgYmV0d2VlbiBgLypgIGFuZCB0aGUgY29tbWVudOKAmXMgdGV4dC5cbiAgICAgKiAqIGByaWdodGA6IHRoZSBzcGFjZSBzeW1ib2xzIGJldHdlZW4gdGhlIGNvbW1lbnTigJlzIHRleHQuXG4gICAgICovXG59XG5cbmV4cG9ydCBkZWZhdWx0IENvbW1lbnQ7XG4iXX0=

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,43 @@
'use strict';
exports.__esModule = true;
exports.default = parse;
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new _input2.default(css, opts);
var parser = new _parser2.default(input);
try {
parser.tokenize();
parser.loop();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.sass/i.test(opts.from)) {
e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBhcnNlLmVzNiJdLCJuYW1lcyI6WyJwYXJzZSIsImNzcyIsIm9wdHMiLCJzYWZlIiwiRXJyb3IiLCJpbnB1dCIsInBhcnNlciIsInRva2VuaXplIiwibG9vcCIsImUiLCJuYW1lIiwiZnJvbSIsInRlc3QiLCJtZXNzYWdlIiwicm9vdCJdLCJtYXBwaW5ncyI6Ijs7O2tCQUd3QkEsSzs7QUFIeEI7Ozs7QUFDQTs7Ozs7O0FBRWUsU0FBU0EsS0FBVCxDQUFlQyxHQUFmLEVBQW9CQyxJQUFwQixFQUEwQjtBQUNyQyxRQUFLQSxRQUFRQSxLQUFLQyxJQUFsQixFQUF5QjtBQUNyQixjQUFNLElBQUlDLEtBQUosQ0FBVSw4QkFDQSw0Q0FEVixDQUFOO0FBRUg7O0FBRUQsUUFBSUMsUUFBUSxvQkFBVUosR0FBVixFQUFlQyxJQUFmLENBQVo7O0FBRUEsUUFBSUksU0FBUyxxQkFBV0QsS0FBWCxDQUFiO0FBQ0EsUUFBSTtBQUNBQyxlQUFPQyxRQUFQO0FBQ0FELGVBQU9FLElBQVA7QUFDSCxLQUhELENBR0UsT0FBT0MsQ0FBUCxFQUFVO0FBQ1IsWUFBS0EsRUFBRUMsSUFBRixLQUFXLGdCQUFYLElBQStCUixJQUEvQixJQUF1Q0EsS0FBS1MsSUFBakQsRUFBd0Q7QUFDcEQsZ0JBQUssV0FBV0MsSUFBWCxDQUFnQlYsS0FBS1MsSUFBckIsQ0FBTCxFQUFrQztBQUM5QkYsa0JBQUVJLE9BQUYsSUFBYSxvQ0FDQSwyQkFEQSxHQUVBLHdDQUZiO0FBR0gsYUFKRCxNQUlPLElBQUssVUFBVUQsSUFBVixDQUFlVixLQUFLUyxJQUFwQixDQUFMLEVBQWlDO0FBQ3BDRixrQkFBRUksT0FBRixJQUFhLG9DQUNBLDJCQURBLEdBRUEsd0NBRmI7QUFHSCxhQUpNLE1BSUEsSUFBSyxXQUFXRCxJQUFYLENBQWdCVixLQUFLUyxJQUFyQixDQUFMLEVBQWtDO0FBQ3JDRixrQkFBRUksT0FBRixJQUFhLG9DQUNBLDJCQURBLEdBRUEsd0NBRmI7QUFHSDtBQUNKO0FBQ0QsY0FBTUosQ0FBTjtBQUNIOztBQUVELFdBQU9ILE9BQU9RLElBQWQ7QUFDSCIsImZpbGUiOiJwYXJzZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBQYXJzZXIgZnJvbSAnLi9wYXJzZXInO1xuaW1wb3J0IElucHV0ICBmcm9tICcuL2lucHV0JztcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gcGFyc2UoY3NzLCBvcHRzKSB7XG4gICAgaWYgKCBvcHRzICYmIG9wdHMuc2FmZSApIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdPcHRpb24gc2FmZSB3YXMgcmVtb3ZlZC4gJyArXG4gICAgICAgICAgICAgICAgICAgICAgICAnVXNlIHBhcnNlcjogcmVxdWlyZShcInBvc3Rjc3Mtc2FmZS1wYXJzZXJcIiknKTtcbiAgICB9XG5cbiAgICBsZXQgaW5wdXQgPSBuZXcgSW5wdXQoY3NzLCBvcHRzKTtcblxuICAgIGxldCBwYXJzZXIgPSBuZXcgUGFyc2VyKGlucHV0KTtcbiAgICB0cnkge1xuICAgICAgICBwYXJzZXIudG9rZW5pemUoKTtcbiAgICAgICAgcGFyc2VyLmxvb3AoKTtcbiAgICB9IGNhdGNoIChlKSB7XG4gICAgICAgIGlmICggZS5uYW1lID09PSAnQ3NzU3ludGF4RXJyb3InICYmIG9wdHMgJiYgb3B0cy5mcm9tICkge1xuICAgICAgICAgICAgaWYgKCAvXFwuc2NzcyQvaS50ZXN0KG9wdHMuZnJvbSkgKSB7XG4gICAgICAgICAgICAgICAgZS5tZXNzYWdlICs9ICdcXG5Zb3UgdHJpZWQgdG8gcGFyc2UgU0NTUyB3aXRoICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndGhlIHN0YW5kYXJkIENTUyBwYXJzZXI7ICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHJ5IGFnYWluIHdpdGggdGhlIHBvc3Rjc3Mtc2NzcyBwYXJzZXInO1xuICAgICAgICAgICAgfSBlbHNlIGlmICggL1xcLnNhc3MvaS50ZXN0KG9wdHMuZnJvbSkgKSB7XG4gICAgICAgICAgICAgICAgZS5tZXNzYWdlICs9ICdcXG5Zb3UgdHJpZWQgdG8gcGFyc2UgU2FzcyB3aXRoICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndGhlIHN0YW5kYXJkIENTUyBwYXJzZXI7ICcgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHJ5IGFnYWluIHdpdGggdGhlIHBvc3Rjc3Mtc2FzcyBwYXJzZXInO1xuICAgICAgICAgICAgfSBlbHNlIGlmICggL1xcLmxlc3MkL2kudGVzdChvcHRzLmZyb20pICkge1xuICAgICAgICAgICAgICAgIGUubWVzc2FnZSArPSAnXFxuWW91IHRyaWVkIHRvIHBhcnNlIExlc3Mgd2l0aCAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ3RoZSBzdGFuZGFyZCBDU1MgcGFyc2VyOyAnICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJ3RyeSBhZ2FpbiB3aXRoIHRoZSBwb3N0Y3NzLWxlc3MgcGFyc2VyJztcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB0aHJvdyBlO1xuICAgIH1cblxuICAgIHJldHVybiBwYXJzZXIucm9vdDtcbn1cbiJdfQ==

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

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