diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +dist diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..32fbb9a --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "git.ignoreLimitWarning": true +} \ No newline at end of file diff --git a/README.md b/README.md index d2e2683..667c705 100644 --- a/README.md +++ b/README.md @@ -10,3 +10,4 @@ Run `npx http-server` and open `http://localhost:8080/` in your favorite browser - Translations powered by [i18next](https://www.i18next.com/overview/getting-started). - Notifications popups by [PNotify](https://sciactive.com/pnotify/). - Routing is done by [Page.js](https://visionmedia.github.io/page.js/). +- Awesomeness added by [jQuery](https://jquery.com/). diff --git a/build.cmd b/build.cmd new file mode 100644 index 0000000..9113b87 --- /dev/null +++ b/build.cmd @@ -0,0 +1,6 @@ +rem This bat file minifies all js and css and creates a dist folder with everything in it + +node node_modules\minifyfromhtml\minifyfromhtml.js --js=dist\myapp.js --css=dist\myapp.css < index.html + +copy /Y index.production.html dist\index.html +xcopy /F /Y /I templates dist\templates diff --git a/index.html b/index.html index 0cf25e0..61a56e7 100644 --- a/index.html +++ b/index.html @@ -11,6 +11,8 @@
+ + @@ -22,10 +24,7 @@ - + + diff --git a/index.production.html b/index.production.html new file mode 100644 index 0000000..a55305d --- /dev/null +++ b/index.production.html @@ -0,0 +1,14 @@ + + + + + + + + + +
+ + + + diff --git a/js/index.js b/js/index.js index 1ec58c0..70d447b 100644 --- a/js/index.js +++ b/js/index.js @@ -83,18 +83,22 @@ } } } - }); - - // render main shell - MyApp.renderShell() + }) .then(function() { - //setup routing - page('/', MyApp.renderHomePage); - page('/about', MyApp.renderAboutPage); - page('/text', MyApp.renderTextPage); + // language initialized - page({ - hashbang: true + // render main shell + MyApp.renderShell() + .then(function() { + //setup routing + page('/', MyApp.renderHomePage); + page('/about', MyApp.renderAboutPage); + page('/text', MyApp.renderTextPage); + + page({ + hashbang: true + }); }); }); + })(); diff --git a/js/language.js b/js/language.js index f0cf048..6691d57 100644 --- a/js/language.js +++ b/js/language.js @@ -1,4 +1,4 @@ -// this file is here so it can correctly handel the language pagameter +// this file is here so it can correctly handle the language parameter (function() { if (typeof(window.MyApp) === 'undefined') { diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 100644 index 0000000..558ebb9 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" + ret=$? +else + node "$basedir/../acorn/bin/acorn" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/acorn.cmd b/node_modules/.bin/acorn.cmd new file mode 100644 index 0000000..45c0c3d --- /dev/null +++ b/node_modules/.bin/acorn.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\acorn\bin\acorn" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\acorn\bin\acorn" %* +) \ No newline at end of file diff --git a/node_modules/.bin/css-b64-images b/node_modules/.bin/css-b64-images new file mode 100644 index 0000000..c721649 --- /dev/null +++ b/node_modules/.bin/css-b64-images @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../css-b64-images/bin/css-b64-images" "$@" + ret=$? +else + node "$basedir/../css-b64-images/bin/css-b64-images" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/css-b64-images.cmd b/node_modules/.bin/css-b64-images.cmd new file mode 100644 index 0000000..fbeae54 --- /dev/null +++ b/node_modules/.bin/css-b64-images.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\css-b64-images\bin\css-b64-images" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\css-b64-images\bin\css-b64-images" %* +) \ No newline at end of file diff --git a/node_modules/.bin/escodegen b/node_modules/.bin/escodegen new file mode 100644 index 0000000..4e46a48 --- /dev/null +++ b/node_modules/.bin/escodegen @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../escodegen/bin/escodegen.js" "$@" + ret=$? +else + node "$basedir/../escodegen/bin/escodegen.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/escodegen.cmd b/node_modules/.bin/escodegen.cmd new file mode 100644 index 0000000..8ffe393 --- /dev/null +++ b/node_modules/.bin/escodegen.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\escodegen\bin\escodegen.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\escodegen\bin\escodegen.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/esgenerate b/node_modules/.bin/esgenerate new file mode 100644 index 0000000..5d097c3 --- /dev/null +++ b/node_modules/.bin/esgenerate @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../escodegen/bin/esgenerate.js" "$@" + ret=$? +else + node "$basedir/../escodegen/bin/esgenerate.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/esgenerate.cmd b/node_modules/.bin/esgenerate.cmd new file mode 100644 index 0000000..39593ad --- /dev/null +++ b/node_modules/.bin/esgenerate.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\escodegen\bin\esgenerate.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\escodegen\bin\esgenerate.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/esparse b/node_modules/.bin/esparse new file mode 100644 index 0000000..2525527 --- /dev/null +++ b/node_modules/.bin/esparse @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../esprima/bin/esparse.js" "$@" + ret=$? +else + node "$basedir/../esprima/bin/esparse.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/esparse.cmd b/node_modules/.bin/esparse.cmd new file mode 100644 index 0000000..064f58e --- /dev/null +++ b/node_modules/.bin/esparse.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\esprima\bin\esparse.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\esprima\bin\esparse.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/esvalidate b/node_modules/.bin/esvalidate new file mode 100644 index 0000000..2137cd5 --- /dev/null +++ b/node_modules/.bin/esvalidate @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../esprima/bin/esvalidate.js" "$@" + ret=$? +else + node "$basedir/../esprima/bin/esvalidate.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/esvalidate.cmd b/node_modules/.bin/esvalidate.cmd new file mode 100644 index 0000000..8dfaec0 --- /dev/null +++ b/node_modules/.bin/esvalidate.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\esprima\bin\esvalidate.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\esprima\bin\esvalidate.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/he b/node_modules/.bin/he new file mode 100644 index 0000000..e3e6a0a --- /dev/null +++ b/node_modules/.bin/he @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../he/bin/he" "$@" + ret=$? +else + node "$basedir/../he/bin/he" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/he.cmd b/node_modules/.bin/he.cmd new file mode 100644 index 0000000..1630c8e --- /dev/null +++ b/node_modules/.bin/he.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\he\bin\he" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\he\bin\he" %* +) \ No newline at end of file diff --git a/node_modules/.bin/html-minifier b/node_modules/.bin/html-minifier new file mode 100644 index 0000000..e7e46d4 --- /dev/null +++ b/node_modules/.bin/html-minifier @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../html-minifier/cli.js" "$@" + ret=$? +else + node "$basedir/../html-minifier/cli.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/html-minifier.cmd b/node_modules/.bin/html-minifier.cmd new file mode 100644 index 0000000..491b26b --- /dev/null +++ b/node_modules/.bin/html-minifier.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\html-minifier\cli.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\html-minifier\cli.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/minify b/node_modules/.bin/minify new file mode 100644 index 0000000..52e00d8 --- /dev/null +++ b/node_modules/.bin/minify @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../minify/bin/minify.js" "$@" + ret=$? +else + node "$basedir/../minify/bin/minify.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/minify.cmd b/node_modules/.bin/minify.cmd new file mode 100644 index 0000000..a9d54f6 --- /dev/null +++ b/node_modules/.bin/minify.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\minify\bin\minify.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\minify\bin\minify.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/minifyfromhtml b/node_modules/.bin/minifyfromhtml new file mode 100644 index 0000000..89df4b0 --- /dev/null +++ b/node_modules/.bin/minifyfromhtml @@ -0,0 +1,2 @@ +"$basedir/../minifyfromhtml/minifyfromhtml.js" "$@" +exit $? diff --git a/node_modules/.bin/minifyfromhtml.cmd b/node_modules/.bin/minifyfromhtml.cmd new file mode 100644 index 0000000..d10aed7 --- /dev/null +++ b/node_modules/.bin/minifyfromhtml.cmd @@ -0,0 +1 @@ +@"%~dp0\..\minifyfromhtml\minifyfromhtml.js" %* diff --git a/node_modules/.bin/sshpk-conv b/node_modules/.bin/sshpk-conv new file mode 100644 index 0000000..c9c2987 --- /dev/null +++ b/node_modules/.bin/sshpk-conv @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sshpk/bin/sshpk-conv" "$@" + ret=$? +else + node "$basedir/../sshpk/bin/sshpk-conv" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/sshpk-conv.cmd b/node_modules/.bin/sshpk-conv.cmd new file mode 100644 index 0000000..dde70b0 --- /dev/null +++ b/node_modules/.bin/sshpk-conv.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-conv" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sshpk\bin\sshpk-conv" %* +) \ No newline at end of file diff --git a/node_modules/.bin/sshpk-sign b/node_modules/.bin/sshpk-sign new file mode 100644 index 0000000..1a92124 --- /dev/null +++ b/node_modules/.bin/sshpk-sign @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sshpk/bin/sshpk-sign" "$@" + ret=$? +else + node "$basedir/../sshpk/bin/sshpk-sign" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/sshpk-sign.cmd b/node_modules/.bin/sshpk-sign.cmd new file mode 100644 index 0000000..45025ec --- /dev/null +++ b/node_modules/.bin/sshpk-sign.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-sign" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sshpk\bin\sshpk-sign" %* +) \ No newline at end of file diff --git a/node_modules/.bin/sshpk-verify b/node_modules/.bin/sshpk-verify new file mode 100644 index 0000000..597a66b --- /dev/null +++ b/node_modules/.bin/sshpk-verify @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sshpk/bin/sshpk-verify" "$@" + ret=$? +else + node "$basedir/../sshpk/bin/sshpk-verify" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/sshpk-verify.cmd b/node_modules/.bin/sshpk-verify.cmd new file mode 100644 index 0000000..1b5fc0c --- /dev/null +++ b/node_modules/.bin/sshpk-verify.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-verify" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sshpk\bin\sshpk-verify" %* +) \ No newline at end of file diff --git a/node_modules/.bin/terser b/node_modules/.bin/terser new file mode 100644 index 0000000..a910452 --- /dev/null +++ b/node_modules/.bin/terser @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../terser/bin/uglifyjs" "$@" + ret=$? +else + node "$basedir/../terser/bin/uglifyjs" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/terser.cmd b/node_modules/.bin/terser.cmd new file mode 100644 index 0000000..31a4723 --- /dev/null +++ b/node_modules/.bin/terser.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\terser\bin\uglifyjs" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\terser\bin\uglifyjs" %* +) \ No newline at end of file diff --git a/node_modules/.bin/uglifyjs b/node_modules/.bin/uglifyjs new file mode 100644 index 0000000..de7b74f --- /dev/null +++ b/node_modules/.bin/uglifyjs @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@" + ret=$? +else + node "$basedir/../uglify-js/bin/uglifyjs" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/uglifyjs.cmd b/node_modules/.bin/uglifyjs.cmd new file mode 100644 index 0000000..3306013 --- /dev/null +++ b/node_modules/.bin/uglifyjs.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\uglify-js\bin\uglifyjs" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\uglify-js\bin\uglifyjs" %* +) \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 100644 index 0000000..f3bfcf4 --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../uuid/bin/uuid" "$@" + ret=$? +else + node "$basedir/../uuid/bin/uuid" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/uuid.cmd b/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..da52d68 --- /dev/null +++ b/node_modules/.bin/uuid.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\uuid\bin\uuid" %* +) \ No newline at end of file diff --git a/node_modules/@babel/runtime/package.json b/node_modules/@babel/runtime/package.json index 5c00988..af27cee 100644 --- a/node_modules/@babel/runtime/package.json +++ b/node_modules/@babel/runtime/package.json @@ -22,7 +22,7 @@ "_resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.4.3.tgz", "_shasum": "79888e452034223ad9609187a0ad1fe0d2ad4bdc", "_spec": "@babel/runtime@^7.3.1", - "_where": "/home/s2/tmp/vanillajs-seed/node_modules/i18next", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\i18next", "author": { "name": "Sebastian McKenzie", "email": "sebmck@gmail.com" diff --git a/node_modules/abab/CHANGELOG.md b/node_modules/abab/CHANGELOG.md new file mode 100644 index 0000000..4f5eb56 --- /dev/null +++ b/node_modules/abab/CHANGELOG.md @@ -0,0 +1,24 @@ +## 2.0.0 + +Modernization updates thanks to @TimothyGu: + +- Use jsdom's eslint config, remove jscs +- Move syntax to ES6 +- Remove Babel +- Via: https://github.com/jsdom/abab/pull/26 + +## 1.0.4 + +- Added license file + +## 1.0.3 + +- Replaced `let` with `var` in `lib/btoa.js` + - Follow up from `1.0.2` + - Resolves https://github.com/jsdom/abab/issues/18 + +## 1.0.2 + +- Replaced `const` with `var` in `index.js` + - Allows use of `abab` in the browser without a transpilation step + - Resolves https://github.com/jsdom/abab/issues/15 diff --git a/node_modules/abab/LICENSE.md b/node_modules/abab/LICENSE.md new file mode 100644 index 0000000..5b59a83 --- /dev/null +++ b/node_modules/abab/LICENSE.md @@ -0,0 +1,11 @@ +Both the original source code and new contributions in this repository are released under the [W3C 3-clause BSD license](https://github.com/w3c/web-platform-tests/blob/master/LICENSE.md#w3c-3-clause-bsd-license). + +# W3C 3-clause BSD License + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/abab/README.md b/node_modules/abab/README.md new file mode 100644 index 0000000..1bd8c45 --- /dev/null +++ b/node_modules/abab/README.md @@ -0,0 +1,50 @@ +# abab [![npm version](https://badge.fury.io/js/abab.svg)](https://www.npmjs.com/package/abab) [![Build Status](https://travis-ci.org/jsdom/abab.svg?branch=master)](https://travis-ci.org/jsdom/abab) + +A JavaScript module that implements `window.atob` and `window.btoa` according the forgiving-base64 algorithm in the [Infra Standard](https://infra.spec.whatwg.org/#forgiving-base64). The original code was forked from [w3c/web-platform-tests](https://github.com/w3c/web-platform-tests/blob/master/html/webappapis/atob/base64.html). + +Compatibility: Node.js version 3+ and all major browsers. + +Install with `npm`: + +```sh +npm install abab +``` + +## API + +### `btoa` (base64 encode) + +```js +const { btoa } = require('abab'); +btoa('Hello, world!'); // 'SGVsbG8sIHdvcmxkIQ==' +``` + +### `atob` (base64 decode) + +```js +const { atob } = require('abab'); +atob('SGVsbG8sIHdvcmxkIQ=='); // 'Hello, world!' +``` + +#### Valid characters + +[Per the spec](https://html.spec.whatwg.org/multipage/webappapis.html#atob:dom-windowbase64-btoa-3), `btoa` will accept strings "containing only characters in the range `U+0000` to `U+00FF`." If passed a string with characters above `U+00FF`, `btoa` will return `null`. If `atob` is passed a string that is not base64-valid, it will also return `null`. In both cases when `null` is returned, the spec calls for throwing a `DOMException` of type `InvalidCharacterError`. + +## Browsers + +If you want to include just one of the methods to save bytes in your client-side code, you can `require` the desired module directly. + +```js +const atob = require('abab/lib/atob'); +const btoa = require('abab/lib/btoa'); +``` + +----- + +### Checklists + +If you're **submitting a PR** or **deploying to npm**, please use the [checklists in CONTRIBUTING.md](https://github.com/jsdom/abab/blob/master/CONTRIBUTING.md#checklists) + +### Remembering `atob` vs. `btoa` + +Here's a mnemonic that might be useful: if you have a plain string and want to base64 encode it, then decode it, `btoa` is what you run before (**b**efore - **b**toa), and `atob` is what you run after (**a**fter - **a**tob). diff --git a/node_modules/abab/index.js b/node_modules/abab/index.js new file mode 100644 index 0000000..49d5ae9 --- /dev/null +++ b/node_modules/abab/index.js @@ -0,0 +1,9 @@ +"use strict"; + +const atob = require("./lib/atob"); +const btoa = require("./lib/btoa"); + +module.exports = { + atob, + btoa +}; diff --git a/node_modules/abab/lib/atob.js b/node_modules/abab/lib/atob.js new file mode 100644 index 0000000..3491898 --- /dev/null +++ b/node_modules/abab/lib/atob.js @@ -0,0 +1,107 @@ +"use strict"; + +/** + * Implementation of atob() according to the HTML and Infra specs, except that + * instead of throwing INVALID_CHARACTER_ERR we return null. + */ +function atob(data) { + // Web IDL requires DOMStrings to just be converted using ECMAScript + // ToString, which in our case amounts to using a template literal. + data = `${data}`; + // "Remove all ASCII whitespace from data." + data = data.replace(/[ \t\n\f\r]/g, ""); + // "If data's length divides by 4 leaving no remainder, then: if data ends + // with one or two U+003D (=) code points, then remove them from data." + if (data.length % 4 === 0) { + data = data.replace(/==?$/, ""); + } + // "If data's length divides by 4 leaving a remainder of 1, then return + // failure." + // + // "If data contains a code point that is not one of + // + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // + // then return failure." + if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) { + return null; + } + // "Let output be an empty byte sequence." + let output = ""; + // "Let buffer be an empty buffer that can have bits appended to it." + // + // We append bits via left-shift and or. accumulatedBits is used to track + // when we've gotten to 24 bits. + let buffer = 0; + let accumulatedBits = 0; + // "Let position be a position variable for data, initially pointing at the + // start of data." + // + // "While position does not point past the end of data:" + for (let i = 0; i < data.length; i++) { + // "Find the code point pointed to by position in the second column of + // Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in + // the first cell of the same row. + // + // "Append to buffer the six bits corresponding to n, most significant bit + // first." + // + // atobLookup() implements the table from RFC 4648. + buffer <<= 6; + buffer |= atobLookup(data[i]); + accumulatedBits += 6; + // "If buffer has accumulated 24 bits, interpret them as three 8-bit + // big-endian numbers. Append three bytes with values equal to those + // numbers to output, in the same order, and then empty buffer." + if (accumulatedBits === 24) { + output += String.fromCharCode((buffer & 0xff0000) >> 16); + output += String.fromCharCode((buffer & 0xff00) >> 8); + output += String.fromCharCode(buffer & 0xff); + buffer = accumulatedBits = 0; + } + // "Advance position by 1." + } + // "If buffer is not empty, it contains either 12 or 18 bits. If it contains + // 12 bits, then discard the last four and interpret the remaining eight as + // an 8-bit big-endian number. If it contains 18 bits, then discard the last + // two and interpret the remaining 16 as two 8-bit big-endian numbers. Append + // the one or two bytes with values equal to those one or two numbers to + // output, in the same order." + if (accumulatedBits === 12) { + buffer >>= 4; + output += String.fromCharCode(buffer); + } else if (accumulatedBits === 18) { + buffer >>= 2; + output += String.fromCharCode((buffer & 0xff00) >> 8); + output += String.fromCharCode(buffer & 0xff); + } + // "Return output." + return output; +} +/** + * A lookup table for atob(), which converts an ASCII character to the + * corresponding six-bit number. + */ +function atobLookup(chr) { + if (/[A-Z]/.test(chr)) { + return chr.charCodeAt(0) - "A".charCodeAt(0); + } + if (/[a-z]/.test(chr)) { + return chr.charCodeAt(0) - "a".charCodeAt(0) + 26; + } + if (/[0-9]/.test(chr)) { + return chr.charCodeAt(0) - "0".charCodeAt(0) + 52; + } + if (chr === "+") { + return 62; + } + if (chr === "/") { + return 63; + } + // Throw exception; should not be hit in tests + return undefined; +} + +module.exports = atob; diff --git a/node_modules/abab/lib/btoa.js b/node_modules/abab/lib/btoa.js new file mode 100644 index 0000000..85dd966 --- /dev/null +++ b/node_modules/abab/lib/btoa.js @@ -0,0 +1,66 @@ +"use strict"; + +/** + * btoa() as defined by the HTML and Infra specs, which mostly just references + * RFC 4648. + */ +function btoa(s) { + let i; + // String conversion as required by Web IDL. + s = `${s}`; + // "The btoa() method must throw an "InvalidCharacterError" DOMException if + // data contains any character whose code point is greater than U+00FF." + for (i = 0; i < s.length; i++) { + if (s.charCodeAt(i) > 255) { + return null; + } + } + let out = ""; + for (i = 0; i < s.length; i += 3) { + const groupsOfSix = [undefined, undefined, undefined, undefined]; + groupsOfSix[0] = s.charCodeAt(i) >> 2; + groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4; + if (s.length > i + 1) { + groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4; + groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2; + } + if (s.length > i + 2) { + groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6; + groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f; + } + for (let j = 0; j < groupsOfSix.length; j++) { + if (typeof groupsOfSix[j] === "undefined") { + out += "="; + } else { + out += btoaLookup(groupsOfSix[j]); + } + } + } + return out; +} + +/** + * Lookup table for btoa(), which converts a six-bit number into the + * corresponding ASCII character. + */ +function btoaLookup(idx) { + if (idx < 26) { + return String.fromCharCode(idx + "A".charCodeAt(0)); + } + if (idx < 52) { + return String.fromCharCode(idx - 26 + "a".charCodeAt(0)); + } + if (idx < 62) { + return String.fromCharCode(idx - 52 + "0".charCodeAt(0)); + } + if (idx === 62) { + return "+"; + } + if (idx === 63) { + return "/"; + } + // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests. + return undefined; +} + +module.exports = btoa; diff --git a/node_modules/abab/package.json b/node_modules/abab/package.json new file mode 100644 index 0000000..7b064b3 --- /dev/null +++ b/node_modules/abab/package.json @@ -0,0 +1,70 @@ +{ + "_from": "abab@^2.0.0", + "_id": "abab@2.0.0", + "_inBundle": false, + "_integrity": "sha512-sY5AXXVZv4Y1VACTtR11UJCPHHudgY5i26Qj5TypE6DKlIApbwb5uqhXcJ5UUGbvZNRh7EeIoW+LrJumBsKp7w==", + "_location": "/abab", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "abab@^2.0.0", + "name": "abab", + "escapedName": "abab", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/data-urls", + "/jsdom" + ], + "_resolved": "https://registry.npmjs.org/abab/-/abab-2.0.0.tgz", + "_shasum": "aba0ab4c5eee2d4c79d3487d85450fb2376ebb0f", + "_spec": "abab@^2.0.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\jsdom", + "author": { + "name": "Jeff Carpenter", + "email": "gcarpenterv@gmail.com" + }, + "bugs": { + "url": "https://github.com/jsdom/abab/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "WHATWG spec-compliant implementations of window.atob and window.btoa.", + "devDependencies": { + "eslint": "^4.19.1", + "karma": "^2.0.0", + "karma-cli": "^1.0.1", + "karma-firefox-launcher": "^1.1.0", + "karma-mocha": "^1.3.0", + "karma-webpack": "^3.0.0", + "mocha": "^5.1.0", + "webpack": "^4.5.0" + }, + "files": [ + "index.js", + "lib/" + ], + "homepage": "https://github.com/jsdom/abab#readme", + "keywords": [ + "atob", + "btoa", + "browser" + ], + "license": "SEE LICENSE IN LICENSE.md", + "main": "index.js", + "name": "abab", + "repository": { + "type": "git", + "url": "git+https://github.com/jsdom/abab.git" + }, + "scripts": { + "karma": "karma start", + "lint": "eslint .", + "mocha": "mocha test/node", + "test": "npm run lint && npm run mocha && npm run karma" + }, + "version": "2.0.0" +} diff --git a/node_modules/acorn-globals/LICENSE b/node_modules/acorn-globals/LICENSE new file mode 100644 index 0000000..27cc9f3 --- /dev/null +++ b/node_modules/acorn-globals/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Forbes Lindesay + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/acorn-globals/README.md b/node_modules/acorn-globals/README.md new file mode 100644 index 0000000..d8cd372 --- /dev/null +++ b/node_modules/acorn-globals/README.md @@ -0,0 +1,76 @@ +# acorn-globals + +Detect global variables in JavaScript using acorn + +[![Build Status](https://img.shields.io/travis/ForbesLindesay/acorn-globals/master.svg)](https://travis-ci.org/ForbesLindesay/acorn-globals) +[![Dependency Status](https://img.shields.io/david/ForbesLindesay/acorn-globals.svg)](https://david-dm.org/ForbesLindesay/acorn-globals) +[![NPM version](https://img.shields.io/npm/v/acorn-globals.svg)](https://www.npmjs.org/package/acorn-globals) + +## Installation + + npm install acorn-globals + +## Usage + +detect.js + +```js +var fs = require('fs'); +var detect = require('acorn-globals'); + +var src = fs.readFileSync(__dirname + '/input.js', 'utf8'); + +var scope = detect(src); +console.dir(scope); +``` + +input.js + +```js +var x = 5; +var y = 3, z = 2; + +w.foo(); +w = 2; + +RAWR=444; +RAWR.foo(); + +BLARG=3; + +foo(function () { + var BAR = 3; + process.nextTick(function (ZZZZZZZZZZZZ) { + console.log('beep boop'); + var xyz = 4; + x += 10; + x.zzzzzz; + ZZZ=6; + }); + function doom () { + } + ZZZ.foo(); + +}); + +console.log(xyz); +``` + +output: + +``` +$ node example/detect.js +[ { name: 'BLARG', nodes: [ [Object] ] }, + { name: 'RAWR', nodes: [ [Object], [Object] ] }, + { name: 'ZZZ', nodes: [ [Object], [Object] ] }, + { name: 'console', nodes: [ [Object], [Object] ] }, + { name: 'foo', nodes: [ [Object] ] }, + { name: 'process', nodes: [ [Object] ] }, + { name: 'w', nodes: [ [Object], [Object] ] }, + { name: 'xyz', nodes: [ [Object] ] } ] +``` + + +## License + + MIT diff --git a/node_modules/acorn-globals/index.js b/node_modules/acorn-globals/index.js new file mode 100644 index 0000000..2410b2d --- /dev/null +++ b/node_modules/acorn-globals/index.js @@ -0,0 +1,171 @@ +'use strict'; + +var acorn = require('acorn'); +var walk = require('acorn-walk'); + +function isScope(node) { + return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression' || node.type === 'Program'; +} +function isBlockScope(node) { + return node.type === 'BlockStatement' || isScope(node); +} + +function declaresArguments(node) { + return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; +} + +function declaresThis(node) { + return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; +} + +function reallyParse(source, options) { + var parseOptions = Object.assign({}, options, + { + allowReturnOutsideFunction: true, + allowImportExportEverywhere: true, + allowHashBang: true + } + ); + return acorn.parse(source, parseOptions); +} +module.exports = findGlobals; +module.exports.parse = reallyParse; +function findGlobals(source, options) { + options = options || {}; + var globals = []; + var ast; + // istanbul ignore else + if (typeof source === 'string') { + ast = reallyParse(source, options); + } else { + ast = source; + } + // istanbul ignore if + if (!(ast && typeof ast === 'object' && ast.type === 'Program')) { + throw new TypeError('Source must be either a string of JavaScript or an acorn AST'); + } + var declareFunction = function (node) { + var fn = node; + fn.locals = fn.locals || {}; + node.params.forEach(function (node) { + declarePattern(node, fn); + }); + if (node.id) { + fn.locals[node.id.name] = true; + } + }; + var declarePattern = function (node, parent) { + switch (node.type) { + case 'Identifier': + parent.locals[node.name] = true; + break; + case 'ObjectPattern': + node.properties.forEach(function (node) { + declarePattern(node.value || node.argument, parent); + }); + break; + case 'ArrayPattern': + node.elements.forEach(function (node) { + if (node) declarePattern(node, parent); + }); + break; + case 'RestElement': + declarePattern(node.argument, parent); + break; + case 'AssignmentPattern': + declarePattern(node.left, parent); + break; + // istanbul ignore next + default: + throw new Error('Unrecognized pattern type: ' + node.type); + } + }; + var declareModuleSpecifier = function (node, parents) { + ast.locals = ast.locals || {}; + ast.locals[node.local.name] = true; + }; + walk.ancestor(ast, { + 'VariableDeclaration': function (node, parents) { + var parent = null; + for (var i = parents.length - 1; i >= 0 && parent === null; i--) { + if (node.kind === 'var' ? isScope(parents[i]) : isBlockScope(parents[i])) { + parent = parents[i]; + } + } + parent.locals = parent.locals || {}; + node.declarations.forEach(function (declaration) { + declarePattern(declaration.id, parent); + }); + }, + 'FunctionDeclaration': function (node, parents) { + var parent = null; + for (var i = parents.length - 2; i >= 0 && parent === null; i--) { + if (isScope(parents[i])) { + parent = parents[i]; + } + } + parent.locals = parent.locals || {}; + if (node.id) { + parent.locals[node.id.name] = true; + } + declareFunction(node); + }, + 'Function': declareFunction, + 'ClassDeclaration': function (node, parents) { + var parent = null; + for (var i = parents.length - 2; i >= 0 && parent === null; i--) { + if (isScope(parents[i])) { + parent = parents[i]; + } + } + parent.locals = parent.locals || {}; + if (node.id) { + parent.locals[node.id.name] = true; + } + }, + 'TryStatement': function (node) { + if (node.handler === null) return; + node.handler.locals = node.handler.locals || {}; + node.handler.locals[node.handler.param.name] = true; + }, + 'ImportDefaultSpecifier': declareModuleSpecifier, + 'ImportSpecifier': declareModuleSpecifier, + 'ImportNamespaceSpecifier': declareModuleSpecifier + }); + function identifier(node, parents) { + var name = node.name; + if (name === 'undefined') return; + for (var i = 0; i < parents.length; i++) { + if (name === 'arguments' && declaresArguments(parents[i])) { + return; + } + if (parents[i].locals && name in parents[i].locals) { + return; + } + } + node.parents = parents.slice(); + globals.push(node); + } + walk.ancestor(ast, { + 'VariablePattern': identifier, + 'Identifier': identifier, + 'ThisExpression': function (node, parents) { + for (var i = 0; i < parents.length; i++) { + if (declaresThis(parents[i])) { + return; + } + } + node.parents = parents.slice(); + globals.push(node); + } + }); + var groupedGlobals = {}; + globals.forEach(function (node) { + var name = node.type === 'ThisExpression' ? 'this' : node.name; + groupedGlobals[name] = (groupedGlobals[name] || []); + groupedGlobals[name].push(node); + }); + return Object.keys(groupedGlobals).sort().map(function (name) { + return {name: name, nodes: groupedGlobals[name]}; + }); +} diff --git a/node_modules/acorn-globals/package.json b/node_modules/acorn-globals/package.json new file mode 100644 index 0000000..ac07ff1 --- /dev/null +++ b/node_modules/acorn-globals/package.json @@ -0,0 +1,66 @@ +{ + "_from": "acorn-globals@^4.3.0", + "_id": "acorn-globals@4.3.1", + "_inBundle": false, + "_integrity": "sha512-gJSiKY8dBIjV/0jagZIFBdVMtfQyA5QHCvAT48H2q8REQoW8Fs5AOjqBql1LgSXgrMWdevcE+8cdZ33NtVbIBA==", + "_location": "/acorn-globals", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "acorn-globals@^4.3.0", + "name": "acorn-globals", + "escapedName": "acorn-globals", + "rawSpec": "^4.3.0", + "saveSpec": null, + "fetchSpec": "^4.3.0" + }, + "_requiredBy": [ + "/jsdom" + ], + "_resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-4.3.1.tgz", + "_shasum": "deb149c59276657ebd40ba2ba849ddd529763ccf", + "_spec": "acorn-globals@^4.3.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\jsdom", + "author": { + "name": "ForbesLindesay" + }, + "bugs": { + "url": "https://github.com/ForbesLindesay/acorn-globals/issues" + }, + "bundleDependencies": false, + "dependencies": { + "acorn": "^6.0.1", + "acorn-walk": "^6.0.1" + }, + "deprecated": false, + "description": "Detect global variables in JavaScript using acorn", + "devDependencies": { + "testit": "^3.0.0" + }, + "files": [ + "index.js", + "LICENSE" + ], + "homepage": "https://github.com/ForbesLindesay/acorn-globals#readme", + "keywords": [ + "ast", + "variable", + "name", + "lexical", + "scope", + "local", + "global", + "implicit" + ], + "license": "MIT", + "name": "acorn-globals", + "repository": { + "type": "git", + "url": "git+https://github.com/ForbesLindesay/acorn-globals.git" + }, + "scripts": { + "test": "node test" + }, + "version": "4.3.1" +} diff --git a/node_modules/acorn-walk/CHANGELOG.md b/node_modules/acorn-walk/CHANGELOG.md new file mode 100644 index 0000000..525950b --- /dev/null +++ b/node_modules/acorn-walk/CHANGELOG.md @@ -0,0 +1,97 @@ +## 6.1.0 (2018-09-28) + +### New features + +The walker now walks `TemplateElement` nodes. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix bad "main" field in package.json. + +## 6.0.0 (2018-09-14) + +### Breaking changes + +This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package. + +The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported. + +## 5.7.1 (2018-06-15) + +### Bug fixes + +Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions). + +## 5.7.0 (2018-06-15) + +### Bug fixes + +Fix crash in walker when walking a binding-less catch node. + +## 5.6.2 (2018-06-05) + +### Bug fixes + +In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere. + +## 5.6.1 (2018-06-01) + +### Bug fixes + +Fix regression when passing `null` as fourth argument to `walk.recursive`. + +## 5.6.0 (2018-05-31) + +### Bug fixes + +Fix a bug in the walker that caused a crash when walking an object pattern spread. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix regression in walker causing property values in object patterns to be walked as expressions. + +## 5.5.0 (2018-02-27) + +### Bug fixes + +Support object spread in the AST walker. + +## 5.4.1 (2018-02-02) + +### Bug fixes + +5.4.0 somehow accidentally included an old version of walk.js. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +The `full` and `fullAncestor` walkers no longer visit nodes multiple times. + +## 5.1.0 (2017-07-05) + +### New features + +New walker functions `full` and `fullAncestor`. + +## 3.2.0 (2016-06-07) + +### New features + +Make it possible to use `visit.ancestor` with a walk state. + +## 3.1.0 (2016-04-18) + +### New features + +The walker now allows defining handlers for `CatchClause` nodes. + +## 2.5.2 (2015-10-27) + +### Fixes + +Fix bug where the walker walked an exported `let` statement as an expression. diff --git a/node_modules/acorn-walk/LICENSE b/node_modules/acorn-walk/LICENSE new file mode 100644 index 0000000..2c0632b --- /dev/null +++ b/node_modules/acorn-walk/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2018 by various contributors (see AUTHORS) + +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. diff --git a/node_modules/acorn-walk/README.md b/node_modules/acorn-walk/README.md new file mode 100644 index 0000000..2b94bec --- /dev/null +++ b/node_modules/acorn-walk/README.md @@ -0,0 +1,126 @@ +# Acorn AST walker + +An abstract syntax tree walker for the +[ESTree](https://github.com/estree/estree) format. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). For questions +and discussion, please use the +[Tern discussion forum](https://discuss.ternjs.net). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn-walk +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +An algorithm for recursing through a syntax tree is stored as an +object, with a property for each tree node type holding a function +that will recurse through such a node. There are several ways to run +such a walker. + +**simple**`(node, visitors, base, state)` does a 'simple' walk over a +tree. `node` should be the AST node to walk, and `visitors` an object +with properties whose names correspond to node types in the [ESTree +spec](https://github.com/estree/estree). The properties should contain +functions that will be called with the node object and, if applicable +the state at that point. The last two arguments are optional. `base` +is a walker algorithm, and `state` is a start state. The default +walker will simply visit all statements and expressions and not +produce a meaningful state. (An example of a use of state is to track +scope at each point in the tree.) + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.simple(acorn.parse("let x = 10"), { + Literal(node) { + console.log(`Found a literal: ${node.value}`) + } +}) +``` + +**ancestor**`(node, visitors, base, state)` does a 'simple' walk over +a tree, building up an array of ancestor nodes (including the current node) +and passing the array to the callbacks as a third parameter. + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.ancestor(acorn.parse("foo('hi')"), { + Literal(_, ancestors) { + console.log("This literal's ancestors are:", ancestors.map(n => n.type)) + } +}) +``` + +**recursive**`(node, state, functions, base)` does a 'recursive' +walk, where the walker functions are responsible for continuing the +walk on the child nodes of their target node. `state` is the start +state, and `functions` should contain an object that maps node types +to walker functions. Such functions are called with `(node, state, c)` +arguments, and can cause the walk to continue on a sub-node by calling +the `c` argument on it with `(node, state)` arguments. The optional +`base` argument provides the fallback walker functions for node types +that aren't handled in the `functions` object. If not given, the +default walkers will be used. + +**make**`(functions, base)` builds a new walker object by using the +walker functions in `functions` and filling in the missing ones by +taking defaults from `base`. + +**full**`(node, callback, base, state)` does a 'full' walk over a +tree, calling the callback with the arguments (node, state, type) for +each node + +**fullAncestor**`(node, callback, base, state)` does a 'full' walk +over a tree, building up an array of ancestor nodes (including the +current node) and passing the array to the callbacks as a third +parameter. + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.full(acorn.parse("1 + 1"), node => { + console.log(`There's a ${node.type} node at ${node.ch}`) +}) +``` + +**findNodeAt**`(node, start, end, test, base, state)` tries to locate +a node in a tree at the given start and/or end offsets, which +satisfies the predicate `test`. `start` and `end` can be either `null` +(as wildcard) or a number. `test` may be a string (indicating a node +type) or a function that takes `(nodeType, node)` arguments and +returns a boolean indicating whether this node is interesting. `base` +and `state` are optional, and can be used to specify a custom walker. +Nodes are tested from inner to outer, so if two nodes match the +boundaries, the inner one will be preferred. + +**findNodeAround**`(node, pos, test, base, state)` is a lot like +`findNodeAt`, but will match any node that exists 'around' (spanning) +the given position. + +**findNodeAfter**`(node, pos, test, base, state)` is similar to +`findNodeAround`, but will match all nodes *after* the given position +(testing outer nodes before inner nodes). diff --git a/node_modules/acorn-walk/package.json b/node_modules/acorn-walk/package.json new file mode 100644 index 0000000..4dbe755 --- /dev/null +++ b/node_modules/acorn-walk/package.json @@ -0,0 +1,63 @@ +{ + "_from": "acorn-walk@^6.0.1", + "_id": "acorn-walk@6.1.1", + "_inBundle": false, + "_integrity": "sha512-OtUw6JUTgxA2QoqqmrmQ7F2NYqiBPi/L2jqHyFtllhOUvXYQXf0Z1CYUinIfyT4bTCGmrA7gX9FvHA81uzCoVw==", + "_location": "/acorn-walk", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "acorn-walk@^6.0.1", + "name": "acorn-walk", + "escapedName": "acorn-walk", + "rawSpec": "^6.0.1", + "saveSpec": null, + "fetchSpec": "^6.0.1" + }, + "_requiredBy": [ + "/acorn-globals" + ], + "_resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-6.1.1.tgz", + "_shasum": "d363b66f5fac5f018ff9c3a1e7b6f8e310cc3913", + "_spec": "acorn-walk@^6.0.1", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\acorn-globals", + "bugs": { + "url": "https://github.com/acornjs/acorn/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "ECMAScript (ESTree) AST walker", + "engines": { + "node": ">=0.4.0" + }, + "homepage": "https://github.com/acornjs/acorn", + "license": "MIT", + "main": "dist/walk.js", + "maintainers": [ + { + "name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "url": "https://marijnhaverbeke.nl" + }, + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "url": "https://rreverser.com/" + }, + { + "name": "Adrian Heine", + "url": "http://adrianheine.de" + } + ], + "module": "dist/walk.mjs", + "name": "acorn-walk", + "repository": { + "type": "git", + "url": "git+https://github.com/acornjs/acorn.git" + }, + "scripts": { + "prepare": "cd ..; npm run build:walk" + }, + "version": "6.1.1" +} diff --git a/node_modules/acorn/CHANGELOG.md b/node_modules/acorn/CHANGELOG.md new file mode 100644 index 0000000..1c8f79c --- /dev/null +++ b/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,514 @@ +## 6.1.1 (2019-02-27) + +### Bug fixes + +Fix bug that caused parsing default exports of with names to fail. + +## 6.1.0 (2019-02-08) + +### Bug fixes + +Fix scope checking when redefining a `var` as a lexical binding. + +### New features + +Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. + +## 6.0.7 (2019-02-04) + +### Bug fixes + +Check that exported bindings are defined. + +Don't treat `\u180e` as a whitespace character. + +Check for duplicate parameter names in methods. + +Don't allow shorthand properties when they are generators or async methods. + +Forbid binding `await` in async arrow function's parameter list. + +## 6.0.6 (2019-01-30) + +### Bug fixes + +The content of class declarations and expressions is now always parsed in strict mode. + +Don't allow `let` or `const` to bind the variable name `let`. + +Treat class declarations as lexical. + +Don't allow a generator function declaration as the sole body of an `if` or `else`. + +Ignore `"use strict"` when after an empty statement. + +Allow string line continuations with special line terminator characters. + +Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. + +Fix bug with parsing `yield` in a `for` loop initializer. + +Implement special cases around scope checking for functions. + +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/node_modules/acorn/LICENSE b/node_modules/acorn/LICENSE new file mode 100644 index 0000000..2c0632b --- /dev/null +++ b/node_modules/acorn/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2018 by various contributors (see AUTHORS) + +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. diff --git a/node_modules/acorn/README.md b/node_modules/acorn/README.md new file mode 100644 index 0000000..3e5f58d --- /dev/null +++ b/node_modules/acorn/README.md @@ -0,0 +1,269 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). For questions +and discussion, please use the +[Tern discussion forum](https://discuss.ternjs.net). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` can be undefined or an object +setting some of the options listed below. The return value will be an +abstract syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +let acorn = require("acorn"); +console.log(acorn.parse("1 + 1")); +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options can be provided by passing a second argument, which should be +an object containing any of these fields: + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be + either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial + support). This influences support for strict mode, the set of + reserved words, and support for new syntax features. Default is 7. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features can be implemented + through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"` or `"module"`. This influences global strict mode + and parsing of `import` and `export` declarations. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed. + +- **allowAwaitOutsideFunction**: By default, `await` expressions can + only appear inside `async` functions. Setting this option to + `true` allows to have top-level `await` expressions. They are + still not allowed in non-`async` functions, though. + +- **allowHashBang**: When this is enabled (off by default), if the + code starts with the characters `#!` (as in a shellscript), the + first line will be treated as a comment. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)]; +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +var JSXParser = acorn.Parser.extend(jsx()); +JSXParser.parse("foo()"); +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) + +Plugins for ECMAScript proposals: + + - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: + - [`acorn-async-iteration`](https://github.com/acornjs/acorn-async-iteration): Parse [async iteration proposal](https://github.com/tc39/proposal-async-iteration) + - [`acorn-bigint`](https://github.com/acornjs/acorn-bigint): Parse [BigInt proposal](https://github.com/tc39/proposal-bigint) + - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) + - [`acorn-dynamic-import`](https://github.com/kesne/acorn-dynamic-import): Parse [import() proposal](https://github.com/tc39/proposal-dynamic-import) + - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) + - [`acorn-numeric-separator`](https://github.com/acornjs/acorn-numeric-separator): Parse [numeric separator proposal](https://github.com/tc39/proposal-numeric-separator) + - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n diff --git a/node_modules/acorn/bin/acorn b/node_modules/acorn/bin/acorn new file mode 100644 index 0000000..cf7df46 --- /dev/null +++ b/node_modules/acorn/bin/acorn @@ -0,0 +1,4 @@ +#!/usr/bin/env node +'use strict'; + +require('../dist/bin.js'); diff --git a/node_modules/acorn/package.json b/node_modules/acorn/package.json new file mode 100644 index 0000000..b134899 --- /dev/null +++ b/node_modules/acorn/package.json @@ -0,0 +1,67 @@ +{ + "_from": "acorn@^6.0.4", + "_id": "acorn@6.1.1", + "_inBundle": false, + "_integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", + "_location": "/acorn", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "acorn@^6.0.4", + "name": "acorn", + "escapedName": "acorn", + "rawSpec": "^6.0.4", + "saveSpec": null, + "fetchSpec": "^6.0.4" + }, + "_requiredBy": [ + "/acorn-globals", + "/jsdom" + ], + "_resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", + "_shasum": "7d25ae05bb8ad1f9b699108e1094ecd7884adc1f", + "_spec": "acorn@^6.0.4", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\jsdom", + "bin": { + "acorn": "./bin/acorn" + }, + "bugs": { + "url": "https://github.com/acornjs/acorn/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "ECMAScript parser", + "engines": { + "node": ">=0.4.0" + }, + "homepage": "https://github.com/acornjs/acorn", + "license": "MIT", + "main": "dist/acorn.js", + "maintainers": [ + { + "name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "url": "https://marijnhaverbeke.nl" + }, + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "url": "https://rreverser.com/" + }, + { + "name": "Adrian Heine", + "url": "http://adrianheine.de" + } + ], + "module": "dist/acorn.mjs", + "name": "acorn", + "repository": { + "type": "git", + "url": "git+https://github.com/acornjs/acorn.git" + }, + "scripts": { + "prepare": "cd ..; npm run build:main && npm run build:bin" + }, + "version": "6.1.1" +} diff --git a/node_modules/ajv/.tonic_example.js b/node_modules/ajv/.tonic_example.js new file mode 100644 index 0000000..aa11812 --- /dev/null +++ b/node_modules/ajv/.tonic_example.js @@ -0,0 +1,20 @@ +var Ajv = require('ajv'); +var ajv = new Ajv({allErrors: true}); + +var schema = { + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "number", "maximum": 3 } + } +}; + +var validate = ajv.compile(schema); + +test({"foo": "abc", "bar": 2}); +test({"foo": 2, "bar": 4}); + +function test(data) { + var valid = validate(data); + if (valid) console.log('Valid!'); + else console.log('Invalid: ' + ajv.errorsText(validate.errors)); +} \ No newline at end of file diff --git a/node_modules/ajv/LICENSE b/node_modules/ajv/LICENSE new file mode 100644 index 0000000..96ee719 --- /dev/null +++ b/node_modules/ajv/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2017 Evgeny Poberezkin + +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. + diff --git a/node_modules/ajv/README.md b/node_modules/ajv/README.md new file mode 100644 index 0000000..c858efd --- /dev/null +++ b/node_modules/ajv/README.md @@ -0,0 +1,1344 @@ +Ajv logo + +# Ajv: Another JSON Schema Validator + +The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. + +[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv) +[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) +[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) +[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master) +[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) + +### _Ajv and [related repositories](#related-packages) will be transfered to [ajv-validator](https://github.com/ajv-validator) org_ + +## Using version 6 + +[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. + +[Ajv version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). + +__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: + +```javascript +ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); +``` + +To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: + +```javascript +var ajv = new Ajv({schemaId: 'id'}); +// If you want to use both draft-04 and draft-06/07 schemas: +// var ajv = new Ajv({schemaId: 'auto'}); +ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); +``` + + +## Contents + +- [Performance](#performance) +- [Features](#features) +- [Getting started](#getting-started) +- [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md) +- [Using in browser](#using-in-browser) +- [Command line interface](#command-line-interface) +- Validation + - [Keywords](#validation-keywords) + - [Annotation keywords](#annotation-keywords) + - [Formats](#formats) + - [Combining schemas with $ref](#ref) + - [$data reference](#data-reference) + - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) + - [Defining custom keywords](#defining-custom-keywords) + - [Asynchronous schema compilation](#asynchronous-schema-compilation) + - [Asynchronous validation](#asynchronous-validation) + - [Security considerations](#security-considerations) +- Modifying data during validation + - [Filtering data](#filtering-data) + - [Assigning defaults](#assigning-defaults) + - [Coercing data types](#coercing-data-types) +- API + - [Methods](#api) + - [Options](#options) + - [Validation errors](#validation-errors) +- [Plugins](#plugins) +- [Related packages](#related-packages) +- [Some packages using Ajv](#some-packages-using-ajv) +- [Tests, Contributing, History, License](#tests) + + +## Performance + +Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. + +Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: + +- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place +- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster +- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) +- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) + + +Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): + +[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) + + +## Features + +- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: + - all validation keywords (see [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md)) + - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) + - support of circular references between schemas + - correct string lengths for strings with unicode pairs (can be turned off) + - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) + - [validates schemas against meta-schema](#api-validateschema) +- supports [browsers](#using-in-browser) and Node.js 0.10-8.x +- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation +- "All errors" validation mode with [option allErrors](#options) +- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages +- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package +- [filtering data](#filtering-data) from additional properties +- [assigning defaults](#assigning-defaults) to missing properties and items +- [coercing data](#coercing-data-types) to the types specified in `type` keywords +- [custom keywords](#defining-custom-keywords) +- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` +- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). +- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package +- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords +- [asynchronous validation](#asynchronous-validation) of custom formats and keywords + +Currently Ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript). + + +## Install + +``` +npm install ajv +``` + + +## Getting started + +Try it in the Node.js REPL: https://tonicdev.com/npm/ajv + + +The fastest validation call: + +```javascript +var Ajv = require('ajv'); +var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} +var validate = ajv.compile(schema); +var valid = validate(data); +if (!valid) console.log(validate.errors); +``` + +or with less code + +```javascript +// ... +var valid = ajv.validate(schema, data); +if (!valid) console.log(ajv.errors); +// ... +``` + +or + +```javascript +// ... +var valid = ajv.addSchema(schema, 'mySchema') + .validate('mySchema', data); +if (!valid) console.log(ajv.errorsText()); +// ... +``` + +See [API](#api) and [Options](#options) for more details. + +Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. + +The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). + +__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) + + +## Using in browser + +You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. + +If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). + +Then you need to load Ajv in the browser: +```html + +``` + +This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. + +The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). + +Ajv is tested with these browsers: + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) + +__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/epoberezkin/ajv/issues/234)). + + +## Command line interface + +CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports: + +- compiling JSON Schemas to test their validity +- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack)) +- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) +- validating data file(s) against JSON Schema +- testing expected validity of data against JSON Schema +- referenced schemas +- custom meta-schemas +- files in JSON and JavaScript format +- all Ajv options +- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format + + +## Validation keywords + +Ajv supports all validation keywords from draft-07 of JSON Schema standard: + +- [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type) +- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf +- [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format +- [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains) +- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames) +- [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const) +- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse) + +With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: + +- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. +- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. + +See [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details. + + +## Annotation keywords + +JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. + +- `title` and `description`: information about the data represented by that schema +- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). +- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). +- `examples` (NEW in draft-07): an array of data instances. Ajv does not check the validity of these instances against the schema. +- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). +- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". +- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". + +__Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. + + +## Formats + +The following formats are supported for string validation with "format" keyword: + +- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). +- _time_: time with optional time-zone. +- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). +- _uri_: full URI. +- _uri-reference_: URI reference, including full and relative URIs. +- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) +- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). +- _email_: email address. +- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). +- _ipv4_: IP address v4. +- _ipv6_: IP address v6. +- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. +- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). +- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). +- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). + +__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. + +There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, `email`, and `hostname`. See [Options](#options) for details. + +You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. + +The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details. + +You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js). + + +## Combining schemas with $ref + +You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. + +Example: + +```javascript +var schema = { + "$id": "http://example.com/schemas/schema.json", + "type": "object", + "properties": { + "foo": { "$ref": "defs.json#/definitions/int" }, + "bar": { "$ref": "defs.json#/definitions/str" } + } +}; + +var defsSchema = { + "$id": "http://example.com/schemas/defs.json", + "definitions": { + "int": { "type": "integer" }, + "str": { "type": "string" } + } +}; +``` + +Now to compile your schema you can either pass all schemas to Ajv instance: + +```javascript +var ajv = new Ajv({schemas: [schema, defsSchema]}); +var validate = ajv.getSchema('http://example.com/schemas/schema.json'); +``` + +or use `addSchema` method: + +```javascript +var ajv = new Ajv; +var validate = ajv.addSchema(defsSchema) + .compile(schema); +``` + +See [Options](#options) and [addSchema](#api) method. + +__Please note__: +- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). +- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). +- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. +- The actual location of the schema file in the file system is not used. +- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. +- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. +- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). + + +## $data reference + +With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works. + +`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. + +The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). + +Examples. + +This schema requires that the value in property `smaller` is less or equal than the value in the property larger: + +```javascript +var ajv = new Ajv({$data: true}); + +var schema = { + "properties": { + "smaller": { + "type": "number", + "maximum": { "$data": "1/larger" } + }, + "larger": { "type": "number" } + } +}; + +var validData = { + smaller: 5, + larger: 7 +}; + +ajv.validate(schema, validData); // true +``` + +This schema requires that the properties have the same format as their field names: + +```javascript +var schema = { + "additionalProperties": { + "type": "string", + "format": { "$data": "0#" } + } +}; + +var validData = { + 'date-time': '1963-06-19T08:30:06.283185Z', + email: 'joe.bloggs@example.com' +} +``` + +`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. + + +## $merge and $patch keywords + +With the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). + +To add keywords `$merge` and `$patch` to Ajv instance use this code: + +```javascript +require('ajv-merge-patch')(ajv); +``` + +Examples. + +Using `$merge`: + +```json +{ + "$merge": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": { + "properties": { "q": { "type": "number" } } + } + } +} +``` + +Using `$patch`: + +```json +{ + "$patch": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": [ + { "op": "add", "path": "/properties/q", "value": { "type": "number" } } + ] + } +} +``` + +The schemas above are equivalent to this schema: + +```json +{ + "type": "object", + "properties": { + "p": { "type": "string" }, + "q": { "type": "number" } + }, + "additionalProperties": false +} +``` + +The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. + +See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information. + + +## Defining custom keywords + +The advantages of using custom keywords are: + +- allow creating validation scenarios that cannot be expressed using JSON Schema +- simplify your schemas +- help bringing a bigger part of the validation logic to your schemas +- make your schemas more expressive, less verbose and closer to your application domain +- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated + +If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). + +The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. + +You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. + +Ajv allows defining keywords with: +- validation function +- compilation function +- macro function +- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. + +Example. `range` and `exclusiveRange` keywords using compiled schema: + +```javascript +ajv.addKeyword('range', { + type: 'number', + compile: function (sch, parentSchema) { + var min = sch[0]; + var max = sch[1]; + + return parentSchema.exclusiveRange === true + ? function (data) { return data > min && data < max; } + : function (data) { return data >= min && data <= max; } + } +}); + +var schema = { "range": [2, 4], "exclusiveRange": true }; +var validate = ajv.compile(schema); +console.log(validate(2.01)); // true +console.log(validate(3.99)); // true +console.log(validate(2)); // false +console.log(validate(4)); // false +``` + +Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. + +See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details. + + +## Asynchronous schema compilation + +During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). + +Example: + +```javascript +var ajv = new Ajv({ loadSchema: loadSchema }); + +ajv.compileAsync(schema).then(function (validate) { + var valid = validate(data); + // ... +}); + +function loadSchema(uri) { + return request.json(uri).then(function (res) { + if (res.statusCode >= 400) + throw new Error('Loading error: ' + res.statusCode); + return res.body; + }); +} +``` + +__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. + + +## Asynchronous validation + +Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation + +You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). + +If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. + +__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. + +Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). + +Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). + +The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. + +Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. + + +Example: + +```javascript +var ajv = new Ajv; +// require('ajv-async')(ajv); + +ajv.addKeyword('idExists', { + async: true, + type: 'number', + validate: checkIdExists +}); + + +function checkIdExists(schema, data) { + return knex(schema.table) + .select('id') + .where('id', data) + .then(function (rows) { + return !!rows.length; // true if record is found + }); +} + +var schema = { + "$async": true, + "properties": { + "userId": { + "type": "integer", + "idExists": { "table": "users" } + }, + "postId": { + "type": "integer", + "idExists": { "table": "posts" } + } + } +}; + +var validate = ajv.compile(schema); + +validate({ userId: 1, postId: 19 }) +.then(function (data) { + console.log('Data is valid', data); // { userId: 1, postId: 19 } +}) +.catch(function (err) { + if (!(err instanceof Ajv.ValidationError)) throw err; + // data is invalid + console.log('Validation errors:', err.errors); +}); +``` + +### Using transpilers with asynchronous validation functions. + +[ajv-async](https://github.com/epoberezkin/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). + + +#### Using nodent + +```javascript +var ajv = new Ajv; +require('ajv-async')(ajv); +// in the browser if you want to load ajv-async bundle separately you can: +// window.ajvAsync(ajv); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + + +#### Using other transpilers + +```javascript +var ajv = new Ajv({ processCode: transpileFunc }); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + +See [Options](#options). + + +## Security considerations + +JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. + + +##### Untrusted schemas + +Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. + +If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: +- compiling schemas can cause stack overflow (if they are too deep) +- compiling schemas can be slow (e.g. [#557](https://github.com/epoberezkin/ajv/issues/557)) +- validating certain data can be slow + +It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. + +Regardless the measures you take, using untrusted schemas increases security risks. + + +##### Circular references in JavaScript objects + +Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/epoberezkin/ajv/issues/802). + +An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. + + +##### Security risks of trusted schemas + +Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): + +- `pattern` and `format` for large strings - use `maxLength` to mitigate +- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate +- `patternProperties` for large property names - use `propertyNames` to mitigate + +__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). + +You can validate your JSON schemas against [this meta-schema](https://github.com/epoberezkin/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: + +```javascript +const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); + +const schema1 = {format: 'email'}; +isSchemaSecure(schema1); // false + +const schema2 = {format: 'email', maxLength: 256}; +isSchemaSecure(schema2); // true +``` + +__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. + + +## Filtering data + +With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. + +This option modifies original data. + +Example: + +```javascript +var ajv = new Ajv({ removeAdditional: true }); +var schema = { + "additionalProperties": false, + "properties": { + "foo": { "type": "number" }, + "bar": { + "additionalProperties": { "type": "number" }, + "properties": { + "baz": { "type": "string" } + } + } + } +} + +var data = { + "foo": 0, + "additional1": 1, // will be removed; `additionalProperties` == false + "bar": { + "baz": "abc", + "additional2": 2 // will NOT be removed; `additionalProperties` != false + }, +} + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } +``` + +If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. + +If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). + +__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: + +```json +{ + "type": "object", + "oneOf": [ + { + "properties": { + "foo": { "type": "string" } + }, + "required": [ "foo" ], + "additionalProperties": false + }, + { + "properties": { + "bar": { "type": "integer" } + }, + "required": [ "bar" ], + "additionalProperties": false + } + ] +} +``` + +The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. + +With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). + +While this behaviour is unexpected (issues [#129](https://github.com/epoberezkin/ajv/issues/129), [#134](https://github.com/epoberezkin/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: + +```json +{ + "type": "object", + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "integer" } + }, + "additionalProperties": false, + "oneOf": [ + { "required": [ "foo" ] }, + { "required": [ "bar" ] } + ] +} +``` + +The schema above is also more efficient - it will compile into a faster function. + + +## Assigning defaults + +With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. + +With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. + +This option modifies original data. + +__Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. + + +Example 1 (`default` in `properties`): + +```javascript +var ajv = new Ajv({ useDefaults: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "string", "default": "baz" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": 1 }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": "baz" } +``` + +Example 2 (`default` in `items`): + +```javascript +var schema = { + "type": "array", + "items": [ + { "type": "number" }, + { "type": "string", "default": "foo" } + ] +} + +var data = [ 1 ]; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // [ 1, "foo" ] +``` + +`default` keywords in other cases are ignored: + +- not in `properties` or `items` subschemas +- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42)) +- in `if` subschema of `switch` keyword +- in schemas generated by custom macro keywords + +The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). + + +## Coercing data types + +When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. + +This option modifies original data. + +__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. + + +Example 1: + +```javascript +var ajv = new Ajv({ coerceTypes: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "boolean" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": "1", "bar": "false" }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": false } +``` + +Example 2 (array coercions): + +```javascript +var ajv = new Ajv({ coerceTypes: 'array' }); +var schema = { + "properties": { + "foo": { "type": "array", "items": { "type": "number" } }, + "bar": { "type": "boolean" } + } +}; + +var data = { "foo": "1", "bar": ["false"] }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": [1], "bar": false } +``` + +The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). + +See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details. + + +## API + +##### new Ajv(Object options) -> Object + +Create Ajv instance. + + +##### .compile(Object schema) -> Function<Object data> + +Generate validating function and cache the compiled schema for future use. + +Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. + +The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). + + +##### .compileAsync(Object schema [, Boolean meta] [, Function callback]) -> Promise + +Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: + +- missing schema can't be loaded (`loadSchema` returns a Promise that rejects). +- a schema containing a missing reference is loaded, but the reference cannot be resolved. +- schema (or some loaded/referenced schema) is invalid. + +The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. + +You can asynchronously compile meta-schema by passing `true` as the second parameter. + +See example in [Asynchronous compilation](#asynchronous-schema-compilation). + + +##### .validate(Object schema|String key|String ref, data) -> Boolean + +Validate data using passed schema (it will be compiled and cached). + +Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. + +Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). + +__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. + +If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). + + +##### .addSchema(Array<Object>|Object schema [, String key]) -> Ajv + +Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. + +Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. + +Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. + + +Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. + +Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. + +By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. + +__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. +This allows you to do nice things like the following. + +```javascript +var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); +``` + +##### .addMetaSchema(Array<Object>|Object schema [, String key]) -> Ajv + +Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). + +There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. + + +##### .validateSchema(Object schema) -> Boolean + +Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. + +By default this method is called automatically when the schema is added, so you rarely need to use it directly. + +If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). + +If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. + +Errors will be available at `ajv.errors`. + + +##### .getSchema(String key) -> Function<Object data> + +Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. + + +##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -> Ajv + +Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. + +Schema can be removed using: +- key passed to `addSchema` +- it's full reference (id) +- RegExp that should match schema id or key (meta-schemas won't be removed) +- actual schema object that will be stable-stringified to remove schema from cache + +If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. + + +##### .addFormat(String name, String|RegExp|Function|Object format) -> Ajv + +Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. + +Strings are converted to RegExp. + +Function should return validation result as `true` or `false`. + +If object is passed it should have properties `validate`, `compare` and `async`: + +- _validate_: a string, RegExp or a function as described above. +- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. +- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. +- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/epoberezkin/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. + +Custom formats can be also added via `formats` option. + + +##### .addKeyword(String keyword, Object definition) -> Ajv + +Add custom validation keyword to Ajv instance. + +Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. + +Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. +It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. + +Example Keywords: +- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. +- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. +- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword + +Keyword definition is an object with the following properties: + +- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. +- _validate_: validating function +- _compile_: compiling function +- _macro_: macro function +- _inline_: compiling function that returns code (as string) +- _schema_: an optional `false` value used with "validate" keyword to not pass schema +- _metaSchema_: an optional meta-schema for keyword schema +- _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation +- _modifying_: `true` MUST be passed if keyword modifies data +- _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) +- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. +- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). +- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. +- _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. + +_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. + +__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. + +See [Defining custom keywords](#defining-custom-keywords) for more details. + + +##### .getKeyword(String keyword) -> Object|Boolean + +Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. + + +##### .removeKeyword(String keyword) -> Ajv + +Removes custom or pre-defined keyword so you can redefine them. + +While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. + +__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. + + +##### .errorsText([Array<Object> errors [, Object options]]) -> String + +Returns the text with all errors in a String. + +Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). + + +## Options + +Defaults: + +```javascript +{ + // validation and reporting options: + $data: false, + allErrors: false, + verbose: false, + $comment: false, // NEW in Ajv version 6.0 + jsonPointers: false, + uniqueItems: true, + unicode: true, + nullable: false, + format: 'fast', + formats: {}, + unknownFormats: true, + schemas: {}, + logger: undefined, + // referenced schema options: + schemaId: '$id', + missingRefs: true, + extendRefs: 'ignore', // recommended 'fail' + loadSchema: undefined, // function(uri: string): Promise {} + // options to modify validated data: + removeAdditional: false, + useDefaults: false, + coerceTypes: false, + // strict mode options + strictDefaults: false, + strictKeywords: false, + // asynchronous validation options: + transpile: undefined, // requires ajv-async package + // advanced options: + meta: true, + validateSchema: true, + addUsedSchema: true, + inlineRefs: true, + passContext: false, + loopRequired: Infinity, + ownProperties: false, + multipleOfPrecision: false, + errorDataPath: 'object', // deprecated + messages: true, + sourceCode: false, + processCode: undefined, // function (str: string): string {} + cache: new Cache, + serialize: undefined +} +``` + +##### Validation and reporting options + +- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). +- _allErrors_: check all rules collecting all errors. Default is to return after the first error. +- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). +- _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: + - `false` (default): ignore $comment keyword. + - `true`: log the keyword value to console. + - function: pass the keyword value, its schema path and root schema to the specified function +- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. +- _uniqueItems_: validate `uniqueItems` keyword (true by default). +- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. +- _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). +- _format_: formats validation mode. Option values: + - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). + - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. + - `false` - ignore all format keywords. +- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. +- _unknownFormats_: handling of unknown formats. Option values: + - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. + - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. + - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. +- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. +- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values: + - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. + - `false` - logging is disabled. + + +##### Referenced schema options + +- _schemaId_: this option defines which keywords are used as schema URI. Option value: + - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). + - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). + - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. +- _missingRefs_: handling of missing referenced schemas. Option values: + - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). + - `"ignore"` - to log error during compilation and always pass validation. + - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. +- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: + - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. + - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. + - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). +- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). + + +##### Options to modify validated data + +- _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: + - `false` (default) - not to remove additional properties + - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). + - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. + - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). +- _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: + - `false` (default) - do not use defaults + - `true` - insert defaults by value (object literal is used). + - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). + - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. +- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values: + - `false` (default) - no type coercion. + - `true` - coerce scalar data types. + - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). + + +##### Strict mode options + +- _strictDefaults_: report ignored `default` keywords in schemas. Option values: + - `false` (default) - ignored defaults are not reported + - `true` - if an ignored default is present, throw an error + - `"log"` - if an ignored default is present, log warning +- _strictKeywords_: report unknown keywords in schemas. Option values: + - `false` (default) - unknown keywords are not reported + - `true` - if an unknown keyword is present, throw an error + - `"log"` - if an unknown keyword is present, log warning + + +##### Asynchronous validation options + +- _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: + - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. + - `true` - always transpile with nodent. + - `false` - do not transpile; if async functions are not supported an exception will be thrown. + + +##### Advanced options + +- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. +- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: + - `true` (default) - if the validation fails, throw the exception. + - `"log"` - if the validation fails, log error. + - `false` - skip schema validation. +- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. +- _inlineRefs_: Affects compilation of referenced schemas. Option values: + - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. + - `false` - to not inline referenced schemas (they will be compiled as separate functions). + - integer number - to limit the maximum number of keywords of the schema that will be inlined. +- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. +- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. +- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. +- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). +- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. +- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)). +- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). +- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: + - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass `require('js-beautify').js_beautify`. + - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/epoberezkin/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. +- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. +- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. + + +## Validation errors + +In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. + + +### Error objects + +Each error is an object with the following properties: + +- _keyword_: validation keyword. +- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). +- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. +- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package). See below for parameters set by all keywords. +- _message_: the standard error message (can be excluded with option `messages` set to false). +- _schema_: the schema of the keyword (added with `verbose` option). +- _parentSchema_: the schema containing the keyword (added with `verbose` option) +- _data_: the data validated by the keyword (added with `verbose` option). + +__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. + + +### Error parameters + +Properties of `params` object in errors depend on the keyword that failed validation. + +- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). +- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). +- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). +- `dependencies` - properties: + - `property` (dependent property), + - `missingProperty` (required missing dependency - only the first one is reported currently) + - `deps` (required dependencies, comma separated list as a string), + - `depsCount` (the number of required dependencies). +- `format` - property `format` (the schema of the keyword). +- `maximum`, `minimum` - properties: + - `limit` (number, the schema of the keyword), + - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), + - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") +- `multipleOf` - property `multipleOf` (the schema of the keyword) +- `pattern` - property `pattern` (the schema of the keyword) +- `required` - property `missingProperty` (required property that is missing). +- `propertyNames` - property `propertyName` (an invalid property name). +- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). +- `type` - property `type` (required type(s), a string, can be a comma-separated list) +- `uniqueItems` - properties `i` and `j` (indices of duplicate items). +- `const` - property `allowedValue` pointing to the value (the schema of the keyword). +- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). +- `$ref` - property `ref` with the referenced schema URI. +- `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). +- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). + + +## Plugins + +Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: + +- it exports a function +- this function accepts ajv instance as the first parameter and returns the same instance to allow chaining +- this function can accept an optional configuration as the second parameter + +If you have published a useful plugin please submit a PR to add it to the next section. + + +## Related packages + +- [ajv-async](https://github.com/epoberezkin/ajv-async) - plugin to configure async validation mode +- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats +- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface +- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - plugin for custom error messages +- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages +- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas +- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) +- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch +- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions + + +## Some packages using Ajv + +- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser +- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services +- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition +- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator +- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org +- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com +- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js +- [table](https://github.com/gajus/table) - formats data into a string table +- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser +- [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content +- [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation +- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation +- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages +- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema +- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests +- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema +- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file +- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app +- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter +- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages +- [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX + + +## Tests + +``` +npm install +git submodule update --init +npm test +``` + +## Contributing + +All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. + +`npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder. + +`npm run watch` - automatically compiles templates when files in dot folder change + +Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md) + + +## Changes history + +See https://github.com/epoberezkin/ajv/releases + +__Please note__: [Changes in version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0). + +[Version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0). + +[Version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0). + +[Version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0). + +[Version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0). + + +## License + +[MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE) diff --git a/node_modules/ajv/lib/.DS_Store b/node_modules/ajv/lib/.DS_Store new file mode 100644 index 0000000..1efcc8f Binary files /dev/null and b/node_modules/ajv/lib/.DS_Store differ diff --git a/node_modules/ajv/lib/ajv.d.ts b/node_modules/ajv/lib/ajv.d.ts new file mode 100644 index 0000000..63f110a --- /dev/null +++ b/node_modules/ajv/lib/ajv.d.ts @@ -0,0 +1,389 @@ +declare var ajv: { + (options?: ajv.Options): ajv.Ajv; + new(options?: ajv.Options): ajv.Ajv; + ValidationError: typeof AjvErrors.ValidationError; + MissingRefError: typeof AjvErrors.MissingRefError; + $dataMetaSchema: object; +} + +declare namespace AjvErrors { + class ValidationError extends Error { + constructor(errors: Array); + + message: string; + errors: Array; + ajv: true; + validation: true; + } + + class MissingRefError extends Error { + constructor(baseId: string, ref: string, message?: string); + static message: (baseId: string, ref: string) => string; + + message: string; + missingRef: string; + missingSchema: string; + } +} + +declare namespace ajv { + type ValidationError = AjvErrors.ValidationError; + + type MissingRefError = AjvErrors.MissingRefError; + + interface Ajv { + /** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default). + * @param {string|object|Boolean} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ + validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike; + /** + * Create validating function for passed schema. + * @param {object|Boolean} schema schema object + * @return {Function} validating function + */ + compile(schema: object | boolean): ValidateFunction; + /** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and node-style callback. + * @this Ajv + * @param {object|Boolean} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function. + * @return {PromiseLike} validating function + */ + compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike; + /** + * Adds schema to the instance. + * @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @return {Ajv} this for method chaining + */ + addSchema(schema: Array | object, key?: string): Ajv; + /** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @param {object} schema schema object + * @param {string} key optional schema key + * @return {Ajv} this for method chaining + */ + addMetaSchema(schema: object, key?: string): Ajv; + /** + * Validate schema + * @param {object|Boolean} schema schema to validate + * @return {Boolean} true if schema is valid + */ + validateSchema(schema: object | boolean): boolean; + /** + * Get compiled schema from the instance by `key` or `ref`. + * @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). + */ + getSchema(keyRef: string): ValidateFunction; + /** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining + */ + removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv; + /** + * Add custom format + * @param {string} name format name + * @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + * @return {Ajv} this for method chaining + */ + addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv; + /** + * Define custom keyword + * @this Ajv + * @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords. + * @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ + addKeyword(keyword: string, definition: KeywordDefinition): Ajv; + /** + * Get keyword definition + * @this Ajv + * @param {string} keyword pre-defined or custom keyword. + * @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ + getKeyword(keyword: string): object | boolean; + /** + * Remove keyword + * @this Ajv + * @param {string} keyword pre-defined or custom keyword. + * @return {Ajv} this for method chaining + */ + removeKeyword(keyword: string): Ajv; + /** + * Validate keyword + * @this Ajv + * @param {object} definition keyword definition object + * @param {boolean} throwError true to throw exception if definition is invalid + * @return {boolean} validation result + */ + validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean; + /** + * Convert array of error message objects to string + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {object} options optional options with properties `separator` and `dataVar`. + * @return {string} human readable string with all errors descriptions + */ + errorsText(errors?: Array | null, options?: ErrorsTextOptions): string; + errors?: Array | null; + } + + interface CustomLogger { + log(...args: any[]): any; + warn(...args: any[]): any; + error(...args: any[]): any; + } + + interface ValidateFunction { + ( + data: any, + dataPath?: string, + parentData?: object | Array, + parentDataProperty?: string | number, + rootData?: object | Array + ): boolean | PromiseLike; + schema?: object | boolean; + errors?: null | Array; + refs?: object; + refVal?: Array; + root?: ValidateFunction | object; + $async?: true; + source?: object; + } + + interface Options { + $data?: boolean; + allErrors?: boolean; + verbose?: boolean; + jsonPointers?: boolean; + uniqueItems?: boolean; + unicode?: boolean; + format?: string; + formats?: object; + unknownFormats?: true | string[] | 'ignore'; + schemas?: Array | object; + schemaId?: '$id' | 'id' | 'auto'; + missingRefs?: true | 'ignore' | 'fail'; + extendRefs?: true | 'ignore' | 'fail'; + loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike; + removeAdditional?: boolean | 'all' | 'failing'; + useDefaults?: boolean | 'shared'; + coerceTypes?: boolean | 'array'; + strictDefaults?: boolean | 'log'; + async?: boolean | string; + transpile?: string | ((code: string) => string); + meta?: boolean | object; + validateSchema?: boolean | 'log'; + addUsedSchema?: boolean; + inlineRefs?: boolean | number; + passContext?: boolean; + loopRequired?: number; + ownProperties?: boolean; + multipleOfPrecision?: boolean | number; + errorDataPath?: string, + messages?: boolean; + sourceCode?: boolean; + processCode?: (code: string) => string; + cache?: object; + logger?: CustomLogger | false; + nullable?: boolean; + serialize?: ((schema: object | boolean) => any) | false; + } + + type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike); + type NumberFormatValidator = ((data: number) => boolean | PromiseLike); + + interface NumberFormatDefinition { + type: "number", + validate: NumberFormatValidator; + compare?: (data1: number, data2: number) => number; + async?: boolean; + } + + interface StringFormatDefinition { + type?: "string", + validate: FormatValidator; + compare?: (data1: string, data2: string) => number; + async?: boolean; + } + + type FormatDefinition = NumberFormatDefinition | StringFormatDefinition; + + interface KeywordDefinition { + type?: string | Array; + async?: boolean; + $data?: boolean; + errors?: boolean | string; + metaSchema?: object; + // schema: false makes validate not to expect schema (ValidateFunction) + schema?: boolean; + statements?: boolean; + dependencies?: Array; + modifying?: boolean; + valid?: boolean; + // one and only one of the following properties should be present + validate?: SchemaValidateFunction | ValidateFunction; + compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction; + macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean; + inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string; + } + + interface CompilationContext { + level: number; + dataLevel: number; + schema: any; + schemaPath: string; + baseId: string; + async: boolean; + opts: Options; + formats: { + [index: string]: FormatDefinition | undefined; + }; + compositeRule: boolean; + validate: (schema: object) => boolean; + util: { + copy(obj: any, target?: any): any; + toHash(source: string[]): { [index: string]: true | undefined }; + equal(obj: any, target: any): boolean; + getProperty(str: string): string; + schemaHasRules(schema: object, rules: any): string; + escapeQuotes(str: string): string; + toQuotedString(str: string): string; + getData(jsonPointer: string, dataLevel: number, paths: string[]): string; + escapeJsonPointer(str: string): string; + unescapeJsonPointer(str: string): string; + escapeFragment(str: string): string; + unescapeFragment(str: string): string; + }; + self: Ajv; + } + + interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: object, + dataPath?: string, + parentData?: object | Array, + parentDataProperty?: string | number, + rootData?: object | Array + ): boolean | PromiseLike; + errors?: Array; + } + + interface ErrorsTextOptions { + separator?: string; + dataVar?: string; + } + + interface ErrorObject { + keyword: string; + dataPath: string; + schemaPath: string; + params: ErrorParameters; + // Added to validation errors of propertyNames keyword schema + propertyName?: string; + // Excluded if messages set to false. + message?: string; + // These are added with the `verbose` option. + schema?: any; + parentSchema?: object; + data?: any; + } + + type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | + DependenciesParams | FormatParams | ComparisonParams | + MultipleOfParams | PatternParams | RequiredParams | + TypeParams | UniqueItemsParams | CustomParams | + PatternRequiredParams | PropertyNamesParams | + IfParams | SwitchParams | NoParams | EnumParams; + + interface RefParams { + ref: string; + } + + interface LimitParams { + limit: number; + } + + interface AdditionalPropertiesParams { + additionalProperty: string; + } + + interface DependenciesParams { + property: string; + missingProperty: string; + depsCount: number; + deps: string; + } + + interface FormatParams { + format: string + } + + interface ComparisonParams { + comparison: string; + limit: number | string; + exclusive: boolean; + } + + interface MultipleOfParams { + multipleOf: number; + } + + interface PatternParams { + pattern: string; + } + + interface RequiredParams { + missingProperty: string; + } + + interface TypeParams { + type: string; + } + + interface UniqueItemsParams { + i: number; + j: number; + } + + interface CustomParams { + keyword: string; + } + + interface PatternRequiredParams { + missingPattern: string; + } + + interface PropertyNamesParams { + propertyName: string; + } + + interface IfParams { + failingKeyword: string; + } + + interface SwitchParams { + caseIndex: number; + } + + interface NoParams { } + + interface EnumParams { + allowedValues: Array; + } +} + +export = ajv; diff --git a/node_modules/ajv/lib/ajv.js b/node_modules/ajv/lib/ajv.js new file mode 100644 index 0000000..611b938 --- /dev/null +++ b/node_modules/ajv/lib/ajv.js @@ -0,0 +1,497 @@ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('fast-json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , $dataMetaSchema = require('./data') + , util = require('./compile/util'); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = require('./compile/async'); +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = require('./compile/error_classes'); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} + + + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} + + +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} + + +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: hostname, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +function hostname(str) { + // https://tools.ietf.org/html/rfc1034#section-3.5 + // https://tools.ietf.org/html/rfc1123#section-2 + return str.length <= 255 && HOSTNAME.test(str); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} diff --git a/node_modules/ajv/lib/compile/index.js b/node_modules/ajv/lib/compile/index.js new file mode 100644 index 0000000..f4d3f0d --- /dev/null +++ b/node_modules/ajv/lib/compile/index.js @@ -0,0 +1,387 @@ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , errorClasses = require('./error_classes') + , stableStringify = require('fast-json-stable-stringify'); + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = require('fast-deep-equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; diff --git a/node_modules/ajv/lib/compile/util.js b/node_modules/ajv/lib/compile/util.js new file mode 100644 index 0000000..0efa001 --- /dev/null +++ b/node_modules/ajv/lib/compile/util.js @@ -0,0 +1,274 @@ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + cleanUpCode: cleanUpCode, + finalCleanUpCode: finalCleanUpCode, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i' + , $notOp = $isMax ? '>' : '<' + , $errorKeyword = undefined; +}} + +{{? $isDataExcl }} + {{ + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) + , $exclusive = 'exclusive' + $lvl + , $exclType = 'exclType' + $lvl + , $exclIsNumber = 'exclIsNumber' + $lvl + , $opExpr = 'op' + $lvl + , $opStr = '\' + ' + $opExpr + ' + \''; + }} + var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; + {{ $schemaValueExcl = 'schemaExcl' + $lvl; }} + + var {{=$exclusive}}; + var {{=$exclType}} = typeof {{=$schemaValueExcl}}; + if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') { + {{ var $errorKeyword = $exclusiveKeyword; }} + {{# def.error:'_exclusiveLimit' }} + } else if ({{# def.$dataNotType:'number' }} + {{=$exclType}} == 'number' + ? ( + ({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}}) + ? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} + ) + : ( + ({{=$exclusive}} = {{=$schemaValueExcl}} === true) + ? {{=$data}} {{=$notOp}}= {{=$schemaValue}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} + ) + || {{=$data}} !== {{=$data}}) { + var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; + {{ + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + }} +{{??}} + {{ + var $exclIsNumber = typeof $schemaExcl == 'number' + , $opStr = $op; /*used in error*/ + }} + + {{? $exclIsNumber && $isData }} + {{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }} + if ({{# def.$dataNotType:'number' }} + ( {{=$schemaValue}} === undefined + || {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}} + ? {{=$data}} {{=$notOp}}= {{=$schemaExcl}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} ) + || {{=$data}} !== {{=$data}}) { + {{??}} + {{ + if ($exclIsNumber && $schema === undefined) { + {{# def.setExclusiveLimit }} + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) + $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + {{# def.setExclusiveLimit }} + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + + var $opExpr = '\'' + $opStr + '\''; /*used in error*/ + }} + + if ({{# def.$dataNotType:'number' }} + {{=$data}} {{=$notOp}} {{=$schemaValue}} + || {{=$data}} !== {{=$data}}) { + {{?}} +{{?}} + {{ $errorKeyword = $errorKeyword || $keyword; }} + {{# def.error:'_limit' }} + } {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/_limitItems.jst b/node_modules/ajv/lib/dot/_limitItems.jst new file mode 100644 index 0000000..a3e078e --- /dev/null +++ b/node_modules/ajv/lib/dot/_limitItems.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitItems' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/_limitLength.jst b/node_modules/ajv/lib/dot/_limitLength.jst new file mode 100644 index 0000000..cfc8dbb --- /dev/null +++ b/node_modules/ajv/lib/dot/_limitLength.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitLength' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/_limitProperties.jst b/node_modules/ajv/lib/dot/_limitProperties.jst new file mode 100644 index 0000000..da7ea77 --- /dev/null +++ b/node_modules/ajv/lib/dot/_limitProperties.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitProperties' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/allOf.jst b/node_modules/ajv/lib/dot/allOf.jst new file mode 100644 index 0000000..4c28363 --- /dev/null +++ b/node_modules/ajv/lib/dot/allOf.jst @@ -0,0 +1,34 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $allSchemasEmpty = true; +}} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{# def.ifResultValid }} + {{?}} +{{~}} + +{{? $breakOnError }} + {{? $allSchemasEmpty }} + if (true) { + {{??}} + {{= $closingBraces.slice(0,-1) }} + {{?}} +{{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/anyOf.jst b/node_modules/ajv/lib/dot/anyOf.jst new file mode 100644 index 0000000..086cf2b --- /dev/null +++ b/node_modules/ajv/lib/dot/anyOf.jst @@ -0,0 +1,48 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $noEmptySchema = $schema.every(function($sch) { + return {{# def.nonEmptySchema:$sch }}; + }); +}} +{{? $noEmptySchema }} + {{ var $currentBaseId = $it.baseId; }} + var {{=$errs}} = errors; + var {{=$valid}} = false; + + {{# def.setCompositeRule }} + + {{~ $schema:$sch:$i }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{=$valid}} = {{=$valid}} || {{=$nextValid}}; + + if (!{{=$valid}}) { + {{ $closingBraces += '}'; }} + {{~}} + + {{# def.resetCompositeRule }} + + {{= $closingBraces }} + + if (!{{=$valid}}) { + {{# def.extraError:'anyOf' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} + + {{# def.cleanUp }} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/coerce.def b/node_modules/ajv/lib/dot/coerce.def new file mode 100644 index 0000000..86e0e18 --- /dev/null +++ b/node_modules/ajv/lib/dot/coerce.def @@ -0,0 +1,61 @@ +{{## def.coerceType: + {{ + var $dataType = 'dataType' + $lvl + , $coerced = 'coerced' + $lvl; + }} + var {{=$dataType}} = typeof {{=$data}}; + {{? it.opts.coerceTypes == 'array'}} + if ({{=$dataType}} == 'object' && Array.isArray({{=$data}})) {{=$dataType}} = 'array'; + {{?}} + + var {{=$coerced}} = undefined; + + {{ var $bracesCoercion = ''; }} + {{~ $coerceToTypes:$type:$i }} + {{? $i }} + if ({{=$coerced}} === undefined) { + {{ $bracesCoercion += '}'; }} + {{?}} + + {{? it.opts.coerceTypes == 'array' && $type != 'array' }} + if ({{=$dataType}} == 'array' && {{=$data}}.length == 1) { + {{=$coerced}} = {{=$data}} = {{=$data}}[0]; + {{=$dataType}} = typeof {{=$data}}; + /*if ({{=$dataType}} == 'object' && Array.isArray({{=$data}})) {{=$dataType}} = 'array';*/ + } + {{?}} + + {{? $type == 'string' }} + if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean') + {{=$coerced}} = '' + {{=$data}}; + else if ({{=$data}} === null) {{=$coerced}} = ''; + {{?? $type == 'number' || $type == 'integer' }} + if ({{=$dataType}} == 'boolean' || {{=$data}} === null + || ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}} + {{? $type == 'integer' }} && !({{=$data}} % 1){{?}})) + {{=$coerced}} = +{{=$data}}; + {{?? $type == 'boolean' }} + if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null) + {{=$coerced}} = false; + else if ({{=$data}} === 'true' || {{=$data}} === 1) + {{=$coerced}} = true; + {{?? $type == 'null' }} + if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false) + {{=$coerced}} = null; + {{?? it.opts.coerceTypes == 'array' && $type == 'array' }} + if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null) + {{=$coerced}} = [{{=$data}}]; + {{?}} + {{~}} + + {{= $bracesCoercion }} + + if ({{=$coerced}} === undefined) { + {{# def.error:'type' }} + } else { + {{# def.setParentData }} + {{=$data}} = {{=$coerced}}; + {{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}} + {{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}}; + } +#}} diff --git a/node_modules/ajv/lib/dot/comment.jst b/node_modules/ajv/lib/dot/comment.jst new file mode 100644 index 0000000..f959150 --- /dev/null +++ b/node_modules/ajv/lib/dot/comment.jst @@ -0,0 +1,9 @@ +{{# def.definitions }} +{{# def.setupKeyword }} + +{{ var $comment = it.util.toQuotedString($schema); }} +{{? it.opts.$comment === true }} + console.log({{=$comment}}); +{{?? typeof it.opts.$comment == 'function' }} + self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema); +{{?}} diff --git a/node_modules/ajv/lib/dot/const.jst b/node_modules/ajv/lib/dot/const.jst new file mode 100644 index 0000000..2aa2298 --- /dev/null +++ b/node_modules/ajv/lib/dot/const.jst @@ -0,0 +1,11 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{? !$isData }} + var schema{{=$lvl}} = validate.schema{{=$schemaPath}}; +{{?}} +var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}}); +{{# def.checkError:'const' }} +{{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/contains.jst b/node_modules/ajv/lib/dot/contains.jst new file mode 100644 index 0000000..925d2c8 --- /dev/null +++ b/node_modules/ajv/lib/dot/contains.jst @@ -0,0 +1,57 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{ + var $idx = 'i' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $currentBaseId = it.baseId + , $nonEmptySchema = {{# def.nonEmptySchema:$schema }}; +}} + +var {{=$errs}} = errors; +var {{=$valid}}; + +{{? $nonEmptySchema }} + {{# def.setCompositeRule }} + + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$nextValid}} = false; + + for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + if ({{=$nextValid}}) break; + } + + {{# def.resetCompositeRule }} + {{= $closingBraces }} + + if (!{{=$nextValid}}) { +{{??}} + if ({{=$data}}.length == 0) { +{{?}} + + {{# def.error:'contains' }} + } else { + {{? $nonEmptySchema }} + {{# def.resetErrors }} + {{?}} + {{? it.opts.allErrors }} } {{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/custom.jst b/node_modules/ajv/lib/dot/custom.jst new file mode 100644 index 0000000..d30588f --- /dev/null +++ b/node_modules/ajv/lib/dot/custom.jst @@ -0,0 +1,191 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $rule = this + , $definition = 'definition' + $lvl + , $rDef = $rule.definition + , $closingBraces = ''; + var $validate = $rDef.validate; + var $compile, $inline, $macro, $ruleValidate, $validateCode; +}} + +{{? $isData && $rDef.$data }} + {{ + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + }} + var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition; + var {{=$validateCode}} = {{=$definition}}.validate; +{{??}} + {{ + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + }} +{{?}} + +{{ + var $ruleErrs = $validateCode + '.errors' + , $i = 'i' + $lvl + , $ruleErr = 'ruleErr' + $lvl + , $asyncKeyword = $rDef.async; + + if ($asyncKeyword && !it.async) + throw new Error('async keyword in sync schema'); +}} + + +{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}} +var {{=$errs}} = errors; +var {{=$valid}}; + +{{## def.callRuleValidate: + {{=$validateCode}}.call( + {{? it.opts.passContext }}this{{??}}self{{?}} + {{? $compile || $rDef.schema === false }} + , {{=$data}} + {{??}} + , {{=$schemaValue}} + , {{=$data}} + , validate.schema{{=it.schemaPath}} + {{?}} + , {{# def.dataPath }} + {{# def.passParentData }} + , rootData + ) +#}} + +{{## def.extendErrors:_inline: + for (var {{=$i}}={{=$errs}}; {{=$i}}= 0 }} + {{# def.skipFormat }} + {{??}} + {{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }} + {{?}} + {{?}} + {{ + var $isObject = typeof $format == 'object' + && !($format instanceof RegExp) + && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + }} + {{? $formatType != $ruleType }} + {{# def.skipFormat }} + {{?}} + {{? $async }} + {{ + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + }} + if (!(await {{=$formatRef}}({{=$data}}))) { + {{??}} + if (!{{# def.checkFormat }}) { + {{?}} +{{?}} + {{# def.error:'format' }} + } {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/if.jst b/node_modules/ajv/lib/dot/if.jst new file mode 100644 index 0000000..7ccc9b7 --- /dev/null +++ b/node_modules/ajv/lib/dot/if.jst @@ -0,0 +1,75 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateIfClause:_clause: + {{ + $it.schema = it.schema['_clause']; + $it.schemaPath = it.schemaPath + '._clause'; + $it.errSchemaPath = it.errSchemaPath + '/_clause'; + }} + {{# def.insertSubschemaCode }} + {{=$valid}} = {{=$nextValid}}; + {{? $thenPresent && $elsePresent }} + {{ $ifClause = 'ifClause' + $lvl; }} + var {{=$ifClause}} = '_clause'; + {{??}} + {{ $ifClause = '\'_clause\''; }} + {{?}} +#}} + +{{ + var $thenSch = it.schema['then'] + , $elseSch = it.schema['else'] + , $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }} + , $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }} + , $currentBaseId = $it.baseId; +}} + +{{? $thenPresent || $elsePresent }} + {{ + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + var {{=$errs}} = errors; + var {{=$valid}} = true; + + {{# def.setCompositeRule }} + {{# def.insertSubschemaCode }} + {{ $it.createErrors = true; }} + {{# def.resetErrors }} + {{# def.resetCompositeRule }} + + {{? $thenPresent }} + if ({{=$nextValid}}) { + {{# def.validateIfClause:then }} + } + {{? $elsePresent }} + else { + {{?}} + {{??}} + if (!{{=$nextValid}}) { + {{?}} + + {{? $elsePresent }} + {{# def.validateIfClause:else }} + } + {{?}} + + if (!{{=$valid}}) { + {{# def.extraError:'if' }} + } + {{? $breakOnError }} else { {{?}} + + {{# def.cleanUp }} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} + diff --git a/node_modules/ajv/lib/dot/items.jst b/node_modules/ajv/lib/dot/items.jst new file mode 100644 index 0000000..8c0f5ac --- /dev/null +++ b/node_modules/ajv/lib/dot/items.jst @@ -0,0 +1,100 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateItems:startFrom: + for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} + if (!{{=$nextValid}}) break; + {{?}} + } +#}} + +{{ + var $idx = 'i' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $currentBaseId = it.baseId; +}} + +var {{=$errs}} = errors; +var {{=$valid}}; + +{{? Array.isArray($schema) }} + {{ /* 'items' is an array of schemas */}} + {{ var $additionalItems = it.schema.additionalItems; }} + {{? $additionalItems === false }} + {{=$valid}} = {{=$data}}.length <= {{= $schema.length }}; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{# def.checkError:'additionalItems' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{# def.elseIfValid}} + {{?}} + + {{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{=$i}}) { + {{ + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + } + + {{# def.ifResultValid }} + {{?}} + {{~}} + + {{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }} + {{ + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{= $schema.length }}) { + {{# def.validateItems: $schema.length }} + } + + {{# def.ifResultValid }} + {{?}} + +{{?? {{# def.nonEmptySchema:$schema }} }} + {{ /* 'items' is a single schema */}} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + {{# def.validateItems: 0 }} +{{?}} + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/missing.def b/node_modules/ajv/lib/dot/missing.def new file mode 100644 index 0000000..a73b9f9 --- /dev/null +++ b/node_modules/ajv/lib/dot/missing.def @@ -0,0 +1,39 @@ +{{## def.checkMissingProperty:_properties: + {{~ _properties:$propertyKey:$i }} + {{?$i}} || {{?}} + {{ + var $prop = it.util.getProperty($propertyKey) + , $useData = $data + $prop; + }} + ( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) ) + {{~}} +#}} + + +{{## def.errorMissingProperty:_error: + {{ + var $propertyPath = 'missing' + $lvl + , $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers + ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) + : $currentErrorPath + ' + ' + $propertyPath; + } + }} + {{# def.error:_error }} +#}} + + +{{## def.allErrorsMissingProperty:_error: + {{ + var $prop = it.util.getProperty($propertyKey) + , $missingProperty = it.util.escapeQuotes($propertyKey) + , $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + }} + if ({{# def.noPropertyInData }}) { + {{# def.addError:_error }} + } +#}} diff --git a/node_modules/ajv/lib/dot/multipleOf.jst b/node_modules/ajv/lib/dot/multipleOf.jst new file mode 100644 index 0000000..5f8dd33 --- /dev/null +++ b/node_modules/ajv/lib/dot/multipleOf.jst @@ -0,0 +1,20 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +var division{{=$lvl}}; +if ({{?$isData}} + {{=$schemaValue}} !== undefined && ( + typeof {{=$schemaValue}} != 'number' || + {{?}} + (division{{=$lvl}} = {{=$data}} / {{=$schemaValue}}, + {{? it.opts.multipleOfPrecision }} + Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}} + {{??}} + division{{=$lvl}} !== parseInt(division{{=$lvl}}) + {{?}} + ) + {{?$isData}} ) {{?}} ) { + {{# def.error:'multipleOf' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/not.jst b/node_modules/ajv/lib/dot/not.jst new file mode 100644 index 0000000..e03185a --- /dev/null +++ b/node_modules/ajv/lib/dot/not.jst @@ -0,0 +1,43 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$errs}} = errors; + + {{# def.setCompositeRule }} + + {{ + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + }} + {{= it.validate($it) }} + {{ + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + }} + + {{# def.resetCompositeRule }} + + if ({{=$nextValid}}) { + {{# def.error:'not' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} +{{??}} + {{# def.addError:'not' }} + {{? $breakOnError}} + if (false) { + {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/oneOf.jst b/node_modules/ajv/lib/dot/oneOf.jst new file mode 100644 index 0000000..bcce2c6 --- /dev/null +++ b/node_modules/ajv/lib/dot/oneOf.jst @@ -0,0 +1,54 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $prevValid = 'prevValid' + $lvl + , $passingSchemas = 'passingSchemas' + $lvl; +}} + +var {{=$errs}} = errors + , {{=$prevValid}} = false + , {{=$valid}} = false + , {{=$passingSchemas}} = null; + +{{# def.setCompositeRule }} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + {{??}} + var {{=$nextValid}} = true; + {{?}} + + {{? $i }} + if ({{=$nextValid}} && {{=$prevValid}}) { + {{=$valid}} = false; + {{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}]; + } else { + {{ $closingBraces += '}'; }} + {{?}} + + if ({{=$nextValid}}) { + {{=$valid}} = {{=$prevValid}} = true; + {{=$passingSchemas}} = {{=$i}}; + } +{{~}} + +{{# def.resetCompositeRule }} + +{{= $closingBraces }} + +if (!{{=$valid}}) { + {{# def.extraError:'oneOf' }} +} else { + {{# def.resetErrors }} +{{? it.opts.allErrors }} } {{?}} diff --git a/node_modules/ajv/lib/dot/pattern.jst b/node_modules/ajv/lib/dot/pattern.jst new file mode 100644 index 0000000..3a37ef6 --- /dev/null +++ b/node_modules/ajv/lib/dot/pattern.jst @@ -0,0 +1,14 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $regexp = $isData + ? '(new RegExp(' + $schemaValue + '))' + : it.usePattern($schema); +}} + +if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) { + {{# def.error:'pattern' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/properties.jst b/node_modules/ajv/lib/dot/properties.jst new file mode 100644 index 0000000..862067e --- /dev/null +++ b/node_modules/ajv/lib/dot/properties.jst @@ -0,0 +1,244 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateAdditional: + {{ /* additionalProperties is schema */ + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty + ? it.errorPath + : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} +#}} + + +{{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $dataProperties = 'dataProperties' + $lvl; + + var $schemaKeys = Object.keys($schema || {}) + , $pProperties = it.schema.patternProperties || {} + , $pPropertyKeys = Object.keys($pProperties) + , $aProperties = it.schema.additionalProperties + , $someProperties = $schemaKeys.length || $pPropertyKeys.length + , $noAdditional = $aProperties === false + , $additionalIsSchema = typeof $aProperties == 'object' + && Object.keys($aProperties).length + , $removeAdditional = it.opts.removeAdditional + , $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) + var $requiredHash = it.util.toHash($required); +}} + + +var {{=$errs}} = errors; +var {{=$nextValid}} = true; +{{? $ownProperties }} + var {{=$dataProperties}} = undefined; +{{?}} + +{{? $checkAdditional }} + {{# def.iterateProperties }} + {{? $someProperties }} + var isAdditional{{=$lvl}} = !(false + {{? $schemaKeys.length }} + {{? $schemaKeys.length > 8 }} + || validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}}) + {{??}} + {{~ $schemaKeys:$propertyKey }} + || {{=$key}} == {{= it.util.toQuotedString($propertyKey) }} + {{~}} + {{?}} + {{?}} + {{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty:$i }} + || {{= it.usePattern($pProperty) }}.test({{=$key}}) + {{~}} + {{?}} + ); + + if (isAdditional{{=$lvl}}) { + {{?}} + {{? $removeAdditional == 'all' }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{ + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + }} + {{? $noAdditional }} + {{? $removeAdditional }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{=$nextValid}} = false; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + }} + {{# def.error:'additionalProperties' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{? $breakOnError }} break; {{?}} + {{?}} + {{?? $additionalIsSchema }} + {{? $removeAdditional == 'failing' }} + var {{=$errs}} = errors; + {{# def.setCompositeRule }} + + {{# def.validateAdditional }} + + if (!{{=$nextValid}}) { + errors = {{=$errs}}; + if (validate.errors !== null) { + if (errors) validate.errors.length = errors; + else validate.errors = null; + } + delete {{=$data}}[{{=$key}}]; + } + + {{# def.resetCompositeRule }} + {{??}} + {{# def.validateAdditional }} + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + {{?}} + {{?}} + {{ it.errorPath = $currentErrorPath; }} + {{?}} + {{? $someProperties }} + } + {{?}} + } + + {{# def.ifResultValid }} +{{?}} + +{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }} + +{{? $schemaKeys.length }} + {{~ $schemaKeys:$propertyKey }} + {{ var $sch = $schema[$propertyKey]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + var $prop = it.util.getProperty($propertyKey) + , $passData = $data + $prop + , $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + }} + + {{# def.generateSubschemaCode }} + + {{? {{# def.willOptimize }} }} + {{ + $code = {{# def._optimizeValidate }}; + var $useData = $passData; + }} + {{??}} + {{ var $useData = $nextData; }} + var {{=$nextData}} = {{=$passData}}; + {{?}} + + {{? $hasDefault }} + {{= $code }} + {{??}} + {{? $requiredHash && $requiredHash[$propertyKey] }} + if ({{# def.noPropertyInData }}) { + {{=$nextValid}} = false; + {{ + var $currentErrorPath = it.errorPath + , $currErrSchemaPath = $errSchemaPath + , $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + }} + {{# def.error:'required' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{ it.errorPath = $currentErrorPath; }} + } else { + {{??}} + {{? $breakOnError }} + if ({{# def.noPropertyInData }}) { + {{=$nextValid}} = true; + } else { + {{??}} + if ({{=$useData}} !== undefined + {{? $ownProperties }} + && {{# def.isOwnProperty }} + {{?}} + ) { + {{?}} + {{?}} + + {{= $code }} + } + {{?}} {{ /* $hasDefault */ }} + {{?}} {{ /* def.nonEmptySchema */ }} + + {{# def.ifResultValid }} + {{~}} +{{?}} + +{{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty }} + {{ var $sch = $pProperties[$pProperty]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + + it.util.escapeFragment($pProperty); + }} + + {{# def.iterateProperties }} + if ({{= it.usePattern($pProperty) }}.test({{=$key}})) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + } + {{? $breakOnError }} else {{=$nextValid}} = true; {{?}} + } + + {{# def.ifResultValid }} + {{?}} {{ /* def.nonEmptySchema */ }} + {{~}} +{{?}} + + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/propertyNames.jst b/node_modules/ajv/lib/dot/propertyNames.jst new file mode 100644 index 0000000..ee52b21 --- /dev/null +++ b/node_modules/ajv/lib/dot/propertyNames.jst @@ -0,0 +1,54 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +var {{=$errs}} = errors; + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + {{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $i = 'i' + $lvl + , $invalidName = '\' + ' + $key + ' + \'' + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $dataProperties = 'dataProperties' + $lvl + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + }} + + {{? $ownProperties }} + var {{=$dataProperties}} = undefined; + {{?}} + {{# def.iterateProperties }} + var startErrs{{=$lvl}} = errors; + + {{ var $passData = $key; }} + {{# def.setCompositeRule }} + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + {{# def.resetCompositeRule }} + + if (!{{=$nextValid}}) { + for (var {{=$i}}=startErrs{{=$lvl}}; {{=$i}}= it.opts.loopRequired + , $ownProperties = it.opts.ownProperties; + }} + + {{? $breakOnError }} + var missing{{=$lvl}}; + {{? $loopRequired }} + {{# def.setupLoop }} + var {{=$valid}} = true; + + {{?$isData}}{{# def.check$dataIsArray }}{{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + {{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined + {{? $ownProperties }} + && {{# def.isRequiredOwnProperty }} + {{?}}; + if (!{{=$valid}}) break; + } + + {{? $isData }} } {{?}} + + {{# def.checkError:'required' }} + else { + {{??}} + if ({{# def.checkMissingProperty:$required }}) { + {{# def.errorMissingProperty:'required' }} + } else { + {{?}} + {{??}} + {{? $loopRequired }} + {{# def.setupLoop }} + {{? $isData }} + if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) { + {{# def.addError:'required' }} + } else if ({{=$vSchema}} !== undefined) { + {{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined + {{? $ownProperties }} + || !{{# def.isRequiredOwnProperty }} + {{?}}) { + {{# def.addError:'required' }} + } + } + + {{? $isData }} } {{?}} + {{??}} + {{~ $required:$propertyKey }} + {{# def.allErrorsMissingProperty:'required' }} + {{~}} + {{?}} + {{?}} + + {{ it.errorPath = $currentErrorPath; }} + +{{?? $breakOnError }} + if (true) { +{{?}} diff --git a/node_modules/ajv/lib/dot/uniqueItems.jst b/node_modules/ajv/lib/dot/uniqueItems.jst new file mode 100644 index 0000000..22f82f9 --- /dev/null +++ b/node_modules/ajv/lib/dot/uniqueItems.jst @@ -0,0 +1,62 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + + +{{? ($schema || $isData) && it.opts.uniqueItems !== false }} + {{? $isData }} + var {{=$valid}}; + if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined) + {{=$valid}} = true; + else if (typeof {{=$schemaValue}} != 'boolean') + {{=$valid}} = false; + else { + {{?}} + + var i = {{=$data}}.length + , {{=$valid}} = true + , j; + if (i > 1) { + {{ + var $itemType = it.schema.items && it.schema.items.type + , $typeIsArray = Array.isArray($itemType); + }} + {{? !$itemType || $itemType == 'object' || $itemType == 'array' || + ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }} + outer: + for (;i--;) { + for (j = i; j--;) { + if (equal({{=$data}}[i], {{=$data}}[j])) { + {{=$valid}} = false; + break outer; + } + } + } + {{??}} + var itemIndices = {}, item; + for (;i--;) { + var item = {{=$data}}[i]; + {{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }} + if ({{= it.util[$method]($itemType, 'item', true) }}) continue; + {{? $typeIsArray}} + if (typeof item == 'string') item = '"' + item; + {{?}} + if (typeof itemIndices[item] == 'number') { + {{=$valid}} = false; + j = itemIndices[item]; + break; + } + itemIndices[item] = i; + } + {{?}} + } + + {{? $isData }} } {{?}} + + if (!{{=$valid}}) { + {{# def.error:'uniqueItems' }} + } {{? $breakOnError }} else { {{?}} +{{??}} + {{? $breakOnError }} if (true) { {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/validate.jst b/node_modules/ajv/lib/dot/validate.jst new file mode 100644 index 0000000..f8a1edf --- /dev/null +++ b/node_modules/ajv/lib/dot/validate.jst @@ -0,0 +1,282 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.defaults }} +{{# def.coerce }} + +{{ /** + * schema compilation (render) time: + * it = { schema, RULES, _validate, opts } + * it.validate - this template function, + * it is used recursively to generate code for subschemas + * + * runtime: + * "validate" is a variable name to which this function will be assigned + * validateRef etc. are defined in the parent scope in index.js + */ }} + +{{ + var $async = it.schema.$async === true + , $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref') + , $id = it.self._getId(it.schema); +}} + +{{ + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } +}} + +{{? it.isTop }} + var validate = {{?$async}}{{it.async = true;}}async {{?}}function(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + {{? $id && (it.opts.sourceCode || it.opts.processCode) }} + {{= '/\*# sourceURL=' + $id + ' */' }} + {{?}} +{{?}} + +{{? typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref) }} + {{ var $keyword = 'false schema'; }} + {{# def.setupKeyword }} + {{? it.schema === false}} + {{? it.isTop}} + {{ $breakOnError = true; }} + {{??}} + var {{=$valid}} = false; + {{?}} + {{# def.error:'false schema' }} + {{??}} + {{? it.isTop}} + {{? $async }} + return data; + {{??}} + validate.errors = null; + return true; + {{?}} + {{??}} + var {{=$valid}} = true; + {{?}} + {{?}} + + {{? it.isTop}} + }; + return validate; + {{?}} + + {{ return out; }} +{{?}} + + +{{? it.isTop }} + {{ + var $top = it.isTop + , $lvl = it.level = 0 + , $dataLvl = it.dataLevel = 0 + , $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + + it.dataPathArr = [undefined]; + + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + }} + + var vErrors = null; {{ /* don't edit, used in replace */ }} + var errors = 0; {{ /* don't edit, used in replace */ }} + if (rootData === undefined) rootData = data; {{ /* don't edit, used in replace */ }} +{{??}} + {{ + var $lvl = it.level + , $dataLvl = it.dataLevel + , $data = 'data' + ($dataLvl || ''); + + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + + if ($async && !it.async) throw new Error('async schema in sync schema'); + }} + + var errs_{{=$lvl}} = errors; +{{?}} + +{{ + var $valid = 'valid' + $lvl + , $breakOnError = !it.opts.allErrors + , $closingBraces1 = '' + , $closingBraces2 = ''; + + var $errorKeyword; + var $typeSchema = it.schema.type + , $typeIsArray = Array.isArray($typeSchema); + + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) + $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } +}} + +{{## def.checkType: + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type' + , $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + }} + + if ({{= it.util[$method]($typeSchema, $data, true) }}) { +#}} + +{{? it.schema.$ref && $refKeywords }} + {{? it.opts.extendRefs == 'fail' }} + {{ throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); }} + {{?? it.opts.extendRefs !== true }} + {{ + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + }} + {{?}} +{{?}} + +{{? it.schema.$comment && it.opts.$comment }} + {{= it.RULES.all.$comment.code(it, '$comment') }} +{{?}} + +{{? $typeSchema }} + {{? it.opts.coerceTypes }} + {{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }} + {{?}} + + {{ var $rulesGroup = it.RULES.types[$typeSchema]; }} + {{? $coerceToTypes || $typeIsArray || $rulesGroup === true || + ($rulesGroup && !$shouldUseGroup($rulesGroup)) }} + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.checkType }} + {{? $coerceToTypes }} + {{# def.coerceType }} + {{??}} + {{# def.error:'type' }} + {{?}} + } + {{?}} +{{?}} + + +{{? it.schema.$ref && !$refKeywords }} + {{= it.RULES.all.$ref.code(it, '$ref') }} + {{? $breakOnError }} + } + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} +{{??}} + {{~ it.RULES:$rulesGroup }} + {{? $shouldUseGroup($rulesGroup) }} + {{? $rulesGroup.type }} + if ({{= it.util.checkDataType($rulesGroup.type, $data) }}) { + {{?}} + {{? it.opts.useDefaults }} + {{? $rulesGroup.type == 'object' && it.schema.properties }} + {{# def.defaultProperties }} + {{?? $rulesGroup.type == 'array' && Array.isArray(it.schema.items) }} + {{# def.defaultItems }} + {{?}} + {{?}} + {{~ $rulesGroup.rules:$rule }} + {{? $shouldUseRule($rule) }} + {{ var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); }} + {{? $code }} + {{= $code }} + {{? $breakOnError }} + {{ $closingBraces1 += '}'; }} + {{?}} + {{?}} + {{?}} + {{~}} + {{? $breakOnError }} + {{= $closingBraces1 }} + {{ $closingBraces1 = ''; }} + {{?}} + {{? $rulesGroup.type }} + } + {{? $typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes }} + else { + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.error:'type' }} + } + {{?}} + {{?}} + + {{? $breakOnError }} + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} + {{?}} + {{~}} +{{?}} + +{{? $breakOnError }} {{= $closingBraces2 }} {{?}} + +{{? $top }} + {{? $async }} + if (errors === 0) return data; {{ /* don't edit, used in replace */ }} + else throw new ValidationError(vErrors); {{ /* don't edit, used in replace */ }} + {{??}} + validate.errors = vErrors; {{ /* don't edit, used in replace */ }} + return errors === 0; {{ /* don't edit, used in replace */ }} + {{?}} + }; + + return validate; +{{??}} + var {{=$valid}} = errors === errs_{{=$lvl}}; +{{?}} + +{{# def.cleanUp }} + +{{? $top }} + {{# def.finalCleanUp }} +{{?}} + +{{ + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i=0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) + return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || + ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i=0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) + return true; + } +}} diff --git a/node_modules/ajv/lib/dotjs/README.md b/node_modules/ajv/lib/dotjs/README.md new file mode 100644 index 0000000..4d99484 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/README.md @@ -0,0 +1,3 @@ +These files are compiled dot templates from dot folder. + +Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. diff --git a/node_modules/ajv/lib/dotjs/_limit.js b/node_modules/ajv/lib/dotjs/_limit.js new file mode 100644 index 0000000..f02a760 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limit.js @@ -0,0 +1,157 @@ +'use strict'; +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limitItems.js b/node_modules/ajv/lib/dotjs/_limitItems.js new file mode 100644 index 0000000..a27d118 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limitItems.js @@ -0,0 +1,77 @@ +'use strict'; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limitLength.js b/node_modules/ajv/lib/dotjs/_limitLength.js new file mode 100644 index 0000000..789f374 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limitLength.js @@ -0,0 +1,82 @@ +'use strict'; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limitProperties.js b/node_modules/ajv/lib/dotjs/_limitProperties.js new file mode 100644 index 0000000..11dc939 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limitProperties.js @@ -0,0 +1,77 @@ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/allOf.js b/node_modules/ajv/lib/dotjs/allOf.js new file mode 100644 index 0000000..5107b18 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/allOf.js @@ -0,0 +1,43 @@ +'use strict'; +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/anyOf.js b/node_modules/ajv/lib/dotjs/anyOf.js new file mode 100644 index 0000000..819c6f8 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/anyOf.js @@ -0,0 +1,74 @@ +'use strict'; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return it.util.schemaHasRules($sch, it.RULES.all); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/comment.js b/node_modules/ajv/lib/dotjs/comment.js new file mode 100644 index 0000000..dd66bb8 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/comment.js @@ -0,0 +1,14 @@ +'use strict'; +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/const.js b/node_modules/ajv/lib/dotjs/const.js new file mode 100644 index 0000000..15b7c61 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/const.js @@ -0,0 +1,56 @@ +'use strict'; +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/contains.js b/node_modules/ajv/lib/dotjs/contains.js new file mode 100644 index 0000000..8899ce5 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/contains.js @@ -0,0 +1,82 @@ +'use strict'; +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/custom.js b/node_modules/ajv/lib/dotjs/custom.js new file mode 100644 index 0000000..f3e641e --- /dev/null +++ b/node_modules/ajv/lib/dotjs/custom.js @@ -0,0 +1,228 @@ +'use strict'; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/if.js b/node_modules/ajv/lib/dotjs/if.js new file mode 100644 index 0000000..eff9090 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/if.js @@ -0,0 +1,104 @@ +'use strict'; +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && it.util.schemaHasRules($thenSch, it.RULES.all), + $elsePresent = $elseSch !== undefined && it.util.schemaHasRules($elseSch, it.RULES.all), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/index.js b/node_modules/ajv/lib/dotjs/index.js new file mode 100644 index 0000000..2fb1b00 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/index.js @@ -0,0 +1,33 @@ +'use strict'; + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': require('./ref'), + allOf: require('./allOf'), + anyOf: require('./anyOf'), + '$comment': require('./comment'), + const: require('./const'), + contains: require('./contains'), + dependencies: require('./dependencies'), + 'enum': require('./enum'), + format: require('./format'), + 'if': require('./if'), + items: require('./items'), + maximum: require('./_limit'), + minimum: require('./_limit'), + maxItems: require('./_limitItems'), + minItems: require('./_limitItems'), + maxLength: require('./_limitLength'), + minLength: require('./_limitLength'), + maxProperties: require('./_limitProperties'), + minProperties: require('./_limitProperties'), + multipleOf: require('./multipleOf'), + not: require('./not'), + oneOf: require('./oneOf'), + pattern: require('./pattern'), + properties: require('./properties'), + propertyNames: require('./propertyNames'), + required: require('./required'), + uniqueItems: require('./uniqueItems'), + validate: require('./validate') +}; diff --git a/node_modules/ajv/lib/dotjs/items.js b/node_modules/ajv/lib/dotjs/items.js new file mode 100644 index 0000000..99ce738 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/items.js @@ -0,0 +1,141 @@ +'use strict'; +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/multipleOf.js b/node_modules/ajv/lib/dotjs/multipleOf.js new file mode 100644 index 0000000..af087d2 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/multipleOf.js @@ -0,0 +1,77 @@ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/not.js b/node_modules/ajv/lib/dotjs/not.js new file mode 100644 index 0000000..c8f8af7 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/not.js @@ -0,0 +1,84 @@ +'use strict'; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/oneOf.js b/node_modules/ajv/lib/dotjs/oneOf.js new file mode 100644 index 0000000..e9df453 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/oneOf.js @@ -0,0 +1,73 @@ +'use strict'; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/pattern.js b/node_modules/ajv/lib/dotjs/pattern.js new file mode 100644 index 0000000..1d74d6b --- /dev/null +++ b/node_modules/ajv/lib/dotjs/pattern.js @@ -0,0 +1,75 @@ +'use strict'; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/properties.js b/node_modules/ajv/lib/dotjs/properties.js new file mode 100644 index 0000000..7d2ea86 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/properties.js @@ -0,0 +1,330 @@ +'use strict'; +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/propertyNames.js b/node_modules/ajv/lib/dotjs/propertyNames.js new file mode 100644 index 0000000..c86a8cb --- /dev/null +++ b/node_modules/ajv/lib/dotjs/propertyNames.js @@ -0,0 +1,82 @@ +'use strict'; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/uniqueItems.js b/node_modules/ajv/lib/dotjs/uniqueItems.js new file mode 100644 index 0000000..c4f6536 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/uniqueItems.js @@ -0,0 +1,86 @@ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/validate.js b/node_modules/ajv/lib/dotjs/validate.js new file mode 100644 index 0000000..cd0efc8 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/validate.js @@ -0,0 +1,494 @@ +'use strict'; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [undefined]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; + } + out += ' var ' + ($coerced) + ' = undefined; '; + var $bracesCoercion = ''; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($i) { + out += ' if (' + ($coerced) + ' === undefined) { '; + $bracesCoercion += '}'; + } + if (it.opts.coerceTypes == 'array' && $type != 'array') { + out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; + } + if ($type == 'string') { + out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + out = it.util.cleanUpCode(out); + if ($top) { + out = it.util.finalCleanUpCode(out, $async); + } + + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} diff --git a/node_modules/ajv/lib/keyword.js b/node_modules/ajv/lib/keyword.js new file mode 100644 index 0000000..cf4d699 --- /dev/null +++ b/node_modules/ajv/lib/keyword.js @@ -0,0 +1,178 @@ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = require('./dotjs/custom'); +var metaSchema = require('./refs/json-schema-draft-07.json'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; + +var definitionSchema = { + definitions: { + simpleTypes: metaSchema.definitions.simpleTypes + }, + type: 'object', + dependencies: { + schema: ['validate'], + $data: ['validate'], + statements: ['inline'], + valid: {not: {required: ['macro']}} + }, + properties: { + type: metaSchema.properties.type, + schema: {type: 'boolean'}, + statements: {type: 'boolean'}, + dependencies: { + type: 'array', + items: {type: 'string'} + }, + metaSchema: {type: 'object'}, + modifying: {type: 'boolean'}, + valid: {type: 'boolean'}, + $data: {type: 'boolean'}, + async: {type: 'boolean'}, + errors: { + anyOf: [ + {type: 'boolean'}, + {const: 'full'} + ] + } + } +}; + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i ../ajv-dist/bower.json + cd ../ajv-dist + + if [[ `git status --porcelain` ]]; then + echo "Changes detected. Updating master branch..." + git add -A + git commit -m "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin master > /dev/null 2>&1 + fi + + echo "Publishing tag..." + + git tag $TRAVIS_TAG + git push --tags > /dev/null 2>&1 + + echo "Done" +fi diff --git a/node_modules/ajv/scripts/travis-gh-pages b/node_modules/ajv/scripts/travis-gh-pages new file mode 100644 index 0000000..46ded16 --- /dev/null +++ b/node_modules/ajv/scripts/travis-gh-pages @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -e + +if [[ "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then + git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qE '\.md$|^LICENSE$|travis-gh-pages$' && { + rm -rf ../gh-pages + git clone -b gh-pages --single-branch https://${GITHUB_TOKEN}@github.com/epoberezkin/ajv.git ../gh-pages + mkdir -p ../gh-pages/_source + cp *.md ../gh-pages/_source + cp LICENSE ../gh-pages/_source + currentDir=$(pwd) + cd ../gh-pages + $currentDir/node_modules/.bin/gh-pages-generator + # remove logo from README + sed -i -E "s/]+ajv_logo[^>]+>//" index.md + git config user.email "$GIT_USER_EMAIL" + git config user.name "$GIT_USER_NAME" + git add . + git commit -am "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin gh-pages > /dev/null 2>&1 + } +fi diff --git a/node_modules/array-equal/.npmignore b/node_modules/array-equal/.npmignore new file mode 100644 index 0000000..e347262 --- /dev/null +++ b/node_modules/array-equal/.npmignore @@ -0,0 +1 @@ +.DS_Store* diff --git a/node_modules/array-equal/LICENSE b/node_modules/array-equal/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/node_modules/array-equal/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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. diff --git a/node_modules/array-equal/README.md b/node_modules/array-equal/README.md new file mode 100644 index 0000000..522dd81 --- /dev/null +++ b/node_modules/array-equal/README.md @@ -0,0 +1,11 @@ + +# Array Equal + +Check if two arrays are equal: + +```js +var equals = require('array-equal') + +assert(equals([1, 2, 3], [1, 2, 3])) // => true +assert(equals([1, 2, 3], [1, 2, 3, 4])) // => false +``` diff --git a/node_modules/array-equal/component.json b/node_modules/array-equal/component.json new file mode 100644 index 0000000..2d555b2 --- /dev/null +++ b/node_modules/array-equal/component.json @@ -0,0 +1,10 @@ +{ + "name": "array-equal", + "description": "check if two arrays are equal", + "version": "1.0.0", + "license": "MIT", + "repository": "component/array-equal", + "scripts": [ + "index.js" + ] +} diff --git a/node_modules/array-equal/index.js b/node_modules/array-equal/index.js new file mode 100644 index 0000000..c4b8803 --- /dev/null +++ b/node_modules/array-equal/index.js @@ -0,0 +1,9 @@ + +module.exports = function equal(arr1, arr2) { + var length = arr1.length + if (length !== arr2.length) return false + for (var i = 0; i < length; i++) + if (arr1[i] !== arr2[i]) + return false + return true +} diff --git a/node_modules/array-equal/package.json b/node_modules/array-equal/package.json new file mode 100644 index 0000000..67e8fe8 --- /dev/null +++ b/node_modules/array-equal/package.json @@ -0,0 +1,44 @@ +{ + "_from": "array-equal@^1.0.0", + "_id": "array-equal@1.0.0", + "_inBundle": false, + "_integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", + "_location": "/array-equal", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "array-equal@^1.0.0", + "name": "array-equal", + "escapedName": "array-equal", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/jsdom" + ], + "_resolved": "https://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", + "_shasum": "8c2a5ef2472fd9ea742b04c77a75093ba2757c93", + "_spec": "array-equal@^1.0.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\jsdom", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/component/array-equal/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "check if two arrays are equal", + "homepage": "https://github.com/component/array-equal#readme", + "license": "MIT", + "name": "array-equal", + "repository": { + "type": "git", + "url": "git+https://github.com/component/array-equal.git" + }, + "version": "1.0.0" +} diff --git a/node_modules/asn1/LICENSE b/node_modules/asn1/LICENSE new file mode 100644 index 0000000..9b5dcdb --- /dev/null +++ b/node_modules/asn1/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Mark Cavage, All rights reserved. + +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 diff --git a/node_modules/asn1/README.md b/node_modules/asn1/README.md new file mode 100644 index 0000000..2208210 --- /dev/null +++ b/node_modules/asn1/README.md @@ -0,0 +1,50 @@ +node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. +Currently BER encoding is supported; at some point I'll likely have to do DER. + +## Usage + +Mostly, if you're *actually* needing to read and write ASN.1, you probably don't +need this readme to explain what and why. If you have no idea what ASN.1 is, +see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc + +The source is pretty much self-explanatory, and has read/write methods for the +common types out there. + +### Decoding + +The following reads an ASN.1 sequence with a boolean. + + var Ber = require('asn1').Ber; + + var reader = new Ber.Reader(Buffer.from([0x30, 0x03, 0x01, 0x01, 0xff])); + + reader.readSequence(); + console.log('Sequence len: ' + reader.length); + if (reader.peek() === Ber.Boolean) + console.log(reader.readBoolean()); + +### Encoding + +The following generates the same payload as above. + + var Ber = require('asn1').Ber; + + var writer = new Ber.Writer(); + + writer.startSequence(); + writer.writeBoolean(true); + writer.endSequence(); + + console.log(writer.buffer); + +## Installation + + npm install asn1 + +## License + +MIT. + +## Bugs + +See . diff --git a/node_modules/asn1/lib/ber/errors.js b/node_modules/asn1/lib/ber/errors.js new file mode 100644 index 0000000..4557b8a --- /dev/null +++ b/node_modules/asn1/lib/ber/errors.js @@ -0,0 +1,13 @@ +// Copyright 2011 Mark Cavage All rights reserved. + + +module.exports = { + + newInvalidAsn1Error: function (msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } + +}; diff --git a/node_modules/asn1/lib/ber/index.js b/node_modules/asn1/lib/ber/index.js new file mode 100644 index 0000000..387d132 --- /dev/null +++ b/node_modules/asn1/lib/ber/index.js @@ -0,0 +1,27 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var errors = require('./errors'); +var types = require('./types'); + +var Reader = require('./reader'); +var Writer = require('./writer'); + + +// --- Exports + +module.exports = { + + Reader: Reader, + + Writer: Writer + +}; + +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; +} diff --git a/node_modules/asn1/lib/ber/reader.js b/node_modules/asn1/lib/ber/reader.js new file mode 100644 index 0000000..8a7e4ca --- /dev/null +++ b/node_modules/asn1/lib/ber/reader.js @@ -0,0 +1,262 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var assert = require('assert'); +var Buffer = require('safer-buffer').Buffer; + +var ASN1 = require('./types'); +var errors = require('./errors'); + + +// --- Globals + +var newInvalidAsn1Error = errors.newInvalidAsn1Error; + + + +// --- API + +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); + + this._buf = data; + this._size = data.length; + + // These hold the "current" state + this._len = 0; + this._offset = 0; +} + +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); + +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); + +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); + +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); + + +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ +Reader.prototype.readByte = function (peek) { + if (this._size - this._offset < 1) + return null; + + var b = this._buf[this._offset] & 0xff; + + if (!peek) + this._offset += 1; + + return b; +}; + + +Reader.prototype.peek = function () { + return this.readByte(true); +}; + + +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ +Reader.prototype.readLength = function (offset) { + if (offset === undefined) + offset = this._offset; + + if (offset >= this._size) + return null; + + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; + + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; + + if (lenB === 0) + throw newInvalidAsn1Error('Indefinite length not supported'); + + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); + + if (this._size - offset < lenB) + return null; + + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + + } else { + // Wasn't a variable length + this._len = lenB; + } + + return offset; +}; + + +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function (tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); + + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; + + this._offset = o; + return seq; +}; + + +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; + + +Reader.prototype.readBoolean = function () { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; + + +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; + + +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; + + var b = this.peek(); + if (b === null) + return null; + + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); + + var o = this.readLength(this._offset + 1); // stored in `length` + + if (o === null) + return null; + + if (this.length > this._size - o) + return null; + + this._offset = o; + + if (this.length === 0) + return retbuf ? Buffer.alloc(0) : ''; + + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; + + return retbuf ? str : str.toString('utf8'); +}; + +Reader.prototype.readOID = function (tag) { + if (!tag) + tag = ASN1.OID; + + var b = this.readString(tag, true); + if (b === null) + return null; + + var values = []; + var value = 0; + + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; + + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) === 0) { + values.push(value); + value = 0; + } + } + + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); + + return values.join('.'); +}; + + +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); + + var b = this.peek(); + + if (b === null) + return null; + + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); + + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; + + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); + + if (this.length > this._size - o) + return null; + this._offset = o; + + var fb = this._buf[this._offset]; + var value = 0; + + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); + } + + if ((fb & 0x80) === 0x80 && i !== 4) + value -= (1 << (i * 8)); + + return value >> 0; +}; + + + +// --- Exported API + +module.exports = Reader; diff --git a/node_modules/asn1/lib/ber/types.js b/node_modules/asn1/lib/ber/types.js new file mode 100644 index 0000000..8aea000 --- /dev/null +++ b/node_modules/asn1/lib/ber/types.js @@ -0,0 +1,36 @@ +// Copyright 2011 Mark Cavage All rights reserved. + + +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; diff --git a/node_modules/asn1/lib/ber/writer.js b/node_modules/asn1/lib/ber/writer.js new file mode 100644 index 0000000..3515acf --- /dev/null +++ b/node_modules/asn1/lib/ber/writer.js @@ -0,0 +1,317 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var assert = require('assert'); +var Buffer = require('safer-buffer').Buffer; +var ASN1 = require('./types'); +var errors = require('./errors'); + + +// --- Globals + +var newInvalidAsn1Error = errors.newInvalidAsn1Error; + +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; + + +// --- Helpers + +function merge(from, to) { + assert.ok(from); + assert.equal(typeof (from), 'object'); + assert.ok(to); + assert.equal(typeof (to), 'object'); + + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function (key) { + if (to[key]) + return; + + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); + + return to; +} + + + +// --- API + +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); + + this._buf = Buffer.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; + + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; +} + +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); + + return (this._buf.slice(0, this._offset)); + } +}); + +Writer.prototype.writeByte = function (b) { + if (typeof (b) !== 'number') + throw new TypeError('argument must be a Number'); + + this._ensure(1); + this._buf[this._offset++] = b; +}; + + +Writer.prototype.writeInt = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Integer; + + var sz = 4; + + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; + } + + if (sz > 4) + throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); + + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; + + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } + +}; + + +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; + + +Writer.prototype.writeEnumeration = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Enumeration; + + return this.writeInt(i, tag); +}; + + +Writer.prototype.writeBoolean = function (b, tag) { + if (typeof (b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof (tag) !== 'number') + tag = ASN1.Boolean; + + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; + + +Writer.prototype.writeString = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); + if (typeof (tag) !== 'number') + tag = ASN1.OctetString; + + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; + + +Writer.prototype.writeBuffer = function (buf, tag) { + if (typeof (tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); + + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; + + +Writer.prototype.writeStringArray = function (strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); + + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; + +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof (tag) !== 'number') + tag = ASN1.OID; + + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } + } + + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function (b) { + encodeOctet(bytes, parseInt(b, 10)); + }); + + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; + + +Writer.prototype.writeLength = function (len) { + if (typeof (len) !== 'number') + throw new TypeError('argument must be a Number'); + + this._ensure(4); + + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw newInvalidAsn1Error('Length too long (> 4 bytes)'); + } +}; + +Writer.prototype.startSequence = function (tag) { + if (typeof (tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; + + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; + + +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; + + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error('Sequence too long'); + } +}; + + +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); + + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; + +Writer.prototype._ensure = function (len) { + assert.ok(len); + + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; + + var buf = Buffer.alloc(sz); + + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; + } +}; + + + +// --- Exported API + +module.exports = Writer; diff --git a/node_modules/asn1/lib/index.js b/node_modules/asn1/lib/index.js new file mode 100644 index 0000000..ede3ab2 --- /dev/null +++ b/node_modules/asn1/lib/index.js @@ -0,0 +1,20 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc + +var Ber = require('./ber/index'); + + + +// --- Exported API + +module.exports = { + + Ber: Ber, + + BerReader: Ber.Reader, + + BerWriter: Ber.Writer + +}; diff --git a/node_modules/asn1/package.json b/node_modules/asn1/package.json new file mode 100644 index 0000000..e6ef470 --- /dev/null +++ b/node_modules/asn1/package.json @@ -0,0 +1,75 @@ +{ + "_from": "asn1@~0.2.3", + "_id": "asn1@0.2.4", + "_inBundle": false, + "_integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "_location": "/asn1", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "asn1@~0.2.3", + "name": "asn1", + "escapedName": "asn1", + "rawSpec": "~0.2.3", + "saveSpec": null, + "fetchSpec": "~0.2.3" + }, + "_requiredBy": [ + "/sshpk" + ], + "_resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "_shasum": "8d2475dfab553bb33e77b54e59e880bb8ce23136", + "_spec": "asn1@~0.2.3", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\sshpk", + "author": { + "name": "Joyent", + "url": "joyent.com" + }, + "bugs": { + "url": "https://github.com/joyent/node-asn1/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Mark Cavage", + "email": "mcavage@gmail.com" + }, + { + "name": "David Gwynne", + "email": "loki@animata.net" + }, + { + "name": "Yunong Xiao", + "email": "yunong@joyent.com" + }, + { + "name": "Alex Wilson", + "email": "alex.wilson@joyent.com" + } + ], + "dependencies": { + "safer-buffer": "~2.1.0" + }, + "deprecated": false, + "description": "Contains parsers and serializers for ASN.1 (currently BER only)", + "devDependencies": { + "eslint": "2.13.1", + "eslint-plugin-joyent": "~1.3.0", + "faucet": "0.0.1", + "istanbul": "^0.3.6", + "tape": "^3.5.0" + }, + "homepage": "https://github.com/joyent/node-asn1#readme", + "license": "MIT", + "main": "lib/index.js", + "name": "asn1", + "repository": { + "type": "git", + "url": "git://github.com/joyent/node-asn1.git" + }, + "scripts": { + "test": "tape ./test/ber/*.test.js" + }, + "version": "0.2.4" +} diff --git a/node_modules/assert-plus/AUTHORS b/node_modules/assert-plus/AUTHORS new file mode 100644 index 0000000..1923524 --- /dev/null +++ b/node_modules/assert-plus/AUTHORS @@ -0,0 +1,6 @@ +Dave Eddy +Fred Kuo +Lars-Magnus Skog +Mark Cavage +Patrick Mooney +Rob Gulewich diff --git a/node_modules/assert-plus/CHANGES.md b/node_modules/assert-plus/CHANGES.md new file mode 100644 index 0000000..57d92bf --- /dev/null +++ b/node_modules/assert-plus/CHANGES.md @@ -0,0 +1,14 @@ +# assert-plus Changelog + +## 1.0.0 + +- *BREAKING* assert.number (and derivatives) now accept Infinity as valid input +- Add assert.finite check. Previous assert.number callers should use this if + they expect Infinity inputs to throw. + +## 0.2.0 + +- Fix `assert.object(null)` so it throws +- Fix optional/arrayOf exports for non-type-of asserts +- Add optiona/arrayOf exports for Stream/Date/Regex/uuid +- Add basic unit test coverage diff --git a/node_modules/assert-plus/README.md b/node_modules/assert-plus/README.md new file mode 100644 index 0000000..ec200d1 --- /dev/null +++ b/node_modules/assert-plus/README.md @@ -0,0 +1,162 @@ +# assert-plus + +This library is a super small wrapper over node's assert module that has two +things: (1) the ability to disable assertions with the environment variable +NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like +`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks +like this: + +```javascript + var assert = require('assert-plus'); + + function fooAccount(options, callback) { + assert.object(options, 'options'); + assert.number(options.id, 'options.id'); + assert.bool(options.isManager, 'options.isManager'); + assert.string(options.name, 'options.name'); + assert.arrayOfString(options.email, 'options.email'); + assert.func(callback, 'callback'); + + // Do stuff + callback(null, {}); + } +``` + +# API + +All methods that *aren't* part of node's core assert API are simply assumed to +take an argument, and then a string 'name' that's not a message; `AssertionError` +will be thrown if the assertion fails with a message like: + + AssertionError: foo (string) is required + at test (/home/mark/work/foo/foo.js:3:9) + at Object. (/home/mark/work/foo/foo.js:15:1) + at Module._compile (module.js:446:26) + at Object..js (module.js:464:10) + at Module.load (module.js:353:31) + at Function._load (module.js:311:12) + at Array.0 (module.js:484:10) + at EventEmitter._tickCallback (node.js:190:38) + +from: + +```javascript + function test(foo) { + assert.string(foo, 'foo'); + } +``` + +There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`: + +```javascript + function test(foo) { + assert.arrayOfString(foo, 'foo'); + } +``` + +You can assert IFF an argument is not `undefined` (i.e., an optional arg): + +```javascript + assert.optionalString(foo, 'foo'); +``` + +Lastly, you can opt-out of assertion checking altogether by setting the +environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have +lots of assertions, and don't want to pay `typeof ()` taxes to v8 in +production. Be advised: The standard functions re-exported from `assert` are +also disabled in assert-plus if NDEBUG is specified. Using them directly from +the `assert` module avoids this behavior. + +The complete list of APIs is: + +* assert.array +* assert.bool +* assert.buffer +* assert.func +* assert.number +* assert.finite +* assert.object +* assert.string +* assert.stream +* assert.date +* assert.regexp +* assert.uuid +* assert.arrayOfArray +* assert.arrayOfBool +* assert.arrayOfBuffer +* assert.arrayOfFunc +* assert.arrayOfNumber +* assert.arrayOfFinite +* assert.arrayOfObject +* assert.arrayOfString +* assert.arrayOfStream +* assert.arrayOfDate +* assert.arrayOfRegexp +* assert.arrayOfUuid +* assert.optionalArray +* assert.optionalBool +* assert.optionalBuffer +* assert.optionalFunc +* assert.optionalNumber +* assert.optionalFinite +* assert.optionalObject +* assert.optionalString +* assert.optionalStream +* assert.optionalDate +* assert.optionalRegexp +* assert.optionalUuid +* assert.optionalArrayOfArray +* assert.optionalArrayOfBool +* assert.optionalArrayOfBuffer +* assert.optionalArrayOfFunc +* assert.optionalArrayOfNumber +* assert.optionalArrayOfFinite +* assert.optionalArrayOfObject +* assert.optionalArrayOfString +* assert.optionalArrayOfStream +* assert.optionalArrayOfDate +* assert.optionalArrayOfRegexp +* assert.optionalArrayOfUuid +* assert.AssertionError +* assert.fail +* assert.ok +* assert.equal +* assert.notEqual +* assert.deepEqual +* assert.notDeepEqual +* assert.strictEqual +* assert.notStrictEqual +* assert.throws +* assert.doesNotThrow +* assert.ifError + +# Installation + + npm install assert-plus + +## License + +The MIT License (MIT) +Copyright (c) 2012 Mark Cavage + +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. + +## Bugs + +See . diff --git a/node_modules/assert-plus/assert.js b/node_modules/assert-plus/assert.js new file mode 100644 index 0000000..26f944e --- /dev/null +++ b/node_modules/assert-plus/assert.js @@ -0,0 +1,211 @@ +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. + +var assert = require('assert'); +var Stream = require('stream').Stream; +var util = require('util'); + + +///--- Globals + +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; + + +///--- Internal + +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); +} + +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); +} + +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} + +function noop() { + // Why even bother with asserts? +} + + +///--- Exports + +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; + } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg); + } + }, + finite: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; + +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; + + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } + + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); + + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; + + return out; +} + +module.exports = _setExports(process.env.NODE_NDEBUG); diff --git a/node_modules/assert-plus/package.json b/node_modules/assert-plus/package.json new file mode 100644 index 0000000..f79f57f --- /dev/null +++ b/node_modules/assert-plus/package.json @@ -0,0 +1,87 @@ +{ + "_from": "assert-plus@^1.0.0", + "_id": "assert-plus@1.0.0", + "_inBundle": false, + "_integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "_location": "/assert-plus", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "assert-plus@^1.0.0", + "name": "assert-plus", + "escapedName": "assert-plus", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/dashdash", + "/getpass", + "/http-signature", + "/jsprim", + "/sshpk", + "/verror" + ], + "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "_shasum": "f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525", + "_spec": "assert-plus@^1.0.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\http-signature", + "author": { + "name": "Mark Cavage", + "email": "mcavage@gmail.com" + }, + "bugs": { + "url": "https://github.com/mcavage/node-assert-plus/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Dave Eddy", + "email": "dave@daveeddy.com" + }, + { + "name": "Fred Kuo", + "email": "fred.kuo@joyent.com" + }, + { + "name": "Lars-Magnus Skog", + "email": "ralphtheninja@riseup.net" + }, + { + "name": "Mark Cavage", + "email": "mcavage@gmail.com" + }, + { + "name": "Patrick Mooney", + "email": "pmooney@pfmooney.com" + }, + { + "name": "Rob Gulewich", + "email": "robert.gulewich@joyent.com" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Extra assertions on top of node's assert module", + "devDependencies": { + "faucet": "0.0.1", + "tape": "4.2.2" + }, + "engines": { + "node": ">=0.8" + }, + "homepage": "https://github.com/mcavage/node-assert-plus#readme", + "license": "MIT", + "main": "./assert.js", + "name": "assert-plus", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/mcavage/node-assert-plus.git" + }, + "scripts": { + "test": "tape tests/*.js | ./node_modules/.bin/faucet" + }, + "version": "1.0.0" +} diff --git a/node_modules/async-limiter/.travis.yml b/node_modules/async-limiter/.travis.yml new file mode 100644 index 0000000..6cf4a7a --- /dev/null +++ b/node_modules/async-limiter/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "6" + - "node" +script: npm run travis +cache: + yarn: true diff --git a/node_modules/async-limiter/LICENSE b/node_modules/async-limiter/LICENSE new file mode 100644 index 0000000..9c91fb2 --- /dev/null +++ b/node_modules/async-limiter/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Samuel Reed + +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. diff --git a/node_modules/async-limiter/coverage/coverage.json b/node_modules/async-limiter/coverage/coverage.json new file mode 100644 index 0000000..5b4a358 --- /dev/null +++ b/node_modules/async-limiter/coverage/coverage.json @@ -0,0 +1 @@ +{"/Users/samuelreed/git/forks/async-throttle/index.js":{"path":"/Users/samuelreed/git/forks/async-throttle/index.js","s":{"1":1,"2":7,"3":1,"4":6,"5":6,"6":6,"7":6,"8":6,"9":6,"10":1,"11":1,"12":3,"13":13,"14":13,"15":13,"16":1,"17":19,"18":1,"19":45,"20":6,"21":39,"22":13,"23":13,"24":13,"25":13,"26":39,"27":18,"28":6,"29":6,"30":1,"31":6,"32":6,"33":6,"34":1,"35":13,"36":13,"37":1},"b":{"1":[1,6],"2":[6,5],"3":[6,5],"4":[6,39],"5":[13,26],"6":[18,21],"7":[6,0]},"f":{"1":7,"2":3,"3":13,"4":19,"5":45,"6":6,"7":13},"fnMap":{"1":{"name":"Queue","line":3,"loc":{"start":{"line":3,"column":0},"end":{"line":3,"column":24}}},"2":{"name":"(anonymous_2)","line":22,"loc":{"start":{"line":22,"column":24},"end":{"line":22,"column":41}}},"3":{"name":"(anonymous_3)","line":23,"loc":{"start":{"line":23,"column":28},"end":{"line":23,"column":39}}},"4":{"name":"(anonymous_4)","line":31,"loc":{"start":{"line":31,"column":7},"end":{"line":31,"column":18}}},"5":{"name":"(anonymous_5)","line":36,"loc":{"start":{"line":36,"column":23},"end":{"line":36,"column":34}}},"6":{"name":"(anonymous_6)","line":55,"loc":{"start":{"line":55,"column":25},"end":{"line":55,"column":38}}},"7":{"name":"done","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":16}}}},"statementMap":{"1":{"start":{"line":3,"column":0},"end":{"line":14,"column":1}},"2":{"start":{"line":4,"column":2},"end":{"line":6,"column":3}},"3":{"start":{"line":5,"column":4},"end":{"line":5,"column":30}},"4":{"start":{"line":8,"column":2},"end":{"line":8,"column":26}},"5":{"start":{"line":9,"column":2},"end":{"line":9,"column":53}},"6":{"start":{"line":10,"column":2},"end":{"line":10,"column":19}},"7":{"start":{"line":11,"column":2},"end":{"line":11,"column":17}},"8":{"start":{"line":12,"column":2},"end":{"line":12,"column":16}},"9":{"start":{"line":13,"column":2},"end":{"line":13,"column":31}},"10":{"start":{"line":16,"column":0},"end":{"line":20,"column":2}},"11":{"start":{"line":22,"column":0},"end":{"line":28,"column":3}},"12":{"start":{"line":23,"column":2},"end":{"line":27,"column":4}},"13":{"start":{"line":24,"column":4},"end":{"line":24,"column":75}},"14":{"start":{"line":25,"column":4},"end":{"line":25,"column":16}},"15":{"start":{"line":26,"column":4},"end":{"line":26,"column":24}},"16":{"start":{"line":30,"column":0},"end":{"line":34,"column":3}},"17":{"start":{"line":32,"column":4},"end":{"line":32,"column":43}},"18":{"start":{"line":36,"column":0},"end":{"line":53,"column":2}},"19":{"start":{"line":37,"column":2},"end":{"line":39,"column":3}},"20":{"start":{"line":38,"column":4},"end":{"line":38,"column":11}},"21":{"start":{"line":40,"column":2},"end":{"line":45,"column":3}},"22":{"start":{"line":41,"column":4},"end":{"line":41,"column":32}},"23":{"start":{"line":42,"column":4},"end":{"line":42,"column":19}},"24":{"start":{"line":43,"column":4},"end":{"line":43,"column":20}},"25":{"start":{"line":44,"column":4},"end":{"line":44,"column":16}},"26":{"start":{"line":47,"column":2},"end":{"line":52,"column":3}},"27":{"start":{"line":48,"column":4},"end":{"line":51,"column":5}},"28":{"start":{"line":49,"column":6},"end":{"line":49,"column":30}},"29":{"start":{"line":50,"column":6},"end":{"line":50,"column":27}},"30":{"start":{"line":55,"column":0},"end":{"line":60,"column":2}},"31":{"start":{"line":56,"column":2},"end":{"line":59,"column":3}},"32":{"start":{"line":57,"column":4},"end":{"line":57,"column":22}},"33":{"start":{"line":58,"column":4},"end":{"line":58,"column":16}},"34":{"start":{"line":62,"column":0},"end":{"line":65,"column":1}},"35":{"start":{"line":63,"column":2},"end":{"line":63,"column":17}},"36":{"start":{"line":64,"column":2},"end":{"line":64,"column":14}},"37":{"start":{"line":67,"column":0},"end":{"line":67,"column":23}}},"branchMap":{"1":{"line":4,"type":"if","locations":[{"start":{"line":4,"column":2},"end":{"line":4,"column":2}},{"start":{"line":4,"column":2},"end":{"line":4,"column":2}}]},"2":{"line":8,"type":"binary-expr","locations":[{"start":{"line":8,"column":12},"end":{"line":8,"column":19}},{"start":{"line":8,"column":23},"end":{"line":8,"column":25}}]},"3":{"line":9,"type":"binary-expr","locations":[{"start":{"line":9,"column":21},"end":{"line":9,"column":40}},{"start":{"line":9,"column":44},"end":{"line":9,"column":52}}]},"4":{"line":37,"type":"if","locations":[{"start":{"line":37,"column":2},"end":{"line":37,"column":2}},{"start":{"line":37,"column":2},"end":{"line":37,"column":2}}]},"5":{"line":40,"type":"if","locations":[{"start":{"line":40,"column":2},"end":{"line":40,"column":2}},{"start":{"line":40,"column":2},"end":{"line":40,"column":2}}]},"6":{"line":47,"type":"if","locations":[{"start":{"line":47,"column":2},"end":{"line":47,"column":2}},{"start":{"line":47,"column":2},"end":{"line":47,"column":2}}]},"7":{"line":56,"type":"if","locations":[{"start":{"line":56,"column":2},"end":{"line":56,"column":2}},{"start":{"line":56,"column":2},"end":{"line":56,"column":2}}]}}}} \ No newline at end of file diff --git a/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html b/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html new file mode 100644 index 0000000..198882b --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html @@ -0,0 +1,73 @@ + + + + Code coverage report for async-throttle/ + + + + + + +
+

Code coverage report for async-throttle/

+

+ Statements: 100% (37 / 37)      + Branches: 92.86% (13 / 14)      + Functions: 100% (7 / 7)      + Lines: 100% (37 / 37)      + Ignored: none      +

+
All files » async-throttle/
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
index.js100%(37 / 37)92.86%(13 / 14)100%(7 / 7)100%(37 / 37)
+
+
+ + + + + + diff --git a/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html b/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html new file mode 100644 index 0000000..adc030f --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html @@ -0,0 +1,246 @@ + + + + Code coverage report for async-throttle/index.js + + + + + + +
+

Code coverage report for async-throttle/index.js

+

+ Statements: 100% (37 / 37)      + Branches: 92.86% (13 / 14)      + Functions: 100% (7 / 7)      + Lines: 100% (37 / 37)      + Ignored: none      +

+
All files » async-throttle/ » index.js
+
+
+

+
+
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  +  +1 +7 +1 +  +  +6 +6 +6 +6 +6 +6 +  +  +1 +  +  +  +  +  +1 +3 +13 +13 +13 +  +  +  +1 +  +19 +  +  +  +1 +45 +6 +  +39 +13 +13 +13 +13 +  +  +39 +18 +6 +6 +  +  +  +  +1 +6 +6 +6 +  +  +  +1 +13 +13 +  +  +1 + 
'use strict';
+ 
+function Queue(options) {
+  if (!(this instanceof Queue)) {
+    return new Queue(options);
+  }
+ 
+  options = options || {};
+  this.concurrency = options.concurrency || Infinity;
+  this.pending = 0;
+  this.jobs = [];
+  this.cbs = [];
+  this._done = done.bind(this);
+}
+ 
+var arrayAddMethods = [
+  'push',
+  'unshift',
+  'splice'
+];
+ 
+arrayAddMethods.forEach(function(method) {
+  Queue.prototype[method] = function() {
+    var methodResult = Array.prototype[method].apply(this.jobs, arguments);
+    this._run();
+    return methodResult;
+  };
+});
+ 
+Object.defineProperty(Queue.prototype, 'length', {
+  get: function() {
+    return this.pending + this.jobs.length;
+  }
+});
+ 
+Queue.prototype._run = function() {
+  if (this.pending === this.concurrency) {
+    return;
+  }
+  if (this.jobs.length) {
+    var job = this.jobs.shift();
+    this.pending++;
+    job(this._done);
+    this._run();
+  }
+ 
+  if (this.pending === 0) {
+    while (this.cbs.length !== 0) {
+      var cb = this.cbs.pop();
+      process.nextTick(cb);
+    }
+  }
+};
+ 
+Queue.prototype.onDone = function(cb) {
+  Eif (typeof cb === 'function') {
+    this.cbs.push(cb);
+    this._run();
+  }
+};
+ 
+function done() {
+  this.pending--;
+  this._run();
+}
+ 
+module.exports = Queue;
+ 
+ +
+ + + + + + diff --git a/node_modules/async-limiter/coverage/lcov-report/base.css b/node_modules/async-limiter/coverage/lcov-report/base.css new file mode 100644 index 0000000..a6a2f32 --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/base.css @@ -0,0 +1,182 @@ +body, html { + margin:0; padding: 0; +} +body { + font-family: Helvetica Neue, Helvetica,Arial; + font-size: 10pt; +} +div.header, div.footer { + background: #eee; + padding: 1em; +} +div.header { + z-index: 100; + position: fixed; + top: 0; + border-bottom: 1px solid #666; + width: 100%; +} +div.footer { + border-top: 1px solid #666; +} +div.body { + margin-top: 10em; +} +div.meta { + font-size: 90%; + text-align: center; +} +h1, h2, h3 { + font-weight: normal; +} +h1 { + font-size: 12pt; +} +h2 { + font-size: 10pt; +} +pre { + font-family: Consolas, Menlo, Monaco, monospace; + margin: 0; + padding: 0; + line-height: 1.3; + font-size: 14px; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} + +div.path { font-size: 110%; } +div.path a:link, div.path a:visited { color: #000; } +table.coverage { border-collapse: collapse; margin:0; padding: 0 } + +table.coverage td { + margin: 0; + padding: 0; + color: #111; + vertical-align: top; +} +table.coverage td.line-count { + width: 50px; + text-align: right; + padding-right: 5px; +} +table.coverage td.line-coverage { + color: #777 !important; + text-align: right; + border-left: 1px solid #666; + border-right: 1px solid #666; +} + +table.coverage td.text { +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 40px; +} +table.coverage td span.cline-neutral { + background: #eee; +} +table.coverage td span.cline-yes { + background: #b5d592; + color: #999; +} +table.coverage td span.cline-no { + background: #fc8c84; +} + +.cstat-yes { color: #111; } +.cstat-no { background: #fc8c84; color: #111; } +.fstat-no { background: #ffc520; color: #111 !important; } +.cbranch-no { background: yellow !important; color: #111; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +.missing-if-branch { + display: inline-block; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: black; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} + +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} + +.entity, .metric { font-weight: bold; } +.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } +.metric small { font-size: 80%; font-weight: normal; color: #666; } + +div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } +div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } +div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } +div.coverage-summary th.file { border-right: none !important; } +div.coverage-summary th.pic { border-left: none !important; text-align: right; } +div.coverage-summary th.pct { border-right: none !important; } +div.coverage-summary th.abs { border-left: none !important; text-align: right; } +div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } +div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } +div.coverage-summary td.file { border-left: 1px solid #666; white-space: nowrap; } +div.coverage-summary td.pic { min-width: 120px !important; } +div.coverage-summary a:link { text-decoration: none; color: #000; } +div.coverage-summary a:visited { text-decoration: none; color: #777; } +div.coverage-summary a:hover { text-decoration: underline; } +div.coverage-summary tfoot td { border-top: 1px solid #666; } + +div.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +div.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +div.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} + +.high { background: #b5d592 !important; } +.medium { background: #ffe87c !important; } +.low { background: #fc8c84 !important; } + +span.cover-fill, span.cover-empty { + display:inline-block; + border:1px solid #444; + background: white; + height: 12px; +} +span.cover-fill { + background: #ccc; + border-right: 1px solid #444; +} +span.cover-empty { + background: white; + border-left: none; +} +span.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } diff --git a/node_modules/async-limiter/coverage/lcov-report/index.html b/node_modules/async-limiter/coverage/lcov-report/index.html new file mode 100644 index 0000000..782a1cf --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/index.html @@ -0,0 +1,73 @@ + + + + Code coverage report for All files + + + + + + +
+

Code coverage report for All files

+

+ Statements: 100% (37 / 37)      + Branches: 92.86% (13 / 14)      + Functions: 100% (7 / 7)      + Lines: 100% (37 / 37)      + Ignored: none      +

+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
async-throttle/100%(37 / 37)92.86%(13 / 14)100%(7 / 7)100%(37 / 37)
+
+
+ + + + + + diff --git a/node_modules/async-limiter/coverage/lcov-report/prettify.css b/node_modules/async-limiter/coverage/lcov-report/prettify.css new file mode 100644 index 0000000..b317a7c --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/node_modules/async-limiter/coverage/lcov-report/prettify.js b/node_modules/async-limiter/coverage/lcov-report/prettify.js new file mode 100644 index 0000000..ef51e03 --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png b/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000..03f704a Binary files /dev/null and b/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png differ diff --git a/node_modules/async-limiter/coverage/lcov-report/sorter.js b/node_modules/async-limiter/coverage/lcov-report/sorter.js new file mode 100644 index 0000000..6afb736 --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov-report/sorter.js @@ -0,0 +1,156 @@ +var addSorting = (function () { + "use strict"; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { return document.querySelector('.coverage-summary table'); } + // returns the thead element of the summary table + function getTableHeader() { return getTable().querySelector('thead tr'); } + // returns the tbody element of the summary table + function getTableBody() { return getTable().querySelector('tbody'); } + // returns the th element for nth column + function getNthColumn(n) { return getTableHeader().querySelectorAll('th')[n]; } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + el = getNthColumn(i).querySelector('.sorter'); + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/node_modules/async-limiter/coverage/lcov.info b/node_modules/async-limiter/coverage/lcov.info new file mode 100644 index 0000000..fbf36aa --- /dev/null +++ b/node_modules/async-limiter/coverage/lcov.info @@ -0,0 +1,74 @@ +TN: +SF:/Users/samuelreed/git/forks/async-throttle/index.js +FN:3,Queue +FN:22,(anonymous_2) +FN:23,(anonymous_3) +FN:31,(anonymous_4) +FN:36,(anonymous_5) +FN:55,(anonymous_6) +FN:62,done +FNF:7 +FNH:7 +FNDA:7,Queue +FNDA:3,(anonymous_2) +FNDA:13,(anonymous_3) +FNDA:19,(anonymous_4) +FNDA:45,(anonymous_5) +FNDA:6,(anonymous_6) +FNDA:13,done +DA:3,1 +DA:4,7 +DA:5,1 +DA:8,6 +DA:9,6 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:16,1 +DA:22,1 +DA:23,3 +DA:24,13 +DA:25,13 +DA:26,13 +DA:30,1 +DA:32,19 +DA:36,1 +DA:37,45 +DA:38,6 +DA:40,39 +DA:41,13 +DA:42,13 +DA:43,13 +DA:44,13 +DA:47,39 +DA:48,18 +DA:49,6 +DA:50,6 +DA:55,1 +DA:56,6 +DA:57,6 +DA:58,6 +DA:62,1 +DA:63,13 +DA:64,13 +DA:67,1 +LF:37 +LH:37 +BRDA:4,1,0,1 +BRDA:4,1,1,6 +BRDA:8,2,0,6 +BRDA:8,2,1,5 +BRDA:9,3,0,6 +BRDA:9,3,1,5 +BRDA:37,4,0,6 +BRDA:37,4,1,39 +BRDA:40,5,0,13 +BRDA:40,5,1,26 +BRDA:47,6,0,18 +BRDA:47,6,1,21 +BRDA:56,7,0,6 +BRDA:56,7,1,0 +BRF:14 +BRH:13 +end_of_record diff --git a/node_modules/async-limiter/index.js b/node_modules/async-limiter/index.js new file mode 100644 index 0000000..c9bd2f9 --- /dev/null +++ b/node_modules/async-limiter/index.js @@ -0,0 +1,67 @@ +'use strict'; + +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); + } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); +} + +var arrayAddMethods = [ + 'push', + 'unshift', + 'splice' +]; + +arrayAddMethods.forEach(function(method) { + Queue.prototype[method] = function() { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + this._run(); + return methodResult; + }; +}); + +Object.defineProperty(Queue.prototype, 'length', { + get: function() { + return this.pending + this.jobs.length; + } +}); + +Queue.prototype._run = function() { + if (this.pending === this.concurrency) { + return; + } + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); + this._run(); + } + + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; + +Queue.prototype.onDone = function(cb) { + if (typeof cb === 'function') { + this.cbs.push(cb); + this._run(); + } +}; + +function done() { + this.pending--; + this._run(); +} + +module.exports = Queue; diff --git a/node_modules/async-limiter/package.json b/node_modules/async-limiter/package.json new file mode 100644 index 0000000..8bd4882 --- /dev/null +++ b/node_modules/async-limiter/package.json @@ -0,0 +1,69 @@ +{ + "_from": "async-limiter@~1.0.0", + "_id": "async-limiter@1.0.0", + "_inBundle": false, + "_integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", + "_location": "/async-limiter", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "async-limiter@~1.0.0", + "name": "async-limiter", + "escapedName": "async-limiter", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/ws" + ], + "_resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "_shasum": "78faed8c3d074ab81f22b4e985d79e8738f720f8", + "_spec": "async-limiter@~1.0.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\ws", + "author": { + "name": "Samuel Reed" + }, + "bugs": { + "url": "https://github.com/strml/async-limiter/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "asynchronous function queue with adjustable concurrency", + "devDependencies": { + "coveralls": "^2.11.2", + "eslint": "^4.6.1", + "eslint-plugin-mocha": "^4.11.0", + "intelli-espower-loader": "^1.0.1", + "istanbul": "^0.3.2", + "mocha": "^3.5.2", + "power-assert": "^1.4.4" + }, + "homepage": "https://github.com/strml/async-limiter#readme", + "keywords": [ + "throttle", + "async", + "limiter", + "asynchronous", + "job", + "task", + "concurrency", + "concurrent" + ], + "license": "MIT", + "name": "async-limiter", + "repository": { + "type": "git", + "url": "git+https://github.com/strml/async-limiter.git" + }, + "scripts": { + "coverage": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | coveralls", + "example": "node example", + "lint": "eslint .", + "test": "mocha --R intelli-espower-loader test/", + "travis": "npm run lint && npm run coverage" + }, + "version": "1.0.0" +} diff --git a/node_modules/async-limiter/readme.md b/node_modules/async-limiter/readme.md new file mode 100644 index 0000000..dcf4932 --- /dev/null +++ b/node_modules/async-limiter/readme.md @@ -0,0 +1,132 @@ +# Async-Limiter + +A module for limiting concurrent asynchronous actions in flight. Forked from [queue](https://github.com/jessetane/queue). + +[![npm](http://img.shields.io/npm/v/async-limiter.svg?style=flat-square)](http://www.npmjs.org/async-limiter) +[![tests](https://img.shields.io/travis/STRML/async-limiter.svg?style=flat-square&branch=master)](https://travis-ci.org/STRML/async-limiter) +[![coverage](https://img.shields.io/coveralls/STRML/async-limiter.svg?style=flat-square&branch=master)](https://coveralls.io/r/STRML/async-limiter) + +This module exports a class `Limiter` that implements some of the `Array` API. +Pass async functions (ones that accept a callback or return a promise) to an instance's additive array methods. + +## Motivation + +Certain functions, like `zlib`, have [undesirable behavior](https://github.com/nodejs/node/issues/8871#issuecomment-250915913) when +run at infinite concurrency. + +In this case, it is actually faster, and takes far less memory, to limit concurrency. + +This module should do the absolute minimum work necessary to queue up functions. PRs are welcome that would +make this module faster or lighter, but new functionality is not desired. + +Style should confirm to nodejs/node style. + +## Example + +``` javascript +var Limiter = require('async-limiter') + +var t = new Limiter({concurrency: 2}); +var results = [] + +// add jobs using the familiar Array API +t.push(function (cb) { + results.push('two') + cb() +}) + +t.push( + function (cb) { + results.push('four') + cb() + }, + function (cb) { + results.push('five') + cb() + } +) + +t.unshift(function (cb) { + results.push('one') + cb() +}) + +t.splice(2, 0, function (cb) { + results.push('three') + cb() +}) + +// Jobs run automatically. If you want a callback when all are done, +// call 'onDone()'. +t.onDone(function () { + console.log('all done:', results) +}) +``` + +## Zlib Example + +```js +const zlib = require('zlib'); +const Limiter = require('async-limiter'); + +const message = {some: "data"}; +const payload = new Buffer(JSON.stringify(message)); + +// Try with different concurrency values to see how this actually +// slows significantly with higher concurrency! +// +// 5: 1398.607ms +// 10: 1375.668ms +// Infinity: 4423.300ms +// +const t = new Limiter({concurrency: 5}); +function deflate(payload, cb) { + t.push(function(done) { + zlib.deflate(payload, function(err, buffer) { + done(); + cb(err, buffer); + }); + }); +} + +console.time('deflate'); +for(let i = 0; i < 30000; ++i) { + deflate(payload, function (err, buffer) {}); +} +q.onDone(function() { + console.timeEnd('deflate'); +}); +``` + +## Install + +`npm install async-limiter` + +## Test + +`npm test` + +## API + +### `var t = new Limiter([opts])` +Constructor. `opts` may contain inital values for: +* `q.concurrency` + +## Instance methods + +### `q.onDone(fn)` +`fn` will be called once and only once, when the queue is empty. + +## Instance methods mixed in from `Array` +Mozilla has docs on how these methods work [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). +### `q.push(element1, ..., elementN)` +### `q.unshift(element1, ..., elementN)` +### `q.splice(index , howMany[, element1[, ...[, elementN]]])` + +## Properties +### `q.concurrency` +Max number of jobs the queue should process concurrently, defaults to `Infinity`. + +### `q.length` +Jobs pending + jobs to process (readonly). + diff --git a/node_modules/asynckit/LICENSE b/node_modules/asynckit/LICENSE new file mode 100644 index 0000000..c9eca5d --- /dev/null +++ b/node_modules/asynckit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Alex Indigo + +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. diff --git a/node_modules/asynckit/README.md b/node_modules/asynckit/README.md new file mode 100644 index 0000000..ddcc7e6 --- /dev/null +++ b/node_modules/asynckit/README.md @@ -0,0 +1,233 @@ +# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) + +Minimal async jobs utility library, with streams support. + +[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) + +[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) +[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) +[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) + + + +AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. +Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. + +It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. + +| compression | size | +| :----------------- | -------: | +| asynckit.js | 12.34 kB | +| asynckit.min.js | 4.11 kB | +| asynckit.min.js.gz | 1.47 kB | + + +## Install + +```sh +$ npm install --save asynckit +``` + +## Examples + +### Parallel Jobs + +Runs iterator over provided array in parallel. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will terminate rest of the active jobs (if abort function is provided) +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var parallel = require('asynckit').parallel + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , target = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// async job accepts one element from the array +// and a callback function +function asyncJob(item, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var parallel = require('asynckit/parallel') + , assert = require('assert') + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] + , target = [] + , keys = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); + assert.deepEqual(keys, expectedKeys); +}); + +// supports full value, key, callback (shortcut) interface +function asyncJob(item, key, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + keys.push(key); + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). + +### Serial Jobs + +Runs iterator over provided array sequentially. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will not proceed to the rest of the items in the list +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var serial = require('asynckit/serial') + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// extended interface (item, key, callback) +// also supported for arrays +function asyncJob(item, key, cb) +{ + target.push(key); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var serial = require('asynckit').serial + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , target = [] + ; + + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// shortcut interface (item, callback) +// works for object as well as for the arrays +function asyncJob(item, cb) +{ + target.push(item); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). + +_Note: Since _object_ is an _unordered_ collection of properties, +it may produce unexpected results with sequential iterations. +Whenever order of the jobs' execution is important please use `serialOrdered` method._ + +### Ordered Serial Iterations + +TBD + +For example [compare-property](compare-property) package. + +### Streaming interface + +TBD + +## Want to Know More? + +More examples can be found in [test folder](test/). + +Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. + +## License + +AsyncKit is licensed under the MIT license. diff --git a/node_modules/asynckit/bench.js b/node_modules/asynckit/bench.js new file mode 100644 index 0000000..c612f1a --- /dev/null +++ b/node_modules/asynckit/bench.js @@ -0,0 +1,76 @@ +/* eslint no-console: "off" */ + +var asynckit = require('./') + , async = require('async') + , assert = require('assert') + , expected = 0 + ; + +var Benchmark = require('benchmark'); +var suite = new Benchmark.Suite; + +var source = []; +for (var z = 1; z < 100; z++) +{ + source.push(z); + expected += z; +} + +suite +// add tests + +.add('async.map', function(deferred) +{ + var total = 0; + + async.map(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +.add('asynckit.parallel', function(deferred) +{ + var total = 0; + + asynckit.parallel(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +// add listeners +.on('cycle', function(ev) +{ + console.log(String(ev.target)); +}) +.on('complete', function() +{ + console.log('Fastest is ' + this.filter('fastest').map('name')); +}) +// run async +.run({ 'async': true }); diff --git a/node_modules/asynckit/index.js b/node_modules/asynckit/index.js new file mode 100644 index 0000000..455f945 --- /dev/null +++ b/node_modules/asynckit/index.js @@ -0,0 +1,6 @@ +module.exports = +{ + parallel : require('./parallel.js'), + serial : require('./serial.js'), + serialOrdered : require('./serialOrdered.js') +}; diff --git a/node_modules/asynckit/lib/abort.js b/node_modules/asynckit/lib/abort.js new file mode 100644 index 0000000..114367e --- /dev/null +++ b/node_modules/asynckit/lib/abort.js @@ -0,0 +1,29 @@ +// API +module.exports = abort; + +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; +} + +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} diff --git a/node_modules/asynckit/lib/async.js b/node_modules/asynckit/lib/async.js new file mode 100644 index 0000000..7f1288a --- /dev/null +++ b/node_modules/asynckit/lib/async.js @@ -0,0 +1,34 @@ +var defer = require('./defer.js'); + +// API +module.exports = async; + +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} diff --git a/node_modules/asynckit/lib/defer.js b/node_modules/asynckit/lib/defer.js new file mode 100644 index 0000000..b67110c --- /dev/null +++ b/node_modules/asynckit/lib/defer.js @@ -0,0 +1,26 @@ +module.exports = defer; + +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} diff --git a/node_modules/asynckit/lib/iterate.js b/node_modules/asynckit/lib/iterate.js new file mode 100644 index 0000000..5d2839a --- /dev/null +++ b/node_modules/asynckit/lib/iterate.js @@ -0,0 +1,75 @@ +var async = require('./async.js') + , abort = require('./abort.js') + ; + +// API +module.exports = iterate; + +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } + + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } + + // return salvaged results + callback(error, state.results); + }); +} + +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } + + return aborter; +} diff --git a/node_modules/asynckit/lib/readable_asynckit.js b/node_modules/asynckit/lib/readable_asynckit.js new file mode 100644 index 0000000..78ad240 --- /dev/null +++ b/node_modules/asynckit/lib/readable_asynckit.js @@ -0,0 +1,91 @@ +var streamify = require('./streamify.js') + , defer = require('./defer.js') + ; + +// API +module.exports = ReadableAsyncKit; + +/** + * Base constructor for all streams + * used to hold properties/methods + */ +function ReadableAsyncKit() +{ + ReadableAsyncKit.super_.apply(this, arguments); + + // list of active jobs + this.jobs = {}; + + // add stream methods + this.destroy = destroy; + this._start = _start; + this._read = _read; +} + +/** + * Destroys readable stream, + * by aborting outstanding jobs + * + * @returns {void} + */ +function destroy() +{ + if (this.destroyed) + { + return; + } + + this.destroyed = true; + + if (typeof this.terminator == 'function') + { + this.terminator(); + } +} + +/** + * Starts provided jobs in async manner + * + * @private + */ +function _start() +{ + // first argument – runner function + var runner = arguments[0] + // take away first argument + , args = Array.prototype.slice.call(arguments, 1) + // second argument - input data + , input = args[0] + // last argument - result callback + , endCb = streamify.callback.call(this, args[args.length - 1]) + ; + + args[args.length - 1] = endCb; + // third argument - iterator + args[1] = streamify.iterator.call(this, args[1]); + + // allow time for proper setup + defer(function() + { + if (!this.destroyed) + { + this.terminator = runner.apply(null, args); + } + else + { + endCb(null, Array.isArray(input) ? [] : {}); + } + }.bind(this)); +} + + +/** + * Implement _read to comply with Readable streams + * Doesn't really make sense for flowing object mode + * + * @private + */ +function _read() +{ + +} diff --git a/node_modules/asynckit/lib/readable_parallel.js b/node_modules/asynckit/lib/readable_parallel.js new file mode 100644 index 0000000..5d2929f --- /dev/null +++ b/node_modules/asynckit/lib/readable_parallel.js @@ -0,0 +1,25 @@ +var parallel = require('../parallel.js'); + +// API +module.exports = ReadableParallel; + +/** + * Streaming wrapper to `asynckit.parallel` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableParallel(list, iterator, callback) +{ + if (!(this instanceof ReadableParallel)) + { + return new ReadableParallel(list, iterator, callback); + } + + // turn on object mode + ReadableParallel.super_.call(this, {objectMode: true}); + + this._start(parallel, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial.js b/node_modules/asynckit/lib/readable_serial.js new file mode 100644 index 0000000..7822698 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial.js @@ -0,0 +1,25 @@ +var serial = require('../serial.js'); + +// API +module.exports = ReadableSerial; + +/** + * Streaming wrapper to `asynckit.serial` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerial(list, iterator, callback) +{ + if (!(this instanceof ReadableSerial)) + { + return new ReadableSerial(list, iterator, callback); + } + + // turn on object mode + ReadableSerial.super_.call(this, {objectMode: true}); + + this._start(serial, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial_ordered.js b/node_modules/asynckit/lib/readable_serial_ordered.js new file mode 100644 index 0000000..3de89c4 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial_ordered.js @@ -0,0 +1,29 @@ +var serialOrdered = require('../serialOrdered.js'); + +// API +module.exports = ReadableSerialOrdered; +// expose sort helpers +module.exports.ascending = serialOrdered.ascending; +module.exports.descending = serialOrdered.descending; + +/** + * Streaming wrapper to `asynckit.serialOrdered` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerialOrdered(list, iterator, sortMethod, callback) +{ + if (!(this instanceof ReadableSerialOrdered)) + { + return new ReadableSerialOrdered(list, iterator, sortMethod, callback); + } + + // turn on object mode + ReadableSerialOrdered.super_.call(this, {objectMode: true}); + + this._start(serialOrdered, list, iterator, sortMethod, callback); +} diff --git a/node_modules/asynckit/lib/state.js b/node_modules/asynckit/lib/state.js new file mode 100644 index 0000000..cbea7ad --- /dev/null +++ b/node_modules/asynckit/lib/state.js @@ -0,0 +1,37 @@ +// API +module.exports = state; + +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; + + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } + + return initState; +} diff --git a/node_modules/asynckit/lib/streamify.js b/node_modules/asynckit/lib/streamify.js new file mode 100644 index 0000000..f56a1c9 --- /dev/null +++ b/node_modules/asynckit/lib/streamify.js @@ -0,0 +1,141 @@ +var async = require('./async.js'); + +// API +module.exports = { + iterator: wrapIterator, + callback: wrapCallback +}; + +/** + * Wraps iterators with long signature + * + * @this ReadableAsyncKit# + * @param {function} iterator - function to wrap + * @returns {function} - wrapped function + */ +function wrapIterator(iterator) +{ + var stream = this; + + return function(item, key, cb) + { + var aborter + , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) + ; + + stream.jobs[key] = wrappedCb; + + // it's either shortcut (item, cb) + if (iterator.length == 2) + { + aborter = iterator(item, wrappedCb); + } + // or long format (item, key, cb) + else + { + aborter = iterator(item, key, wrappedCb); + } + + return aborter; + }; +} + +/** + * Wraps provided callback function + * allowing to execute snitch function before + * real callback + * + * @this ReadableAsyncKit# + * @param {function} callback - function to wrap + * @returns {function} - wrapped function + */ +function wrapCallback(callback) +{ + var stream = this; + + var wrapped = function(error, result) + { + return finisher.call(stream, error, result, callback); + }; + + return wrapped; +} + +/** + * Wraps provided iterator callback function + * makes sure snitch only called once, + * but passes secondary calls to the original callback + * + * @this ReadableAsyncKit# + * @param {function} callback - callback to wrap + * @param {number|string} key - iteration key + * @returns {function} wrapped callback + */ +function wrapIteratorCallback(callback, key) +{ + var stream = this; + + return function(error, output) + { + // don't repeat yourself + if (!(key in stream.jobs)) + { + callback(error, output); + return; + } + + // clean up jobs + delete stream.jobs[key]; + + return streamer.call(stream, error, {key: key, value: output}, callback); + }; +} + +/** + * Stream wrapper for iterator callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects iterator results + */ +function streamer(error, output, callback) +{ + if (error && !this.error) + { + this.error = error; + this.pause(); + this.emit('error', error); + // send back value only, as expected + callback(error, output && output.value); + return; + } + + // stream stuff + this.push(output); + + // back to original track + // send back value only, as expected + callback(error, output && output.value); +} + +/** + * Stream wrapper for finishing callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects final results + */ +function finisher(error, output, callback) +{ + // signal end of the stream + // only for successfully finished streams + if (!error) + { + this.push(null); + } + + // back to original track + callback(error, output); +} diff --git a/node_modules/asynckit/lib/terminator.js b/node_modules/asynckit/lib/terminator.js new file mode 100644 index 0000000..d6eb992 --- /dev/null +++ b/node_modules/asynckit/lib/terminator.js @@ -0,0 +1,29 @@ +var abort = require('./abort.js') + , async = require('./async.js') + ; + +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } + + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); +} diff --git a/node_modules/asynckit/package.json b/node_modules/asynckit/package.json new file mode 100644 index 0000000..5fa7b14 --- /dev/null +++ b/node_modules/asynckit/package.json @@ -0,0 +1,91 @@ +{ + "_from": "asynckit@^0.4.0", + "_id": "asynckit@0.4.0", + "_inBundle": false, + "_integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "_location": "/asynckit", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "asynckit@^0.4.0", + "name": "asynckit", + "escapedName": "asynckit", + "rawSpec": "^0.4.0", + "saveSpec": null, + "fetchSpec": "^0.4.0" + }, + "_requiredBy": [ + "/form-data" + ], + "_resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "_shasum": "c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79", + "_spec": "asynckit@^0.4.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\form-data", + "author": { + "name": "Alex Indigo", + "email": "iam@alexindigo.com" + }, + "bugs": { + "url": "https://github.com/alexindigo/asynckit/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Minimal async jobs utility library, with streams support", + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^2.11.9", + "eslint": "^2.9.0", + "istanbul": "^0.4.3", + "obake": "^0.1.2", + "phantomjs-prebuilt": "^2.1.7", + "pre-commit": "^1.1.3", + "reamde": "^1.1.0", + "rimraf": "^2.5.2", + "size-table": "^0.2.0", + "tap-spec": "^4.1.1", + "tape": "^4.5.1" + }, + "homepage": "https://github.com/alexindigo/asynckit#readme", + "keywords": [ + "async", + "jobs", + "parallel", + "serial", + "iterator", + "array", + "object", + "stream", + "destroy", + "terminate", + "abort" + ], + "license": "MIT", + "main": "index.js", + "name": "asynckit", + "pre-commit": [ + "clean", + "lint", + "test", + "browser", + "report", + "size" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/alexindigo/asynckit.git" + }, + "scripts": { + "browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec", + "clean": "rimraf coverage", + "debug": "tape test/test-*.js", + "lint": "eslint *.js lib/*.js test/*.js", + "report": "istanbul report", + "size": "browserify index.js | size-table asynckit", + "test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec", + "win-test": "tape test/test-*.js" + }, + "version": "0.4.0" +} diff --git a/node_modules/asynckit/parallel.js b/node_modules/asynckit/parallel.js new file mode 100644 index 0000000..3c50344 --- /dev/null +++ b/node_modules/asynckit/parallel.js @@ -0,0 +1,43 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} diff --git a/node_modules/asynckit/serial.js b/node_modules/asynckit/serial.js new file mode 100644 index 0000000..6cd949a --- /dev/null +++ b/node_modules/asynckit/serial.js @@ -0,0 +1,17 @@ +var serialOrdered = require('./serialOrdered.js'); + +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} diff --git a/node_modules/asynckit/serialOrdered.js b/node_modules/asynckit/serialOrdered.js new file mode 100644 index 0000000..607eafe --- /dev/null +++ b/node_modules/asynckit/serialOrdered.js @@ -0,0 +1,75 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods + */ + +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} diff --git a/node_modules/asynckit/stream.js b/node_modules/asynckit/stream.js new file mode 100644 index 0000000..d43465f --- /dev/null +++ b/node_modules/asynckit/stream.js @@ -0,0 +1,21 @@ +var inherits = require('util').inherits + , Readable = require('stream').Readable + , ReadableAsyncKit = require('./lib/readable_asynckit.js') + , ReadableParallel = require('./lib/readable_parallel.js') + , ReadableSerial = require('./lib/readable_serial.js') + , ReadableSerialOrdered = require('./lib/readable_serial_ordered.js') + ; + +// API +module.exports = +{ + parallel : ReadableParallel, + serial : ReadableSerial, + serialOrdered : ReadableSerialOrdered, +}; + +inherits(ReadableAsyncKit, Readable); + +inherits(ReadableParallel, ReadableAsyncKit); +inherits(ReadableSerial, ReadableAsyncKit); +inherits(ReadableSerialOrdered, ReadableAsyncKit); diff --git a/node_modules/aws-sign2/LICENSE b/node_modules/aws-sign2/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/aws-sign2/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/aws-sign2/README.md b/node_modules/aws-sign2/README.md new file mode 100644 index 0000000..763564e --- /dev/null +++ b/node_modules/aws-sign2/README.md @@ -0,0 +1,4 @@ +aws-sign +======== + +AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module. diff --git a/node_modules/aws-sign2/index.js b/node_modules/aws-sign2/index.js new file mode 100644 index 0000000..fb35f6d --- /dev/null +++ b/node_modules/aws-sign2/index.js @@ -0,0 +1,212 @@ + +/*! + * Copyright 2010 LearnBoost + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Module dependencies. + */ + +var crypto = require('crypto') + , parse = require('url').parse + ; + +/** + * Valid keys. + */ + +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] + +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ + +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) +} + +module.exports = authorization +module.exports.authorization = authorization + +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ + +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} + +module.exports.hmacSha1 = hmacSha1 + +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ + +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) +} +module.exports.sign = sign + +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ + +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery + +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.stringToSign = stringToSign + +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign + +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ + +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) + } + return buf.sort().join('\n') +} +module.exports.canonicalizeHeaders = canonicalizeHeaders + +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ + +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; + + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) + + return path + (buf.length ? '?' + buf.sort().join('&') : '') +} +module.exports.canonicalizeResource = canonicalizeResource diff --git a/node_modules/aws-sign2/package.json b/node_modules/aws-sign2/package.json new file mode 100644 index 0000000..2bfb4cb --- /dev/null +++ b/node_modules/aws-sign2/package.json @@ -0,0 +1,50 @@ +{ + "_from": "aws-sign2@~0.7.0", + "_id": "aws-sign2@0.7.0", + "_inBundle": false, + "_integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "_location": "/aws-sign2", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "aws-sign2@~0.7.0", + "name": "aws-sign2", + "escapedName": "aws-sign2", + "rawSpec": "~0.7.0", + "saveSpec": null, + "fetchSpec": "~0.7.0" + }, + "_requiredBy": [ + "/request" + ], + "_resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "_shasum": "b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8", + "_spec": "aws-sign2@~0.7.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\request", + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "bugs": { + "url": "https://github.com/mikeal/aws-sign/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.", + "devDependencies": {}, + "engines": { + "node": "*" + }, + "homepage": "https://github.com/mikeal/aws-sign#readme", + "license": "Apache-2.0", + "main": "index.js", + "name": "aws-sign2", + "optionalDependencies": {}, + "repository": { + "url": "git+https://github.com/mikeal/aws-sign.git" + }, + "version": "0.7.0" +} diff --git a/node_modules/aws4/.travis.yml b/node_modules/aws4/.travis.yml new file mode 100644 index 0000000..61d0634 --- /dev/null +++ b/node_modules/aws4/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4.2" diff --git a/node_modules/aws4/LICENSE b/node_modules/aws4/LICENSE new file mode 100644 index 0000000..4f321e5 --- /dev/null +++ b/node_modules/aws4/LICENSE @@ -0,0 +1,19 @@ +Copyright 2013 Michael Hart (michael.hart.au@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/aws4/README.md b/node_modules/aws4/README.md new file mode 100644 index 0000000..6b002d0 --- /dev/null +++ b/node_modules/aws4/README.md @@ -0,0 +1,523 @@ +aws4 +---- + +[![Build Status](https://secure.travis-ci.org/mhart/aws4.png?branch=master)](http://travis-ci.org/mhart/aws4) + +A small utility to sign vanilla node.js http(s) request options using Amazon's +[AWS Signature Version 4](http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html). + +Can also be used [in the browser](./browser). + +This signature is supported by nearly all Amazon services, including +[S3](http://docs.aws.amazon.com/AmazonS3/latest/API/), +[EC2](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/), +[DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html), +[Kinesis](http://docs.aws.amazon.com/kinesis/latest/APIReference/), +[Lambda](http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html), +[SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/), +[SNS](http://docs.aws.amazon.com/sns/latest/api/), +[IAM](http://docs.aws.amazon.com/IAM/latest/APIReference/), +[STS](http://docs.aws.amazon.com/STS/latest/APIReference/), +[RDS](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/), +[CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/), +[CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/), +[CodeDeploy](http://docs.aws.amazon.com/codedeploy/latest/APIReference/), +[CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/), +[CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/), +[ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/), +[EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/API/), +[Glacier](http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html), +[CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/APIReq.html), +[Elastic Load Balancing](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/), +[Elastic Transcoder](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/api-reference.html), +[CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/), +[Elastic Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/api/), +[Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html), +[Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/APIReference/), +[Direct Connect](http://docs.aws.amazon.com/directconnect/latest/APIReference/), +[Redshift](http://docs.aws.amazon.com/redshift/latest/APIReference/), +[OpsWorks](http://docs.aws.amazon.com/opsworks/latest/APIReference/), +[SES](http://docs.aws.amazon.com/ses/latest/APIReference/), +[SWF](http://docs.aws.amazon.com/amazonswf/latest/apireference/), +[AutoScaling](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/), +[Mobile Analytics](http://docs.aws.amazon.com/mobileanalytics/latest/ug/server-reference.html), +[Cognito Identity](http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/), +[Cognito Sync](http://docs.aws.amazon.com/cognitosync/latest/APIReference/), +[Container Service](http://docs.aws.amazon.com/AmazonECS/latest/APIReference/), +[AppStream](http://docs.aws.amazon.com/appstream/latest/developerguide/appstream-api-rest.html), +[Key Management Service](http://docs.aws.amazon.com/kms/latest/APIReference/), +[Config](http://docs.aws.amazon.com/config/latest/APIReference/), +[CloudHSM](http://docs.aws.amazon.com/cloudhsm/latest/dg/api-ref.html), +[Route53](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rest.html) and +[Route53 Domains](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rpc.html). + +Indeed, the only AWS services that *don't* support v4 as of 2014-12-30 are +[Import/Export](http://docs.aws.amazon.com/AWSImportExport/latest/DG/api-reference.html) and +[SimpleDB](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html) +(they only support [AWS Signature Version 2](https://github.com/mhart/aws2)). + +It also provides defaults for a number of core AWS headers and +request parameters, making it very easy to query AWS services, or +build out a fully-featured AWS library. + +Example +------- + +```javascript +var http = require('http'), + https = require('https'), + aws4 = require('aws4') + +// given an options object you could pass to http.request +var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'} + +// alternatively (as aws4 can infer the host): +opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'} + +// alternatively (as us-east-1 is default): +opts = {service: 'sqs', path: '/?Action=ListQueues'} + +aws4.sign(opts) // assumes AWS credentials are available in process.env + +console.log(opts) +/* +{ + host: 'sqs.us-east-1.amazonaws.com', + path: '/?Action=ListQueues', + headers: { + Host: 'sqs.us-east-1.amazonaws.com', + 'X-Amz-Date': '20121226T061030Z', + Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...' + } +} +*/ + +// we can now use this to query AWS using the standard node.js http API +http.request(opts, function(res) { res.pipe(process.stdout) }).end() +/* + + +... +*/ +``` + +More options +------------ + +```javascript +// you can also pass AWS credentials in explicitly (otherwise taken from process.env) +aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''}) + +// can also add the signature to query strings +aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true}) + +// create a utility function to pipe to stdout (with https this time) +function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') } + +// aws4 can infer the HTTP method if a body is passed in +// method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8' +request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'})) +/* + +... +*/ + +// can specify any custom option or header as per usual +request(aws4.sign({ + service: 'dynamodb', + region: 'ap-southeast-2', + method: 'POST', + path: '/', + headers: { + 'Content-Type': 'application/x-amz-json-1.0', + 'X-Amz-Target': 'DynamoDB_20120810.ListTables' + }, + body: '{}' +})) +/* +{"TableNames":[]} +... +*/ + +// works with all other services that support Signature Version 4 + +request(aws4.sign({service: 's3', path: '/', signQuery: true})) +/* + +... +*/ + +request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'})) +/* + +... +*/ + +request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'})) +/* + +... +*/ + +request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'})) +/* + +... +*/ + +request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'})) +/* + +... +*/ + +request(aws4.sign({service: 'appstream', path: '/applications'})) +/* +{"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/... +... +*/ + +request(aws4.sign({service: 'cognito-sync', path: '/identitypools'})) +/* +{"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null} +... +*/ + +request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'})) +/* +{"NextPageToken":null,"Pipelines":[]} +... +*/ + +request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'})) +/* +{"Functions":[],"NextMarker":null} +... +*/ + +request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'})) +/* + +... +*/ + +request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}})) +/* +{"Marker":null,"VaultList":[]} +... +*/ + +request(aws4.sign({service: 'storagegateway', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'StorageGateway_20120630.ListGateways' +}})) +/* +{"Gateways":[]} +... +*/ + +request(aws4.sign({service: 'datapipeline', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'DataPipeline.ListPipelines' +}})) +/* +{"hasMoreResults":false,"pipelineIdList":[]} +... +*/ + +request(aws4.sign({service: 'opsworks', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks' +}})) +/* +{"Stacks":[]} +... +*/ + +request(aws4.sign({service: 'route53domains', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'Route53Domains_v20140515.ListDomains' +}})) +/* +{"Domains":[]} +... +*/ + +request(aws4.sign({service: 'kinesis', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'Kinesis_20131202.ListStreams' +}})) +/* +{"HasMoreStreams":false,"StreamNames":[]} +... +*/ + +request(aws4.sign({service: 'cloudtrail', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails' +}})) +/* +{"trailList":[]} +... +*/ + +request(aws4.sign({service: 'logs', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'Logs_20140328.DescribeLogGroups' +}})) +/* +{"logGroups":[]} +... +*/ + +request(aws4.sign({service: 'codedeploy', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'CodeDeploy_20141006.ListApplications' +}})) +/* +{"applications":[]} +... +*/ + +request(aws4.sign({service: 'directconnect', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'OvertureService.DescribeConnections' +}})) +/* +{"connections":[]} +... +*/ + +request(aws4.sign({service: 'kms', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'TrentService.ListKeys' +}})) +/* +{"Keys":[],"Truncated":false} +... +*/ + +request(aws4.sign({service: 'config', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels' +}})) +/* +{"DeliveryChannels":[]} +... +*/ + +request(aws4.sign({service: 'cloudhsm', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones' +}})) +/* +{"AZList":["us-east-1a","us-east-1b","us-east-1c"]} +... +*/ + +request(aws4.sign({ + service: 'swf', + body: '{"registrationStatus":"REGISTERED"}', + headers: { + 'Content-Type': 'application/x-amz-json-1.0', + 'X-Amz-Target': 'SimpleWorkflowService.ListDomains' + } +})) +/* +{"domainInfos":[]} +... +*/ + +request(aws4.sign({ + service: 'cognito-identity', + body: '{"MaxResults": 1}', + headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools' + } +})) +/* +{"IdentityPools":[]} +... +*/ + +request(aws4.sign({ + service: 'mobileanalytics', + path: '/2014-06-05/events', + body: JSON.stringify({events:[{ + eventType: 'a', + timestamp: new Date().toISOString(), + session: {}, + }]}), + headers: { + 'Content-Type': 'application/json', + 'X-Amz-Client-Context': JSON.stringify({ + client: {client_id: 'a', app_title: 'a'}, + custom: {}, + env: {platform: 'a'}, + services: {}, + }), + } +})) +/* +(HTTP 202, empty response) +*/ + +// Generate CodeCommit Git access password +var signer = new aws4.RequestSigner({ + service: 'codecommit', + host: 'git-codecommit.us-east-1.amazonaws.com', + method: 'GIT', + path: '/v1/repos/MyAwesomeRepo', +}) +var password = signer.getDateTime() + 'Z' + signer.signature() +``` + +API +--- + +### aws4.sign(requestOptions, [credentials]) + +This calculates and populates the `Authorization` header of +`requestOptions`, and any other necessary AWS headers and/or request +options. Returns `requestOptions` as a convenience for chaining. + +`requestOptions` is an object holding the same options that the node.js +[http.request](http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback) +function takes. + +The following properties of `requestOptions` are used in the signing or +populated if they don't already exist: + +- `hostname` or `host` (will be determined from `service` and `region` if not given) +- `method` (will use `'GET'` if not given or `'POST'` if there is a `body`) +- `path` (will use `'/'` if not given) +- `body` (will use `''` if not given) +- `service` (will be calculated from `hostname` or `host` if not given) +- `region` (will be calculated from `hostname` or `host` or use `'us-east-1'` if not given) +- `headers['Host']` (will use `hostname` or `host` or be calculated if not given) +- `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'` + if not given and there is a `body`) +- `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used) + +Your AWS credentials (which can be found in your +[AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials)) +can be specified in one of two ways: + +- As the second argument, like this: + +```javascript +aws4.sign(requestOptions, { + secretAccessKey: "", + accessKeyId: "", + sessionToken: "" +}) +``` + +- From `process.env`, such as this: + +``` +export AWS_SECRET_ACCESS_KEY="" +export AWS_ACCESS_KEY_ID="" +export AWS_SESSION_TOKEN="" +``` + +(will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available) + +The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing +with [IAM STS temporary credentials](http://docs.aws.amazon.com/STS/latest/UsingSTS/using-temp-creds.html). + +Installation +------------ + +With [npm](http://npmjs.org/) do: + +``` +npm install aws4 +``` + +Can also be used [in the browser](./browser). + +Thanks +------ + +Thanks to [@jed](https://github.com/jed) for his +[dynamo-client](https://github.com/jed/dynamo-client) lib where I first +committed and subsequently extracted this code. + +Also thanks to the +[official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving +me a start on implementing the v4 signature. + diff --git a/node_modules/aws4/aws4.js b/node_modules/aws4/aws4.js new file mode 100644 index 0000000..124cd7a --- /dev/null +++ b/node_modules/aws4/aws4.js @@ -0,0 +1,332 @@ +var aws4 = exports, + url = require('url'), + querystring = require('querystring'), + crypto = require('crypto'), + lru = require('./lru'), + credentialsCache = lru(1000) + +// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html + +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) +} + +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} + +// This function assumes the string has already been percent encoded +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} + +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { + + if (typeof request === 'string') request = url.parse(request) + + var headers = request.headers = (request.headers || {}), + hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host) + + this.request = request + this.credentials = credentials || this.defaultCredentials() + + this.service = request.service || hostParts[0] || '' + this.region = request.region || hostParts[1] || 'us-east-1' + + // SES uses a different domain from the service name + if (this.service === 'email') this.service = 'ses' + + if (!request.method && request.body) + request.method = 'POST' + + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() + + // If a port is specified explicitly, use it as is + if (request.port) + headers.Host += ':' + request.port + } + if (!request.hostname && !request.host) + request.hostname = headers.Host || headers.host + + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +} + +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) + var hostParts = (match || []).slice(1, 3) + + // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com + if (hostParts[1] === 'es') + hostParts = hostParts.reverse() + + return hostParts +} + +// http://docs.aws.amazon.com/general/latest/gr/rande.html +RequestSigner.prototype.isSingleRegion = function() { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true + + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} + +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : + (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region, + service = this.service === 'ses' ? 'email' : this.service + return service + region + '.amazonaws.com' +} + +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() + + var request = this.request, headers = request.headers, query + + if (request.signQuery) { + + this.parsedPath.query = query = this.parsedPath.query || {} + + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 + + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() + + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() + + } else { + + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) + headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' + + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) + + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') + + if (headers['X-Amz-Date'] || headers['x-amz-date']) + this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] + else + headers['X-Amz-Date'] = this.getDateTime() + } + + delete headers.Authorization + delete headers.authorization + } +} + +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() + + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } + + this.request.path = this.formatPath() + + return this.request +} + +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) + + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') + + // Remove the trailing 'Z' on the timestamp string for CodeCommit git access + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) + } + return this.datetime +} + +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} + +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} + +RequestSigner.prototype.signature = function() { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) + kRegion = hmac(kDate, this.region) + kService = hmac(kRegion, this.service) + kCredentials = hmac(kService, 'aws4_request') + credentialsCache.set(cacheKey, kCredentials) + } + return hmac(kCredentials, this.stringToSign(), 'hex') +} + +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} + +RequestSigner.prototype.canonicalString = function() { + if (!this.parsedPath) this.prepareRequest() + + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash + + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD' + } else if (this.isCodeCommitGit) { + bodyHash = '' + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || + hash(this.request.body || '', 'hex') + } + + if (query) { + queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) { + if (!key) return obj + obj[key] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key].slice().sort()) + return obj + }, {}))) + } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') + pathStr = pathStr.split('/').reduce(function(path, piece) { + if (normalizePath && piece === '..') { + path.pop() + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = decodeURIComponent(piece) + path.push(encodeRfc3986(encodeURIComponent(piece))) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') + } + + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} + +RequestSigner.prototype.canonicalHeaders = function() { + var headers = this.request.headers + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' ') + } + return Object.keys(headers) + .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) + .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) + .join('\n') +} + +RequestSigner.prototype.signedHeaders = function() { + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .sort() + .join(';') +} + +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} + +RequestSigner.prototype.defaultCredentials = function() { + var env = process.env + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN, + } +} + +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/', + queryIx = path.indexOf('?'), + query = null + + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } + + // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all + if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) { + path = path.split('/').map(function(piece) { + return encodeURIComponent(decodeURIComponent(piece)) + }).join('/') + } + + this.parsedPath = { + path: path, + query: query, + } +} + +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query + + if (!query) return path + + // Services don't support empty query string keys + if (query[''] != null) delete query[''] + + return path + '?' + encodeRfc3986(querystring.stringify(query)) +} + +aws4.RequestSigner = RequestSigner + +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} diff --git a/node_modules/aws4/lru.js b/node_modules/aws4/lru.js new file mode 100644 index 0000000..333f66a --- /dev/null +++ b/node_modules/aws4/lru.js @@ -0,0 +1,96 @@ +module.exports = function(size) { + return new LruCache(size) +} + +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} + +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} + +LruCache.prototype.set = function(key, val) { + var node = this.map[key] + if (node != null) { + node.val = val + } else { + if (!this.capacity) this.prune() + if (!this.capacity) return false + node = new DoublyLinkedNode(key, val) + this.map[key] = node + this.capacity-- + } + this.used(node) + return true +} + +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} + +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} + + +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} + +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return + + this.remove(node) + + if (this.firstNode == null) { + this.firstNode = node + this.lastNode = node + node.prev = null + node.next = null + } else { + node.prev = null + node.next = this.firstNode + node.next.prev = node + this.firstNode = node + } +} + +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) + } + return lastNode +} + +DoublyLinkedList.prototype.remove = function(node) { + if (this.firstNode == node) { + this.firstNode = node.next + } else if (node.prev != null) { + node.prev.next = node.next + } + if (this.lastNode == node) { + this.lastNode = node.prev + } else if (node.next != null) { + node.next.prev = node.prev + } +} + + +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null +} diff --git a/node_modules/aws4/package.json b/node_modules/aws4/package.json new file mode 100644 index 0000000..368dff6 --- /dev/null +++ b/node_modules/aws4/package.json @@ -0,0 +1,104 @@ +{ + "_from": "aws4@^1.8.0", + "_id": "aws4@1.8.0", + "_inBundle": false, + "_integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", + "_location": "/aws4", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "aws4@^1.8.0", + "name": "aws4", + "escapedName": "aws4", + "rawSpec": "^1.8.0", + "saveSpec": null, + "fetchSpec": "^1.8.0" + }, + "_requiredBy": [ + "/request" + ], + "_resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "_shasum": "f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f", + "_spec": "aws4@^1.8.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\request", + "author": { + "name": "Michael Hart", + "email": "michael.hart.au@gmail.com", + "url": "http://github.com/mhart" + }, + "bugs": { + "url": "https://github.com/mhart/aws4/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Signs and prepares requests using AWS Signature Version 4", + "devDependencies": { + "mocha": "^2.4.5", + "should": "^8.2.2" + }, + "homepage": "https://github.com/mhart/aws4#readme", + "keywords": [ + "amazon", + "aws", + "signature", + "s3", + "ec2", + "autoscaling", + "cloudformation", + "elasticloadbalancing", + "elb", + "elasticbeanstalk", + "cloudsearch", + "dynamodb", + "kinesis", + "lambda", + "glacier", + "sqs", + "sns", + "iam", + "sts", + "ses", + "swf", + "storagegateway", + "datapipeline", + "directconnect", + "redshift", + "opsworks", + "rds", + "monitoring", + "cloudtrail", + "cloudfront", + "codedeploy", + "elasticache", + "elasticmapreduce", + "elastictranscoder", + "emr", + "cloudwatch", + "mobileanalytics", + "cognitoidentity", + "cognitosync", + "cognito", + "containerservice", + "ecs", + "appstream", + "keymanagementservice", + "kms", + "config", + "cloudhsm", + "route53", + "route53domains", + "logs" + ], + "license": "MIT", + "main": "aws4.js", + "name": "aws4", + "repository": { + "type": "git", + "url": "git+https://github.com/mhart/aws4.git" + }, + "scripts": { + "test": "mocha ./test/fast.js ./test/slow.js -b -t 100s -R list" + }, + "version": "1.8.0" +} diff --git a/node_modules/bcrypt-pbkdf/CONTRIBUTING.md b/node_modules/bcrypt-pbkdf/CONTRIBUTING.md new file mode 100644 index 0000000..401d34e --- /dev/null +++ b/node_modules/bcrypt-pbkdf/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contributing + +This repository uses [cr.joyent.us](https://cr.joyent.us) (Gerrit) for new +changes. Anyone can submit changes. To get started, see the [cr.joyent.us user +guide](https://github.com/joyent/joyent-gerrit/blob/master/docs/user/README.md). +This repo does not use GitHub pull requests. + +See the [Joyent Engineering +Guidelines](https://github.com/joyent/eng/blob/master/docs/index.md) for general +best practices expected in this repository. + +If you're changing something non-trivial or user-facing, you may want to submit +an issue first. diff --git a/node_modules/bcrypt-pbkdf/LICENSE b/node_modules/bcrypt-pbkdf/LICENSE new file mode 100644 index 0000000..fc58d2a --- /dev/null +++ b/node_modules/bcrypt-pbkdf/LICENSE @@ -0,0 +1,66 @@ +The Blowfish portions are under the following license: + +Blowfish block cipher for OpenBSD +Copyright 1997 Niels Provos +All rights reserved. + +Implementation advice by David Mazieres . + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +The bcrypt_pbkdf portions are under the following license: + +Copyright (c) 2013 Ted Unangst + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + + +Performance improvements (Javascript-specific): + +Copyright 2016, Joyent Inc +Author: Alex Wilson + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/bcrypt-pbkdf/README.md b/node_modules/bcrypt-pbkdf/README.md new file mode 100644 index 0000000..7551f33 --- /dev/null +++ b/node_modules/bcrypt-pbkdf/README.md @@ -0,0 +1,45 @@ +Port of the OpenBSD `bcrypt_pbkdf` function to pure Javascript. `npm`-ified +version of [Devi Mandiri's port](https://github.com/devi/tmp/blob/master/js/bcrypt_pbkdf.js), +with some minor performance improvements. The code is copied verbatim (and +un-styled) from Devi's work. + +This product includes software developed by Niels Provos. + +## API + +### `bcrypt_pbkdf.pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds)` + +Derive a cryptographic key of arbitrary length from a given password and salt, +using the OpenBSD `bcrypt_pbkdf` function. This is a combination of Blowfish and +SHA-512. + +See [this article](http://www.tedunangst.com/flak/post/bcrypt-pbkdf) for +further information. + +Parameters: + + * `pass`, a Uint8Array of length `passlen` + * `passlen`, an integer Number + * `salt`, a Uint8Array of length `saltlen` + * `saltlen`, an integer Number + * `key`, a Uint8Array of length `keylen`, will be filled with output + * `keylen`, an integer Number + * `rounds`, an integer Number, number of rounds of the PBKDF to run + +### `bcrypt_pbkdf.hash(sha2pass, sha2salt, out)` + +Calculate a Blowfish hash, given SHA2-512 output of a password and salt. Used as +part of the inner round function in the PBKDF. + +Parameters: + + * `sha2pass`, a Uint8Array of length 64 + * `sha2salt`, a Uint8Array of length 64 + * `out`, a Uint8Array of length 32, will be filled with output + +## License + +This source form is a 1:1 port from the OpenBSD `blowfish.c` and `bcrypt_pbkdf.c`. +As a result, it retains the original copyright and license. The two files are +under slightly different (but compatible) licenses, and are here combined in +one file. For each of the full license texts see `LICENSE`. diff --git a/node_modules/bcrypt-pbkdf/index.js b/node_modules/bcrypt-pbkdf/index.js new file mode 100644 index 0000000..b1b5ad4 --- /dev/null +++ b/node_modules/bcrypt-pbkdf/index.js @@ -0,0 +1,556 @@ +'use strict'; + +var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash; + +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ + +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + +var BLF_J = 0; + +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; + +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; + +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; + +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; + +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; + +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; + + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } +}; + +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } + BLF_J = 0; +}; + +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; + +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; + +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; + +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" + + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } + + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); + + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; + } +}; + +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; + + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; + + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); + + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; + + crypto_hash_sha512(sha2pass, pass, passlen); + + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; + + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; + + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; + } + + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } + + return 0; +}; + +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; diff --git a/node_modules/bcrypt-pbkdf/package.json b/node_modules/bcrypt-pbkdf/package.json new file mode 100644 index 0000000..55fdf87 --- /dev/null +++ b/node_modules/bcrypt-pbkdf/package.json @@ -0,0 +1,44 @@ +{ + "_from": "bcrypt-pbkdf@^1.0.0", + "_id": "bcrypt-pbkdf@1.0.2", + "_inBundle": false, + "_integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "_location": "/bcrypt-pbkdf", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bcrypt-pbkdf@^1.0.0", + "name": "bcrypt-pbkdf", + "escapedName": "bcrypt-pbkdf", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/sshpk" + ], + "_resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "_shasum": "a4301d389b6a43f9b67ff3ca11a3f6637e360e9e", + "_spec": "bcrypt-pbkdf@^1.0.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\sshpk", + "bugs": { + "url": "https://github.com/joyent/node-bcrypt-pbkdf/issues" + }, + "bundleDependencies": false, + "dependencies": { + "tweetnacl": "^0.14.3" + }, + "deprecated": false, + "description": "Port of the OpenBSD bcrypt_pbkdf function to pure JS", + "devDependencies": {}, + "homepage": "https://github.com/joyent/node-bcrypt-pbkdf#readme", + "license": "BSD-3-Clause", + "main": "index.js", + "name": "bcrypt-pbkdf", + "repository": { + "type": "git", + "url": "git://github.com/joyent/node-bcrypt-pbkdf.git" + }, + "version": "1.0.2" +} diff --git a/node_modules/bootstrap/package.json b/node_modules/bootstrap/package.json index 18c849b..00d871a 100644 --- a/node_modules/bootstrap/package.json +++ b/node_modules/bootstrap/package.json @@ -21,7 +21,7 @@ "_resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-4.3.1.tgz", "_shasum": "280ca8f610504d99d7b6b4bfc4b68cec601704ac", "_spec": "bootstrap@^4.3.1", - "_where": "/home/s2/tmp/vanillajs-seed", + "_where": "F:\\projects\\vanillajs-seed", "author": { "name": "The Bootstrap Authors", "url": "https://github.com/twbs/bootstrap/graphs/contributors" diff --git a/node_modules/browser-process-hrtime/LICENSE b/node_modules/browser-process-hrtime/LICENSE new file mode 100644 index 0000000..d78d076 --- /dev/null +++ b/node_modules/browser-process-hrtime/LICENSE @@ -0,0 +1,9 @@ +Copyright 2014 kumavis + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/browser-process-hrtime/README.md b/node_modules/browser-process-hrtime/README.md new file mode 100644 index 0000000..acecb1c --- /dev/null +++ b/node_modules/browser-process-hrtime/README.md @@ -0,0 +1,25 @@ +# browser-process-hrtime + +Browser shim for Node.js process.hrtime(). +See [documentation at nodejs.org](http://nodejs.org/api/process.html#process_process_hrtime) + +### usage +Use hrtime independant of environment (node or browser). +It will use process.hrtime first and fallback if not present. +```js +var hrtime = require('browser-process-hrtime') +var start = hrtime() +// ... +var delta = hrtime(start) +``` + +### monkey-patching +You can monkey-patch process.hrtime for your dependency graph like this: +```js +process.hrtime = require('browser-process-hrtime') +var coolTool = require('module-that-uses-hrtime-somewhere-in-its-depths') +``` + +### note +This was originally pull-requested against [node-process](https://github.com/defunctzombie/node-process), +but they are trying to stay lean. diff --git a/node_modules/browser-process-hrtime/index.js b/node_modules/browser-process-hrtime/index.js new file mode 100644 index 0000000..7312c2c --- /dev/null +++ b/node_modules/browser-process-hrtime/index.js @@ -0,0 +1,28 @@ +module.exports = process.hrtime || hrtime + +// polyfil for window.performance.now +var performance = global.performance || {} +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() } + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3 + var seconds = Math.floor(clocktime) + var nanoseconds = Math.floor((clocktime%1)*1e9) + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0] + nanoseconds = nanoseconds - previousTimestamp[1] + if (nanoseconds<0) { + seconds-- + nanoseconds += 1e9 + } + } + return [seconds,nanoseconds] +} \ No newline at end of file diff --git a/node_modules/browser-process-hrtime/package.json b/node_modules/browser-process-hrtime/package.json new file mode 100644 index 0000000..f65b031 --- /dev/null +++ b/node_modules/browser-process-hrtime/package.json @@ -0,0 +1,46 @@ +{ + "_from": "browser-process-hrtime@^0.1.2", + "_id": "browser-process-hrtime@0.1.3", + "_inBundle": false, + "_integrity": "sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw==", + "_location": "/browser-process-hrtime", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "browser-process-hrtime@^0.1.2", + "name": "browser-process-hrtime", + "escapedName": "browser-process-hrtime", + "rawSpec": "^0.1.2", + "saveSpec": null, + "fetchSpec": "^0.1.2" + }, + "_requiredBy": [ + "/w3c-hr-time" + ], + "_resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz", + "_shasum": "616f00faef1df7ec1b5bf9cfe2bdc3170f26c7b4", + "_spec": "browser-process-hrtime@^0.1.2", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\w3c-hr-time", + "author": { + "name": "kumavis" + }, + "bugs": { + "url": "https://github.com/kumavis/browser-process-hrtime/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Shim for process.hrtime in the browser", + "homepage": "https://github.com/kumavis/browser-process-hrtime#readme", + "license": "BSD-2-Clause", + "main": "index.js", + "name": "browser-process-hrtime", + "repository": { + "type": "git", + "url": "git://github.com/kumavis/browser-process-hrtime.git" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "version": "0.1.3" +} diff --git a/node_modules/buffer-from/LICENSE b/node_modules/buffer-from/LICENSE new file mode 100644 index 0000000..e4bf1d6 --- /dev/null +++ b/node_modules/buffer-from/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016, 2018 Linus Unnebäck + +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. diff --git a/node_modules/buffer-from/index.js b/node_modules/buffer-from/index.js new file mode 100644 index 0000000..d92a83d --- /dev/null +++ b/node_modules/buffer-from/index.js @@ -0,0 +1,69 @@ +var toString = Object.prototype.toString + +var isModern = ( + typeof Buffer.alloc === 'function' && + typeof Buffer.allocUnsafe === 'function' && + typeof Buffer.from === 'function' +) + +function isArrayBuffer (input) { + return toString.call(input).slice(8, -1) === 'ArrayBuffer' +} + +function fromArrayBuffer (obj, byteOffset, length) { + byteOffset >>>= 0 + + var maxLength = obj.byteLength - byteOffset + + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds") + } + + if (length === undefined) { + length = maxLength + } else { + length >>>= 0 + + if (length > maxLength) { + throw new RangeError("'length' is out of bounds") + } + } + + return isModern + ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + return isModern + ? Buffer.from(string, encoding) + : new Buffer(string, encoding) +} + +function bufferFrom (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + return isModern + ? Buffer.from(value) + : new Buffer(value) +} + +module.exports = bufferFrom diff --git a/node_modules/buffer-from/package.json b/node_modules/buffer-from/package.json new file mode 100644 index 0000000..5cfd33d --- /dev/null +++ b/node_modules/buffer-from/package.json @@ -0,0 +1,52 @@ +{ + "_from": "buffer-from@^1.0.0", + "_id": "buffer-from@1.1.1", + "_inBundle": false, + "_integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "_location": "/buffer-from", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "buffer-from@^1.0.0", + "name": "buffer-from", + "escapedName": "buffer-from", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/source-map-support" + ], + "_resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "_shasum": "32713bc028f75c02fdb710d7c7bcec1f2c6070ef", + "_spec": "buffer-from@^1.0.0", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\source-map-support", + "bugs": { + "url": "https://github.com/LinusU/buffer-from/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available.", + "devDependencies": { + "standard": "^7.1.2" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/LinusU/buffer-from#readme", + "keywords": [ + "buffer", + "buffer from" + ], + "license": "MIT", + "name": "buffer-from", + "repository": { + "type": "git", + "url": "git+https://github.com/LinusU/buffer-from.git" + }, + "scripts": { + "test": "standard && node test" + }, + "version": "1.1.1" +} diff --git a/node_modules/buffer-from/readme.md b/node_modules/buffer-from/readme.md new file mode 100644 index 0000000..9880a55 --- /dev/null +++ b/node_modules/buffer-from/readme.md @@ -0,0 +1,69 @@ +# Buffer From + +A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available. + +## Installation + +```sh +npm install --save buffer-from +``` + +## Usage + +```js +const bufferFrom = require('buffer-from') + +console.log(bufferFrom([1, 2, 3, 4])) +//=> + +const arr = new Uint8Array([1, 2, 3, 4]) +console.log(bufferFrom(arr.buffer, 1, 2)) +//=> + +console.log(bufferFrom('test', 'utf8')) +//=> + +const buf = bufferFrom('test') +console.log(bufferFrom(buf)) +//=> +``` + +## API + +### bufferFrom(array) + +- `array` <Array> + +Allocates a new `Buffer` using an `array` of octets. + +### bufferFrom(arrayBuffer[, byteOffset[, length]]) + +- `arrayBuffer` <ArrayBuffer> The `.buffer` property of a TypedArray or ArrayBuffer +- `byteOffset` <Integer> Where to start copying from `arrayBuffer`. **Default:** `0` +- `length` <Integer> How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a TypedArray instance, the +newly created `Buffer` will share the same allocated memory as the TypedArray. + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +### bufferFrom(buffer) + +- `buffer` <Buffer> An existing `Buffer` to copy data from + +Copies the passed `buffer` data onto a new `Buffer` instance. + +### bufferFrom(string[, encoding]) + +- `string` <String> A string to encode. +- `encoding` <String> The encoding of `string`. **Default:** `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `string`. If +provided, the `encoding` parameter identifies the character encoding of +`string`. + +## See also + +- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc` +- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe` diff --git a/node_modules/camel-case/LICENSE b/node_modules/camel-case/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/node_modules/camel-case/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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. diff --git a/node_modules/camel-case/camel-case.d.ts b/node_modules/camel-case/camel-case.d.ts new file mode 100644 index 0000000..782ef3b --- /dev/null +++ b/node_modules/camel-case/camel-case.d.ts @@ -0,0 +1,3 @@ +declare function camelCase (value: string, locale?: string, mergeNumbers?: boolean): string; + +export = camelCase; diff --git a/node_modules/camel-case/camel-case.js b/node_modules/camel-case/camel-case.js new file mode 100644 index 0000000..1be652e --- /dev/null +++ b/node_modules/camel-case/camel-case.js @@ -0,0 +1,23 @@ +var upperCase = require('upper-case') +var noCase = require('no-case') + +/** + * Camel case a string. + * + * @param {string} value + * @param {string} [locale] + * @return {string} + */ +module.exports = function (value, locale, mergeNumbers) { + var result = noCase(value, locale) + + // Replace periods between numeric entities with an underscore. + if (!mergeNumbers) { + result = result.replace(/ (?=\d)/g, '_') + } + + // Replace spaces between words with an upper cased character. + return result.replace(/ (.)/g, function (m, $1) { + return upperCase($1, locale) + }) +} diff --git a/node_modules/camel-case/package.json b/node_modules/camel-case/package.json new file mode 100644 index 0000000..6c2c8db --- /dev/null +++ b/node_modules/camel-case/package.json @@ -0,0 +1,81 @@ +{ + "_from": "camel-case@3.0.x", + "_id": "camel-case@3.0.0", + "_inBundle": false, + "_integrity": "sha1-yjw2iKTpzzpM2nd9xNy8cTJJz3M=", + "_location": "/camel-case", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "camel-case@3.0.x", + "name": "camel-case", + "escapedName": "camel-case", + "rawSpec": "3.0.x", + "saveSpec": null, + "fetchSpec": "3.0.x" + }, + "_requiredBy": [ + "/html-minifier" + ], + "_resolved": "https://registry.npmjs.org/camel-case/-/camel-case-3.0.0.tgz", + "_shasum": "ca3c3688a4e9cf3a4cda777dc4dcbc713249cf73", + "_spec": "camel-case@3.0.x", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\html-minifier", + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "bugs": { + "url": "https://github.com/blakeembrey/camel-case/issues" + }, + "bundleDependencies": false, + "dependencies": { + "no-case": "^2.2.0", + "upper-case": "^1.1.1" + }, + "deprecated": false, + "description": "Camel case a string", + "devDependencies": { + "istanbul": "^0.4.3", + "mocha": "^2.2.1", + "standard": "^7.1.2" + }, + "files": [ + "camel-case.js", + "camel-case.d.ts", + "LICENSE" + ], + "homepage": "https://github.com/blakeembrey/camel-case", + "keywords": [ + "camel", + "case", + "camelcase", + "camel-case", + "dash", + "hyphen", + "dot", + "underscore", + "lodash", + "separator", + "string", + "text", + "convert" + ], + "license": "MIT", + "main": "camel-case.js", + "name": "camel-case", + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/camel-case.git" + }, + "scripts": { + "lint": "standard", + "test": "npm run lint && npm run test-cov", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- -R spec --bail", + "test-spec": "mocha -- -R spec --bail" + }, + "typings": "camel-case.d.ts", + "version": "3.0.0" +} diff --git a/node_modules/caseless/LICENSE b/node_modules/caseless/LICENSE new file mode 100644 index 0000000..61789f4 --- /dev/null +++ b/node_modules/caseless/LICENSE @@ -0,0 +1,28 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +1. Definitions. +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/caseless/README.md b/node_modules/caseless/README.md new file mode 100644 index 0000000..e5077a2 --- /dev/null +++ b/node_modules/caseless/README.md @@ -0,0 +1,45 @@ +## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing. + +This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set. + +## Usage + +```javascript +var headers = {} + , c = caseless(headers) + ; +c.set('a-Header', 'asdf') +c.get('a-header') === 'asdf' +``` + +## has(key) + +Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with. + +```javascript +c.has('a-header') === 'a-Header' +``` + +## set(key, value[, clobber=true]) + +Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header. + +```javascript +c.set('a-Header', 'fdas') +c.set('a-HEADER', 'more', false) +c.get('a-header') === 'fdsa,more' +``` + +## swap(key) + +Swaps the casing of a header with the new one that is passed in. + +```javascript +var headers = {} + , c = caseless(headers) + ; +c.set('a-Header', 'fdas') +c.swap('a-HEADER') +c.has('a-header') === 'a-HEADER' +headers === {'a-HEADER': 'fdas'} +``` diff --git a/node_modules/caseless/index.js b/node_modules/caseless/index.js new file mode 100644 index 0000000..b194734 --- /dev/null +++ b/node_modules/caseless/index.js @@ -0,0 +1,67 @@ +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) + } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) + + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i `0`. +* Fixed issue [#396](https://github.com/jakubpawlowicz/clean-css/issues/396) - better input source maps tracking. +* Fixed issue [#397](https://github.com/jakubpawlowicz/clean-css/issues/397) - support for source map sources. +* Fixed issue [#399](https://github.com/jakubpawlowicz/clean-css/issues/399) - support compacting with source maps. +* Fixed issue [#429](https://github.com/jakubpawlowicz/clean-css/issues/429) - unifies data tokenization. +* Fixed issue [#446](https://github.com/jakubpawlowicz/clean-css/issues/446) - `list-style` fuzzy matching. +* Fixed issue [#468](https://github.com/jakubpawlowicz/clean-css/issues/468) - bumps `source-map` to 0.4.x. +* Fixed issue [#480](https://github.com/jakubpawlowicz/clean-css/issues/480) - extracting uppercase property names. +* Fixed issue [#487](https://github.com/jakubpawlowicz/clean-css/issues/487) - source map paths under Windows. +* Fixed issue [#490](https://github.com/jakubpawlowicz/clean-css/issues/490) - vendor prefixed multivalue `background`. +* Fixed issue [#500](https://github.com/jakubpawlowicz/clean-css/issues/500) - merging duplicate adjacent properties. +* Fixed issue [#504](https://github.com/jakubpawlowicz/clean-css/issues/504) - keeping `url()` quotes. +* Fixed issue [#507](https://github.com/jakubpawlowicz/clean-css/issues/507) - merging longhands into many shorthands. +* Fixed issue [#508](https://github.com/jakubpawlowicz/clean-css/issues/508) - removing duplicate media queries. +* Fixed issue [#521](https://github.com/jakubpawlowicz/clean-css/issues/521) - unit optimizations inside `calc()`. +* Fixed issue [#524](https://github.com/jakubpawlowicz/clean-css/issues/524) - timeouts in `@import` inlining. +* Fixed issue [#526](https://github.com/jakubpawlowicz/clean-css/issues/526) - shorthand overriding into a function. +* Fixed issue [#528](https://github.com/jakubpawlowicz/clean-css/issues/528) - better support for IE<9 hacks. +* Fixed issue [#529](https://github.com/jakubpawlowicz/clean-css/issues/529) - wrong font weight minification. + +[3.1.9 / 2015-04-04](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.8...v3.1.9) +================== + +* Fixes issue [#511](https://github.com/jakubpawlowicz/clean-css/issues/511) - `)` advanced processing. + +[3.1.8 / 2015-03-17](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.7...v3.1.8) +================== + +* Fixes issue [#498](https://github.com/jakubpawlowicz/clean-css/issues/498) - reordering and flexbox. +* Fixes issue [#499](https://github.com/jakubpawlowicz/clean-css/issues/499) - too aggressive `-` removal. + +[3.1.7 / 2015-03-16](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.6...v3.1.7) +================== + +* Backports fix to [#480](https://github.com/jakubpawlowicz/clean-css/issues/480) - reordering and uppercase properties. +* Fixes issue [#496](https://github.com/jakubpawlowicz/clean-css/issues/496) - space after bracket removal. + +[3.1.6 / 2015-03-12](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.5...v3.1.6) +================== + +* Fixes issue [#489](https://github.com/jakubpawlowicz/clean-css/issues/489) - `AlphaImageLoader` IE filter. + +[3.1.5 / 2015-03-06](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.4...v3.1.5) +================== + +* Fixes issue [#483](https://github.com/jakubpawlowicz/clean-css/issues/483) - property order in restructuring. + +[3.1.4 / 2015-03-04](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.3...v3.1.4) +================== + +* Fixes issue [#472](https://github.com/jakubpawlowicz/clean-css/issues/472) - broken function minification. +* Fixes issue [#477](https://github.com/jakubpawlowicz/clean-css/issues/477) - `@import`s order in restructuring. +* Fixes issue [#478](https://github.com/jakubpawlowicz/clean-css/issues/478) - ultimate fix to brace whitespace. + +[3.1.3 / 2015-03-03](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.2...v3.1.3) +================== + +* Fixes issue [#464](https://github.com/jakubpawlowicz/clean-css/issues/464) - data URI with quoted braces. +* Fixes issue [#475](https://github.com/jakubpawlowicz/clean-css/issues/475) - whitespace after closing brace. + +[3.1.2 / 2015-03-01](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.1...v3.1.2) +================== + +* Refixed issue [#471](https://github.com/jakubpawlowicz/clean-css/issues/471) - correct order after restructuring. +* Fixes issue [#466](https://github.com/jakubpawlowicz/clean-css/issues/466) - rebuilding background shorthand. +* Fixes issue [#462](https://github.com/jakubpawlowicz/clean-css/issues/462) - escaped apostrophes in selectors. + +[3.1.1 / 2015-02-27](https://github.com/jakubpawlowicz/clean-css/compare/v3.1.0...v3.1.1) +================== + +* Fixed issue [#469](https://github.com/jakubpawlowicz/clean-css/issues/469) - extracting broken property. +* Fixed issue [#470](https://github.com/jakubpawlowicz/clean-css/issues/470) - negative padding removal. +* Fixed issue [#471](https://github.com/jakubpawlowicz/clean-css/issues/471) - correct order after restructuring. + +[3.1.0 / 2015-02-26](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.10...v3.1.0) +================== + +* Adds `0deg` to `0` minification where possible. +* Adds better non-adjacent selector merging when body is the same. +* Adds official support for node.js 0.12. +* Adds official support for io.js 1.0. +* Adds restructuring optimizations to reorganize selectors, which vastly improves minification. +* Fixed issue [#158](https://github.com/jakubpawlowicz/clean-css/issues/158) - adds body-based selectors reduction. +* Fixed issue [#182](https://github.com/jakubpawlowicz/clean-css/issues/182) - removing space after closing brace. +* Fixed issue [#204](https://github.com/jakubpawlowicz/clean-css/issues/204) - `@media` merging. +* Fixed issue [#351](https://github.com/jakubpawlowicz/clean-css/issues/351) - remote `@import`s after content. +* Fixed issue [#357](https://github.com/jakubpawlowicz/clean-css/issues/357) - non-standard but valid URLs. +* Fixed issue [#416](https://github.com/jakubpawlowicz/clean-css/issues/416) - accepts hash as `minify` argument. +* Fixed issue [#419](https://github.com/jakubpawlowicz/clean-css/issues/419) - multiple input source maps. +* Fixed issue [#435](https://github.com/jakubpawlowicz/clean-css/issues/435) - `background-clip` in shorthand. +* Fixed issue [#439](https://github.com/jakubpawlowicz/clean-css/issues/439) - `background-origin` in shorthand. +* Fixed issue [#442](https://github.com/jakubpawlowicz/clean-css/issues/442) - space before adjacent `nav`. +* Fixed issue [#445](https://github.com/jakubpawlowicz/clean-css/issues/445) - regression issue in url processor. +* Fixed issue [#449](https://github.com/jakubpawlowicz/clean-css/issues/449) - warns of missing close braces. +* Fixed issue [#463](https://github.com/jakubpawlowicz/clean-css/issues/463) - relative remote `@import` URLs. + +[3.0.10 / 2015-02-07](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.9...v3.0.10) +================== + +* Fixed issue [#453](https://github.com/jakubpawlowicz/clean-css/issues/453) - double `background-repeat`. +* Fixed issue [#455](https://github.com/jakubpawlowicz/clean-css/issues/455) - property extracting regression. + +[3.0.9 / 2015-02-04](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.8...v3.0.9) +================== + +* Fixed issue [#452](https://github.com/jakubpawlowicz/clean-css/issues/452) - regression in advanced merging. + +[3.0.8 / 2015-01-31](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.7...v3.0.8) +================== + +* Fixed issue [#447](https://github.com/jakubpawlowicz/clean-css/issues/447) - `background-color` in shorthands. +* Fixed issue [#450](https://github.com/jakubpawlowicz/clean-css/issues/450) - name to hex color converting. + +[3.0.7 / 2015-01-22](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.6...v3.0.7) +================== + +* Fixed issue [#441](https://github.com/jakubpawlowicz/clean-css/issues/441) - hex to name color converting. + +[3.0.6 / 2015-01-20](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.5...v3.0.6) +================== + +* Refixed issue [#414](https://github.com/jakubpawlowicz/clean-css/issues/414) - source maps position fallback. + +[3.0.5 / 2015-01-18](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.4...v3.0.5) +================== + +* Fixed issue [#414](https://github.com/jakubpawlowicz/clean-css/issues/414) - source maps position fallback. +* Fixed issue [#433](https://github.com/jakubpawlowicz/clean-css/issues/433) - meging `!important` in shorthands. + +[3.0.4 / 2015-01-11](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.3...v3.0.4) +================== + +* Fixed issue [#314](https://github.com/jakubpawlowicz/clean-css/issues/314) - spaces inside `calc`. + +[3.0.3 / 2015-01-07](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.2...v3.0.3) +================== + +* Just a version bump as npm incorrectly things 2.2.23 is the latest one. + +[3.0.2 / 2015-01-04](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.1...v3.0.2) +================== + +* Fixed issue [#422](https://github.com/jakubpawlowicz/clean-css/issues/422) - handling `calc` as a unit. + +[3.0.1 / 2014-12-19](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.0...v3.0.1) +================== + +* Fixed issue [#410](https://github.com/jakubpawlowicz/clean-css/issues/410) - advanced merging and comments. +* Fixed issue [#411](https://github.com/jakubpawlowicz/clean-css/issues/411) - properties and important comments. + +[3.0.0 / 2014-12-18](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.22...v3.0.0) +================== + +* Adds more granular control over compatibility settings. +* Adds support for @counter-style at-rule. +* Adds `--source-map`/`sourceMap` switch for building input's source map. +* Adds `--skip-shorthand-compacting`/`shorthandComacting` option for disabling shorthand compacting. +* Allows `target` option to be a path to a folder instead of a file. +* Allows disabling rounding precision. By [@superlukas](https://github.com/superlukas). +* Breaks 2.x compatibility for using CleanCSS as a function. +* Changes `minify` method output to handle multiple outputs. +* Reworks minification to tokenize first then minify. + See [changes](https://github.com/jakubpawlowicz/clean-css/compare/b06f37d...dd8c14a). +* Removes support for node.js 0.8.x. +* Renames `noAdvanced` option into `advanced`. +* Renames `noAggressiveMerging` option into `aggressiveMerging`. +* Renames `noRebase` option into `rebase`. +* Speeds up advanced processing by shortening optimize loop. +* Fixed issue [#125](https://github.com/jakubpawlowicz/clean-css/issues/125) - source maps! +* Fixed issue [#344](https://github.com/jakubpawlowicz/clean-css/issues/344) - merging `background-size` into shorthand. +* Fixed issue [#352](https://github.com/jakubpawlowicz/clean-css/issues/352) - honors rebasing in imported stylesheets. +* Fixed issue [#360](https://github.com/jakubpawlowicz/clean-css/issues/360) - adds 7 extra CSS colors. +* Fixed issue [#363](https://github.com/jakubpawlowicz/clean-css/issues/363) - `rem` units overriding `px`. +* Fixed issue [#373](https://github.com/jakubpawlowicz/clean-css/issues/373) - proper `background` shorthand merging. +* Fixed issue [#395](https://github.com/jakubpawlowicz/clean-css/issues/395) - unescaped brackets in data URIs. +* Fixed issue [#398](https://github.com/jakubpawlowicz/clean-css/issues/398) - restoring important comments. +* Fixed issue [#400](https://github.com/jakubpawlowicz/clean-css/issues/400) - API to accept an array of filenames. +* Fixed issue [#403](https://github.com/jakubpawlowicz/clean-css/issues/403) - tracking input files in source maps. +* Fixed issue [#404](https://github.com/jakubpawlowicz/clean-css/issues/404) - no state sharing in API. +* Fixed issue [#405](https://github.com/jakubpawlowicz/clean-css/issues/405) - disables default `background-size` merging. +* Refixed issue [#304](https://github.com/jakubpawlowicz/clean-css/issues/304) - `background-position` merging. + +[2.2.22 / 2014-12-13](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.21...v2.2.22) +================== + +* Backports fix to issue [#304](https://github.com/jakubpawlowicz/clean-css/issues/304) - `background-position` merging. + +[2.2.21 / 2014-12-10](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.20...v2.2.21) +================== + +* Backports fix to issue [#373](https://github.com/jakubpawlowicz/clean-css/issues/373) - `background` shorthand merging. + +[2.2.20 / 2014-12-02](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.19...v2.2.20) +================== + +* Backports fix to issue [#390](https://github.com/jakubpawlowicz/clean-css/issues/390) - pseudo-class merging. + +[2.2.19 / 2014-11-20](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.18...v2.2.19) +================== + +* Fixed issue [#385](https://github.com/jakubpawlowicz/clean-css/issues/385) - edge cases in processing cut off data. + +[2.2.18 / 2014-11-17](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.17...v2.2.18) +================== + +* Fixed issue [#383](https://github.com/jakubpawlowicz/clean-css/issues/383) - rounding fractions once again. + +[2.2.17 / 2014-11-09](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.16...v2.2.17) +================== + +* Fixed issue [#380](https://github.com/jakubpawlowicz/clean-css/issues/380) - rounding fractions to a whole number. + +[2.2.16 / 2014-09-16](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.15...v2.2.16) +================== + +* Fixed issue [#359](https://github.com/jakubpawlowicz/clean-css/issues/359) - handling escaped double backslash. +* Fixed issue [#358](https://github.com/jakubpawlowicz/clean-css/issues/358) - property merging in compatibility mode. +* Fixed issue [#356](https://github.com/jakubpawlowicz/clean-css/issues/356) - preserving `*+html` hack. +* Fixed issue [#354](https://github.com/jakubpawlowicz/clean-css/issues/354) - `!important` overriding in shorthands. + +[2.2.15 / 2014-09-01](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.14...v2.2.15) +================== + +* Fixed issue [#343](https://github.com/jakubpawlowicz/clean-css/issues/343) - too aggressive `rgba`/`hsla` minification. +* Fixed issue [#345](https://github.com/jakubpawlowicz/clean-css/issues/345) - URL rebasing for document relative ones. +* Fixed issue [#346](https://github.com/jakubpawlowicz/clean-css/issues/346) - overriding `!important` by `!important`. +* Fixed issue [#350](https://github.com/jakubpawlowicz/clean-css/issues/350) - edge cases in `@import` processing. + +[2.2.14 / 2014-08-25](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.13...v2.2.14) +================== + +* Makes multival operations idempotent. +* Fixed issue [#339](https://github.com/jakubpawlowicz/clean-css/issues/339) - skips invalid properties. +* Fixed issue [#341](https://github.com/jakubpawlowicz/clean-css/issues/341) - ensure output is shorter than input. + +[2.2.13 / 2014-08-12](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.12...v2.2.13) +================== + +* Fixed issue [#337](https://github.com/jakubpawlowicz/clean-css/issues/337) - handling component importance. + +[2.2.12 / 2014-08-02](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.11...v2.2.12) +================== + +* Fixed issue with tokenizer removing first selector after an unknown @ rule. +* Fixed issue [#329](https://github.com/jakubpawlowicz/clean-css/issues/329) - `font` shorthands incorrectly processed. +* Fixed issue [#332](https://github.com/jakubpawlowicz/clean-css/issues/332) - `background` shorthand with colors. +* Refixed issue [#325](https://github.com/jakubpawlowicz/clean-css/issues/325) - invalid charset declarations. + +[2.2.11 / 2014-07-28](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.10...v2.2.11) +================== + +* Fixed issue [#326](https://github.com/jakubpawlowicz/clean-css/issues/326) - `background-size` regression. + +[2.2.10 / 2014-07-27](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.9...v2.2.10) +================== + +* Improved performance of advanced mode validators. +* Fixed issue [#307](https://github.com/jakubpawlowicz/clean-css/issues/307) - `background-color` in multiple backgrounds. +* Fixed issue [#322](https://github.com/jakubpawlowicz/clean-css/issues/322) - adds `background-size` support. +* Fixed issue [#323](https://github.com/jakubpawlowicz/clean-css/issues/323) - stripping variable references. +* Fixed issue [#325](https://github.com/jakubpawlowicz/clean-css/issues/325) - removing invalid `@charset` declarations. + +[2.2.9 / 2014-07-23](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.8...v2.2.9) +================== + +* Adds `background` normalization according to W3C spec. +* Fixed issue [#316](https://github.com/jakubpawlowicz/clean-css/issues/316) - incorrect `background` processing. + +[2.2.8 / 2014-07-14](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.7...v2.2.8) +================== + +* Fixed issue [#313](https://github.com/jakubpawlowicz/clean-css/issues/313) - processing comment marks in URLs. +* Fixed issue [#315](https://github.com/jakubpawlowicz/clean-css/issues/315) - `rgba`/`hsla` -> `transparent` in gradients. + +[2.2.7 / 2014-07-10](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.6...v2.2.7) +================== + +* Fixed issue [#304](https://github.com/jakubpawlowicz/clean-css/issues/304) - merging multiple backgrounds. +* Fixed issue [#312](https://github.com/jakubpawlowicz/clean-css/issues/312) - merging with mixed repeat. + +[2.2.6 / 2014-07-05](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.5...v2.2.6) +================== + +* Adds faster quote matching in QuoteScanner. +* Improves QuoteScanner to handle comments correctly. +* Fixed issue [#308](https://github.com/jakubpawlowicz/clean-css/issues/308) - parsing comments in quoted URLs. +* Fixed issue [#311](https://github.com/jakubpawlowicz/clean-css/issues/311) - leading/trailing decimal points. + +[2.2.5 / 2014-06-29](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.4...v2.2.5) +================== + +* Adds removing extra spaces around / in border-radius. +* Adds replacing same horizontal & vertical value in border-radius. +* Fixed issue [#305](https://github.com/jakubpawlowicz/clean-css/issues/305) - allows width keywords in `border-width`. + +[2.2.4 / 2014-06-27](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.3...v2.2.4) +================== + +* Fixed issue [#301](https://github.com/jakubpawlowicz/clean-css/issues/301) - proper `border-radius` processing. +* Fixed issue [#303](https://github.com/jakubpawlowicz/clean-css/issues/303) - correctly preserves viewport units. + +[2.2.3 / 2014-06-24](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.2...v2.2.3) +================== + +* Fixed issue [#302](https://github.com/jakubpawlowicz/clean-css/issues/302) - handling of `outline-style: auto`. + +[2.2.2 / 2014-06-18](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.1...v2.2.2) +================== + +* Fixed issue [#297](https://github.com/jakubpawlowicz/clean-css/issues/297) - `box-shadow` zeros minification. + +[2.2.1 / 2014-06-14](https://github.com/jakubpawlowicz/clean-css/compare/v2.2.0...v2.2.1) +================== + +* Fixes new property optimizer for 'none' values. +* Fixed issue [#294](https://github.com/jakubpawlowicz/clean-css/issues/294) - space after `rgba`/`hsla` in IE<=11. + +[2.2.0 / 2014-06-11](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.8...v2.2.0) +================== + +* Adds a better algorithm for quotation marks' removal. +* Adds a better non-adjacent optimizer compatible with the upcoming new property optimizer. +* Adds minifying remote files directly from CLI. +* Adds `--rounding-precision` to control rounding precision. +* Moves quotation matching into a `QuoteScanner` class. +* Adds `npm run browserify` for creating embeddable version of clean-css. +* Fixed list-style-* advanced processing. +* Fixed issue [#134](https://github.com/jakubpawlowicz/clean-css/issues/134) - merges properties into shorthand form. +* Fixed issue [#164](https://github.com/jakubpawlowicz/clean-css/issues/164) - removes default values if not needed. +* Fixed issue [#168](https://github.com/jakubpawlowicz/clean-css/issues/168) - adds better property merging algorithm. +* Fixed issue [#173](https://github.com/jakubpawlowicz/clean-css/issues/173) - merges same properties if grouped. +* Fixed issue [#184](https://github.com/jakubpawlowicz/clean-css/issues/184) - uses `!important` for optimization opportunities. +* Fixed issue [#190](https://github.com/jakubpawlowicz/clean-css/issues/190) - uses shorthand to override another shorthand. +* Fixed issue [#197](https://github.com/jakubpawlowicz/clean-css/issues/197) - adds borders merging by understandability. +* Fixed issue [#210](https://github.com/jakubpawlowicz/clean-css/issues/210) - adds temporary workaround for aggressive merging. +* Fixed issue [#246](https://github.com/jakubpawlowicz/clean-css/issues/246) - removes IE hacks when not in compatibility mode. +* Fixed issue [#247](https://github.com/jakubpawlowicz/clean-css/issues/247) - removes deprecated `selectorsMergeMode` switch. +* Refixed issue [#250](https://github.com/jakubpawlowicz/clean-css/issues/250) - based on new quotation marks removal. +* Fixed issue [#257](https://github.com/jakubpawlowicz/clean-css/issues/257) - turns `rgba`/`hsla` to `transparent` if possible. +* Fixed issue [#265](https://github.com/jakubpawlowicz/clean-css/issues/265) - adds support for multiple input files. +* Fixed issue [#275](https://github.com/jakubpawlowicz/clean-css/issues/275) - handling transform properties. +* Fixed issue [#276](https://github.com/jakubpawlowicz/clean-css/issues/276) - corrects unicode handling. +* Fixed issue [#288](https://github.com/jakubpawlowicz/clean-css/issues/288) - adds smarter expression parsing. +* Fixed issue [#293](https://github.com/jakubpawlowicz/clean-css/issues/293) - handles escaped `@` symbols in class names and IDs. + +[2.1.8 / 2014-03-28](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.7...v2.1.8) +================== + +* Fixed issue [#267](https://github.com/jakubpawlowicz/clean-css/issues/267) - incorrect non-adjacent selector merging. + +[2.1.7 / 2014-03-24](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.6...v2.1.7) +================== + +* Fixed issue [#264](https://github.com/jakubpawlowicz/clean-css/issues/264) - `@import` statements inside comments. + +[2.1.6 / 2014-03-10](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.5...v2.1.6) +================== + +* Fixed issue [#258](https://github.com/jakubpawlowicz/clean-css/issues/258) - wrong `@import` handling in `EmptyRemoval`. + +[2.1.5 / 2014-03-07](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.4...v2.1.5) +================== + +* Fixed issue [#255](https://github.com/jakubpawlowicz/clean-css/issues/255) - incorrect processing of a trailing `-0`. + +[2.1.4 / 2014-03-01](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.3...v2.1.4) +================== + +* Fixed issue [#250](https://github.com/jakubpawlowicz/clean-css/issues/250) - correctly handle JSON data in quotations. + +[2.1.3 / 2014-02-26](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.2...v2.1.3) +================== + +* Fixed issue [#248](https://github.com/jakubpawlowicz/clean-css/issues/248) - incorrect merging for vendor selectors. + +[2.1.2 / 2014-02-25](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.1...v2.1.2) +================== + +* Fixed issue [#245](https://github.com/jakubpawlowicz/clean-css/issues/245) - incorrect handling of backslash IE hack. + +[2.1.1 / 2014-02-18](https://github.com/jakubpawlowicz/clean-css/compare/v2.1.0...v2.1.1) +================== + +* Adds faster selectors processing in advanced optimizer. +* Fixed issue [#241](https://github.com/jakubpawlowicz/clean-css/issues/241) - incorrect handling of `:not()` selectors. + +[2.1.0 / 2014-02-13](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.8...v2.1.0) +================== + +* Adds an optional callback to minify method. +* Deprecates `--selectors-merge-mode` / `selectorsMergeMode` in favor to `--compatibility` / `compatibility`. +* Fixes debug mode stats for stylesheets using `@import` statements. +* Skips empty removal if advanced processing is enabled. +* Fixed issue [#85](https://github.com/jakubpawlowicz/clean-css/issues/85) - resolving protocol `@import`s. +* Fixed issue [#160](https://github.com/jakubpawlowicz/clean-css/issues/160) - re-runs optimizer until a clean pass. +* Fixed issue [#161](https://github.com/jakubpawlowicz/clean-css/issues/161) - improves tokenizer performance. +* Fixed issue [#163](https://github.com/jakubpawlowicz/clean-css/issues/163) - round pixels to 2nd decimal place. +* Fixed issue [#165](https://github.com/jakubpawlowicz/clean-css/issues/165) - extra space after trailing parenthesis. +* Fixed issue [#186](https://github.com/jakubpawlowicz/clean-css/issues/186) - strip unit from `0rem`. +* Fixed issue [#207](https://github.com/jakubpawlowicz/clean-css/issues/207) - bug in parsing protocol `@import`s. +* Fixed issue [#213](https://github.com/jakubpawlowicz/clean-css/issues/213) - faster `rgb` to `hex` transforms. +* Fixed issue [#215](https://github.com/jakubpawlowicz/clean-css/issues/215) - leading zeros in numerical values. +* Fixed issue [#217](https://github.com/jakubpawlowicz/clean-css/issues/217) - whitespace inside attribute selectors and URLs. +* Fixed issue [#218](https://github.com/jakubpawlowicz/clean-css/issues/218) - `@import` statements cleanup. +* Fixed issue [#220](https://github.com/jakubpawlowicz/clean-css/issues/220) - selector between comments. +* Fixed issue [#223](https://github.com/jakubpawlowicz/clean-css/issues/223) - two-pass adjacent selectors merging. +* Fixed issue [#226](https://github.com/jakubpawlowicz/clean-css/issues/226) - don't minify `border:none` to `border:0`. +* Fixed issue [#229](https://github.com/jakubpawlowicz/clean-css/issues/229) - improved processing of fraction numbers. +* Fixed issue [#230](https://github.com/jakubpawlowicz/clean-css/issues/230) - better handling of zero values. +* Fixed issue [#235](https://github.com/jakubpawlowicz/clean-css/issues/235) - IE7 compatibility mode. +* Fixed issue [#236](https://github.com/jakubpawlowicz/clean-css/issues/236) - incorrect rebasing with nested `import`s. + +[2.0.8 / 2014-02-07](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.7...v2.0.8) +================== + +* Fixed issue [#232](https://github.com/jakubpawlowicz/clean-css/issues/232) - edge case in non-adjacent selectors merging. + +[2.0.7 / 2014-01-16](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.6...v2.0.7) +================== + +* Fixed issue [#208](https://github.com/jakubpawlowicz/clean-css/issues/208) - don't swallow `@page` and `@viewport`. + +[2.0.6 / 2014-01-04](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.5...v2.0.6) +================== + +* Fixed issue [#198](https://github.com/jakubpawlowicz/clean-css/issues/198) - process comments and `@import`s correctly. +* Fixed issue [#205](https://github.com/jakubpawlowicz/clean-css/issues/205) - freeze on broken `@import` declaration. + +[2.0.5 / 2014-01-03](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.4...v2.0.5) +================== + +* Fixed issue [#199](https://github.com/jakubpawlowicz/clean-css/issues/199) - keep line breaks with no advanced optimizations. +* Fixed issue [#203](https://github.com/jakubpawlowicz/clean-css/issues/203) - Buffer as a first argument to minify method. + +[2.0.4 / 2013-12-19](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.3...v2.0.4) +================== + +* Fixed issue [#193](https://github.com/jakubpawlowicz/clean-css/issues/193) - HSL color space normalization. + +[2.0.3 / 2013-12-18](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.2...v2.0.3) +================== + +* Fixed issue [#191](https://github.com/jakubpawlowicz/clean-css/issues/191) - leading numbers in `font`/`animation` names. +* Fixed issue [#192](https://github.com/jakubpawlowicz/clean-css/issues/192) - many `@import`s inside a comment. + +[2.0.2 / 2013-11-18](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.1...v2.0.2) +================== + +* Fixed issue [#177](https://github.com/jakubpawlowicz/clean-css/issues/177) - process broken content correctly. + +[2.0.1 / 2013-11-14](https://github.com/jakubpawlowicz/clean-css/compare/v2.0.0...v2.0.1) +================== + +* Fixed issue [#176](https://github.com/jakubpawlowicz/clean-css/issues/176) - hangs on `undefined` keyword. + +[2.0.0 / 2013-11-04](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.7...v2.0.0) +================== + +* Adds simplified and more advanced text escaping / restoring via `EscapeStore` class. +* Adds simplified and much faster empty elements removal. +* Adds missing `@import` processing to our benchmark (run via `npm run bench`). +* Adds CSS tokenizer which will make it possible to optimize content by reordering and/or merging selectors. +* Adds basic optimizer removing duplicate selectors from a list. +* Adds merging duplicate properties within a single selector's body. +* Adds merging adjacent selectors within a scope (single and multiple ones). +* Changes behavior of `--keep-line-breaks`/`keepBreaks` option to keep breaks after trailing braces only. +* Makes all multiple selectors ordered alphabetically (aids merging). +* Adds property overriding so more coarse properties override more granular ones. +* Adds reducing non-adjacent selectors. +* Adds `--skip-advanced`/`noAdvanced` switch to disable advanced optimizations. +* Adds reducing non-adjacent selectors when overridden by more complex selectors. +* Fixed issue [#138](https://github.com/jakubpawlowicz/clean-css/issues/138) - makes CleanCSS interface OO. +* Fixed issue [#139](https://github.com/jakubpawlowicz/clean-css/issues/138) - consistent error & warning handling. +* Fixed issue [#145](https://github.com/jakubpawlowicz/clean-css/issues/145) - debug mode in library too. +* Fixed issue [#157](https://github.com/jakubpawlowicz/clean-css/issues/157) - gets rid of `removeEmpty` option. +* Fixed issue [#159](https://github.com/jakubpawlowicz/clean-css/issues/159) - escaped quotes inside content. +* Fixed issue [#162](https://github.com/jakubpawlowicz/clean-css/issues/162) - strip quotes from Base64 encoded URLs. +* Fixed issue [#166](https://github.com/jakubpawlowicz/clean-css/issues/166) - `debug` formatting in CLI +* Fixed issue [#167](https://github.com/jakubpawlowicz/clean-css/issues/167) - `background:transparent` minification. + +[1.1.7 / 2013-10-28](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.6...v1.1.7) +================== + +* Fixed issue [#156](https://github.com/jakubpawlowicz/clean-css/issues/156) - `@import`s inside comments. + +[1.1.6 / 2013-10-26](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.5...v1.1.6) +================== + +* Fixed issue [#155](https://github.com/jakubpawlowicz/clean-css/issues/155) - broken irregular CSS content. + +[1.1.5 / 2013-10-24](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.4...v1.1.5) +================== + +* Fixed issue [#153](https://github.com/jakubpawlowicz/clean-css/issues/153) - `keepSpecialComments` `0`/`1` as a string. + +[1.1.4 / 2013-10-23](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.3...v1.1.4) +================== + +* Fixed issue [#152](https://github.com/jakubpawlowicz/clean-css/issues/152) - adds an option to disable rebasing. + +[1.1.3 / 2013-10-04](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.2...v1.1.3) +================== + +* Fixed issue [#150](https://github.com/jakubpawlowicz/clean-css/issues/150) - minifying `background:none`. + +[1.1.2 / 2013-09-29](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.1...v1.1.2) +================== + +* Fixed issue [#149](https://github.com/jakubpawlowicz/clean-css/issues/149) - shorthand `font` property. + +[1.1.1 / 2013-09-07](https://github.com/jakubpawlowicz/clean-css/compare/v1.1.0...v1.1.1) +================== + +* Fixed issue [#144](https://github.com/jakubpawlowicz/clean-css/issues/144) - skip URLs rebasing by default. + +[1.1.0 / 2013-09-06](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.12...v1.1.0) +================== + +* Renamed lib's `debug` option to `benchmark` when doing per-minification benchmarking. +* Added simplified comments processing & imports. +* Fixed issue [#43](https://github.com/jakubpawlowicz/clean-css/issues/43) - `--debug` switch for minification stats. +* Fixed issue [#65](https://github.com/jakubpawlowicz/clean-css/issues/65) - full color name / hex shortening. +* Fixed issue [#84](https://github.com/jakubpawlowicz/clean-css/issues/84) - support for `@import` with media queries. +* Fixed issue [#124](https://github.com/jakubpawlowicz/clean-css/issues/124) - raise error on broken imports. +* Fixed issue [#126](https://github.com/jakubpawlowicz/clean-css/issues/126) - proper CSS expressions handling. +* Fixed issue [#129](https://github.com/jakubpawlowicz/clean-css/issues/129) - rebasing imported URLs. +* Fixed issue [#130](https://github.com/jakubpawlowicz/clean-css/issues/130) - better code modularity. +* Fixed issue [#135](https://github.com/jakubpawlowicz/clean-css/issues/135) - require node.js 0.8+. + +[1.0.12 / 2013-07-19](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.11...v1.0.12) +=================== + +* Fixed issue [#121](https://github.com/jakubpawlowicz/clean-css/issues/121) - ability to skip `@import` processing. + +[1.0.11 / 2013-07-08](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.10...v1.0.11) +=================== + +* Fixed issue [#117](https://github.com/jakubpawlowicz/clean-css/issues/117) - line break escaping in comments. + +[1.0.10 / 2013-06-13](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.9...v1.0.10) +=================== + +* Fixed issue [#114](https://github.com/jakubpawlowicz/clean-css/issues/114) - comments in imported stylesheets. + +[1.0.9 / 2013-06-11](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.8...v1.0.9) +================== + +* Fixed issue [#113](https://github.com/jakubpawlowicz/clean-css/issues/113) - `@import` in comments. + +[1.0.8 / 2013-06-10](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.7...v1.0.8) +================== + +* Fixed issue [#112](https://github.com/jakubpawlowicz/clean-css/issues/112) - reducing `box-shadow` zeros. + +[1.0.7 / 2013-06-05](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.6...v1.0.7) +================== + +* Support for `@import` URLs starting with `//`. By [@petetak](https://github.com/petetak). + +[1.0.6 / 2013-06-04](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.5...v1.0.6) +================== + +* Fixed issue [#110](https://github.com/jakubpawlowicz/clean-css/issues/110) - data URIs in URLs. + +[1.0.5 / 2013-05-26](https://github.com/jakubpawlowicz/clean-css/compare/v1.0.4...v1.0.5) +================== + +* Fixed issue [#107](https://github.com/jakubpawlowicz/clean-css/issues/107) - data URIs in imported stylesheets. + +1.0.4 / 2013-05-23 +================== + +* Rewrite relative URLs in imported stylesheets. By [@bluej100](https://github.com/bluej100). + +1.0.3 / 2013-05-20 +================== + +* Support alternative `@import` syntax with file name not wrapped inside `url()` statement. + By [@bluej100](https://github.com/bluej100). + +1.0.2 / 2013-04-29 +================== + +* Fixed issue [#97](https://github.com/jakubpawlowicz/clean-css/issues/97) - `--remove-empty` & FontAwesome. + +1.0.1 / 2013-04-08 +================== + +* Do not pick up `bench` and `test` while building `npm` package. + By [@sindresorhus](https://https://github.com/sindresorhus). + +1.0.0 / 2013-03-30 +================== + +* Fixed issue [#2](https://github.com/jakubpawlowicz/clean-css/issues/2) - resolving `@import` rules. +* Fixed issue [#44](https://github.com/jakubpawlowicz/clean-css/issues/44) - examples in `--help`. +* Fixed issue [#46](https://github.com/jakubpawlowicz/clean-css/issues/46) - preserving special characters in URLs and attributes. +* Fixed issue [#80](https://github.com/jakubpawlowicz/clean-css/issues/80) - quotation in multi line strings. +* Fixed issue [#83](https://github.com/jakubpawlowicz/clean-css/issues/83) - HSL to hex color conversions. +* Fixed issue [#86](https://github.com/jakubpawlowicz/clean-css/issues/86) - broken `@charset` replacing. +* Fixed issue [#88](https://github.com/jakubpawlowicz/clean-css/issues/88) - removes space in `! important`. +* Fixed issue [#92](https://github.com/jakubpawlowicz/clean-css/issues/92) - uppercase hex to short versions. + +0.10.2 / 2013-03-19 +=================== + +* Fixed issue [#79](https://github.com/jakubpawlowicz/clean-css/issues/79) - node.js 0.10.x compatibility. + +0.10.1 / 2013-02-14 +=================== + +* Fixed issue [#66](https://github.com/jakubpawlowicz/clean-css/issues/66) - line breaks without extra spaces should + be handled correctly. + +0.10.0 / 2013-02-09 +=================== + +* Switched from [optimist](https://github.com/substack/node-optimist) to + [commander](https://github.com/visionmedia/commander.js) for CLI processing. +* Changed long options from `--removeempty` to `--remove-empty` and from `--keeplinebreaks` to `--keep-line-breaks`. +* Fixed performance issue with replacing multiple `@charset` declarations and issue + with line break after `@charset` when using `keepLineBreaks` option. By [@rrjaime](https://github.com/rrjamie). +* Removed Makefile in favor to `npm run` commands (e.g. `make check` -> `npm run check`). +* Fixed issue [#47](https://github.com/jakubpawlowicz/clean-css/issues/47) - commandline issues on Windows. +* Fixed issue [#49](https://github.com/jakubpawlowicz/clean-css/issues/49) - remove empty selectors from media query. +* Fixed issue [#52](https://github.com/jakubpawlowicz/clean-css/issues/52) - strip fraction zeros if not needed. +* Fixed issue [#58](https://github.com/jakubpawlowicz/clean-css/issues/58) - remove colon where possible. +* Fixed issue [#59](https://github.com/jakubpawlowicz/clean-css/issues/59) - content property handling. + +0.9.1 / 2012-12-19 +================== + +* Fixed issue [#37](https://github.com/jakubpawlowicz/clean-css/issues/37) - converting + `white` and other colors in class names (reported by [@malgorithms](https://github.com/malgorithms)). + +0.9.0 / 2012-12-15 +================== + +* Added stripping quotation from font names (if possible). +* Added stripping quotation from `@keyframes` declaration, `animation` and + `animation-name` property. +* Added stripping quotations from attributes' value (e.g. `[data-target='x']`). +* Added better hex->name and name->hex color shortening. +* Added `font: normal` and `font: bold` shortening the same way as `font-weight` is. +* Refactored shorthand selectors and added `border-radius`, `border-style` + and `border-color` shortening. +* Added `margin`, `padding` and `border-width` shortening. +* Added removing line break after commas. +* Fixed removing whitespace inside media query definition. +* Added removing line breaks after a comma, so all declarations are one-liners now. +* Speed optimizations (~10% despite many new features). +* Added [JSHint](https://github.com/jshint/jshint/) validation rules via `make check`. + +0.8.3 / 2012-11-29 +================== + +* Fixed HSL/HSLA colors processing. + +0.8.2 / 2012-10-31 +================== + +* Fixed shortening hex colors and their relation to hashes in URLs. +* Cleanup by [@XhmikosR](https://github.com/XhmikosR). + +0.8.1 / 2012-10-28 +================== + +* Added better zeros processing for `rect(...)` syntax (clip property). + +0.8.0 / 2012-10-21 +================== + +* Added removing URLs quotation if possible. +* Rewrote breaks processing. +* Added `keepBreaks`/`-b` option to keep line breaks in the minimized file. +* Reformatted [lib/clean.js](/lib/clean.js) so it's easier to follow the rules. +* Minimized test data is now minimized with line breaks so it's easier to + compare the changes line by line. + +0.7.0 / 2012-10-14 +================== + +* Added stripping special comments to CLI (`--s0` and `--s1` options). +* Added stripping special comments to programmatic interface + (`keepSpecialComments` option). + +0.6.0 / 2012-08-05 +================== + +* Full Windows support with tests (./test.bat). + +0.5.0 / 2012-08-02 +================== + +* Made path to vows local. +* Explicit node.js 0.6 requirement. + +0.4.2 / 2012-06-28 +================== + +* Updated binary `-v` option (version). +* Updated binary to output help when no options given (but not in piped mode). +* Added binary tests. + +0.4.1 / 2012-06-10 +================== + +* Fixed stateless mode where calling `CleanCSS#process` directly was giving + errors (reported by [@facelessuser](https://github.com/facelessuser)). + +0.4.0 / 2012-06-04 +================== + +* Speed improvements up to 4x thanks to the rewrite of comments and CSS' content + processing. +* Stripping empty CSS tags is now optional (see [bin/cleancss](/bin/cleancss) for details). +* Improved debugging mode (see [test/bench.js](/test/bench.js)) +* Added `make bench` for a one-pass benchmark. + +0.3.3 / 2012-05-27 +================== + +* Fixed tests, [package.json](/package.json) for development, and regex + for removing empty declarations (thanks to [@vvo](https://github.com/vvo)). + +0.3.2 / 2012-01-17 +================== + +* Fixed output method under node.js 0.6 which incorrectly tried to close + `process.stdout`. + +0.3.1 / 2011-12-16 +================== + +* Fixed cleaning up `0 0 0 0` expressions. + +0.3.0 / 2011-11-29 +================== + +* Clean-css requires node.js 0.4.0+ to run. +* Removed node.js's 0.2.x 'sys' package dependency + (thanks to [@jmalonzo](https://github.com/jmalonzo) for a patch). + +0.2.6 / 2011-11-27 +================== + +* Fixed expanding `+` signs in `calc()` when mixed up with adjacent `+` selector. + +0.2.5 / 2011-11-27 +================== + +* Fixed issue with cleaning up spaces inside `calc`/`-moz-calc` declarations + (thanks to [@cvan](https://github.com/cvan) for reporting it). +* Fixed converting `#f00` to `red` in borders and gradients. + +0.2.4 / 2011-05-25 +================== + +* Fixed problem with expanding `none` to `0` in partial/full background + declarations. +* Fixed including clean-css library from binary (global to local). + +0.2.3 / 2011-04-18 +================== + +* Fixed problem with optimizing IE filters. + +0.2.2 / 2011-04-17 +================== + +* Fixed problem with space before color in `border` property. + +0.2.1 / 2011-03-19 +================== + +* Added stripping space before `!important` keyword. +* Updated repository location and author information in [package.json](/package.json). + +0.2.0 / 2011-03-02 +================== + +* Added options parsing via optimist. +* Changed code inclusion (thus the version bump). + +0.1.0 / 2011-02-27 +================== + +* First version of clean-css library. +* Implemented all basic CSS transformations. diff --git a/node_modules/clean-css/LICENSE b/node_modules/clean-css/LICENSE new file mode 100644 index 0000000..bf2f405 --- /dev/null +++ b/node_modules/clean-css/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2017 JakubPawlowicz.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. diff --git a/node_modules/clean-css/README.md b/node_modules/clean-css/README.md new file mode 100644 index 0000000..3f7965b --- /dev/null +++ b/node_modules/clean-css/README.md @@ -0,0 +1,764 @@ +

+
+ clean-css logo +
+
+

+ +[![NPM version](https://img.shields.io/npm/v/clean-css.svg?style=flat)](https://www.npmjs.com/package/clean-css) +[![Linux Build Status](https://img.shields.io/travis/jakubpawlowicz/clean-css/master.svg?style=flat&label=Linux%20build)](https://travis-ci.org/jakubpawlowicz/clean-css) +[![Windows Build status](https://img.shields.io/appveyor/ci/jakubpawlowicz/clean-css/master.svg?style=flat&label=Windows%20build)](https://ci.appveyor.com/project/jakubpawlowicz/clean-css/branch/master) +[![Dependency Status](https://img.shields.io/david/jakubpawlowicz/clean-css.svg?style=flat)](https://david-dm.org/jakubpawlowicz/clean-css) +[![NPM Downloads](https://img.shields.io/npm/dm/clean-css.svg)](https://npmcharts.com/compare/clean-css?minimal=true) +[![Twitter](https://img.shields.io/badge/Twitter-@cleancss-blue.svg)](https://twitter.com/cleancss) + +clean-css is a fast and efficient CSS optimizer for [Node.js](http://nodejs.org/) platform and [any modern browser](https://jakubpawlowicz.github.io/clean-css). + +According to [tests](http://goalsmashers.github.io/css-minification-benchmark/) it is one of the best available. + +**Table of Contents** + +- [Node.js version support](#nodejs-version-support) +- [Install](#install) +- [Use](#use) + * [Important: 4.0 breaking changes](#important-40-breaking-changes) + * [What's new in version 4.1](#whats-new-in-version-41) + * [What's new in version 4.2](#whats-new-in-version-42) + * [Constructor options](#constructor-options) + * [Compatibility modes](#compatibility-modes) + * [Fetch option](#fetch-option) + * [Formatting options](#formatting-options) + * [Inlining options](#inlining-options) + * [Optimization levels](#optimization-levels) + + [Level 0 optimizations](#level-0-optimizations) + + [Level 1 optimizations](#level-1-optimizations) + + [Level 2 optimizations](#level-2-optimizations) + * [Minify method](#minify-method) + * [Promise interface](#promise-interface) + * [CLI utility](#cli-utility) +- [FAQ](#faq) + * [How to optimize multiple files?](#how-to-optimize-multiple-files) + * [How to process remote `@import`s correctly?](#how-to-process-remote-imports-correctly) + * [How to apply arbitrary transformations to CSS properties?](#how-to-apply-arbitrary-transformations-to-css-properties) + * [How to specify a custom rounding precision?](#how-to-specify-a-custom-rounding-precision) + * [How to keep a CSS fragment intact?](#how-to-keep-a-css-fragment-intact) + * [How to preserve a comment block?](#how-to-preserve-a-comment-block) + * [How to rebase relative image URLs?](#how-to-rebase-relative-image-urls) + * [How to work with source maps?](#how-to-work-with-source-maps) + * [How to apply level 1 & 2 optimizations at the same time?](#how-to-apply-level-1--2-optimizations-at-the-same-time) + * [What level 2 optimizations do?](#what-level-2-optimizations-do) + * [How to use clean-css with build tools?](#how-to-use-clean-css-with-build-tools) + * [How to use clean-css from web browser?](#how-to-use-clean-css-from-web-browser) +- [Contributing](#contributing) + * [How to get started?](#how-to-get-started) +- [Acknowledgments](#acknowledgments) +- [License](#license) + +# Node.js version support + +clean-css requires Node.js 4.0+ (tested on Linux, OS X, and Windows) + +# Install + +``` +npm install --save-dev clean-css +``` + +# Use + +```js +var CleanCSS = require('clean-css'); +var input = 'a{font-weight:bold;}'; +var options = { /* options */ }; +var output = new CleanCSS(options).minify(input); +``` + +## Important: 4.0 breaking changes + +clean-css 4.0 introduces some breaking changes: + +* API and CLI interfaces are split, so API stays in this repository while CLI moves to [clean-css-cli](https://github.com/jakubpawlowicz/clean-css-cli); +* `root`, `relativeTo`, and `target` options are replaced by a single `rebaseTo` option - this means that rebasing URLs and import inlining is much simpler but may not be (YMMV) as powerful as in 3.x; +* `debug` option is gone as stats are always provided in output object under `stats` property; +* `roundingPrecision` is disabled by default; +* `roundingPrecision` applies to **all** units now, not only `px` as in 3.x; +* `processImport` and `processImportFrom` are merged into `inline` option which defaults to `local`. Remote `@import` rules are **NOT** inlined by default anymore; +* splits `inliner: { request: ..., timeout: ... }` option into `inlineRequest` and `inlineTimeout` options; +* remote resources without a protocol, e.g. `//fonts.googleapis.com/css?family=Domine:700`, are not inlined anymore; +* changes default Internet Explorer compatibility from 9+ to 10+, to revert the old default use `{ compatibility: 'ie9' }` flag; +* renames `keepSpecialComments` to `specialComments`; +* moves `roundingPrecision` and `specialComments` to level 1 optimizations options, see examples; +* moves `mediaMerging`, `restructuring`, `semanticMerging`, and `shorthandCompacting` to level 2 optimizations options, see examples below; +* renames `shorthandCompacting` option to `mergeIntoShorthands`; +* level 1 optimizations are the new default, up to 3.x it was level 2; +* `keepBreaks` option is replaced with `{ format: 'keep-breaks' }` to ease transition; +* `sourceMap` option has to be a boolean from now on - to specify an input source map pass it a 2nd argument to `minify` method or via a hash instead; +* `aggressiveMerging` option is removed as aggressive merging is replaced by smarter override merging. + +## What's new in version 4.1 + +clean-css 4.1 introduces the following changes / features: + +* `inline: false` as an alias to `inline: ['none']`; +* `multiplePseudoMerging` compatibility flag controlling merging of rules with multiple pseudo classes / elements; +* `removeEmpty` flag in level 1 optimizations controlling removal of rules and nested blocks; +* `removeEmpty` flag in level 2 optimizations controlling removal of rules and nested blocks; +* `compatibility: { selectors: { mergeLimit: } }` flag in compatibility settings controlling maximum number of selectors in a single rule; +* `minify` method improved signature accepting a list of hashes for a predictable traversal; +* `selectorsSortingMethod` level 1 optimization allows `false` or `'none'` for disabling selector sorting; +* `fetch` option controlling a function for handling remote requests; +* new `font` shorthand and `font-*` longhand optimizers; +* removal of `optimizeFont` flag in level 1 optimizations due to new `font` shorthand optimizer; +* `skipProperties` flag in level 2 optimizations controlling which properties won't be optimized; +* new `animation` shorthand and `animation-*` longhand optimizers; +* `removeUnusedAtRules` level 2 optimization controlling removal of unused `@counter-style`, `@font-face`, `@keyframes`, and `@namespace` at rules; +* the [web interface](https://jakubpawlowicz.github.io/clean-css) gets an improved settings panel with "reset to defaults", instant option changes, and settings being persisted across sessions. + +## What's new in version 4.2 + +clean-css 4.2 introduces the following changes / features: + +* Adds `process` method for compatibility with optimize-css-assets-webpack-plugin; +* new `transition` property optimizer; +* preserves any CSS content between `/* clean-css ignore:start */` and `/* clean-css ignore:end */` comments; +* allows filtering based on selector in `transform` callback, see [example](#how-to-apply-arbitrary-transformations-to-css-properties); +* adds configurable line breaks via `format: { breakWith: 'lf' }` option. + +## Constructor options + +clean-css constructor accepts a hash as a parameter with the following options available: + +* `compatibility` - controls compatibility mode used; defaults to `ie10+`; see [compatibility modes](#compatibility-modes) for examples; +* `fetch` - controls a function for handling remote requests; see [fetch option](#fetch-option) for examples (since 4.1.0); +* `format` - controls output CSS formatting; defaults to `false`; see [formatting options](#formatting-options) for examples; +* `inline` - controls `@import` inlining rules; defaults to `'local'`; see [inlining options](#inlining-options) for examples; +* `inlineRequest` - controls extra options for inlining remote `@import` rules, can be any of [HTTP(S) request options](https://nodejs.org/api/http.html#http_http_request_options_callback); +* `inlineTimeout` - controls number of milliseconds after which inlining a remote `@import` fails; defaults to 5000; +* `level` - controls optimization level used; defaults to `1`; see [optimization levels](#optimization-levels) for examples; +* `rebase` - controls URL rebasing; defaults to `true`; +* `rebaseTo` - controls a directory to which all URLs are rebased, most likely the directory under which the output file will live; defaults to the current directory; +* `returnPromise` - controls whether `minify` method returns a Promise object or not; defaults to `false`; see [promise interface](#promise-interface) for examples; +* `sourceMap` - controls whether an output source map is built; defaults to `false`; +* `sourceMapInlineSources` - controls embedding sources inside a source map's `sourcesContent` field; defaults to false. + +## Compatibility modes + +There is a certain number of compatibility mode shortcuts, namely: + +* `new CleanCSS({ compatibility: '*' })` (default) - Internet Explorer 10+ compatibility mode +* `new CleanCSS({ compatibility: 'ie9' })` - Internet Explorer 9+ compatibility mode +* `new CleanCSS({ compatibility: 'ie8' })` - Internet Explorer 8+ compatibility mode +* `new CleanCSS({ compatibility: 'ie7' })` - Internet Explorer 7+ compatibility mode + +Each of these modes is an alias to a [fine grained configuration](https://github.com/jakubpawlowicz/clean-css/blob/master/lib/options/compatibility.js), with the following options available: + +```js +new CleanCSS({ + compatibility: { + colors: { + opacity: true // controls `rgba()` / `hsla()` color support + }, + properties: { + backgroundClipMerging: true, // controls background-clip merging into shorthand + backgroundOriginMerging: true, // controls background-origin merging into shorthand + backgroundSizeMerging: true, // controls background-size merging into shorthand + colors: true, // controls color optimizations + ieBangHack: false, // controls keeping IE bang hack + ieFilters: false, // controls keeping IE `filter` / `-ms-filter` + iePrefixHack: false, // controls keeping IE prefix hack + ieSuffixHack: false, // controls keeping IE suffix hack + merging: true, // controls property merging based on understandability + shorterLengthUnits: false, // controls shortening pixel units into `pc`, `pt`, or `in` units + spaceAfterClosingBrace: true, // controls keeping space after closing brace - `url() no-repeat` into `url()no-repeat` + urlQuotes: false, // controls keeping quoting inside `url()` + zeroUnits: true // controls removal of units `0` value + }, + selectors: { + adjacentSpace: false, // controls extra space before `nav` element + ie7Hack: true, // controls removal of IE7 selector hacks, e.g. `*+html...` + mergeablePseudoClasses: [':active', ...], // controls a whitelist of mergeable pseudo classes + mergeablePseudoElements: ['::after', ...], // controls a whitelist of mergeable pseudo elements + mergeLimit: 8191, // controls maximum number of selectors in a single rule (since 4.1.0) + multiplePseudoMerging: true // controls merging of rules with multiple pseudo classes / elements (since 4.1.0) + }, + units: { + ch: true, // controls treating `ch` as a supported unit + in: true, // controls treating `in` as a supported unit + pc: true, // controls treating `pc` as a supported unit + pt: true, // controls treating `pt` as a supported unit + rem: true, // controls treating `rem` as a supported unit + vh: true, // controls treating `vh` as a supported unit + vm: true, // controls treating `vm` as a supported unit + vmax: true, // controls treating `vmax` as a supported unit + vmin: true // controls treating `vmin` as a supported unit + } + } +}) +``` + +You can also use a string when setting a compatibility mode, e.g. + +```js +new CleanCSS({ + compatibility: 'ie9,-properties.merging' // sets compatibility to IE9 mode with disabled property merging +}) +``` + +## Fetch option + +The `fetch` option accepts a function which handles remote resource fetching, e.g. + +```js +var request = require('request'); +var source = '@import url(http://example.com/path/to/stylesheet.css);'; +new CleanCSS({ + fetch: function (uri, inlineRequest, inlineTimeout, callback) { + request(uri, function (error, response, body) { + if (error) { + callback(error, null); + } else if (response && response.statusCode != 200) { + callback(response.statusCode, null); + } else { + callback(null, body); + } + }); + } +}).minify(source); +``` + +This option provides a convenient way of overriding the default fetching logic if it doesn't support a particular feature, say CONNECT proxies. + +Unless given, the default [loadRemoteResource](https://github.com/jakubpawlowicz/clean-css/blob/master/lib/reader/load-remote-resource.js) logic is used. + +## Formatting options + +By default output CSS is formatted without any whitespace unless a `format` option is given. +First of all there are two shorthands: + +```js +new CleanCSS({ + format: 'beautify' // formats output in a really nice way +}) +``` + +and + +```js +new CleanCSS({ + format: 'keep-breaks' // formats output the default way but adds line breaks for improved readability +}) +``` + +however `format` option also accept a fine-grained set of options: + +```js +new CleanCSS({ + format: { + breaks: { // controls where to insert breaks + afterAtRule: false, // controls if a line break comes after an at-rule; e.g. `@charset`; defaults to `false` + afterBlockBegins: false, // controls if a line break comes after a block begins; e.g. `@media`; defaults to `false` + afterBlockEnds: false, // controls if a line break comes after a block ends, defaults to `false` + afterComment: false, // controls if a line break comes after a comment; defaults to `false` + afterProperty: false, // controls if a line break comes after a property; defaults to `false` + afterRuleBegins: false, // controls if a line break comes after a rule begins; defaults to `false` + afterRuleEnds: false, // controls if a line break comes after a rule ends; defaults to `false` + beforeBlockEnds: false, // controls if a line break comes before a block ends; defaults to `false` + betweenSelectors: false // controls if a line break comes between selectors; defaults to `false` + }, + breakWith: '\n', // controls the new line character, can be `'\r\n'` or `'\n'` (aliased as `'windows'` and `'unix'` or `'crlf'` and `'lf'`); defaults to system one, so former on Windows and latter on Unix + indentBy: 0, // controls number of characters to indent with; defaults to `0` + indentWith: 'space', // controls a character to indent with, can be `'space'` or `'tab'`; defaults to `'space'` + spaces: { // controls where to insert spaces + aroundSelectorRelation: false, // controls if spaces come around selector relations; e.g. `div > a`; defaults to `false` + beforeBlockBegins: false, // controls if a space comes before a block begins; e.g. `.block {`; defaults to `false` + beforeValue: false // controls if a space comes before a value; e.g. `width: 1rem`; defaults to `false` + }, + wrapAt: false // controls maximum line length; defaults to `false` + } +}) +``` + +## Inlining options + +`inline` option whitelists which `@import` rules will be processed, e.g. + +```js +new CleanCSS({ + inline: ['local'] // default; enables local inlining only +}) +``` + +```js +new CleanCSS({ + inline: ['none'] // disables all inlining +}) +``` + +```js +// introduced in clean-css 4.1.0 + +new CleanCSS({ + inline: false // disables all inlining (alias to `['none']`) +}) +``` + +```js +new CleanCSS({ + inline: ['all'] // enables all inlining, same as ['local', 'remote'] +}) +``` + +```js +new CleanCSS({ + inline: ['local', 'mydomain.example.com'] // enables local inlining plus given remote source +}) +``` + +```js +new CleanCSS({ + inline: ['local', 'remote', '!fonts.googleapis.com'] // enables all inlining but from given remote source +}) +``` + +## Optimization levels + +The `level` option can be either `0`, `1` (default), or `2`, e.g. + +```js +new CleanCSS({ + level: 2 +}) +``` + +or a fine-grained configuration given via a hash. + +Please note that level 1 optimization options are generally safe while level 2 optimizations should be safe for most users. + +### Level 0 optimizations + +Level 0 optimizations simply means "no optimizations". Use it when you'd like to inline imports and / or rebase URLs but skip everything else. + +### Level 1 optimizations + +Level 1 optimizations (default) operate on single properties only, e.g. can remove units when not required, turn rgb colors to a shorter hex representation, remove comments, etc + +Here is a full list of available options: + +```js +new CleanCSS({ + level: { + 1: { + cleanupCharsets: true, // controls `@charset` moving to the front of a stylesheet; defaults to `true` + normalizeUrls: true, // controls URL normalization; defaults to `true` + optimizeBackground: true, // controls `background` property optimizations; defaults to `true` + optimizeBorderRadius: true, // controls `border-radius` property optimizations; defaults to `true` + optimizeFilter: true, // controls `filter` property optimizations; defaults to `true` + optimizeFont: true, // controls `font` property optimizations; defaults to `true` + optimizeFontWeight: true, // controls `font-weight` property optimizations; defaults to `true` + optimizeOutline: true, // controls `outline` property optimizations; defaults to `true` + removeEmpty: true, // controls removing empty rules and nested blocks; defaults to `true` + removeNegativePaddings: true, // controls removing negative paddings; defaults to `true` + removeQuotes: true, // controls removing quotes when unnecessary; defaults to `true` + removeWhitespace: true, // controls removing unused whitespace; defaults to `true` + replaceMultipleZeros: true, // contols removing redundant zeros; defaults to `true` + replaceTimeUnits: true, // controls replacing time units with shorter values; defaults to `true` + replaceZeroUnits: true, // controls replacing zero values with units; defaults to `true` + roundingPrecision: false, // rounds pixel values to `N` decimal places; `false` disables rounding; defaults to `false` + selectorsSortingMethod: 'standard', // denotes selector sorting method; can be `'natural'` or `'standard'`, `'none'`, or false (the last two since 4.1.0); defaults to `'standard'` + specialComments: 'all', // denotes a number of /*! ... */ comments preserved; defaults to `all` + tidyAtRules: true, // controls at-rules (e.g. `@charset`, `@import`) optimizing; defaults to `true` + tidyBlockScopes: true, // controls block scopes (e.g. `@media`) optimizing; defaults to `true` + tidySelectors: true, // controls selectors optimizing; defaults to `true`, + semicolonAfterLastProperty: false, // controls removing trailing semicolons in rule; defaults to `false` - means remove + transform: function () {} // defines a callback for fine-grained property optimization; defaults to no-op + } + } +}); +``` + +There is an `all` shortcut for toggling all options at the same time, e.g. + +```js +new CleanCSS({ + level: { + 1: { + all: false, // set all values to `false` + tidySelectors: true // turns on optimizing selectors + } + } +}); +``` + +### Level 2 optimizations + +Level 2 optimizations operate at rules or multiple properties level, e.g. can remove duplicate rules, remove properties redefined further down a stylesheet, or restructure rules by moving them around. + +Please note that if level 2 optimizations are turned on then, unless explicitely disabled, level 1 optimizations are applied as well. + +Here is a full list of available options: + +```js +new CleanCSS({ + level: { + 2: { + mergeAdjacentRules: true, // controls adjacent rules merging; defaults to true + mergeIntoShorthands: true, // controls merging properties into shorthands; defaults to true + mergeMedia: true, // controls `@media` merging; defaults to true + mergeNonAdjacentRules: true, // controls non-adjacent rule merging; defaults to true + mergeSemantically: false, // controls semantic merging; defaults to false + overrideProperties: true, // controls property overriding based on understandability; defaults to true + removeEmpty: true, // controls removing empty rules and nested blocks; defaults to `true` + reduceNonAdjacentRules: true, // controls non-adjacent rule reducing; defaults to true + removeDuplicateFontRules: true, // controls duplicate `@font-face` removing; defaults to true + removeDuplicateMediaBlocks: true, // controls duplicate `@media` removing; defaults to true + removeDuplicateRules: true, // controls duplicate rules removing; defaults to true + removeUnusedAtRules: false, // controls unused at rule removing; defaults to false (available since 4.1.0) + restructureRules: false, // controls rule restructuring; defaults to false + skipProperties: [] // controls which properties won't be optimized, defaults to `[]` which means all will be optimized (since 4.1.0) + } + } +}); +``` + +There is an `all` shortcut for toggling all options at the same time, e.g. + +```js +new CleanCSS({ + level: { + 2: { + all: false, // sets all values to `false` + removeDuplicateRules: true // turns on removing duplicate rules + } + } +}); +``` + +## Minify method + +Once configured clean-css provides a `minify` method to optimize a given CSS, e.g. + +```js +var output = new CleanCSS(options).minify(source); +``` + +The output of the `minify` method is a hash with following fields: + +```js +console.log(output.styles); // optimized output CSS as a string +console.log(output.sourceMap); // output source map if requested with `sourceMap` option +console.log(output.errors); // a list of errors raised +console.log(output.warnings); // a list of warnings raised +console.log(output.stats.originalSize); // original content size after import inlining +console.log(output.stats.minifiedSize); // optimized content size +console.log(output.stats.timeSpent); // time spent on optimizations in milliseconds +console.log(output.stats.efficiency); // `(originalSize - minifiedSize) / originalSize`, e.g. 0.25 if size is reduced from 100 bytes to 75 bytes +``` + +The `minify` method also accepts an input source map, e.g. + +```js +var output = new CleanCSS(options).minify(source, inputSourceMap); +``` + +or a callback invoked when optimizations are finished, e.g. + +```js +new CleanCSS(options).minify(source, function (error, output) { + // `output` is the same as in the synchronous call above +}); +``` + +## Promise interface + +If you prefer clean-css to return a Promise object then you need to explicitely ask for it, e.g. + +```js +new CleanCSS({ returnPromise: true }) + .minify(source) + .then(function (output) { console.log(output.styles); }) + .catch(function (error) { // deal with errors }); +``` + +## CLI utility + +Clean-css has an associated command line utility that can be installed separately using `npm install clean-css-cli`. For more detailed information, please visit https://github.com/jakubpawlowicz/clean-css-cli. + +# FAQ + +## How to optimize multiple files? + +It can be done either by passing an array of paths, or, when sources are already available, a hash or an array of hashes: + +```js +new CleanCSS().minify(['path/to/file/one', 'path/to/file/two']); +``` + +```js +new CleanCSS().minify({ + 'path/to/file/one': { + styles: 'contents of file one' + }, + 'path/to/file/two': { + styles: 'contents of file two' + } +}); +``` + +```js +new CleanCSS().minify([ + {'path/to/file/one': {styles: 'contents of file one'}}, + {'path/to/file/two': {styles: 'contents of file two'}} +]); +``` + +Passing an array of hashes allows you to explicitly specify the order in which the input files are concatenated. Whereas when you use a single hash the order is determined by the [traversal order of object properties](http://2ality.com/2015/10/property-traversal-order-es6.html) - available since 4.1.0. + +Important note - any `@import` rules already present in the hash will be resolved in memory. + +## How to process remote `@import`s correctly? + +In order to inline remote `@import` statements you need to provide a callback to minify method as fetching remote assets is an asynchronous operation, e.g.: + +```js +var source = '@import url(http://example.com/path/to/remote/styles);'; +new CleanCSS({ inline: ['remote'] }).minify(source, function (error, output) { + // output.styles +}); +``` + +If you don't provide a callback, then remote `@import`s will be left as is. + +## How to apply arbitrary transformations to CSS properties? + +If clean-css doesn't perform a particular property optimization, you can use `transform` callback to apply it: + +```js +var source = '.block{background-image:url(/path/to/image.png)}'; +var output = new CleanCSS({ + level: { + 1: { + transform: function (propertyName, propertyValue, selector /* `selector` available since 4.2.0-pre */) { + if (propertyName == 'background-image' && propertyValue.indexOf('/path/to') > -1) { + return propertyValue.replace('/path/to', '../valid/path/to'); + } + } + } + } +}).minify(source); + +console.log(output.styles); # => .block{background-image:url(../valid/path/to/image.png)} +``` + +Note: returning `false` from `transform` callback will drop a property. + +## How to specify a custom rounding precision? + +The level 1 `roundingPrecision` optimization option accept a string with per-unit rounding precision settings, e.g. + +```js +new CleanCSS({ + level: { + 1: { + roundingPrecision: 'all=3,px=5' + } + } +}).minify(source) +``` + +which sets all units rounding precision to 3 digits except `px` unit precision of 5 digits. + +## How to keep a CSS fragment intact? + +Note: available in the current master, to be released in 4.2.0. + +Wrap the CSS fragment in special comments which instruct clean-css to preserve it, e.g. + +```css +.block-1 { + color: red +} +/* clean-css ignore:start */ +.block-special { + color: transparent +} +/* clean-css ignore:end */ +.block-2 { + margin: 0 +} +``` + +Optimizing this CSS will result in the following output: + +```css +.block-1{color:red} +.block-special { + color: transparent +} +.block-2{margin:0} +``` + +## How to preserve a comment block? + +Use the `/*!` notation instead of the standard one `/*`: + +```css +/*! + Important comments included in optimized output. +*/ +``` + +## How to rebase relative image URLs? + +clean-css will handle it automatically for you in the following cases: + +* when full paths to input files are passed in as options; +* when correct paths are passed in via a hash; +* when `rebaseTo` is used with any of above two. + +## How to work with source maps? + +To generate a source map, use `sourceMap: true` option, e.g.: + +```js +new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }) + .minify(source, function (error, output) { + // access output.sourceMap for SourceMapGenerator object + // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details +}); +``` + +You can also pass an input source map directly as a 2nd argument to `minify` method: + +```js +new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }) + .minify(source, inputSourceMap, function (error, output) { + // access output.sourceMap to access SourceMapGenerator object + // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details +}); +``` + +or even multiple input source maps at once: + +```js +new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }).minify({ + 'path/to/source/1': { + styles: '...styles...', + sourceMap: '...source-map...' + }, + 'path/to/source/2': { + styles: '...styles...', + sourceMap: '...source-map...' + } +}, function (error, output) { + // access output.sourceMap as above +}); +``` + +## How to apply level 1 & 2 optimizations at the same time? + +Using the hash configuration specifying both optimization levels, e.g. + +```js +new CleanCSS({ + level: { + 1: { + all: true, + normalizeUrls: false + }, + 2: { + restructureRules: true + } + } +}) +``` + +will apply level 1 optimizations, except url normalization, and default level 2 optimizations with rule restructuring. + +## What level 2 optimizations do? + +All level 2 optimizations are dispatched [here](https://github.com/jakubpawlowicz/clean-css/blob/master/lib/optimizer/level-2/optimize.js#L67), and this is what they do: + +* `recursivelyOptimizeBlocks` - does all the following operations on a nested block, like `@media` or `@keyframe`; +* `recursivelyOptimizeProperties` - optimizes properties in rulesets and flat at-rules, like @font-face, by splitting them into components (e.g. `margin` into `margin-(bottom|left|right|top)`), optimizing, and restoring them back. You may want to use `mergeIntoShorthands` option to control whether you want to turn multiple components into shorthands; +* `removeDuplicates` - gets rid of duplicate rulesets with exactly the same set of properties, e.g. when including a Sass / Less partial twice for no good reason; +* `mergeAdjacent` - merges adjacent rulesets with the same selector or rules; +* `reduceNonAdjacent` - identifies which properties are overridden in same-selector non-adjacent rulesets, and removes them; +* `mergeNonAdjacentBySelector` - identifies same-selector non-adjacent rulesets which can be moved (!) to be merged, requires all intermediate rulesets to not redefine the moved properties, or if redefined to have the same value; +* `mergeNonAdjacentByBody` - same as the one above but for same-selector non-adjacent rulesets; +* `restructure` - tries to reorganize different-selector different-rules rulesets so they take less space, e.g. `.one{padding:0}.two{margin:0}.one{margin-bottom:3px}` into `.two{margin:0}.one{padding:0;margin-bottom:3px}`; +* `removeDuplicateFontAtRules` - removes duplicated `@font-face` rules; +* `removeDuplicateMediaQueries` - removes duplicated `@media` nested blocks; +* `mergeMediaQueries` - merges non-adjacent `@media` at-rules by the same rules as `mergeNonAdjacentBy*` above; + +## How to use clean-css with build tools? + +There is a number of 3rd party plugins to popular build tools: + +* [Broccoli](https://github.com/broccolijs/broccoli#broccoli): [broccoli-clean-css](https://github.com/shinnn/broccoli-clean-css) +* [Brunch](http://brunch.io/): [clean-css-brunch](https://github.com/brunch/clean-css-brunch) +* [Grunt](http://gruntjs.com): [grunt-contrib-cssmin](https://github.com/gruntjs/grunt-contrib-cssmin) +* [Gulp](http://gulpjs.com/): [gulp-clean-css](https://github.com/scniro/gulp-clean-css) +* [Gulp](http://gulpjs.com/): [using vinyl-map as a wrapper - courtesy of @sogko](https://github.com/jakubpawlowicz/clean-css/issues/342) +* [component-builder2](https://github.com/component/builder2.js): [builder-clean-css](https://github.com/poying/builder-clean-css) +* [Metalsmith](http://metalsmith.io): [metalsmith-clean-css](https://github.com/aymericbeaumet/metalsmith-clean-css) +* [Lasso](https://github.com/lasso-js/lasso): [lasso-clean-css](https://github.com/yomed/lasso-clean-css) +* [Start](https://github.com/start-runner/start): [start-clean-css](https://github.com/start-runner/clean-css) + +## How to use clean-css from web browser? + +* https://jakubpawlowicz.github.io/clean-css/ (official web interface) +* http://refresh-sf.com/ +* http://adamburgess.github.io/clean-css-online/ + +# Contributing + +See [CONTRIBUTING.md](https://github.com/jakubpawlowicz/clean-css/blob/master/CONTRIBUTING.md). + +## How to get started? + +First clone the sources: + +```bash +git clone git@github.com:jakubpawlowicz/clean-css.git +``` + +then install dependencies: + +```bash +cd clean-css +npm install +``` + +then use any of the following commands to verify your copy: + +```bash +npm run bench # for clean-css benchmarks (see [test/bench.js](https://github.com/jakubpawlowicz/clean-css/blob/master/test/bench.js) for details) +npm run browserify # to create the browser-ready clean-css version +npm run check # to lint JS sources with [JSHint](https://github.com/jshint/jshint/) +npm test # to run all tests +``` + +# Acknowledgments + +Sorted alphabetically by GitHub handle: + +* [@abarre](https://github.com/abarre) (Anthony Barre) for improvements to `@import` processing; +* [@alexlamsl](https://github.com/alexlamsl) (Alex Lam S.L.) for testing early clean-css 4 versions, reporting bugs, and suggesting numerous improvements. +* [@altschuler](https://github.com/altschuler) (Simon Altschuler) for fixing `@import` processing inside comments; +* [@ben-eb](https://github.com/ben-eb) (Ben Briggs) for sharing ideas about CSS optimizations; +* [@davisjam](https://github.com/davisjam) (Jamie Davis) for disclosing ReDOS vulnerabilities; +* [@facelessuser](https://github.com/facelessuser) (Isaac) for pointing out a flaw in clean-css' stateless mode; +* [@grandrath](https://github.com/grandrath) (Martin Grandrath) for improving `minify` method source traversal in ES6; +* [@jmalonzo](https://github.com/jmalonzo) (Jan Michael Alonzo) for a patch removing node.js' old `sys` package; +* [@lukeapage](https://github.com/lukeapage) (Luke Page) for suggestions and testing the source maps feature; + Plus everyone else involved in [#125](https://github.com/jakubpawlowicz/clean-css/issues/125) for pushing it forward; +* [@madwizard-thomas](https://github.com/madwizard-thomas) for sharing ideas about `@import` inlining and URL rebasing. +* [@ngyikp](https://github.com/ngyikp) (Ng Yik Phang) for testing early clean-css 4 versions, reporting bugs, and suggesting numerous improvements. +* [@wagenet](https://github.com/wagenet) (Peter Wagenet) for suggesting improvements to `@import` inlining behavior; +* [@venemo](https://github.com/venemo) (Timur Kristóf) for an outstanding contribution of advanced property optimizer for 2.2 release; +* [@vvo](https://github.com/vvo) (Vincent Voyer) for a patch with better empty element regex and for inspiring us to do many performance improvements in 0.4 release; +* [@xhmikosr](https://github.com/xhmikosr) for suggesting new features, like option to remove special comments and strip out URLs quotation, and pointing out numerous improvements like JSHint, media queries, etc. + +# License + +clean-css is released under the [MIT License](https://github.com/jakubpawlowicz/clean-css/blob/master/LICENSE). diff --git a/node_modules/clean-css/index.js b/node_modules/clean-css/index.js new file mode 100644 index 0000000..d7b0503 --- /dev/null +++ b/node_modules/clean-css/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/clean'); diff --git a/node_modules/clean-css/lib/clean.js b/node_modules/clean-css/lib/clean.js new file mode 100644 index 0000000..8cdb4b7 --- /dev/null +++ b/node_modules/clean-css/lib/clean.js @@ -0,0 +1,172 @@ +/** + * Clean-css - https://github.com/jakubpawlowicz/clean-css + * Released under the terms of MIT license + * + * Copyright (C) 2017 JakubPawlowicz.com + */ + +var level0Optimize = require('./optimizer/level-0/optimize'); +var level1Optimize = require('./optimizer/level-1/optimize'); +var level2Optimize = require('./optimizer/level-2/optimize'); +var validator = require('./optimizer/validator'); + +var compatibilityFrom = require('./options/compatibility'); +var fetchFrom = require('./options/fetch'); +var formatFrom = require('./options/format').formatFrom; +var inlineFrom = require('./options/inline'); +var inlineRequestFrom = require('./options/inline-request'); +var inlineTimeoutFrom = require('./options/inline-timeout'); +var OptimizationLevel = require('./options/optimization-level').OptimizationLevel; +var optimizationLevelFrom = require('./options/optimization-level').optimizationLevelFrom; +var rebaseFrom = require('./options/rebase'); +var rebaseToFrom = require('./options/rebase-to'); + +var inputSourceMapTracker = require('./reader/input-source-map-tracker'); +var readSources = require('./reader/read-sources'); + +var serializeStyles = require('./writer/simple'); +var serializeStylesAndSourceMap = require('./writer/source-maps'); + +var CleanCSS = module.exports = function CleanCSS(options) { + options = options || {}; + + this.options = { + compatibility: compatibilityFrom(options.compatibility), + fetch: fetchFrom(options.fetch), + format: formatFrom(options.format), + inline: inlineFrom(options.inline), + inlineRequest: inlineRequestFrom(options.inlineRequest), + inlineTimeout: inlineTimeoutFrom(options.inlineTimeout), + level: optimizationLevelFrom(options.level), + rebase: rebaseFrom(options.rebase), + rebaseTo: rebaseToFrom(options.rebaseTo), + returnPromise: !!options.returnPromise, + sourceMap: !!options.sourceMap, + sourceMapInlineSources: !!options.sourceMapInlineSources + }; +}; + + +// for compatibility with optimize-css-assets-webpack-plugin +CleanCSS.process = function (input, opts) { + var cleanCss; + var optsTo = opts.to; + + delete opts.to; + cleanCss = new CleanCSS(Object.assign({ returnPromise: true, rebaseTo: optsTo }, opts)); + + return cleanCss.minify(input) + .then(function(output) { + return { css: output.styles }; + }); +}; + + +CleanCSS.prototype.minify = function (input, maybeSourceMap, maybeCallback) { + var options = this.options; + + if (options.returnPromise) { + return new Promise(function (resolve, reject) { + minify(input, options, maybeSourceMap, function (errors, output) { + return errors ? + reject(errors) : + resolve(output); + }); + }); + } else { + return minify(input, options, maybeSourceMap, maybeCallback); + } +}; + +function minify(input, options, maybeSourceMap, maybeCallback) { + var sourceMap = typeof maybeSourceMap != 'function' ? + maybeSourceMap : + null; + var callback = typeof maybeCallback == 'function' ? + maybeCallback : + (typeof maybeSourceMap == 'function' ? maybeSourceMap : null); + var context = { + stats: { + efficiency: 0, + minifiedSize: 0, + originalSize: 0, + startedAt: Date.now(), + timeSpent: 0 + }, + cache: { + specificity: {} + }, + errors: [], + inlinedStylesheets: [], + inputSourceMapTracker: inputSourceMapTracker(), + localOnly: !callback, + options: options, + source: null, + sourcesContent: {}, + validator: validator(options.compatibility), + warnings: [] + }; + + if (sourceMap) { + context.inputSourceMapTracker.track(undefined, sourceMap); + } + + return runner(context.localOnly)(function () { + return readSources(input, context, function (tokens) { + var serialize = context.options.sourceMap ? + serializeStylesAndSourceMap : + serializeStyles; + + var optimizedTokens = optimize(tokens, context); + var optimizedStyles = serialize(optimizedTokens, context); + var output = withMetadata(optimizedStyles, context); + + return callback ? + callback(context.errors.length > 0 ? context.errors : null, output) : + output; + }); + }); +} + +function runner(localOnly) { + // to always execute code asynchronously when a callback is given + // more at blog.izs.me/post/59142742143/designing-apis-for-asynchrony + return localOnly ? + function (callback) { return callback(); } : + process.nextTick; +} + +function optimize(tokens, context) { + var optimized; + + optimized = level0Optimize(tokens, context); + optimized = OptimizationLevel.One in context.options.level ? + level1Optimize(tokens, context) : + tokens; + optimized = OptimizationLevel.Two in context.options.level ? + level2Optimize(tokens, context, true) : + optimized; + + return optimized; +} + +function withMetadata(output, context) { + output.stats = calculateStatsFrom(output.styles, context); + output.errors = context.errors; + output.inlinedStylesheets = context.inlinedStylesheets; + output.warnings = context.warnings; + + return output; +} + +function calculateStatsFrom(styles, context) { + var finishedAt = Date.now(); + var timeSpent = finishedAt - context.stats.startedAt; + + delete context.stats.startedAt; + context.stats.timeSpent = timeSpent; + context.stats.efficiency = 1 - styles.length / context.stats.originalSize; + context.stats.minifiedSize = styles.length; + + return context.stats; +} diff --git a/node_modules/clean-css/lib/optimizer/hack.js b/node_modules/clean-css/lib/optimizer/hack.js new file mode 100644 index 0000000..812b5d5 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/hack.js @@ -0,0 +1,8 @@ +var Hack = { + ASTERISK: 'asterisk', + BANG: 'bang', + BACKSLASH: 'backslash', + UNDERSCORE: 'underscore' +}; + +module.exports = Hack; diff --git a/node_modules/clean-css/lib/optimizer/level-0/optimize.js b/node_modules/clean-css/lib/optimizer/level-0/optimize.js new file mode 100644 index 0000000..2a56f89 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-0/optimize.js @@ -0,0 +1,6 @@ +function level0Optimize(tokens) { + // noop as level 0 means no optimizations! + return tokens; +} + +module.exports = level0Optimize; diff --git a/node_modules/clean-css/lib/optimizer/level-1/optimize.js b/node_modules/clean-css/lib/optimizer/level-1/optimize.js new file mode 100644 index 0000000..13cfd8c --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/optimize.js @@ -0,0 +1,676 @@ +var shortenHex = require('./shorten-hex'); +var shortenHsl = require('./shorten-hsl'); +var shortenRgb = require('./shorten-rgb'); +var sortSelectors = require('./sort-selectors'); +var tidyRules = require('./tidy-rules'); +var tidyBlock = require('./tidy-block'); +var tidyAtRule = require('./tidy-at-rule'); + +var Hack = require('../hack'); +var removeUnused = require('../remove-unused'); +var restoreFromOptimizing = require('../restore-from-optimizing'); +var wrapForOptimizing = require('../wrap-for-optimizing').all; + +var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel; + +var Token = require('../../tokenizer/token'); +var Marker = require('../../tokenizer/marker'); + +var formatPosition = require('../../utils/format-position'); +var split = require('../../utils/split'); + +var serializeRules = require('../../writer/one-time').rules; + +var IgnoreProperty = 'ignore-property'; + +var CHARSET_TOKEN = '@charset'; +var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i'); + +var DEFAULT_ROUNDING_PRECISION = require('../../options/rounding-precision').DEFAULT; + +var WHOLE_PIXEL_VALUE = /(?:^|\s|\()(-?\d+)px/; +var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/; + +var HEX_VALUE_PATTERN = /[0-9a-f]/i; +var PROPERTY_NAME_PATTERN = /^(?:\-chrome\-|\-[\w\-]+\w|\w[\w\-]+\w|\-\-\S+)$/; +var IMPORT_PREFIX_PATTERN = /^@import/i; +var QUOTED_PATTERN = /^('.*'|".*")$/; +var QUOTED_BUT_SAFE_PATTERN = /^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/; +var URL_PREFIX_PATTERN = /^url\(/i; +var VARIABLE_NAME_PATTERN = /^--\S+$/; + +function isNegative(value) { + return value && value[1][0] == '-' && parseFloat(value[1]) < 0; +} + +function isQuoted(value) { + return QUOTED_PATTERN.test(value); +} + +function isUrl(value) { + return URL_PREFIX_PATTERN.test(value); +} + +function normalizeUrl(value) { + return value + .replace(URL_PREFIX_PATTERN, 'url(') + .replace(/\\?\n|\\?\r\n/g, ''); +} + +function optimizeBackground(property) { + var values = property.value; + + if (values.length == 1 && values[0][1] == 'none') { + values[0][1] = '0 0'; + } + + if (values.length == 1 && values[0][1] == 'transparent') { + values[0][1] = '0 0'; + } +} + +function optimizeBorderRadius(property) { + var values = property.value; + var spliceAt; + + if (values.length == 3 && values[1][1] == '/' && values[0][1] == values[2][1]) { + spliceAt = 1; + } else if (values.length == 5 && values[2][1] == '/' && values[0][1] == values[3][1] && values[1][1] == values[4][1]) { + spliceAt = 2; + } else if (values.length == 7 && values[3][1] == '/' && values[0][1] == values[4][1] && values[1][1] == values[5][1] && values[2][1] == values[6][1]) { + spliceAt = 3; + } else if (values.length == 9 && values[4][1] == '/' && values[0][1] == values[5][1] && values[1][1] == values[6][1] && values[2][1] == values[7][1] && values[3][1] == values[8][1]) { + spliceAt = 4; + } + + if (spliceAt) { + property.value.splice(spliceAt); + property.dirty = true; + } +} + +function optimizeColors(name, value, compatibility) { + if (value.indexOf('#') === -1 && value.indexOf('rgb') == -1 && value.indexOf('hsl') == -1) { + return shortenHex(value); + } + + value = value + .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g, function (match, red, green, blue) { + return shortenRgb(red, green, blue); + }) + .replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g, function (match, hue, saturation, lightness) { + return shortenHsl(hue, saturation, lightness); + }) + .replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color, at, inputValue) { + var suffix = inputValue[at + match.length]; + + if (suffix && HEX_VALUE_PATTERN.test(suffix)) { + return match; + } else if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) { + return (prefix + '#' + color[0] + color[2] + color[4]).toLowerCase(); + } else { + return (prefix + '#' + color).toLowerCase(); + } + }) + .replace(/(^|[^='"])#([0-9a-f]{3})/gi, function (match, prefix, color) { + return prefix + '#' + color.toLowerCase(); + }) + .replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g, function (match, colorFunction, colorDef) { + var tokens = colorDef.split(','); + var applies = (colorFunction == 'hsl' && tokens.length == 3) || + (colorFunction == 'hsla' && tokens.length == 4) || + (colorFunction == 'rgb' && tokens.length == 3 && colorDef.indexOf('%') > 0) || + (colorFunction == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0); + + if (!applies) { + return match; + } + + if (tokens[1].indexOf('%') == -1) { + tokens[1] += '%'; + } + + if (tokens[2].indexOf('%') == -1) { + tokens[2] += '%'; + } + + return colorFunction + '(' + tokens.join(',') + ')'; + }); + + if (compatibility.colors.opacity && name.indexOf('background') == -1) { + value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) { + if (split(value, ',').pop().indexOf('gradient(') > -1) { + return match; + } + + return 'transparent'; + }); + } + + return shortenHex(value); +} + +function optimizeFilter(property) { + if (property.value.length == 1) { + property.value[0][1] = property.value[0][1].replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/, function (match, filter, suffix) { + return filter.toLowerCase() + suffix; + }); + } + + property.value[0][1] = property.value[0][1] + .replace(/,(\S)/g, ', $1') + .replace(/ ?= ?/g, '='); +} + +function optimizeFontWeight(property, atIndex) { + var value = property.value[atIndex][1]; + + if (value == 'normal') { + value = '400'; + } else if (value == 'bold') { + value = '700'; + } + + property.value[atIndex][1] = value; +} + +function optimizeMultipleZeros(property) { + var values = property.value; + var spliceAt; + + if (values.length == 4 && values[0][1] === '0' && values[1][1] === '0' && values[2][1] === '0' && values[3][1] === '0') { + if (property.name.indexOf('box-shadow') > -1) { + spliceAt = 2; + } else { + spliceAt = 1; + } + } + + if (spliceAt) { + property.value.splice(spliceAt); + property.dirty = true; + } +} + +function optimizeOutline(property) { + var values = property.value; + + if (values.length == 1 && values[0][1] == 'none') { + values[0][1] = '0'; + } +} + +function optimizePixelLengths(_, value, compatibility) { + if (!WHOLE_PIXEL_VALUE.test(value)) { + return value; + } + + return value.replace(WHOLE_PIXEL_VALUE, function (match, val) { + var newValue; + var intVal = parseInt(val); + + if (intVal === 0) { + return match; + } + + if (compatibility.properties.shorterLengthUnits && compatibility.units.pt && intVal * 3 % 4 === 0) { + newValue = intVal * 3 / 4 + 'pt'; + } + + if (compatibility.properties.shorterLengthUnits && compatibility.units.pc && intVal % 16 === 0) { + newValue = intVal / 16 + 'pc'; + } + + if (compatibility.properties.shorterLengthUnits && compatibility.units.in && intVal % 96 === 0) { + newValue = intVal / 96 + 'in'; + } + + if (newValue) { + newValue = match.substring(0, match.indexOf(val)) + newValue; + } + + return newValue && newValue.length < match.length ? newValue : match; + }); +} + +function optimizePrecision(_, value, precisionOptions) { + if (!precisionOptions.enabled || value.indexOf('.') === -1) { + return value; + } + + return value + .replace(precisionOptions.decimalPointMatcher, '$1$2$3') + .replace(precisionOptions.zeroMatcher, function (match, integerPart, fractionPart, unit) { + var multiplier = precisionOptions.units[unit].multiplier; + var parsedInteger = parseInt(integerPart); + var integer = isNaN(parsedInteger) ? 0 : parsedInteger; + var fraction = parseFloat(fractionPart); + + return Math.round((integer + fraction) * multiplier) / multiplier + unit; + }); +} + +function optimizeTimeUnits(_, value) { + if (!TIME_VALUE.test(value)) + return value; + + return value.replace(TIME_VALUE, function (match, val, unit) { + var newValue; + + if (unit == 'ms') { + newValue = parseInt(val) / 1000 + 's'; + } else if (unit == 's') { + newValue = parseFloat(val) * 1000 + 'ms'; + } + + return newValue.length < match.length ? newValue : match; + }); +} + +function optimizeUnits(name, value, unitsRegexp) { + if (/^(?:\-moz\-calc|\-webkit\-calc|calc|rgb|hsl|rgba|hsla)\(/.test(value)) { + return value; + } + + if (name == 'flex' || name == '-ms-flex' || name == '-webkit-flex' || name == 'flex-basis' || name == '-webkit-flex-basis') { + return value; + } + + if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height' || name == 'width' || name == 'max-width')) { + return value; + } + + return value + .replace(unitsRegexp, '$1' + '0' + '$2') + .replace(unitsRegexp, '$1' + '0' + '$2'); +} + +function optimizeWhitespace(name, value) { + if (name.indexOf('filter') > -1 || value.indexOf(' ') == -1 || value.indexOf('expression') === 0) { + return value; + } + + if (value.indexOf(Marker.SINGLE_QUOTE) > -1 || value.indexOf(Marker.DOUBLE_QUOTE) > -1) { + return value; + } + + value = value.replace(/\s+/g, ' '); + + if (value.indexOf('calc') > -1) { + value = value.replace(/\) ?\/ ?/g, ')/ '); + } + + return value + .replace(/(\(;?)\s+/g, '$1') + .replace(/\s+(;?\))/g, '$1') + .replace(/, /g, ','); +} + +function optimizeZeroDegUnit(_, value) { + if (value.indexOf('0deg') == -1) { + return value; + } + + return value.replace(/\(0deg\)/g, '(0)'); +} + +function optimizeZeroUnits(name, value) { + if (value.indexOf('0') == -1) { + return value; + } + + if (value.indexOf('-') > -1) { + value = value + .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2') + .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2'); + } + + return value + .replace(/(^|\s)0+([1-9])/g, '$1$2') + .replace(/(^|\D)\.0+(\D|$)/g, '$10$2') + .replace(/(^|\D)\.0+(\D|$)/g, '$10$2') + .replace(/\.([1-9]*)0+(\D|$)/g, function (match, nonZeroPart, suffix) { + return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix; + }) + .replace(/(^|\D)0\.(\d)/g, '$1.$2'); +} + +function removeQuotes(name, value) { + if (name == 'content' || name.indexOf('font-variation-settings') > -1 || name.indexOf('font-feature-settings') > -1 || name.indexOf('grid-') > -1) { + return value; + } + + return QUOTED_BUT_SAFE_PATTERN.test(value) ? + value.substring(1, value.length - 1) : + value; +} + +function removeUrlQuotes(value) { + return /^url\(['"].+['"]\)$/.test(value) && !/^url\(['"].*[\*\s\(\)'"].*['"]\)$/.test(value) && !/^url\(['"]data:[^;]+;charset/.test(value) ? + value.replace(/["']/g, '') : + value; +} + +function transformValue(propertyName, propertyValue, rule, transformCallback) { + var selector = serializeRules(rule); + var transformedValue = transformCallback(propertyName, propertyValue, selector); + + if (transformedValue === undefined) { + return propertyValue; + } else if (transformedValue === false) { + return IgnoreProperty; + } else { + return transformedValue; + } +} + +// + +function optimizeBody(rule, properties, context) { + var options = context.options; + var levelOptions = options.level[OptimizationLevel.One]; + var property, name, type, value; + var valueIsUrl; + var propertyToken; + var _properties = wrapForOptimizing(properties, true); + + propertyLoop: + for (var i = 0, l = _properties.length; i < l; i++) { + property = _properties[i]; + name = property.name; + + if (!PROPERTY_NAME_PATTERN.test(name)) { + propertyToken = property.all[property.position]; + context.warnings.push('Invalid property name \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.'); + property.unused = true; + } + + if (property.value.length === 0) { + propertyToken = property.all[property.position]; + context.warnings.push('Empty property \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.'); + property.unused = true; + } + + if (property.hack && ( + (property.hack[0] == Hack.ASTERISK || property.hack[0] == Hack.UNDERSCORE) && !options.compatibility.properties.iePrefixHack || + property.hack[0] == Hack.BACKSLASH && !options.compatibility.properties.ieSuffixHack || + property.hack[0] == Hack.BANG && !options.compatibility.properties.ieBangHack)) { + property.unused = true; + } + + if (levelOptions.removeNegativePaddings && name.indexOf('padding') === 0 && (isNegative(property.value[0]) || isNegative(property.value[1]) || isNegative(property.value[2]) || isNegative(property.value[3]))) { + property.unused = true; + } + + if (!options.compatibility.properties.ieFilters && isLegacyFilter(property)) { + property.unused = true; + } + + if (property.unused) { + continue; + } + + if (property.block) { + optimizeBody(rule, property.value[0][1], context); + continue; + } + + if (VARIABLE_NAME_PATTERN.test(name)) { + continue; + } + + for (var j = 0, m = property.value.length; j < m; j++) { + type = property.value[j][0]; + value = property.value[j][1]; + valueIsUrl = isUrl(value); + + if (type == Token.PROPERTY_BLOCK) { + property.unused = true; + context.warnings.push('Invalid value token at ' + formatPosition(value[0][1][2][0]) + '. Ignoring.'); + break; + } + + if (valueIsUrl && !context.validator.isUrl(value)) { + property.unused = true; + context.warnings.push('Broken URL \'' + value + '\' at ' + formatPosition(property.value[j][2][0]) + '. Ignoring.'); + break; + } + + if (valueIsUrl) { + value = levelOptions.normalizeUrls ? + normalizeUrl(value) : + value; + value = !options.compatibility.properties.urlQuotes ? + removeUrlQuotes(value) : + value; + } else if (isQuoted(value)) { + value = levelOptions.removeQuotes ? + removeQuotes(name, value) : + value; + } else { + value = levelOptions.removeWhitespace ? + optimizeWhitespace(name, value) : + value; + value = optimizePrecision(name, value, options.precision); + value = optimizePixelLengths(name, value, options.compatibility); + value = levelOptions.replaceTimeUnits ? + optimizeTimeUnits(name, value) : + value; + value = levelOptions.replaceZeroUnits ? + optimizeZeroUnits(name, value) : + value; + + if (options.compatibility.properties.zeroUnits) { + value = optimizeZeroDegUnit(name, value); + value = optimizeUnits(name, value, options.unitsRegexp); + } + + if (options.compatibility.properties.colors) { + value = optimizeColors(name, value, options.compatibility); + } + } + + value = transformValue(name, value, rule, levelOptions.transform); + + if (value === IgnoreProperty) { + property.unused = true; + continue propertyLoop; + } + + property.value[j][1] = value; + } + + if (levelOptions.replaceMultipleZeros) { + optimizeMultipleZeros(property); + } + + if (name == 'background' && levelOptions.optimizeBackground) { + optimizeBackground(property); + } else if (name.indexOf('border') === 0 && name.indexOf('radius') > 0 && levelOptions.optimizeBorderRadius) { + optimizeBorderRadius(property); + } else if (name == 'filter'&& levelOptions.optimizeFilter && options.compatibility.properties.ieFilters) { + optimizeFilter(property); + } else if (name == 'font-weight' && levelOptions.optimizeFontWeight) { + optimizeFontWeight(property, 0); + } else if (name == 'outline' && levelOptions.optimizeOutline) { + optimizeOutline(property); + } + } + + restoreFromOptimizing(_properties); + removeUnused(_properties); + removeComments(properties, options); +} + +function removeComments(tokens, options) { + var token; + var i; + + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + + if (token[0] != Token.COMMENT) { + continue; + } + + optimizeComment(token, options); + + if (token[1].length === 0) { + tokens.splice(i, 1); + i--; + } + } +} + +function optimizeComment(token, options) { + if (token[1][2] == Marker.EXCLAMATION && (options.level[OptimizationLevel.One].specialComments == 'all' || options.commentsKept < options.level[OptimizationLevel.One].specialComments)) { + options.commentsKept++; + return; + } + + token[1] = []; +} + +function cleanupCharsets(tokens) { + var hasCharset = false; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + if (token[0] != Token.AT_RULE) + continue; + + if (!CHARSET_REGEXP.test(token[1])) + continue; + + if (hasCharset || token[1].indexOf(CHARSET_TOKEN) == -1) { + tokens.splice(i, 1); + i--; + l--; + } else { + hasCharset = true; + tokens.splice(i, 1); + tokens.unshift([Token.AT_RULE, token[1].replace(CHARSET_REGEXP, CHARSET_TOKEN)]); + } + } +} + +function buildUnitRegexp(options) { + var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%']; + var otherUnits = ['ch', 'rem', 'vh', 'vm', 'vmax', 'vmin', 'vw']; + + otherUnits.forEach(function (unit) { + if (options.compatibility.units[unit]) { + units.push(unit); + } + }); + + return new RegExp('(^|\\s|\\(|,)0(?:' + units.join('|') + ')(\\W|$)', 'g'); +} + +function buildPrecisionOptions(roundingPrecision) { + var precisionOptions = { + matcher: null, + units: {}, + }; + var optimizable = []; + var unit; + var value; + + for (unit in roundingPrecision) { + value = roundingPrecision[unit]; + + if (value != DEFAULT_ROUNDING_PRECISION) { + precisionOptions.units[unit] = {}; + precisionOptions.units[unit].value = value; + precisionOptions.units[unit].multiplier = Math.pow(10, value); + + optimizable.push(unit); + } + } + + if (optimizable.length > 0) { + precisionOptions.enabled = true; + precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\W)', 'g'); + precisionOptions.zeroMatcher = new RegExp('(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')', 'g'); + } + + return precisionOptions; +} + +function isImport(token) { + return IMPORT_PREFIX_PATTERN.test(token[1]); +} + +function isLegacyFilter(property) { + var value; + + if (property.name == 'filter' || property.name == '-ms-filter') { + value = property.value[0][1]; + + return value.indexOf('progid') > -1 || + value.indexOf('alpha') === 0 || + value.indexOf('chroma') === 0; + } else { + return false; + } +} + +function level1Optimize(tokens, context) { + var options = context.options; + var levelOptions = options.level[OptimizationLevel.One]; + var ie7Hack = options.compatibility.selectors.ie7Hack; + var adjacentSpace = options.compatibility.selectors.adjacentSpace; + var spaceAfterClosingBrace = options.compatibility.properties.spaceAfterClosingBrace; + var format = options.format; + var mayHaveCharset = false; + var afterRules = false; + + options.unitsRegexp = options.unitsRegexp || buildUnitRegexp(options); + options.precision = options.precision || buildPrecisionOptions(levelOptions.roundingPrecision); + options.commentsKept = options.commentsKept || 0; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + switch (token[0]) { + case Token.AT_RULE: + token[1] = isImport(token) && afterRules ? '' : token[1]; + token[1] = levelOptions.tidyAtRules ? tidyAtRule(token[1]) : token[1]; + mayHaveCharset = true; + break; + case Token.AT_RULE_BLOCK: + optimizeBody(token[1], token[2], context); + afterRules = true; + break; + case Token.NESTED_BLOCK: + token[1] = levelOptions.tidyBlockScopes ? tidyBlock(token[1], spaceAfterClosingBrace) : token[1]; + level1Optimize(token[2], context); + afterRules = true; + break; + case Token.COMMENT: + optimizeComment(token, options); + break; + case Token.RULE: + token[1] = levelOptions.tidySelectors ? tidyRules(token[1], !ie7Hack, adjacentSpace, format, context.warnings) : token[1]; + token[1] = token[1].length > 1 ? sortSelectors(token[1], levelOptions.selectorsSortingMethod) : token[1]; + optimizeBody(token[1], token[2], context); + afterRules = true; + break; + } + + if (token[0] == Token.COMMENT && token[1].length === 0 || levelOptions.removeEmpty && (token[1].length === 0 || (token[2] && token[2].length === 0))) { + tokens.splice(i, 1); + i--; + l--; + } + } + + if (levelOptions.cleanupCharsets && mayHaveCharset) { + cleanupCharsets(tokens); + } + + return tokens; +} + +module.exports = level1Optimize; diff --git a/node_modules/clean-css/lib/optimizer/level-1/shorten-hex.js b/node_modules/clean-css/lib/optimizer/level-1/shorten-hex.js new file mode 100644 index 0000000..3deea38 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/shorten-hex.js @@ -0,0 +1,189 @@ +var COLORS = { + aliceblue: '#f0f8ff', + antiquewhite: '#faebd7', + aqua: '#0ff', + aquamarine: '#7fffd4', + azure: '#f0ffff', + beige: '#f5f5dc', + bisque: '#ffe4c4', + black: '#000', + blanchedalmond: '#ffebcd', + blue: '#00f', + blueviolet: '#8a2be2', + brown: '#a52a2a', + burlywood: '#deb887', + cadetblue: '#5f9ea0', + chartreuse: '#7fff00', + chocolate: '#d2691e', + coral: '#ff7f50', + cornflowerblue: '#6495ed', + cornsilk: '#fff8dc', + crimson: '#dc143c', + cyan: '#0ff', + darkblue: '#00008b', + darkcyan: '#008b8b', + darkgoldenrod: '#b8860b', + darkgray: '#a9a9a9', + darkgreen: '#006400', + darkgrey: '#a9a9a9', + darkkhaki: '#bdb76b', + darkmagenta: '#8b008b', + darkolivegreen: '#556b2f', + darkorange: '#ff8c00', + darkorchid: '#9932cc', + darkred: '#8b0000', + darksalmon: '#e9967a', + darkseagreen: '#8fbc8f', + darkslateblue: '#483d8b', + darkslategray: '#2f4f4f', + darkslategrey: '#2f4f4f', + darkturquoise: '#00ced1', + darkviolet: '#9400d3', + deeppink: '#ff1493', + deepskyblue: '#00bfff', + dimgray: '#696969', + dimgrey: '#696969', + dodgerblue: '#1e90ff', + firebrick: '#b22222', + floralwhite: '#fffaf0', + forestgreen: '#228b22', + fuchsia: '#f0f', + gainsboro: '#dcdcdc', + ghostwhite: '#f8f8ff', + gold: '#ffd700', + goldenrod: '#daa520', + gray: '#808080', + green: '#008000', + greenyellow: '#adff2f', + grey: '#808080', + honeydew: '#f0fff0', + hotpink: '#ff69b4', + indianred: '#cd5c5c', + indigo: '#4b0082', + ivory: '#fffff0', + khaki: '#f0e68c', + lavender: '#e6e6fa', + lavenderblush: '#fff0f5', + lawngreen: '#7cfc00', + lemonchiffon: '#fffacd', + lightblue: '#add8e6', + lightcoral: '#f08080', + lightcyan: '#e0ffff', + lightgoldenrodyellow: '#fafad2', + lightgray: '#d3d3d3', + lightgreen: '#90ee90', + lightgrey: '#d3d3d3', + lightpink: '#ffb6c1', + lightsalmon: '#ffa07a', + lightseagreen: '#20b2aa', + lightskyblue: '#87cefa', + lightslategray: '#778899', + lightslategrey: '#778899', + lightsteelblue: '#b0c4de', + lightyellow: '#ffffe0', + lime: '#0f0', + limegreen: '#32cd32', + linen: '#faf0e6', + magenta: '#ff00ff', + maroon: '#800000', + mediumaquamarine: '#66cdaa', + mediumblue: '#0000cd', + mediumorchid: '#ba55d3', + mediumpurple: '#9370db', + mediumseagreen: '#3cb371', + mediumslateblue: '#7b68ee', + mediumspringgreen: '#00fa9a', + mediumturquoise: '#48d1cc', + mediumvioletred: '#c71585', + midnightblue: '#191970', + mintcream: '#f5fffa', + mistyrose: '#ffe4e1', + moccasin: '#ffe4b5', + navajowhite: '#ffdead', + navy: '#000080', + oldlace: '#fdf5e6', + olive: '#808000', + olivedrab: '#6b8e23', + orange: '#ffa500', + orangered: '#ff4500', + orchid: '#da70d6', + palegoldenrod: '#eee8aa', + palegreen: '#98fb98', + paleturquoise: '#afeeee', + palevioletred: '#db7093', + papayawhip: '#ffefd5', + peachpuff: '#ffdab9', + peru: '#cd853f', + pink: '#ffc0cb', + plum: '#dda0dd', + powderblue: '#b0e0e6', + purple: '#800080', + rebeccapurple: '#663399', + red: '#f00', + rosybrown: '#bc8f8f', + royalblue: '#4169e1', + saddlebrown: '#8b4513', + salmon: '#fa8072', + sandybrown: '#f4a460', + seagreen: '#2e8b57', + seashell: '#fff5ee', + sienna: '#a0522d', + silver: '#c0c0c0', + skyblue: '#87ceeb', + slateblue: '#6a5acd', + slategray: '#708090', + slategrey: '#708090', + snow: '#fffafa', + springgreen: '#00ff7f', + steelblue: '#4682b4', + tan: '#d2b48c', + teal: '#008080', + thistle: '#d8bfd8', + tomato: '#ff6347', + turquoise: '#40e0d0', + violet: '#ee82ee', + wheat: '#f5deb3', + white: '#fff', + whitesmoke: '#f5f5f5', + yellow: '#ff0', + yellowgreen: '#9acd32' +}; + +var toHex = {}; +var toName = {}; + +for (var name in COLORS) { + var hex = COLORS[name]; + + if (name.length < hex.length) { + toName[hex] = name; + } else { + toHex[name] = hex; + } +} + +var toHexPattern = new RegExp('(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig'); +var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)', 'ig'); + +function hexConverter(match, prefix, colorValue, suffix) { + return prefix + toHex[colorValue.toLowerCase()] + suffix; +} + +function nameConverter(match, colorValue, suffix) { + return toName[colorValue.toLowerCase()] + suffix; +} + +function shortenHex(value) { + var hasHex = value.indexOf('#') > -1; + var shortened = value.replace(toHexPattern, hexConverter); + + if (shortened != value) { + shortened = shortened.replace(toHexPattern, hexConverter); + } + + return hasHex ? + shortened.replace(toNamePattern, nameConverter) : + shortened; +} + +module.exports = shortenHex; diff --git a/node_modules/clean-css/lib/optimizer/level-1/shorten-hsl.js b/node_modules/clean-css/lib/optimizer/level-1/shorten-hsl.js new file mode 100644 index 0000000..fe98dfd --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/shorten-hsl.js @@ -0,0 +1,61 @@ +// HSL to RGB converter. Both methods adapted from: +// http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript + +function hslToRgb(h, s, l) { + var r, g, b; + + // normalize hue orientation b/w 0 and 360 degrees + h = h % 360; + if (h < 0) + h += 360; + h = ~~h / 360; + + if (s < 0) + s = 0; + else if (s > 100) + s = 100; + s = ~~s / 100; + + if (l < 0) + l = 0; + else if (l > 100) + l = 100; + l = ~~l / 100; + + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? + l * (1 + s) : + l + s - l * s; + var p = 2 * l - q; + r = hueToRgb(p, q, h + 1/3); + g = hueToRgb(p, q, h); + b = hueToRgb(p, q, h - 1/3); + } + + return [~~(r * 255), ~~(g * 255), ~~(b * 255)]; +} + +function hueToRgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1/6) return p + (q - p) * 6 * t; + if (t < 1/2) return q; + if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; +} + +function shortenHsl(hue, saturation, lightness) { + var asRgb = hslToRgb(hue, saturation, lightness); + var redAsHex = asRgb[0].toString(16); + var greenAsHex = asRgb[1].toString(16); + var blueAsHex = asRgb[2].toString(16); + + return '#' + + ((redAsHex.length == 1 ? '0' : '') + redAsHex) + + ((greenAsHex.length == 1 ? '0' : '') + greenAsHex) + + ((blueAsHex.length == 1 ? '0' : '') + blueAsHex); +} + +module.exports = shortenHsl; diff --git a/node_modules/clean-css/lib/optimizer/level-1/shorten-rgb.js b/node_modules/clean-css/lib/optimizer/level-1/shorten-rgb.js new file mode 100644 index 0000000..3c0a5fa --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/shorten-rgb.js @@ -0,0 +1,10 @@ +function shortenRgb(red, green, blue) { + var normalizedRed = Math.max(0, Math.min(parseInt(red), 255)); + var normalizedGreen = Math.max(0, Math.min(parseInt(green), 255)); + var normalizedBlue = Math.max(0, Math.min(parseInt(blue), 255)); + + // Credit: Asen http://jsbin.com/UPUmaGOc/2/edit?js,console + return '#' + ('00000' + (normalizedRed << 16 | normalizedGreen << 8 | normalizedBlue).toString(16)).slice(-6); +} + +module.exports = shortenRgb; diff --git a/node_modules/clean-css/lib/optimizer/level-1/sort-selectors.js b/node_modules/clean-css/lib/optimizer/level-1/sort-selectors.js new file mode 100644 index 0000000..5b261df --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/sort-selectors.js @@ -0,0 +1,23 @@ +var naturalCompare = require('../../utils/natural-compare'); + +function naturalSorter(scope1, scope2) { + return naturalCompare(scope1[1], scope2[1]); +} + +function standardSorter(scope1, scope2) { + return scope1[1] > scope2[1] ? 1 : -1; +} + +function sortSelectors(selectors, method) { + switch (method) { + case 'natural': + return selectors.sort(naturalSorter); + case 'standard': + return selectors.sort(standardSorter); + case 'none': + case false: + return selectors; + } +} + +module.exports = sortSelectors; diff --git a/node_modules/clean-css/lib/optimizer/level-1/tidy-at-rule.js b/node_modules/clean-css/lib/optimizer/level-1/tidy-at-rule.js new file mode 100644 index 0000000..a7b149f --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/tidy-at-rule.js @@ -0,0 +1,9 @@ +function tidyAtRule(value) { + return value + .replace(/\s+/g, ' ') + .replace(/url\(\s+/g, 'url(') + .replace(/\s+\)/g, ')') + .trim(); +} + +module.exports = tidyAtRule; diff --git a/node_modules/clean-css/lib/optimizer/level-1/tidy-block.js b/node_modules/clean-css/lib/optimizer/level-1/tidy-block.js new file mode 100644 index 0000000..8322aec --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/tidy-block.js @@ -0,0 +1,23 @@ +var SUPPORTED_COMPACT_BLOCK_MATCHER = /^@media\W/; + +function tidyBlock(values, spaceAfterClosingBrace) { + var withoutSpaceAfterClosingBrace; + var i; + + for (i = values.length - 1; i >= 0; i--) { + withoutSpaceAfterClosingBrace = !spaceAfterClosingBrace && SUPPORTED_COMPACT_BLOCK_MATCHER.test(values[i][1]); + + values[i][1] = values[i][1] + .replace(/\n|\r\n/g, ' ') + .replace(/\s+/g, ' ') + .replace(/(,|:|\() /g, '$1') + .replace(/ \)/g, ')') + .replace(/'([a-zA-Z][a-zA-Z\d\-_]+)'/, '$1') + .replace(/"([a-zA-Z][a-zA-Z\d\-_]+)"/, '$1') + .replace(withoutSpaceAfterClosingBrace ? /\) /g : null, ')'); + } + + return values; +} + +module.exports = tidyBlock; diff --git a/node_modules/clean-css/lib/optimizer/level-1/tidy-rules.js b/node_modules/clean-css/lib/optimizer/level-1/tidy-rules.js new file mode 100644 index 0000000..d046d0e --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-1/tidy-rules.js @@ -0,0 +1,213 @@ +var Spaces = require('../../options/format').Spaces; +var Marker = require('../../tokenizer/marker'); +var formatPosition = require('../../utils/format-position'); + +var CASE_ATTRIBUTE_PATTERN = /[\s"'][iI]\s*\]/; +var CASE_RESTORE_PATTERN = /([\d\w])([iI])\]/g; +var DOUBLE_QUOTE_CASE_PATTERN = /="([a-zA-Z][a-zA-Z\d\-_]+)"([iI])/g; +var DOUBLE_QUOTE_PATTERN = /="([a-zA-Z][a-zA-Z\d\-_]+)"(\s|\])/g; +var HTML_COMMENT_PATTERN = /^(?:(?:)\s*)+/; +var SINGLE_QUOTE_CASE_PATTERN = /='([a-zA-Z][a-zA-Z\d\-_]+)'([iI])/g; +var SINGLE_QUOTE_PATTERN = /='([a-zA-Z][a-zA-Z\d\-_]+)'(\s|\])/g; +var RELATION_PATTERN = /[>\+~]/; +var WHITESPACE_PATTERN = /\s/; + +var ASTERISK_PLUS_HTML_HACK = '*+html '; +var ASTERISK_FIRST_CHILD_PLUS_HTML_HACK = '*:first-child+html '; +var LESS_THAN = '<'; + +function hasInvalidCharacters(value) { + var isEscaped; + var isInvalid = false; + var character; + var isQuote = false; + var i, l; + + for (i = 0, l = value.length; i < l; i++) { + character = value[i]; + + if (isEscaped) { + // continue as always + } else if (character == Marker.SINGLE_QUOTE || character == Marker.DOUBLE_QUOTE) { + isQuote = !isQuote; + } else if (!isQuote && (character == Marker.CLOSE_CURLY_BRACKET || character == Marker.EXCLAMATION || character == LESS_THAN || character == Marker.SEMICOLON)) { + isInvalid = true; + break; + } else if (!isQuote && i === 0 && RELATION_PATTERN.test(character)) { + isInvalid = true; + break; + } + + isEscaped = character == Marker.BACK_SLASH; + } + + return isInvalid; +} + +function removeWhitespace(value, format) { + var stripped = []; + var character; + var isNewLineNix; + var isNewLineWin; + var isEscaped; + var wasEscaped; + var isQuoted; + var isSingleQuoted; + var isDoubleQuoted; + var isAttribute; + var isRelation; + var isWhitespace; + var roundBracketLevel = 0; + var wasRelation = false; + var wasWhitespace = false; + var withCaseAttribute = CASE_ATTRIBUTE_PATTERN.test(value); + var spaceAroundRelation = format && format.spaces[Spaces.AroundSelectorRelation]; + var i, l; + + for (i = 0, l = value.length; i < l; i++) { + character = value[i]; + + isNewLineNix = character == Marker.NEW_LINE_NIX; + isNewLineWin = character == Marker.NEW_LINE_NIX && value[i - 1] == Marker.CARRIAGE_RETURN; + isQuoted = isSingleQuoted || isDoubleQuoted; + isRelation = !isAttribute && !isEscaped && roundBracketLevel === 0 && RELATION_PATTERN.test(character); + isWhitespace = WHITESPACE_PATTERN.test(character); + + if (wasEscaped && isQuoted && isNewLineWin) { + // swallow escaped new windows lines in comments + stripped.pop(); + stripped.pop(); + } else if (isEscaped && isQuoted && isNewLineNix) { + // swallow escaped new *nix lines in comments + stripped.pop(); + } else if (isEscaped) { + stripped.push(character); + } else if (character == Marker.OPEN_SQUARE_BRACKET && !isQuoted) { + stripped.push(character); + isAttribute = true; + } else if (character == Marker.CLOSE_SQUARE_BRACKET && !isQuoted) { + stripped.push(character); + isAttribute = false; + } else if (character == Marker.OPEN_ROUND_BRACKET && !isQuoted) { + stripped.push(character); + roundBracketLevel++; + } else if (character == Marker.CLOSE_ROUND_BRACKET && !isQuoted) { + stripped.push(character); + roundBracketLevel--; + } else if (character == Marker.SINGLE_QUOTE && !isQuoted) { + stripped.push(character); + isSingleQuoted = true; + } else if (character == Marker.DOUBLE_QUOTE && !isQuoted) { + stripped.push(character); + isDoubleQuoted = true; + } else if (character == Marker.SINGLE_QUOTE && isQuoted) { + stripped.push(character); + isSingleQuoted = false; + } else if (character == Marker.DOUBLE_QUOTE && isQuoted) { + stripped.push(character); + isDoubleQuoted = false; + } else if (isWhitespace && wasRelation && !spaceAroundRelation) { + continue; + } else if (!isWhitespace && wasRelation && spaceAroundRelation) { + stripped.push(Marker.SPACE); + stripped.push(character); + } else if (isWhitespace && (isAttribute || roundBracketLevel > 0) && !isQuoted) { + // skip space + } else if (isWhitespace && wasWhitespace && !isQuoted) { + // skip extra space + } else if ((isNewLineWin || isNewLineNix) && (isAttribute || roundBracketLevel > 0) && isQuoted) { + // skip newline + } else if (isRelation && wasWhitespace && !spaceAroundRelation) { + stripped.pop(); + stripped.push(character); + } else if (isRelation && !wasWhitespace && spaceAroundRelation) { + stripped.push(Marker.SPACE); + stripped.push(character); + } else if (isWhitespace) { + stripped.push(Marker.SPACE); + } else { + stripped.push(character); + } + + wasEscaped = isEscaped; + isEscaped = character == Marker.BACK_SLASH; + wasRelation = isRelation; + wasWhitespace = isWhitespace; + } + + return withCaseAttribute ? + stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]') : + stripped.join(''); +} + +function removeQuotes(value) { + if (value.indexOf('\'') == -1 && value.indexOf('"') == -1) { + return value; + } + + return value + .replace(SINGLE_QUOTE_CASE_PATTERN, '=$1 $2') + .replace(SINGLE_QUOTE_PATTERN, '=$1$2') + .replace(DOUBLE_QUOTE_CASE_PATTERN, '=$1 $2') + .replace(DOUBLE_QUOTE_PATTERN, '=$1$2'); +} + +function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) { + var list = []; + var repeated = []; + + function removeHTMLComment(rule, match) { + warnings.push('HTML comment \'' + match + '\' at ' + formatPosition(rule[2][0]) + '. Removing.'); + return ''; + } + + for (var i = 0, l = rules.length; i < l; i++) { + var rule = rules[i]; + var reduced = rule[1]; + + reduced = reduced.replace(HTML_COMMENT_PATTERN, removeHTMLComment.bind(null, rule)); + + if (hasInvalidCharacters(reduced)) { + warnings.push('Invalid selector \'' + rule[1] + '\' at ' + formatPosition(rule[2][0]) + '. Ignoring.'); + continue; + } + + reduced = removeWhitespace(reduced, format); + reduced = removeQuotes(reduced); + + if (adjacentSpace && reduced.indexOf('nav') > 0) { + reduced = reduced.replace(/\+nav(\S|$)/, '+ nav$1'); + } + + if (removeUnsupported && reduced.indexOf(ASTERISK_PLUS_HTML_HACK) > -1) { + continue; + } + + if (removeUnsupported && reduced.indexOf(ASTERISK_FIRST_CHILD_PLUS_HTML_HACK) > -1) { + continue; + } + + if (reduced.indexOf('*') > -1) { + reduced = reduced + .replace(/\*([:#\.\[])/g, '$1') + .replace(/^(\:first\-child)?\+html/, '*$1+html'); + } + + if (repeated.indexOf(reduced) > -1) { + continue; + } + + rule[1] = reduced; + repeated.push(reduced); + list.push(rule); + } + + if (list.length == 1 && list[0][1].length === 0) { + warnings.push('Empty selector \'' + list[0][1] + '\' at ' + formatPosition(list[0][2][0]) + '. Ignoring.'); + list = []; + } + + return list; +} + +module.exports = tidyRules; diff --git a/node_modules/clean-css/lib/optimizer/level-2/break-up.js b/node_modules/clean-css/lib/optimizer/level-2/break-up.js new file mode 100644 index 0000000..5301cb8 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/break-up.js @@ -0,0 +1,644 @@ +var InvalidPropertyError = require('./invalid-property-error'); + +var wrapSingle = require('../wrap-for-optimizing').single; + +var Token = require('../../tokenizer/token'); +var Marker = require('../../tokenizer/marker'); + +var formatPosition = require('../../utils/format-position'); + +function _anyIsInherit(values) { + var i, l; + + for (i = 0, l = values.length; i < l; i++) { + if (values[i][1] == 'inherit') { + return true; + } + } + + return false; +} + +function _colorFilter(validator) { + return function (value) { + return value[1] == 'invert' || validator.isColor(value[1]) || validator.isPrefixed(value[1]); + }; +} + +function _styleFilter(validator) { + return function (value) { + return value[1] != 'inherit' && validator.isStyleKeyword(value[1]) && !validator.isColorFunction(value[1]); + }; +} + +function _wrapDefault(name, property, compactable) { + var descriptor = compactable[name]; + if (descriptor.doubleValues && descriptor.defaultValue.length == 2) { + return wrapSingle([ + Token.PROPERTY, + [Token.PROPERTY_NAME, name], + [Token.PROPERTY_VALUE, descriptor.defaultValue[0]], + [Token.PROPERTY_VALUE, descriptor.defaultValue[1]] + ]); + } else if (descriptor.doubleValues && descriptor.defaultValue.length == 1) { + return wrapSingle([ + Token.PROPERTY, + [Token.PROPERTY_NAME, name], + [Token.PROPERTY_VALUE, descriptor.defaultValue[0]] + ]); + } else { + return wrapSingle([ + Token.PROPERTY, + [Token.PROPERTY_NAME, name], + [Token.PROPERTY_VALUE, descriptor.defaultValue] + ]); + } +} + +function _widthFilter(validator) { + return function (value) { + return value[1] != 'inherit' && + (validator.isWidth(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1])) && + !validator.isStyleKeyword(value[1]) && + !validator.isColorFunction(value[1]); + }; +} + +function animation(property, compactable, validator) { + var duration = _wrapDefault(property.name + '-duration', property, compactable); + var timing = _wrapDefault(property.name + '-timing-function', property, compactable); + var delay = _wrapDefault(property.name + '-delay', property, compactable); + var iteration = _wrapDefault(property.name + '-iteration-count', property, compactable); + var direction = _wrapDefault(property.name + '-direction', property, compactable); + var fill = _wrapDefault(property.name + '-fill-mode', property, compactable); + var play = _wrapDefault(property.name + '-play-state', property, compactable); + var name = _wrapDefault(property.name + '-name', property, compactable); + var components = [duration, timing, delay, iteration, direction, fill, play, name]; + var values = property.value; + var value; + var durationSet = false; + var timingSet = false; + var delaySet = false; + var iterationSet = false; + var directionSet = false; + var fillSet = false; + var playSet = false; + var nameSet = false; + var i; + var l; + + if (property.value.length == 1 && property.value[0][1] == 'inherit') { + duration.value = timing.value = delay.value = iteration.value = direction.value = fill.value = play.value = name.value = property.value; + return components; + } + + if (values.length > 1 && _anyIsInherit(values)) { + throw new InvalidPropertyError('Invalid animation values at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + for (i = 0, l = values.length; i < l; i++) { + value = values[i]; + + if (validator.isTime(value[1]) && !durationSet) { + duration.value = [value]; + durationSet = true; + } else if (validator.isTime(value[1]) && !delaySet) { + delay.value = [value]; + delaySet = true; + } else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) { + timing.value = [value]; + timingSet = true; + } else if ((validator.isAnimationIterationCountKeyword(value[1]) || validator.isPositiveNumber(value[1])) && !iterationSet) { + iteration.value = [value]; + iterationSet = true; + } else if (validator.isAnimationDirectionKeyword(value[1]) && !directionSet) { + direction.value = [value]; + directionSet = true; + } else if (validator.isAnimationFillModeKeyword(value[1]) && !fillSet) { + fill.value = [value]; + fillSet = true; + } else if (validator.isAnimationPlayStateKeyword(value[1]) && !playSet) { + play.value = [value]; + playSet = true; + } else if ((validator.isAnimationNameKeyword(value[1]) || validator.isIdentifier(value[1])) && !nameSet) { + name.value = [value]; + nameSet = true; + } else { + throw new InvalidPropertyError('Invalid animation value at ' + formatPosition(value[2][0]) + '. Ignoring.'); + } + } + + return components; +} + +function background(property, compactable, validator) { + var image = _wrapDefault('background-image', property, compactable); + var position = _wrapDefault('background-position', property, compactable); + var size = _wrapDefault('background-size', property, compactable); + var repeat = _wrapDefault('background-repeat', property, compactable); + var attachment = _wrapDefault('background-attachment', property, compactable); + var origin = _wrapDefault('background-origin', property, compactable); + var clip = _wrapDefault('background-clip', property, compactable); + var color = _wrapDefault('background-color', property, compactable); + var components = [image, position, size, repeat, attachment, origin, clip, color]; + var values = property.value; + + var positionSet = false; + var clipSet = false; + var originSet = false; + var repeatSet = false; + + var anyValueSet = false; + + if (property.value.length == 1 && property.value[0][1] == 'inherit') { + // NOTE: 'inherit' is not a valid value for background-attachment + color.value = image.value = repeat.value = position.value = size.value = origin.value = clip.value = property.value; + return components; + } + + if (property.value.length == 1 && property.value[0][1] == '0 0') { + return components; + } + + for (var i = values.length - 1; i >= 0; i--) { + var value = values[i]; + + if (validator.isBackgroundAttachmentKeyword(value[1])) { + attachment.value = [value]; + anyValueSet = true; + } else if (validator.isBackgroundClipKeyword(value[1]) || validator.isBackgroundOriginKeyword(value[1])) { + if (clipSet) { + origin.value = [value]; + originSet = true; + } else { + clip.value = [value]; + clipSet = true; + } + anyValueSet = true; + } else if (validator.isBackgroundRepeatKeyword(value[1])) { + if (repeatSet) { + repeat.value.unshift(value); + } else { + repeat.value = [value]; + repeatSet = true; + } + anyValueSet = true; + } else if (validator.isBackgroundPositionKeyword(value[1]) || validator.isBackgroundSizeKeyword(value[1]) || validator.isUnit(value[1]) || validator.isDynamicUnit(value[1])) { + if (i > 0) { + var previousValue = values[i - 1]; + + if (previousValue[1] == Marker.FORWARD_SLASH) { + size.value = [value]; + } else if (i > 1 && values[i - 2][1] == Marker.FORWARD_SLASH) { + size.value = [previousValue, value]; + i -= 2; + } else { + if (!positionSet) + position.value = []; + + position.value.unshift(value); + positionSet = true; + } + } else { + if (!positionSet) + position.value = []; + + position.value.unshift(value); + positionSet = true; + } + anyValueSet = true; + } else if ((color.value[0][1] == compactable[color.name].defaultValue || color.value[0][1] == 'none') && (validator.isColor(value[1]) || validator.isPrefixed(value[1]))) { + color.value = [value]; + anyValueSet = true; + } else if (validator.isUrl(value[1]) || validator.isFunction(value[1])) { + image.value = [value]; + anyValueSet = true; + } + } + + if (clipSet && !originSet) + origin.value = clip.value.slice(0); + + if (!anyValueSet) { + throw new InvalidPropertyError('Invalid background value at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + return components; +} + +function borderRadius(property, compactable) { + var values = property.value; + var splitAt = -1; + + for (var i = 0, l = values.length; i < l; i++) { + if (values[i][1] == Marker.FORWARD_SLASH) { + splitAt = i; + break; + } + } + + if (splitAt === 0 || splitAt === values.length - 1) { + throw new InvalidPropertyError('Invalid border-radius value at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + var target = _wrapDefault(property.name, property, compactable); + target.value = splitAt > -1 ? + values.slice(0, splitAt) : + values.slice(0); + target.components = fourValues(target, compactable); + + var remainder = _wrapDefault(property.name, property, compactable); + remainder.value = splitAt > -1 ? + values.slice(splitAt + 1) : + values.slice(0); + remainder.components = fourValues(remainder, compactable); + + for (var j = 0; j < 4; j++) { + target.components[j].multiplex = true; + target.components[j].value = target.components[j].value.concat(remainder.components[j].value); + } + + return target.components; +} + +function font(property, compactable, validator) { + var style = _wrapDefault('font-style', property, compactable); + var variant = _wrapDefault('font-variant', property, compactable); + var weight = _wrapDefault('font-weight', property, compactable); + var stretch = _wrapDefault('font-stretch', property, compactable); + var size = _wrapDefault('font-size', property, compactable); + var height = _wrapDefault('line-height', property, compactable); + var family = _wrapDefault('font-family', property, compactable); + var components = [style, variant, weight, stretch, size, height, family]; + var values = property.value; + var fuzzyMatched = 4; // style, variant, weight, and stretch + var index = 0; + var isStretchSet = false; + var isStretchValid; + var isStyleSet = false; + var isStyleValid; + var isVariantSet = false; + var isVariantValid; + var isWeightSet = false; + var isWeightValid; + var isSizeSet = false; + var appendableFamilyName = false; + + if (!values[index]) { + throw new InvalidPropertyError('Missing font values at ' + formatPosition(property.all[property.position][1][2][0]) + '. Ignoring.'); + } + + if (values.length == 1 && values[0][1] == 'inherit') { + style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values; + return components; + } + + if (values.length == 1 && (validator.isFontKeyword(values[0][1]) || validator.isGlobal(values[0][1]) || validator.isPrefixed(values[0][1]))) { + values[0][1] = Marker.INTERNAL + values[0][1]; + style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values; + return components; + } + + if (values.length < 2 || !_anyIsFontSize(values, validator) || !_anyIsFontFamily(values, validator)) { + throw new InvalidPropertyError('Invalid font values at ' + formatPosition(property.all[property.position][1][2][0]) + '. Ignoring.'); + } + + if (values.length > 1 && _anyIsInherit(values)) { + throw new InvalidPropertyError('Invalid font values at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + // fuzzy match style, variant, weight, and stretch on first elements + while (index < fuzzyMatched) { + isStretchValid = validator.isFontStretchKeyword(values[index][1]) || validator.isGlobal(values[index][1]); + isStyleValid = validator.isFontStyleKeyword(values[index][1]) || validator.isGlobal(values[index][1]); + isVariantValid = validator.isFontVariantKeyword(values[index][1]) || validator.isGlobal(values[index][1]); + isWeightValid = validator.isFontWeightKeyword(values[index][1]) || validator.isGlobal(values[index][1]); + + if (isStyleValid && !isStyleSet) { + style.value = [values[index]]; + isStyleSet = true; + } else if (isVariantValid && !isVariantSet) { + variant.value = [values[index]]; + isVariantSet = true; + } else if (isWeightValid && !isWeightSet) { + weight.value = [values[index]]; + isWeightSet = true; + } else if (isStretchValid && !isStretchSet) { + stretch.value = [values[index]]; + isStretchSet = true; + } else if (isStyleValid && isStyleSet || isVariantValid && isVariantSet || isWeightValid && isWeightSet || isStretchValid && isStretchSet) { + throw new InvalidPropertyError('Invalid font style / variant / weight / stretch value at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } else { + break; + } + + index++; + } + + // now comes font-size ... + if (validator.isFontSizeKeyword(values[index][1]) || validator.isUnit(values[index][1]) && !validator.isDynamicUnit(values[index][1])) { + size.value = [values[index]]; + isSizeSet = true; + index++; + } else { + throw new InvalidPropertyError('Missing font size at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + if (!values[index]) { + throw new InvalidPropertyError('Missing font family at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + // ... and perhaps line-height + if (isSizeSet && values[index] && values[index][1] == Marker.FORWARD_SLASH && values[index + 1] && (validator.isLineHeightKeyword(values[index + 1][1]) || validator.isUnit(values[index + 1][1]) || validator.isNumber(values[index + 1][1]))) { + height.value = [values[index + 1]]; + index++; + index++; + } + + // ... and whatever comes next is font-family + family.value = []; + + while (values[index]) { + if (values[index][1] == Marker.COMMA) { + appendableFamilyName = false; + } else { + if (appendableFamilyName) { + family.value[family.value.length - 1][1] += Marker.SPACE + values[index][1]; + } else { + family.value.push(values[index]); + } + + appendableFamilyName = true; + } + + index++; + } + + if (family.value.length === 0) { + throw new InvalidPropertyError('Missing font family at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + return components; +} + +function _anyIsFontSize(values, validator) { + var value; + var i, l; + + for (i = 0, l = values.length; i < l; i++) { + value = values[i]; + + if (validator.isFontSizeKeyword(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1]) || validator.isFunction(value[1])) { + return true; + } + } + + return false; +} + +function _anyIsFontFamily(values, validator) { + var value; + var i, l; + + for (i = 0, l = values.length; i < l; i++) { + value = values[i]; + + if (validator.isIdentifier(value[1])) { + return true; + } + } + + return false; +} + +function fourValues(property, compactable) { + var componentNames = compactable[property.name].components; + var components = []; + var value = property.value; + + if (value.length < 1) + return []; + + if (value.length < 2) + value[1] = value[0].slice(0); + if (value.length < 3) + value[2] = value[0].slice(0); + if (value.length < 4) + value[3] = value[1].slice(0); + + for (var i = componentNames.length - 1; i >= 0; i--) { + var component = wrapSingle([ + Token.PROPERTY, + [Token.PROPERTY_NAME, componentNames[i]] + ]); + component.value = [value[i]]; + components.unshift(component); + } + + return components; +} + +function multiplex(splitWith) { + return function (property, compactable, validator) { + var splitsAt = []; + var values = property.value; + var i, j, l, m; + + // find split commas + for (i = 0, l = values.length; i < l; i++) { + if (values[i][1] == ',') + splitsAt.push(i); + } + + if (splitsAt.length === 0) + return splitWith(property, compactable, validator); + + var splitComponents = []; + + // split over commas, and into components + for (i = 0, l = splitsAt.length; i <= l; i++) { + var from = i === 0 ? 0 : splitsAt[i - 1] + 1; + var to = i < l ? splitsAt[i] : values.length; + + var _property = _wrapDefault(property.name, property, compactable); + _property.value = values.slice(from, to); + + splitComponents.push(splitWith(_property, compactable, validator)); + } + + var components = splitComponents[0]; + + // group component values from each split + for (i = 0, l = components.length; i < l; i++) { + components[i].multiplex = true; + + for (j = 1, m = splitComponents.length; j < m; j++) { + components[i].value.push([Token.PROPERTY_VALUE, Marker.COMMA]); + Array.prototype.push.apply(components[i].value, splitComponents[j][i].value); + } + } + + return components; + }; +} + +function listStyle(property, compactable, validator) { + var type = _wrapDefault('list-style-type', property, compactable); + var position = _wrapDefault('list-style-position', property, compactable); + var image = _wrapDefault('list-style-image', property, compactable); + var components = [type, position, image]; + + if (property.value.length == 1 && property.value[0][1] == 'inherit') { + type.value = position.value = image.value = [property.value[0]]; + return components; + } + + var values = property.value.slice(0); + var total = values.length; + var index = 0; + + // `image` first... + for (index = 0, total = values.length; index < total; index++) { + if (validator.isUrl(values[index][1]) || values[index][1] == '0') { + image.value = [values[index]]; + values.splice(index, 1); + break; + } + } + + // ... then `position` + for (index = 0, total = values.length; index < total; index++) { + if (validator.isListStylePositionKeyword(values[index][1])) { + position.value = [values[index]]; + values.splice(index, 1); + break; + } + } + + // ... and what's left is a `type` + if (values.length > 0 && (validator.isListStyleTypeKeyword(values[0][1]) || validator.isIdentifier(values[0][1]))) { + type.value = [values[0]]; + } + + return components; +} + +function transition(property, compactable, validator) { + var prop = _wrapDefault(property.name + '-property', property, compactable); + var duration = _wrapDefault(property.name + '-duration', property, compactable); + var timing = _wrapDefault(property.name + '-timing-function', property, compactable); + var delay = _wrapDefault(property.name + '-delay', property, compactable); + var components = [prop, duration, timing, delay]; + var values = property.value; + var value; + var durationSet = false; + var delaySet = false; + var propSet = false; + var timingSet = false; + var i; + var l; + + if (property.value.length == 1 && property.value[0][1] == 'inherit') { + prop.value = duration.value = timing.value = delay.value = property.value; + return components; + } + + if (values.length > 1 && _anyIsInherit(values)) { + throw new InvalidPropertyError('Invalid animation values at ' + formatPosition(values[0][2][0]) + '. Ignoring.'); + } + + for (i = 0, l = values.length; i < l; i++) { + value = values[i]; + + if (validator.isTime(value[1]) && !durationSet) { + duration.value = [value]; + durationSet = true; + } else if (validator.isTime(value[1]) && !delaySet) { + delay.value = [value]; + delaySet = true; + } else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) { + timing.value = [value]; + timingSet = true; + } else if (validator.isIdentifier(value[1]) && !propSet) { + prop.value = [value]; + propSet = true; + } else { + throw new InvalidPropertyError('Invalid animation value at ' + formatPosition(value[2][0]) + '. Ignoring.'); + } + } + + return components; +} + +function widthStyleColor(property, compactable, validator) { + var descriptor = compactable[property.name]; + var components = [ + _wrapDefault(descriptor.components[0], property, compactable), + _wrapDefault(descriptor.components[1], property, compactable), + _wrapDefault(descriptor.components[2], property, compactable) + ]; + var color, style, width; + + for (var i = 0; i < 3; i++) { + var component = components[i]; + + if (component.name.indexOf('color') > 0) + color = component; + else if (component.name.indexOf('style') > 0) + style = component; + else + width = component; + } + + if ((property.value.length == 1 && property.value[0][1] == 'inherit') || + (property.value.length == 3 && property.value[0][1] == 'inherit' && property.value[1][1] == 'inherit' && property.value[2][1] == 'inherit')) { + color.value = style.value = width.value = [property.value[0]]; + return components; + } + + var values = property.value.slice(0); + var match, matches; + + // NOTE: usually users don't follow the required order of parts in this shorthand, + // so we'll try to parse it caring as little about order as possible + + if (values.length > 0) { + matches = values.filter(_widthFilter(validator)); + match = matches.length > 1 && (matches[0][1] == 'none' || matches[0][1] == 'auto') ? matches[1] : matches[0]; + if (match) { + width.value = [match]; + values.splice(values.indexOf(match), 1); + } + } + + if (values.length > 0) { + match = values.filter(_styleFilter(validator))[0]; + if (match) { + style.value = [match]; + values.splice(values.indexOf(match), 1); + } + } + + if (values.length > 0) { + match = values.filter(_colorFilter(validator))[0]; + if (match) { + color.value = [match]; + values.splice(values.indexOf(match), 1); + } + } + + return components; +} + +module.exports = { + animation: animation, + background: background, + border: widthStyleColor, + borderRadius: borderRadius, + font: font, + fourValues: fourValues, + listStyle: listStyle, + multiplex: multiplex, + outline: widthStyleColor, + transition: transition +}; diff --git a/node_modules/clean-css/lib/optimizer/level-2/can-override.js b/node_modules/clean-css/lib/optimizer/level-2/can-override.js new file mode 100644 index 0000000..3dae08f --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/can-override.js @@ -0,0 +1,283 @@ +var understandable = require('./properties/understandable'); + +function animationIterationCount(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2); +} + +function animationName(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2); +} + +function areSameFunction(validator, value1, value2) { + if (!validator.isFunction(value1) || !validator.isFunction(value2)) { + return false; + } + + var function1Name = value1.substring(0, value1.indexOf('(')); + var function2Name = value2.substring(0, value2.indexOf('(')); + + return function1Name === function2Name; +} + +function backgroundPosition(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if (validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2)) { + return true; + } + + return unit(validator, value1, value2); +} + +function backgroundSize(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if (validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2)) { + return true; + } + + return unit(validator, value1, value2); +} + +function color(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isColor(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if (!validator.colorOpacity && (validator.isRgbColor(value1) || validator.isHslColor(value1))) { + return false; + } else if (!validator.colorOpacity && (validator.isRgbColor(value2) || validator.isHslColor(value2))) { + return false; + } else if (validator.isColor(value1) && validator.isColor(value2)) { + return true; + } + + return sameFunctionOrValue(validator, value1, value2); +} + +function components(overrideCheckers) { + return function (validator, value1, value2, position) { + return overrideCheckers[position](validator, value1, value2); + }; +} + +function fontFamily(validator, value1, value2) { + return understandable(validator, value1, value2, 0, true); +} + +function image(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isImage(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if (validator.isImage(value2)) { + return true; + } else if (validator.isImage(value1)) { + return false; + } + + return sameFunctionOrValue(validator, value1, value2); +} + +function keyword(propertyName) { + return function(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isKeyword(propertyName)(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isKeyword(propertyName)(value2); + }; +} + +function keywordWithGlobal(propertyName) { + return function(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2); + }; +} + +function propertyName(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isIdentifier(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isIdentifier(value2); +} + +function sameFunctionOrValue(validator, value1, value2) { + return areSameFunction(validator, value1, value2) ? + true : + value1 === value2; +} + +function textShadow(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2); +} + +function time(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isTime(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if (validator.isTime(value1) && !validator.isTime(value2)) { + return false; + } else if (validator.isTime(value2)) { + return true; + } else if (validator.isTime(value1)) { + return false; + } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) { + return true; + } + + return sameFunctionOrValue(validator, value1, value2); +} + +function timingFunction(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isTimingFunction(value2) || validator.isGlobal(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isTimingFunction(value2) || validator.isGlobal(value2); +} + +function unit(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isUnit(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if (validator.isUnit(value1) && !validator.isUnit(value2)) { + return false; + } else if (validator.isUnit(value2)) { + return true; + } else if (validator.isUnit(value1)) { + return false; + } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) { + return true; + } + + return sameFunctionOrValue(validator, value1, value2); +} + +function unitOrKeywordWithGlobal(propertyName) { + var byKeyword = keywordWithGlobal(propertyName); + + return function(validator, value1, value2) { + return unit(validator, value1, value2) || byKeyword(validator, value1, value2); + }; +} + +function unitOrNumber(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isNumber(value2))) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } else if ((validator.isUnit(value1) || validator.isNumber(value1)) && !(validator.isUnit(value2) || validator.isNumber(value2))) { + return false; + } else if (validator.isUnit(value2) || validator.isNumber(value2)) { + return true; + } else if (validator.isUnit(value1) || validator.isNumber(value1)) { + return false; + } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) { + return true; + } + + return sameFunctionOrValue(validator, value1, value2); +} + +function zIndex(validator, value1, value2) { + if (!understandable(validator, value1, value2, 0, true) && !validator.isZIndex(value2)) { + return false; + } else if (validator.isVariable(value1) && validator.isVariable(value2)) { + return true; + } + + return validator.isZIndex(value2); +} + +module.exports = { + generic: { + color: color, + components: components, + image: image, + propertyName: propertyName, + time: time, + timingFunction: timingFunction, + unit: unit, + unitOrNumber: unitOrNumber + }, + property: { + animationDirection: keywordWithGlobal('animation-direction'), + animationFillMode: keyword('animation-fill-mode'), + animationIterationCount: animationIterationCount, + animationName: animationName, + animationPlayState: keywordWithGlobal('animation-play-state'), + backgroundAttachment: keyword('background-attachment'), + backgroundClip: keywordWithGlobal('background-clip'), + backgroundOrigin: keyword('background-origin'), + backgroundPosition: backgroundPosition, + backgroundRepeat: keyword('background-repeat'), + backgroundSize: backgroundSize, + bottom: unitOrKeywordWithGlobal('bottom'), + borderCollapse: keyword('border-collapse'), + borderStyle: keywordWithGlobal('*-style'), + clear: keywordWithGlobal('clear'), + cursor: keywordWithGlobal('cursor'), + display: keywordWithGlobal('display'), + float: keywordWithGlobal('float'), + left: unitOrKeywordWithGlobal('left'), + fontFamily: fontFamily, + fontStretch: keywordWithGlobal('font-stretch'), + fontStyle: keywordWithGlobal('font-style'), + fontVariant: keywordWithGlobal('font-variant'), + fontWeight: keywordWithGlobal('font-weight'), + listStyleType: keywordWithGlobal('list-style-type'), + listStylePosition: keywordWithGlobal('list-style-position'), + outlineStyle: keywordWithGlobal('*-style'), + overflow: keywordWithGlobal('overflow'), + position: keywordWithGlobal('position'), + right: unitOrKeywordWithGlobal('right'), + textAlign: keywordWithGlobal('text-align'), + textDecoration: keywordWithGlobal('text-decoration'), + textOverflow: keywordWithGlobal('text-overflow'), + textShadow: textShadow, + top: unitOrKeywordWithGlobal('top'), + transform: sameFunctionOrValue, + verticalAlign: unitOrKeywordWithGlobal('vertical-align'), + visibility: keywordWithGlobal('visibility'), + whiteSpace: keywordWithGlobal('white-space'), + zIndex: zIndex + } +}; diff --git a/node_modules/clean-css/lib/optimizer/level-2/clone.js b/node_modules/clean-css/lib/optimizer/level-2/clone.js new file mode 100644 index 0000000..3830095 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/clone.js @@ -0,0 +1,33 @@ +var wrapSingle = require('../wrap-for-optimizing').single; + +var Token = require('../../tokenizer/token'); + +function deep(property) { + var cloned = shallow(property); + for (var i = property.components.length - 1; i >= 0; i--) { + var component = shallow(property.components[i]); + component.value = property.components[i].value.slice(0); + cloned.components.unshift(component); + } + + cloned.dirty = true; + cloned.value = property.value.slice(0); + + return cloned; +} + +function shallow(property) { + var cloned = wrapSingle([ + Token.PROPERTY, + [Token.PROPERTY_NAME, property.name] + ]); + cloned.important = property.important; + cloned.hack = property.hack; + cloned.unused = false; + return cloned; +} + +module.exports = { + deep: deep, + shallow: shallow +}; diff --git a/node_modules/clean-css/lib/optimizer/level-2/compactable.js b/node_modules/clean-css/lib/optimizer/level-2/compactable.js new file mode 100644 index 0000000..73f42a1 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/compactable.js @@ -0,0 +1,1063 @@ +// Contains the interpretation of CSS properties, as used by the property optimizer + +var breakUp = require('./break-up'); +var canOverride = require('./can-override'); +var restore = require('./restore'); + +var override = require('../../utils/override'); + +// Properties to process +// Extend this object in order to add support for more properties in the optimizer. +// +// Each key in this object represents a CSS property and should be an object. +// Such an object contains properties that describe how the represented CSS property should be handled. +// Possible options: +// +// * components: array (Only specify for shorthand properties.) +// Contains the names of the granular properties this shorthand compacts. +// +// * canOverride: function +// Returns whether two tokens of this property can be merged with each other. +// This property has no meaning for shorthands. +// +// * defaultValue: string +// Specifies the default value of the property according to the CSS standard. +// For shorthand, this is used when every component is set to its default value, therefore it should be the shortest possible default value of all the components. +// +// * shortestValue: string +// Specifies the shortest possible value the property can possibly have. +// (Falls back to defaultValue if unspecified.) +// +// * breakUp: function (Only specify for shorthand properties.) +// Breaks the shorthand up to its components. +// +// * restore: function (Only specify for shorthand properties.) +// Puts the shorthand together from its components. +// +var compactable = { + 'animation': { + canOverride: canOverride.generic.components([ + canOverride.generic.time, + canOverride.generic.timingFunction, + canOverride.generic.time, + canOverride.property.animationIterationCount, + canOverride.property.animationDirection, + canOverride.property.animationFillMode, + canOverride.property.animationPlayState, + canOverride.property.animationName + ]), + components: [ + 'animation-duration', + 'animation-timing-function', + 'animation-delay', + 'animation-iteration-count', + 'animation-direction', + 'animation-fill-mode', + 'animation-play-state', + 'animation-name' + ], + breakUp: breakUp.multiplex(breakUp.animation), + defaultValue: 'none', + restore: restore.multiplex(restore.withoutDefaults), + shorthand: true, + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-delay': { + canOverride: canOverride.generic.time, + componentOf: [ + 'animation' + ], + defaultValue: '0s', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-direction': { + canOverride: canOverride.property.animationDirection, + componentOf: [ + 'animation' + ], + defaultValue: 'normal', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-duration': { + canOverride: canOverride.generic.time, + componentOf: [ + 'animation' + ], + defaultValue: '0s', + intoMultiplexMode: 'real', + keepUnlessDefault: 'animation-delay', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-fill-mode': { + canOverride: canOverride.property.animationFillMode, + componentOf: [ + 'animation' + ], + defaultValue: 'none', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-iteration-count': { + canOverride: canOverride.property.animationIterationCount, + componentOf: [ + 'animation' + ], + defaultValue: '1', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-name': { + canOverride: canOverride.property.animationName, + componentOf: [ + 'animation' + ], + defaultValue: 'none', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-play-state': { + canOverride: canOverride.property.animationPlayState, + componentOf: [ + 'animation' + ], + defaultValue: 'running', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'animation-timing-function': { + canOverride: canOverride.generic.timingFunction, + componentOf: [ + 'animation' + ], + defaultValue: 'ease', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'background': { + canOverride: canOverride.generic.components([ + canOverride.generic.image, + canOverride.property.backgroundPosition, + canOverride.property.backgroundSize, + canOverride.property.backgroundRepeat, + canOverride.property.backgroundAttachment, + canOverride.property.backgroundOrigin, + canOverride.property.backgroundClip, + canOverride.generic.color + ]), + components: [ + 'background-image', + 'background-position', + 'background-size', + 'background-repeat', + 'background-attachment', + 'background-origin', + 'background-clip', + 'background-color' + ], + breakUp: breakUp.multiplex(breakUp.background), + defaultValue: '0 0', + restore: restore.multiplex(restore.background), + shortestValue: '0', + shorthand: true + }, + 'background-attachment': { + canOverride: canOverride.property.backgroundAttachment, + componentOf: [ + 'background' + ], + defaultValue: 'scroll', + intoMultiplexMode: 'real' + }, + 'background-clip': { + canOverride: canOverride.property.backgroundClip, + componentOf: [ + 'background' + ], + defaultValue: 'border-box', + intoMultiplexMode: 'real', + shortestValue: 'border-box' + }, + 'background-color': { + canOverride: canOverride.generic.color, + componentOf: [ + 'background' + ], + defaultValue: 'transparent', + intoMultiplexMode: 'real', // otherwise real color will turn into default since color appears in last multiplex only + multiplexLastOnly: true, + nonMergeableValue: 'none', + shortestValue: 'red' + }, + 'background-image': { + canOverride: canOverride.generic.image, + componentOf: [ + 'background' + ], + defaultValue: 'none', + intoMultiplexMode: 'default' + }, + 'background-origin': { + canOverride: canOverride.property.backgroundOrigin, + componentOf: [ + 'background' + ], + defaultValue: 'padding-box', + intoMultiplexMode: 'real', + shortestValue: 'border-box' + }, + 'background-position': { + canOverride: canOverride.property.backgroundPosition, + componentOf: [ + 'background' + ], + defaultValue: ['0', '0'], + doubleValues: true, + intoMultiplexMode: 'real', + shortestValue: '0' + }, + 'background-repeat': { + canOverride: canOverride.property.backgroundRepeat, + componentOf: [ + 'background' + ], + defaultValue: ['repeat'], + doubleValues: true, + intoMultiplexMode: 'real' + }, + 'background-size': { + canOverride: canOverride.property.backgroundSize, + componentOf: [ + 'background' + ], + defaultValue: ['auto'], + doubleValues: true, + intoMultiplexMode: 'real', + shortestValue: '0 0' + }, + 'bottom': { + canOverride: canOverride.property.bottom, + defaultValue: 'auto' + }, + 'border': { + breakUp: breakUp.border, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.property.borderStyle, + canOverride.generic.color + ]), + components: [ + 'border-width', + 'border-style', + 'border-color' + ], + defaultValue: 'none', + overridesShorthands: [ + 'border-bottom', + 'border-left', + 'border-right', + 'border-top' + ], + restore: restore.withoutDefaults, + shorthand: true, + shorthandComponents: true + }, + 'border-bottom': { + breakUp: breakUp.border, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.property.borderStyle, + canOverride.generic.color + ]), + components: [ + 'border-bottom-width', + 'border-bottom-style', + 'border-bottom-color' + ], + defaultValue: 'none', + restore: restore.withoutDefaults, + shorthand: true + }, + 'border-bottom-color': { + canOverride: canOverride.generic.color, + componentOf: [ + 'border-bottom', + 'border-color' + ], + defaultValue: 'none' + }, + 'border-bottom-left-radius': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-radius' + ], + defaultValue: '0', + vendorPrefixes: [ + '-moz-', + '-o-' + ] + }, + 'border-bottom-right-radius': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-radius' + ], + defaultValue: '0', + vendorPrefixes: [ + '-moz-', + '-o-' + ] + }, + 'border-bottom-style': { + canOverride: canOverride.property.borderStyle, + componentOf: [ + 'border-bottom', + 'border-style' + ], + defaultValue: 'none' + }, + 'border-bottom-width': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-bottom', + 'border-width' + ], + defaultValue: 'medium', + oppositeTo: 'border-top-width', + shortestValue: '0' + }, + 'border-collapse': { + canOverride: canOverride.property.borderCollapse, + defaultValue: 'separate' + }, + 'border-color': { + breakUp: breakUp.fourValues, + canOverride: canOverride.generic.components([ + canOverride.generic.color, + canOverride.generic.color, + canOverride.generic.color, + canOverride.generic.color + ]), + componentOf: [ + 'border' + ], + components: [ + 'border-top-color', + 'border-right-color', + 'border-bottom-color', + 'border-left-color' + ], + defaultValue: 'none', + restore: restore.fourValues, + shortestValue: 'red', + shorthand: true + }, + 'border-left': { + breakUp: breakUp.border, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.property.borderStyle, + canOverride.generic.color + ]), + components: [ + 'border-left-width', + 'border-left-style', + 'border-left-color' + ], + defaultValue: 'none', + restore: restore.withoutDefaults, + shorthand: true + }, + 'border-left-color': { + canOverride: canOverride.generic.color, + componentOf: [ + 'border-color', + 'border-left' + ], + defaultValue: 'none' + }, + 'border-left-style': { + canOverride: canOverride.property.borderStyle, + componentOf: [ + 'border-left', + 'border-style' + ], + defaultValue: 'none' + }, + 'border-left-width': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-left', + 'border-width' + ], + defaultValue: 'medium', + oppositeTo: 'border-right-width', + shortestValue: '0' + }, + 'border-radius': { + breakUp: breakUp.borderRadius, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit + ]), + components: [ + 'border-top-left-radius', + 'border-top-right-radius', + 'border-bottom-right-radius', + 'border-bottom-left-radius' + ], + defaultValue: '0', + restore: restore.borderRadius, + shorthand: true, + vendorPrefixes: [ + '-moz-', + '-o-' + ] + }, + 'border-right': { + breakUp: breakUp.border, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.property.borderStyle, + canOverride.generic.color + ]), + components: [ + 'border-right-width', + 'border-right-style', + 'border-right-color' + ], + defaultValue: 'none', + restore: restore.withoutDefaults, + shorthand: true + }, + 'border-right-color': { + canOverride: canOverride.generic.color, + componentOf: [ + 'border-color', + 'border-right' + ], + defaultValue: 'none' + }, + 'border-right-style': { + canOverride: canOverride.property.borderStyle, + componentOf: [ + 'border-right', + 'border-style' + ], + defaultValue: 'none' + }, + 'border-right-width': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-right', + 'border-width' + ], + defaultValue: 'medium', + oppositeTo: 'border-left-width', + shortestValue: '0' + }, + 'border-style': { + breakUp: breakUp.fourValues, + canOverride: canOverride.generic.components([ + canOverride.property.borderStyle, + canOverride.property.borderStyle, + canOverride.property.borderStyle, + canOverride.property.borderStyle + ]), + componentOf: [ + 'border' + ], + components: [ + 'border-top-style', + 'border-right-style', + 'border-bottom-style', + 'border-left-style' + ], + defaultValue: 'none', + restore: restore.fourValues, + shorthand: true + }, + 'border-top': { + breakUp: breakUp.border, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.property.borderStyle, + canOverride.generic.color + ]), + components: [ + 'border-top-width', + 'border-top-style', + 'border-top-color' + ], + defaultValue: 'none', + restore: restore.withoutDefaults, + shorthand: true + }, + 'border-top-color': { + canOverride: canOverride.generic.color, + componentOf: [ + 'border-color', + 'border-top' + ], + defaultValue: 'none' + }, + 'border-top-left-radius': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-radius' + ], + defaultValue: '0', + vendorPrefixes: [ + '-moz-', + '-o-' + ] + }, + 'border-top-right-radius': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-radius' + ], + defaultValue: '0', + vendorPrefixes: [ + '-moz-', + '-o-' + ] + }, + 'border-top-style': { + canOverride: canOverride.property.borderStyle, + componentOf: [ + 'border-style', + 'border-top' + ], + defaultValue: 'none' + }, + 'border-top-width': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'border-top', + 'border-width' + ], + defaultValue: 'medium', + oppositeTo: 'border-bottom-width', + shortestValue: '0' + }, + 'border-width': { + breakUp: breakUp.fourValues, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit + ]), + componentOf: [ + 'border' + ], + components: [ + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width' + ], + defaultValue: 'medium', + restore: restore.fourValues, + shortestValue: '0', + shorthand: true + }, + 'clear': { + canOverride: canOverride.property.clear, + defaultValue: 'none' + }, + 'color': { + canOverride: canOverride.generic.color, + defaultValue: 'transparent', + shortestValue: 'red' + }, + 'cursor': { + canOverride: canOverride.property.cursor, + defaultValue: 'auto' + }, + 'display': { + canOverride: canOverride.property.display, + }, + 'float': { + canOverride: canOverride.property.float, + defaultValue: 'none' + }, + 'font': { + breakUp: breakUp.font, + canOverride: canOverride.generic.components([ + canOverride.property.fontStyle, + canOverride.property.fontVariant, + canOverride.property.fontWeight, + canOverride.property.fontStretch, + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.property.fontFamily + ]), + components: [ + 'font-style', + 'font-variant', + 'font-weight', + 'font-stretch', + 'font-size', + 'line-height', + 'font-family' + ], + restore: restore.font, + shorthand: true + }, + 'font-family': { + canOverride: canOverride.property.fontFamily, + defaultValue: 'user|agent|specific' + }, + 'font-size': { + canOverride: canOverride.generic.unit, + defaultValue: 'medium', + shortestValue: '0' + }, + 'font-stretch': { + canOverride: canOverride.property.fontStretch, + defaultValue: 'normal' + }, + 'font-style': { + canOverride: canOverride.property.fontStyle, + defaultValue: 'normal' + }, + 'font-variant': { + canOverride: canOverride.property.fontVariant, + defaultValue: 'normal' + }, + 'font-weight': { + canOverride: canOverride.property.fontWeight, + defaultValue: 'normal', + shortestValue: '400' + }, + 'height': { + canOverride: canOverride.generic.unit, + defaultValue: 'auto', + shortestValue: '0' + }, + 'left': { + canOverride: canOverride.property.left, + defaultValue: 'auto' + }, + 'line-height': { + canOverride: canOverride.generic.unitOrNumber, + defaultValue: 'normal', + shortestValue: '0' + }, + 'list-style': { + canOverride: canOverride.generic.components([ + canOverride.property.listStyleType, + canOverride.property.listStylePosition, + canOverride.property.listStyleImage + ]), + components: [ + 'list-style-type', + 'list-style-position', + 'list-style-image' + ], + breakUp: breakUp.listStyle, + restore: restore.withoutDefaults, + defaultValue: 'outside', // can't use 'disc' because that'd override default 'decimal' for
    + shortestValue: 'none', + shorthand: true + }, + 'list-style-image' : { + canOverride: canOverride.generic.image, + componentOf: [ + 'list-style' + ], + defaultValue: 'none' + }, + 'list-style-position' : { + canOverride: canOverride.property.listStylePosition, + componentOf: [ + 'list-style' + ], + defaultValue: 'outside', + shortestValue: 'inside' + }, + 'list-style-type' : { + canOverride: canOverride.property.listStyleType, + componentOf: [ + 'list-style' + ], + // NOTE: we can't tell the real default value here, it's 'disc' for
      and 'decimal' for
        + // this is a hack, but it doesn't matter because this value will be either overridden or + // it will disappear at the final step anyway + defaultValue: 'decimal|disc', + shortestValue: 'none' + }, + 'margin': { + breakUp: breakUp.fourValues, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit + ]), + components: [ + 'margin-top', + 'margin-right', + 'margin-bottom', + 'margin-left' + ], + defaultValue: '0', + restore: restore.fourValues, + shorthand: true + }, + 'margin-bottom': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'margin' + ], + defaultValue: '0', + oppositeTo: 'margin-top' + }, + 'margin-left': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'margin' + ], + defaultValue: '0', + oppositeTo: 'margin-right' + }, + 'margin-right': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'margin' + ], + defaultValue: '0', + oppositeTo: 'margin-left' + }, + 'margin-top': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'margin' + ], + defaultValue: '0', + oppositeTo: 'margin-bottom' + }, + 'outline': { + canOverride: canOverride.generic.components([ + canOverride.generic.color, + canOverride.property.outlineStyle, + canOverride.generic.unit + ]), + components: [ + 'outline-color', + 'outline-style', + 'outline-width' + ], + breakUp: breakUp.outline, + restore: restore.withoutDefaults, + defaultValue: '0', + shorthand: true + }, + 'outline-color': { + canOverride: canOverride.generic.color, + componentOf: [ + 'outline' + ], + defaultValue: 'invert', + shortestValue: 'red' + }, + 'outline-style': { + canOverride: canOverride.property.outlineStyle, + componentOf: [ + 'outline' + ], + defaultValue: 'none' + }, + 'outline-width': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'outline' + ], + defaultValue: 'medium', + shortestValue: '0' + }, + 'overflow': { + canOverride: canOverride.property.overflow, + defaultValue: 'visible' + }, + 'overflow-x': { + canOverride: canOverride.property.overflow, + defaultValue: 'visible' + }, + 'overflow-y': { + canOverride: canOverride.property.overflow, + defaultValue: 'visible' + }, + 'padding': { + breakUp: breakUp.fourValues, + canOverride: canOverride.generic.components([ + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit, + canOverride.generic.unit + ]), + components: [ + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left' + ], + defaultValue: '0', + restore: restore.fourValues, + shorthand: true + }, + 'padding-bottom': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'padding' + ], + defaultValue: '0', + oppositeTo: 'padding-top' + }, + 'padding-left': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'padding' + ], + defaultValue: '0', + oppositeTo: 'padding-right' + }, + 'padding-right': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'padding' + ], + defaultValue: '0', + oppositeTo: 'padding-left' + }, + 'padding-top': { + canOverride: canOverride.generic.unit, + componentOf: [ + 'padding' + ], + defaultValue: '0', + oppositeTo: 'padding-bottom' + }, + 'position': { + canOverride: canOverride.property.position, + defaultValue: 'static' + }, + 'right': { + canOverride: canOverride.property.right, + defaultValue: 'auto' + }, + 'text-align': { + canOverride: canOverride.property.textAlign, + // NOTE: we can't tell the real default value here, as it depends on default text direction + // this is a hack, but it doesn't matter because this value will be either overridden or + // it will disappear anyway + defaultValue: 'left|right' + }, + 'text-decoration': { + canOverride: canOverride.property.textDecoration, + defaultValue: 'none' + }, + 'text-overflow': { + canOverride: canOverride.property.textOverflow, + defaultValue: 'none' + }, + 'text-shadow': { + canOverride: canOverride.property.textShadow, + defaultValue: 'none' + }, + 'top': { + canOverride: canOverride.property.top, + defaultValue: 'auto' + }, + 'transform': { + canOverride: canOverride.property.transform, + vendorPrefixes: [ + '-moz-', + '-ms-', + '-webkit-' + ] + }, + 'transition': { + breakUp: breakUp.multiplex(breakUp.transition), + canOverride: canOverride.generic.components([ + canOverride.property.transitionProperty, + canOverride.generic.time, + canOverride.generic.timingFunction, + canOverride.generic.time + ]), + components: [ + 'transition-property', + 'transition-duration', + 'transition-timing-function', + 'transition-delay' + ], + defaultValue: 'none', + restore: restore.multiplex(restore.withoutDefaults), + shorthand: true, + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'transition-delay': { + canOverride: canOverride.generic.time, + componentOf: [ + 'transition' + ], + defaultValue: '0s', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'transition-duration': { + canOverride: canOverride.generic.time, + componentOf: [ + 'transition' + ], + defaultValue: '0s', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'transition-property': { + canOverride: canOverride.generic.propertyName, + componentOf: [ + 'transition' + ], + defaultValue: 'all', + intoMultiplexMode: 'placeholder', + placeholderValue: '_', // it's a short value that won't match any property and still be a valid `transition-property` + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'transition-timing-function': { + canOverride: canOverride.generic.timingFunction, + componentOf: [ + 'transition' + ], + defaultValue: 'ease', + intoMultiplexMode: 'real', + vendorPrefixes: [ + '-moz-', + '-o-', + '-webkit-' + ] + }, + 'vertical-align': { + canOverride: canOverride.property.verticalAlign, + defaultValue: 'baseline' + }, + 'visibility': { + canOverride: canOverride.property.visibility, + defaultValue: 'visible' + }, + 'white-space': { + canOverride: canOverride.property.whiteSpace, + defaultValue: 'normal' + }, + 'width': { + canOverride: canOverride.generic.unit, + defaultValue: 'auto', + shortestValue: '0' + }, + 'z-index': { + canOverride: canOverride.property.zIndex, + defaultValue: 'auto' + } +}; + +function cloneDescriptor(propertyName, prefix) { + var clonedDescriptor = override(compactable[propertyName], {}); + + if ('componentOf' in clonedDescriptor) { + clonedDescriptor.componentOf = clonedDescriptor.componentOf.map(function (shorthandName) { + return prefix + shorthandName; + }); + } + + if ('components' in clonedDescriptor) { + clonedDescriptor.components = clonedDescriptor.components.map(function (longhandName) { + return prefix + longhandName; + }); + } + + if ('keepUnlessDefault' in clonedDescriptor) { + clonedDescriptor.keepUnlessDefault = prefix + clonedDescriptor.keepUnlessDefault; + } + + return clonedDescriptor; +} + +// generate vendor-prefixed properties +var vendorPrefixedCompactable = {}; + +for (var propertyName in compactable) { + var descriptor = compactable[propertyName]; + + if (!('vendorPrefixes' in descriptor)) { + continue; + } + + for (var i = 0; i < descriptor.vendorPrefixes.length; i++) { + var prefix = descriptor.vendorPrefixes[i]; + var clonedDescriptor = cloneDescriptor(propertyName, prefix); + delete clonedDescriptor.vendorPrefixes; + + vendorPrefixedCompactable[prefix + propertyName] = clonedDescriptor; + } + + delete descriptor.vendorPrefixes; +} + +module.exports = override(compactable, vendorPrefixedCompactable); diff --git a/node_modules/clean-css/lib/optimizer/level-2/extract-properties.js b/node_modules/clean-css/lib/optimizer/level-2/extract-properties.js new file mode 100644 index 0000000..8b9b1c2 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/extract-properties.js @@ -0,0 +1,73 @@ +// This extractor is used in level 2 optimizations +// IMPORTANT: Mind Token class and this code is not related! +// Properties will be tokenized in one step, see #429 + +var Token = require('../../tokenizer/token'); +var serializeRules = require('../../writer/one-time').rules; +var serializeValue = require('../../writer/one-time').value; + +function extractProperties(token) { + var properties = []; + var inSpecificSelector; + var property; + var name; + var value; + var i, l; + + if (token[0] == Token.RULE) { + inSpecificSelector = !/[\.\+>~]/.test(serializeRules(token[1])); + + for (i = 0, l = token[2].length; i < l; i++) { + property = token[2][i]; + + if (property[0] != Token.PROPERTY) + continue; + + name = property[1][1]; + if (name.length === 0) + continue; + + if (name.indexOf('--') === 0) + continue; + + value = serializeValue(property, i); + + properties.push([ + name, + value, + findNameRoot(name), + token[2][i], + name + ':' + value, + token[1], + inSpecificSelector + ]); + } + } else if (token[0] == Token.NESTED_BLOCK) { + for (i = 0, l = token[2].length; i < l; i++) { + properties = properties.concat(extractProperties(token[2][i])); + } + } + + return properties; +} + +function findNameRoot(name) { + if (name == 'list-style') + return name; + if (name.indexOf('-radius') > 0) + return 'border-radius'; + if (name == 'border-collapse' || name == 'border-spacing' || name == 'border-image') + return name; + if (name.indexOf('border-') === 0 && /^border\-\w+\-\w+$/.test(name)) + return name.match(/border\-\w+/)[0]; + if (name.indexOf('border-') === 0 && /^border\-\w+$/.test(name)) + return 'border'; + if (name.indexOf('text-') === 0) + return name; + if (name == '-chrome-') + return name; + + return name.replace(/^\-\w+\-/, '').match(/([a-zA-Z]+)/)[0].toLowerCase(); +} + +module.exports = extractProperties; diff --git a/node_modules/clean-css/lib/optimizer/level-2/invalid-property-error.js b/node_modules/clean-css/lib/optimizer/level-2/invalid-property-error.js new file mode 100644 index 0000000..86d5b5f --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/invalid-property-error.js @@ -0,0 +1,10 @@ +function InvalidPropertyError(message) { + this.name = 'InvalidPropertyError'; + this.message = message; + this.stack = (new Error()).stack; +} + +InvalidPropertyError.prototype = Object.create(Error.prototype); +InvalidPropertyError.prototype.constructor = InvalidPropertyError; + +module.exports = InvalidPropertyError; diff --git a/node_modules/clean-css/lib/optimizer/level-2/is-mergeable.js b/node_modules/clean-css/lib/optimizer/level-2/is-mergeable.js new file mode 100644 index 0000000..2904930 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/is-mergeable.js @@ -0,0 +1,259 @@ +var Marker = require('../../tokenizer/marker'); +var split = require('../../utils/split'); + +var DEEP_SELECTOR_PATTERN = /\/deep\//; +var DOUBLE_COLON_PATTERN = /^::/; +var NOT_PSEUDO = ':not'; +var PSEUDO_CLASSES_WITH_ARGUMENTS = [ + ':dir', + ':lang', + ':not', + ':nth-child', + ':nth-last-child', + ':nth-last-of-type', + ':nth-of-type' +]; +var RELATION_PATTERN = /[>\+~]/; +var UNMIXABLE_PSEUDO_CLASSES = [ + ':after', + ':before', + ':first-letter', + ':first-line', + ':lang' +]; +var UNMIXABLE_PSEUDO_ELEMENTS = [ + '::after', + '::before', + '::first-letter', + '::first-line' +]; + +var Level = { + DOUBLE_QUOTE: 'double-quote', + SINGLE_QUOTE: 'single-quote', + ROOT: 'root' +}; + +function isMergeable(selector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) { + var singleSelectors = split(selector, Marker.COMMA); + var singleSelector; + var i, l; + + for (i = 0, l = singleSelectors.length; i < l; i++) { + singleSelector = singleSelectors[i]; + + if (singleSelector.length === 0 || + isDeepSelector(singleSelector) || + (singleSelector.indexOf(Marker.COLON) > -1 && !areMergeable(singleSelector, extractPseudoFrom(singleSelector), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging))) { + return false; + } + } + + return true; +} + +function isDeepSelector(selector) { + return DEEP_SELECTOR_PATTERN.test(selector); +} + +function extractPseudoFrom(selector) { + var list = []; + var character; + var buffer = []; + var level = Level.ROOT; + var roundBracketLevel = 0; + var isQuoted; + var isEscaped; + var isPseudo = false; + var isRelation; + var wasColon = false; + var index; + var len; + + for (index = 0, len = selector.length; index < len; index++) { + character = selector[index]; + + isRelation = !isEscaped && RELATION_PATTERN.test(character); + isQuoted = level == Level.DOUBLE_QUOTE || level == Level.SINGLE_QUOTE; + + if (isEscaped) { + buffer.push(character); + } else if (character == Marker.DOUBLE_QUOTE && level == Level.ROOT) { + buffer.push(character); + level = Level.DOUBLE_QUOTE; + } else if (character == Marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) { + buffer.push(character); + level = Level.ROOT; + } else if (character == Marker.SINGLE_QUOTE && level == Level.ROOT) { + buffer.push(character); + level = Level.SINGLE_QUOTE; + } else if (character == Marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) { + buffer.push(character); + level = Level.ROOT; + } else if (isQuoted) { + buffer.push(character); + } else if (character == Marker.OPEN_ROUND_BRACKET) { + buffer.push(character); + roundBracketLevel++; + } else if (character == Marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1 && isPseudo) { + buffer.push(character); + list.push(buffer.join('')); + roundBracketLevel--; + buffer = []; + isPseudo = false; + } else if (character == Marker.CLOSE_ROUND_BRACKET) { + buffer.push(character); + roundBracketLevel--; + } else if (character == Marker.COLON && roundBracketLevel === 0 && isPseudo && !wasColon) { + list.push(buffer.join('')); + buffer = []; + buffer.push(character); + } else if (character == Marker.COLON && roundBracketLevel === 0 && !wasColon) { + buffer = []; + buffer.push(character); + isPseudo = true; + } else if (character == Marker.SPACE && roundBracketLevel === 0 && isPseudo) { + list.push(buffer.join('')); + buffer = []; + isPseudo = false; + } else if (isRelation && roundBracketLevel === 0 && isPseudo) { + list.push(buffer.join('')); + buffer = []; + isPseudo = false; + } else { + buffer.push(character); + } + + isEscaped = character == Marker.BACK_SLASH; + wasColon = character == Marker.COLON; + } + + if (buffer.length > 0 && isPseudo) { + list.push(buffer.join('')); + } + + return list; +} + +function areMergeable(selector, matches, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) { + return areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) && + needArguments(matches) && + (matches.length < 2 || !someIncorrectlyChained(selector, matches)) && + (matches.length < 2 || multiplePseudoMerging && allMixable(matches)); +} + +function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) { + var match; + var name; + var i, l; + + for (i = 0, l = matches.length; i < l; i++) { + match = matches[i]; + name = match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ? + match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET)) : + match; + + if (mergeablePseudoClasses.indexOf(name) === -1 && mergeablePseudoElements.indexOf(name) === -1) { + return false; + } + } + + return true; +} + +function needArguments(matches) { + var match; + var name; + var bracketOpensAt; + var hasArguments; + var i, l; + + for (i = 0, l = matches.length; i < l; i++) { + match = matches[i]; + + bracketOpensAt = match.indexOf(Marker.OPEN_ROUND_BRACKET); + hasArguments = bracketOpensAt > -1; + name = hasArguments ? + match.substring(0, bracketOpensAt) : + match; + + if (hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) == -1) { + return false; + } + + if (!hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) > -1) { + return false; + } + } + + return true; +} + +function someIncorrectlyChained(selector, matches) { + var positionInSelector = 0; + var match; + var matchAt; + var nextMatch; + var nextMatchAt; + var name; + var nextName; + var areChained; + var i, l; + + for (i = 0, l = matches.length; i < l; i++) { + match = matches[i]; + nextMatch = matches[i + 1]; + + if (!nextMatch) { + break; + } + + matchAt = selector.indexOf(match, positionInSelector); + nextMatchAt = selector.indexOf(match, matchAt + 1); + positionInSelector = nextMatchAt; + areChained = matchAt + match.length == nextMatchAt; + + if (areChained) { + name = match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ? + match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET)) : + match; + nextName = nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ? + nextMatch.substring(0, nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET)) : + nextMatch; + + if (name != NOT_PSEUDO || nextName != NOT_PSEUDO) { + return true; + } + } + } + + return false; +} + +function allMixable(matches) { + var unmixableMatches = 0; + var match; + var i, l; + + for (i = 0, l = matches.length; i < l; i++) { + match = matches[i]; + + if (isPseudoElement(match)) { + unmixableMatches += UNMIXABLE_PSEUDO_ELEMENTS.indexOf(match) > -1 ? 1 : 0; + } else { + unmixableMatches += UNMIXABLE_PSEUDO_CLASSES.indexOf(match) > -1 ? 1 : 0; + } + + if (unmixableMatches > 1) { + return false; + } + } + + return true; +} + +function isPseudoElement(pseudo) { + return DOUBLE_COLON_PATTERN.test(pseudo); +} + +module.exports = isMergeable; diff --git a/node_modules/clean-css/lib/optimizer/level-2/merge-adjacent.js b/node_modules/clean-css/lib/optimizer/level-2/merge-adjacent.js new file mode 100644 index 0000000..b148bac --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/merge-adjacent.js @@ -0,0 +1,50 @@ +var isMergeable = require('./is-mergeable'); + +var optimizeProperties = require('./properties/optimize'); + +var sortSelectors = require('../level-1/sort-selectors'); +var tidyRules = require('../level-1/tidy-rules'); + +var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel; + +var serializeBody = require('../../writer/one-time').body; +var serializeRules = require('../../writer/one-time').rules; + +var Token = require('../../tokenizer/token'); + +function mergeAdjacent(tokens, context) { + var lastToken = [null, [], []]; + var options = context.options; + var adjacentSpace = options.compatibility.selectors.adjacentSpace; + var selectorsSortingMethod = options.level[OptimizationLevel.One].selectorsSortingMethod; + var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; + var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; + var mergeLimit = options.compatibility.selectors.mergeLimit; + var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + if (token[0] != Token.RULE) { + lastToken = [null, [], []]; + continue; + } + + if (lastToken[0] == Token.RULE && serializeRules(token[1]) == serializeRules(lastToken[1])) { + Array.prototype.push.apply(lastToken[2], token[2]); + optimizeProperties(lastToken[2], true, true, context); + token[2] = []; + } else if (lastToken[0] == Token.RULE && serializeBody(token[2]) == serializeBody(lastToken[2]) && + isMergeable(serializeRules(token[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) && + isMergeable(serializeRules(lastToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) && + lastToken[1].length < mergeLimit) { + lastToken[1] = tidyRules(lastToken[1].concat(token[1]), false, adjacentSpace, false, context.warnings); + lastToken[1] = lastToken.length > 1 ? sortSelectors(lastToken[1], selectorsSortingMethod) : lastToken[1]; + token[2] = []; + } else { + lastToken = token; + } + } +} + +module.exports = mergeAdjacent; diff --git a/node_modules/clean-css/lib/optimizer/level-2/merge-media-queries.js b/node_modules/clean-css/lib/optimizer/level-2/merge-media-queries.js new file mode 100644 index 0000000..c3c60dc --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/merge-media-queries.js @@ -0,0 +1,103 @@ +var canReorder = require('./reorderable').canReorder; +var canReorderSingle = require('./reorderable').canReorderSingle; +var extractProperties = require('./extract-properties'); +var rulesOverlap = require('./rules-overlap'); + +var serializeRules = require('../../writer/one-time').rules; +var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel; +var Token = require('../../tokenizer/token'); + +function mergeMediaQueries(tokens, context) { + var mergeSemantically = context.options.level[OptimizationLevel.Two].mergeSemantically; + var specificityCache = context.cache.specificity; + var candidates = {}; + var reduced = []; + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + if (token[0] != Token.NESTED_BLOCK) { + continue; + } + + var key = serializeRules(token[1]); + var candidate = candidates[key]; + if (!candidate) { + candidate = []; + candidates[key] = candidate; + } + + candidate.push(i); + } + + for (var name in candidates) { + var positions = candidates[name]; + + positionLoop: + for (var j = positions.length - 1; j > 0; j--) { + var positionOne = positions[j]; + var tokenOne = tokens[positionOne]; + var positionTwo = positions[j - 1]; + var tokenTwo = tokens[positionTwo]; + + directionLoop: + for (var direction = 1; direction >= -1; direction -= 2) { + var topToBottom = direction == 1; + var from = topToBottom ? positionOne + 1 : positionTwo - 1; + var to = topToBottom ? positionTwo : positionOne; + var delta = topToBottom ? 1 : -1; + var source = topToBottom ? tokenOne : tokenTwo; + var target = topToBottom ? tokenTwo : tokenOne; + var movedProperties = extractProperties(source); + + while (from != to) { + var traversedProperties = extractProperties(tokens[from]); + from += delta; + + if (mergeSemantically && allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache)) { + continue; + } + + if (!canReorder(movedProperties, traversedProperties, specificityCache)) + continue directionLoop; + } + + target[2] = topToBottom ? + source[2].concat(target[2]) : + target[2].concat(source[2]); + source[2] = []; + + reduced.push(target); + continue positionLoop; + } + } + } + + return reduced; +} + +function allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache) { + var movedProperty; + var movedRule; + var traversedProperty; + var traversedRule; + var i, l; + var j, m; + + for (i = 0, l = movedProperties.length; i < l; i++) { + movedProperty = movedProperties[i]; + movedRule = movedProperty[5]; + + for (j = 0, m = traversedProperties.length; j < m; j++) { + traversedProperty = traversedProperties[j]; + traversedRule = traversedProperty[5]; + + if (rulesOverlap(movedRule, traversedRule, true) && !canReorderSingle(movedProperty, traversedProperty, specificityCache)) { + return false; + } + } + } + + return true; +} + +module.exports = mergeMediaQueries; diff --git a/node_modules/clean-css/lib/optimizer/level-2/merge-non-adjacent-by-body.js b/node_modules/clean-css/lib/optimizer/level-2/merge-non-adjacent-by-body.js new file mode 100644 index 0000000..82db950 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/merge-non-adjacent-by-body.js @@ -0,0 +1,80 @@ +var isMergeable = require('./is-mergeable'); + +var sortSelectors = require('../level-1/sort-selectors'); +var tidyRules = require('../level-1/tidy-rules'); + +var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel; + +var serializeBody = require('../../writer/one-time').body; +var serializeRules = require('../../writer/one-time').rules; + +var Token = require('../../tokenizer/token'); + +function unsafeSelector(value) { + return /\.|\*| :/.test(value); +} + +function isBemElement(token) { + var asString = serializeRules(token[1]); + return asString.indexOf('__') > -1 || asString.indexOf('--') > -1; +} + +function withoutModifier(selector) { + return selector.replace(/--[^ ,>\+~:]+/g, ''); +} + +function removeAnyUnsafeElements(left, candidates) { + var leftSelector = withoutModifier(serializeRules(left[1])); + + for (var body in candidates) { + var right = candidates[body]; + var rightSelector = withoutModifier(serializeRules(right[1])); + + if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1) + delete candidates[body]; + } +} + +function mergeNonAdjacentByBody(tokens, context) { + var options = context.options; + var mergeSemantically = options.level[OptimizationLevel.Two].mergeSemantically; + var adjacentSpace = options.compatibility.selectors.adjacentSpace; + var selectorsSortingMethod = options.level[OptimizationLevel.One].selectorsSortingMethod; + var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; + var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; + var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; + var candidates = {}; + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + if (token[0] != Token.RULE) + continue; + + if (token[2].length > 0 && (!mergeSemantically && unsafeSelector(serializeRules(token[1])))) + candidates = {}; + + if (token[2].length > 0 && mergeSemantically && isBemElement(token)) + removeAnyUnsafeElements(token, candidates); + + var candidateBody = serializeBody(token[2]); + var oldToken = candidates[candidateBody]; + if (oldToken && + isMergeable(serializeRules(token[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) && + isMergeable(serializeRules(oldToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) { + + if (token[2].length > 0) { + token[1] = tidyRules(oldToken[1].concat(token[1]), false, adjacentSpace, false, context.warnings); + token[1] = token[1].length > 1 ? sortSelectors(token[1], selectorsSortingMethod) : token[1]; + } else { + token[1] = oldToken[1].concat(token[1]); + } + + oldToken[2] = []; + candidates[candidateBody] = null; + } + + candidates[serializeBody(token[2])] = token; + } +} + +module.exports = mergeNonAdjacentByBody; diff --git a/node_modules/clean-css/lib/optimizer/level-2/merge-non-adjacent-by-selector.js b/node_modules/clean-css/lib/optimizer/level-2/merge-non-adjacent-by-selector.js new file mode 100644 index 0000000..5e23064 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/merge-non-adjacent-by-selector.js @@ -0,0 +1,78 @@ +var canReorder = require('./reorderable').canReorder; +var extractProperties = require('./extract-properties'); + +var optimizeProperties = require('./properties/optimize'); + +var serializeRules = require('../../writer/one-time').rules; + +var Token = require('../../tokenizer/token'); + +function mergeNonAdjacentBySelector(tokens, context) { + var specificityCache = context.cache.specificity; + var allSelectors = {}; + var repeatedSelectors = []; + var i; + + for (i = tokens.length - 1; i >= 0; i--) { + if (tokens[i][0] != Token.RULE) + continue; + if (tokens[i][2].length === 0) + continue; + + var selector = serializeRules(tokens[i][1]); + allSelectors[selector] = [i].concat(allSelectors[selector] || []); + + if (allSelectors[selector].length == 2) + repeatedSelectors.push(selector); + } + + for (i = repeatedSelectors.length - 1; i >= 0; i--) { + var positions = allSelectors[repeatedSelectors[i]]; + + selectorIterator: + for (var j = positions.length - 1; j > 0; j--) { + var positionOne = positions[j - 1]; + var tokenOne = tokens[positionOne]; + var positionTwo = positions[j]; + var tokenTwo = tokens[positionTwo]; + + directionIterator: + for (var direction = 1; direction >= -1; direction -= 2) { + var topToBottom = direction == 1; + var from = topToBottom ? positionOne + 1 : positionTwo - 1; + var to = topToBottom ? positionTwo : positionOne; + var delta = topToBottom ? 1 : -1; + var moved = topToBottom ? tokenOne : tokenTwo; + var target = topToBottom ? tokenTwo : tokenOne; + var movedProperties = extractProperties(moved); + + while (from != to) { + var traversedProperties = extractProperties(tokens[from]); + from += delta; + + // traversed then moved as we move selectors towards the start + var reorderable = topToBottom ? + canReorder(movedProperties, traversedProperties, specificityCache) : + canReorder(traversedProperties, movedProperties, specificityCache); + + if (!reorderable && !topToBottom) + continue selectorIterator; + if (!reorderable && topToBottom) + continue directionIterator; + } + + if (topToBottom) { + Array.prototype.push.apply(moved[2], target[2]); + target[2] = moved[2]; + } else { + Array.prototype.push.apply(target[2], moved[2]); + } + + optimizeProperties(target[2], true, true, context); + moved[2] = []; + } + } + } +} + +module.exports = mergeNonAdjacentBySelector; diff --git a/node_modules/clean-css/lib/optimizer/level-2/optimize.js b/node_modules/clean-css/lib/optimizer/level-2/optimize.js new file mode 100644 index 0000000..9be961d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/optimize.js @@ -0,0 +1,134 @@ +var mergeAdjacent = require('./merge-adjacent'); +var mergeMediaQueries = require('./merge-media-queries'); +var mergeNonAdjacentByBody = require('./merge-non-adjacent-by-body'); +var mergeNonAdjacentBySelector = require('./merge-non-adjacent-by-selector'); +var reduceNonAdjacent = require('./reduce-non-adjacent'); +var removeDuplicateFontAtRules = require('./remove-duplicate-font-at-rules'); +var removeDuplicateMediaQueries = require('./remove-duplicate-media-queries'); +var removeDuplicates = require('./remove-duplicates'); +var removeUnusedAtRules = require('./remove-unused-at-rules'); +var restructure = require('./restructure'); + +var optimizeProperties = require('./properties/optimize'); + +var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel; + +var Token = require('../../tokenizer/token'); + +function removeEmpty(tokens) { + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + var isEmpty = false; + + switch (token[0]) { + case Token.RULE: + isEmpty = token[1].length === 0 || token[2].length === 0; + break; + case Token.NESTED_BLOCK: + removeEmpty(token[2]); + isEmpty = token[2].length === 0; + break; + case Token.AT_RULE: + isEmpty = token[1].length === 0; + break; + case Token.AT_RULE_BLOCK: + isEmpty = token[2].length === 0; + } + + if (isEmpty) { + tokens.splice(i, 1); + i--; + l--; + } + } +} + +function recursivelyOptimizeBlocks(tokens, context) { + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + if (token[0] == Token.NESTED_BLOCK) { + var isKeyframes = /@(-moz-|-o-|-webkit-)?keyframes/.test(token[1][0][1]); + level2Optimize(token[2], context, !isKeyframes); + } + } +} + +function recursivelyOptimizeProperties(tokens, context) { + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + switch (token[0]) { + case Token.RULE: + optimizeProperties(token[2], true, true, context); + break; + case Token.NESTED_BLOCK: + recursivelyOptimizeProperties(token[2], context); + } + } +} + +function level2Optimize(tokens, context, withRestructuring) { + var levelOptions = context.options.level[OptimizationLevel.Two]; + var reduced; + var i; + + recursivelyOptimizeBlocks(tokens, context); + recursivelyOptimizeProperties(tokens, context); + + if (levelOptions.removeDuplicateRules) { + removeDuplicates(tokens, context); + } + + if (levelOptions.mergeAdjacentRules) { + mergeAdjacent(tokens, context); + } + + if (levelOptions.reduceNonAdjacentRules) { + reduceNonAdjacent(tokens, context); + } + + if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'body') { + mergeNonAdjacentBySelector(tokens, context); + } + + if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'selector') { + mergeNonAdjacentByBody(tokens, context); + } + + if (levelOptions.restructureRules && levelOptions.mergeAdjacentRules && withRestructuring) { + restructure(tokens, context); + mergeAdjacent(tokens, context); + } + + if (levelOptions.restructureRules && !levelOptions.mergeAdjacentRules && withRestructuring) { + restructure(tokens, context); + } + + if (levelOptions.removeDuplicateFontRules) { + removeDuplicateFontAtRules(tokens, context); + } + + if (levelOptions.removeDuplicateMediaBlocks) { + removeDuplicateMediaQueries(tokens, context); + } + + if (levelOptions.removeUnusedAtRules) { + removeUnusedAtRules(tokens, context); + } + + if (levelOptions.mergeMedia) { + reduced = mergeMediaQueries(tokens, context); + for (i = reduced.length - 1; i >= 0; i--) { + level2Optimize(reduced[i][2], context, false); + } + } + + if (levelOptions.removeEmpty) { + removeEmpty(tokens); + } + + return tokens; +} + +module.exports = level2Optimize; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/every-values-pair.js b/node_modules/clean-css/lib/optimizer/level-2/properties/every-values-pair.js new file mode 100644 index 0000000..44fcb7d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/every-values-pair.js @@ -0,0 +1,28 @@ +var Marker = require('../../../tokenizer/marker'); + +function everyValuesPair(fn, left, right) { + var leftSize = left.value.length; + var rightSize = right.value.length; + var total = Math.max(leftSize, rightSize); + var lowerBound = Math.min(leftSize, rightSize) - 1; + var leftValue; + var rightValue; + var position; + + for (position = 0; position < total; position++) { + leftValue = left.value[position] && left.value[position][1] || leftValue; + rightValue = right.value[position] && right.value[position][1] || rightValue; + + if (leftValue == Marker.COMMA || rightValue == Marker.COMMA) { + continue; + } + + if (!fn(leftValue, rightValue, position, position <= lowerBound)) { + return false; + } + } + + return true; +} + +module.exports = everyValuesPair; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/find-component-in.js b/node_modules/clean-css/lib/optimizer/level-2/properties/find-component-in.js new file mode 100644 index 0000000..dd7c719 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/find-component-in.js @@ -0,0 +1,40 @@ +var compactable = require('../compactable'); + +function findComponentIn(shorthand, longhand) { + var comparator = nameComparator(longhand); + + return findInDirectComponents(shorthand, comparator) || findInSubComponents(shorthand, comparator); +} + +function nameComparator(to) { + return function (property) { + return to.name === property.name; + }; +} + +function findInDirectComponents(shorthand, comparator) { + return shorthand.components.filter(comparator)[0]; +} + +function findInSubComponents(shorthand, comparator) { + var shorthandComponent; + var longhandMatch; + var i, l; + + if (!compactable[shorthand.name].shorthandComponents) { + return; + } + + for (i = 0, l = shorthand.components.length; i < l; i++) { + shorthandComponent = shorthand.components[i]; + longhandMatch = findInDirectComponents(shorthandComponent, comparator); + + if (longhandMatch) { + return longhandMatch; + } + } + + return; +} + +module.exports = findComponentIn; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/has-inherit.js b/node_modules/clean-css/lib/optimizer/level-2/properties/has-inherit.js new file mode 100644 index 0000000..84f220d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/has-inherit.js @@ -0,0 +1,10 @@ +function hasInherit(property) { + for (var i = property.value.length - 1; i >= 0; i--) { + if (property.value[i][1] == 'inherit') + return true; + } + + return false; +} + +module.exports = hasInherit; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/is-component-of.js b/node_modules/clean-css/lib/optimizer/level-2/properties/is-component-of.js new file mode 100644 index 0000000..237de7d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/is-component-of.js @@ -0,0 +1,22 @@ +var compactable = require('../compactable'); + +function isComponentOf(property1, property2, shallow) { + return isDirectComponentOf(property1, property2) || + !shallow && !!compactable[property1.name].shorthandComponents && isSubComponentOf(property1, property2); +} + +function isDirectComponentOf(property1, property2) { + var descriptor = compactable[property1.name]; + + return 'components' in descriptor && descriptor.components.indexOf(property2.name) > -1; +} + +function isSubComponentOf(property1, property2) { + return property1 + .components + .some(function (component) { + return isDirectComponentOf(component, property2); + }); +} + +module.exports = isComponentOf; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/is-mergeable-shorthand.js b/node_modules/clean-css/lib/optimizer/level-2/properties/is-mergeable-shorthand.js new file mode 100644 index 0000000..ee7191e --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/is-mergeable-shorthand.js @@ -0,0 +1,11 @@ +var Marker = require('../../../tokenizer/marker'); + +function isMergeableShorthand(shorthand) { + if (shorthand.name != 'font') { + return true; + } + + return shorthand.value[0][1].indexOf(Marker.INTERNAL) == -1; +} + +module.exports = isMergeableShorthand; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/merge-into-shorthands.js b/node_modules/clean-css/lib/optimizer/level-2/properties/merge-into-shorthands.js new file mode 100644 index 0000000..bcfeeb6 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/merge-into-shorthands.js @@ -0,0 +1,445 @@ +var everyValuesPair = require('./every-values-pair'); +var hasInherit = require('./has-inherit'); +var populateComponents = require('./populate-components'); + +var compactable = require('../compactable'); +var deepClone = require('../clone').deep; +var restoreWithComponents = require('../restore-with-components'); + +var restoreFromOptimizing = require('../../restore-from-optimizing'); +var wrapSingle = require('../../wrap-for-optimizing').single; + +var serializeBody = require('../../../writer/one-time').body; +var Token = require('../../../tokenizer/token'); + +function mergeIntoShorthands(properties, validator) { + var candidates = {}; + var descriptor; + var componentOf; + var property; + var i, l; + var j, m; + + // there is no shorthand property made up of less than 3 longhands + if (properties.length < 3) { + return; + } + + for (i = 0, l = properties.length; i < l; i++) { + property = properties[i]; + descriptor = compactable[property.name]; + + if (property.unused) { + continue; + } + + if (property.hack) { + continue; + } + + if (property.block) { + continue; + } + + invalidateOrCompact(properties, i, candidates, validator); + + if (descriptor && descriptor.componentOf) { + for (j = 0, m = descriptor.componentOf.length; j < m; j++) { + componentOf = descriptor.componentOf[j]; + + candidates[componentOf] = candidates[componentOf] || {}; + candidates[componentOf][property.name] = property; + } + } + } + + invalidateOrCompact(properties, i, candidates, validator); +} + +function invalidateOrCompact(properties, position, candidates, validator) { + var invalidatedBy = properties[position]; + var shorthandName; + var shorthandDescriptor; + var candidateComponents; + + for (shorthandName in candidates) { + if (undefined !== invalidatedBy && shorthandName == invalidatedBy.name) { + continue; + } + + shorthandDescriptor = compactable[shorthandName]; + candidateComponents = candidates[shorthandName]; + if (invalidatedBy && invalidates(candidates, shorthandName, invalidatedBy)) { + delete candidates[shorthandName]; + continue; + } + + if (shorthandDescriptor.components.length > Object.keys(candidateComponents).length) { + continue; + } + + if (mixedImportance(candidateComponents)) { + continue; + } + + if (!overridable(candidateComponents, shorthandName, validator)) { + continue; + } + + if (!mergeable(candidateComponents)) { + continue; + } + + if (mixedInherit(candidateComponents)) { + replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator); + } else { + replaceWithShorthand(properties, candidateComponents, shorthandName, validator); + } + } +} + +function invalidates(candidates, shorthandName, invalidatedBy) { + var shorthandDescriptor = compactable[shorthandName]; + var invalidatedByDescriptor = compactable[invalidatedBy.name]; + var componentName; + + if ('overridesShorthands' in shorthandDescriptor && shorthandDescriptor.overridesShorthands.indexOf(invalidatedBy.name) > -1) { + return true; + } + + if (invalidatedByDescriptor && 'componentOf' in invalidatedByDescriptor) { + for (componentName in candidates[shorthandName]) { + if (invalidatedByDescriptor.componentOf.indexOf(componentName) > -1) { + return true; + } + } + } + + return false; +} + +function mixedImportance(components) { + var important; + var componentName; + + for (componentName in components) { + if (undefined !== important && components[componentName].important != important) { + return true; + } + + important = components[componentName].important; + } + + return false; +} + +function overridable(components, shorthandName, validator) { + var descriptor = compactable[shorthandName]; + var newValuePlaceholder = [ + Token.PROPERTY, + [Token.PROPERTY_NAME, shorthandName], + [Token.PROPERTY_VALUE, descriptor.defaultValue] + ]; + var newProperty = wrapSingle(newValuePlaceholder); + var component; + var mayOverride; + var i, l; + + populateComponents([newProperty], validator, []); + + for (i = 0, l = descriptor.components.length; i < l; i++) { + component = components[descriptor.components[i]]; + mayOverride = compactable[component.name].canOverride; + + if (!everyValuesPair(mayOverride.bind(null, validator), newProperty.components[i], component)) { + return false; + } + } + + return true; +} + +function mergeable(components) { + var lastCount = null; + var currentCount; + var componentName; + var component; + var descriptor; + var values; + + for (componentName in components) { + component = components[componentName]; + descriptor = compactable[componentName]; + + if (!('restore' in descriptor)) { + continue; + } + + restoreFromOptimizing([component.all[component.position]], restoreWithComponents); + values = descriptor.restore(component, compactable); + + currentCount = values.length; + + if (lastCount !== null && currentCount !== lastCount) { + return false; + } + + lastCount = currentCount; + } + + return true; +} + +function mixedInherit(components) { + var componentName; + var lastValue = null; + var currentValue; + + for (componentName in components) { + currentValue = hasInherit(components[componentName]); + + if (lastValue !== null && lastValue !== currentValue) { + return true; + } + + lastValue = currentValue; + } + + return false; +} + +function replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator) { + var viaLonghands = buildSequenceWithInheritLonghands(candidateComponents, shorthandName, validator); + var viaShorthand = buildSequenceWithInheritShorthand(candidateComponents, shorthandName, validator); + var longhandTokensSequence = viaLonghands[0]; + var shorthandTokensSequence = viaShorthand[0]; + var isLonghandsShorter = serializeBody(longhandTokensSequence).length < serializeBody(shorthandTokensSequence).length; + var newTokensSequence = isLonghandsShorter ? longhandTokensSequence : shorthandTokensSequence; + var newProperty = isLonghandsShorter ? viaLonghands[1] : viaShorthand[1]; + var newComponents = isLonghandsShorter ? viaLonghands[2] : viaShorthand[2]; + var all = candidateComponents[Object.keys(candidateComponents)[0]].all; + var componentName; + var oldComponent; + var newComponent; + var newToken; + + newProperty.position = all.length; + newProperty.shorthand = true; + newProperty.dirty = true; + newProperty.all = all; + newProperty.all.push(newTokensSequence[0]); + + properties.push(newProperty); + + for (componentName in candidateComponents) { + oldComponent = candidateComponents[componentName]; + oldComponent.unused = true; + + if (oldComponent.name in newComponents) { + newComponent = newComponents[oldComponent.name]; + newToken = findTokenIn(newTokensSequence, componentName); + + newComponent.position = all.length; + newComponent.all = all; + newComponent.all.push(newToken); + + properties.push(newComponent); + } + } +} + +function buildSequenceWithInheritLonghands(components, shorthandName, validator) { + var tokensSequence = []; + var inheritComponents = {}; + var nonInheritComponents = {}; + var descriptor = compactable[shorthandName]; + var shorthandToken = [ + Token.PROPERTY, + [Token.PROPERTY_NAME, shorthandName], + [Token.PROPERTY_VALUE, descriptor.defaultValue] + ]; + var newProperty = wrapSingle(shorthandToken); + var component; + var longhandToken; + var newComponent; + var nameMetadata; + var i, l; + + populateComponents([newProperty], validator, []); + + for (i = 0, l = descriptor.components.length; i < l; i++) { + component = components[descriptor.components[i]]; + + if (hasInherit(component)) { + longhandToken = component.all[component.position].slice(0, 2); + Array.prototype.push.apply(longhandToken, component.value); + tokensSequence.push(longhandToken); + + newComponent = deepClone(component); + newComponent.value = inferComponentValue(components, newComponent.name); + + newProperty.components[i] = newComponent; + inheritComponents[component.name] = deepClone(component); + } else { + newComponent = deepClone(component); + newComponent.all = component.all; + newProperty.components[i] = newComponent; + + nonInheritComponents[component.name] = component; + } + } + + nameMetadata = joinMetadata(nonInheritComponents, 1); + shorthandToken[1].push(nameMetadata); + + restoreFromOptimizing([newProperty], restoreWithComponents); + + shorthandToken = shorthandToken.slice(0, 2); + Array.prototype.push.apply(shorthandToken, newProperty.value); + + tokensSequence.unshift(shorthandToken); + + return [tokensSequence, newProperty, inheritComponents]; +} + +function inferComponentValue(components, propertyName) { + var descriptor = compactable[propertyName]; + + if ('oppositeTo' in descriptor) { + return components[descriptor.oppositeTo].value; + } else { + return [[Token.PROPERTY_VALUE, descriptor.defaultValue]]; + } +} + +function joinMetadata(components, at) { + var metadata = []; + var component; + var originalValue; + var componentMetadata; + var componentName; + + for (componentName in components) { + component = components[componentName]; + originalValue = component.all[component.position]; + componentMetadata = originalValue[at][originalValue[at].length - 1]; + + Array.prototype.push.apply(metadata, componentMetadata); + } + + return metadata.sort(metadataSorter); +} + +function metadataSorter(metadata1, metadata2) { + var line1 = metadata1[0]; + var line2 = metadata2[0]; + var column1 = metadata1[1]; + var column2 = metadata2[1]; + + if (line1 < line2) { + return -1; + } else if (line1 === line2) { + return column1 < column2 ? -1 : 1; + } else { + return 1; + } +} + +function buildSequenceWithInheritShorthand(components, shorthandName, validator) { + var tokensSequence = []; + var inheritComponents = {}; + var nonInheritComponents = {}; + var descriptor = compactable[shorthandName]; + var shorthandToken = [ + Token.PROPERTY, + [Token.PROPERTY_NAME, shorthandName], + [Token.PROPERTY_VALUE, 'inherit'] + ]; + var newProperty = wrapSingle(shorthandToken); + var component; + var longhandToken; + var nameMetadata; + var valueMetadata; + var i, l; + + populateComponents([newProperty], validator, []); + + for (i = 0, l = descriptor.components.length; i < l; i++) { + component = components[descriptor.components[i]]; + + if (hasInherit(component)) { + inheritComponents[component.name] = component; + } else { + longhandToken = component.all[component.position].slice(0, 2); + Array.prototype.push.apply(longhandToken, component.value); + tokensSequence.push(longhandToken); + + nonInheritComponents[component.name] = deepClone(component); + } + } + + nameMetadata = joinMetadata(inheritComponents, 1); + shorthandToken[1].push(nameMetadata); + + valueMetadata = joinMetadata(inheritComponents, 2); + shorthandToken[2].push(valueMetadata); + + tokensSequence.unshift(shorthandToken); + + return [tokensSequence, newProperty, nonInheritComponents]; +} + +function findTokenIn(tokens, componentName) { + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + if (tokens[i][1][1] == componentName) { + return tokens[i]; + } + } +} + +function replaceWithShorthand(properties, candidateComponents, shorthandName, validator) { + var descriptor = compactable[shorthandName]; + var nameMetadata; + var valueMetadata; + var newValuePlaceholder = [ + Token.PROPERTY, + [Token.PROPERTY_NAME, shorthandName], + [Token.PROPERTY_VALUE, descriptor.defaultValue] + ]; + var all; + + var newProperty = wrapSingle(newValuePlaceholder); + newProperty.shorthand = true; + newProperty.dirty = true; + + populateComponents([newProperty], validator, []); + + for (var i = 0, l = descriptor.components.length; i < l; i++) { + var component = candidateComponents[descriptor.components[i]]; + + newProperty.components[i] = deepClone(component); + newProperty.important = component.important; + + all = component.all; + } + + for (var componentName in candidateComponents) { + candidateComponents[componentName].unused = true; + } + + nameMetadata = joinMetadata(candidateComponents, 1); + newValuePlaceholder[1].push(nameMetadata); + + valueMetadata = joinMetadata(candidateComponents, 2); + newValuePlaceholder[2].push(valueMetadata); + + newProperty.position = all.length; + newProperty.all = all; + newProperty.all.push(newValuePlaceholder); + + properties.push(newProperty); +} + +module.exports = mergeIntoShorthands; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/optimize.js b/node_modules/clean-css/lib/optimizer/level-2/properties/optimize.js new file mode 100644 index 0000000..5dc4bfb --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/optimize.js @@ -0,0 +1,40 @@ +var mergeIntoShorthands = require('./merge-into-shorthands'); +var overrideProperties = require('./override-properties'); +var populateComponents = require('./populate-components'); + +var restoreWithComponents = require('../restore-with-components'); + +var wrapForOptimizing = require('../../wrap-for-optimizing').all; +var removeUnused = require('../../remove-unused'); +var restoreFromOptimizing = require('../../restore-from-optimizing'); + +var OptimizationLevel = require('../../../options/optimization-level').OptimizationLevel; + +function optimizeProperties(properties, withOverriding, withMerging, context) { + var levelOptions = context.options.level[OptimizationLevel.Two]; + var _properties = wrapForOptimizing(properties, false, levelOptions.skipProperties); + var _property; + var i, l; + + populateComponents(_properties, context.validator, context.warnings); + + for (i = 0, l = _properties.length; i < l; i++) { + _property = _properties[i]; + if (_property.block) { + optimizeProperties(_property.value[0][1], withOverriding, withMerging, context); + } + } + + if (withMerging && levelOptions.mergeIntoShorthands) { + mergeIntoShorthands(_properties, context.validator); + } + + if (withOverriding && levelOptions.overrideProperties) { + overrideProperties(_properties, withMerging, context.options.compatibility, context.validator); + } + + restoreFromOptimizing(_properties, restoreWithComponents); + removeUnused(_properties); +} + +module.exports = optimizeProperties; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/override-properties.js b/node_modules/clean-css/lib/optimizer/level-2/properties/override-properties.js new file mode 100644 index 0000000..0f7b97a --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/override-properties.js @@ -0,0 +1,484 @@ +var hasInherit = require('./has-inherit'); +var everyValuesPair = require('./every-values-pair'); +var findComponentIn = require('./find-component-in'); +var isComponentOf = require('./is-component-of'); +var isMergeableShorthand = require('./is-mergeable-shorthand'); +var overridesNonComponentShorthand = require('./overrides-non-component-shorthand'); +var sameVendorPrefixesIn = require('./vendor-prefixes').same; + +var compactable = require('../compactable'); +var deepClone = require('../clone').deep; +var restoreWithComponents = require('../restore-with-components'); +var shallowClone = require('../clone').shallow; + +var restoreFromOptimizing = require('../../restore-from-optimizing'); + +var Token = require('../../../tokenizer/token'); +var Marker = require('../../../tokenizer/marker'); + +var serializeProperty = require('../../../writer/one-time').property; + +function wouldBreakCompatibility(property, validator) { + for (var i = 0; i < property.components.length; i++) { + var component = property.components[i]; + var descriptor = compactable[component.name]; + var canOverride = descriptor && descriptor.canOverride || canOverride.sameValue; + + var _component = shallowClone(component); + _component.value = [[Token.PROPERTY_VALUE, descriptor.defaultValue]]; + + if (!everyValuesPair(canOverride.bind(null, validator), _component, component)) { + return true; + } + } + + return false; +} + +function overrideIntoMultiplex(property, by) { + by.unused = true; + + turnIntoMultiplex(by, multiplexSize(property)); + property.value = by.value; +} + +function overrideByMultiplex(property, by) { + by.unused = true; + property.multiplex = true; + property.value = by.value; +} + +function overrideSimple(property, by) { + by.unused = true; + property.value = by.value; +} + +function override(property, by) { + if (by.multiplex) + overrideByMultiplex(property, by); + else if (property.multiplex) + overrideIntoMultiplex(property, by); + else + overrideSimple(property, by); +} + +function overrideShorthand(property, by) { + by.unused = true; + + for (var i = 0, l = property.components.length; i < l; i++) { + override(property.components[i], by.components[i], property.multiplex); + } +} + +function turnIntoMultiplex(property, size) { + property.multiplex = true; + + if (compactable[property.name].shorthand) { + turnShorthandValueIntoMultiplex(property, size); + } else { + turnLonghandValueIntoMultiplex(property, size); + } +} + +function turnShorthandValueIntoMultiplex(property, size) { + var component; + var i, l; + + for (i = 0, l = property.components.length; i < l; i++) { + component = property.components[i]; + + if (!component.multiplex) { + turnLonghandValueIntoMultiplex(component, size); + } + } +} + +function turnLonghandValueIntoMultiplex(property, size) { + var descriptor = compactable[property.name]; + var withRealValue = descriptor.intoMultiplexMode == 'real'; + var withValue = descriptor.intoMultiplexMode == 'real' ? + property.value.slice(0) : + (descriptor.intoMultiplexMode == 'placeholder' ? descriptor.placeholderValue : descriptor.defaultValue); + var i = multiplexSize(property); + var j; + var m = withValue.length; + + for (; i < size; i++) { + property.value.push([Token.PROPERTY_VALUE, Marker.COMMA]); + + if (Array.isArray(withValue)) { + for (j = 0; j < m; j++) { + property.value.push(withRealValue ? withValue[j] : [Token.PROPERTY_VALUE, withValue[j]]); + } + } else { + property.value.push(withRealValue ? withValue : [Token.PROPERTY_VALUE, withValue]); + } + } +} + +function multiplexSize(component) { + var size = 0; + + for (var i = 0, l = component.value.length; i < l; i++) { + if (component.value[i][1] == Marker.COMMA) + size++; + } + + return size + 1; +} + +function lengthOf(property) { + var fakeAsArray = [ + Token.PROPERTY, + [Token.PROPERTY_NAME, property.name] + ].concat(property.value); + return serializeProperty([fakeAsArray], 0).length; +} + +function moreSameShorthands(properties, startAt, name) { + // Since we run the main loop in `compactOverrides` backwards, at this point some + // properties may not be marked as unused. + // We should consider reverting the order if possible + var count = 0; + + for (var i = startAt; i >= 0; i--) { + if (properties[i].name == name && !properties[i].unused) + count++; + if (count > 1) + break; + } + + return count > 1; +} + +function overridingFunction(shorthand, validator) { + for (var i = 0, l = shorthand.components.length; i < l; i++) { + if (!anyValue(validator.isUrl, shorthand.components[i]) && anyValue(validator.isFunction, shorthand.components[i])) { + return true; + } + } + + return false; +} + +function anyValue(fn, property) { + for (var i = 0, l = property.value.length; i < l; i++) { + if (property.value[i][1] == Marker.COMMA) + continue; + + if (fn(property.value[i][1])) + return true; + } + + return false; +} + +function wouldResultInLongerValue(left, right) { + if (!left.multiplex && !right.multiplex || left.multiplex && right.multiplex) + return false; + + var multiplex = left.multiplex ? left : right; + var simple = left.multiplex ? right : left; + var component; + + var multiplexClone = deepClone(multiplex); + restoreFromOptimizing([multiplexClone], restoreWithComponents); + + var simpleClone = deepClone(simple); + restoreFromOptimizing([simpleClone], restoreWithComponents); + + var lengthBefore = lengthOf(multiplexClone) + 1 + lengthOf(simpleClone); + + if (left.multiplex) { + component = findComponentIn(multiplexClone, simpleClone); + overrideIntoMultiplex(component, simpleClone); + } else { + component = findComponentIn(simpleClone, multiplexClone); + turnIntoMultiplex(simpleClone, multiplexSize(multiplexClone)); + overrideByMultiplex(component, multiplexClone); + } + + restoreFromOptimizing([simpleClone], restoreWithComponents); + + var lengthAfter = lengthOf(simpleClone); + + return lengthBefore <= lengthAfter; +} + +function isCompactable(property) { + return property.name in compactable; +} + +function noneOverrideHack(left, right) { + return !left.multiplex && + (left.name == 'background' || left.name == 'background-image') && + right.multiplex && + (right.name == 'background' || right.name == 'background-image') && + anyLayerIsNone(right.value); +} + +function anyLayerIsNone(values) { + var layers = intoLayers(values); + + for (var i = 0, l = layers.length; i < l; i++) { + if (layers[i].length == 1 && layers[i][0][1] == 'none') + return true; + } + + return false; +} + +function intoLayers(values) { + var layers = []; + + for (var i = 0, layer = [], l = values.length; i < l; i++) { + var value = values[i]; + if (value[1] == Marker.COMMA) { + layers.push(layer); + layer = []; + } else { + layer.push(value); + } + } + + layers.push(layer); + return layers; +} + +function overrideProperties(properties, withMerging, compatibility, validator) { + var mayOverride, right, left, component; + var overriddenComponents; + var overriddenComponent; + var overridingComponent; + var overridable; + var i, j, k; + + propertyLoop: + for (i = properties.length - 1; i >= 0; i--) { + right = properties[i]; + + if (!isCompactable(right)) + continue; + + if (right.block) + continue; + + mayOverride = compactable[right.name].canOverride; + + traverseLoop: + for (j = i - 1; j >= 0; j--) { + left = properties[j]; + + if (!isCompactable(left)) + continue; + + if (left.block) + continue; + + if (left.unused || right.unused) + continue; + + if (left.hack && !right.hack && !right.important || !left.hack && !left.important && right.hack) + continue; + + if (left.important == right.important && left.hack[0] != right.hack[0]) + continue; + + if (left.important == right.important && (left.hack[0] != right.hack[0] || (left.hack[1] && left.hack[1] != right.hack[1]))) + continue; + + if (hasInherit(right)) + continue; + + if (noneOverrideHack(left, right)) + continue; + + if (right.shorthand && isComponentOf(right, left)) { + // maybe `left` can be overridden by `right` which is a shorthand? + if (!right.important && left.important) + continue; + + if (!sameVendorPrefixesIn([left], right.components)) + continue; + + if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) + continue; + + if (!isMergeableShorthand(right)) { + left.unused = true; + continue; + } + + component = findComponentIn(right, left); + mayOverride = compactable[left.name].canOverride; + if (everyValuesPair(mayOverride.bind(null, validator), left, component)) { + left.unused = true; + } + } else if (right.shorthand && overridesNonComponentShorthand(right, left)) { + // `right` is a shorthand while `left` can be overriden by it, think `border` and `border-top` + if (!right.important && left.important) { + continue; + } + + if (!sameVendorPrefixesIn([left], right.components)) { + continue; + } + + if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) { + continue; + } + + overriddenComponents = left.shorthand ? + left.components: + [left]; + + for (k = overriddenComponents.length - 1; k >= 0; k--) { + overriddenComponent = overriddenComponents[k]; + overridingComponent = findComponentIn(right, overriddenComponent); + mayOverride = compactable[overriddenComponent.name].canOverride; + + if (!everyValuesPair(mayOverride.bind(null, validator), left, overridingComponent)) { + continue traverseLoop; + } + } + + left.unused = true; + } else if (withMerging && left.shorthand && !right.shorthand && isComponentOf(left, right, true)) { + // maybe `right` can be pulled into `left` which is a shorthand? + if (right.important && !left.important) + continue; + + if (!right.important && left.important) { + right.unused = true; + continue; + } + + // Pending more clever algorithm in #527 + if (moreSameShorthands(properties, i - 1, left.name)) + continue; + + if (overridingFunction(left, validator)) + continue; + + if (!isMergeableShorthand(left)) + continue; + + component = findComponentIn(left, right); + if (everyValuesPair(mayOverride.bind(null, validator), component, right)) { + var disabledBackgroundMerging = + !compatibility.properties.backgroundClipMerging && component.name.indexOf('background-clip') > -1 || + !compatibility.properties.backgroundOriginMerging && component.name.indexOf('background-origin') > -1 || + !compatibility.properties.backgroundSizeMerging && component.name.indexOf('background-size') > -1; + var nonMergeableValue = compactable[right.name].nonMergeableValue === right.value[0][1]; + + if (disabledBackgroundMerging || nonMergeableValue) + continue; + + if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator)) + continue; + + if (component.value[0][1] != right.value[0][1] && (hasInherit(left) || hasInherit(right))) + continue; + + if (wouldResultInLongerValue(left, right)) + continue; + + if (!left.multiplex && right.multiplex) + turnIntoMultiplex(left, multiplexSize(right)); + + override(component, right); + left.dirty = true; + } + } else if (withMerging && left.shorthand && right.shorthand && left.name == right.name) { + // merge if all components can be merged + + if (!left.multiplex && right.multiplex) + continue; + + if (!right.important && left.important) { + right.unused = true; + continue propertyLoop; + } + + if (right.important && !left.important) { + left.unused = true; + continue; + } + + if (!isMergeableShorthand(right)) { + left.unused = true; + continue; + } + + for (k = left.components.length - 1; k >= 0; k--) { + var leftComponent = left.components[k]; + var rightComponent = right.components[k]; + + mayOverride = compactable[leftComponent.name].canOverride; + if (!everyValuesPair(mayOverride.bind(null, validator), leftComponent, rightComponent)) + continue propertyLoop; + } + + overrideShorthand(left, right); + left.dirty = true; + } else if (withMerging && left.shorthand && right.shorthand && isComponentOf(left, right)) { + // border is a shorthand but any of its components is a shorthand too + + if (!left.important && right.important) + continue; + + component = findComponentIn(left, right); + mayOverride = compactable[right.name].canOverride; + if (!everyValuesPair(mayOverride.bind(null, validator), component, right)) + continue; + + if (left.important && !right.important) { + right.unused = true; + continue; + } + + var rightRestored = compactable[right.name].restore(right, compactable); + if (rightRestored.length > 1) + continue; + + component = findComponentIn(left, right); + override(component, right); + right.dirty = true; + } else if (left.name == right.name) { + // two non-shorthands should be merged based on understandability + overridable = true; + + if (right.shorthand) { + for (k = right.components.length - 1; k >= 0 && overridable; k--) { + overriddenComponent = left.components[k]; + overridingComponent = right.components[k]; + mayOverride = compactable[overridingComponent.name].canOverride; + + overridable = overridable && everyValuesPair(mayOverride.bind(null, validator), overriddenComponent, overridingComponent); + } + } else { + mayOverride = compactable[right.name].canOverride; + overridable = everyValuesPair(mayOverride.bind(null, validator), left, right); + } + + if (left.important && !right.important && overridable) { + right.unused = true; + continue; + } + + if (!left.important && right.important && overridable) { + left.unused = true; + continue; + } + + if (!overridable) { + continue; + } + + left.unused = true; + } + } + } +} + +module.exports = overrideProperties; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/overrides-non-component-shorthand.js b/node_modules/clean-css/lib/optimizer/level-2/properties/overrides-non-component-shorthand.js new file mode 100644 index 0000000..c385218 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/overrides-non-component-shorthand.js @@ -0,0 +1,9 @@ +var compactable = require('../compactable'); + +function overridesNonComponentShorthand(property1, property2) { + return property1.name in compactable && + 'overridesShorthands' in compactable[property1.name] && + compactable[property1.name].overridesShorthands.indexOf(property2.name) > -1; +} + +module.exports = overridesNonComponentShorthand; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/populate-components.js b/node_modules/clean-css/lib/optimizer/level-2/properties/populate-components.js new file mode 100644 index 0000000..c587e83 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/populate-components.js @@ -0,0 +1,42 @@ +var compactable = require('../compactable'); +var InvalidPropertyError = require('../invalid-property-error'); + +function populateComponents(properties, validator, warnings) { + var component; + var j, m; + + for (var i = properties.length - 1; i >= 0; i--) { + var property = properties[i]; + var descriptor = compactable[property.name]; + + if (descriptor && descriptor.shorthand) { + property.shorthand = true; + property.dirty = true; + + try { + property.components = descriptor.breakUp(property, compactable, validator); + + if (descriptor.shorthandComponents) { + for (j = 0, m = property.components.length; j < m; j++) { + component = property.components[j]; + component.components = compactable[component.name].breakUp(component, compactable, validator); + } + } + } catch (e) { + if (e instanceof InvalidPropertyError) { + property.components = []; // this will set property.unused to true below + warnings.push(e.message); + } else { + throw e; + } + } + + if (property.components.length > 0) + property.multiplex = property.components[0].multiplex; + else + property.unused = true; + } + } +} + +module.exports = populateComponents; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/understandable.js b/node_modules/clean-css/lib/optimizer/level-2/properties/understandable.js new file mode 100644 index 0000000..032169a --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/understandable.js @@ -0,0 +1,15 @@ +var sameVendorPrefixes = require('./vendor-prefixes').same; + +function understandable(validator, value1, value2, _position, isPaired) { + if (!sameVendorPrefixes(value1, value2)) { + return false; + } + + if (isPaired && validator.isVariable(value1) !== validator.isVariable(value2)) { + return false; + } + + return true; +} + +module.exports = understandable; diff --git a/node_modules/clean-css/lib/optimizer/level-2/properties/vendor-prefixes.js b/node_modules/clean-css/lib/optimizer/level-2/properties/vendor-prefixes.js new file mode 100644 index 0000000..f9ab527 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/properties/vendor-prefixes.js @@ -0,0 +1,23 @@ +var VENDOR_PREFIX_PATTERN = /(?:^|\W)(\-\w+\-)/g; + +function unique(value) { + var prefixes = []; + var match; + + while ((match = VENDOR_PREFIX_PATTERN.exec(value)) !== null) { + if (prefixes.indexOf(match[0]) == -1) { + prefixes.push(match[0]); + } + } + + return prefixes; +} + +function same(value1, value2) { + return unique(value1).sort().join(',') == unique(value2).sort().join(','); +} + +module.exports = { + unique: unique, + same: same +}; diff --git a/node_modules/clean-css/lib/optimizer/level-2/reduce-non-adjacent.js b/node_modules/clean-css/lib/optimizer/level-2/reduce-non-adjacent.js new file mode 100644 index 0000000..6ce0902 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/reduce-non-adjacent.js @@ -0,0 +1,180 @@ +var isMergeable = require('./is-mergeable'); + +var optimizeProperties = require('./properties/optimize'); + +var cloneArray = require('../../utils/clone-array'); + +var Token = require('../../tokenizer/token'); + +var serializeBody = require('../../writer/one-time').body; +var serializeRules = require('../../writer/one-time').rules; + +function reduceNonAdjacent(tokens, context) { + var options = context.options; + var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; + var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; + var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; + var candidates = {}; + var repeated = []; + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + + if (token[0] != Token.RULE) { + continue; + } else if (token[2].length === 0) { + continue; + } + + var selectorAsString = serializeRules(token[1]); + var isComplexAndNotSpecial = token[1].length > 1 && + isMergeable(selectorAsString, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging); + var wrappedSelectors = wrappedSelectorsFrom(token[1]); + var selectors = isComplexAndNotSpecial ? + [selectorAsString].concat(wrappedSelectors) : + [selectorAsString]; + + for (var j = 0, m = selectors.length; j < m; j++) { + var selector = selectors[j]; + + if (!candidates[selector]) + candidates[selector] = []; + else + repeated.push(selector); + + candidates[selector].push({ + where: i, + list: wrappedSelectors, + isPartial: isComplexAndNotSpecial && j > 0, + isComplex: isComplexAndNotSpecial && j === 0 + }); + } + } + + reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context); + reduceComplexNonAdjacentCases(tokens, candidates, options, context); +} + +function wrappedSelectorsFrom(list) { + var wrapped = []; + + for (var i = 0; i < list.length; i++) { + wrapped.push([list[i][1]]); + } + + return wrapped; +} + +function reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context) { + function filterOut(idx, bodies) { + return data[idx].isPartial && bodies.length === 0; + } + + function reduceBody(token, newBody, processedCount, tokenIdx) { + if (!data[processedCount - tokenIdx - 1].isPartial) + token[2] = newBody; + } + + for (var i = 0, l = repeated.length; i < l; i++) { + var selector = repeated[i]; + var data = candidates[selector]; + + reduceSelector(tokens, data, { + filterOut: filterOut, + callback: reduceBody + }, options, context); + } +} + +function reduceComplexNonAdjacentCases(tokens, candidates, options, context) { + var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; + var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; + var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; + var localContext = {}; + + function filterOut(idx) { + return localContext.data[idx].where < localContext.intoPosition; + } + + function collectReducedBodies(token, newBody, processedCount, tokenIdx) { + if (tokenIdx === 0) + localContext.reducedBodies.push(newBody); + } + + allSelectors: + for (var complexSelector in candidates) { + var into = candidates[complexSelector]; + if (!into[0].isComplex) + continue; + + var intoPosition = into[into.length - 1].where; + var intoToken = tokens[intoPosition]; + var reducedBodies = []; + + var selectors = isMergeable(complexSelector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) ? + into[0].list : + [complexSelector]; + + localContext.intoPosition = intoPosition; + localContext.reducedBodies = reducedBodies; + + for (var j = 0, m = selectors.length; j < m; j++) { + var selector = selectors[j]; + var data = candidates[selector]; + + if (data.length < 2) + continue allSelectors; + + localContext.data = data; + + reduceSelector(tokens, data, { + filterOut: filterOut, + callback: collectReducedBodies + }, options, context); + + if (serializeBody(reducedBodies[reducedBodies.length - 1]) != serializeBody(reducedBodies[0])) + continue allSelectors; + } + + intoToken[2] = reducedBodies[0]; + } +} + +function reduceSelector(tokens, data, context, options, outerContext) { + var bodies = []; + var bodiesAsList = []; + var processedTokens = []; + + for (var j = data.length - 1; j >= 0; j--) { + if (context.filterOut(j, bodies)) + continue; + + var where = data[j].where; + var token = tokens[where]; + var clonedBody = cloneArray(token[2]); + + bodies = bodies.concat(clonedBody); + bodiesAsList.push(clonedBody); + processedTokens.push(where); + } + + optimizeProperties(bodies, true, false, outerContext); + + var processedCount = processedTokens.length; + var propertyIdx = bodies.length - 1; + var tokenIdx = processedCount - 1; + + while (tokenIdx >= 0) { + if ((tokenIdx === 0 || (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) { + propertyIdx--; + continue; + } + + var newBody = bodies.splice(propertyIdx + 1); + context.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx); + + tokenIdx--; + } +} + +module.exports = reduceNonAdjacent; diff --git a/node_modules/clean-css/lib/optimizer/level-2/remove-duplicate-font-at-rules.js b/node_modules/clean-css/lib/optimizer/level-2/remove-duplicate-font-at-rules.js new file mode 100644 index 0000000..bc85d5d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/remove-duplicate-font-at-rules.js @@ -0,0 +1,30 @@ +var Token = require('../../tokenizer/token'); + +var serializeAll = require('../../writer/one-time').all; + +var FONT_FACE_SCOPE = '@font-face'; + +function removeDuplicateFontAtRules(tokens) { + var fontAtRules = []; + var token; + var key; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + + if (token[0] != Token.AT_RULE_BLOCK && token[1][0][1] != FONT_FACE_SCOPE) { + continue; + } + + key = serializeAll([token]); + + if (fontAtRules.indexOf(key) > -1) { + token[2] = []; + } else { + fontAtRules.push(key); + } + } +} + +module.exports = removeDuplicateFontAtRules; diff --git a/node_modules/clean-css/lib/optimizer/level-2/remove-duplicate-media-queries.js b/node_modules/clean-css/lib/optimizer/level-2/remove-duplicate-media-queries.js new file mode 100644 index 0000000..2c8f31d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/remove-duplicate-media-queries.js @@ -0,0 +1,30 @@ +var Token = require('../../tokenizer/token'); + +var serializeAll = require('../../writer/one-time').all; +var serializeRules = require('../../writer/one-time').rules; + +function removeDuplicateMediaQueries(tokens) { + var candidates = {}; + var candidate; + var token; + var key; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + if (token[0] != Token.NESTED_BLOCK) { + continue; + } + + key = serializeRules(token[1]) + '%' + serializeAll(token[2]); + candidate = candidates[key]; + + if (candidate) { + candidate[2] = []; + } + + candidates[key] = token; + } +} + +module.exports = removeDuplicateMediaQueries; diff --git a/node_modules/clean-css/lib/optimizer/level-2/remove-duplicates.js b/node_modules/clean-css/lib/optimizer/level-2/remove-duplicates.js new file mode 100644 index 0000000..9aa6ace --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/remove-duplicates.js @@ -0,0 +1,43 @@ +var Token = require('../../tokenizer/token'); + +var serializeBody = require('../../writer/one-time').body; +var serializeRules = require('../../writer/one-time').rules; + +function removeDuplicates(tokens) { + var matched = {}; + var moreThanOnce = []; + var id, token; + var body, bodies; + + for (var i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + if (token[0] != Token.RULE) + continue; + + id = serializeRules(token[1]); + + if (matched[id] && matched[id].length == 1) + moreThanOnce.push(id); + else + matched[id] = matched[id] || []; + + matched[id].push(i); + } + + for (i = 0, l = moreThanOnce.length; i < l; i++) { + id = moreThanOnce[i]; + bodies = []; + + for (var j = matched[id].length - 1; j >= 0; j--) { + token = tokens[matched[id][j]]; + body = serializeBody(token[2]); + + if (bodies.indexOf(body) > -1) + token[2] = []; + else + bodies.push(body); + } + } +} + +module.exports = removeDuplicates; diff --git a/node_modules/clean-css/lib/optimizer/level-2/remove-unused-at-rules.js b/node_modules/clean-css/lib/optimizer/level-2/remove-unused-at-rules.js new file mode 100644 index 0000000..798d393 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/remove-unused-at-rules.js @@ -0,0 +1,249 @@ +var populateComponents = require('./properties/populate-components'); + +var wrapForOptimizing = require('../wrap-for-optimizing').single; +var restoreFromOptimizing = require('../restore-from-optimizing'); + +var Token = require('../../tokenizer/token'); + +var animationNameRegex = /^(\-moz\-|\-o\-|\-webkit\-)?animation-name$/; +var animationRegex = /^(\-moz\-|\-o\-|\-webkit\-)?animation$/; +var keyframeRegex = /^@(\-moz\-|\-o\-|\-webkit\-)?keyframes /; +var importantRegex = /\s{0,31}!important$/; +var optionalMatchingQuotesRegex = /^(['"]?)(.*)\1$/; + +function normalize(value) { + return value + .replace(optionalMatchingQuotesRegex, '$2') + .replace(importantRegex, ''); +} + +function removeUnusedAtRules(tokens, context) { + removeUnusedAtRule(tokens, matchCounterStyle, markCounterStylesAsUsed, context); + removeUnusedAtRule(tokens, matchFontFace, markFontFacesAsUsed, context); + removeUnusedAtRule(tokens, matchKeyframe, markKeyframesAsUsed, context); + removeUnusedAtRule(tokens, matchNamespace, markNamespacesAsUsed, context); +} + +function removeUnusedAtRule(tokens, matchCallback, markCallback, context) { + var atRules = {}; + var atRule; + var atRuleTokens; + var atRuleToken; + var zeroAt; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + matchCallback(tokens[i], atRules); + } + + if (Object.keys(atRules).length === 0) { + return; + } + + markUsedAtRules(tokens, markCallback, atRules, context); + + for (atRule in atRules) { + atRuleTokens = atRules[atRule]; + + for (i = 0, l = atRuleTokens.length; i < l; i++) { + atRuleToken = atRuleTokens[i]; + zeroAt = atRuleToken[0] == Token.AT_RULE ? 1 : 2; + atRuleToken[zeroAt] = []; + } + } +} + +function markUsedAtRules(tokens, markCallback, atRules, context) { + var boundMarkCallback = markCallback(atRules); + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + switch (tokens[i][0]) { + case Token.RULE: + boundMarkCallback(tokens[i], context); + break; + case Token.NESTED_BLOCK: + markUsedAtRules(tokens[i][2], markCallback, atRules, context); + } + } +} + +function matchCounterStyle(token, atRules) { + var match; + + if (token[0] == Token.AT_RULE_BLOCK && token[1][0][1].indexOf('@counter-style') === 0) { + match = token[1][0][1].split(' ')[1]; + atRules[match] = atRules[match] || []; + atRules[match].push(token); + } +} + +function markCounterStylesAsUsed(atRules) { + return function (token, context) { + var property; + var wrappedProperty; + var i, l; + + for (i = 0, l = token[2].length; i < l; i++) { + property = token[2][i]; + + if (property[1][1] == 'list-style') { + wrappedProperty = wrapForOptimizing(property); + populateComponents([wrappedProperty], context.validator, context.warnings); + + if (wrappedProperty.components[0].value[0][1] in atRules) { + delete atRules[property[2][1]]; + } + + restoreFromOptimizing([wrappedProperty]); + } + + if (property[1][1] == 'list-style-type' && property[2][1] in atRules) { + delete atRules[property[2][1]]; + } + } + }; +} + +function matchFontFace(token, atRules) { + var property; + var match; + var i, l; + + if (token[0] == Token.AT_RULE_BLOCK && token[1][0][1] == '@font-face') { + for (i = 0, l = token[2].length; i < l; i++) { + property = token[2][i]; + + if (property[1][1] == 'font-family') { + match = normalize(property[2][1].toLowerCase()); + atRules[match] = atRules[match] || []; + atRules[match].push(token); + break; + } + } + } +} + +function markFontFacesAsUsed(atRules) { + return function (token, context) { + var property; + var wrappedProperty; + var component; + var normalizedMatch; + var i, l; + var j, m; + + for (i = 0, l = token[2].length; i < l; i++) { + property = token[2][i]; + + if (property[1][1] == 'font') { + wrappedProperty = wrapForOptimizing(property); + populateComponents([wrappedProperty], context.validator, context.warnings); + component = wrappedProperty.components[6]; + + for (j = 0, m = component.value.length; j < m; j++) { + normalizedMatch = normalize(component.value[j][1].toLowerCase()); + + if (normalizedMatch in atRules) { + delete atRules[normalizedMatch]; + } + } + + restoreFromOptimizing([wrappedProperty]); + } + + if (property[1][1] == 'font-family') { + for (j = 2, m = property.length; j < m; j++) { + normalizedMatch = normalize(property[j][1].toLowerCase()); + + if (normalizedMatch in atRules) { + delete atRules[normalizedMatch]; + } + } + } + } + }; +} + +function matchKeyframe(token, atRules) { + var match; + + if (token[0] == Token.NESTED_BLOCK && keyframeRegex.test(token[1][0][1])) { + match = token[1][0][1].split(' ')[1]; + atRules[match] = atRules[match] || []; + atRules[match].push(token); + } +} + +function markKeyframesAsUsed(atRules) { + return function (token, context) { + var property; + var wrappedProperty; + var component; + var i, l; + var j, m; + + for (i = 0, l = token[2].length; i < l; i++) { + property = token[2][i]; + + if (animationRegex.test(property[1][1])) { + wrappedProperty = wrapForOptimizing(property); + populateComponents([wrappedProperty], context.validator, context.warnings); + component = wrappedProperty.components[7]; + + for (j = 0, m = component.value.length; j < m; j++) { + if (component.value[j][1] in atRules) { + delete atRules[component.value[j][1]]; + } + } + + restoreFromOptimizing([wrappedProperty]); + } + + if (animationNameRegex.test(property[1][1])) { + for (j = 2, m = property.length; j < m; j++) { + if (property[j][1] in atRules) { + delete atRules[property[j][1]]; + } + } + } + } + }; +} + +function matchNamespace(token, atRules) { + var match; + + if (token[0] == Token.AT_RULE && token[1].indexOf('@namespace') === 0) { + match = token[1].split(' ')[1]; + atRules[match] = atRules[match] || []; + atRules[match].push(token); + } +} + +function markNamespacesAsUsed(atRules) { + var namespaceRegex = new RegExp(Object.keys(atRules).join('\\\||') + '\\\|', 'g'); + + return function (token) { + var match; + var scope; + var normalizedMatch; + var i, l; + var j, m; + + for (i = 0, l = token[1].length; i < l; i++) { + scope = token[1][i]; + match = scope[1].match(namespaceRegex); + + for (j = 0, m = match.length; j < m; j++) { + normalizedMatch = match[j].substring(0, match[j].length - 1); + + if (normalizedMatch in atRules) { + delete atRules[normalizedMatch]; + } + } + } + }; +} + +module.exports = removeUnusedAtRules; diff --git a/node_modules/clean-css/lib/optimizer/level-2/reorderable.js b/node_modules/clean-css/lib/optimizer/level-2/reorderable.js new file mode 100644 index 0000000..4a3747a --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/reorderable.js @@ -0,0 +1,93 @@ +// TODO: it'd be great to merge it with the other canReorder functionality + +var rulesOverlap = require('./rules-overlap'); +var specificitiesOverlap = require('./specificities-overlap'); + +var FLEX_PROPERTIES = /align\-items|box\-align|box\-pack|flex|justify/; +var BORDER_PROPERTIES = /^border\-(top|right|bottom|left|color|style|width|radius)/; + +function canReorder(left, right, cache) { + for (var i = right.length - 1; i >= 0; i--) { + for (var j = left.length - 1; j >= 0; j--) { + if (!canReorderSingle(left[j], right[i], cache)) + return false; + } + } + + return true; +} + +function canReorderSingle(left, right, cache) { + var leftName = left[0]; + var leftValue = left[1]; + var leftNameRoot = left[2]; + var leftSelector = left[5]; + var leftInSpecificSelector = left[6]; + var rightName = right[0]; + var rightValue = right[1]; + var rightNameRoot = right[2]; + var rightSelector = right[5]; + var rightInSpecificSelector = right[6]; + + if (leftName == 'font' && rightName == 'line-height' || rightName == 'font' && leftName == 'line-height') + return false; + if (FLEX_PROPERTIES.test(leftName) && FLEX_PROPERTIES.test(rightName)) + return false; + if (leftNameRoot == rightNameRoot && unprefixed(leftName) == unprefixed(rightName) && (vendorPrefixed(leftName) ^ vendorPrefixed(rightName))) + return false; + if (leftNameRoot == 'border' && BORDER_PROPERTIES.test(rightNameRoot) && (leftName == 'border' || leftName == rightNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName)))) + return false; + if (rightNameRoot == 'border' && BORDER_PROPERTIES.test(leftNameRoot) && (rightName == 'border' || rightName == leftNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName)))) + return false; + if (leftNameRoot == 'border' && rightNameRoot == 'border' && leftName != rightName && (isSideBorder(leftName) && isStyleBorder(rightName) || isStyleBorder(leftName) && isSideBorder(rightName))) + return false; + if (leftNameRoot != rightNameRoot) + return true; + if (leftName == rightName && leftNameRoot == rightNameRoot && (leftValue == rightValue || withDifferentVendorPrefix(leftValue, rightValue))) + return true; + if (leftName != rightName && leftNameRoot == rightNameRoot && leftName != leftNameRoot && rightName != rightNameRoot) + return true; + if (leftName != rightName && leftNameRoot == rightNameRoot && leftValue == rightValue) + return true; + if (rightInSpecificSelector && leftInSpecificSelector && !inheritable(leftNameRoot) && !inheritable(rightNameRoot) && !rulesOverlap(rightSelector, leftSelector, false)) + return true; + if (!specificitiesOverlap(leftSelector, rightSelector, cache)) + return true; + + return false; +} + +function vendorPrefixed(name) { + return /^\-(?:moz|webkit|ms|o)\-/.test(name); +} + +function unprefixed(name) { + return name.replace(/^\-(?:moz|webkit|ms|o)\-/, ''); +} + +function sameBorderComponent(name1, name2) { + return name1.split('-').pop() == name2.split('-').pop(); +} + +function isSideBorder(name) { + return name == 'border-top' || name == 'border-right' || name == 'border-bottom' || name == 'border-left'; +} + +function isStyleBorder(name) { + return name == 'border-color' || name == 'border-style' || name == 'border-width'; +} + +function withDifferentVendorPrefix(value1, value2) { + return vendorPrefixed(value1) && vendorPrefixed(value2) && value1.split('-')[1] != value2.split('-')[2]; +} + +function inheritable(name) { + // According to http://www.w3.org/TR/CSS21/propidx.html + // Others will be catched by other, preceeding rules + return name == 'font' || name == 'line-height' || name == 'list-style'; +} + +module.exports = { + canReorder: canReorder, + canReorderSingle: canReorderSingle +}; diff --git a/node_modules/clean-css/lib/optimizer/level-2/restore-with-components.js b/node_modules/clean-css/lib/optimizer/level-2/restore-with-components.js new file mode 100644 index 0000000..caf7c4c --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/restore-with-components.js @@ -0,0 +1,13 @@ +var compactable = require('./compactable'); + +function restoreWithComponents(property) { + var descriptor = compactable[property.name]; + + if (descriptor && descriptor.shorthand) { + return descriptor.restore(property, compactable); + } else { + return property.value; + } +} + +module.exports = restoreWithComponents; diff --git a/node_modules/clean-css/lib/optimizer/level-2/restore.js b/node_modules/clean-css/lib/optimizer/level-2/restore.js new file mode 100644 index 0000000..f9c2f0d --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/restore.js @@ -0,0 +1,303 @@ +var shallowClone = require('./clone').shallow; + +var Token = require('../../tokenizer/token'); +var Marker = require('../../tokenizer/marker'); + +function isInheritOnly(values) { + for (var i = 0, l = values.length; i < l; i++) { + var value = values[i][1]; + + if (value != 'inherit' && value != Marker.COMMA && value != Marker.FORWARD_SLASH) + return false; + } + + return true; +} + +function background(property, compactable, lastInMultiplex) { + var components = property.components; + var restored = []; + var needsOne, needsBoth; + + function restoreValue(component) { + Array.prototype.unshift.apply(restored, component.value); + } + + function isDefaultValue(component) { + var descriptor = compactable[component.name]; + + if (descriptor.doubleValues && descriptor.defaultValue.length == 1) { + return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] == descriptor.defaultValue[0] : true); + } else if (descriptor.doubleValues && descriptor.defaultValue.length != 1) { + return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] : component.value[0][1]) == descriptor.defaultValue[1]; + } else { + return component.value[0][1] == descriptor.defaultValue; + } + } + + for (var i = components.length - 1; i >= 0; i--) { + var component = components[i]; + var isDefault = isDefaultValue(component); + + if (component.name == 'background-clip') { + var originComponent = components[i - 1]; + var isOriginDefault = isDefaultValue(originComponent); + + needsOne = component.value[0][1] == originComponent.value[0][1]; + + needsBoth = !needsOne && ( + (isOriginDefault && !isDefault) || + (!isOriginDefault && !isDefault) || + (!isOriginDefault && isDefault && component.value[0][1] != originComponent.value[0][1])); + + if (needsOne) { + restoreValue(originComponent); + } else if (needsBoth) { + restoreValue(component); + restoreValue(originComponent); + } + + i--; + } else if (component.name == 'background-size') { + var positionComponent = components[i - 1]; + var isPositionDefault = isDefaultValue(positionComponent); + + needsOne = !isPositionDefault && isDefault; + + needsBoth = !needsOne && + (isPositionDefault && !isDefault || !isPositionDefault && !isDefault); + + if (needsOne) { + restoreValue(positionComponent); + } else if (needsBoth) { + restoreValue(component); + restored.unshift([Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]); + restoreValue(positionComponent); + } else if (positionComponent.value.length == 1) { + restoreValue(positionComponent); + } + + i--; + } else { + if (isDefault || compactable[component.name].multiplexLastOnly && !lastInMultiplex) + continue; + + restoreValue(component); + } + } + + if (restored.length === 0 && property.value.length == 1 && property.value[0][1] == '0') + restored.push(property.value[0]); + + if (restored.length === 0) + restored.push([Token.PROPERTY_VALUE, compactable[property.name].defaultValue]); + + if (isInheritOnly(restored)) + return [restored[0]]; + + return restored; +} + +function borderRadius(property, compactable) { + if (property.multiplex) { + var horizontal = shallowClone(property); + var vertical = shallowClone(property); + + for (var i = 0; i < 4; i++) { + var component = property.components[i]; + + var horizontalComponent = shallowClone(property); + horizontalComponent.value = [component.value[0]]; + horizontal.components.push(horizontalComponent); + + var verticalComponent = shallowClone(property); + // FIXME: only shorthand compactor (see breakup#borderRadius) knows that border radius + // longhands have two values, whereas tokenizer does not care about populating 2nd value + // if it's missing, hence this fallback + verticalComponent.value = [component.value[1] || component.value[0]]; + vertical.components.push(verticalComponent); + } + + var horizontalValues = fourValues(horizontal, compactable); + var verticalValues = fourValues(vertical, compactable); + + if (horizontalValues.length == verticalValues.length && + horizontalValues[0][1] == verticalValues[0][1] && + (horizontalValues.length > 1 ? horizontalValues[1][1] == verticalValues[1][1] : true) && + (horizontalValues.length > 2 ? horizontalValues[2][1] == verticalValues[2][1] : true) && + (horizontalValues.length > 3 ? horizontalValues[3][1] == verticalValues[3][1] : true)) { + return horizontalValues; + } else { + return horizontalValues.concat([[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]).concat(verticalValues); + } + } else { + return fourValues(property, compactable); + } +} + +function font(property, compactable) { + var components = property.components; + var restored = []; + var component; + var componentIndex = 0; + var fontFamilyIndex = 0; + + if (property.value[0][1].indexOf(Marker.INTERNAL) === 0) { + property.value[0][1] = property.value[0][1].substring(Marker.INTERNAL.length); + return property.value; + } + + // first four components are optional + while (componentIndex < 4) { + component = components[componentIndex]; + + if (component.value[0][1] != compactable[component.name].defaultValue) { + Array.prototype.push.apply(restored, component.value); + } + + componentIndex++; + } + + // then comes font-size + Array.prototype.push.apply(restored, components[componentIndex].value); + componentIndex++; + + // then may come line-height + if (components[componentIndex].value[0][1] != compactable[components[componentIndex].name].defaultValue) { + Array.prototype.push.apply(restored, [[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]); + Array.prototype.push.apply(restored, components[componentIndex].value); + } + + componentIndex++; + + // then comes font-family + while (components[componentIndex].value[fontFamilyIndex]) { + restored.push(components[componentIndex].value[fontFamilyIndex]); + + if (components[componentIndex].value[fontFamilyIndex + 1]) { + restored.push([Token.PROPERTY_VALUE, Marker.COMMA]); + } + + fontFamilyIndex++; + } + + if (isInheritOnly(restored)) { + return [restored[0]]; + } + + return restored; +} + +function fourValues(property) { + var components = property.components; + var value1 = components[0].value[0]; + var value2 = components[1].value[0]; + var value3 = components[2].value[0]; + var value4 = components[3].value[0]; + + if (value1[1] == value2[1] && value1[1] == value3[1] && value1[1] == value4[1]) { + return [value1]; + } else if (value1[1] == value3[1] && value2[1] == value4[1]) { + return [value1, value2]; + } else if (value2[1] == value4[1]) { + return [value1, value2, value3]; + } else { + return [value1, value2, value3, value4]; + } +} + +function multiplex(restoreWith) { + return function (property, compactable) { + if (!property.multiplex) + return restoreWith(property, compactable, true); + + var multiplexSize = 0; + var restored = []; + var componentMultiplexSoFar = {}; + var i, l; + + // At this point we don't know what's the multiplex size, e.g. how many background layers are there + for (i = 0, l = property.components[0].value.length; i < l; i++) { + if (property.components[0].value[i][1] == Marker.COMMA) + multiplexSize++; + } + + for (i = 0; i <= multiplexSize; i++) { + var _property = shallowClone(property); + + // We split multiplex into parts and restore them one by one + for (var j = 0, m = property.components.length; j < m; j++) { + var componentToClone = property.components[j]; + var _component = shallowClone(componentToClone); + _property.components.push(_component); + + // The trick is some properties has more than one value, so we iterate over values looking for + // a multiplex separator - a comma + for (var k = componentMultiplexSoFar[_component.name] || 0, n = componentToClone.value.length; k < n; k++) { + if (componentToClone.value[k][1] == Marker.COMMA) { + componentMultiplexSoFar[_component.name] = k + 1; + break; + } + + _component.value.push(componentToClone.value[k]); + } + } + + // No we can restore shorthand value + var lastInMultiplex = i == multiplexSize; + var _restored = restoreWith(_property, compactable, lastInMultiplex); + Array.prototype.push.apply(restored, _restored); + + if (i < multiplexSize) + restored.push([Token.PROPERTY_VALUE, Marker.COMMA]); + } + + return restored; + }; +} + +function withoutDefaults(property, compactable) { + var components = property.components; + var restored = []; + + for (var i = components.length - 1; i >= 0; i--) { + var component = components[i]; + var descriptor = compactable[component.name]; + + if (component.value[0][1] != descriptor.defaultValue || ('keepUnlessDefault' in descriptor) && !isDefault(components, compactable, descriptor.keepUnlessDefault)) { + restored.unshift(component.value[0]); + } + } + + if (restored.length === 0) + restored.push([Token.PROPERTY_VALUE, compactable[property.name].defaultValue]); + + if (isInheritOnly(restored)) + return [restored[0]]; + + return restored; +} + +function isDefault(components, compactable, propertyName) { + var component; + var i, l; + + for (i = 0, l = components.length; i < l; i++) { + component = components[i]; + + if (component.name == propertyName && component.value[0][1] == compactable[propertyName].defaultValue) { + return true; + } + } + + return false; +} + +module.exports = { + background: background, + borderRadius: borderRadius, + font: font, + fourValues: fourValues, + multiplex: multiplex, + withoutDefaults: withoutDefaults +}; diff --git a/node_modules/clean-css/lib/optimizer/level-2/restructure.js b/node_modules/clean-css/lib/optimizer/level-2/restructure.js new file mode 100644 index 0000000..90b8bfa --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/restructure.js @@ -0,0 +1,389 @@ +var canReorderSingle = require('./reorderable').canReorderSingle; +var extractProperties = require('./extract-properties'); +var isMergeable = require('./is-mergeable'); +var tidyRuleDuplicates = require('./tidy-rule-duplicates'); + +var Token = require('../../tokenizer/token'); + +var cloneArray = require('../../utils/clone-array'); + +var serializeBody = require('../../writer/one-time').body; +var serializeRules = require('../../writer/one-time').rules; + +function naturalSorter(a, b) { + return a > b ? 1 : -1; +} + +function cloneAndMergeSelectors(propertyA, propertyB) { + var cloned = cloneArray(propertyA); + cloned[5] = cloned[5].concat(propertyB[5]); + + return cloned; +} + +function restructure(tokens, context) { + var options = context.options; + var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; + var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; + var mergeLimit = options.compatibility.selectors.mergeLimit; + var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; + var specificityCache = context.cache.specificity; + var movableTokens = {}; + var movedProperties = []; + var multiPropertyMoveCache = {}; + var movedToBeDropped = []; + var maxCombinationsLevel = 2; + var ID_JOIN_CHARACTER = '%'; + + function sendToMultiPropertyMoveCache(position, movedProperty, allFits) { + for (var i = allFits.length - 1; i >= 0; i--) { + var fit = allFits[i][0]; + var id = addToCache(movedProperty, fit); + + if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) { + removeAllMatchingFromCache(id); + break; + } + } + } + + function addToCache(movedProperty, fit) { + var id = cacheId(fit); + multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || []; + multiPropertyMoveCache[id].push([movedProperty, fit]); + return id; + } + + function removeAllMatchingFromCache(matchId) { + var matchSelectors = matchId.split(ID_JOIN_CHARACTER); + var forRemoval = []; + var i; + + for (var id in multiPropertyMoveCache) { + var selectors = id.split(ID_JOIN_CHARACTER); + for (i = selectors.length - 1; i >= 0; i--) { + if (matchSelectors.indexOf(selectors[i]) > -1) { + forRemoval.push(id); + break; + } + } + } + + for (i = forRemoval.length - 1; i >= 0; i--) { + delete multiPropertyMoveCache[forRemoval[i]]; + } + } + + function cacheId(cachedTokens) { + var id = []; + for (var i = 0, l = cachedTokens.length; i < l; i++) { + id.push(serializeRules(cachedTokens[i][1])); + } + return id.join(ID_JOIN_CHARACTER); + } + + function tokensToMerge(sourceTokens) { + var uniqueTokensWithBody = []; + var mergeableTokens = []; + + for (var i = sourceTokens.length - 1; i >= 0; i--) { + if (!isMergeable(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) { + continue; + } + + mergeableTokens.unshift(sourceTokens[i]); + if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1) + uniqueTokensWithBody.push(sourceTokens[i]); + } + + return uniqueTokensWithBody.length > 1 ? + mergeableTokens : + []; + } + + function shortenIfPossible(position, movedProperty) { + var name = movedProperty[0]; + var value = movedProperty[1]; + var key = movedProperty[4]; + var valueSize = name.length + value.length + 1; + var allSelectors = []; + var qualifiedTokens = []; + + var mergeableTokens = tokensToMerge(movableTokens[key]); + if (mergeableTokens.length < 2) + return; + + var allFits = findAllFits(mergeableTokens, valueSize, 1); + var bestFit = allFits[0]; + if (bestFit[1] > 0) + return sendToMultiPropertyMoveCache(position, movedProperty, allFits); + + for (var i = bestFit[0].length - 1; i >=0; i--) { + allSelectors = bestFit[0][i][1].concat(allSelectors); + qualifiedTokens.unshift(bestFit[0][i]); + } + + allSelectors = tidyRuleDuplicates(allSelectors); + dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens); + } + + function fitSorter(fit1, fit2) { + return fit1[1] > fit2[1] ? 1 : (fit1[1] == fit2[1] ? 0 : -1); + } + + function findAllFits(mergeableTokens, propertySize, propertiesCount) { + var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1); + return combinations.sort(fitSorter); + } + + function allCombinations(tokensVariant, propertySize, propertiesCount, level) { + var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]]; + if (tokensVariant.length > 2 && level > 0) { + for (var i = tokensVariant.length - 1; i >= 0; i--) { + var subVariant = Array.prototype.slice.call(tokensVariant, 0); + subVariant.splice(i, 1); + differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1)); + } + } + + return differenceVariants; + } + + function sizeDifference(tokensVariant, propertySize, propertiesCount) { + var allSelectorsSize = 0; + for (var i = tokensVariant.length - 1; i >= 0; i--) { + allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? serializeRules(tokensVariant[i][1]).length : -1; + } + return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1; + } + + function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) { + var i, j, k, m; + var allProperties = []; + + for (i = mergeableTokens.length - 1; i >= 0; i--) { + var mergeableToken = mergeableTokens[i]; + + for (j = mergeableToken[2].length - 1; j >= 0; j--) { + var mergeableProperty = mergeableToken[2][j]; + + for (k = 0, m = properties.length; k < m; k++) { + var property = properties[k]; + + var mergeablePropertyName = mergeableProperty[1][1]; + var propertyName = property[0]; + var propertyBody = property[4]; + if (mergeablePropertyName == propertyName && serializeBody([mergeableProperty]) == propertyBody) { + mergeableToken[2].splice(j, 1); + break; + } + } + } + } + + for (i = properties.length - 1; i >= 0; i--) { + allProperties.unshift(properties[i][3]); + } + + var newToken = [Token.RULE, allSelectors, allProperties]; + tokens.splice(position, 0, newToken); + } + + function dropPropertiesAt(position, movedProperty) { + var key = movedProperty[4]; + var toMove = movableTokens[key]; + + if (toMove && toMove.length > 1) { + if (!shortenMultiMovesIfPossible(position, movedProperty)) + shortenIfPossible(position, movedProperty); + } + } + + function shortenMultiMovesIfPossible(position, movedProperty) { + var candidates = []; + var propertiesAndMergableTokens = []; + var key = movedProperty[4]; + var j, k; + + var mergeableTokens = tokensToMerge(movableTokens[key]); + if (mergeableTokens.length < 2) + return; + + movableLoop: + for (var value in movableTokens) { + var tokensList = movableTokens[value]; + + for (j = mergeableTokens.length - 1; j >= 0; j--) { + if (tokensList.indexOf(mergeableTokens[j]) == -1) + continue movableLoop; + } + + candidates.push(value); + } + + if (candidates.length < 2) + return false; + + for (j = candidates.length - 1; j >= 0; j--) { + for (k = movedProperties.length - 1; k >= 0; k--) { + if (movedProperties[k][4] == candidates[j]) { + propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]); + break; + } + } + } + + return processMultiPropertyMove(position, propertiesAndMergableTokens); + } + + function processMultiPropertyMove(position, propertiesAndMergableTokens) { + var valueSize = 0; + var properties = []; + var property; + + for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) { + property = propertiesAndMergableTokens[i][0]; + var fullValue = property[4]; + valueSize += fullValue.length + (i > 0 ? 1 : 0); + + properties.push(property); + } + + var mergeableTokens = propertiesAndMergableTokens[0][1]; + var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0]; + if (bestFit[1] > 0) + return false; + + var allSelectors = []; + var qualifiedTokens = []; + for (i = bestFit[0].length - 1; i >= 0; i--) { + allSelectors = bestFit[0][i][1].concat(allSelectors); + qualifiedTokens.unshift(bestFit[0][i]); + } + + allSelectors = tidyRuleDuplicates(allSelectors); + dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens); + + for (i = properties.length - 1; i >= 0; i--) { + property = properties[i]; + var index = movedProperties.indexOf(property); + + delete movableTokens[property[4]]; + + if (index > -1 && movedToBeDropped.indexOf(index) == -1) + movedToBeDropped.push(index); + } + + return true; + } + + function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) { + var propertyName = property[0]; + var movedPropertyName = movedProperty[0]; + if (propertyName != movedPropertyName) + return false; + + var key = movedProperty[4]; + var toMove = movableTokens[key]; + return toMove && toMove.indexOf(token) > -1; + } + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + var isRule; + var j, k, m; + var samePropertyAt; + + if (token[0] == Token.RULE) { + isRule = true; + } else if (token[0] == Token.NESTED_BLOCK) { + isRule = false; + } else { + continue; + } + + // We cache movedProperties.length as it may change in the loop + var movedCount = movedProperties.length; + + var properties = extractProperties(token); + movedToBeDropped = []; + + var unmovableInCurrentToken = []; + for (j = properties.length - 1; j >= 0; j--) { + for (k = j - 1; k >= 0; k--) { + if (!canReorderSingle(properties[j], properties[k], specificityCache)) { + unmovableInCurrentToken.push(j); + break; + } + } + } + + for (j = properties.length - 1; j >= 0; j--) { + var property = properties[j]; + var movedSameProperty = false; + + for (k = 0; k < movedCount; k++) { + var movedProperty = movedProperties[k]; + + if (movedToBeDropped.indexOf(k) == -1 && (!canReorderSingle(property, movedProperty, specificityCache) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) || + movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)) { + dropPropertiesAt(i + 1, movedProperty, token); + + if (movedToBeDropped.indexOf(k) == -1) { + movedToBeDropped.push(k); + delete movableTokens[movedProperty[4]]; + } + } + + if (!movedSameProperty) { + movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1]; + + if (movedSameProperty) { + samePropertyAt = k; + } + } + } + + if (!isRule || unmovableInCurrentToken.indexOf(j) > -1) + continue; + + var key = property[4]; + + if (movedSameProperty && movedProperties[samePropertyAt][5].length + property[5].length > mergeLimit) { + dropPropertiesAt(i + 1, movedProperties[samePropertyAt]); + movedProperties.splice(samePropertyAt, 1); + movableTokens[key] = [token]; + movedSameProperty = false; + } else { + movableTokens[key] = movableTokens[key] || []; + movableTokens[key].push(token); + } + + if (movedSameProperty) { + movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property); + } else { + movedProperties.push(property); + } + } + + movedToBeDropped = movedToBeDropped.sort(naturalSorter); + for (j = 0, m = movedToBeDropped.length; j < m; j++) { + var dropAt = movedToBeDropped[j] - j; + movedProperties.splice(dropAt, 1); + } + } + + var position = tokens[0] && tokens[0][0] == Token.AT_RULE && tokens[0][1].indexOf('@charset') === 0 ? 1 : 0; + for (; position < tokens.length - 1; position++) { + var isImportRule = tokens[position][0] === Token.AT_RULE && tokens[position][1].indexOf('@import') === 0; + var isComment = tokens[position][0] === Token.COMMENT; + if (!(isImportRule || isComment)) + break; + } + + for (i = 0; i < movedProperties.length; i++) { + dropPropertiesAt(position, movedProperties[i]); + } +} + +module.exports = restructure; diff --git a/node_modules/clean-css/lib/optimizer/level-2/rules-overlap.js b/node_modules/clean-css/lib/optimizer/level-2/rules-overlap.js new file mode 100644 index 0000000..811a517 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/rules-overlap.js @@ -0,0 +1,32 @@ +var MODIFIER_PATTERN = /\-\-.+$/; + +function rulesOverlap(rule1, rule2, bemMode) { + var scope1; + var scope2; + var i, l; + var j, m; + + for (i = 0, l = rule1.length; i < l; i++) { + scope1 = rule1[i][1]; + + for (j = 0, m = rule2.length; j < m; j++) { + scope2 = rule2[j][1]; + + if (scope1 == scope2) { + return true; + } + + if (bemMode && withoutModifiers(scope1) == withoutModifiers(scope2)) { + return true; + } + } + } + + return false; +} + +function withoutModifiers(scope) { + return scope.replace(MODIFIER_PATTERN, ''); +} + +module.exports = rulesOverlap; diff --git a/node_modules/clean-css/lib/optimizer/level-2/specificities-overlap.js b/node_modules/clean-css/lib/optimizer/level-2/specificities-overlap.js new file mode 100644 index 0000000..bde0374 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/specificities-overlap.js @@ -0,0 +1,34 @@ +var specificity = require('./specificity'); + +function specificitiesOverlap(selector1, selector2, cache) { + var specificity1; + var specificity2; + var i, l; + var j, m; + + for (i = 0, l = selector1.length; i < l; i++) { + specificity1 = findSpecificity(selector1[i][1], cache); + + for (j = 0, m = selector2.length; j < m; j++) { + specificity2 = findSpecificity(selector2[j][1], cache); + + if (specificity1[0] === specificity2[0] && specificity1[1] === specificity2[1] && specificity1[2] === specificity2[2]) { + return true; + } + } + } + + return false; +} + +function findSpecificity(selector, cache) { + var value; + + if (!(selector in cache)) { + cache[selector] = value = specificity(selector); + } + + return value || cache[selector]; +} + +module.exports = specificitiesOverlap; diff --git a/node_modules/clean-css/lib/optimizer/level-2/specificity.js b/node_modules/clean-css/lib/optimizer/level-2/specificity.js new file mode 100644 index 0000000..bbd224f --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/specificity.js @@ -0,0 +1,77 @@ +var Marker = require('../../tokenizer/marker'); + +var Selector = { + ADJACENT_SIBLING: '+', + DESCENDANT: '>', + DOT: '.', + HASH: '#', + NON_ADJACENT_SIBLING: '~', + PSEUDO: ':' +}; + +var LETTER_PATTERN = /[a-zA-Z]/; +var NOT_PREFIX = ':not('; +var SEPARATOR_PATTERN = /[\s,\(>~\+]/; + +function specificity(selector) { + var result = [0, 0, 0]; + var character; + var isEscaped; + var isSingleQuoted; + var isDoubleQuoted; + var roundBracketLevel = 0; + var couldIntroduceNewTypeSelector; + var withinNotPseudoClass = false; + var wasPseudoClass = false; + var i, l; + + for (i = 0, l = selector.length; i < l; i++) { + character = selector[i]; + + if (isEscaped) { + // noop + } else if (character == Marker.SINGLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) { + isSingleQuoted = true; + } else if (character == Marker.SINGLE_QUOTE && !isDoubleQuoted && isSingleQuoted) { + isSingleQuoted = false; + } else if (character == Marker.DOUBLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) { + isDoubleQuoted = true; + } else if (character == Marker.DOUBLE_QUOTE && isDoubleQuoted && !isSingleQuoted) { + isDoubleQuoted = false; + } else if (isSingleQuoted || isDoubleQuoted) { + continue; + } else if (roundBracketLevel > 0 && !withinNotPseudoClass) { + // noop + } else if (character == Marker.OPEN_ROUND_BRACKET) { + roundBracketLevel++; + } else if (character == Marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1) { + roundBracketLevel--; + withinNotPseudoClass = false; + } else if (character == Marker.CLOSE_ROUND_BRACKET) { + roundBracketLevel--; + } else if (character == Selector.HASH) { + result[0]++; + } else if (character == Selector.DOT || character == Marker.OPEN_SQUARE_BRACKET) { + result[1]++; + } else if (character == Selector.PSEUDO && !wasPseudoClass && !isNotPseudoClass(selector, i)) { + result[1]++; + withinNotPseudoClass = false; + } else if (character == Selector.PSEUDO) { + withinNotPseudoClass = true; + } else if ((i === 0 || couldIntroduceNewTypeSelector) && LETTER_PATTERN.test(character)) { + result[2]++; + } + + isEscaped = character == Marker.BACK_SLASH; + wasPseudoClass = character == Selector.PSEUDO; + couldIntroduceNewTypeSelector = !isEscaped && SEPARATOR_PATTERN.test(character); + } + + return result; +} + +function isNotPseudoClass(selector, index) { + return selector.indexOf(NOT_PREFIX, index) === index; +} + +module.exports = specificity; diff --git a/node_modules/clean-css/lib/optimizer/level-2/tidy-rule-duplicates.js b/node_modules/clean-css/lib/optimizer/level-2/tidy-rule-duplicates.js new file mode 100644 index 0000000..30a9c21 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/level-2/tidy-rule-duplicates.js @@ -0,0 +1,21 @@ +function ruleSorter(s1, s2) { + return s1[1] > s2[1] ? 1 : -1; +} + +function tidyRuleDuplicates(rules) { + var list = []; + var repeated = []; + + for (var i = 0, l = rules.length; i < l; i++) { + var rule = rules[i]; + + if (repeated.indexOf(rule[1]) == -1) { + repeated.push(rule[1]); + list.push(rule); + } + } + + return list.sort(ruleSorter); +} + +module.exports = tidyRuleDuplicates; diff --git a/node_modules/clean-css/lib/optimizer/remove-unused.js b/node_modules/clean-css/lib/optimizer/remove-unused.js new file mode 100644 index 0000000..7b90c40 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/remove-unused.js @@ -0,0 +1,11 @@ +function removeUnused(properties) { + for (var i = properties.length - 1; i >= 0; i--) { + var property = properties[i]; + + if (property.unused) { + property.all.splice(property.position, 1); + } + } +} + +module.exports = removeUnused; diff --git a/node_modules/clean-css/lib/optimizer/restore-from-optimizing.js b/node_modules/clean-css/lib/optimizer/restore-from-optimizing.js new file mode 100644 index 0000000..ebd69c2 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/restore-from-optimizing.js @@ -0,0 +1,69 @@ +var Hack = require('./hack'); + +var Marker = require('../tokenizer/marker'); + +var ASTERISK_HACK = '*'; +var BACKSLASH_HACK = '\\'; +var IMPORTANT_TOKEN = '!important'; +var UNDERSCORE_HACK = '_'; +var BANG_HACK = '!ie'; + +function restoreFromOptimizing(properties, restoreCallback) { + var property; + var restored; + var current; + var i; + + for (i = properties.length - 1; i >= 0; i--) { + property = properties[i]; + + if (property.unused) { + continue; + } + + if (!property.dirty && !property.important && !property.hack) { + continue; + } + + if (restoreCallback) { + restored = restoreCallback(property); + property.value = restored; + } else { + restored = property.value; + } + + if (property.important) { + restoreImportant(property); + } + + if (property.hack) { + restoreHack(property); + } + + if ('all' in property) { + current = property.all[property.position]; + current[1][1] = property.name; + + current.splice(2, current.length - 1); + Array.prototype.push.apply(current, restored); + } + } +} + +function restoreImportant(property) { + property.value[property.value.length - 1][1] += IMPORTANT_TOKEN; +} + +function restoreHack(property) { + if (property.hack[0] == Hack.UNDERSCORE) { + property.name = UNDERSCORE_HACK + property.name; + } else if (property.hack[0] == Hack.ASTERISK) { + property.name = ASTERISK_HACK + property.name; + } else if (property.hack[0] == Hack.BACKSLASH) { + property.value[property.value.length - 1][1] += BACKSLASH_HACK + property.hack[1]; + } else if (property.hack[0] == Hack.BANG) { + property.value[property.value.length - 1][1] += Marker.SPACE + BANG_HACK; + } +} + +module.exports = restoreFromOptimizing; diff --git a/node_modules/clean-css/lib/optimizer/validator.js b/node_modules/clean-css/lib/optimizer/validator.js new file mode 100644 index 0000000..fd3fb97 --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/validator.js @@ -0,0 +1,529 @@ +var functionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(.*?\\)'; +var functionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(.*?\\)'; +var variableRegexStr = 'var\\(\\-\\-[^\\)]+\\)'; +var functionAnyRegexStr = '(' + variableRegexStr + '|' + functionNoVendorRegexStr + '|' + functionVendorRegexStr + ')'; + +var calcRegex = new RegExp('^(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)$', 'i'); +var decimalRegex = /[0-9]/; +var functionAnyRegex = new RegExp('^' + functionAnyRegexStr + '$', 'i'); +var hslColorRegex = /^hsl\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+\s{0,31}\)$/; +var identifierRegex = /^(\-[a-z0-9_][a-z0-9\-_]*|[a-z][a-z0-9\-_]*)$/i; +var namedEntityRegex = /^[a-z]+$/i; +var prefixRegex = /^-([a-z0-9]|-)*$/i; +var rgbColorRegex = /^rgb\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31}\)|rgba\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\.\d]+\s{0,31}\)$/; +var timingFunctionRegex = /^(cubic\-bezier|steps)\([^\)]+\)$/; +var validTimeUnits = ['ms', 's']; +var urlRegex = /^url\([\s\S]+\)$/i; +var variableRegex = new RegExp('^' + variableRegexStr + '$', 'i'); + +var eightValueColorRegex = /^#[0-9a-f]{8}$/i; +var fourValueColorRegex = /^#[0-9a-f]{4}$/i; +var sixValueColorRegex = /^#[0-9a-f]{6}$/i; +var threeValueColorRegex = /^#[0-9a-f]{3}$/i; + +var DECIMAL_DOT = '.'; +var MINUS_SIGN = '-'; +var PLUS_SIGN = '+'; + +var Keywords = { + '^': [ + 'inherit', + 'initial', + 'unset' + ], + '*-style': [ + 'auto', + 'dashed', + 'dotted', + 'double', + 'groove', + 'hidden', + 'inset', + 'none', + 'outset', + 'ridge', + 'solid' + ], + '*-timing-function': [ + 'ease', + 'ease-in', + 'ease-in-out', + 'ease-out', + 'linear', + 'step-end', + 'step-start' + ], + 'animation-direction': [ + 'alternate', + 'alternate-reverse', + 'normal', + 'reverse' + ], + 'animation-fill-mode': [ + 'backwards', + 'both', + 'forwards', + 'none' + ], + 'animation-iteration-count': [ + 'infinite' + ], + 'animation-name': [ + 'none' + ], + 'animation-play-state': [ + 'paused', + 'running' + ], + 'background-attachment': [ + 'fixed', + 'inherit', + 'local', + 'scroll' + ], + 'background-clip': [ + 'border-box', + 'content-box', + 'inherit', + 'padding-box', + 'text' + ], + 'background-origin': [ + 'border-box', + 'content-box', + 'inherit', + 'padding-box' + ], + 'background-position': [ + 'bottom', + 'center', + 'left', + 'right', + 'top' + ], + 'background-repeat': [ + 'no-repeat', + 'inherit', + 'repeat', + 'repeat-x', + 'repeat-y', + 'round', + 'space' + ], + 'background-size': [ + 'auto', + 'cover', + 'contain' + ], + 'border-collapse': [ + 'collapse', + 'inherit', + 'separate' + ], + 'bottom': [ + 'auto' + ], + 'clear': [ + 'both', + 'left', + 'none', + 'right' + ], + 'color': [ + 'transparent' + ], + 'cursor': [ + 'all-scroll', + 'auto', + 'col-resize', + 'crosshair', + 'default', + 'e-resize', + 'help', + 'move', + 'n-resize', + 'ne-resize', + 'no-drop', + 'not-allowed', + 'nw-resize', + 'pointer', + 'progress', + 'row-resize', + 's-resize', + 'se-resize', + 'sw-resize', + 'text', + 'vertical-text', + 'w-resize', + 'wait' + ], + 'display': [ + 'block', + 'inline', + 'inline-block', + 'inline-table', + 'list-item', + 'none', + 'table', + 'table-caption', + 'table-cell', + 'table-column', + 'table-column-group', + 'table-footer-group', + 'table-header-group', + 'table-row', + 'table-row-group' + ], + 'float': [ + 'left', + 'none', + 'right' + ], + 'left': [ + 'auto' + ], + 'font': [ + 'caption', + 'icon', + 'menu', + 'message-box', + 'small-caption', + 'status-bar', + 'unset' + ], + 'font-size': [ + 'large', + 'larger', + 'medium', + 'small', + 'smaller', + 'x-large', + 'x-small', + 'xx-large', + 'xx-small' + ], + 'font-stretch': [ + 'condensed', + 'expanded', + 'extra-condensed', + 'extra-expanded', + 'normal', + 'semi-condensed', + 'semi-expanded', + 'ultra-condensed', + 'ultra-expanded' + ], + 'font-style': [ + 'italic', + 'normal', + 'oblique' + ], + 'font-variant': [ + 'normal', + 'small-caps' + ], + 'font-weight': [ + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900', + 'bold', + 'bolder', + 'lighter', + 'normal' + ], + 'line-height': [ + 'normal' + ], + 'list-style-position': [ + 'inside', + 'outside' + ], + 'list-style-type': [ + 'armenian', + 'circle', + 'decimal', + 'decimal-leading-zero', + 'disc', + 'decimal|disc', // this is the default value of list-style-type, see comment in compactable.js + 'georgian', + 'lower-alpha', + 'lower-greek', + 'lower-latin', + 'lower-roman', + 'none', + 'square', + 'upper-alpha', + 'upper-latin', + 'upper-roman' + ], + 'overflow': [ + 'auto', + 'hidden', + 'scroll', + 'visible' + ], + 'position': [ + 'absolute', + 'fixed', + 'relative', + 'static' + ], + 'right': [ + 'auto' + ], + 'text-align': [ + 'center', + 'justify', + 'left', + 'left|right', // this is the default value of list-style-type, see comment in compactable.js + 'right' + ], + 'text-decoration': [ + 'line-through', + 'none', + 'overline', + 'underline' + ], + 'text-overflow': [ + 'clip', + 'ellipsis' + ], + 'top': [ + 'auto' + ], + 'vertical-align': [ + 'baseline', + 'bottom', + 'middle', + 'sub', + 'super', + 'text-bottom', + 'text-top', + 'top' + ], + 'visibility': [ + 'collapse', + 'hidden', + 'visible' + ], + 'white-space': [ + 'normal', + 'nowrap', + 'pre' + ], + 'width': [ + 'inherit', + 'initial', + 'medium', + 'thick', + 'thin' + ] +}; + +var Units = [ + '%', + 'ch', + 'cm', + 'em', + 'ex', + 'in', + 'mm', + 'pc', + 'pt', + 'px', + 'rem', + 'vh', + 'vm', + 'vmax', + 'vmin', + 'vw' +]; + +function isColor(value) { + return value != 'auto' && + ( + isKeyword('color')(value) || + isHexColor(value) || + isColorFunction(value) || + isNamedEntity(value) + ); +} + +function isColorFunction(value) { + return isRgbColor(value) || isHslColor(value); +} + +function isDynamicUnit(value) { + return calcRegex.test(value); +} + +function isFunction(value) { + return functionAnyRegex.test(value); +} + +function isHexColor(value) { + return threeValueColorRegex.test(value) || fourValueColorRegex.test(value) || sixValueColorRegex.test(value) || eightValueColorRegex.test(value); +} + +function isHslColor(value) { + return hslColorRegex.test(value); +} + +function isIdentifier(value) { + return identifierRegex.test(value); +} + +function isImage(value) { + return value == 'none' || value == 'inherit' || isUrl(value); +} + +function isKeyword(propertyName) { + return function(value) { + return Keywords[propertyName].indexOf(value) > -1; + }; +} + +function isNamedEntity(value) { + return namedEntityRegex.test(value); +} + +function isNumber(value) { + return scanForNumber(value) == value.length; +} + +function isRgbColor(value) { + return rgbColorRegex.test(value); +} + +function isPrefixed(value) { + return prefixRegex.test(value); +} + +function isPositiveNumber(value) { + return isNumber(value) && + parseFloat(value) >= 0; +} + +function isVariable(value) { + return variableRegex.test(value); +} + +function isTime(value) { + var numberUpTo = scanForNumber(value); + + return numberUpTo == value.length && parseInt(value) === 0 || + numberUpTo > -1 && validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1; +} + +function isTimingFunction() { + var isTimingFunctionKeyword = isKeyword('*-timing-function'); + + return function (value) { + return isTimingFunctionKeyword(value) || timingFunctionRegex.test(value); + }; +} + +function isUnit(validUnits, value) { + var numberUpTo = scanForNumber(value); + + return numberUpTo == value.length && parseInt(value) === 0 || + numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1)) > -1 || + value == 'auto' || + value == 'inherit'; +} + +function isUrl(value) { + return urlRegex.test(value); +} + +function isZIndex(value) { + return value == 'auto' || + isNumber(value) || + isKeyword('^')(value); +} + +function scanForNumber(value) { + var hasDot = false; + var hasSign = false; + var character; + var i, l; + + for (i = 0, l = value.length; i < l; i++) { + character = value[i]; + + if (i === 0 && (character == PLUS_SIGN || character == MINUS_SIGN)) { + hasSign = true; + } else if (i > 0 && hasSign && (character == PLUS_SIGN || character == MINUS_SIGN)) { + return i - 1; + } else if (character == DECIMAL_DOT && !hasDot) { + hasDot = true; + } else if (character == DECIMAL_DOT && hasDot) { + return i - 1; + } else if (decimalRegex.test(character)) { + continue; + } else { + return i - 1; + } + } + + return i; +} + +function validator(compatibility) { + var validUnits = Units.slice(0).filter(function (value) { + return !(value in compatibility.units) || compatibility.units[value] === true; + }); + + return { + colorOpacity: compatibility.colors.opacity, + isAnimationDirectionKeyword: isKeyword('animation-direction'), + isAnimationFillModeKeyword: isKeyword('animation-fill-mode'), + isAnimationIterationCountKeyword: isKeyword('animation-iteration-count'), + isAnimationNameKeyword: isKeyword('animation-name'), + isAnimationPlayStateKeyword: isKeyword('animation-play-state'), + isTimingFunction: isTimingFunction(), + isBackgroundAttachmentKeyword: isKeyword('background-attachment'), + isBackgroundClipKeyword: isKeyword('background-clip'), + isBackgroundOriginKeyword: isKeyword('background-origin'), + isBackgroundPositionKeyword: isKeyword('background-position'), + isBackgroundRepeatKeyword: isKeyword('background-repeat'), + isBackgroundSizeKeyword: isKeyword('background-size'), + isColor: isColor, + isColorFunction: isColorFunction, + isDynamicUnit: isDynamicUnit, + isFontKeyword: isKeyword('font'), + isFontSizeKeyword: isKeyword('font-size'), + isFontStretchKeyword: isKeyword('font-stretch'), + isFontStyleKeyword: isKeyword('font-style'), + isFontVariantKeyword: isKeyword('font-variant'), + isFontWeightKeyword: isKeyword('font-weight'), + isFunction: isFunction, + isGlobal: isKeyword('^'), + isHslColor: isHslColor, + isIdentifier: isIdentifier, + isImage: isImage, + isKeyword: isKeyword, + isLineHeightKeyword: isKeyword('line-height'), + isListStylePositionKeyword: isKeyword('list-style-position'), + isListStyleTypeKeyword: isKeyword('list-style-type'), + isNumber: isNumber, + isPrefixed: isPrefixed, + isPositiveNumber: isPositiveNumber, + isRgbColor: isRgbColor, + isStyleKeyword: isKeyword('*-style'), + isTime: isTime, + isUnit: isUnit.bind(null, validUnits), + isUrl: isUrl, + isVariable: isVariable, + isWidth: isKeyword('width'), + isZIndex: isZIndex + }; +} + +module.exports = validator; diff --git a/node_modules/clean-css/lib/optimizer/wrap-for-optimizing.js b/node_modules/clean-css/lib/optimizer/wrap-for-optimizing.js new file mode 100644 index 0000000..c516fbc --- /dev/null +++ b/node_modules/clean-css/lib/optimizer/wrap-for-optimizing.js @@ -0,0 +1,191 @@ +var Hack = require('./hack'); + +var Marker = require('../tokenizer/marker'); +var Token = require('../tokenizer/token'); + +var Match = { + ASTERISK: '*', + BACKSLASH: '\\', + BANG: '!', + BANG_SUFFIX_PATTERN: /!\w+$/, + IMPORTANT_TOKEN: '!important', + IMPORTANT_TOKEN_PATTERN: new RegExp('!important$', 'i'), + IMPORTANT_WORD: 'important', + IMPORTANT_WORD_PATTERN: new RegExp('important$', 'i'), + SUFFIX_BANG_PATTERN: /!$/, + UNDERSCORE: '_', + VARIABLE_REFERENCE_PATTERN: /var\(--.+\)$/ +}; + +function wrapAll(properties, includeVariable, skipProperties) { + var wrapped = []; + var single; + var property; + var i; + + for (i = properties.length - 1; i >= 0; i--) { + property = properties[i]; + + if (property[0] != Token.PROPERTY) { + continue; + } + + if (!includeVariable && someVariableReferences(property)) { + continue; + } + + if (skipProperties && skipProperties.indexOf(property[1][1]) > -1) { + continue; + } + + single = wrapSingle(property); + single.all = properties; + single.position = i; + wrapped.unshift(single); + } + + return wrapped; +} + +function someVariableReferences(property) { + var i, l; + var value; + + // skipping `property` and property name tokens + for (i = 2, l = property.length; i < l; i++) { + value = property[i]; + + if (value[0] != Token.PROPERTY_VALUE) { + continue; + } + + if (isVariableReference(value[1])) { + return true; + } + } + + return false; +} + +function isVariableReference(value) { + return Match.VARIABLE_REFERENCE_PATTERN.test(value); +} + +function isMultiplex(property) { + var value; + var i, l; + + for (i = 3, l = property.length; i < l; i++) { + value = property[i]; + + if (value[0] == Token.PROPERTY_VALUE && (value[1] == Marker.COMMA || value[1] == Marker.FORWARD_SLASH)) { + return true; + } + } + + return false; +} + +function hackFrom(property) { + var match = false; + var name = property[1][1]; + var lastValue = property[property.length - 1]; + + if (name[0] == Match.UNDERSCORE) { + match = [Hack.UNDERSCORE]; + } else if (name[0] == Match.ASTERISK) { + match = [Hack.ASTERISK]; + } else if (lastValue[1][0] == Match.BANG && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN)) { + match = [Hack.BANG]; + } else if (lastValue[1].indexOf(Match.BANG) > 0 && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN) && Match.BANG_SUFFIX_PATTERN.test(lastValue[1])) { + match = [Hack.BANG]; + } else if (lastValue[1].indexOf(Match.BACKSLASH) > 0 && lastValue[1].indexOf(Match.BACKSLASH) == lastValue[1].length - Match.BACKSLASH.length - 1) { + match = [Hack.BACKSLASH, lastValue[1].substring(lastValue[1].indexOf(Match.BACKSLASH) + 1)]; + } else if (lastValue[1].indexOf(Match.BACKSLASH) === 0 && lastValue[1].length == 2) { + match = [Hack.BACKSLASH, lastValue[1].substring(1)]; + } + + return match; +} + +function isImportant(property) { + if (property.length < 3) + return false; + + var lastValue = property[property.length - 1]; + if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) { + return true; + } else if (Match.IMPORTANT_WORD_PATTERN.test(lastValue[1]) && Match.SUFFIX_BANG_PATTERN.test(property[property.length - 2][1])) { + return true; + } + + return false; +} + +function stripImportant(property) { + var lastValue = property[property.length - 1]; + var oneButLastValue = property[property.length - 2]; + + if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) { + lastValue[1] = lastValue[1].replace(Match.IMPORTANT_TOKEN_PATTERN, ''); + } else { + lastValue[1] = lastValue[1].replace(Match.IMPORTANT_WORD_PATTERN, ''); + oneButLastValue[1] = oneButLastValue[1].replace(Match.SUFFIX_BANG_PATTERN, ''); + } + + if (lastValue[1].length === 0) { + property.pop(); + } + + if (oneButLastValue[1].length === 0) { + property.pop(); + } +} + +function stripPrefixHack(property) { + property[1][1] = property[1][1].substring(1); +} + +function stripSuffixHack(property, hackFrom) { + var lastValue = property[property.length - 1]; + lastValue[1] = lastValue[1] + .substring(0, lastValue[1].indexOf(hackFrom[0] == Hack.BACKSLASH ? Match.BACKSLASH : Match.BANG)) + .trim(); + + if (lastValue[1].length === 0) { + property.pop(); + } +} + +function wrapSingle(property) { + var importantProperty = isImportant(property); + if (importantProperty) { + stripImportant(property); + } + + var whichHack = hackFrom(property); + if (whichHack[0] == Hack.ASTERISK || whichHack[0] == Hack.UNDERSCORE) { + stripPrefixHack(property); + } else if (whichHack[0] == Hack.BACKSLASH || whichHack[0] == Hack.BANG) { + stripSuffixHack(property, whichHack); + } + + return { + block: property[2] && property[2][0] == Token.PROPERTY_BLOCK, + components: [], + dirty: false, + hack: whichHack, + important: importantProperty, + name: property[1][1], + multiplex: property.length > 3 ? isMultiplex(property) : false, + position: 0, + shorthand: false, + unused: false, + value: property.slice(2) + }; +} + +module.exports = { + all: wrapAll, + single: wrapSingle +}; diff --git a/node_modules/clean-css/lib/options/compatibility.js b/node_modules/clean-css/lib/options/compatibility.js new file mode 100644 index 0000000..8e6a119 --- /dev/null +++ b/node_modules/clean-css/lib/options/compatibility.js @@ -0,0 +1,183 @@ +var DEFAULTS = { + '*': { + colors: { + opacity: true // rgba / hsla + }, + properties: { + backgroundClipMerging: true, // background-clip to shorthand + backgroundOriginMerging: true, // background-origin to shorthand + backgroundSizeMerging: true, // background-size to shorthand + colors: true, // any kind of color transformations, like `#ff00ff` to `#f0f` or `#fff` into `red` + ieBangHack: false, // !ie suffix hacks on IE<8 + ieFilters: false, // whether to preserve `filter` and `-ms-filter` properties + iePrefixHack: false, // underscore / asterisk prefix hacks on IE + ieSuffixHack: false, // \9 suffix hacks on IE6-9 + merging: true, // merging properties into one + shorterLengthUnits: false, // optimize pixel units into `pt`, `pc` or `in` units + spaceAfterClosingBrace: true, // 'url() no-repeat' to 'url()no-repeat' + urlQuotes: false, // whether to wrap content of `url()` into quotes or not + zeroUnits: true // 0[unit] -> 0 + }, + selectors: { + adjacentSpace: false, // div+ nav Android stock browser hack + ie7Hack: false, // *+html hack + mergeablePseudoClasses: [ + ':active', + ':after', + ':before', + ':empty', + ':checked', + ':disabled', + ':empty', + ':enabled', + ':first-child', + ':first-letter', + ':first-line', + ':first-of-type', + ':focus', + ':hover', + ':lang', + ':last-child', + ':last-of-type', + ':link', + ':not', + ':nth-child', + ':nth-last-child', + ':nth-last-of-type', + ':nth-of-type', + ':only-child', + ':only-of-type', + ':root', + ':target', + ':visited' + ], // selectors with these pseudo-classes can be merged as these are universally supported + mergeablePseudoElements: [ + '::after', + '::before', + '::first-letter', + '::first-line' + ], // selectors with these pseudo-elements can be merged as these are universally supported + mergeLimit: 8191, // number of rules that can be safely merged together + multiplePseudoMerging: true + }, + units: { + ch: true, + in: true, + pc: true, + pt: true, + rem: true, + vh: true, + vm: true, // vm is vmin on IE9+ see https://developer.mozilla.org/en-US/docs/Web/CSS/length + vmax: true, + vmin: true, + vw: true + } + } +}; + +DEFAULTS.ie11 = DEFAULTS['*']; + +DEFAULTS.ie10 = DEFAULTS['*']; + +DEFAULTS.ie9 = merge(DEFAULTS['*'], { + properties: { + ieFilters: true, + ieSuffixHack: true + } +}); + +DEFAULTS.ie8 = merge(DEFAULTS.ie9, { + colors: { + opacity: false + }, + properties: { + backgroundClipMerging: false, + backgroundOriginMerging: false, + backgroundSizeMerging: false, + iePrefixHack: true, + merging: false + }, + selectors: { + mergeablePseudoClasses: [ + ':after', + ':before', + ':first-child', + ':first-letter', + ':focus', + ':hover', + ':visited' + ], + mergeablePseudoElements: [] + }, + units: { + ch: false, + rem: false, + vh: false, + vm: false, + vmax: false, + vmin: false, + vw: false + } +}); + +DEFAULTS.ie7 = merge(DEFAULTS.ie8, { + properties: { + ieBangHack: true + }, + selectors: { + ie7Hack: true, + mergeablePseudoClasses: [ + ':first-child', + ':first-letter', + ':hover', + ':visited' + ] + }, +}); + +function compatibilityFrom(source) { + return merge(DEFAULTS['*'], calculateSource(source)); +} + +function merge(source, target) { + for (var key in source) { + var value = source[key]; + + if (typeof value === 'object' && !Array.isArray(value)) { + target[key] = merge(value, target[key] || {}); + } else { + target[key] = key in target ? target[key] : value; + } + } + + return target; +} + +function calculateSource(source) { + if (typeof source == 'object') + return source; + + if (!/[,\+\-]/.test(source)) + return DEFAULTS[source] || DEFAULTS['*']; + + var parts = source.split(','); + var template = parts[0] in DEFAULTS ? + DEFAULTS[parts.shift()] : + DEFAULTS['*']; + + source = {}; + + parts.forEach(function (part) { + var isAdd = part[0] == '+'; + var key = part.substring(1).split('.'); + var group = key[0]; + var option = key[1]; + + source[group] = source[group] || {}; + source[group][option] = isAdd; + }); + + return merge(template, source); +} + +module.exports = compatibilityFrom; diff --git a/node_modules/clean-css/lib/options/fetch.js b/node_modules/clean-css/lib/options/fetch.js new file mode 100644 index 0000000..0aaad78 --- /dev/null +++ b/node_modules/clean-css/lib/options/fetch.js @@ -0,0 +1,7 @@ +var loadRemoteResource = require('../reader/load-remote-resource'); + +function fetchFrom(callback) { + return callback || loadRemoteResource; +} + +module.exports = fetchFrom; diff --git a/node_modules/clean-css/lib/options/format.js b/node_modules/clean-css/lib/options/format.js new file mode 100644 index 0000000..48c7efa --- /dev/null +++ b/node_modules/clean-css/lib/options/format.js @@ -0,0 +1,216 @@ +var systemLineBreak = require('os').EOL; + +var override = require('../utils/override'); + +var Breaks = { + AfterAtRule: 'afterAtRule', + AfterBlockBegins: 'afterBlockBegins', + AfterBlockEnds: 'afterBlockEnds', + AfterComment: 'afterComment', + AfterProperty: 'afterProperty', + AfterRuleBegins: 'afterRuleBegins', + AfterRuleEnds: 'afterRuleEnds', + BeforeBlockEnds: 'beforeBlockEnds', + BetweenSelectors: 'betweenSelectors' +}; + +var BreakWith = { + CarriageReturnLineFeed: '\r\n', + LineFeed: '\n', + System: systemLineBreak +}; + +var IndentWith = { + Space: ' ', + Tab: '\t' +}; + +var Spaces = { + AroundSelectorRelation: 'aroundSelectorRelation', + BeforeBlockBegins: 'beforeBlockBegins', + BeforeValue: 'beforeValue' +}; + +var DEFAULTS = { + breaks: breaks(false), + breakWith: BreakWith.System, + indentBy: 0, + indentWith: IndentWith.Space, + spaces: spaces(false), + wrapAt: false, + semicolonAfterLastProperty: false +}; + +var BEAUTIFY_ALIAS = 'beautify'; +var KEEP_BREAKS_ALIAS = 'keep-breaks'; + +var OPTION_SEPARATOR = ';'; +var OPTION_NAME_VALUE_SEPARATOR = ':'; +var HASH_VALUES_OPTION_SEPARATOR = ','; +var HASH_VALUES_NAME_VALUE_SEPARATOR = '='; + +var FALSE_KEYWORD_1 = 'false'; +var FALSE_KEYWORD_2 = 'off'; +var TRUE_KEYWORD_1 = 'true'; +var TRUE_KEYWORD_2 = 'on'; + +function breaks(value) { + var breakOptions = {}; + + breakOptions[Breaks.AfterAtRule] = value; + breakOptions[Breaks.AfterBlockBegins] = value; + breakOptions[Breaks.AfterBlockEnds] = value; + breakOptions[Breaks.AfterComment] = value; + breakOptions[Breaks.AfterProperty] = value; + breakOptions[Breaks.AfterRuleBegins] = value; + breakOptions[Breaks.AfterRuleEnds] = value; + breakOptions[Breaks.BeforeBlockEnds] = value; + breakOptions[Breaks.BetweenSelectors] = value; + + return breakOptions; +} + +function spaces(value) { + var spaceOptions = {}; + + spaceOptions[Spaces.AroundSelectorRelation] = value; + spaceOptions[Spaces.BeforeBlockBegins] = value; + spaceOptions[Spaces.BeforeValue] = value; + + return spaceOptions; +} + +function formatFrom(source) { + if (source === undefined || source === false) { + return false; + } + + if (typeof source == 'object' && 'breakWith' in source) { + source = override(source, { breakWith: mapBreakWith(source.breakWith) }); + } + + if (typeof source == 'object' && 'indentBy' in source) { + source = override(source, { indentBy: parseInt(source.indentBy) }); + } + + if (typeof source == 'object' && 'indentWith' in source) { + source = override(source, { indentWith: mapIndentWith(source.indentWith) }); + } + + if (typeof source == 'object') { + return override(DEFAULTS, source); + } + + if (typeof source == 'object') { + return override(DEFAULTS, source); + } + + if (typeof source == 'string' && source == BEAUTIFY_ALIAS) { + return override(DEFAULTS, { + breaks: breaks(true), + indentBy: 2, + spaces: spaces(true) + }); + } + + if (typeof source == 'string' && source == KEEP_BREAKS_ALIAS) { + return override(DEFAULTS, { + breaks: { + afterAtRule: true, + afterBlockBegins: true, + afterBlockEnds: true, + afterComment: true, + afterRuleEnds: true, + beforeBlockEnds: true + } + }); + } + + if (typeof source == 'string') { + return override(DEFAULTS, toHash(source)); + } + + return DEFAULTS; +} + +function toHash(string) { + return string + .split(OPTION_SEPARATOR) + .reduce(function (accumulator, directive) { + var parts = directive.split(OPTION_NAME_VALUE_SEPARATOR); + var name = parts[0]; + var value = parts[1]; + + if (name == 'breaks' || name == 'spaces') { + accumulator[name] = hashValuesToHash(value); + } else if (name == 'indentBy' || name == 'wrapAt') { + accumulator[name] = parseInt(value); + } else if (name == 'indentWith') { + accumulator[name] = mapIndentWith(value); + } else if (name == 'breakWith') { + accumulator[name] = mapBreakWith(value); + } + + return accumulator; + }, {}); +} + +function hashValuesToHash(string) { + return string + .split(HASH_VALUES_OPTION_SEPARATOR) + .reduce(function (accumulator, directive) { + var parts = directive.split(HASH_VALUES_NAME_VALUE_SEPARATOR); + var name = parts[0]; + var value = parts[1]; + + accumulator[name] = normalizeValue(value); + + return accumulator; + }, {}); +} + + +function normalizeValue(value) { + switch (value) { + case FALSE_KEYWORD_1: + case FALSE_KEYWORD_2: + return false; + case TRUE_KEYWORD_1: + case TRUE_KEYWORD_2: + return true; + default: + return value; + } +} + +function mapBreakWith(value) { + switch (value) { + case 'windows': + case 'crlf': + case BreakWith.CarriageReturnLineFeed: + return BreakWith.CarriageReturnLineFeed; + case 'unix': + case 'lf': + case BreakWith.LineFeed: + return BreakWith.LineFeed; + default: + return systemLineBreak; + } +} + +function mapIndentWith(value) { + switch (value) { + case 'space': + return IndentWith.Space; + case 'tab': + return IndentWith.Tab; + default: + return value; + } +} + +module.exports = { + Breaks: Breaks, + Spaces: Spaces, + formatFrom: formatFrom +}; diff --git a/node_modules/clean-css/lib/options/inline-request.js b/node_modules/clean-css/lib/options/inline-request.js new file mode 100644 index 0000000..1e14c63 --- /dev/null +++ b/node_modules/clean-css/lib/options/inline-request.js @@ -0,0 +1,22 @@ +var url = require('url'); + +var override = require('../utils/override'); + +function inlineRequestFrom(option) { + return override( + /* jshint camelcase: false */ + proxyOptionsFrom(process.env.HTTP_PROXY || process.env.http_proxy), + option || {} + ); +} + +function proxyOptionsFrom(httpProxy) { + return httpProxy ? + { + hostname: url.parse(httpProxy).hostname, + port: parseInt(url.parse(httpProxy).port) + } : + {}; +} + +module.exports = inlineRequestFrom; diff --git a/node_modules/clean-css/lib/options/inline-timeout.js b/node_modules/clean-css/lib/options/inline-timeout.js new file mode 100644 index 0000000..c7fb454 --- /dev/null +++ b/node_modules/clean-css/lib/options/inline-timeout.js @@ -0,0 +1,7 @@ +var DEFAULT_TIMEOUT = 5000; + +function inlineTimeoutFrom(option) { + return option || DEFAULT_TIMEOUT; +} + +module.exports = inlineTimeoutFrom; diff --git a/node_modules/clean-css/lib/options/inline.js b/node_modules/clean-css/lib/options/inline.js new file mode 100644 index 0000000..54761f4 --- /dev/null +++ b/node_modules/clean-css/lib/options/inline.js @@ -0,0 +1,15 @@ +function inlineOptionsFrom(rules) { + if (Array.isArray(rules)) { + return rules; + } + + if (rules === false) { + return ['none']; + } + + return undefined === rules ? + ['local'] : + rules.split(','); +} + +module.exports = inlineOptionsFrom; diff --git a/node_modules/clean-css/lib/options/optimization-level.js b/node_modules/clean-css/lib/options/optimization-level.js new file mode 100644 index 0000000..0d3ad73 --- /dev/null +++ b/node_modules/clean-css/lib/options/optimization-level.js @@ -0,0 +1,221 @@ +var roundingPrecisionFrom = require('./rounding-precision').roundingPrecisionFrom; + +var override = require('../utils/override'); + +var OptimizationLevel = { + Zero: '0', + One: '1', + Two: '2' +}; + +var DEFAULTS = {}; + +DEFAULTS[OptimizationLevel.Zero] = {}; +DEFAULTS[OptimizationLevel.One] = { + cleanupCharsets: true, + normalizeUrls: true, + optimizeBackground: true, + optimizeBorderRadius: true, + optimizeFilter: true, + optimizeFontWeight: true, + optimizeOutline: true, + removeEmpty: true, + removeNegativePaddings: true, + removeQuotes: true, + removeWhitespace: true, + replaceMultipleZeros: true, + replaceTimeUnits: true, + replaceZeroUnits: true, + roundingPrecision: roundingPrecisionFrom(undefined), + selectorsSortingMethod: 'standard', + specialComments: 'all', + tidyAtRules: true, + tidyBlockScopes: true, + tidySelectors: true, + transform: noop +}; +DEFAULTS[OptimizationLevel.Two] = { + mergeAdjacentRules: true, + mergeIntoShorthands: true, + mergeMedia: true, + mergeNonAdjacentRules: true, + mergeSemantically: false, + overrideProperties: true, + removeEmpty: true, + reduceNonAdjacentRules: true, + removeDuplicateFontRules: true, + removeDuplicateMediaBlocks: true, + removeDuplicateRules: true, + removeUnusedAtRules: false, + restructureRules: false, + skipProperties: [] +}; + +var ALL_KEYWORD_1 = '*'; +var ALL_KEYWORD_2 = 'all'; +var FALSE_KEYWORD_1 = 'false'; +var FALSE_KEYWORD_2 = 'off'; +var TRUE_KEYWORD_1 = 'true'; +var TRUE_KEYWORD_2 = 'on'; + +var LIST_VALUE_SEPARATOR = ','; +var OPTION_SEPARATOR = ';'; +var OPTION_VALUE_SEPARATOR = ':'; + +function noop() {} + +function optimizationLevelFrom(source) { + var level = override(DEFAULTS, {}); + var Zero = OptimizationLevel.Zero; + var One = OptimizationLevel.One; + var Two = OptimizationLevel.Two; + + + if (undefined === source) { + delete level[Two]; + return level; + } + + if (typeof source == 'string') { + source = parseInt(source); + } + + if (typeof source == 'number' && source === parseInt(Two)) { + return level; + } + + if (typeof source == 'number' && source === parseInt(One)) { + delete level[Two]; + return level; + } + + if (typeof source == 'number' && source === parseInt(Zero)) { + delete level[Two]; + delete level[One]; + return level; + } + + if (typeof source == 'object') { + source = covertValuesToHashes(source); + } + + if (One in source && 'roundingPrecision' in source[One]) { + source[One].roundingPrecision = roundingPrecisionFrom(source[One].roundingPrecision); + } + + if (Two in source && 'skipProperties' in source[Two] && typeof(source[Two].skipProperties) == 'string') { + source[Two].skipProperties = source[Two].skipProperties.split(LIST_VALUE_SEPARATOR); + } + + if (Zero in source || One in source || Two in source) { + level[Zero] = override(level[Zero], source[Zero]); + } + + if (One in source && ALL_KEYWORD_1 in source[One]) { + level[One] = override(level[One], defaults(One, normalizeValue(source[One][ALL_KEYWORD_1]))); + delete source[One][ALL_KEYWORD_1]; + } + + if (One in source && ALL_KEYWORD_2 in source[One]) { + level[One] = override(level[One], defaults(One, normalizeValue(source[One][ALL_KEYWORD_2]))); + delete source[One][ALL_KEYWORD_2]; + } + + if (One in source || Two in source) { + level[One] = override(level[One], source[One]); + } else { + delete level[One]; + } + + if (Two in source && ALL_KEYWORD_1 in source[Two]) { + level[Two] = override(level[Two], defaults(Two, normalizeValue(source[Two][ALL_KEYWORD_1]))); + delete source[Two][ALL_KEYWORD_1]; + } + + if (Two in source && ALL_KEYWORD_2 in source[Two]) { + level[Two] = override(level[Two], defaults(Two, normalizeValue(source[Two][ALL_KEYWORD_2]))); + delete source[Two][ALL_KEYWORD_2]; + } + + if (Two in source) { + level[Two] = override(level[Two], source[Two]); + } else { + delete level[Two]; + } + + return level; +} + +function defaults(level, value) { + var options = override(DEFAULTS[level], {}); + var key; + + for (key in options) { + if (typeof options[key] == 'boolean') { + options[key] = value; + } + } + + return options; +} + +function normalizeValue(value) { + switch (value) { + case FALSE_KEYWORD_1: + case FALSE_KEYWORD_2: + return false; + case TRUE_KEYWORD_1: + case TRUE_KEYWORD_2: + return true; + default: + return value; + } +} + +function covertValuesToHashes(source) { + var clonedSource = override(source, {}); + var level; + var i; + + for (i = 0; i <= 2; i++) { + level = '' + i; + + if (level in clonedSource && (clonedSource[level] === undefined || clonedSource[level] === false)) { + delete clonedSource[level]; + } + + if (level in clonedSource && clonedSource[level] === true) { + clonedSource[level] = {}; + } + + if (level in clonedSource && typeof clonedSource[level] == 'string') { + clonedSource[level] = covertToHash(clonedSource[level], level); + } + } + + return clonedSource; +} + +function covertToHash(asString, level) { + return asString + .split(OPTION_SEPARATOR) + .reduce(function (accumulator, directive) { + var parts = directive.split(OPTION_VALUE_SEPARATOR); + var name = parts[0]; + var value = parts[1]; + var normalizedValue = normalizeValue(value); + + if (ALL_KEYWORD_1 == name || ALL_KEYWORD_2 == name) { + accumulator = override(accumulator, defaults(level, normalizedValue)); + } else { + accumulator[name] = normalizedValue; + } + + return accumulator; + }, {}); +} + +module.exports = { + OptimizationLevel: OptimizationLevel, + optimizationLevelFrom: optimizationLevelFrom, +}; diff --git a/node_modules/clean-css/lib/options/rebase-to.js b/node_modules/clean-css/lib/options/rebase-to.js new file mode 100644 index 0000000..134b4a3 --- /dev/null +++ b/node_modules/clean-css/lib/options/rebase-to.js @@ -0,0 +1,7 @@ +var path = require('path'); + +function rebaseToFrom(option) { + return option ? path.resolve(option) : process.cwd(); +} + +module.exports = rebaseToFrom; diff --git a/node_modules/clean-css/lib/options/rebase.js b/node_modules/clean-css/lib/options/rebase.js new file mode 100644 index 0000000..999c83f --- /dev/null +++ b/node_modules/clean-css/lib/options/rebase.js @@ -0,0 +1,5 @@ +function rebaseFrom(rebaseOption) { + return undefined === rebaseOption ? true : !!rebaseOption; +} + +module.exports = rebaseFrom; diff --git a/node_modules/clean-css/lib/options/rounding-precision.js b/node_modules/clean-css/lib/options/rounding-precision.js new file mode 100644 index 0000000..42ecf1b --- /dev/null +++ b/node_modules/clean-css/lib/options/rounding-precision.js @@ -0,0 +1,88 @@ +var override = require('../utils/override'); + +var INTEGER_PATTERN = /^\d+$/; + +var ALL_UNITS = ['*', 'all']; +var DEFAULT_PRECISION = 'off'; // all precision changes are disabled +var DIRECTIVES_SEPARATOR = ','; // e.g. *=5,px=3 +var DIRECTIVE_VALUE_SEPARATOR = '='; // e.g. *=5 + +function roundingPrecisionFrom(source) { + return override(defaults(DEFAULT_PRECISION), buildPrecisionFrom(source)); +} + +function defaults(value) { + return { + 'ch': value, + 'cm': value, + 'em': value, + 'ex': value, + 'in': value, + 'mm': value, + 'pc': value, + 'pt': value, + 'px': value, + 'q': value, + 'rem': value, + 'vh': value, + 'vmax': value, + 'vmin': value, + 'vw': value, + '%': value + }; +} + +function buildPrecisionFrom(source) { + if (source === null || source === undefined) { + return {}; + } + + if (typeof source == 'boolean') { + return {}; + } + + if (typeof source == 'number' && source == -1) { + return defaults(DEFAULT_PRECISION); + } + + if (typeof source == 'number') { + return defaults(source); + } + + if (typeof source == 'string' && INTEGER_PATTERN.test(source)) { + return defaults(parseInt(source)); + } + + if (typeof source == 'string' && source == DEFAULT_PRECISION) { + return defaults(DEFAULT_PRECISION); + } + + if (typeof source == 'object') { + return source; + } + + return source + .split(DIRECTIVES_SEPARATOR) + .reduce(function (accumulator, directive) { + var directiveParts = directive.split(DIRECTIVE_VALUE_SEPARATOR); + var name = directiveParts[0]; + var value = parseInt(directiveParts[1]); + + if (isNaN(value) || value == -1) { + value = DEFAULT_PRECISION; + } + + if (ALL_UNITS.indexOf(name) > -1) { + accumulator = override(accumulator, defaults(value)); + } else { + accumulator[name] = value; + } + + return accumulator; + }, {}); +} + +module.exports = { + DEFAULT: DEFAULT_PRECISION, + roundingPrecisionFrom: roundingPrecisionFrom +}; diff --git a/node_modules/clean-css/lib/reader/apply-source-maps.js b/node_modules/clean-css/lib/reader/apply-source-maps.js new file mode 100644 index 0000000..7c5a928 --- /dev/null +++ b/node_modules/clean-css/lib/reader/apply-source-maps.js @@ -0,0 +1,245 @@ +var fs = require('fs'); +var path = require('path'); + +var isAllowedResource = require('./is-allowed-resource'); +var matchDataUri = require('./match-data-uri'); +var rebaseLocalMap = require('./rebase-local-map'); +var rebaseRemoteMap = require('./rebase-remote-map'); + +var Token = require('../tokenizer/token'); +var hasProtocol = require('../utils/has-protocol'); +var isDataUriResource = require('../utils/is-data-uri-resource'); +var isRemoteResource = require('../utils/is-remote-resource'); + +var MAP_MARKER_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/; + +function applySourceMaps(tokens, context, callback) { + var applyContext = { + callback: callback, + fetch: context.options.fetch, + index: 0, + inline: context.options.inline, + inlineRequest: context.options.inlineRequest, + inlineTimeout: context.options.inlineTimeout, + inputSourceMapTracker: context.inputSourceMapTracker, + localOnly: context.localOnly, + processedTokens: [], + rebaseTo: context.options.rebaseTo, + sourceTokens: tokens, + warnings: context.warnings + }; + + return context.options.sourceMap && tokens.length > 0 ? + doApplySourceMaps(applyContext) : + callback(tokens); +} + +function doApplySourceMaps(applyContext) { + var singleSourceTokens = []; + var lastSource = findTokenSource(applyContext.sourceTokens[0]); + var source; + var token; + var l; + + for (l = applyContext.sourceTokens.length; applyContext.index < l; applyContext.index++) { + token = applyContext.sourceTokens[applyContext.index]; + source = findTokenSource(token); + + if (source != lastSource) { + singleSourceTokens = []; + lastSource = source; + } + + singleSourceTokens.push(token); + applyContext.processedTokens.push(token); + + if (token[0] == Token.COMMENT && MAP_MARKER_PATTERN.test(token[1])) { + return fetchAndApplySourceMap(token[1], source, singleSourceTokens, applyContext); + } + } + + return applyContext.callback(applyContext.processedTokens); +} + +function findTokenSource(token) { + var scope; + var metadata; + + if (token[0] == Token.AT_RULE || token[0] == Token.COMMENT) { + metadata = token[2][0]; + } else { + scope = token[1][0]; + metadata = scope[2][0]; + } + + return metadata[2]; +} + +function fetchAndApplySourceMap(sourceMapComment, source, singleSourceTokens, applyContext) { + return extractInputSourceMapFrom(sourceMapComment, applyContext, function (inputSourceMap) { + if (inputSourceMap) { + applyContext.inputSourceMapTracker.track(source, inputSourceMap); + applySourceMapRecursively(singleSourceTokens, applyContext.inputSourceMapTracker); + } + + applyContext.index++; + return doApplySourceMaps(applyContext); + }); +} + +function extractInputSourceMapFrom(sourceMapComment, applyContext, whenSourceMapReady) { + var uri = MAP_MARKER_PATTERN.exec(sourceMapComment)[1]; + var absoluteUri; + var sourceMap; + var rebasedMap; + + if (isDataUriResource(uri)) { + sourceMap = extractInputSourceMapFromDataUri(uri); + return whenSourceMapReady(sourceMap); + } else if (isRemoteResource(uri)) { + return loadInputSourceMapFromRemoteUri(uri, applyContext, function (sourceMap) { + var parsedMap; + + if (sourceMap) { + parsedMap = JSON.parse(sourceMap); + rebasedMap = rebaseRemoteMap(parsedMap, uri); + whenSourceMapReady(rebasedMap); + } else { + whenSourceMapReady(null); + } + }); + } else { + // at this point `uri` is already rebased, see lib/reader/rebase.js#rebaseSourceMapComment + // it is rebased to be consistent with rebasing other URIs + // however here we need to resolve it back to read it from disk + absoluteUri = path.resolve(applyContext.rebaseTo, uri); + sourceMap = loadInputSourceMapFromLocalUri(absoluteUri, applyContext); + + if (sourceMap) { + rebasedMap = rebaseLocalMap(sourceMap, absoluteUri, applyContext.rebaseTo); + return whenSourceMapReady(rebasedMap); + } else { + return whenSourceMapReady(null); + } + } +} + +function extractInputSourceMapFromDataUri(uri) { + var dataUriMatch = matchDataUri(uri); + var charset = dataUriMatch[2] ? dataUriMatch[2].split(/[=;]/)[2] : 'us-ascii'; + var encoding = dataUriMatch[3] ? dataUriMatch[3].split(';')[1] : 'utf8'; + var data = encoding == 'utf8' ? global.unescape(dataUriMatch[4]) : dataUriMatch[4]; + + var buffer = new Buffer(data, encoding); + buffer.charset = charset; + + return JSON.parse(buffer.toString()); +} + +function loadInputSourceMapFromRemoteUri(uri, applyContext, whenLoaded) { + var isAllowed = isAllowedResource(uri, true, applyContext.inline); + var isRuntimeResource = !hasProtocol(uri); + + if (applyContext.localOnly) { + applyContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.'); + return whenLoaded(null); + } else if (isRuntimeResource) { + applyContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.'); + return whenLoaded(null); + } else if (!isAllowed) { + applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.'); + return whenLoaded(null); + } + + applyContext.fetch(uri, applyContext.inlineRequest, applyContext.inlineTimeout, function (error, body) { + if (error) { + applyContext.warnings.push('Missing source map at "' + uri + '" - ' + error); + return whenLoaded(null); + } + + whenLoaded(body); + }); +} + +function loadInputSourceMapFromLocalUri(uri, applyContext) { + var isAllowed = isAllowedResource(uri, false, applyContext.inline); + var sourceMap; + + if (!fs.existsSync(uri) || !fs.statSync(uri).isFile()) { + applyContext.warnings.push('Ignoring local source map at "' + uri + '" as resource is missing.'); + return null; + } else if (!isAllowed) { + applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.'); + return null; + } + + sourceMap = fs.readFileSync(uri, 'utf-8'); + return JSON.parse(sourceMap); +} + +function applySourceMapRecursively(tokens, inputSourceMapTracker) { + var token; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + + switch (token[0]) { + case Token.AT_RULE: + applySourceMapTo(token, inputSourceMapTracker); + break; + case Token.AT_RULE_BLOCK: + applySourceMapRecursively(token[1], inputSourceMapTracker); + applySourceMapRecursively(token[2], inputSourceMapTracker); + break; + case Token.AT_RULE_BLOCK_SCOPE: + applySourceMapTo(token, inputSourceMapTracker); + break; + case Token.NESTED_BLOCK: + applySourceMapRecursively(token[1], inputSourceMapTracker); + applySourceMapRecursively(token[2], inputSourceMapTracker); + break; + case Token.NESTED_BLOCK_SCOPE: + applySourceMapTo(token, inputSourceMapTracker); + break; + case Token.COMMENT: + applySourceMapTo(token, inputSourceMapTracker); + break; + case Token.PROPERTY: + applySourceMapRecursively(token, inputSourceMapTracker); + break; + case Token.PROPERTY_BLOCK: + applySourceMapRecursively(token[1], inputSourceMapTracker); + break; + case Token.PROPERTY_NAME: + applySourceMapTo(token, inputSourceMapTracker); + break; + case Token.PROPERTY_VALUE: + applySourceMapTo(token, inputSourceMapTracker); + break; + case Token.RULE: + applySourceMapRecursively(token[1], inputSourceMapTracker); + applySourceMapRecursively(token[2], inputSourceMapTracker); + break; + case Token.RULE_SCOPE: + applySourceMapTo(token, inputSourceMapTracker); + } + } + + return tokens; +} + +function applySourceMapTo(token, inputSourceMapTracker) { + var value = token[1]; + var metadata = token[2]; + var newMetadata = []; + var i, l; + + for (i = 0, l = metadata.length; i < l; i++) { + newMetadata.push(inputSourceMapTracker.originalPositionFor(metadata[i], value.length)); + } + + token[2] = newMetadata; +} + +module.exports = applySourceMaps; diff --git a/node_modules/clean-css/lib/reader/extract-import-url-and-media.js b/node_modules/clean-css/lib/reader/extract-import-url-and-media.js new file mode 100644 index 0000000..e309c2f --- /dev/null +++ b/node_modules/clean-css/lib/reader/extract-import-url-and-media.js @@ -0,0 +1,35 @@ +var split = require('../utils/split'); + +var BRACE_PREFIX = /^\(/; +var BRACE_SUFFIX = /\)$/; +var IMPORT_PREFIX_PATTERN = /^@import/i; +var QUOTE_PREFIX_PATTERN = /['"]\s*/; +var QUOTE_SUFFIX_PATTERN = /\s*['"]/; +var URL_PREFIX_PATTERN = /^url\(\s*/i; +var URL_SUFFIX_PATTERN = /\s*\)/i; + +function extractImportUrlAndMedia(atRuleValue) { + var uri; + var mediaQuery; + var stripped; + var parts; + + stripped = atRuleValue + .replace(IMPORT_PREFIX_PATTERN, '') + .trim() + .replace(URL_PREFIX_PATTERN, '(') + .replace(URL_SUFFIX_PATTERN, ')') + .replace(QUOTE_PREFIX_PATTERN, '') + .replace(QUOTE_SUFFIX_PATTERN, ''); + + parts = split(stripped, ' '); + + uri = parts[0] + .replace(BRACE_PREFIX, '') + .replace(BRACE_SUFFIX, ''); + mediaQuery = parts.slice(1).join(' '); + + return [uri, mediaQuery]; +} + +module.exports = extractImportUrlAndMedia; diff --git a/node_modules/clean-css/lib/reader/input-source-map-tracker.js b/node_modules/clean-css/lib/reader/input-source-map-tracker.js new file mode 100644 index 0000000..4b8730c --- /dev/null +++ b/node_modules/clean-css/lib/reader/input-source-map-tracker.js @@ -0,0 +1,58 @@ +var SourceMapConsumer = require('source-map').SourceMapConsumer; + +function inputSourceMapTracker() { + var maps = {}; + + return { + all: all.bind(null, maps), + isTracking: isTracking.bind(null, maps), + originalPositionFor: originalPositionFor.bind(null, maps), + track: track.bind(null, maps) + }; +} + +function all(maps) { + return maps; +} + +function isTracking(maps, source) { + return source in maps; +} + +function originalPositionFor(maps, metadata, range, selectorFallbacks) { + var line = metadata[0]; + var column = metadata[1]; + var source = metadata[2]; + var position = { + line: line, + column: column + range + }; + var originalPosition; + + while (!originalPosition && position.column > column) { + position.column--; + originalPosition = maps[source].originalPositionFor(position); + } + + if (!originalPosition || originalPosition.column < 0) { + return metadata; + } + + if (originalPosition.line === null && line > 1 && selectorFallbacks > 0) { + return originalPositionFor(maps, [line - 1, column, source], range, selectorFallbacks - 1); + } + + return originalPosition.line !== null ? + toMetadata(originalPosition) : + metadata; +} + +function toMetadata(asHash) { + return [asHash.line, asHash.column, asHash.source]; +} + +function track(maps, source, data) { + maps[source] = new SourceMapConsumer(data); +} + +module.exports = inputSourceMapTracker; diff --git a/node_modules/clean-css/lib/reader/is-allowed-resource.js b/node_modules/clean-css/lib/reader/is-allowed-resource.js new file mode 100644 index 0000000..043066e --- /dev/null +++ b/node_modules/clean-css/lib/reader/is-allowed-resource.js @@ -0,0 +1,77 @@ +var path = require('path'); +var url = require('url'); + +var isRemoteResource = require('../utils/is-remote-resource'); +var hasProtocol = require('../utils/has-protocol'); + +var HTTP_PROTOCOL = 'http:'; + +function isAllowedResource(uri, isRemote, rules) { + var match; + var absoluteUri; + var allowed = isRemote ? false : true; + var rule; + var isNegated; + var normalizedRule; + var i; + + if (rules.length === 0) { + return false; + } + + if (isRemote && !hasProtocol(uri)) { + uri = HTTP_PROTOCOL + uri; + } + + match = isRemote ? + url.parse(uri).host : + uri; + + absoluteUri = isRemote ? + uri : + path.resolve(uri); + + for (i = 0; i < rules.length; i++) { + rule = rules[i]; + isNegated = rule[0] == '!'; + normalizedRule = rule.substring(1); + + if (isNegated && isRemote && isRemoteRule(normalizedRule)) { + allowed = allowed && !isAllowedResource(uri, true, [normalizedRule]); + } else if (isNegated && !isRemote && !isRemoteRule(normalizedRule)) { + allowed = allowed && !isAllowedResource(uri, false, [normalizedRule]); + } else if (isNegated) { + allowed = allowed && true; + } else if (rule == 'all') { + allowed = true; + } else if (isRemote && rule == 'local') { + allowed = allowed || false; + } else if (isRemote && rule == 'remote') { + allowed = true; + } else if (!isRemote && rule == 'remote') { + allowed = false; + } else if (!isRemote && rule == 'local') { + allowed = true; + } else if (rule === match) { + allowed = true; + } else if (rule === uri) { + allowed = true; + } else if (isRemote && absoluteUri.indexOf(rule) === 0) { + allowed = true; + } else if (!isRemote && absoluteUri.indexOf(path.resolve(rule)) === 0) { + allowed = true; + } else if (isRemote != isRemoteRule(normalizedRule)) { + allowed = allowed && true; + } else { + allowed = false; + } + } + + return allowed; +} + +function isRemoteRule(rule) { + return isRemoteResource(rule) || url.parse(HTTP_PROTOCOL + '//' + rule).host == rule; +} + +module.exports = isAllowedResource; diff --git a/node_modules/clean-css/lib/reader/load-original-sources.js b/node_modules/clean-css/lib/reader/load-original-sources.js new file mode 100644 index 0000000..465035d --- /dev/null +++ b/node_modules/clean-css/lib/reader/load-original-sources.js @@ -0,0 +1,126 @@ +var fs = require('fs'); +var path = require('path'); + +var isAllowedResource = require('./is-allowed-resource'); + +var hasProtocol = require('../utils/has-protocol'); +var isRemoteResource = require('../utils/is-remote-resource'); + +function loadOriginalSources(context, callback) { + var loadContext = { + callback: callback, + fetch: context.options.fetch, + index: 0, + inline: context.options.inline, + inlineRequest: context.options.inlineRequest, + inlineTimeout: context.options.inlineTimeout, + localOnly: context.localOnly, + rebaseTo: context.options.rebaseTo, + sourcesContent: context.sourcesContent, + uriToSource: uriToSourceMapping(context.inputSourceMapTracker.all()), + warnings: context.warnings + }; + + return context.options.sourceMap && context.options.sourceMapInlineSources ? + doLoadOriginalSources(loadContext) : + callback(); +} + +function uriToSourceMapping(allSourceMapConsumers) { + var mapping = {}; + var consumer; + var uri; + var source; + var i, l; + + for (source in allSourceMapConsumers) { + consumer = allSourceMapConsumers[source]; + + for (i = 0, l = consumer.sources.length; i < l; i++) { + uri = consumer.sources[i]; + source = consumer.sourceContentFor(uri, true); + + mapping[uri] = source; + } + } + + return mapping; +} + +function doLoadOriginalSources(loadContext) { + var uris = Object.keys(loadContext.uriToSource); + var uri; + var source; + var total; + + for (total = uris.length; loadContext.index < total; loadContext.index++) { + uri = uris[loadContext.index]; + source = loadContext.uriToSource[uri]; + + if (source) { + loadContext.sourcesContent[uri] = source; + } else { + return loadOriginalSource(uri, loadContext); + } + } + + return loadContext.callback(); +} + +function loadOriginalSource(uri, loadContext) { + var content; + + if (isRemoteResource(uri)) { + return loadOriginalSourceFromRemoteUri(uri, loadContext, function (content) { + loadContext.index++; + loadContext.sourcesContent[uri] = content; + return doLoadOriginalSources(loadContext); + }); + } else { + content = loadOriginalSourceFromLocalUri(uri, loadContext); + loadContext.index++; + loadContext.sourcesContent[uri] = content; + return doLoadOriginalSources(loadContext); + } +} + +function loadOriginalSourceFromRemoteUri(uri, loadContext, whenLoaded) { + var isAllowed = isAllowedResource(uri, true, loadContext.inline); + var isRuntimeResource = !hasProtocol(uri); + + if (loadContext.localOnly) { + loadContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.'); + return whenLoaded(null); + } else if (isRuntimeResource) { + loadContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.'); + return whenLoaded(null); + } else if (!isAllowed) { + loadContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.'); + return whenLoaded(null); + } + + loadContext.fetch(uri, loadContext.inlineRequest, loadContext.inlineTimeout, function (error, content) { + if (error) { + loadContext.warnings.push('Missing original source at "' + uri + '" - ' + error); + } + + whenLoaded(content); + }); +} + +function loadOriginalSourceFromLocalUri(relativeUri, loadContext) { + var isAllowed = isAllowedResource(relativeUri, false, loadContext.inline); + var absoluteUri = path.resolve(loadContext.rebaseTo, relativeUri); + + if (!fs.existsSync(absoluteUri) || !fs.statSync(absoluteUri).isFile()) { + loadContext.warnings.push('Ignoring local source map at "' + absoluteUri + '" as resource is missing.'); + return null; + } else if (!isAllowed) { + loadContext.warnings.push('Cannot fetch "' + absoluteUri + '" as resource is not allowed.'); + return null; + } + + return fs.readFileSync(absoluteUri, 'utf8'); +} + +module.exports = loadOriginalSources; diff --git a/node_modules/clean-css/lib/reader/load-remote-resource.js b/node_modules/clean-css/lib/reader/load-remote-resource.js new file mode 100644 index 0000000..0133c78 --- /dev/null +++ b/node_modules/clean-css/lib/reader/load-remote-resource.js @@ -0,0 +1,74 @@ +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var isHttpResource = require('../utils/is-http-resource'); +var isHttpsResource = require('../utils/is-https-resource'); +var override = require('../utils/override'); + +var HTTP_PROTOCOL = 'http:'; + +function loadRemoteResource(uri, inlineRequest, inlineTimeout, callback) { + var proxyProtocol = inlineRequest.protocol || inlineRequest.hostname; + var errorHandled = false; + var requestOptions; + var fetch; + + requestOptions = override( + url.parse(uri), + inlineRequest || {} + ); + + if (inlineRequest.hostname !== undefined) { + // overwrite as we always expect a http proxy currently + requestOptions.protocol = inlineRequest.protocol || HTTP_PROTOCOL; + requestOptions.path = requestOptions.href; + } + + fetch = (proxyProtocol && !isHttpsResource(proxyProtocol)) || isHttpResource(uri) ? + http.get : + https.get; + + fetch(requestOptions, function (res) { + var chunks = []; + var movedUri; + + if (errorHandled) { + return; + } + + if (res.statusCode < 200 || res.statusCode > 399) { + return callback(res.statusCode, null); + } else if (res.statusCode > 299) { + movedUri = url.resolve(uri, res.headers.location); + return loadRemoteResource(movedUri, inlineRequest, inlineTimeout, callback); + } + + res.on('data', function (chunk) { + chunks.push(chunk.toString()); + }); + res.on('end', function () { + var body = chunks.join(''); + callback(null, body); + }); + }) + .on('error', function (res) { + if (errorHandled) { + return; + } + + errorHandled = true; + callback(res.message, null); + }) + .on('timeout', function () { + if (errorHandled) { + return; + } + + errorHandled = true; + callback('timeout', null); + }) + .setTimeout(inlineTimeout); +} + +module.exports = loadRemoteResource; diff --git a/node_modules/clean-css/lib/reader/match-data-uri.js b/node_modules/clean-css/lib/reader/match-data-uri.js new file mode 100644 index 0000000..d0d5a4c --- /dev/null +++ b/node_modules/clean-css/lib/reader/match-data-uri.js @@ -0,0 +1,7 @@ +var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/; + +function matchDataUri(uri) { + return DATA_URI_PATTERN.exec(uri); +} + +module.exports = matchDataUri; diff --git a/node_modules/clean-css/lib/reader/normalize-path.js b/node_modules/clean-css/lib/reader/normalize-path.js new file mode 100644 index 0000000..a9eca38 --- /dev/null +++ b/node_modules/clean-css/lib/reader/normalize-path.js @@ -0,0 +1,8 @@ +var UNIX_SEPARATOR = '/'; +var WINDOWS_SEPARATOR_PATTERN = /\\/g; + +function normalizePath(path) { + return path.replace(WINDOWS_SEPARATOR_PATTERN, UNIX_SEPARATOR); +} + +module.exports = normalizePath; diff --git a/node_modules/clean-css/lib/reader/read-sources.js b/node_modules/clean-css/lib/reader/read-sources.js new file mode 100644 index 0000000..1338f6a --- /dev/null +++ b/node_modules/clean-css/lib/reader/read-sources.js @@ -0,0 +1,341 @@ +var fs = require('fs'); +var path = require('path'); + +var applySourceMaps = require('./apply-source-maps'); +var extractImportUrlAndMedia = require('./extract-import-url-and-media'); +var isAllowedResource = require('./is-allowed-resource'); +var loadOriginalSources = require('./load-original-sources'); +var normalizePath = require('./normalize-path'); +var rebase = require('./rebase'); +var rebaseLocalMap = require('./rebase-local-map'); +var rebaseRemoteMap = require('./rebase-remote-map'); +var restoreImport = require('./restore-import'); + +var tokenize = require('../tokenizer/tokenize'); +var Token = require('../tokenizer/token'); +var Marker = require('../tokenizer/marker'); +var hasProtocol = require('../utils/has-protocol'); +var isImport = require('../utils/is-import'); +var isRemoteResource = require('../utils/is-remote-resource'); + +var UNKNOWN_URI = 'uri:unknown'; + +function readSources(input, context, callback) { + return doReadSources(input, context, function (tokens) { + return applySourceMaps(tokens, context, function () { + return loadOriginalSources(context, function () { return callback(tokens); }); + }); + }); +} + +function doReadSources(input, context, callback) { + if (typeof input == 'string') { + return fromString(input, context, callback); + } else if (Buffer.isBuffer(input)) { + return fromString(input.toString(), context, callback); + } else if (Array.isArray(input)) { + return fromArray(input, context, callback); + } else if (typeof input == 'object') { + return fromHash(input, context, callback); + } +} + +function fromString(input, context, callback) { + context.source = undefined; + context.sourcesContent[undefined] = input; + context.stats.originalSize += input.length; + + return fromStyles(input, context, { inline: context.options.inline }, callback); +} + +function fromArray(input, context, callback) { + var inputAsImports = input.reduce(function (accumulator, uriOrHash) { + if (typeof uriOrHash === 'string') { + return addStringSource(uriOrHash, accumulator); + } else { + return addHashSource(uriOrHash, context, accumulator); + } + + }, []); + + return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback); +} + +function fromHash(input, context, callback) { + var inputAsImports = addHashSource(input, context, []); + return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback); +} + +function addStringSource(input, imports) { + imports.push(restoreAsImport(normalizeUri(input))); + return imports; +} + +function addHashSource(input, context, imports) { + var uri; + var normalizedUri; + var source; + + for (uri in input) { + source = input[uri]; + normalizedUri = normalizeUri(uri); + + imports.push(restoreAsImport(normalizedUri)); + + context.sourcesContent[normalizedUri] = source.styles; + + if (source.sourceMap) { + trackSourceMap(source.sourceMap, normalizedUri, context); + } + } + + return imports; +} + +function normalizeUri(uri) { + var currentPath = path.resolve(''); + var absoluteUri; + var relativeToCurrentPath; + var normalizedUri; + + if (isRemoteResource(uri)) { + return uri; + } + + absoluteUri = path.isAbsolute(uri) ? + uri : + path.resolve(uri); + relativeToCurrentPath = path.relative(currentPath, absoluteUri); + normalizedUri = normalizePath(relativeToCurrentPath); + + return normalizedUri; +} + +function trackSourceMap(sourceMap, uri, context) { + var parsedMap = typeof sourceMap == 'string' ? + JSON.parse(sourceMap) : + sourceMap; + var rebasedMap = isRemoteResource(uri) ? + rebaseRemoteMap(parsedMap, uri) : + rebaseLocalMap(parsedMap, uri || UNKNOWN_URI, context.options.rebaseTo); + + context.inputSourceMapTracker.track(uri, rebasedMap); +} + +function restoreAsImport(uri) { + return restoreImport('url(' + uri + ')', '') + Marker.SEMICOLON; +} + +function fromStyles(styles, context, parentInlinerContext, callback) { + var tokens; + var rebaseConfig = {}; + + if (!context.source) { + rebaseConfig.fromBase = path.resolve(''); + rebaseConfig.toBase = context.options.rebaseTo; + } else if (isRemoteResource(context.source)) { + rebaseConfig.fromBase = context.source; + rebaseConfig.toBase = context.source; + } else if (path.isAbsolute(context.source)) { + rebaseConfig.fromBase = path.dirname(context.source); + rebaseConfig.toBase = context.options.rebaseTo; + } else { + rebaseConfig.fromBase = path.dirname(path.resolve(context.source)); + rebaseConfig.toBase = context.options.rebaseTo; + } + + tokens = tokenize(styles, context); + tokens = rebase(tokens, context.options.rebase, context.validator, rebaseConfig); + + return allowsAnyImports(parentInlinerContext.inline) ? + inline(tokens, context, parentInlinerContext, callback) : + callback(tokens); +} + +function allowsAnyImports(inline) { + return !(inline.length == 1 && inline[0] == 'none'); +} + +function inline(tokens, externalContext, parentInlinerContext, callback) { + var inlinerContext = { + afterContent: false, + callback: callback, + errors: externalContext.errors, + externalContext: externalContext, + fetch: externalContext.options.fetch, + inlinedStylesheets: parentInlinerContext.inlinedStylesheets || externalContext.inlinedStylesheets, + inline: parentInlinerContext.inline, + inlineRequest: externalContext.options.inlineRequest, + inlineTimeout: externalContext.options.inlineTimeout, + isRemote: parentInlinerContext.isRemote || false, + localOnly: externalContext.localOnly, + outputTokens: [], + rebaseTo: externalContext.options.rebaseTo, + sourceTokens: tokens, + warnings: externalContext.warnings + }; + + return doInlineImports(inlinerContext); +} + +function doInlineImports(inlinerContext) { + var token; + var i, l; + + for (i = 0, l = inlinerContext.sourceTokens.length; i < l; i++) { + token = inlinerContext.sourceTokens[i]; + + if (token[0] == Token.AT_RULE && isImport(token[1])) { + inlinerContext.sourceTokens.splice(0, i); + return inlineStylesheet(token, inlinerContext); + } else if (token[0] == Token.AT_RULE || token[0] == Token.COMMENT) { + inlinerContext.outputTokens.push(token); + } else { + inlinerContext.outputTokens.push(token); + inlinerContext.afterContent = true; + } + } + + inlinerContext.sourceTokens = []; + return inlinerContext.callback(inlinerContext.outputTokens); +} + +function inlineStylesheet(token, inlinerContext) { + var uriAndMediaQuery = extractImportUrlAndMedia(token[1]); + var uri = uriAndMediaQuery[0]; + var mediaQuery = uriAndMediaQuery[1]; + var metadata = token[2]; + + return isRemoteResource(uri) ? + inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) : + inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext); +} + +function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) { + var isAllowed = isAllowedResource(uri, true, inlinerContext.inline); + var originalUri = uri; + var isLoaded = uri in inlinerContext.externalContext.sourcesContent; + var isRuntimeResource = !hasProtocol(uri); + + if (inlinerContext.inlinedStylesheets.indexOf(uri) > -1) { + inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as it has already been imported.'); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + return doInlineImports(inlinerContext); + } else if (inlinerContext.localOnly && inlinerContext.afterContent) { + inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as no callback given and after other content.'); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + return doInlineImports(inlinerContext); + } else if (isRuntimeResource) { + inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no protocol given.'); + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + return doInlineImports(inlinerContext); + } else if (inlinerContext.localOnly && !isLoaded) { + inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no callback given.'); + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + return doInlineImports(inlinerContext); + } else if (!isAllowed && inlinerContext.afterContent) { + inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as resource is not allowed and after other content.'); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + return doInlineImports(inlinerContext); + } else if (!isAllowed) { + inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as resource is not allowed.'); + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + return doInlineImports(inlinerContext); + } + + inlinerContext.inlinedStylesheets.push(uri); + + function whenLoaded(error, importedStyles) { + if (error) { + inlinerContext.errors.push('Broken @import declaration of "' + uri + '" - ' + error); + + return process.nextTick(function () { + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + doInlineImports(inlinerContext); + }); + } + + inlinerContext.inline = inlinerContext.externalContext.options.inline; + inlinerContext.isRemote = true; + + inlinerContext.externalContext.source = originalUri; + inlinerContext.externalContext.sourcesContent[uri] = importedStyles; + inlinerContext.externalContext.stats.originalSize += importedStyles.length; + + return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) { + importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata); + + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + + return doInlineImports(inlinerContext); + }); + } + + return isLoaded ? + whenLoaded(null, inlinerContext.externalContext.sourcesContent[uri]) : + inlinerContext.fetch(uri, inlinerContext.inlineRequest, inlinerContext.inlineTimeout, whenLoaded); +} + +function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) { + var currentPath = path.resolve(''); + var absoluteUri = path.isAbsolute(uri) ? + path.resolve(currentPath, uri[0] == '/' ? uri.substring(1) : uri) : + path.resolve(inlinerContext.rebaseTo, uri); + var relativeToCurrentPath = path.relative(currentPath, absoluteUri); + var importedStyles; + var isAllowed = isAllowedResource(uri, false, inlinerContext.inline); + var normalizedPath = normalizePath(relativeToCurrentPath); + var isLoaded = normalizedPath in inlinerContext.externalContext.sourcesContent; + + if (inlinerContext.inlinedStylesheets.indexOf(absoluteUri) > -1) { + inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as it has already been imported.'); + } else if (!isLoaded && (!fs.existsSync(absoluteUri) || !fs.statSync(absoluteUri).isFile())) { + inlinerContext.errors.push('Ignoring local @import of "' + uri + '" as resource is missing.'); + } else if (!isAllowed && inlinerContext.afterContent) { + inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as resource is not allowed and after other content.'); + } else if (inlinerContext.afterContent) { + inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as after other content.'); + } else if (!isAllowed) { + inlinerContext.warnings.push('Skipping local @import of "' + uri + '" as resource is not allowed.'); + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); + } else { + importedStyles = isLoaded ? + inlinerContext.externalContext.sourcesContent[normalizedPath] : + fs.readFileSync(absoluteUri, 'utf-8'); + + inlinerContext.inlinedStylesheets.push(absoluteUri); + inlinerContext.inline = inlinerContext.externalContext.options.inline; + + inlinerContext.externalContext.source = normalizedPath; + inlinerContext.externalContext.sourcesContent[normalizedPath] = importedStyles; + inlinerContext.externalContext.stats.originalSize += importedStyles.length; + + return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) { + importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata); + + inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens); + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + + return doInlineImports(inlinerContext); + }); + } + + inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); + + return doInlineImports(inlinerContext); +} + +function wrapInMedia(tokens, mediaQuery, metadata) { + if (mediaQuery) { + return [[Token.NESTED_BLOCK, [[Token.NESTED_BLOCK_SCOPE, '@media ' + mediaQuery, metadata]], tokens]]; + } else { + return tokens; + } +} + +module.exports = readSources; diff --git a/node_modules/clean-css/lib/reader/rebase-local-map.js b/node_modules/clean-css/lib/reader/rebase-local-map.js new file mode 100644 index 0000000..aec8d23 --- /dev/null +++ b/node_modules/clean-css/lib/reader/rebase-local-map.js @@ -0,0 +1,15 @@ +var path = require('path'); + +function rebaseLocalMap(sourceMap, sourceUri, rebaseTo) { + var currentPath = path.resolve(''); + var absoluteUri = path.resolve(currentPath, sourceUri); + var absoluteUriDirectory = path.dirname(absoluteUri); + + sourceMap.sources = sourceMap.sources.map(function(source) { + return path.relative(rebaseTo, path.resolve(absoluteUriDirectory, source)); + }); + + return sourceMap; +} + +module.exports = rebaseLocalMap; diff --git a/node_modules/clean-css/lib/reader/rebase-remote-map.js b/node_modules/clean-css/lib/reader/rebase-remote-map.js new file mode 100644 index 0000000..7b6bb7a --- /dev/null +++ b/node_modules/clean-css/lib/reader/rebase-remote-map.js @@ -0,0 +1,14 @@ +var path = require('path'); +var url = require('url'); + +function rebaseRemoteMap(sourceMap, sourceUri) { + var sourceDirectory = path.dirname(sourceUri); + + sourceMap.sources = sourceMap.sources.map(function(source) { + return url.resolve(sourceDirectory, source); + }); + + return sourceMap; +} + +module.exports = rebaseRemoteMap; diff --git a/node_modules/clean-css/lib/reader/rebase.js b/node_modules/clean-css/lib/reader/rebase.js new file mode 100644 index 0000000..181b319 --- /dev/null +++ b/node_modules/clean-css/lib/reader/rebase.js @@ -0,0 +1,101 @@ +var extractImportUrlAndMedia = require('./extract-import-url-and-media'); +var restoreImport = require('./restore-import'); +var rewriteUrl = require('./rewrite-url'); + +var Token = require('../tokenizer/token'); +var isImport = require('../utils/is-import'); + +var SOURCE_MAP_COMMENT_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/; + +function rebase(tokens, rebaseAll, validator, rebaseConfig) { + return rebaseAll ? + rebaseEverything(tokens, validator, rebaseConfig) : + rebaseAtRules(tokens, validator, rebaseConfig); +} + +function rebaseEverything(tokens, validator, rebaseConfig) { + var token; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + + switch (token[0]) { + case Token.AT_RULE: + rebaseAtRule(token, validator, rebaseConfig); + break; + case Token.AT_RULE_BLOCK: + rebaseProperties(token[2], validator, rebaseConfig); + break; + case Token.COMMENT: + rebaseSourceMapComment(token, rebaseConfig); + break; + case Token.NESTED_BLOCK: + rebaseEverything(token[2], validator, rebaseConfig); + break; + case Token.RULE: + rebaseProperties(token[2], validator, rebaseConfig); + break; + } + } + + return tokens; +} + +function rebaseAtRules(tokens, validator, rebaseConfig) { + var token; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + + switch (token[0]) { + case Token.AT_RULE: + rebaseAtRule(token, validator, rebaseConfig); + break; + } + } + + return tokens; +} + +function rebaseAtRule(token, validator, rebaseConfig) { + if (!isImport(token[1])) { + return; + } + + var uriAndMediaQuery = extractImportUrlAndMedia(token[1]); + var newUrl = rewriteUrl(uriAndMediaQuery[0], rebaseConfig); + var mediaQuery = uriAndMediaQuery[1]; + + token[1] = restoreImport(newUrl, mediaQuery); +} + +function rebaseSourceMapComment(token, rebaseConfig) { + var matches = SOURCE_MAP_COMMENT_PATTERN.exec(token[1]); + + if (matches && matches[1].indexOf('data:') === -1) { + token[1] = token[1].replace(matches[1], rewriteUrl(matches[1], rebaseConfig, true)); + } +} + +function rebaseProperties(properties, validator, rebaseConfig) { + var property; + var value; + var i, l; + var j, m; + + for (i = 0, l = properties.length; i < l; i++) { + property = properties[i]; + + for (j = 2 /* 0 is Token.PROPERTY, 1 is name */, m = property.length; j < m; j++) { + value = property[j][1]; + + if (validator.isUrl(value)) { + property[j][1] = rewriteUrl(value, rebaseConfig); + } + } + } +} + +module.exports = rebase; diff --git a/node_modules/clean-css/lib/reader/restore-import.js b/node_modules/clean-css/lib/reader/restore-import.js new file mode 100644 index 0000000..5bdbd92 --- /dev/null +++ b/node_modules/clean-css/lib/reader/restore-import.js @@ -0,0 +1,5 @@ +function restoreImport(uri, mediaQuery) { + return ('@import ' + uri + ' ' + mediaQuery).trim(); +} + +module.exports = restoreImport; diff --git a/node_modules/clean-css/lib/reader/rewrite-url.js b/node_modules/clean-css/lib/reader/rewrite-url.js new file mode 100644 index 0000000..a4793fd --- /dev/null +++ b/node_modules/clean-css/lib/reader/rewrite-url.js @@ -0,0 +1,118 @@ +var path = require('path'); +var url = require('url'); + +var DOUBLE_QUOTE = '"'; +var SINGLE_QUOTE = '\''; +var URL_PREFIX = 'url('; +var URL_SUFFIX = ')'; + +var QUOTE_PREFIX_PATTERN = /^["']/; +var QUOTE_SUFFIX_PATTERN = /["']$/; +var ROUND_BRACKETS_PATTERN = /[\(\)]/; +var URL_PREFIX_PATTERN = /^url\(/i; +var URL_SUFFIX_PATTERN = /\)$/; +var WHITESPACE_PATTERN = /\s/; + +var isWindows = process.platform == 'win32'; + +function rebase(uri, rebaseConfig) { + if (!rebaseConfig) { + return uri; + } + + if (isAbsolute(uri) && !isRemote(rebaseConfig.toBase)) { + return uri; + } + + if (isRemote(uri) || isSVGMarker(uri) || isInternal(uri)) { + return uri; + } + + if (isData(uri)) { + return '\'' + uri + '\''; + } + + if (isRemote(rebaseConfig.toBase)) { + return url.resolve(rebaseConfig.toBase, uri); + } + + return rebaseConfig.absolute ? + normalize(absolute(uri, rebaseConfig)) : + normalize(relative(uri, rebaseConfig)); +} + +function isAbsolute(uri) { + return path.isAbsolute(uri); +} + +function isSVGMarker(uri) { + return uri[0] == '#'; +} + +function isInternal(uri) { + return /^\w+:\w+/.test(uri); +} + +function isRemote(uri) { + return /^[^:]+?:\/\//.test(uri) || uri.indexOf('//') === 0; +} + +function isData(uri) { + return uri.indexOf('data:') === 0; +} + +function absolute(uri, rebaseConfig) { + return path + .resolve(path.join(rebaseConfig.fromBase || '', uri)) + .replace(rebaseConfig.toBase, ''); +} + +function relative(uri, rebaseConfig) { + return path.relative(rebaseConfig.toBase, path.join(rebaseConfig.fromBase || '', uri)); +} + +function normalize(uri) { + return isWindows ? uri.replace(/\\/g, '/') : uri; +} + +function quoteFor(unquotedUrl) { + if (unquotedUrl.indexOf(SINGLE_QUOTE) > -1) { + return DOUBLE_QUOTE; + } else if (unquotedUrl.indexOf(DOUBLE_QUOTE) > -1) { + return SINGLE_QUOTE; + } else if (hasWhitespace(unquotedUrl) || hasRoundBrackets(unquotedUrl)) { + return SINGLE_QUOTE; + } else { + return ''; + } +} + +function hasWhitespace(url) { + return WHITESPACE_PATTERN.test(url); +} + +function hasRoundBrackets(url) { + return ROUND_BRACKETS_PATTERN.test(url); +} + +function rewriteUrl(originalUrl, rebaseConfig, pathOnly) { + var strippedUrl = originalUrl + .replace(URL_PREFIX_PATTERN, '') + .replace(URL_SUFFIX_PATTERN, '') + .trim(); + + var unquotedUrl = strippedUrl + .replace(QUOTE_PREFIX_PATTERN, '') + .replace(QUOTE_SUFFIX_PATTERN, '') + .trim(); + + var quote = strippedUrl[0] == SINGLE_QUOTE || strippedUrl[0] == DOUBLE_QUOTE ? + strippedUrl[0] : + quoteFor(unquotedUrl); + + return pathOnly ? + rebase(unquotedUrl, rebaseConfig) : + URL_PREFIX + quote + rebase(unquotedUrl, rebaseConfig) + quote + URL_SUFFIX; +} + +module.exports = rewriteUrl; diff --git a/node_modules/clean-css/lib/tokenizer/marker.js b/node_modules/clean-css/lib/tokenizer/marker.js new file mode 100644 index 0000000..270fdbc --- /dev/null +++ b/node_modules/clean-css/lib/tokenizer/marker.js @@ -0,0 +1,26 @@ +var Marker = { + ASTERISK: '*', + AT: '@', + BACK_SLASH: '\\', + CARRIAGE_RETURN: '\r', + CLOSE_CURLY_BRACKET: '}', + CLOSE_ROUND_BRACKET: ')', + CLOSE_SQUARE_BRACKET: ']', + COLON: ':', + COMMA: ',', + DOUBLE_QUOTE: '"', + EXCLAMATION: '!', + FORWARD_SLASH: '/', + INTERNAL: '-clean-css-', + NEW_LINE_NIX: '\n', + OPEN_CURLY_BRACKET: '{', + OPEN_ROUND_BRACKET: '(', + OPEN_SQUARE_BRACKET: '[', + SEMICOLON: ';', + SINGLE_QUOTE: '\'', + SPACE: ' ', + TAB: '\t', + UNDERSCORE: '_' +}; + +module.exports = Marker; diff --git a/node_modules/clean-css/lib/tokenizer/token.js b/node_modules/clean-css/lib/tokenizer/token.js new file mode 100644 index 0000000..a1d726f --- /dev/null +++ b/node_modules/clean-css/lib/tokenizer/token.js @@ -0,0 +1,17 @@ +var Token = { + AT_RULE: 'at-rule', // e.g. `@import`, `@charset` + AT_RULE_BLOCK: 'at-rule-block', // e.g. `@font-face{...}` + AT_RULE_BLOCK_SCOPE: 'at-rule-block-scope', // e.g. `@font-face` + COMMENT: 'comment', // e.g. `/* comment */` + NESTED_BLOCK: 'nested-block', // e.g. `@media screen{...}`, `@keyframes animation {...}` + NESTED_BLOCK_SCOPE: 'nested-block-scope', // e.g. `@media`, `@keyframes` + PROPERTY: 'property', // e.g. `color:red` + PROPERTY_BLOCK: 'property-block', // e.g. `--var:{color:red}` + PROPERTY_NAME: 'property-name', // e.g. `color` + PROPERTY_VALUE: 'property-value', // e.g. `red` + RAW: 'raw', // e.g. anything between /* clean-css ignore:start */ and /* clean-css ignore:end */ comments + RULE: 'rule', // e.g `div > a{...}` + RULE_SCOPE: 'rule-scope' // e.g `div > a` +}; + +module.exports = Token; diff --git a/node_modules/clean-css/lib/tokenizer/tokenize.js b/node_modules/clean-css/lib/tokenizer/tokenize.js new file mode 100644 index 0000000..39c9e67 --- /dev/null +++ b/node_modules/clean-css/lib/tokenizer/tokenize.js @@ -0,0 +1,571 @@ +var Marker = require('./marker'); +var Token = require('./token'); + +var formatPosition = require('../utils/format-position'); + +var Level = { + BLOCK: 'block', + COMMENT: 'comment', + DOUBLE_QUOTE: 'double-quote', + RULE: 'rule', + SINGLE_QUOTE: 'single-quote' +}; + +var AT_RULES = [ + '@charset', + '@import' +]; + +var BLOCK_RULES = [ + '@-moz-document', + '@document', + '@-moz-keyframes', + '@-ms-keyframes', + '@-o-keyframes', + '@-webkit-keyframes', + '@keyframes', + '@media', + '@supports' +]; + +var IGNORE_END_COMMENT_PATTERN = /\/\* clean\-css ignore:end \*\/$/; +var IGNORE_START_COMMENT_PATTERN = /^\/\* clean\-css ignore:start \*\//; + +var PAGE_MARGIN_BOXES = [ + '@bottom-center', + '@bottom-left', + '@bottom-left-corner', + '@bottom-right', + '@bottom-right-corner', + '@left-bottom', + '@left-middle', + '@left-top', + '@right-bottom', + '@right-middle', + '@right-top', + '@top-center', + '@top-left', + '@top-left-corner', + '@top-right', + '@top-right-corner' +]; + +var EXTRA_PAGE_BOXES = [ + '@footnote', + '@footnotes', + '@left', + '@page-float-bottom', + '@page-float-top', + '@right' +]; + +var REPEAT_PATTERN = /^\[\s{0,31}\d+\s{0,31}\]$/; +var RULE_WORD_SEPARATOR_PATTERN = /[\s\(]/; +var TAIL_BROKEN_VALUE_PATTERN = /[\s|\}]*$/; + +function tokenize(source, externalContext) { + var internalContext = { + level: Level.BLOCK, + position: { + source: externalContext.source || undefined, + line: 1, + column: 0, + index: 0 + } + }; + + return intoTokens(source, externalContext, internalContext, false); +} + +function intoTokens(source, externalContext, internalContext, isNested) { + var allTokens = []; + var newTokens = allTokens; + var lastToken; + var ruleToken; + var ruleTokens = []; + var propertyToken; + var metadata; + var metadatas = []; + var level = internalContext.level; + var levels = []; + var buffer = []; + var buffers = []; + var serializedBuffer; + var serializedBufferPart; + var roundBracketLevel = 0; + var isQuoted; + var isSpace; + var isNewLineNix; + var isNewLineWin; + var isCarriageReturn; + var isCommentStart; + var wasCommentStart = false; + var isCommentEnd; + var wasCommentEnd = false; + var isCommentEndMarker; + var isEscaped; + var wasEscaped = false; + var isRaw = false; + var seekingValue = false; + var seekingPropertyBlockClosing = false; + var position = internalContext.position; + var lastCommentStartAt; + + for (; position.index < source.length; position.index++) { + var character = source[position.index]; + + isQuoted = level == Level.SINGLE_QUOTE || level == Level.DOUBLE_QUOTE; + isSpace = character == Marker.SPACE || character == Marker.TAB; + isNewLineNix = character == Marker.NEW_LINE_NIX; + isNewLineWin = character == Marker.NEW_LINE_NIX && source[position.index - 1] == Marker.CARRIAGE_RETURN; + isCarriageReturn = character == Marker.CARRIAGE_RETURN && source[position.index + 1] && source[position.index + 1] != Marker.NEW_LINE_NIX; + isCommentStart = !wasCommentEnd && level != Level.COMMENT && !isQuoted && character == Marker.ASTERISK && source[position.index - 1] == Marker.FORWARD_SLASH; + isCommentEndMarker = !wasCommentStart && !isQuoted && character == Marker.FORWARD_SLASH && source[position.index - 1] == Marker.ASTERISK; + isCommentEnd = level == Level.COMMENT && isCommentEndMarker; + roundBracketLevel = Math.max(roundBracketLevel, 0); + + metadata = buffer.length === 0 ? + [position.line, position.column, position.source] : + metadata; + + if (isEscaped) { + // previous character was a backslash + buffer.push(character); + } else if (!isCommentEnd && level == Level.COMMENT) { + buffer.push(character); + } else if (!isCommentStart && !isCommentEnd && isRaw) { + buffer.push(character); + } else if (isCommentStart && (level == Level.BLOCK || level == Level.RULE) && buffer.length > 1) { + // comment start within block preceded by some content, e.g. div/*<-- + metadatas.push(metadata); + buffer.push(character); + buffers.push(buffer.slice(0, buffer.length - 2)); + + buffer = buffer.slice(buffer.length - 2); + metadata = [position.line, position.column - 1, position.source]; + + levels.push(level); + level = Level.COMMENT; + } else if (isCommentStart) { + // comment start, e.g. /*<-- + levels.push(level); + level = Level.COMMENT; + buffer.push(character); + } else if (isCommentEnd && isIgnoreStartComment(buffer)) { + // ignore:start comment end, e.g. /* clean-css ignore:start */<-- + serializedBuffer = buffer.join('').trim() + character; + lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]; + newTokens.push(lastToken); + + isRaw = true; + metadata = metadatas.pop() || null; + buffer = buffers.pop() || []; + } else if (isCommentEnd && isIgnoreEndComment(buffer)) { + // ignore:start comment end, e.g. /* clean-css ignore:end */<-- + serializedBuffer = buffer.join('') + character; + lastCommentStartAt = serializedBuffer.lastIndexOf(Marker.FORWARD_SLASH + Marker.ASTERISK); + + serializedBufferPart = serializedBuffer.substring(0, lastCommentStartAt); + lastToken = [Token.RAW, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]]; + newTokens.push(lastToken); + + serializedBufferPart = serializedBuffer.substring(lastCommentStartAt); + metadata = [position.line, position.column - serializedBufferPart.length + 1, position.source]; + lastToken = [Token.COMMENT, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]]; + newTokens.push(lastToken); + + isRaw = false; + level = levels.pop(); + metadata = metadatas.pop() || null; + buffer = buffers.pop() || []; + } else if (isCommentEnd) { + // comment end, e.g. /* comment */<-- + serializedBuffer = buffer.join('').trim() + character; + lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]; + newTokens.push(lastToken); + + level = levels.pop(); + metadata = metadatas.pop() || null; + buffer = buffers.pop() || []; + } else if (isCommentEndMarker && source[position.index + 1] != Marker.ASTERISK) { + externalContext.warnings.push('Unexpected \'*/\' at ' + formatPosition([position.line, position.column, position.source]) + '.'); + buffer = []; + } else if (character == Marker.SINGLE_QUOTE && !isQuoted) { + // single quotation start, e.g. a[href^='https<-- + levels.push(level); + level = Level.SINGLE_QUOTE; + buffer.push(character); + } else if (character == Marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) { + // single quotation end, e.g. a[href^='https'<-- + level = levels.pop(); + buffer.push(character); + } else if (character == Marker.DOUBLE_QUOTE && !isQuoted) { + // double quotation start, e.g. a[href^="<-- + levels.push(level); + level = Level.DOUBLE_QUOTE; + buffer.push(character); + } else if (character == Marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) { + // double quotation end, e.g. a[href^="https"<-- + level = levels.pop(); + buffer.push(character); + } else if (!isCommentStart && !isCommentEnd && character != Marker.CLOSE_ROUND_BRACKET && character != Marker.OPEN_ROUND_BRACKET && level != Level.COMMENT && !isQuoted && roundBracketLevel > 0) { + // character inside any function, e.g. hsla(.<-- + buffer.push(character); + } else if (character == Marker.OPEN_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) { + // round open bracket, e.g. @import url(<-- + buffer.push(character); + + roundBracketLevel++; + } else if (character == Marker.CLOSE_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) { + // round open bracket, e.g. @import url(test.css)<-- + buffer.push(character); + + roundBracketLevel--; + } else if (character == Marker.SEMICOLON && level == Level.BLOCK && buffer[0] == Marker.AT) { + // semicolon ending rule at block level, e.g. @import '...';<-- + serializedBuffer = buffer.join('').trim(); + allTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + buffer = []; + } else if (character == Marker.COMMA && level == Level.BLOCK && ruleToken) { + // comma separator at block level, e.g. a,div,<-- + serializedBuffer = buffer.join('').trim(); + ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]); + + buffer = []; + } else if (character == Marker.COMMA && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.AT_RULE) { + // comma separator at block level, e.g. @import url(...) screen,<-- + // keep iterating as end semicolon will create the token + buffer.push(character); + } else if (character == Marker.COMMA && level == Level.BLOCK) { + // comma separator at block level, e.g. a,<-- + ruleToken = [tokenTypeFrom(buffer), [], []]; + serializedBuffer = buffer.join('').trim(); + ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, 0)]]); + + buffer = []; + } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && ruleToken && ruleToken[0] == Token.NESTED_BLOCK) { + // open brace opening at-rule at block level, e.g. @media{<-- + serializedBuffer = buffer.join('').trim(); + ruleToken[1].push([Token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + allTokens.push(ruleToken); + + levels.push(level); + position.column++; + position.index++; + buffer = []; + + ruleToken[2] = intoTokens(source, externalContext, internalContext, true); + ruleToken = null; + } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.NESTED_BLOCK) { + // open brace opening at-rule at block level, e.g. @media{<-- + serializedBuffer = buffer.join('').trim(); + ruleToken = ruleToken || [Token.NESTED_BLOCK, [], []]; + ruleToken[1].push([Token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + allTokens.push(ruleToken); + + levels.push(level); + position.column++; + position.index++; + buffer = []; + + ruleToken[2] = intoTokens(source, externalContext, internalContext, true); + ruleToken = null; + } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK) { + // open brace opening rule at block level, e.g. div{<-- + serializedBuffer = buffer.join('').trim(); + ruleToken = ruleToken || [tokenTypeFrom(buffer), [], []]; + ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]); + newTokens = ruleToken[2]; + allTokens.push(ruleToken); + + levels.push(level); + level = Level.RULE; + buffer = []; + } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.RULE && seekingValue) { + // open brace opening rule at rule level, e.g. div{--variable:{<-- + ruleTokens.push(ruleToken); + ruleToken = [Token.PROPERTY_BLOCK, []]; + propertyToken.push(ruleToken); + newTokens = ruleToken[1]; + + levels.push(level); + level = Level.RULE; + seekingValue = false; + } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.RULE && isPageMarginBox(buffer)) { + // open brace opening page-margin box at rule level, e.g. @page{@top-center{<-- + serializedBuffer = buffer.join('').trim(); + ruleTokens.push(ruleToken); + ruleToken = [Token.AT_RULE_BLOCK, [], []]; + ruleToken[1].push([Token.AT_RULE_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + newTokens.push(ruleToken); + newTokens = ruleToken[2]; + + levels.push(level); + level = Level.RULE; + buffer = []; + } else if (character == Marker.COLON && level == Level.RULE && !seekingValue) { + // colon at rule level, e.g. a{color:<-- + serializedBuffer = buffer.join('').trim(); + propertyToken = [Token.PROPERTY, [Token.PROPERTY_NAME, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]]; + newTokens.push(propertyToken); + + seekingValue = true; + buffer = []; + } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && ruleTokens.length > 0 && buffer.length > 0 && buffer[0] == Marker.AT) { + // semicolon at rule level for at-rule, e.g. a{--color:{@apply(--other-color);<-- + serializedBuffer = buffer.join('').trim(); + ruleToken[1].push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + buffer = []; + } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length > 0) { + // semicolon at rule level, e.g. a{color:red;<-- + serializedBuffer = buffer.join('').trim(); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + propertyToken = null; + seekingValue = false; + buffer = []; + } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length === 0) { + // semicolon after bracketed value at rule level, e.g. a{color:rgb(...);<-- + propertyToken = null; + seekingValue = false; + } else if (character == Marker.SEMICOLON && level == Level.RULE && buffer.length > 0 && buffer[0] == Marker.AT) { + // semicolon for at-rule at rule level, e.g. a{@apply(--variable);<-- + serializedBuffer = buffer.join(''); + newTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + seekingValue = false; + buffer = []; + } else if (character == Marker.SEMICOLON && level == Level.RULE && seekingPropertyBlockClosing) { + // close brace after a property block at rule level, e.g. a{--custom:{color:red;};<-- + seekingPropertyBlockClosing = false; + buffer = []; + } else if (character == Marker.SEMICOLON && level == Level.RULE && buffer.length === 0) { + // stray semicolon at rule level, e.g. a{;<-- + // noop + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && seekingValue && buffer.length > 0 && ruleTokens.length > 0) { + // close brace at rule level, e.g. a{--color:{color:red}<-- + serializedBuffer = buffer.join(''); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + propertyToken = null; + ruleToken = ruleTokens.pop(); + newTokens = ruleToken[2]; + + level = levels.pop(); + seekingValue = false; + buffer = []; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0 && buffer[0] == Marker.AT && ruleTokens.length > 0) { + // close brace at rule level for at-rule, e.g. a{--color:{@apply(--other-color)}<-- + serializedBuffer = buffer.join(''); + ruleToken[1].push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + propertyToken = null; + ruleToken = ruleTokens.pop(); + newTokens = ruleToken[2]; + + level = levels.pop(); + seekingValue = false; + buffer = []; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && ruleTokens.length > 0) { + // close brace at rule level after space, e.g. a{--color:{color:red }<-- + propertyToken = null; + ruleToken = ruleTokens.pop(); + newTokens = ruleToken[2]; + + level = levels.pop(); + seekingValue = false; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0) { + // close brace at rule level, e.g. a{color:red}<-- + serializedBuffer = buffer.join(''); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + propertyToken = null; + ruleToken = ruleTokens.pop(); + newTokens = allTokens; + + level = levels.pop(); + seekingValue = false; + buffer = []; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && buffer.length > 0 && buffer[0] == Marker.AT) { + // close brace after at-rule at rule level, e.g. a{@apply(--variable)}<-- + propertyToken = null; + ruleToken = null; + serializedBuffer = buffer.join('').trim(); + newTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + newTokens = allTokens; + + level = levels.pop(); + seekingValue = false; + buffer = []; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && levels[levels.length - 1] == Level.RULE) { + // close brace after a property block at rule level, e.g. a{--custom:{color:red;}<-- + propertyToken = null; + ruleToken = ruleTokens.pop(); + newTokens = ruleToken[2]; + + level = levels.pop(); + seekingValue = false; + seekingPropertyBlockClosing = true; + buffer = []; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE) { + // close brace after a rule, e.g. a{color:red;}<-- + propertyToken = null; + ruleToken = null; + newTokens = allTokens; + + level = levels.pop(); + seekingValue = false; + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK && !isNested && position.index <= source.length - 1) { + // stray close brace at block level, e.g. a{color:red}color:blue}<-- + externalContext.warnings.push('Unexpected \'}\' at ' + formatPosition([position.line, position.column, position.source]) + '.'); + buffer.push(character); + } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK) { + // close brace at block level, e.g. @media screen {...}<-- + break; + } else if (character == Marker.OPEN_ROUND_BRACKET && level == Level.RULE && seekingValue) { + // round open bracket, e.g. a{color:hsla(<-- + buffer.push(character); + roundBracketLevel++; + } else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue && roundBracketLevel == 1) { + // round close bracket, e.g. a{color:hsla(0,0%,0%)<-- + buffer.push(character); + serializedBuffer = buffer.join('').trim(); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + roundBracketLevel--; + buffer = []; + } else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue) { + // round close bracket within other brackets, e.g. a{width:calc((10rem / 2)<-- + buffer.push(character); + roundBracketLevel--; + } else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue && buffer.length > 0) { + // forward slash within a property, e.g. a{background:url(image.png) 0 0/<-- + serializedBuffer = buffer.join('').trim(); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); + + buffer = []; + } else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue) { + // forward slash within a property after space, e.g. a{background:url(image.png) 0 0 /<-- + propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); + + buffer = []; + } else if (character == Marker.COMMA && level == Level.RULE && seekingValue && buffer.length > 0) { + // comma within a property, e.g. a{background:url(image.png),<-- + serializedBuffer = buffer.join('').trim(); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); + + buffer = []; + } else if (character == Marker.COMMA && level == Level.RULE && seekingValue) { + // comma within a property after space, e.g. a{background:url(image.png) ,<-- + propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); + + buffer = []; + } else if (character == Marker.CLOSE_SQUARE_BRACKET && propertyToken && propertyToken.length > 1 && buffer.length > 0 && isRepeatToken(buffer)) { + buffer.push(character); + serializedBuffer = buffer.join('').trim(); + propertyToken[propertyToken.length - 1][1] += serializedBuffer; + + buffer = []; + } else if ((isSpace || (isNewLineNix && !isNewLineWin)) && level == Level.RULE && seekingValue && propertyToken && buffer.length > 0) { + // space or *nix newline within property, e.g. a{margin:0 <-- + serializedBuffer = buffer.join('').trim(); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + buffer = []; + } else if (isNewLineWin && level == Level.RULE && seekingValue && propertyToken && buffer.length > 1) { + // win newline within property, e.g. a{margin:0\r\n<-- + serializedBuffer = buffer.join('').trim(); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + buffer = []; + } else if (isNewLineWin && level == Level.RULE && seekingValue) { + // win newline + buffer = []; + } else if (buffer.length == 1 && isNewLineWin) { + // ignore windows newline which is composed of two characters + buffer.pop(); + } else if (buffer.length > 0 || !isSpace && !isNewLineNix && !isNewLineWin && !isCarriageReturn) { + // any character + buffer.push(character); + } + + wasEscaped = isEscaped; + isEscaped = !wasEscaped && character == Marker.BACK_SLASH; + wasCommentStart = isCommentStart; + wasCommentEnd = isCommentEnd; + + position.line = (isNewLineWin || isNewLineNix || isCarriageReturn) ? position.line + 1 : position.line; + position.column = (isNewLineWin || isNewLineNix || isCarriageReturn) ? 0 : position.column + 1; + } + + if (seekingValue) { + externalContext.warnings.push('Missing \'}\' at ' + formatPosition([position.line, position.column, position.source]) + '.'); + } + + if (seekingValue && buffer.length > 0) { + serializedBuffer = buffer.join('').replace(TAIL_BROKEN_VALUE_PATTERN, ''); + propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); + + buffer = []; + } + + if (buffer.length > 0) { + externalContext.warnings.push('Invalid character(s) \'' + buffer.join('') + '\' at ' + formatPosition(metadata) + '. Ignoring.'); + } + + return allTokens; +} + +function isIgnoreStartComment(buffer) { + return IGNORE_START_COMMENT_PATTERN.test(buffer.join('') + Marker.FORWARD_SLASH); +} + +function isIgnoreEndComment(buffer) { + return IGNORE_END_COMMENT_PATTERN.test(buffer.join('') + Marker.FORWARD_SLASH); +} + +function originalMetadata(metadata, value, externalContext, selectorFallbacks) { + var source = metadata[2]; + + return externalContext.inputSourceMapTracker.isTracking(source) ? + externalContext.inputSourceMapTracker.originalPositionFor(metadata, value.length, selectorFallbacks) : + metadata; +} + +function tokenTypeFrom(buffer) { + var isAtRule = buffer[0] == Marker.AT || buffer[0] == Marker.UNDERSCORE; + var ruleWord = buffer.join('').split(RULE_WORD_SEPARATOR_PATTERN)[0]; + + if (isAtRule && BLOCK_RULES.indexOf(ruleWord) > -1) { + return Token.NESTED_BLOCK; + } else if (isAtRule && AT_RULES.indexOf(ruleWord) > -1) { + return Token.AT_RULE; + } else if (isAtRule) { + return Token.AT_RULE_BLOCK; + } else { + return Token.RULE; + } +} + +function tokenScopeFrom(tokenType) { + if (tokenType == Token.RULE) { + return Token.RULE_SCOPE; + } else if (tokenType == Token.NESTED_BLOCK) { + return Token.NESTED_BLOCK_SCOPE; + } else if (tokenType == Token.AT_RULE_BLOCK) { + return Token.AT_RULE_BLOCK_SCOPE; + } +} + +function isPageMarginBox(buffer) { + var serializedBuffer = buffer.join('').trim(); + + return PAGE_MARGIN_BOXES.indexOf(serializedBuffer) > -1 || EXTRA_PAGE_BOXES.indexOf(serializedBuffer) > -1; +} + +function isRepeatToken(buffer) { + return REPEAT_PATTERN.test(buffer.join('') + Marker.CLOSE_SQUARE_BRACKET); +} + +module.exports = tokenize; diff --git a/node_modules/clean-css/lib/utils/clone-array.js b/node_modules/clean-css/lib/utils/clone-array.js new file mode 100644 index 0000000..b95ee68 --- /dev/null +++ b/node_modules/clean-css/lib/utils/clone-array.js @@ -0,0 +1,12 @@ +function cloneArray(array) { + var cloned = array.slice(0); + + for (var i = 0, l = cloned.length; i < l; i++) { + if (Array.isArray(cloned[i])) + cloned[i] = cloneArray(cloned[i]); + } + + return cloned; +} + +module.exports = cloneArray; diff --git a/node_modules/clean-css/lib/utils/format-position.js b/node_modules/clean-css/lib/utils/format-position.js new file mode 100644 index 0000000..0e3713c --- /dev/null +++ b/node_modules/clean-css/lib/utils/format-position.js @@ -0,0 +1,11 @@ +function formatPosition(metadata) { + var line = metadata[0]; + var column = metadata[1]; + var source = metadata[2]; + + return source ? + source + ':' + line + ':' + column : + line + ':' + column; +} + +module.exports = formatPosition; diff --git a/node_modules/clean-css/lib/utils/has-protocol.js b/node_modules/clean-css/lib/utils/has-protocol.js new file mode 100644 index 0000000..fa1b61f --- /dev/null +++ b/node_modules/clean-css/lib/utils/has-protocol.js @@ -0,0 +1,7 @@ +var NO_PROTOCOL_RESOURCE_PATTERN = /^\/\//; + +function hasProtocol(uri) { + return !NO_PROTOCOL_RESOURCE_PATTERN.test(uri); +} + +module.exports = hasProtocol; diff --git a/node_modules/clean-css/lib/utils/is-data-uri-resource.js b/node_modules/clean-css/lib/utils/is-data-uri-resource.js new file mode 100644 index 0000000..5855811 --- /dev/null +++ b/node_modules/clean-css/lib/utils/is-data-uri-resource.js @@ -0,0 +1,7 @@ +var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/; + +function isDataUriResource(uri) { + return DATA_URI_PATTERN.test(uri); +} + +module.exports = isDataUriResource; diff --git a/node_modules/clean-css/lib/utils/is-http-resource.js b/node_modules/clean-css/lib/utils/is-http-resource.js new file mode 100644 index 0000000..5179c2e --- /dev/null +++ b/node_modules/clean-css/lib/utils/is-http-resource.js @@ -0,0 +1,7 @@ +var HTTP_RESOURCE_PATTERN = /^http:\/\//; + +function isHttpResource(uri) { + return HTTP_RESOURCE_PATTERN.test(uri); +} + +module.exports = isHttpResource; diff --git a/node_modules/clean-css/lib/utils/is-https-resource.js b/node_modules/clean-css/lib/utils/is-https-resource.js new file mode 100644 index 0000000..c6938f5 --- /dev/null +++ b/node_modules/clean-css/lib/utils/is-https-resource.js @@ -0,0 +1,7 @@ +var HTTPS_RESOURCE_PATTERN = /^https:\/\//; + +function isHttpsResource(uri) { + return HTTPS_RESOURCE_PATTERN.test(uri); +} + +module.exports = isHttpsResource; diff --git a/node_modules/clean-css/lib/utils/is-import.js b/node_modules/clean-css/lib/utils/is-import.js new file mode 100644 index 0000000..72abc32 --- /dev/null +++ b/node_modules/clean-css/lib/utils/is-import.js @@ -0,0 +1,7 @@ +var IMPORT_PREFIX_PATTERN = /^@import/i; + +function isImport(value) { + return IMPORT_PREFIX_PATTERN.test(value); +} + +module.exports = isImport; diff --git a/node_modules/clean-css/lib/utils/is-remote-resource.js b/node_modules/clean-css/lib/utils/is-remote-resource.js new file mode 100644 index 0000000..fb3b61f --- /dev/null +++ b/node_modules/clean-css/lib/utils/is-remote-resource.js @@ -0,0 +1,7 @@ +var REMOTE_RESOURCE_PATTERN = /^(\w+:\/\/|\/\/)/; + +function isRemoteResource(uri) { + return REMOTE_RESOURCE_PATTERN.test(uri); +} + +module.exports = isRemoteResource; diff --git a/node_modules/clean-css/lib/utils/natural-compare.js b/node_modules/clean-css/lib/utils/natural-compare.js new file mode 100644 index 0000000..7a52467 --- /dev/null +++ b/node_modules/clean-css/lib/utils/natural-compare.js @@ -0,0 +1,31 @@ +// adapted from http://nedbatchelder.com/blog/200712.html#e20071211T054956 + +var NUMBER_PATTERN = /([0-9]+)/; + +function naturalCompare(value1, value2) { + var keys1 = ('' + value1).split(NUMBER_PATTERN).map(tryParseInt); + var keys2 = ('' + value2).split(NUMBER_PATTERN).map(tryParseInt); + var key1; + var key2; + var compareFirst = Math.min(keys1.length, keys2.length); + var i, l; + + for (i = 0, l = compareFirst; i < l; i++) { + key1 = keys1[i]; + key2 = keys2[i]; + + if (key1 != key2) { + return key1 > key2 ? 1 : -1; + } + } + + return keys1.length > keys2.length ? 1 : (keys1.length == keys2.length ? 0 : -1); +} + +function tryParseInt(value) { + return ('' + parseInt(value)) == value ? + parseInt(value) : + value; +} + +module.exports = naturalCompare; diff --git a/node_modules/clean-css/lib/utils/override.js b/node_modules/clean-css/lib/utils/override.js new file mode 100644 index 0000000..e7f8494 --- /dev/null +++ b/node_modules/clean-css/lib/utils/override.js @@ -0,0 +1,34 @@ +function override(source1, source2) { + var target = {}; + var key1; + var key2; + var item; + + for (key1 in source1) { + item = source1[key1]; + + if (Array.isArray(item)) { + target[key1] = item.slice(0); + } else if (typeof item == 'object' && item !== null) { + target[key1] = override(item, {}); + } else { + target[key1] = item; + } + } + + for (key2 in source2) { + item = source2[key2]; + + if (key2 in target && Array.isArray(item)) { + target[key2] = item.slice(0); + } else if (key2 in target && typeof item == 'object' && item !== null) { + target[key2] = override(target[key2], item); + } else { + target[key2] = item; + } + } + + return target; +} + +module.exports = override; diff --git a/node_modules/clean-css/lib/utils/split.js b/node_modules/clean-css/lib/utils/split.js new file mode 100644 index 0000000..c916255 --- /dev/null +++ b/node_modules/clean-css/lib/utils/split.js @@ -0,0 +1,50 @@ +var Marker = require('../tokenizer/marker'); + +function split(value, separator) { + var openLevel = Marker.OPEN_ROUND_BRACKET; + var closeLevel = Marker.CLOSE_ROUND_BRACKET; + var level = 0; + var cursor = 0; + var lastStart = 0; + var lastValue; + var lastCharacter; + var len = value.length; + var parts = []; + + if (value.indexOf(separator) == -1) { + return [value]; + } + + if (value.indexOf(openLevel) == -1) { + return value.split(separator); + } + + while (cursor < len) { + if (value[cursor] == openLevel) { + level++; + } else if (value[cursor] == closeLevel) { + level--; + } + + if (level === 0 && cursor > 0 && cursor + 1 < len && value[cursor] == separator) { + parts.push(value.substring(lastStart, cursor)); + lastStart = cursor + 1; + } + + cursor++; + } + + if (lastStart < cursor + 1) { + lastValue = value.substring(lastStart); + lastCharacter = lastValue[lastValue.length - 1]; + if (lastCharacter == separator) { + lastValue = lastValue.substring(0, lastValue.length - 1); + } + + parts.push(lastValue); + } + + return parts; +} + +module.exports = split; diff --git a/node_modules/clean-css/lib/writer/helpers.js b/node_modules/clean-css/lib/writer/helpers.js new file mode 100644 index 0000000..1172740 --- /dev/null +++ b/node_modules/clean-css/lib/writer/helpers.js @@ -0,0 +1,243 @@ +var emptyCharacter = ''; + +var Breaks = require('../options/format').Breaks; +var Spaces = require('../options/format').Spaces; + +var Marker = require('../tokenizer/marker'); +var Token = require('../tokenizer/token'); + +function supportsAfterClosingBrace(token) { + return token[1][1] == 'background' || token[1][1] == 'transform' || token[1][1] == 'src'; +} + +function afterClosingBrace(token, valueIndex) { + return token[valueIndex][1][token[valueIndex][1].length - 1] == Marker.CLOSE_ROUND_BRACKET; +} + +function afterComma(token, valueIndex) { + return token[valueIndex][1] == Marker.COMMA; +} + +function afterSlash(token, valueIndex) { + return token[valueIndex][1] == Marker.FORWARD_SLASH; +} + +function beforeComma(token, valueIndex) { + return token[valueIndex + 1] && token[valueIndex + 1][1] == Marker.COMMA; +} + +function beforeSlash(token, valueIndex) { + return token[valueIndex + 1] && token[valueIndex + 1][1] == Marker.FORWARD_SLASH; +} + +function inFilter(token) { + return token[1][1] == 'filter' || token[1][1] == '-ms-filter'; +} + +function disallowsSpace(context, token, valueIndex) { + return !context.spaceAfterClosingBrace && supportsAfterClosingBrace(token) && afterClosingBrace(token, valueIndex) || + beforeSlash(token, valueIndex) || + afterSlash(token, valueIndex) || + beforeComma(token, valueIndex) || + afterComma(token, valueIndex); +} + +function rules(context, tokens) { + var store = context.store; + + for (var i = 0, l = tokens.length; i < l; i++) { + store(context, tokens[i]); + + if (i < l - 1) { + store(context, comma(context)); + } + } +} + +function body(context, tokens) { + var lastPropertyAt = lastPropertyIndex(tokens); + + for (var i = 0, l = tokens.length; i < l; i++) { + property(context, tokens, i, lastPropertyAt); + } +} + +function lastPropertyIndex(tokens) { + var index = tokens.length - 1; + + for (; index >= 0; index--) { + if (tokens[index][0] != Token.COMMENT) { + break; + } + } + + return index; +} + +function property(context, tokens, position, lastPropertyAt) { + var store = context.store; + var token = tokens[position]; + var isPropertyBlock = token[2][0] == Token.PROPERTY_BLOCK; + + var needsSemicolon; + if ( context.format ) { + if ( context.format.semicolonAfterLastProperty || isPropertyBlock ) { + needsSemicolon = true; + } else if ( position < lastPropertyAt ) { + needsSemicolon = true; + } else { + needsSemicolon = false; + } + } else { + needsSemicolon = position < lastPropertyAt || isPropertyBlock; + } + + var isLast = position === lastPropertyAt; + + switch (token[0]) { + case Token.AT_RULE: + store(context, token); + store(context, semicolon(context, Breaks.AfterProperty, false)); + break; + case Token.AT_RULE_BLOCK: + rules(context, token[1]); + store(context, openBrace(context, Breaks.AfterRuleBegins, true)); + body(context, token[2]); + store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast)); + break; + case Token.COMMENT: + store(context, token); + break; + case Token.PROPERTY: + store(context, token[1]); + store(context, colon(context)); + value(context, token); + store(context, needsSemicolon ? semicolon(context, Breaks.AfterProperty, isLast) : emptyCharacter); + break; + case Token.RAW: + store(context, token); + } +} + +function value(context, token) { + var store = context.store; + var j, m; + + if (token[2][0] == Token.PROPERTY_BLOCK) { + store(context, openBrace(context, Breaks.AfterBlockBegins, false)); + body(context, token[2][1]); + store(context, closeBrace(context, Breaks.AfterBlockEnds, false, true)); + } else { + for (j = 2, m = token.length; j < m; j++) { + store(context, token[j]); + + if (j < m - 1 && (inFilter(token) || !disallowsSpace(context, token, j))) { + store(context, Marker.SPACE); + } + } + } +} + +function allowsBreak(context, where) { + return context.format && context.format.breaks[where]; +} + +function allowsSpace(context, where) { + return context.format && context.format.spaces[where]; +} + +function openBrace(context, where, needsPrefixSpace) { + if (context.format) { + context.indentBy += context.format.indentBy; + context.indentWith = context.format.indentWith.repeat(context.indentBy); + return (needsPrefixSpace && allowsSpace(context, Spaces.BeforeBlockBegins) ? Marker.SPACE : emptyCharacter) + + Marker.OPEN_CURLY_BRACKET + + (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) + + context.indentWith; + } else { + return Marker.OPEN_CURLY_BRACKET; + } +} + +function closeBrace(context, where, beforeBlockEnd, isLast) { + if (context.format) { + context.indentBy -= context.format.indentBy; + context.indentWith = context.format.indentWith.repeat(context.indentBy); + return (allowsBreak(context, Breaks.AfterProperty) || beforeBlockEnd && allowsBreak(context, Breaks.BeforeBlockEnds) ? context.format.breakWith : emptyCharacter) + + context.indentWith + + Marker.CLOSE_CURLY_BRACKET + + (isLast ? emptyCharacter : (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) + context.indentWith); + } else { + return Marker.CLOSE_CURLY_BRACKET; + } +} + +function colon(context) { + return context.format ? + Marker.COLON + (allowsSpace(context, Spaces.BeforeValue) ? Marker.SPACE : emptyCharacter) : + Marker.COLON; +} + +function semicolon(context, where, isLast) { + return context.format ? + Marker.SEMICOLON + (isLast || !allowsBreak(context, where) ? emptyCharacter : context.format.breakWith + context.indentWith) : + Marker.SEMICOLON; +} + +function comma(context) { + return context.format ? + Marker.COMMA + (allowsBreak(context, Breaks.BetweenSelectors) ? context.format.breakWith : emptyCharacter) + context.indentWith : + Marker.COMMA; +} + +function all(context, tokens) { + var store = context.store; + var token; + var isLast; + var i, l; + + for (i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + isLast = i == l - 1; + + switch (token[0]) { + case Token.AT_RULE: + store(context, token); + store(context, semicolon(context, Breaks.AfterAtRule, isLast)); + break; + case Token.AT_RULE_BLOCK: + rules(context, token[1]); + store(context, openBrace(context, Breaks.AfterRuleBegins, true)); + body(context, token[2]); + store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast)); + break; + case Token.NESTED_BLOCK: + rules(context, token[1]); + store(context, openBrace(context, Breaks.AfterBlockBegins, true)); + all(context, token[2]); + store(context, closeBrace(context, Breaks.AfterBlockEnds, true, isLast)); + break; + case Token.COMMENT: + store(context, token); + store(context, allowsBreak(context, Breaks.AfterComment) ? context.format.breakWith : emptyCharacter); + break; + case Token.RAW: + store(context, token); + break; + case Token.RULE: + rules(context, token[1]); + store(context, openBrace(context, Breaks.AfterRuleBegins, true)); + body(context, token[2]); + store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast)); + break; + } + } +} + +module.exports = { + all: all, + body: body, + property: property, + rules: rules, + value: value +}; diff --git a/node_modules/clean-css/lib/writer/one-time.js b/node_modules/clean-css/lib/writer/one-time.js new file mode 100644 index 0000000..33fccea --- /dev/null +++ b/node_modules/clean-css/lib/writer/one-time.js @@ -0,0 +1,52 @@ +var helpers = require('./helpers'); + +function store(serializeContext, token) { + serializeContext.output.push(typeof token == 'string' ? token : token[1]); +} + +function context() { + var newContext = { + output: [], + store: store + }; + + return newContext; +} + +function all(tokens) { + var oneTimeContext = context(); + helpers.all(oneTimeContext, tokens); + return oneTimeContext.output.join(''); +} + +function body(tokens) { + var oneTimeContext = context(); + helpers.body(oneTimeContext, tokens); + return oneTimeContext.output.join(''); +} + +function property(tokens, position) { + var oneTimeContext = context(); + helpers.property(oneTimeContext, tokens, position, true); + return oneTimeContext.output.join(''); +} + +function rules(tokens) { + var oneTimeContext = context(); + helpers.rules(oneTimeContext, tokens); + return oneTimeContext.output.join(''); +} + +function value(tokens) { + var oneTimeContext = context(); + helpers.value(oneTimeContext, tokens); + return oneTimeContext.output.join(''); +} + +module.exports = { + all: all, + body: body, + property: property, + rules: rules, + value: value +}; diff --git a/node_modules/clean-css/lib/writer/simple.js b/node_modules/clean-css/lib/writer/simple.js new file mode 100644 index 0000000..20fde2a --- /dev/null +++ b/node_modules/clean-css/lib/writer/simple.js @@ -0,0 +1,50 @@ +var all = require('./helpers').all; + +function store(serializeContext, token) { + var value = typeof token == 'string' ? + token : + token[1]; + var wrap = serializeContext.wrap; + + wrap(serializeContext, value); + track(serializeContext, value); + serializeContext.output.push(value); +} + +function wrap(serializeContext, value) { + if (serializeContext.column + value.length > serializeContext.format.wrapAt) { + track(serializeContext, serializeContext.format.breakWith); + serializeContext.output.push(serializeContext.format.breakWith); + } +} + +function track(serializeContext, value) { + var parts = value.split('\n'); + + serializeContext.line += parts.length - 1; + serializeContext.column = parts.length > 1 ? 0 : (serializeContext.column + parts.pop().length); +} + +function serializeStyles(tokens, context) { + var serializeContext = { + column: 0, + format: context.options.format, + indentBy: 0, + indentWith: '', + line: 1, + output: [], + spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace, + store: store, + wrap: context.options.format.wrapAt ? + wrap : + function () { /* noop */ } + }; + + all(serializeContext, tokens); + + return { + styles: serializeContext.output.join('') + }; +} + +module.exports = serializeStyles; diff --git a/node_modules/clean-css/lib/writer/source-maps.js b/node_modules/clean-css/lib/writer/source-maps.js new file mode 100644 index 0000000..6856579 --- /dev/null +++ b/node_modules/clean-css/lib/writer/source-maps.js @@ -0,0 +1,101 @@ +var SourceMapGenerator = require('source-map').SourceMapGenerator; +var all = require('./helpers').all; + +var isRemoteResource = require('../utils/is-remote-resource'); + +var isWindows = process.platform == 'win32'; + +var NIX_SEPARATOR_PATTERN = /\//g; +var UNKNOWN_SOURCE = '$stdin'; +var WINDOWS_SEPARATOR = '\\'; + +function store(serializeContext, element) { + var fromString = typeof element == 'string'; + var value = fromString ? element : element[1]; + var mappings = fromString ? null : element[2]; + var wrap = serializeContext.wrap; + + wrap(serializeContext, value); + track(serializeContext, value, mappings); + serializeContext.output.push(value); +} + +function wrap(serializeContext, value) { + if (serializeContext.column + value.length > serializeContext.format.wrapAt) { + track(serializeContext, serializeContext.format.breakWith, false); + serializeContext.output.push(serializeContext.format.breakWith); + } +} + +function track(serializeContext, value, mappings) { + var parts = value.split('\n'); + + if (mappings) { + trackAllMappings(serializeContext, mappings); + } + + serializeContext.line += parts.length - 1; + serializeContext.column = parts.length > 1 ? 0 : (serializeContext.column + parts.pop().length); +} + +function trackAllMappings(serializeContext, mappings) { + for (var i = 0, l = mappings.length; i < l; i++) { + trackMapping(serializeContext, mappings[i]); + } +} + +function trackMapping(serializeContext, mapping) { + var line = mapping[0]; + var column = mapping[1]; + var originalSource = mapping[2]; + var source = originalSource; + var storedSource = source || UNKNOWN_SOURCE; + + if (isWindows && source && !isRemoteResource(source)) { + storedSource = source.replace(NIX_SEPARATOR_PATTERN, WINDOWS_SEPARATOR); + } + + serializeContext.outputMap.addMapping({ + generated: { + line: serializeContext.line, + column: serializeContext.column + }, + source: storedSource, + original: { + line: line, + column: column + } + }); + + if (serializeContext.inlineSources && (originalSource in serializeContext.sourcesContent)) { + serializeContext.outputMap.setSourceContent(storedSource, serializeContext.sourcesContent[originalSource]); + } +} + +function serializeStylesAndSourceMap(tokens, context) { + var serializeContext = { + column: 0, + format: context.options.format, + indentBy: 0, + indentWith: '', + inlineSources: context.options.sourceMapInlineSources, + line: 1, + output: [], + outputMap: new SourceMapGenerator(), + sourcesContent: context.sourcesContent, + spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace, + store: store, + wrap: context.options.format.wrapAt ? + wrap : + function () { /* noop */ } + }; + + all(serializeContext, tokens); + + return { + sourceMap: serializeContext.outputMap, + styles: serializeContext.output.join('') + }; +} + +module.exports = serializeStylesAndSourceMap; diff --git a/node_modules/clean-css/package.json b/node_modules/clean-css/package.json new file mode 100644 index 0000000..c18beda --- /dev/null +++ b/node_modules/clean-css/package.json @@ -0,0 +1,78 @@ +{ + "_from": "clean-css@^4.1.6", + "_id": "clean-css@4.2.1", + "_inBundle": false, + "_integrity": "sha512-4ZxI6dy4lrY6FHzfiy1aEOXgu4LIsW2MhwG0VBKdcoGoH/XLFgaHSdLTGr4O8Be6A8r3MOphEiI8Gc1n0ecf3g==", + "_location": "/clean-css", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "clean-css@^4.1.6", + "name": "clean-css", + "escapedName": "clean-css", + "rawSpec": "^4.1.6", + "saveSpec": null, + "fetchSpec": "^4.1.6" + }, + "_requiredBy": [ + "/html-minifier", + "/minify" + ], + "_resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.2.1.tgz", + "_shasum": "2d411ef76b8569b6d0c84068dabe85b0aa5e5c17", + "_spec": "clean-css@^4.1.6", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\minify", + "author": { + "name": "Jakub Pawlowicz", + "email": "contact@jakubpawlowicz.com", + "url": "http://twitter.com/jakubpawlowicz" + }, + "bugs": { + "url": "https://github.com/jakubpawlowicz/clean-css/issues" + }, + "bundleDependencies": false, + "dependencies": { + "source-map": "~0.6.0" + }, + "deprecated": false, + "description": "A well-tested CSS minifier", + "devDependencies": { + "browserify": "^14.0.0", + "http-proxy": "1.x", + "jshint": "2.x", + "nock": "9.x", + "server-destroy": "1.x", + "uglify-js": ">=2.6.1", + "vows": "0.8.x" + }, + "engines": { + "node": ">= 4.0" + }, + "files": [ + "lib", + "History.md", + "index.js", + "LICENSE" + ], + "homepage": "https://github.com/jakubpawlowicz/clean-css", + "keywords": [ + "css", + "minifier" + ], + "license": "MIT", + "main": "index.js", + "name": "clean-css", + "repository": { + "type": "git", + "url": "git+https://github.com/jakubpawlowicz/clean-css.git" + }, + "scripts": { + "bench": "node ./test/bench.js", + "browserify": "browserify --standalone CleanCSS index.js | uglifyjs --compress --mangle -o cleancss-browser.js", + "check": "jshint .", + "prepublish": "npm run check", + "test": "vows" + }, + "version": "4.2.1" +} diff --git a/node_modules/combined-stream/License b/node_modules/combined-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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. diff --git a/node_modules/combined-stream/Readme.md b/node_modules/combined-stream/Readme.md new file mode 100644 index 0000000..9e367b5 --- /dev/null +++ b/node_modules/combined-stream/Readme.md @@ -0,0 +1,138 @@ +# combined-stream + +A stream that emits multiple other streams one after another. + +**NB** Currently `combined-stream` works with streams version 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatibility with `combined-stream`. + +- [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module. + +- [multistream](https://www.npmjs.com/package/multistream): A stream that emits multiple other streams one after another. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/combined-stream/lib/combined_stream.js b/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 0000000..809b3c2 --- /dev/null +++ b/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,189 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); +var defer = require('./defer.js'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + defer(this._pipeNext.bind(this, stream)); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/combined-stream/lib/defer.js b/node_modules/combined-stream/lib/defer.js new file mode 100644 index 0000000..b67110c --- /dev/null +++ b/node_modules/combined-stream/lib/defer.js @@ -0,0 +1,26 @@ +module.exports = defer; + +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} diff --git a/node_modules/combined-stream/package.json b/node_modules/combined-stream/package.json new file mode 100644 index 0000000..18d04f7 --- /dev/null +++ b/node_modules/combined-stream/package.json @@ -0,0 +1,58 @@ +{ + "_from": "combined-stream@~1.0.6", + "_id": "combined-stream@1.0.7", + "_inBundle": false, + "_integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", + "_location": "/combined-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "combined-stream@~1.0.6", + "name": "combined-stream", + "escapedName": "combined-stream", + "rawSpec": "~1.0.6", + "saveSpec": null, + "fetchSpec": "~1.0.6" + }, + "_requiredBy": [ + "/form-data", + "/request" + ], + "_resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", + "_shasum": "2d1d24317afb8abe95d6d2c0b07b57813539d828", + "_spec": "combined-stream@~1.0.6", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\request", + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "bugs": { + "url": "https://github.com/felixge/node-combined-stream/issues" + }, + "bundleDependencies": false, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "deprecated": false, + "description": "A stream that emits multiple other streams one after another.", + "devDependencies": { + "far": "~0.0.7" + }, + "engines": { + "node": ">= 0.8" + }, + "homepage": "https://github.com/felixge/node-combined-stream", + "license": "MIT", + "main": "./lib/combined_stream", + "name": "combined-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "scripts": { + "test": "node test/run.js" + }, + "version": "1.0.7" +} diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md new file mode 100644 index 0000000..67d68c5 --- /dev/null +++ b/node_modules/commander/CHANGELOG.md @@ -0,0 +1,382 @@ + +2.17.1 / 2018-08-07 +================== + + * Fix bug in command emit (#844) + +2.17.0 / 2018-08-03 +================== + + * fixed newline output after help information (#833) + * Fix to emit the action even without command (#778) + * npm update (#823) + +2.16.0 / 2018-06-29 +================== + + * Remove Makefile and `test/run` (#821) + * Make 'npm test' run on Windows (#820) + * Add badge to display install size (#807) + * chore: cache node_modules (#814) + * chore: remove Node.js 4 (EOL), add Node.js 10 (#813) + * fixed typo in readme (#812) + * Fix types (#804) + * Update eslint to resolve vulnerabilities in lodash (#799) + * updated readme with custom event listeners. (#791) + * fix tests (#794) + +2.15.0 / 2018-03-07 +================== + + * Update downloads badge to point to graph of downloads over time instead of duplicating link to npm + * Arguments description + +2.14.1 / 2018-02-07 +================== + + * Fix typing of help function + +2.14.0 / 2018-02-05 +================== + + * only register the option:version event once + * Fixes issue #727: Passing empty string for option on command is set to undefined + * enable eqeqeq rule + * resolves #754 add linter configuration to project + * resolves #560 respect custom name for version option + * document how to override the version flag + * document using options per command + +2.13.0 / 2018-01-09 +================== + + * Do not print default for --no- + * remove trailing spaces in command help + * Update CI's Node.js to LTS and latest version + * typedefs: Command and Option types added to commander namespace + +2.12.2 / 2017-11-28 +================== + + * fix: typings are not shipped + +2.12.1 / 2017-11-23 +================== + + * Move @types/node to dev dependency + +2.12.0 / 2017-11-22 +================== + + * add attributeName() method to Option objects + * Documentation updated for options with --no prefix + * typings: `outputHelp` takes a string as the first parameter + * typings: use overloads + * feat(typings): update to match js api + * Print default value in option help + * Fix translation error + * Fail when using same command and alias (#491) + * feat(typings): add help callback + * fix bug when description is add after command with options (#662) + * Format js code + * Rename History.md to CHANGELOG.md (#668) + * feat(typings): add typings to support TypeScript (#646) + * use current node + +2.11.0 / 2017-07-03 +================== + + * Fix help section order and padding (#652) + * feature: support for signals to subcommands (#632) + * Fixed #37, --help should not display first (#447) + * Fix translation errors. (#570) + * Add package-lock.json + * Remove engines + * Upgrade package version + * Prefix events to prevent conflicts between commands and options (#494) + * Removing dependency on graceful-readlink + * Support setting name in #name function and make it chainable + * Add .vscode directory to .gitignore (Visual Studio Code metadata) + * Updated link to ruby commander in readme files + +2.10.0 / 2017-06-19 +================== + + * Update .travis.yml. drop support for older node.js versions. + * Fix require arguments in README.md + * On SemVer you do not start from 0.0.1 + * Add missing semi colon in readme + * Add save param to npm install + * node v6 travis test + * Update Readme_zh-CN.md + * Allow literal '--' to be passed-through as an argument + * Test subcommand alias help + * link build badge to master branch + * Support the alias of Git style sub-command + * added keyword commander for better search result on npm + * Fix Sub-Subcommands + * test node.js stable + * Fixes TypeError when a command has an option called `--description` + * Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets. + * Add chinese Readme file + +2.9.0 / 2015-10-13 +================== + + * Add option `isDefault` to set default subcommand #415 @Qix- + * Add callback to allow filtering or post-processing of help text #434 @djulien + * Fix `undefined` text in help information close #414 #416 @zhiyelee + +2.8.1 / 2015-04-22 +================== + + * Back out `support multiline description` Close #396 #397 + +2.8.0 / 2015-04-07 +================== + + * Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee + * Fix bug in Git-style sub-commands #372 @zhiyelee + * Allow commands to be hidden from help #383 @tonylukasavage + * When git-style sub-commands are in use, yet none are called, display help #382 @claylo + * Add ability to specify arguments syntax for top-level command #258 @rrthomas + * Support multiline descriptions #208 @zxqfox + +2.7.1 / 2015-03-11 +================== + + * Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. + +2.7.0 / 2015-03-09 +================== + + * Fix git-style bug when installed globally. Close #335 #349 @zhiyelee + * Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage + * Add support for camelCase on `opts()`. Close #353 @nkzawa + * Add node.js 0.12 and io.js to travis.yml + * Allow RegEx options. #337 @palanik + * Fixes exit code when sub-command failing. Close #260 #332 @pirelenito + * git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee + +2.6.0 / 2014-12-30 +================== + + * added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee + * Add application description to the help msg. Close #112 @dalssoft + +2.5.1 / 2014-12-15 +================== + + * fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee + +2.5.0 / 2014-10-24 +================== + + * add support for variadic arguments. Closes #277 @whitlockjc + +2.4.0 / 2014-10-17 +================== + + * fixed a bug on executing the coercion function of subcommands option. Closes #270 + * added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage + * added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage + * fixed a bug on subcommand name. Closes #248 @jonathandelgado + * fixed function normalize doesn’t honor option terminator. Closes #216 @abbr + +2.3.0 / 2014-07-16 +================== + + * add command alias'. Closes PR #210 + * fix: Typos. Closes #99 + * fix: Unused fs module. Closes #217 + +2.2.0 / 2014-03-29 +================== + + * add passing of previous option value + * fix: support subcommands on windows. Closes #142 + * Now the defaultValue passed as the second argument of the coercion function. + +2.1.0 / 2013-11-21 +================== + + * add: allow cflag style option params, unit test, fixes #174 + +2.0.0 / 2013-07-18 +================== + + * remove input methods (.prompt, .confirm, etc) + +1.3.2 / 2013-07-18 +================== + + * add support for sub-commands to co-exist with the original command + +1.3.1 / 2013-07-18 +================== + + * add quick .runningCommand hack so you can opt-out of other logic when running a sub command + +1.3.0 / 2013-07-09 +================== + + * add EACCES error handling + * fix sub-command --help + +1.2.0 / 2013-06-13 +================== + + * allow "-" hyphen as an option argument + * support for RegExp coercion + +1.1.1 / 2012-11-20 +================== + + * add more sub-command padding + * fix .usage() when args are present. Closes #106 + +1.1.0 / 2012-11-16 +================== + + * add git-style executable subcommand support. Closes #94 + +1.0.5 / 2012-10-09 +================== + + * fix `--name` clobbering. Closes #92 + * fix examples/help. Closes #89 + +1.0.4 / 2012-09-03 +================== + + * add `outputHelp()` method. + +1.0.3 / 2012-08-30 +================== + + * remove invalid .version() defaulting + +1.0.2 / 2012-08-24 +================== + + * add `--foo=bar` support [arv] + * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus] + +1.0.1 / 2012-08-03 +================== + + * fix issue #56 + * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) + +1.0.0 / 2012-07-05 +================== + + * add support for optional option descriptions + * add defaulting of `.version()` to package.json's version + +0.6.1 / 2012-06-01 +================== + + * Added: append (yes or no) on confirmation + * Added: allow node.js v0.7.x + +0.6.0 / 2012-04-10 +================== + + * Added `.prompt(obj, callback)` support. Closes #49 + * Added default support to .choose(). Closes #41 + * Fixed the choice example + +0.5.1 / 2011-12-20 +================== + + * Fixed `password()` for recent nodes. Closes #36 + +0.5.0 / 2011-12-04 +================== + + * Added sub-command option support [itay] + +0.4.3 / 2011-12-04 +================== + + * Fixed custom help ordering. Closes #32 + +0.4.2 / 2011-11-24 +================== + + * Added travis support + * Fixed: line-buffered input automatically trimmed. Closes #31 + +0.4.1 / 2011-11-18 +================== + + * Removed listening for "close" on --help + +0.4.0 / 2011-11-15 +================== + + * Added support for `--`. Closes #24 + +0.3.3 / 2011-11-14 +================== + + * Fixed: wait for close event when writing help info [Jerry Hamlet] + +0.3.2 / 2011-11-01 +================== + + * Fixed long flag definitions with values [felixge] + +0.3.1 / 2011-10-31 +================== + + * Changed `--version` short flag to `-V` from `-v` + * Changed `.version()` so it's configurable [felixge] + +0.3.0 / 2011-10-31 +================== + + * Added support for long flags only. Closes #18 + +0.2.1 / 2011-10-24 +================== + + * "node": ">= 0.4.x < 0.7.0". Closes #20 + +0.2.0 / 2011-09-26 +================== + + * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] + +0.1.0 / 2011-08-24 +================== + + * Added support for custom `--help` output + +0.0.5 / 2011-08-18 +================== + + * Changed: when the user enters nothing prompt for password again + * Fixed issue with passwords beginning with numbers [NuckChorris] + +0.0.4 / 2011-08-15 +================== + + * Fixed `Commander#args` + +0.0.3 / 2011-08-15 +================== + + * Added default option value support + +0.0.2 / 2011-08-15 +================== + + * Added mask support to `Command#password(str[, mask], fn)` + * Added `Command#password(str, fn)` + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/commander/LICENSE b/node_modules/commander/LICENSE new file mode 100644 index 0000000..10f997a --- /dev/null +++ b/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +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. diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md new file mode 100644 index 0000000..5897d37 --- /dev/null +++ b/node_modules/commander/Readme.md @@ -0,0 +1,425 @@ +# Commander.js + + +[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) +[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander) +[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). + [API documentation](http://tj.github.com/commander.js/) + + +## Installation + + $ npm install commander --save + +## Option parsing + +Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.1.0') + .option('-p, --peppers', 'Add peppers') + .option('-P, --pineapple', 'Add pineapple') + .option('-b, --bbq-sauce', 'Add bbq sauce') + .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') + .parse(process.argv); + +console.log('you ordered a pizza with:'); +if (program.peppers) console.log(' - peppers'); +if (program.pineapple) console.log(' - pineapple'); +if (program.bbqSauce) console.log(' - bbq'); +console.log(' - %s cheese', program.cheese); +``` + +Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. + +Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .option('--no-sauce', 'Remove sauce') + .parse(process.argv); + +console.log('you ordered a pizza'); +if (program.sauce) console.log(' with sauce'); +else console.log(' without sauce'); +``` + +## Version option + +Calling the `version` implicitly adds the `-V` and `--version` options to the command. +When either of these options is present, the command prints the version number and exits. + + $ ./examples/pizza -V + 0.0.1 + +If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method. + +```js +program + .version('0.0.1', '-v, --version') +``` + +The version flags can be named anything, but the long option is required. + +## Command-specific options + +You can attach options to a command. + +```js +#!/usr/bin/env node + +var program = require('commander'); + +program + .command('rm ') + .option('-r, --recursive', 'Remove recursively') + .action(function (dir, cmd) { + console.log('remove ' + dir + (cmd.recursive ? ' recursively' : '')) + }) + +program.parse(process.argv) +``` + +A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated. + +## Coercion + +```js +function range(val) { + return val.split('..').map(Number); +} + +function list(val) { + return val.split(','); +} + +function collect(val, memo) { + memo.push(val); + return memo; +} + +function increaseVerbosity(v, total) { + return total + 1; +} + +program + .version('0.1.0') + .usage('[options] ') + .option('-i, --integer ', 'An integer argument', parseInt) + .option('-f, --float ', 'A float argument', parseFloat) + .option('-r, --range ..', 'A range', range) + .option('-l, --list ', 'A list', list) + .option('-o, --optional [value]', 'An optional value') + .option('-c, --collect [value]', 'A repeatable value', collect, []) + .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) + .parse(process.argv); + +console.log(' int: %j', program.integer); +console.log(' float: %j', program.float); +console.log(' optional: %j', program.optional); +program.range = program.range || []; +console.log(' range: %j..%j', program.range[0], program.range[1]); +console.log(' list: %j', program.list); +console.log(' collect: %j', program.collect); +console.log(' verbosity: %j', program.verbose); +console.log(' args: %j', program.args); +``` + +## Regular Expression +```js +program + .version('0.1.0') + .option('-s --size ', 'Pizza size', /^(large|medium|small)$/i, 'medium') + .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i) + .parse(process.argv); + +console.log(' size: %j', program.size); +console.log(' drink: %j', program.drink); +``` + +## Variadic arguments + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to + append `...` to the argument name. Here is an example: + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.1.0') + .command('rmdir [otherDirs...]') + .action(function (dir, otherDirs) { + console.log('rmdir %s', dir); + if (otherDirs) { + otherDirs.forEach(function (oDir) { + console.log('rmdir %s', oDir); + }); + } + }); + +program.parse(process.argv); +``` + + An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed + to your action as demonstrated above. + +## Specify the argument syntax + +```js +#!/usr/bin/env node + +var program = require('commander'); + +program + .version('0.1.0') + .arguments(' [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; + }); + +program.parse(process.argv); + +if (typeof cmdValue === 'undefined') { + console.error('no command given!'); + process.exit(1); +} +console.log('command:', cmdValue); +console.log('environment:', envValue || "no environment given"); +``` +Angled brackets (e.g. ``) indicate required input. Square brackets (e.g. `[env]`) indicate optional input. + +## Git-style sub-commands + +```js +// file: ./examples/pm +var program = require('commander'); + +program + .version('0.1.0') + .command('install [name]', 'install one or more packages') + .command('search [query]', 'search with optional query') + .command('list', 'list packages installed', {isDefault: true}) + .parse(process.argv); +``` + +When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. +The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`. + +Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified. + +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. + +### `--harmony` + +You can enable `--harmony` option in two ways: +* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern. +* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process. + +## Automated --help + + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: + +``` + $ ./examples/pizza --help + + Usage: pizza [options] + + An application for pizzas ordering + + Options: + + -h, --help output usage information + -V, --version output the version number + -p, --peppers Add peppers + -P, --pineapple Add pineapple + -b, --bbq Add bbq sauce + -c, --cheese Add the specified type of cheese [marble] + -C, --no-cheese You do not want any cheese + +``` + +## Custom help + + You can display arbitrary `-h, --help` information + by listening for "--help". Commander will automatically + exit once you are done so that the remainder of your program + does not execute causing undesired behaviours, for example + in the following executable "stuff" will not output when + `--help` is used. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.1.0') + .option('-f, --foo', 'enable some foo') + .option('-b, --bar', 'enable some bar') + .option('-B, --baz', 'enable some baz'); + +// must be before .parse() since +// node's emit() is immediate + +program.on('--help', function(){ + console.log(' Examples:'); + console.log(''); + console.log(' $ custom-help --help'); + console.log(' $ custom-help -h'); + console.log(''); +}); + +program.parse(process.argv); + +console.log('stuff'); +``` + +Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run: + +``` + +Usage: custom-help [options] + +Options: + + -h, --help output usage information + -V, --version output the version number + -f, --foo enable some foo + -b, --bar enable some bar + -B, --baz enable some baz + +Examples: + + $ custom-help --help + $ custom-help -h + +``` + +## .outputHelp(cb) + +Output help information without exiting. +Optional callback cb allows post-processing of help text before it is displayed. + +If you want to display help by default (e.g. if no command was provided), you can use something like: + +```js +var program = require('commander'); +var colors = require('colors'); + +program + .version('0.1.0') + .command('getstream [url]', 'get stream URL') + .parse(process.argv); + +if (!process.argv.slice(2).length) { + program.outputHelp(make_red); +} + +function make_red(txt) { + return colors.red(txt); //display the help text in red on the console +} +``` + +## .help(cb) + + Output help information and exit immediately. + Optional callback cb allows post-processing of help text before it is displayed. + + +## Custom event listeners + You can execute custom actions by listening to command and option events. + +```js +program.on('option:verbose', function () { + process.env.VERBOSE = this.verbose; +}); + +// error on unknown commands +program.on('command:*', function () { + console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' ')); + process.exit(1); +}); +``` + +## Examples + +```js +var program = require('commander'); + +program + .version('0.1.0') + .option('-C, --chdir ', 'change the working directory') + .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + .option('-T, --no-tests', 'ignore test hook'); + +program + .command('setup [env]') + .description('run setup commands for all envs') + .option("-s, --setup_mode [mode]", "Which setup mode to use") + .action(function(env, options){ + var mode = options.setup_mode || "normal"; + env = env || 'all'; + console.log('setup for %s env(s) with %s mode', env, mode); + }); + +program + .command('exec ') + .alias('ex') + .description('execute the given remote cmd') + .option("-e, --exec_mode ", "Which exec mode to use") + .action(function(cmd, options){ + console.log('exec "%s" using %s mode', cmd, options.exec_mode); + }).on('--help', function() { + console.log(' Examples:'); + console.log(); + console.log(' $ deploy exec sequential'); + console.log(' $ deploy exec async'); + console.log(); + }); + +program + .command('*') + .action(function(env){ + console.log('deploying "%s"', env); + }); + +program.parse(process.argv); +``` + +More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## License + +MIT diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js new file mode 100644 index 0000000..3ad0cac --- /dev/null +++ b/node_modules/commander/index.js @@ -0,0 +1,1236 @@ +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var spawn = require('child_process').spawn; +var path = require('path'); +var dirname = path.dirname; +var basename = path.basename; +var fs = require('fs'); + +/** + * Inherit `Command` from `EventEmitter.prototype`. + */ + +require('util').inherits(Command, EventEmitter); + +/** + * Expose the root command. + */ + +exports = module.exports = new Command(); + +/** + * Expose `Command`. + */ + +exports.Command = Command; + +/** + * Expose `Option`. + */ + +exports.Option = Option; + +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ + +function Option(flags, description) { + this.flags = flags; + this.required = flags.indexOf('<') >= 0; + this.optional = flags.indexOf('[') >= 0; + this.bool = flags.indexOf('-no-') === -1; + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} + +/** + * Return option name. + * + * @return {String} + * @api private + */ + +Option.prototype.name = function() { + return this.long + .replace('--', '') + .replace('no-', ''); +}; + +/** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {String} + * @api private + */ + +Option.prototype.attributeName = function() { + return camelcase(this.name()); +}; + +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ + +Option.prototype.is = function(arg) { + return this.short === arg || this.long === arg; +}; + +/** + * Initialize a new `Command`. + * + * @param {String} name + * @api public + */ + +function Command(name) { + this.commands = []; + this.options = []; + this._execs = {}; + this._allowUnknownOption = false; + this._args = []; + this._name = name || ''; +} + +/** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * Examples: + * + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {String} name + * @param {String} [desc] for git-style sub-commands + * @return {Command} the new command + * @api public + */ + +Command.prototype.command = function(name, desc, opts) { + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + var args = name.split(/ +/); + var cmd = new Command(args.shift()); + + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs[cmd._name] = true; + if (opts.isDefault) this.defaultExecutable = cmd._name; + } + cmd._noHelp = !!opts.noHelp; + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; +}; + +/** + * Define argument syntax for the top-level command. + * + * @api public + */ + +Command.prototype.arguments = function(desc) { + return this.parseExpectedArgs(desc.split(/ +/)); +}; + +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ + +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; + +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; + + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } + + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + self._args.push(argDetails); + } + }); + return this; +}; + +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ + +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; + + var parsed = self.parseOptions(unknown); + + // Output help if necessary + outputHelpIfNecessary(self, parsed.unknown); + + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } + + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); + + self._args.forEach(function(arg, i) { + if (arg.required && args[i] == null) { + self.missingArgument(arg.name); + } else if (arg.variadic) { + if (i !== self._args.length - 1) { + self.variadicArgNotLast(arg.name); + } + + args[i] = args.splice(i); + } + }); + + // Always append ourselves to the end of the arguments, + // to make sure we match the number of arguments the user + // expects + if (self._args.length) { + args[self._args.length] = self; + } else { + args.push(self); + } + + fn.apply(self, args); + }; + var parent = this.parent || this; + var name = parent === this ? '*' : this._name; + parent.on('command:' + name, listener); + if (this._alias) parent.on('command:' + this._alias, listener); + return this; +}; + +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] or default + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.option = function(flags, description, fn, defaultValue) { + var self = this, + option = new Option(flags, description), + oname = option.name(), + name = option.attributeName(); + + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } + + // preassign default value only for --no-*, [optional], or + if (!option.bool || option.optional || option.required) { + // when --no-* we make sure default is true + if (!option.bool) defaultValue = true; + // preassign only if we have a default + if (defaultValue !== undefined) { + self[name] = defaultValue; + option.defaultValue = defaultValue; + } + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, function(val) { + // coercion + if (val !== null && fn) { + val = fn(val, self[name] === undefined ? defaultValue : self[name]); + } + + // unassigned or bool + if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') { + // if no value, bool true, and we have a default, then use it! + if (val == null) { + self[name] = option.bool + ? defaultValue || true + : false; + } else { + self[name] = val; + } + } else if (val !== null) { + // reassign + self[name] = val; + } + }); + + return this; +}; + +/** + * Allow unknown options on the command line. + * + * @param {Boolean} arg if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ +Command.prototype.allowUnknownOption = function(arg) { + this._allowUnknownOption = arguments.length === 0 || arg; + return this; +}; + +/** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); + + // store raw args + this.rawArgs = argv; + + // guess name + this._name = this._name || basename(argv[1], '.js'); + + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3 && !this.defaultExecutable) { + // this user needs help + argv.push('--help'); + } + + // process argv + var parsed = this.parseOptions(this.normalize(argv.slice(2))); + var args = this.args = parsed.args; + + var result = this.parseArgs(this.args, parsed.unknown); + + // executable sub-commands + var name = result.args[0]; + + var aliasCommand = null; + // check alias of sub commands + if (name) { + aliasCommand = this.commands.filter(function(command) { + return command.alias() === name; + })[0]; + } + + if (this._execs[name] && typeof this._execs[name] !== 'function') { + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (aliasCommand) { + // is alias of a subCommand + args[0] = aliasCommand._name; + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (this.defaultExecutable) { + // use the default subcommand + args.unshift(this.defaultExecutable); + return this.executeSubCommand(argv, args, parsed.unknown); + } + + return result; +}; + +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @api private + */ + +Command.prototype.executeSubCommand = function(argv, args, unknown) { + args = args.concat(unknown); + + if (!args.length) this.help(); + if (args[0] === 'help' && args.length === 1) this.help(); + + // --help + if (args[0] === 'help') { + args[0] = args[1]; + args[1] = '--help'; + } + + // executable + var f = argv[1]; + // name of the subcommand, link `pm-install` + var bin = basename(f, '.js') + '-' + args[0]; + + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir, + link = fs.lstatSync(f).isSymbolicLink() ? fs.readlinkSync(f) : f; + + // when symbolink is relative path + if (link !== f && link.charAt(0) !== '/') { + link = path.join(dirname(f), link); + } + baseDir = dirname(link); + + // prefer local `./` to bin in the $PATH + var localBin = path.join(baseDir, bin); + + // whether bin file is a js script with explicit `.js` extension + var isExplicitJS = false; + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin)) { + bin = localBin; + } + + args = args.slice(1); + + var proc; + if (process.platform !== 'win32') { + if (isExplicitJS) { + args.unshift(bin); + // add executable arguments to spawn + args = (process.execArgv || []).concat(args); + + proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] }); + } else { + proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); + } + } else { + args.unshift(bin); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } + + var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach(function(signal) { + process.on(signal, function() { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + proc.on('close', process.exit.bind(process)); + proc.on('error', function(err) { + if (err.code === 'ENOENT') { + console.error('\n %s(1) does not exist, try --help\n', bin); + } else if (err.code === 'EACCES') { + console.error('\n %s(1) not executable. try chmod or run with root\n', bin); + } + process.exit(1); + }); + + // Store the reference to the child process + this.runningCommand = proc; +}; + +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ + +Command.prototype.normalize = function(args) { + var ret = [], + arg, + lastOpt, + index; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i - 1]); + } + + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } + } + + return ret; +}; + +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ + +Command.prototype.parseArgs = function(args, unknown) { + var name; + + if (args.length) { + name = args[0]; + if (this.listeners('command:' + name).length) { + this.emit('command:' + args.shift(), args, unknown); + } else { + this.emit('command:*', args); + } + } else { + outputHelpIfNecessary(this, unknown); + + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0) { + this.unknownOption(unknown[0]); + } + if (this.commands.length === 0 && + this._args.filter(function(a) { return a.required }).length === 0) { + this.emit('command:*'); + } + } + + return this; +}; + +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ + +Command.prototype.optionFor = function(arg) { + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } + } +}; + +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {Array} + * @api public + */ + +Command.prototype.parseOptions = function(argv) { + var args = [], + len = argv.length, + literal, + option, + arg; + + var unknownOptions = []; + + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + + // literal args after -- + if (literal) { + args.push(arg); + continue; + } + + if (arg === '--') { + literal = true; + continue; + } + + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (arg == null) return this.optionMissingArgument(option); + this.emit('option:' + option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i + 1]; + if (arg == null || (arg[0] === '-' && arg !== '-')) { + arg = null; + } else { + ++i; + } + this.emit('option:' + option.name(), arg); + // bool + } else { + this.emit('option:' + option.name()); + } + continue; + } + + // looks like an option + if (arg.length > 1 && arg[0] === '-') { + unknownOptions.push(arg); + + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if ((i + 1) < argv.length && argv[i + 1][0] !== '-') { + unknownOptions.push(argv[++i]); + } + continue; + } + + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; + +/** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ +Command.prototype.opts = function() { + var result = {}, + len = this.options.length; + + for (var i = 0; i < len; i++) { + var key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; +}; + +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ + +Command.prototype.missingArgument = function(name) { + console.error(); + console.error(" error: missing required argument `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {String} option + * @param {String} flag + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag) { + console.error(); + if (flag) { + console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); + } else { + console.error(" error: option `%s' argument missing", option.flags); + } + console.error(); + process.exit(1); +}; + +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ + +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + console.error(); + console.error(" error: unknown option `%s'", flag); + console.error(); + process.exit(1); +}; + +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ + +Command.prototype.variadicArgNotLast = function(name) { + console.error(); + console.error(" error: variadic arguments must be last `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {String} str + * @param {String} [flags] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.version = function(str, flags) { + if (arguments.length === 0) return this._version; + this._version = str; + flags = flags || '-V, --version'; + var versionOption = new Option(flags, 'output the version number'); + this._versionOptionName = versionOption.long.substr(2) || 'version'; + this.options.push(versionOption); + this.on('option:' + this._versionOptionName, function() { + process.stdout.write(str + '\n'); + process.exit(0); + }); + return this; +}; + +/** + * Set the description to `str`. + * + * @param {String} str + * @param {Object} argsDescription + * @return {String|Command} + * @api public + */ + +Command.prototype.description = function(str, argsDescription) { + if (arguments.length === 0) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; +}; + +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ + +Command.prototype.alias = function(alias) { + var command = this; + if (this.commands.length !== 0) { + command = this.commands[this.commands.length - 1]; + } + + if (arguments.length === 0) return command._alias; + + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); + + command._alias = alias; + return this; +}; + +/** + * Set / get the command usage `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); + + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); + + if (arguments.length === 0) return this._usage || usage; + this._usage = str; + + return this; +}; + +/** + * Get or set the name of the command + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.name = function(str) { + if (arguments.length === 0) return this._name; + this._name = str; + return this; +}; + +/** + * Return prepared commands. + * + * @return {Array} + * @api private + */ + +Command.prototype.prepareCommands = function() { + return this.commands.filter(function(cmd) { + return !cmd._noHelp; + }).map(function(cmd) { + var args = cmd._args.map(function(arg) { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._alias ? '|' + cmd._alias : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); +}; + +/** + * Return the largest command length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestCommandLength = function() { + var commands = this.prepareCommands(); + return commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); +}; + +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestOptionLength = function() { + var options = [].slice.call(this.options); + options.push({ + flags: '-h, --help' + }); + return options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; + +/** + * Return the largest arg length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestArgLength = function() { + return this._args.reduce(function(max, arg) { + return Math.max(max, arg.name.length); + }, 0); +}; + +/** + * Return the pad width. + * + * @return {Number} + * @api private + */ + +Command.prototype.padWidth = function() { + var width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } + + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } + + return width; +}; + +/** + * Return help for options. + * + * @return {String} + * @api private + */ + +Command.prototype.optionHelp = function() { + var width = this.padWidth(); + + // Append the help information + return this.options.map(function(option) { + return pad(option.flags, width) + ' ' + option.description + + ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + option.defaultValue + ')' : ''); + }).concat([pad('-h, --help', width) + ' ' + 'output usage information']) + .join('\n'); +}; + +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; + + var commands = this.prepareCommands(); + var width = this.padWidth(); + + return [ + ' Commands:', + '', + commands.map(function(cmd) { + var desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + desc; + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); +}; + +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.helpInformation = function() { + var desc = []; + if (this._description) { + desc = [ + ' ' + this._description, + '' + ]; + + var argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + var width = this.padWidth(); + desc.push(' Arguments:'); + desc.push(''); + this._args.forEach(function(arg) { + desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]); + }); + desc.push(''); + } + } + + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var usage = [ + '', + ' Usage: ' + cmdName + ' ' + this.usage(), + '' + ]; + + var cmds = []; + var commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; + + var options = [ + ' Options:', + '', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .concat(['']) + .join('\n'); +}; + +/** + * Output help information for this command + * + * @api public + */ + +Command.prototype.outputHelp = function(cb) { + if (!cb) { + cb = function(passthru) { + return passthru; + }; + } + process.stdout.write(cb(this.helpInformation())); + this.emit('--help'); +}; + +/** + * Output help information and exit. + * + * @api public + */ + +Command.prototype.help = function(cb) { + this.outputHelp(cb); + process.exit(); +}; + +/** + * Camel-case the given `flag` + * + * @param {String} flag + * @return {String} + * @api private + */ + +function camelcase(flag) { + return flag.split('-').reduce(function(str, word) { + return str + word[0].toUpperCase() + word.slice(1); + }); +} + +/** + * Pad `str` to `width`. + * + * @param {String} str + * @param {Number} width + * @return {String} + * @api private + */ + +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} + +/** + * Output help information if necessary + * + * @param {Command} command to output help for + * @param {Array} array of options to search for -h or --help + * @api private + */ + +function outputHelpIfNecessary(cmd, options) { + options = options || []; + for (var i = 0; i < options.length; i++) { + if (options[i] === '--help' || options[i] === '-h') { + cmd.outputHelp(); + process.exit(0); + } + } +} + +/** + * Takes an argument an returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {String} + * @api private + */ + +function humanReadableArgName(arg) { + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} + +// for versions before node v0.8 when there weren't `fs.existsSync` +function exists(file) { + try { + if (fs.statSync(file).isFile()) { + return true; + } + } catch (e) { + return false; + } +} diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json new file mode 100644 index 0000000..a40dbb9 --- /dev/null +++ b/node_modules/commander/package.json @@ -0,0 +1,69 @@ +{ + "_from": "commander@2.17.x", + "_id": "commander@2.17.1", + "_inBundle": false, + "_integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==", + "_location": "/commander", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "commander@2.17.x", + "name": "commander", + "escapedName": "commander", + "rawSpec": "2.17.x", + "saveSpec": null, + "fetchSpec": "2.17.x" + }, + "_requiredBy": [ + "/html-minifier" + ], + "_resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", + "_shasum": "bd77ab7de6de94205ceacc72f1716d29f20a77bf", + "_spec": "commander@2.17.x", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\html-minifier", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "bugs": { + "url": "https://github.com/tj/commander.js/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "the complete solution for node.js command-line programs", + "devDependencies": { + "@types/node": "^10.5.7", + "eslint": "^5.3.0", + "should": "^13.2.3", + "sinon": "^6.1.4", + "standard": "^11.0.1", + "typescript": "^2.9.2" + }, + "files": [ + "index.js", + "typings/index.d.ts" + ], + "homepage": "https://github.com/tj/commander.js#readme", + "keywords": [ + "commander", + "command", + "option", + "parser" + ], + "license": "MIT", + "main": "index", + "name": "commander", + "repository": { + "type": "git", + "url": "git+https://github.com/tj/commander.js.git" + }, + "scripts": { + "lint": "eslint index.js", + "test": "node test/run.js && npm run test-typings", + "test-typings": "tsc -p tsconfig.json" + }, + "typings": "typings/index.d.ts", + "version": "2.17.1" +} diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts new file mode 100644 index 0000000..312b056 --- /dev/null +++ b/node_modules/commander/typings/index.d.ts @@ -0,0 +1,309 @@ +// Type definitions for commander 2.11 +// Project: https://github.com/visionmedia/commander.js +// Definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace local { + + class Option { + flags: string; + required: boolean; + optional: boolean; + bool: boolean; + short?: string; + long: string; + description: string; + + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} [description] + */ + constructor(flags: string, description?: string); + } + + class Command extends NodeJS.EventEmitter { + [key: string]: any; + + args: string[]; + + /** + * Initialize a new `Command`. + * + * @param {string} [name] + */ + constructor(name?: string); + + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {string} str + * @param {string} [flags] + * @returns {Command} for chaining + */ + version(str: string, flags?: string): Command; + + /** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * @example + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {string} name + * @param {string} [desc] for git-style sub-commands + * @param {CommandOptions} [opts] command options + * @returns {Command} the new command + */ + command(name: string, desc?: string, opts?: commander.CommandOptions): Command; + + /** + * Define argument syntax for the top-level command. + * + * @param {string} desc + * @returns {Command} for chaining + */ + arguments(desc: string): Command; + + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {string[]} args + * @returns {Command} for chaining + */ + parseExpectedArgs(args: string[]): Command; + + /** + * Register callback `fn` for the command. + * + * @example + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {(...args: any[]) => void} fn + * @returns {Command} for chaining + */ + action(fn: (...args: any[]) => void): Command; + + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @example + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} [description] + * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default + * @param {*} [defaultValue] + * @returns {Command} for chaining + */ + option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + option(flags: string, description?: string, defaultValue?: any): Command; + + /** + * Allow unknown options on the command line. + * + * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options. + * @returns {Command} for chaining + */ + allowUnknownOption(arg?: boolean): Command; + + /** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {string[]} argv + * @returns {Command} for chaining + */ + parse(argv: string[]): Command; + + /** + * Parse options from `argv` returning `argv` void of these options. + * + * @param {string[]} argv + * @returns {ParseOptionsResult} + */ + parseOptions(argv: string[]): commander.ParseOptionsResult; + + /** + * Return an object containing options as key-value pairs + * + * @returns {{[key: string]: any}} + */ + opts(): { [key: string]: any }; + + /** + * Set the description to `str`. + * + * @param {string} str + * @return {(Command | string)} + */ + description(str: string): Command; + description(): string; + + /** + * Set an alias for the command. + * + * @param {string} alias + * @return {(Command | string)} + */ + alias(alias: string): Command; + alias(): string; + + /** + * Set or get the command usage. + * + * @param {string} str + * @return {(Command | string)} + */ + usage(str: string): Command; + usage(): string; + + /** + * Set the name of the command. + * + * @param {string} str + * @return {Command} + */ + name(str: string): Command; + + /** + * Get the name of the command. + * + * @return {string} + */ + name(): string; + + /** + * Output help information for this command. + * + * @param {(str: string) => string} [cb] + */ + outputHelp(cb?: (str: string) => string): void; + + /** Output help information and exit. + * + * @param {(str: string) => string} [cb] + */ + help(cb?: (str: string) => string): never; + } + +} + +declare namespace commander { + + type Command = local.Command + + type Option = local.Option + + interface CommandOptions { + noHelp?: boolean; + isDefault?: boolean; + } + + interface ParseOptionsResult { + args: string[]; + unknown: string[]; + } + + interface CommanderStatic extends Command { + Command: typeof local.Command; + Option: typeof local.Option; + CommandOptions: CommandOptions; + ParseOptionsResult: ParseOptionsResult; + } + +} + +declare const commander: commander.CommanderStatic; +export = commander; diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js contributors. All rights reserved. + +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. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..ff4c851 --- /dev/null +++ b/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json new file mode 100644 index 0000000..e76cde0 --- /dev/null +++ b/node_modules/core-util-is/package.json @@ -0,0 +1,62 @@ +{ + "_from": "core-util-is@1.0.2", + "_id": "core-util-is@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "_location": "/core-util-is", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "core-util-is@1.0.2", + "name": "core-util-is", + "escapedName": "core-util-is", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/verror" + ], + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_spec": "core-util-is@1.0.2", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\verror", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The `util.is*` functions introduced in Node v0.12.", + "devDependencies": { + "tap": "^2.3.0" + }, + "homepage": "https://github.com/isaacs/core-util-is#readme", + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "license": "MIT", + "main": "lib/util.js", + "name": "core-util-is", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "scripts": { + "test": "tap test.js" + }, + "version": "1.0.2" +} diff --git a/node_modules/core-util-is/test.js b/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/css-b64-images/.npmignore b/node_modules/css-b64-images/.npmignore new file mode 100644 index 0000000..7dccd97 --- /dev/null +++ b/node_modules/css-b64-images/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/css-b64-images/.travis.yml b/node_modules/css-b64-images/.travis.yml new file mode 100644 index 0000000..58f2371 --- /dev/null +++ b/node_modules/css-b64-images/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.10 diff --git a/node_modules/css-b64-images/README.md b/node_modules/css-b64-images/README.md new file mode 100644 index 0000000..dbbdea9 --- /dev/null +++ b/node_modules/css-b64-images/README.md @@ -0,0 +1,78 @@ +[![build status](https://secure.travis-ci.org/Filirom1/css-base64-images.png)](http://travis-ci.org/Filirom1/css-base64-images) +css-base64-images +================= + +Base64 images in your css file. + +![Base64](https://github.com/Filirom1/css-base64-images/raw/master/draft.png) + +Transform this: + + .single-quote { + background: url('../img/background-pattern.gif'); + } + +into + + .single-quote { + background: url('data:image/gif;base64,R0lGODlhBgAGAIAAAObm5vLy8iH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS4wLWMwNjAgNjEuMTM0Nzc3LCAyMDEwLzAyLzEyLTE3OjMyOjAwICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpFMEY0NTFERjVEQ0ExMUUwOURGQ0Y2NjAyQTkzMUQ2OSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpFMEY0NTFFMDVEQ0ExMUUwOURGQ0Y2NjAyQTkzMUQ2OSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkUwRjQ1MURENURDQTExRTA5REZDRjY2MDJBOTMxRDY5IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkUwRjQ1MURFNURDQTExRTA5REZDRjY2MDJBOTMxRDY5Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAAAYABgAAAgqMDYcaqX6AnKAAADs='); + } + +Only works with CSS files. + +Works with: + +* single quotes: url('../img/background-pattern.gif'); +* double quotes: url("../img/background-pattern.gif"); +* absolute URL: url("/img/background-pattern.gif"); but you must specify a `root` path + +Do not work with (a warning is shown, but the process continue) + +* File bigger than 4Ko (configurable) +* external urls: url("http://my-company.ext/img/background-pattern.gif"); +* not found images + +## Install + + npm install -g css-b64-images + +## Usage + + cd /your/www/root/dir + css-b64-images css/styles.css > css/style.optimized.css + +## As a library + +### From File + +fromFile(cssFile, root, [options,] cb) + +You must specify the `root` path for absolute URLs to work. + + var b64img = require('css-b64-images'); + + b64img.fromFile('/your/www/root/dir/css/your-stylesheet.css', '/your/www/root/dir/', function(err, css){ + if(err) console.error('Error:', err); + console.log(css); + }); + +### From String + +fromString(css, relativePath, rootPath, [options,] cb) + + var b64img = require('css-b64-images'); + var css = fs.readFileSync('/your/www/root/dir/css/your-stylesheet.css'); + + b64img.fromString(css, '/your/www/root/dir/css/', '/your/www/root/dir/', function(err, css){ + if(err) console.error('Error:', err); + console.log(css); + }); + +### Options + +* maxSize: (default 4096) bigger images are not base64 in the CSS + + +## LICENSE + +MIT diff --git a/node_modules/css-b64-images/bin/css-b64-images b/node_modules/css-b64-images/bin/css-b64-images new file mode 100644 index 0000000..29b456f --- /dev/null +++ b/node_modules/css-b64-images/bin/css-b64-images @@ -0,0 +1,13 @@ +#!/usr/bin/env node + +var b64img = require('..'), + root = process.cwd(), + cssFile = process.argv[2]; + +if(!cssFile) handleError(new Error('Usage: css-b64-images file.css')); + +b64img.fromFile(cssFile, root, function(err, css){ + if(err) console.error('Error:', err); + console.log(css); +}); + diff --git a/node_modules/css-b64-images/draft.png b/node_modules/css-b64-images/draft.png new file mode 100644 index 0000000..9ce9151 Binary files /dev/null and b/node_modules/css-b64-images/draft.png differ diff --git a/node_modules/css-b64-images/draft.xcf b/node_modules/css-b64-images/draft.xcf new file mode 100644 index 0000000..7ed16cb Binary files /dev/null and b/node_modules/css-b64-images/draft.xcf differ diff --git a/node_modules/css-b64-images/lib/css-b64-images.js b/node_modules/css-b64-images/lib/css-b64-images.js new file mode 100644 index 0000000..c60764d --- /dev/null +++ b/node_modules/css-b64-images/lib/css-b64-images.js @@ -0,0 +1,116 @@ +'use strict'; + +var fs = require('fs'), + Path = require('path'), + MAX_SIZE = 4096, + /* Adapted from https://gist.github.com/2594980 */ + imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi, + absoluteUrlRegex = /^\//, + externalUrlRegex = /http/, + mediatypes = { + '.eot' : 'application/vnd.ms-fontobject', + '.gif' : 'image/gif', + '.ico' : 'image/vnd.microsoft.icon', + '.jpg' : 'image/jpeg', + '.jpeg' : 'image/jpeg', + '.otf' : 'application/x-font-opentype', + '.png' : 'image/png', + '.svg' : 'image/svg+xml', + '.ttf' : 'application/x-font-ttf', + '.webp' : 'image/webp', + '.woff' : 'application/x-font-woff', + '.woff2' : 'application/font-woff2' + }; + +module.exports = { + fromFile: fromFile, + fromString: fromString +}; + +function fromString(css, relativePath, rootPath , options, cb) { + if(!cb) { + cb = options; + options = {maxSize: MAX_SIZE}; + } + if(!css.replace && css.toString) css = css.toString(); + var urls = [], + match = imgRegex.exec(css); + while(match) { + urls.push(match[1]); + match = imgRegex.exec(css) + } + forEachSeries(urls, base64img, function(err){ + if(err) return cb(err, css); + cb(null, css); + }); + + function base64img(imageUrl, cb){ + if(externalUrlRegex.test(imageUrl)) { + return cb(new Error('Skip ' + imageUrl + ' External file.'), css); + } + + var imagePath; + if(absoluteUrlRegex.test(imageUrl)) { + imagePath = Path.join(rootPath, imageUrl.substr(1)); + }else{ + imagePath = Path.join(relativePath, imageUrl); + } + replaceUrlByB64(imageUrl, imagePath, css, options, function (err, newCss){ + if(err) return cb(err, css); + css = newCss; + cb(); + }); + } +} + +function fromFile(cssFile, root, options, cb) { + if(!cb) { + cb = options; + options = {maxSize: MAX_SIZE}; + } + fs.readFile(cssFile, function(err, css){ + if(err) return cb(err, css); + fromString(css.toString(), Path.dirname(cssFile), root, options, cb); + }); +} + +function replaceUrlByB64(imageUrl, imagePath, css, options, cb){ + imagePath = imagePath.replace(/[?#].*/g, ''); + fs.stat(imagePath, function(err, stat){ + if(err) return cb(err, css); + if (stat.size > options.maxSize){ + return cb(new Error('Skip ' + imageUrl + ' Exceed max size'), css); + } + fs.readFile(imagePath, 'base64', function(err, img){ + if(err) return cb(err, css); + var ext = Path.extname(imagePath); + var newCss = css.replace(imageUrl, 'data:' + mediatypes[ext] + ';base64,' + img); + cb(null, newCss); + }); + }); +} + +/* Adapted from async. Continue on error. */ +function forEachSeries(arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0, errs = []; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + errs.push(err); + } + completed += 1; + if (completed === arr.length) { + if(errs.length) return callback(errs); + callback(null); + } + else { + iterate(); + } + }); + }; + iterate(); +} diff --git a/node_modules/css-b64-images/package.json b/node_modules/css-b64-images/package.json new file mode 100644 index 0000000..164957e --- /dev/null +++ b/node_modules/css-b64-images/package.json @@ -0,0 +1,64 @@ +{ + "_from": "css-b64-images@~0.2.5", + "_id": "css-b64-images@0.2.5", + "_inBundle": false, + "_integrity": "sha1-QgBdgyBLK0pdk7axpWRBM7WSegI=", + "_location": "/css-b64-images", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "css-b64-images@~0.2.5", + "name": "css-b64-images", + "escapedName": "css-b64-images", + "rawSpec": "~0.2.5", + "saveSpec": null, + "fetchSpec": "~0.2.5" + }, + "_requiredBy": [ + "/minify" + ], + "_resolved": "https://registry.npmjs.org/css-b64-images/-/css-b64-images-0.2.5.tgz", + "_shasum": "42005d83204b2b4a5d93b6b1a5644133b5927a02", + "_spec": "css-b64-images@~0.2.5", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\minify", + "author": { + "name": "Filirom1", + "email": "filirom1@gmail.com" + }, + "bin": { + "css-b64-images": "bin/css-b64-images" + }, + "bugs": { + "url": "https://github.com/Filirom1/css-base64-images/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Base64 images in your css", + "devDependencies": { + "mocha": "~1.1.0", + "should": "~0.6.3" + }, + "engines": { + "node": "*" + }, + "homepage": "https://github.com/Filirom1/css-base64-images#readme", + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "lib/css-b64-images.js", + "name": "css-b64-images", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/Filirom1/css-base64-images.git" + }, + "scripts": { + "test": "mocha" + }, + "version": "0.2.5" +} diff --git a/node_modules/css-b64-images/test/css-b64-images-test.js b/node_modules/css-b64-images/test/css-b64-images-test.js new file mode 100644 index 0000000..1a4fb6c --- /dev/null +++ b/node_modules/css-b64-images/test/css-b64-images-test.js @@ -0,0 +1,38 @@ +var Path = require('path'), + fs = require('fs'), + b64 = require('..'); + +require('should'); + +describe('A complex CSS', function(){ + var cssFile = Path.join(__dirname, 'fixture', 'css', 'style.css'), + relative = Path.join(__dirname, 'fixture', 'css'); + root = Path.join(__dirname, 'fixture'); + + it('a file should be optimized with base64', function(done){ + b64.fromFile(cssFile, root, function(err, css){ + cssShouldBeCorrect(css); + done(); + }); + }); + + it('a string should be optimized with base64', function(done){ + var css = fs.readFileSync(cssFile); + b64.fromString(css, relative, root, function(err, css){ + cssShouldBeCorrect(css); + done(); + }); + }); +}); + +function cssShouldBeCorrect(css){ + css.should.include(".single-quote {\n background: url('data:image/gif;base64,"); + css.should.include(".double-quote {\n background: url(\"data:image/gif;base64,"); + css.should.include(".absolute {\n background: url('data:image/gif;base64,"); + + css.should.include(".external {\n background: url('http"); + css.should.include(".tooBig {\n background: url('../img"); + css.should.include(".not-found {\n background: url('../img"); + + css.should.include(".mediatype {\n background: url('data:image/svg+xml;base64,"); +} diff --git a/node_modules/css-b64-images/test/fixture/css/style.css b/node_modules/css-b64-images/test/fixture/css/style.css new file mode 100644 index 0000000..e215a78 --- /dev/null +++ b/node_modules/css-b64-images/test/fixture/css/style.css @@ -0,0 +1,52 @@ +/* ---- Fonts ---- */ + +@font-face { + font-family: 'MavenProMedium'; + src: url('../fonts/maven_pro_medium-webfont.eot'); + src: url('../fonts/maven_pro_medium-webfont.eot?iefix') format('eot'), + url('../fonts/maven_pro_medium-webfont.woff') format('woff'), + url('../fonts/maven_pro_medium-webfont.ttf') format('truetype'), + url('../fonts/maven_pro_medium-webfont.svg#webfontyQA0TEWF') format('svg'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'CallunaSansRegular'; + src: url('../fonts/callunasansregular-webfont.eot'); + src: url('../fonts/callunasansregular-webfont.eot?#iefix') format('eot'), + url('../fonts/callunasansregular-webfont.woff') format('woff'), + url('../fonts/callunasansregular-webfont.ttf') format('truetype'), + url('../fonts/callunasansregular-webfont.svg#webfontW850hM1B') format('svg'); + font-weight: normal; + font-style: normal; +} + + +.single-quote { + background: url('../img/background-pattern.gif'); +} + +.double-quote { + background: url("../img/background-pattern.gif"); +} + +.absolute { + background: url('/img/background-pattern.gif'); +} + +.external { + background: url('http://pullrequest.org/img/background-pattern.gif'); +} + +.tooBig { + background: url('../img/mixit-banner.png'); +} + +.not-found { + background: url('../img/nlabal.png'); +} + +.mediatype { + background: url('../img/dots.svg'); +} \ No newline at end of file diff --git a/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.eot b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.eot new file mode 100644 index 0000000..ba3b5db Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.eot differ diff --git a/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.svg b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.svg new file mode 100644 index 0000000..f562d3c --- /dev/null +++ b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.svg @@ -0,0 +1,248 @@ + + + + +This is a custom SVG webfont generated by Font Squirrel. +Copyright : Copyright c 2010 by Jos Buivenga All rights reserved +Designer : Jos Buivenga +Foundry : Jos Buivenga +Foundry URL : httpexljbriscom + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.ttf b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.ttf new file mode 100644 index 0000000..1a18093 Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.ttf differ diff --git a/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.woff b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.woff new file mode 100644 index 0000000..46c4675 Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/fonts/callunasansregular-webfont.woff differ diff --git a/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.eot b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.eot new file mode 100644 index 0000000..9601d51 Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.eot differ diff --git a/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.svg b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.svg new file mode 100644 index 0000000..c4fe7b5 --- /dev/null +++ b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.svg @@ -0,0 +1,245 @@ + + + + +This is a custom SVG webfont generated by Font Squirrel. +Copyright : Copyright c 2011 by Vissol Ltd All rights reserved +Designer : Joe Prince +Foundry : Joe Prince + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.ttf b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.ttf new file mode 100644 index 0000000..ffd16e2 Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.ttf differ diff --git a/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.woff b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.woff new file mode 100644 index 0000000..b03b731 Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/fonts/maven_pro_medium-webfont.woff differ diff --git a/node_modules/css-b64-images/test/fixture/img/background-pattern.gif b/node_modules/css-b64-images/test/fixture/img/background-pattern.gif new file mode 100644 index 0000000..77893d5 Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/img/background-pattern.gif differ diff --git a/node_modules/css-b64-images/test/fixture/img/dots.svg b/node_modules/css-b64-images/test/fixture/img/dots.svg new file mode 100644 index 0000000..30cd43f --- /dev/null +++ b/node_modules/css-b64-images/test/fixture/img/dots.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/node_modules/css-b64-images/test/fixture/img/mixit-banner.png b/node_modules/css-b64-images/test/fixture/img/mixit-banner.png new file mode 100644 index 0000000..c5c20cb Binary files /dev/null and b/node_modules/css-b64-images/test/fixture/img/mixit-banner.png differ diff --git a/node_modules/cssom/LICENSE.txt b/node_modules/cssom/LICENSE.txt new file mode 100644 index 0000000..bc57aac --- /dev/null +++ b/node_modules/cssom/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) Nikita Vasilyev + +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. diff --git a/node_modules/cssom/README.mdown b/node_modules/cssom/README.mdown new file mode 100644 index 0000000..1e7c440 --- /dev/null +++ b/node_modules/cssom/README.mdown @@ -0,0 +1,69 @@ +# CSSOM + +CSSOM.js is a CSS parser written in pure JavaScript. It also a partial implementation of [CSS Object Model](http://dev.w3.org/csswg/cssom/). + + CSSOM.parse("body {color: black}") + -> { + cssRules: [ + { + selectorText: "body", + style: { + 0: "color", + color: "black", + length: 1 + } + } + ] + } + + +## [Parser demo](http://nv.github.com/CSSOM/docs/parse.html) + +Works well in Google Chrome 6+, Safari 5+, Firefox 3.6+, Opera 10.63+. +Doesn't work in IE < 9 because of unsupported getters/setters. + +To use CSSOM.js in the browser you might want to build a one-file version that exposes CSSOM global variable: + + ➤ git clone https://github.com/NV/CSSOM.git + ➤ cd CSSOM + ➤ npm install -d + ➤ ./node_modules/.bin/jake + build/CSSOM.js is done + +To use it with Node.js or any other CommonJS loader: + + ➤ npm install cssom + +## Don’t use it if... + +You parse CSS to mungle, minify or reformat the following code: + +```css +div { + background: gray; + background: linear-gradient(to bottom, white 0%, black 100%); +} +``` + +This pattern is often used to give browsers that don’t understand linear gradients a fallback solution (e.g. gray color in the example). +In CSSOM, `background: gray` [gets overwritten](http://nv.github.io/CSSOM/docs/parse.html#css=div%20%7B%0A%20%20%20%20%20%20background%3A%20gray%3B%0A%20%20%20%20background%3A%20linear-gradient(to%20bottom%2C%20white%200%25%2C%20black%20100%25)%3B%0A%7D). +The last same-name property always overwrites all the previous ones. + + +If you do CSS mungling, minification, image inlining, and such, CSSOM.js is no good for you, considere using one of the following: + + * [postcss](https://github.com/postcss/postcss) + * [reworkcss/css](https://github.com/reworkcss/css) + * [csso](https://github.com/css/csso) + * [mensch](https://github.com/brettstimmerman/mensch) + + +## [Specs](http://nv.github.com/CSSOM/spec/) + +To run specs locally: + + ➤ git submodule init + ➤ git submodule update + + +## [Who uses CSSOM.js](https://github.com/NV/CSSOM/wiki/Who-uses-CSSOM.js) diff --git a/node_modules/cssom/lib/CSSDocumentRule.js b/node_modules/cssom/lib/CSSDocumentRule.js new file mode 100644 index 0000000..aec0776 --- /dev/null +++ b/node_modules/cssom/lib/CSSDocumentRule.js @@ -0,0 +1,39 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + MatcherList: require("./MatcherList").MatcherList +}; +///CommonJS + + +/** + * @constructor + * @see https://developer.mozilla.org/en/CSS/@-moz-document + */ +CSSOM.CSSDocumentRule = function CSSDocumentRule() { + CSSOM.CSSRule.call(this); + this.matcher = new CSSOM.MatcherList(); + this.cssRules = []; +}; + +CSSOM.CSSDocumentRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSDocumentRule.prototype.constructor = CSSOM.CSSDocumentRule; +CSSOM.CSSDocumentRule.prototype.type = 10; +//FIXME +//CSSOM.CSSDocumentRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSDocumentRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSDocumentRule.prototype, "cssText", { + get: function() { + var cssTexts = []; + for (var i=0, length=this.cssRules.length; i < length; i++) { + cssTexts.push(this.cssRules[i].cssText); + } + return "@-moz-document " + this.matcher.matcherText + " {" + cssTexts.join("") + "}"; + } +}); + + +//.CommonJS +exports.CSSDocumentRule = CSSOM.CSSDocumentRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSFontFaceRule.js b/node_modules/cssom/lib/CSSFontFaceRule.js new file mode 100644 index 0000000..7a537fb --- /dev/null +++ b/node_modules/cssom/lib/CSSFontFaceRule.js @@ -0,0 +1,36 @@ +//.CommonJS +var CSSOM = { + CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration, + CSSRule: require("./CSSRule").CSSRule +}; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#css-font-face-rule + */ +CSSOM.CSSFontFaceRule = function CSSFontFaceRule() { + CSSOM.CSSRule.call(this); + this.style = new CSSOM.CSSStyleDeclaration(); + this.style.parentRule = this; +}; + +CSSOM.CSSFontFaceRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSFontFaceRule.prototype.constructor = CSSOM.CSSFontFaceRule; +CSSOM.CSSFontFaceRule.prototype.type = 5; +//FIXME +//CSSOM.CSSFontFaceRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSFontFaceRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSFontFaceRule.cpp +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "cssText", { + get: function() { + return "@font-face {" + this.style.cssText + "}"; + } +}); + + +//.CommonJS +exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSHostRule.js b/node_modules/cssom/lib/CSSHostRule.js new file mode 100644 index 0000000..365304f --- /dev/null +++ b/node_modules/cssom/lib/CSSHostRule.js @@ -0,0 +1,37 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule +}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/shadow-dom/#host-at-rule + */ +CSSOM.CSSHostRule = function CSSHostRule() { + CSSOM.CSSRule.call(this); + this.cssRules = []; +}; + +CSSOM.CSSHostRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSHostRule.prototype.constructor = CSSOM.CSSHostRule; +CSSOM.CSSHostRule.prototype.type = 1001; +//FIXME +//CSSOM.CSSHostRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSHostRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSHostRule.prototype, "cssText", { + get: function() { + var cssTexts = []; + for (var i=0, length=this.cssRules.length; i < length; i++) { + cssTexts.push(this.cssRules[i].cssText); + } + return "@host {" + cssTexts.join("") + "}"; + } +}); + + +//.CommonJS +exports.CSSHostRule = CSSOM.CSSHostRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSImportRule.js b/node_modules/cssom/lib/CSSImportRule.js new file mode 100644 index 0000000..0398105 --- /dev/null +++ b/node_modules/cssom/lib/CSSImportRule.js @@ -0,0 +1,132 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSStyleSheet: require("./CSSStyleSheet").CSSStyleSheet, + MediaList: require("./MediaList").MediaList +}; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssimportrule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule + */ +CSSOM.CSSImportRule = function CSSImportRule() { + CSSOM.CSSRule.call(this); + this.href = ""; + this.media = new CSSOM.MediaList(); + this.styleSheet = new CSSOM.CSSStyleSheet(); +}; + +CSSOM.CSSImportRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; +CSSOM.CSSImportRule.prototype.type = 3; + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { + get: function() { + var mediaText = this.media.mediaText; + return "@import url(" + this.href + ")" + (mediaText ? " " + mediaText : "") + ";"; + }, + set: function(cssText) { + var i = 0; + + /** + * @import url(partial.css) screen, handheld; + * || | + * after-import media + * | + * url + */ + var state = ''; + + var buffer = ''; + var index; + for (var character; (character = cssText.charAt(i)); i++) { + + switch (character) { + case ' ': + case '\t': + case '\r': + case '\n': + case '\f': + if (state === 'after-import') { + state = 'url'; + } else { + buffer += character; + } + break; + + case '@': + if (!state && cssText.indexOf('@import', i) === i) { + state = 'after-import'; + i += 'import'.length; + buffer = ''; + } + break; + + case 'u': + if (state === 'url' && cssText.indexOf('url(', i) === i) { + index = cssText.indexOf(')', i + 1); + if (index === -1) { + throw i + ': ")" not found'; + } + i += 'url('.length; + var url = cssText.slice(i, index); + if (url[0] === url[url.length - 1]) { + if (url[0] === '"' || url[0] === "'") { + url = url.slice(1, -1); + } + } + this.href = url; + i = index; + state = 'media'; + } + break; + + case '"': + if (state === 'url') { + index = cssText.indexOf('"', i + 1); + if (!index) { + throw i + ": '\"' not found"; + } + this.href = cssText.slice(i + 1, index); + i = index; + state = 'media'; + } + break; + + case "'": + if (state === 'url') { + index = cssText.indexOf("'", i + 1); + if (!index) { + throw i + ': "\'" not found'; + } + this.href = cssText.slice(i + 1, index); + i = index; + state = 'media'; + } + break; + + case ';': + if (state === 'media') { + if (buffer) { + this.media.mediaText = buffer.trim(); + } + } + break; + + default: + if (state === 'media') { + buffer += character; + } + break; + } + } + } +}); + + +//.CommonJS +exports.CSSImportRule = CSSOM.CSSImportRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSKeyframeRule.js b/node_modules/cssom/lib/CSSKeyframeRule.js new file mode 100644 index 0000000..c22f2f5 --- /dev/null +++ b/node_modules/cssom/lib/CSSKeyframeRule.js @@ -0,0 +1,37 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSStyleDeclaration: require('./CSSStyleDeclaration').CSSStyleDeclaration +}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframeRule + */ +CSSOM.CSSKeyframeRule = function CSSKeyframeRule() { + CSSOM.CSSRule.call(this); + this.keyText = ''; + this.style = new CSSOM.CSSStyleDeclaration(); + this.style.parentRule = this; +}; + +CSSOM.CSSKeyframeRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSKeyframeRule.prototype.constructor = CSSOM.CSSKeyframeRule; +CSSOM.CSSKeyframeRule.prototype.type = 9; +//FIXME +//CSSOM.CSSKeyframeRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSKeyframeRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframeRule.cpp +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "cssText", { + get: function() { + return this.keyText + " {" + this.style.cssText + "} "; + } +}); + + +//.CommonJS +exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSKeyframesRule.js b/node_modules/cssom/lib/CSSKeyframesRule.js new file mode 100644 index 0000000..7e42717 --- /dev/null +++ b/node_modules/cssom/lib/CSSKeyframesRule.js @@ -0,0 +1,39 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule +}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframesRule + */ +CSSOM.CSSKeyframesRule = function CSSKeyframesRule() { + CSSOM.CSSRule.call(this); + this.name = ''; + this.cssRules = []; +}; + +CSSOM.CSSKeyframesRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSKeyframesRule.prototype.constructor = CSSOM.CSSKeyframesRule; +CSSOM.CSSKeyframesRule.prototype.type = 8; +//FIXME +//CSSOM.CSSKeyframesRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSKeyframesRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframesRule.cpp +Object.defineProperty(CSSOM.CSSKeyframesRule.prototype, "cssText", { + get: function() { + var cssTexts = []; + for (var i=0, length=this.cssRules.length; i < length; i++) { + cssTexts.push(" " + this.cssRules[i].cssText); + } + return "@" + (this._vendorPrefix || '') + "keyframes " + this.name + " { \n" + cssTexts.join("\n") + "\n}"; + } +}); + + +//.CommonJS +exports.CSSKeyframesRule = CSSOM.CSSKeyframesRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSMediaRule.js b/node_modules/cssom/lib/CSSMediaRule.js new file mode 100644 index 0000000..367a35e --- /dev/null +++ b/node_modules/cssom/lib/CSSMediaRule.js @@ -0,0 +1,41 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + MediaList: require("./MediaList").MediaList +}; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssmediarule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSMediaRule + */ +CSSOM.CSSMediaRule = function CSSMediaRule() { + CSSOM.CSSRule.call(this); + this.media = new CSSOM.MediaList(); + this.cssRules = []; +}; + +CSSOM.CSSMediaRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSMediaRule.prototype.constructor = CSSOM.CSSMediaRule; +CSSOM.CSSMediaRule.prototype.type = 4; +//FIXME +//CSSOM.CSSMediaRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSMediaRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +// http://opensource.apple.com/source/WebCore/WebCore-658.28/css/CSSMediaRule.cpp +Object.defineProperty(CSSOM.CSSMediaRule.prototype, "cssText", { + get: function() { + var cssTexts = []; + for (var i=0, length=this.cssRules.length; i < length; i++) { + cssTexts.push(this.cssRules[i].cssText); + } + return "@media " + this.media.mediaText + " {" + cssTexts.join("") + "}"; + } +}); + + +//.CommonJS +exports.CSSMediaRule = CSSOM.CSSMediaRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSOM.js b/node_modules/cssom/lib/CSSOM.js new file mode 100644 index 0000000..95f3563 --- /dev/null +++ b/node_modules/cssom/lib/CSSOM.js @@ -0,0 +1,3 @@ +var CSSOM = {}; + + diff --git a/node_modules/cssom/lib/CSSRule.js b/node_modules/cssom/lib/CSSRule.js new file mode 100644 index 0000000..0b5e25b --- /dev/null +++ b/node_modules/cssom/lib/CSSRule.js @@ -0,0 +1,43 @@ +//.CommonJS +var CSSOM = {}; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#the-cssrule-interface + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule + */ +CSSOM.CSSRule = function CSSRule() { + this.parentRule = null; + this.parentStyleSheet = null; +}; + +CSSOM.CSSRule.UNKNOWN_RULE = 0; // obsolete +CSSOM.CSSRule.STYLE_RULE = 1; +CSSOM.CSSRule.CHARSET_RULE = 2; // obsolete +CSSOM.CSSRule.IMPORT_RULE = 3; +CSSOM.CSSRule.MEDIA_RULE = 4; +CSSOM.CSSRule.FONT_FACE_RULE = 5; +CSSOM.CSSRule.PAGE_RULE = 6; +CSSOM.CSSRule.KEYFRAMES_RULE = 7; +CSSOM.CSSRule.KEYFRAME_RULE = 8; +CSSOM.CSSRule.MARGIN_RULE = 9; +CSSOM.CSSRule.NAMESPACE_RULE = 10; +CSSOM.CSSRule.COUNTER_STYLE_RULE = 11; +CSSOM.CSSRule.SUPPORTS_RULE = 12; +CSSOM.CSSRule.DOCUMENT_RULE = 13; +CSSOM.CSSRule.FONT_FEATURE_VALUES_RULE = 14; +CSSOM.CSSRule.VIEWPORT_RULE = 15; +CSSOM.CSSRule.REGION_STYLE_RULE = 16; + + +CSSOM.CSSRule.prototype = { + constructor: CSSOM.CSSRule + //FIXME +}; + + +//.CommonJS +exports.CSSRule = CSSOM.CSSRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSStyleDeclaration.js b/node_modules/cssom/lib/CSSStyleDeclaration.js new file mode 100644 index 0000000..b43b9af --- /dev/null +++ b/node_modules/cssom/lib/CSSStyleDeclaration.js @@ -0,0 +1,148 @@ +//.CommonJS +var CSSOM = {}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration + */ +CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ + this.length = 0; + this.parentRule = null; + + // NON-STANDARD + this._importants = {}; +}; + + +CSSOM.CSSStyleDeclaration.prototype = { + + constructor: CSSOM.CSSStyleDeclaration, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set. + */ + getPropertyValue: function(name) { + return this[name] || ""; + }, + + /** + * + * @param {string} name + * @param {string} value + * @param {string} [priority=null] "important" or null + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty + */ + setProperty: function(name, value, priority) { + if (this[name]) { + // Property already exist. Overwrite it. + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + this[this.length] = name; + this.length++; + } + } else { + // New property. + this[this.length] = name; + this.length++; + } + this[name] = value + ""; + this._importants[name] = priority; + }, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. + */ + removeProperty: function(name) { + if (!(name in this)) { + return ""; + } + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + return ""; + } + var prevValue = this[name]; + this[name] = ""; + + // That's what WebKit and Opera do + Array.prototype.splice.call(this, index, 1); + + // That's what Firefox does + //this[index] = "" + + return prevValue; + }, + + getPropertyCSSValue: function() { + //FIXME + }, + + /** + * + * @param {String} name + */ + getPropertyPriority: function(name) { + return this._importants[name] || ""; + }, + + + /** + * element.style.overflow = "auto" + * element.style.getPropertyShorthand("overflow-x") + * -> "overflow" + */ + getPropertyShorthand: function() { + //FIXME + }, + + isPropertyImplicit: function() { + //FIXME + }, + + // Doesn't work in IE < 9 + get cssText(){ + var properties = []; + for (var i=0, length=this.length; i < length; ++i) { + var name = this[i]; + var value = this.getPropertyValue(name); + var priority = this.getPropertyPriority(name); + if (priority) { + priority = " !" + priority; + } + properties[i] = name + ": " + value + priority + ";"; + } + return properties.join(" "); + }, + + set cssText(text){ + var i, name; + for (i = this.length; i--;) { + name = this[i]; + this[name] = ""; + } + Array.prototype.splice.call(this, 0, this.length); + this._importants = {}; + + var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; + var length = dummyRule.length; + for (i = 0; i < length; ++i) { + name = dummyRule[i]; + this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); + } + } +}; + + +//.CommonJS +exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; +CSSOM.parse = require('./parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js +///CommonJS diff --git a/node_modules/cssom/lib/CSSStyleRule.js b/node_modules/cssom/lib/CSSStyleRule.js new file mode 100644 index 0000000..630b3f8 --- /dev/null +++ b/node_modules/cssom/lib/CSSStyleRule.js @@ -0,0 +1,190 @@ +//.CommonJS +var CSSOM = { + CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration, + CSSRule: require("./CSSRule").CSSRule +}; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssstylerule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule + */ +CSSOM.CSSStyleRule = function CSSStyleRule() { + CSSOM.CSSRule.call(this); + this.selectorText = ""; + this.style = new CSSOM.CSSStyleDeclaration(); + this.style.parentRule = this; +}; + +CSSOM.CSSStyleRule.prototype = new CSSOM.CSSRule(); +CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; +CSSOM.CSSStyleRule.prototype.type = 1; + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { + get: function() { + var text; + if (this.selectorText) { + text = this.selectorText + " {" + this.style.cssText + "}"; + } else { + text = ""; + } + return text; + }, + set: function(cssText) { + var rule = CSSOM.CSSStyleRule.parse(cssText); + this.style = rule.style; + this.selectorText = rule.selectorText; + } +}); + + +/** + * NON-STANDARD + * lightweight version of parse.js. + * @param {string} ruleText + * @return CSSStyleRule + */ +CSSOM.CSSStyleRule.parse = function(ruleText) { + var i = 0; + var state = "selector"; + var index; + var j = i; + var buffer = ""; + + var SIGNIFICANT_WHITESPACE = { + "selector": true, + "value": true + }; + + var styleRule = new CSSOM.CSSStyleRule(); + var name, priority=""; + + for (var character; (character = ruleText.charAt(i)); i++) { + + switch (character) { + + case " ": + case "\t": + case "\r": + case "\n": + case "\f": + if (SIGNIFICANT_WHITESPACE[state]) { + // Squash 2 or more white-spaces in the row into 1 + switch (ruleText.charAt(i - 1)) { + case " ": + case "\t": + case "\r": + case "\n": + case "\f": + break; + default: + buffer += " "; + break; + } + } + break; + + // String + case '"': + j = i + 1; + index = ruleText.indexOf('"', j) + 1; + if (!index) { + throw '" is missing'; + } + buffer += ruleText.slice(i, index); + i = index - 1; + break; + + case "'": + j = i + 1; + index = ruleText.indexOf("'", j) + 1; + if (!index) { + throw "' is missing"; + } + buffer += ruleText.slice(i, index); + i = index - 1; + break; + + // Comment + case "/": + if (ruleText.charAt(i + 1) === "*") { + i += 2; + index = ruleText.indexOf("*/", i); + if (index === -1) { + throw new SyntaxError("Missing */"); + } else { + i = index + 1; + } + } else { + buffer += character; + } + break; + + case "{": + if (state === "selector") { + styleRule.selectorText = buffer.trim(); + buffer = ""; + state = "name"; + } + break; + + case ":": + if (state === "name") { + name = buffer.trim(); + buffer = ""; + state = "value"; + } else { + buffer += character; + } + break; + + case "!": + if (state === "value" && ruleText.indexOf("!important", i) === i) { + priority = "important"; + i += "important".length; + } else { + buffer += character; + } + break; + + case ";": + if (state === "value") { + styleRule.style.setProperty(name, buffer.trim(), priority); + priority = ""; + buffer = ""; + state = "name"; + } else { + buffer += character; + } + break; + + case "}": + if (state === "value") { + styleRule.style.setProperty(name, buffer.trim(), priority); + priority = ""; + buffer = ""; + } else if (state === "name") { + break; + } else { + buffer += character; + } + state = "selector"; + break; + + default: + buffer += character; + break; + + } + } + + return styleRule; + +}; + + +//.CommonJS +exports.CSSStyleRule = CSSOM.CSSStyleRule; +///CommonJS diff --git a/node_modules/cssom/lib/CSSStyleSheet.js b/node_modules/cssom/lib/CSSStyleSheet.js new file mode 100644 index 0000000..f0e0dfc --- /dev/null +++ b/node_modules/cssom/lib/CSSStyleSheet.js @@ -0,0 +1,88 @@ +//.CommonJS +var CSSOM = { + StyleSheet: require("./StyleSheet").StyleSheet, + CSSStyleRule: require("./CSSStyleRule").CSSStyleRule +}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet + */ +CSSOM.CSSStyleSheet = function CSSStyleSheet() { + CSSOM.StyleSheet.call(this); + this.cssRules = []; +}; + + +CSSOM.CSSStyleSheet.prototype = new CSSOM.StyleSheet(); +CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; + + +/** + * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. + * + * sheet = new Sheet("body {margin: 0}") + * sheet.toString() + * -> "body{margin:0;}" + * sheet.insertRule("img {border: none}", 0) + * -> 0 + * sheet.toString() + * -> "img{border:none;}body{margin:0;}" + * + * @param {string} rule + * @param {number} index + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule + * @return {number} The index within the style sheet's rule collection of the newly inserted rule. + */ +CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { + if (index < 0 || index > this.cssRules.length) { + throw new RangeError("INDEX_SIZE_ERR"); + } + var cssRule = CSSOM.parse(rule).cssRules[0]; + cssRule.parentStyleSheet = this; + this.cssRules.splice(index, 0, cssRule); + return index; +}; + + +/** + * Used to delete a rule from the style sheet. + * + * sheet = new Sheet("img{border:none} body{margin:0}") + * sheet.toString() + * -> "img{border:none;}body{margin:0;}" + * sheet.deleteRule(0) + * sheet.toString() + * -> "body{margin:0;}" + * + * @param {number} index within the style sheet's rule list of the rule to remove. + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule + */ +CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { + if (index < 0 || index >= this.cssRules.length) { + throw new RangeError("INDEX_SIZE_ERR"); + } + this.cssRules.splice(index, 1); +}; + + +/** + * NON-STANDARD + * @return {string} serialize stylesheet + */ +CSSOM.CSSStyleSheet.prototype.toString = function() { + var result = ""; + var rules = this.cssRules; + for (var i=0; i 1000 ? '1000px' : 'auto'); + * } + */ +CSSOM.CSSValueExpression.prototype.parse = function() { + var token = this._token, + idx = this._idx; + + var character = '', + expression = '', + error = '', + info, + paren = []; + + + for (; ; ++idx) { + character = token.charAt(idx); + + // end of token + if (character === '') { + error = 'css expression error: unfinished expression!'; + break; + } + + switch(character) { + case '(': + paren.push(character); + expression += character; + break; + + case ')': + paren.pop(character); + expression += character; + break; + + case '/': + if ((info = this._parseJSComment(token, idx))) { // comment? + if (info.error) { + error = 'css expression error: unfinished comment in expression!'; + } else { + idx = info.idx; + // ignore the comment + } + } else if ((info = this._parseJSRexExp(token, idx))) { // regexp + idx = info.idx; + expression += info.text; + } else { // other + expression += character; + } + break; + + case "'": + case '"': + info = this._parseJSString(token, idx, character); + if (info) { // string + idx = info.idx; + expression += info.text; + } else { + expression += character; + } + break; + + default: + expression += character; + break; + } + + if (error) { + break; + } + + // end of expression + if (paren.length === 0) { + break; + } + } + + var ret; + if (error) { + ret = { + error: error + }; + } else { + ret = { + idx: idx, + expression: expression + }; + } + + return ret; +}; + + +/** + * + * @return {Object|false} + * - idx: + * - text: + * or + * - error: + * or + * false + * + */ +CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { + var nextChar = token.charAt(idx + 1), + text; + + if (nextChar === '/' || nextChar === '*') { + var startIdx = idx, + endIdx, + commentEndChar; + + if (nextChar === '/') { // line comment + commentEndChar = '\n'; + } else if (nextChar === '*') { // block comment + commentEndChar = '*/'; + } + + endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); + if (endIdx !== -1) { + endIdx = endIdx + commentEndChar.length - 1; + text = token.substring(idx, endIdx + 1); + return { + idx: endIdx, + text: text + }; + } else { + var error = 'css expression error: unfinished comment in expression!'; + return { + error: error + }; + } + } else { + return false; + } +}; + + +/** + * + * @return {Object|false} + * - idx: + * - text: + * or + * false + * + */ +CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { + var endIdx = this._findMatchedIdx(token, idx, sep), + text; + + if (endIdx === -1) { + return false; + } else { + text = token.substring(idx, endIdx + sep.length); + + return { + idx: endIdx, + text: text + }; + } +}; + + +/** + * parse regexp in css expression + * + * @return {Object|false} + * - idx: + * - regExp: + * or + * false + */ + +/* + +all legal RegExp + +/a/ +(/a/) +[/a/] +[12, /a/] + +!/a/ + ++/a/ +-/a/ +* /a/ +/ /a/ +%/a/ + +===/a/ +!==/a/ +==/a/ +!=/a/ +>/a/ +>=/a/ +>/a/ +>>>/a/ + +&&/a/ +||/a/ +?/a/ +=/a/ +,/a/ + + delete /a/ + in /a/ +instanceof /a/ + new /a/ + typeof /a/ + void /a/ + +*/ +CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { + var before = token.substring(0, idx).replace(/\s+$/, ""), + legalRegx = [ + /^$/, + /\($/, + /\[$/, + /\!$/, + /\+$/, + /\-$/, + /\*$/, + /\/\s+/, + /\%$/, + /\=$/, + /\>$/, + /<$/, + /\&$/, + /\|$/, + /\^$/, + /\~$/, + /\?$/, + /\,$/, + /delete$/, + /in$/, + /instanceof$/, + /new$/, + /typeof$/, + /void$/ + ]; + + var isLegal = legalRegx.some(function(reg) { + return reg.test(before); + }); + + if (!isLegal) { + return false; + } else { + var sep = '/'; + + // same logic as string + return this._parseJSString(token, idx, sep); + } +}; + + +/** + * + * find next sep(same line) index in `token` + * + * @return {Number} + * + */ +CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { + var startIdx = idx, + endIdx; + + var NOT_FOUND = -1; + + while(true) { + endIdx = token.indexOf(sep, startIdx + 1); + + if (endIdx === -1) { // not found + endIdx = NOT_FOUND; + break; + } else { + var text = token.substring(idx + 1, endIdx), + matched = text.match(/\\+$/); + if (!matched || matched[0] % 2 === 0) { // not escaped + break; + } else { + startIdx = endIdx; + } + } + } + + // boundary must be in the same line(js sting or regexp) + var nextNewLineIdx = token.indexOf('\n', idx + 1); + if (nextNewLineIdx < endIdx) { + endIdx = NOT_FOUND; + } + + + return endIdx; +}; + + + + +//.CommonJS +exports.CSSValueExpression = CSSOM.CSSValueExpression; +///CommonJS diff --git a/node_modules/cssom/lib/MatcherList.js b/node_modules/cssom/lib/MatcherList.js new file mode 100644 index 0000000..a791585 --- /dev/null +++ b/node_modules/cssom/lib/MatcherList.js @@ -0,0 +1,62 @@ +//.CommonJS +var CSSOM = {}; +///CommonJS + + +/** + * @constructor + * @see https://developer.mozilla.org/en/CSS/@-moz-document + */ +CSSOM.MatcherList = function MatcherList(){ + this.length = 0; +}; + +CSSOM.MatcherList.prototype = { + + constructor: CSSOM.MatcherList, + + /** + * @return {string} + */ + get matcherText() { + return Array.prototype.join.call(this, ", "); + }, + + /** + * @param {string} value + */ + set matcherText(value) { + // just a temporary solution, actually it may be wrong by just split the value with ',', because a url can include ','. + var values = value.split(","); + var length = this.length = values.length; + for (var i=0; i 0; + + while (ancestorRules.length > 0) { + parentRule = ancestorRules.pop(); + + if ( + parentRule.constructor.name === "CSSMediaRule" + || parentRule.constructor.name === "CSSSupportsRule" + ) { + prevScope = currentScope; + currentScope = parentRule; + currentScope.cssRules.push(prevScope); + break; + } + + if (ancestorRules.length === 0) { + hasAncestors = false; + } + } + + if (!hasAncestors) { + currentScope.__ends = i + 1; + styleSheet.cssRules.push(currentScope); + currentScope = styleSheet; + parentRule = null; + } + + buffer = ""; + state = "before-selector"; + break; + } + break; + + default: + switch (state) { + case "before-selector": + state = "selector"; + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + break; + case "before-name": + state = "name"; + break; + case "before-value": + state = "value"; + break; + case "importRule-begin": + state = "importRule"; + break; + } + buffer += character; + break; + } + } + + return styleSheet; +}; + + +//.CommonJS +exports.parse = CSSOM.parse; +// The following modules cannot be included sooner due to the mutual dependency with parse.js +CSSOM.CSSStyleSheet = require("./CSSStyleSheet").CSSStyleSheet; +CSSOM.CSSStyleRule = require("./CSSStyleRule").CSSStyleRule; +CSSOM.CSSImportRule = require("./CSSImportRule").CSSImportRule; +CSSOM.CSSMediaRule = require("./CSSMediaRule").CSSMediaRule; +CSSOM.CSSSupportsRule = require("./CSSSupportsRule").CSSSupportsRule; +CSSOM.CSSFontFaceRule = require("./CSSFontFaceRule").CSSFontFaceRule; +CSSOM.CSSHostRule = require("./CSSHostRule").CSSHostRule; +CSSOM.CSSStyleDeclaration = require('./CSSStyleDeclaration').CSSStyleDeclaration; +CSSOM.CSSKeyframeRule = require('./CSSKeyframeRule').CSSKeyframeRule; +CSSOM.CSSKeyframesRule = require('./CSSKeyframesRule').CSSKeyframesRule; +CSSOM.CSSValueExpression = require('./CSSValueExpression').CSSValueExpression; +CSSOM.CSSDocumentRule = require('./CSSDocumentRule').CSSDocumentRule; +///CommonJS diff --git a/node_modules/cssom/lib/snapshot.js b/node_modules/cssom/lib/snapshot.js new file mode 100644 index 0000000..2acf071 --- /dev/null +++ b/node_modules/cssom/lib/snapshot.js @@ -0,0 +1,76 @@ +//.CommonJS +var CSSOM = { + CSSStyleSheet: require("./CSSStyleSheet").CSSStyleSheet, + CSSStyleRule: require("./CSSStyleRule").CSSStyleRule, + CSSMediaRule: require("./CSSMediaRule").CSSMediaRule, + CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration, + CSSKeyframeRule: require('./CSSKeyframeRule').CSSKeyframeRule, + CSSKeyframesRule: require('./CSSKeyframesRule').CSSKeyframesRule +}; +///CommonJS + + +/** + * Produces a deep copy of stylesheet — the instance variables of stylesheet are copied recursively. + * @param {CSSStyleSheet|CSSOM.CSSStyleSheet} stylesheet + * @nosideeffects + * @return {CSSOM.CSSStyleSheet} + */ +CSSOM.snapshot = function clone(stylesheet) { + + var cloned = new CSSOM.CSSStyleSheet; + + var rules = stylesheet.cssRules; + if (!rules) { + return cloned; + } + + var RULE_TYPES = { + 1: CSSOM.CSSStyleRule, + 4: CSSOM.CSSMediaRule, + //3: CSSOM.CSSImportRule, + //5: CSSOM.CSSFontFaceRule, + //6: CSSOM.CSSPageRule, + 8: CSSOM.CSSKeyframesRule, + 9: CSSOM.CSSKeyframeRule + }; + + for (var i=0, rulesLength=rules.length; i < rulesLength; i++) { + var rule = rules[i]; + var ruleClone = cloned.cssRules[i] = new RULE_TYPES[rule.type]; + + var style = rule.style; + if (style) { + var styleClone = ruleClone.style = new CSSOM.CSSStyleDeclaration; + for (var j=0, styleLength=style.length; j < styleLength; j++) { + var name = styleClone[j] = style[j]; + styleClone[name] = style[name]; + styleClone._importants[name] = style.getPropertyPriority(name); + } + styleClone.length = style.length; + } + + if ("keyText" in rule) { + ruleClone.keyText = rule.keyText; + } + + if ("selectorText" in rule) { + ruleClone.selectorText = rule.selectorText; + } + + if ("mediaText" in rule) { + ruleClone.mediaText = rule.mediaText; + } + + if ("cssRules" in rule) { + rule.cssRules = clone(rule).cssRules; + } + } + + return cloned; + +}; + +//.CommonJS +exports.clone = CSSOM.clone; +///CommonJS diff --git a/node_modules/cssom/package.json b/node_modules/cssom/package.json new file mode 100644 index 0000000..eab020d --- /dev/null +++ b/node_modules/cssom/package.json @@ -0,0 +1,60 @@ +{ + "_from": "cssom@^0.3.4", + "_id": "cssom@0.3.6", + "_inBundle": false, + "_integrity": "sha512-DtUeseGk9/GBW0hl0vVPpU22iHL6YB5BUX7ml1hB+GMpo0NX5G4voX3kdWiMSEguFtcW3Vh3djqNF4aIe6ne0A==", + "_location": "/cssom", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cssom@^0.3.4", + "name": "cssom", + "escapedName": "cssom", + "rawSpec": "^0.3.4", + "saveSpec": null, + "fetchSpec": "^0.3.4" + }, + "_requiredBy": [ + "/cssstyle", + "/jsdom" + ], + "_resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.6.tgz", + "_shasum": "f85206cee04efa841f3c5982a74ba96ab20d65ad", + "_spec": "cssom@^0.3.4", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\jsdom", + "author": { + "name": "Nikita Vasilyev", + "email": "me@elv1s.ru" + }, + "bugs": { + "url": "https://github.com/NV/CSSOM/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "CSS Object Model implementation and CSS parser", + "devDependencies": { + "jake": "~0.7.3" + }, + "files": [ + "lib/" + ], + "homepage": "https://github.com/NV/CSSOM#readme", + "keywords": [ + "CSS", + "CSSOM", + "parser", + "styleSheet" + ], + "license": "MIT", + "main": "./lib/index.js", + "name": "cssom", + "repository": { + "type": "git", + "url": "git+https://github.com/NV/CSSOM.git" + }, + "scripts": { + "prepublish": "jake lib/index.js" + }, + "version": "0.3.6" +} diff --git a/node_modules/cssstyle/.eslintignore b/node_modules/cssstyle/.eslintignore new file mode 100644 index 0000000..f9e0b73 --- /dev/null +++ b/node_modules/cssstyle/.eslintignore @@ -0,0 +1,3 @@ +node_modules +lib/implementedProperties.js +lib/properties.js diff --git a/node_modules/cssstyle/.eslintrc.js b/node_modules/cssstyle/.eslintrc.js new file mode 100644 index 0000000..770d799 --- /dev/null +++ b/node_modules/cssstyle/.eslintrc.js @@ -0,0 +1,50 @@ +'use strict'; + +module.exports = { + root: true, + extends: ['eslint:recommended', 'prettier'], + parserOptions: { + ecmaVersion: 2018, + }, + env: { + es6: true, + }, + globals: { + exports: true, + module: true, + require: true, + window: true, + }, + plugins: ['prettier'], + rules: { + 'prettier/prettier': [ + 'warn', + { + printWidth: 100, + singleQuote: true, + trailingComma: 'es5', + }, + ], + strict: ['warn', 'global'], + }, + overrides: [ + { + files: ['lib/implementedProperties.js', 'lib/properties.js'], + rules: { + 'prettier/prettier': 'off', + }, + }, + { + files: 'scripts/**/*', + rules: { + 'no-console': 'off', + }, + }, + { + files: ['scripts/**/*', 'tests/**/*'], + env: { + node: true, + }, + }, + ], +}; diff --git a/node_modules/cssstyle/.travis.yml b/node_modules/cssstyle/.travis.yml new file mode 100644 index 0000000..cf9a223 --- /dev/null +++ b/node_modules/cssstyle/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +cache: + directories: + - node_modules +notifications: + email: true +node_js: + - 6 + - 8 + - 10 + - 11 + +script: + - npm run test-ci diff --git a/node_modules/cssstyle/MIT-LICENSE.txt b/node_modules/cssstyle/MIT-LICENSE.txt new file mode 100644 index 0000000..060a7e6 --- /dev/null +++ b/node_modules/cssstyle/MIT-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) Chad Walker + +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. diff --git a/node_modules/cssstyle/README.md b/node_modules/cssstyle/README.md new file mode 100644 index 0000000..66b14ae --- /dev/null +++ b/node_modules/cssstyle/README.md @@ -0,0 +1,27 @@ +# CSSStyleDeclaration + +[![NpmVersion](https://img.shields.io/npm/v/cssstyle.svg)](https://www.npmjs.com/package/cssstyle) [![Build Status](https://travis-ci.org/jsakas/CSSStyleDeclaration.svg?branch=master)](https://travis-ci.org/jsakas/CSSStyleDeclaration) + +CSSStyleDeclaration is a work-a-like to the CSSStyleDeclaration class in Nikita Vasilyev's [CSSOM](https://github.com/NV/CSSOM). I made it so that when using [jQuery in node](https://github.com/tmtk75/node-jquery) setting css attributes via $.fn.css() would work. node-jquery uses [jsdom](https://github.com/tmpvar/jsdom) to create a DOM to use in node. jsdom uses CSSOM for styling, and CSSOM's implementation of the [CSSStyleDeclaration](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration) doesn't support [CSS2Properties](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSS2Properties), which is how jQuery's [$.fn.css()](http://api.jquery.com/css/) operates. + +### Why not just issue a pull request? + +Well, NV wants to keep CSSOM fast (which I can appreciate) and CSS2Properties aren't required by the standard (though every browser has the interface). So I figured the path of least resistance would be to just modify this one class, publish it as a node module (that requires CSSOM) and then make a pull request of jsdom to use it. + +### How do I test this code? + +`npm test` should do the trick, assuming you have the dev dependencies installed: + +``` +$ npm test + +tests +✔ Verify Has Properties +✔ Verify Has Functions +✔ Verify Has Special Properties +✔ Test From Style String +✔ Test From Properties +✔ Test Shorthand Properties +✔ Test width and height Properties and null and empty strings +✔ Test Implicit Properties +``` diff --git a/node_modules/cssstyle/lib/CSSStyleDeclaration.js b/node_modules/cssstyle/lib/CSSStyleDeclaration.js new file mode 100644 index 0000000..0bb9ece --- /dev/null +++ b/node_modules/cssstyle/lib/CSSStyleDeclaration.js @@ -0,0 +1,255 @@ +/********************************************************************* + * This is a fork from the CSS Style Declaration part of + * https://github.com/NV/CSSOM + ********************************************************************/ +'use strict'; +var CSSOM = require('cssom'); +var allProperties = require('./allProperties'); +var allExtraProperties = require('./allExtraProperties'); +var implementedProperties = require('./implementedProperties'); +var { dashedToCamelCase } = require('./parsers'); +var getBasicPropertyDescriptor = require('./utils/getBasicPropertyDescriptor'); + +/** + * @constructor + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration + */ +var CSSStyleDeclaration = function CSSStyleDeclaration(onChangeCallback) { + this._values = {}; + this._importants = {}; + this._length = 0; + this._onChange = + onChangeCallback || + function() { + return; + }; +}; +CSSStyleDeclaration.prototype = { + constructor: CSSStyleDeclaration, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set. + */ + getPropertyValue: function(name) { + if (!this._values.hasOwnProperty(name)) { + return ''; + } + return this._values[name].toString(); + }, + + /** + * + * @param {string} name + * @param {string} value + * @param {string} [priority=null] "important" or null + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty + */ + setProperty: function(name, value, priority) { + if (value === undefined) { + return; + } + if (value === null || value === '') { + this.removeProperty(name); + return; + } + var lowercaseName = name.toLowerCase(); + if (!allProperties.has(lowercaseName) && !allExtraProperties.has(lowercaseName)) { + return; + } + + this[lowercaseName] = value; + this._importants[lowercaseName] = priority; + }, + _setProperty: function(name, value, priority) { + if (value === undefined) { + return; + } + if (value === null || value === '') { + this.removeProperty(name); + return; + } + if (this._values[name]) { + // Property already exist. Overwrite it. + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + this[this._length] = name; + this._length++; + } + } else { + // New property. + this[this._length] = name; + this._length++; + } + this._values[name] = value; + this._importants[name] = priority; + this._onChange(this.cssText); + }, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. + */ + removeProperty: function(name) { + if (!this._values.hasOwnProperty(name)) { + return ''; + } + + var prevValue = this._values[name]; + delete this._values[name]; + delete this._importants[name]; + + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + return prevValue; + } + + // That's what WebKit and Opera do + Array.prototype.splice.call(this, index, 1); + + // That's what Firefox does + //this[index] = "" + + this._onChange(this.cssText); + return prevValue; + }, + + /** + * + * @param {String} name + */ + getPropertyPriority: function(name) { + return this._importants[name] || ''; + }, + + getPropertyCSSValue: function() { + //FIXME + return; + }, + + /** + * element.style.overflow = "auto" + * element.style.getPropertyShorthand("overflow-x") + * -> "overflow" + */ + getPropertyShorthand: function() { + //FIXME + return; + }, + + isPropertyImplicit: function() { + //FIXME + return; + }, + + /** + * http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-item + */ + item: function(index) { + index = parseInt(index, 10); + if (index < 0 || index >= this._length) { + return ''; + } + return this[index]; + }, +}; + +Object.defineProperties(CSSStyleDeclaration.prototype, { + cssText: { + get: function() { + var properties = []; + var i; + var name; + var value; + var priority; + for (i = 0; i < this._length; i++) { + name = this[i]; + value = this.getPropertyValue(name); + priority = this.getPropertyPriority(name); + if (priority !== '') { + priority = ' !' + priority; + } + properties.push([name, ': ', value, priority, ';'].join('')); + } + return properties.join(' '); + }, + set: function(value) { + var i; + this._values = {}; + Array.prototype.splice.call(this, 0, this._length); + this._importants = {}; + var dummyRule; + try { + dummyRule = CSSOM.parse('#bogus{' + value + '}').cssRules[0].style; + } catch (err) { + // malformed css, just return + return; + } + var rule_length = dummyRule.length; + var name; + for (i = 0; i < rule_length; ++i) { + name = dummyRule[i]; + this.setProperty( + dummyRule[i], + dummyRule.getPropertyValue(name), + dummyRule.getPropertyPriority(name) + ); + } + this._onChange(this.cssText); + }, + enumerable: true, + configurable: true, + }, + parentRule: { + get: function() { + return null; + }, + enumerable: true, + configurable: true, + }, + length: { + get: function() { + return this._length; + }, + /** + * This deletes indices if the new length is less then the current + * length. If the new length is more, it does nothing, the new indices + * will be undefined until set. + **/ + set: function(value) { + var i; + for (i = value; i < this._length; i++) { + delete this[i]; + } + this._length = value; + }, + enumerable: true, + configurable: true, + }, +}); + +require('./properties')(CSSStyleDeclaration.prototype); + +allProperties.forEach(function(property) { + if (!implementedProperties.has(property)) { + var declaration = getBasicPropertyDescriptor(property); + Object.defineProperty(CSSStyleDeclaration.prototype, property, declaration); + Object.defineProperty(CSSStyleDeclaration.prototype, dashedToCamelCase(property), declaration); + } +}); + +allExtraProperties.forEach(function(property) { + if (!implementedProperties.has(property)) { + var declaration = getBasicPropertyDescriptor(property); + Object.defineProperty(CSSStyleDeclaration.prototype, property, declaration); + Object.defineProperty(CSSStyleDeclaration.prototype, dashedToCamelCase(property), declaration); + } +}); + +exports.CSSStyleDeclaration = CSSStyleDeclaration; diff --git a/node_modules/cssstyle/lib/allExtraProperties.js b/node_modules/cssstyle/lib/allExtraProperties.js new file mode 100644 index 0000000..0d66ca8 --- /dev/null +++ b/node_modules/cssstyle/lib/allExtraProperties.js @@ -0,0 +1,248 @@ +'use strict'; + +/** + * This file contains all implemented properties that are not a part of any + * current specifications or drafts, but are handled by browsers nevertheless. + */ + +var allExtraProperties = new Set(); +module.exports = allExtraProperties; +allExtraProperties.add('background-position-x'); +allExtraProperties.add('background-position-y'); +allExtraProperties.add('background-repeat-x'); +allExtraProperties.add('background-repeat-y'); +allExtraProperties.add('color-interpolation'); +allExtraProperties.add('color-profile'); +allExtraProperties.add('color-rendering'); +allExtraProperties.add('css-float'); +allExtraProperties.add('enable-background'); +allExtraProperties.add('fill'); +allExtraProperties.add('fill-opacity'); +allExtraProperties.add('fill-rule'); +allExtraProperties.add('glyph-orientation-horizontal'); +allExtraProperties.add('image-rendering'); +allExtraProperties.add('kerning'); +allExtraProperties.add('marker'); +allExtraProperties.add('marker-end'); +allExtraProperties.add('marker-mid'); +allExtraProperties.add('marker-offset'); +allExtraProperties.add('marker-start'); +allExtraProperties.add('marks'); +allExtraProperties.add('pointer-events'); +allExtraProperties.add('shape-rendering'); +allExtraProperties.add('size'); +allExtraProperties.add('src'); +allExtraProperties.add('stop-color'); +allExtraProperties.add('stop-opacity'); +allExtraProperties.add('stroke'); +allExtraProperties.add('stroke-dasharray'); +allExtraProperties.add('stroke-dashoffset'); +allExtraProperties.add('stroke-linecap'); +allExtraProperties.add('stroke-linejoin'); +allExtraProperties.add('stroke-miterlimit'); +allExtraProperties.add('stroke-opacity'); +allExtraProperties.add('stroke-width'); +allExtraProperties.add('text-anchor'); +allExtraProperties.add('text-line-through'); +allExtraProperties.add('text-line-through-color'); +allExtraProperties.add('text-line-through-mode'); +allExtraProperties.add('text-line-through-style'); +allExtraProperties.add('text-line-through-width'); +allExtraProperties.add('text-overline'); +allExtraProperties.add('text-overline-color'); +allExtraProperties.add('text-overline-mode'); +allExtraProperties.add('text-overline-style'); +allExtraProperties.add('text-overline-width'); +allExtraProperties.add('text-rendering'); +allExtraProperties.add('text-underline'); +allExtraProperties.add('text-underline-color'); +allExtraProperties.add('text-underline-mode'); +allExtraProperties.add('text-underline-style'); +allExtraProperties.add('text-underline-width'); +allExtraProperties.add('unicode-range'); +allExtraProperties.add('vector-effect'); +allExtraProperties.add('webkit-animation'); +allExtraProperties.add('webkit-animation-delay'); +allExtraProperties.add('webkit-animation-direction'); +allExtraProperties.add('webkit-animation-duration'); +allExtraProperties.add('webkit-animation-fill-mode'); +allExtraProperties.add('webkit-animation-iteration-count'); +allExtraProperties.add('webkit-animation-name'); +allExtraProperties.add('webkit-animation-play-state'); +allExtraProperties.add('webkit-animation-timing-function'); +allExtraProperties.add('webkit-appearance'); +allExtraProperties.add('webkit-aspect-ratio'); +allExtraProperties.add('webkit-backface-visibility'); +allExtraProperties.add('webkit-background-clip'); +allExtraProperties.add('webkit-background-composite'); +allExtraProperties.add('webkit-background-origin'); +allExtraProperties.add('webkit-background-size'); +allExtraProperties.add('webkit-border-after'); +allExtraProperties.add('webkit-border-after-color'); +allExtraProperties.add('webkit-border-after-style'); +allExtraProperties.add('webkit-border-after-width'); +allExtraProperties.add('webkit-border-before'); +allExtraProperties.add('webkit-border-before-color'); +allExtraProperties.add('webkit-border-before-style'); +allExtraProperties.add('webkit-border-before-width'); +allExtraProperties.add('webkit-border-end'); +allExtraProperties.add('webkit-border-end-color'); +allExtraProperties.add('webkit-border-end-style'); +allExtraProperties.add('webkit-border-end-width'); +allExtraProperties.add('webkit-border-fit'); +allExtraProperties.add('webkit-border-horizontal-spacing'); +allExtraProperties.add('webkit-border-image'); +allExtraProperties.add('webkit-border-radius'); +allExtraProperties.add('webkit-border-start'); +allExtraProperties.add('webkit-border-start-color'); +allExtraProperties.add('webkit-border-start-style'); +allExtraProperties.add('webkit-border-start-width'); +allExtraProperties.add('webkit-border-vertical-spacing'); +allExtraProperties.add('webkit-box-align'); +allExtraProperties.add('webkit-box-direction'); +allExtraProperties.add('webkit-box-flex'); +allExtraProperties.add('webkit-box-flex-group'); +allExtraProperties.add('webkit-box-lines'); +allExtraProperties.add('webkit-box-ordinal-group'); +allExtraProperties.add('webkit-box-orient'); +allExtraProperties.add('webkit-box-pack'); +allExtraProperties.add('webkit-box-reflect'); +allExtraProperties.add('webkit-box-shadow'); +allExtraProperties.add('webkit-color-correction'); +allExtraProperties.add('webkit-column-axis'); +allExtraProperties.add('webkit-column-break-after'); +allExtraProperties.add('webkit-column-break-before'); +allExtraProperties.add('webkit-column-break-inside'); +allExtraProperties.add('webkit-column-count'); +allExtraProperties.add('webkit-column-gap'); +allExtraProperties.add('webkit-column-rule'); +allExtraProperties.add('webkit-column-rule-color'); +allExtraProperties.add('webkit-column-rule-style'); +allExtraProperties.add('webkit-column-rule-width'); +allExtraProperties.add('webkit-columns'); +allExtraProperties.add('webkit-column-span'); +allExtraProperties.add('webkit-column-width'); +allExtraProperties.add('webkit-filter'); +allExtraProperties.add('webkit-flex-align'); +allExtraProperties.add('webkit-flex-direction'); +allExtraProperties.add('webkit-flex-flow'); +allExtraProperties.add('webkit-flex-item-align'); +allExtraProperties.add('webkit-flex-line-pack'); +allExtraProperties.add('webkit-flex-order'); +allExtraProperties.add('webkit-flex-pack'); +allExtraProperties.add('webkit-flex-wrap'); +allExtraProperties.add('webkit-flow-from'); +allExtraProperties.add('webkit-flow-into'); +allExtraProperties.add('webkit-font-feature-settings'); +allExtraProperties.add('webkit-font-kerning'); +allExtraProperties.add('webkit-font-size-delta'); +allExtraProperties.add('webkit-font-smoothing'); +allExtraProperties.add('webkit-font-variant-ligatures'); +allExtraProperties.add('webkit-highlight'); +allExtraProperties.add('webkit-hyphenate-character'); +allExtraProperties.add('webkit-hyphenate-limit-after'); +allExtraProperties.add('webkit-hyphenate-limit-before'); +allExtraProperties.add('webkit-hyphenate-limit-lines'); +allExtraProperties.add('webkit-hyphens'); +allExtraProperties.add('webkit-line-align'); +allExtraProperties.add('webkit-line-box-contain'); +allExtraProperties.add('webkit-line-break'); +allExtraProperties.add('webkit-line-clamp'); +allExtraProperties.add('webkit-line-grid'); +allExtraProperties.add('webkit-line-snap'); +allExtraProperties.add('webkit-locale'); +allExtraProperties.add('webkit-logical-height'); +allExtraProperties.add('webkit-logical-width'); +allExtraProperties.add('webkit-margin-after'); +allExtraProperties.add('webkit-margin-after-collapse'); +allExtraProperties.add('webkit-margin-before'); +allExtraProperties.add('webkit-margin-before-collapse'); +allExtraProperties.add('webkit-margin-bottom-collapse'); +allExtraProperties.add('webkit-margin-collapse'); +allExtraProperties.add('webkit-margin-end'); +allExtraProperties.add('webkit-margin-start'); +allExtraProperties.add('webkit-margin-top-collapse'); +allExtraProperties.add('webkit-marquee'); +allExtraProperties.add('webkit-marquee-direction'); +allExtraProperties.add('webkit-marquee-increment'); +allExtraProperties.add('webkit-marquee-repetition'); +allExtraProperties.add('webkit-marquee-speed'); +allExtraProperties.add('webkit-marquee-style'); +allExtraProperties.add('webkit-mask'); +allExtraProperties.add('webkit-mask-attachment'); +allExtraProperties.add('webkit-mask-box-image'); +allExtraProperties.add('webkit-mask-box-image-outset'); +allExtraProperties.add('webkit-mask-box-image-repeat'); +allExtraProperties.add('webkit-mask-box-image-slice'); +allExtraProperties.add('webkit-mask-box-image-source'); +allExtraProperties.add('webkit-mask-box-image-width'); +allExtraProperties.add('webkit-mask-clip'); +allExtraProperties.add('webkit-mask-composite'); +allExtraProperties.add('webkit-mask-image'); +allExtraProperties.add('webkit-mask-origin'); +allExtraProperties.add('webkit-mask-position'); +allExtraProperties.add('webkit-mask-position-x'); +allExtraProperties.add('webkit-mask-position-y'); +allExtraProperties.add('webkit-mask-repeat'); +allExtraProperties.add('webkit-mask-repeat-x'); +allExtraProperties.add('webkit-mask-repeat-y'); +allExtraProperties.add('webkit-mask-size'); +allExtraProperties.add('webkit-match-nearest-mail-blockquote-color'); +allExtraProperties.add('webkit-max-logical-height'); +allExtraProperties.add('webkit-max-logical-width'); +allExtraProperties.add('webkit-min-logical-height'); +allExtraProperties.add('webkit-min-logical-width'); +allExtraProperties.add('webkit-nbsp-mode'); +allExtraProperties.add('webkit-overflow-scrolling'); +allExtraProperties.add('webkit-padding-after'); +allExtraProperties.add('webkit-padding-before'); +allExtraProperties.add('webkit-padding-end'); +allExtraProperties.add('webkit-padding-start'); +allExtraProperties.add('webkit-perspective'); +allExtraProperties.add('webkit-perspective-origin'); +allExtraProperties.add('webkit-perspective-origin-x'); +allExtraProperties.add('webkit-perspective-origin-y'); +allExtraProperties.add('webkit-print-color-adjust'); +allExtraProperties.add('webkit-region-break-after'); +allExtraProperties.add('webkit-region-break-before'); +allExtraProperties.add('webkit-region-break-inside'); +allExtraProperties.add('webkit-region-overflow'); +allExtraProperties.add('webkit-rtl-ordering'); +allExtraProperties.add('webkit-svg-shadow'); +allExtraProperties.add('webkit-tap-highlight-color'); +allExtraProperties.add('webkit-text-combine'); +allExtraProperties.add('webkit-text-decorations-in-effect'); +allExtraProperties.add('webkit-text-emphasis'); +allExtraProperties.add('webkit-text-emphasis-color'); +allExtraProperties.add('webkit-text-emphasis-position'); +allExtraProperties.add('webkit-text-emphasis-style'); +allExtraProperties.add('webkit-text-fill-color'); +allExtraProperties.add('webkit-text-orientation'); +allExtraProperties.add('webkit-text-security'); +allExtraProperties.add('webkit-text-size-adjust'); +allExtraProperties.add('webkit-text-stroke'); +allExtraProperties.add('webkit-text-stroke-color'); +allExtraProperties.add('webkit-text-stroke-width'); +allExtraProperties.add('webkit-transform'); +allExtraProperties.add('webkit-transform-origin'); +allExtraProperties.add('webkit-transform-origin-x'); +allExtraProperties.add('webkit-transform-origin-y'); +allExtraProperties.add('webkit-transform-origin-z'); +allExtraProperties.add('webkit-transform-style'); +allExtraProperties.add('webkit-transition'); +allExtraProperties.add('webkit-transition-delay'); +allExtraProperties.add('webkit-transition-duration'); +allExtraProperties.add('webkit-transition-property'); +allExtraProperties.add('webkit-transition-timing-function'); +allExtraProperties.add('webkit-user-drag'); +allExtraProperties.add('webkit-user-modify'); +allExtraProperties.add('webkit-user-select'); +allExtraProperties.add('webkit-wrap'); +allExtraProperties.add('webkit-wrap-flow'); +allExtraProperties.add('webkit-wrap-margin'); +allExtraProperties.add('webkit-wrap-padding'); +allExtraProperties.add('webkit-wrap-shape-inside'); +allExtraProperties.add('webkit-wrap-shape-outside'); +allExtraProperties.add('webkit-wrap-through'); +allExtraProperties.add('webkit-writing-mode'); +allExtraProperties.add('zoom'); diff --git a/node_modules/cssstyle/lib/allProperties.js b/node_modules/cssstyle/lib/allProperties.js new file mode 100644 index 0000000..fc801df --- /dev/null +++ b/node_modules/cssstyle/lib/allProperties.js @@ -0,0 +1,457 @@ +'use strict'; + +// autogenerated - 2/3/2019 + +/* + * + * https://www.w3.org/Style/CSS/all-properties.en.html + */ + +var allProperties = new Set(); +module.exports = allProperties; +allProperties.add('align-content'); +allProperties.add('align-items'); +allProperties.add('align-self'); +allProperties.add('alignment-baseline'); +allProperties.add('all'); +allProperties.add('animation'); +allProperties.add('animation-delay'); +allProperties.add('animation-direction'); +allProperties.add('animation-duration'); +allProperties.add('animation-fill-mode'); +allProperties.add('animation-iteration-count'); +allProperties.add('animation-name'); +allProperties.add('animation-play-state'); +allProperties.add('animation-timing-function'); +allProperties.add('appearance'); +allProperties.add('azimuth'); +allProperties.add('background'); +allProperties.add('background-attachment'); +allProperties.add('background-blend-mode'); +allProperties.add('background-clip'); +allProperties.add('background-color'); +allProperties.add('background-image'); +allProperties.add('background-origin'); +allProperties.add('background-position'); +allProperties.add('background-repeat'); +allProperties.add('background-size'); +allProperties.add('baseline-shift'); +allProperties.add('block-overflow'); +allProperties.add('block-size'); +allProperties.add('bookmark-label'); +allProperties.add('bookmark-level'); +allProperties.add('bookmark-state'); +allProperties.add('border'); +allProperties.add('border-block'); +allProperties.add('border-block-color'); +allProperties.add('border-block-end'); +allProperties.add('border-block-end-color'); +allProperties.add('border-block-end-style'); +allProperties.add('border-block-end-width'); +allProperties.add('border-block-start'); +allProperties.add('border-block-start-color'); +allProperties.add('border-block-start-style'); +allProperties.add('border-block-start-width'); +allProperties.add('border-block-style'); +allProperties.add('border-block-width'); +allProperties.add('border-bottom'); +allProperties.add('border-bottom-color'); +allProperties.add('border-bottom-left-radius'); +allProperties.add('border-bottom-right-radius'); +allProperties.add('border-bottom-style'); +allProperties.add('border-bottom-width'); +allProperties.add('border-boundary'); +allProperties.add('border-collapse'); +allProperties.add('border-color'); +allProperties.add('border-end-end-radius'); +allProperties.add('border-end-start-radius'); +allProperties.add('border-image'); +allProperties.add('border-image-outset'); +allProperties.add('border-image-repeat'); +allProperties.add('border-image-slice'); +allProperties.add('border-image-source'); +allProperties.add('border-image-width'); +allProperties.add('border-inline'); +allProperties.add('border-inline-color'); +allProperties.add('border-inline-end'); +allProperties.add('border-inline-end-color'); +allProperties.add('border-inline-end-style'); +allProperties.add('border-inline-end-width'); +allProperties.add('border-inline-start'); +allProperties.add('border-inline-start-color'); +allProperties.add('border-inline-start-style'); +allProperties.add('border-inline-start-width'); +allProperties.add('border-inline-style'); +allProperties.add('border-inline-width'); +allProperties.add('border-left'); +allProperties.add('border-left-color'); +allProperties.add('border-left-style'); +allProperties.add('border-left-width'); +allProperties.add('border-radius'); +allProperties.add('border-right'); +allProperties.add('border-right-color'); +allProperties.add('border-right-style'); +allProperties.add('border-right-width'); +allProperties.add('border-spacing'); +allProperties.add('border-start-end-radius'); +allProperties.add('border-start-start-radius'); +allProperties.add('border-style'); +allProperties.add('border-top'); +allProperties.add('border-top-color'); +allProperties.add('border-top-left-radius'); +allProperties.add('border-top-right-radius'); +allProperties.add('border-top-style'); +allProperties.add('border-top-width'); +allProperties.add('border-width'); +allProperties.add('bottom'); +allProperties.add('box-decoration-break'); +allProperties.add('box-shadow'); +allProperties.add('box-sizing'); +allProperties.add('box-snap'); +allProperties.add('break-after'); +allProperties.add('break-before'); +allProperties.add('break-inside'); +allProperties.add('caption-side'); +allProperties.add('caret'); +allProperties.add('caret-color'); +allProperties.add('caret-shape'); +allProperties.add('chains'); +allProperties.add('clear'); +allProperties.add('clip'); +allProperties.add('clip-path'); +allProperties.add('clip-rule'); +allProperties.add('color'); +allProperties.add('color-interpolation-filters'); +allProperties.add('column-count'); +allProperties.add('column-fill'); +allProperties.add('column-gap'); +allProperties.add('column-rule'); +allProperties.add('column-rule-color'); +allProperties.add('column-rule-style'); +allProperties.add('column-rule-width'); +allProperties.add('column-span'); +allProperties.add('column-width'); +allProperties.add('columns'); +allProperties.add('contain'); +allProperties.add('content'); +allProperties.add('continue'); +allProperties.add('counter-increment'); +allProperties.add('counter-reset'); +allProperties.add('counter-set'); +allProperties.add('cue'); +allProperties.add('cue-after'); +allProperties.add('cue-before'); +allProperties.add('cursor'); +allProperties.add('direction'); +allProperties.add('display'); +allProperties.add('dominant-baseline'); +allProperties.add('elevation'); +allProperties.add('empty-cells'); +allProperties.add('filter'); +allProperties.add('flex'); +allProperties.add('flex-basis'); +allProperties.add('flex-direction'); +allProperties.add('flex-flow'); +allProperties.add('flex-grow'); +allProperties.add('flex-shrink'); +allProperties.add('flex-wrap'); +allProperties.add('float'); +allProperties.add('flood-color'); +allProperties.add('flood-opacity'); +allProperties.add('flow'); +allProperties.add('flow-from'); +allProperties.add('flow-into'); +allProperties.add('font'); +allProperties.add('font-family'); +allProperties.add('font-feature-settings'); +allProperties.add('font-kerning'); +allProperties.add('font-language-override'); +allProperties.add('font-max-size'); +allProperties.add('font-min-size'); +allProperties.add('font-optical-sizing'); +allProperties.add('font-palette'); +allProperties.add('font-size'); +allProperties.add('font-size-adjust'); +allProperties.add('font-stretch'); +allProperties.add('font-style'); +allProperties.add('font-synthesis'); +allProperties.add('font-synthesis-small-caps'); +allProperties.add('font-synthesis-style'); +allProperties.add('font-synthesis-weight'); +allProperties.add('font-variant'); +allProperties.add('font-variant-alternates'); +allProperties.add('font-variant-caps'); +allProperties.add('font-variant-east-asian'); +allProperties.add('font-variant-emoji'); +allProperties.add('font-variant-ligatures'); +allProperties.add('font-variant-numeric'); +allProperties.add('font-variant-position'); +allProperties.add('font-variation-settings'); +allProperties.add('font-weight'); +allProperties.add('footnote-display'); +allProperties.add('footnote-policy'); +allProperties.add('gap'); +allProperties.add('glyph-orientation-vertical'); +allProperties.add('grid'); +allProperties.add('grid-area'); +allProperties.add('grid-auto-columns'); +allProperties.add('grid-auto-flow'); +allProperties.add('grid-auto-rows'); +allProperties.add('grid-column'); +allProperties.add('grid-column-end'); +allProperties.add('grid-column-start'); +allProperties.add('grid-row'); +allProperties.add('grid-row-end'); +allProperties.add('grid-row-start'); +allProperties.add('grid-template'); +allProperties.add('grid-template-areas'); +allProperties.add('grid-template-columns'); +allProperties.add('grid-template-rows'); +allProperties.add('hanging-punctuation'); +allProperties.add('height'); +allProperties.add('hyphenate-character'); +allProperties.add('hyphenate-limit-chars'); +allProperties.add('hyphenate-limit-last'); +allProperties.add('hyphenate-limit-lines'); +allProperties.add('hyphenate-limit-zone'); +allProperties.add('hyphens'); +allProperties.add('image-orientation'); +allProperties.add('image-resolution'); +allProperties.add('initial-letters'); +allProperties.add('initial-letters-align'); +allProperties.add('initial-letters-wrap'); +allProperties.add('inline-size'); +allProperties.add('inline-sizing'); +allProperties.add('inset'); +allProperties.add('inset-block'); +allProperties.add('inset-block-end'); +allProperties.add('inset-block-start'); +allProperties.add('inset-inline'); +allProperties.add('inset-inline-end'); +allProperties.add('inset-inline-start'); +allProperties.add('isolation'); +allProperties.add('justify-content'); +allProperties.add('justify-items'); +allProperties.add('justify-self'); +allProperties.add('left'); +allProperties.add('letter-spacing'); +allProperties.add('lighting-color'); +allProperties.add('line-break'); +allProperties.add('line-clamp'); +allProperties.add('line-grid'); +allProperties.add('line-height'); +allProperties.add('line-padding'); +allProperties.add('line-snap'); +allProperties.add('list-style'); +allProperties.add('list-style-image'); +allProperties.add('list-style-position'); +allProperties.add('list-style-type'); +allProperties.add('margin'); +allProperties.add('margin-block'); +allProperties.add('margin-block-end'); +allProperties.add('margin-block-start'); +allProperties.add('margin-bottom'); +allProperties.add('margin-inline'); +allProperties.add('margin-inline-end'); +allProperties.add('margin-inline-start'); +allProperties.add('margin-left'); +allProperties.add('margin-right'); +allProperties.add('margin-top'); +allProperties.add('margin-trim'); +allProperties.add('marker-side'); +allProperties.add('mask'); +allProperties.add('mask-border'); +allProperties.add('mask-border-mode'); +allProperties.add('mask-border-outset'); +allProperties.add('mask-border-repeat'); +allProperties.add('mask-border-slice'); +allProperties.add('mask-border-source'); +allProperties.add('mask-border-width'); +allProperties.add('mask-clip'); +allProperties.add('mask-composite'); +allProperties.add('mask-image'); +allProperties.add('mask-mode'); +allProperties.add('mask-origin'); +allProperties.add('mask-position'); +allProperties.add('mask-repeat'); +allProperties.add('mask-size'); +allProperties.add('mask-type'); +allProperties.add('max-block-size'); +allProperties.add('max-height'); +allProperties.add('max-inline-size'); +allProperties.add('max-lines'); +allProperties.add('max-width'); +allProperties.add('min-block-size'); +allProperties.add('min-height'); +allProperties.add('min-inline-size'); +allProperties.add('min-width'); +allProperties.add('mix-blend-mode'); +allProperties.add('nav-down'); +allProperties.add('nav-left'); +allProperties.add('nav-right'); +allProperties.add('nav-up'); +allProperties.add('object-fit'); +allProperties.add('object-position'); +allProperties.add('offset'); +allProperties.add('offset-after'); +allProperties.add('offset-anchor'); +allProperties.add('offset-before'); +allProperties.add('offset-distance'); +allProperties.add('offset-end'); +allProperties.add('offset-path'); +allProperties.add('offset-position'); +allProperties.add('offset-rotate'); +allProperties.add('offset-start'); +allProperties.add('opacity'); +allProperties.add('order'); +allProperties.add('orphans'); +allProperties.add('outline'); +allProperties.add('outline-color'); +allProperties.add('outline-offset'); +allProperties.add('outline-style'); +allProperties.add('outline-width'); +allProperties.add('overflow'); +allProperties.add('overflow-block'); +allProperties.add('overflow-inline'); +allProperties.add('overflow-wrap'); +allProperties.add('overflow-x'); +allProperties.add('overflow-y'); +allProperties.add('padding'); +allProperties.add('padding-block'); +allProperties.add('padding-block-end'); +allProperties.add('padding-block-start'); +allProperties.add('padding-bottom'); +allProperties.add('padding-inline'); +allProperties.add('padding-inline-end'); +allProperties.add('padding-inline-start'); +allProperties.add('padding-left'); +allProperties.add('padding-right'); +allProperties.add('padding-top'); +allProperties.add('page'); +allProperties.add('page-break-after'); +allProperties.add('page-break-before'); +allProperties.add('page-break-inside'); +allProperties.add('pause'); +allProperties.add('pause-after'); +allProperties.add('pause-before'); +allProperties.add('pitch'); +allProperties.add('pitch-range'); +allProperties.add('place-content'); +allProperties.add('place-items'); +allProperties.add('place-self'); +allProperties.add('play-during'); +allProperties.add('position'); +allProperties.add('presentation-level'); +allProperties.add('quotes'); +allProperties.add('region-fragment'); +allProperties.add('resize'); +allProperties.add('rest'); +allProperties.add('rest-after'); +allProperties.add('rest-before'); +allProperties.add('richness'); +allProperties.add('right'); +allProperties.add('row-gap'); +allProperties.add('ruby-align'); +allProperties.add('ruby-merge'); +allProperties.add('ruby-position'); +allProperties.add('running'); +allProperties.add('scroll-behavior'); +allProperties.add('scroll-margin'); +allProperties.add('scroll-margin-block'); +allProperties.add('scroll-margin-block-end'); +allProperties.add('scroll-margin-block-start'); +allProperties.add('scroll-margin-bottom'); +allProperties.add('scroll-margin-inline'); +allProperties.add('scroll-margin-inline-end'); +allProperties.add('scroll-margin-inline-start'); +allProperties.add('scroll-margin-left'); +allProperties.add('scroll-margin-right'); +allProperties.add('scroll-margin-top'); +allProperties.add('scroll-padding'); +allProperties.add('scroll-padding-block'); +allProperties.add('scroll-padding-block-end'); +allProperties.add('scroll-padding-block-start'); +allProperties.add('scroll-padding-bottom'); +allProperties.add('scroll-padding-inline'); +allProperties.add('scroll-padding-inline-end'); +allProperties.add('scroll-padding-inline-start'); +allProperties.add('scroll-padding-left'); +allProperties.add('scroll-padding-right'); +allProperties.add('scroll-padding-top'); +allProperties.add('scroll-snap-align'); +allProperties.add('scroll-snap-stop'); +allProperties.add('scroll-snap-type'); +allProperties.add('shape-image-threshold'); +allProperties.add('shape-inside'); +allProperties.add('shape-margin'); +allProperties.add('shape-outside'); +allProperties.add('speak'); +allProperties.add('speak-as'); +allProperties.add('speak-header'); +allProperties.add('speak-numeral'); +allProperties.add('speak-punctuation'); +allProperties.add('speech-rate'); +allProperties.add('stress'); +allProperties.add('string-set'); +allProperties.add('tab-size'); +allProperties.add('table-layout'); +allProperties.add('text-align'); +allProperties.add('text-align-all'); +allProperties.add('text-align-last'); +allProperties.add('text-combine-upright'); +allProperties.add('text-decoration'); +allProperties.add('text-decoration-color'); +allProperties.add('text-decoration-line'); +allProperties.add('text-decoration-style'); +allProperties.add('text-emphasis'); +allProperties.add('text-emphasis-color'); +allProperties.add('text-emphasis-position'); +allProperties.add('text-emphasis-style'); +allProperties.add('text-group-align'); +allProperties.add('text-indent'); +allProperties.add('text-justify'); +allProperties.add('text-orientation'); +allProperties.add('text-overflow'); +allProperties.add('text-shadow'); +allProperties.add('text-space-collapse'); +allProperties.add('text-space-trim'); +allProperties.add('text-spacing'); +allProperties.add('text-transform'); +allProperties.add('text-underline-position'); +allProperties.add('text-wrap'); +allProperties.add('top'); +allProperties.add('transform'); +allProperties.add('transform-box'); +allProperties.add('transform-origin'); +allProperties.add('transition'); +allProperties.add('transition-delay'); +allProperties.add('transition-duration'); +allProperties.add('transition-property'); +allProperties.add('transition-timing-function'); +allProperties.add('unicode-bidi'); +allProperties.add('user-select'); +allProperties.add('vertical-align'); +allProperties.add('visibility'); +allProperties.add('voice-balance'); +allProperties.add('voice-duration'); +allProperties.add('voice-family'); +allProperties.add('voice-pitch'); +allProperties.add('voice-range'); +allProperties.add('voice-rate'); +allProperties.add('voice-stress'); +allProperties.add('voice-volume'); +allProperties.add('volume'); +allProperties.add('white-space'); +allProperties.add('widows'); +allProperties.add('width'); +allProperties.add('will-change'); +allProperties.add('word-break'); +allProperties.add('word-spacing'); +allProperties.add('word-wrap'); +allProperties.add('wrap-after'); +allProperties.add('wrap-before'); +allProperties.add('wrap-flow'); +allProperties.add('wrap-inside'); +allProperties.add('wrap-through'); +allProperties.add('writing-mode'); +allProperties.add('z-index'); diff --git a/node_modules/cssstyle/lib/constants.js b/node_modules/cssstyle/lib/constants.js new file mode 100644 index 0000000..1b58869 --- /dev/null +++ b/node_modules/cssstyle/lib/constants.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports.POSITION_AT_SHORTHAND = { + first: 0, + second: 1, +}; diff --git a/node_modules/cssstyle/lib/implementedProperties.js b/node_modules/cssstyle/lib/implementedProperties.js new file mode 100644 index 0000000..edc6f5b --- /dev/null +++ b/node_modules/cssstyle/lib/implementedProperties.js @@ -0,0 +1,90 @@ +'use strict'; + +// autogenerated - 3/27/2019 + +/* + * + * https://www.w3.org/Style/CSS/all-properties.en.html + */ + +var implementedProperties = new Set(); +implementedProperties.add("azimuth"); +implementedProperties.add("background"); +implementedProperties.add("background-attachment"); +implementedProperties.add("background-color"); +implementedProperties.add("background-image"); +implementedProperties.add("background-position"); +implementedProperties.add("background-repeat"); +implementedProperties.add("border"); +implementedProperties.add("border-bottom"); +implementedProperties.add("border-bottom-color"); +implementedProperties.add("border-bottom-style"); +implementedProperties.add("border-bottom-width"); +implementedProperties.add("border-collapse"); +implementedProperties.add("border-color"); +implementedProperties.add("border-left"); +implementedProperties.add("border-left-color"); +implementedProperties.add("border-left-style"); +implementedProperties.add("border-left-width"); +implementedProperties.add("border-right"); +implementedProperties.add("border-right-color"); +implementedProperties.add("border-right-style"); +implementedProperties.add("border-right-width"); +implementedProperties.add("border-spacing"); +implementedProperties.add("border-style"); +implementedProperties.add("border-top"); +implementedProperties.add("border-top-color"); +implementedProperties.add("border-top-style"); +implementedProperties.add("border-top-width"); +implementedProperties.add("border-width"); +implementedProperties.add("bottom"); +implementedProperties.add("clear"); +implementedProperties.add("clip"); +implementedProperties.add("color"); +implementedProperties.add("css-float"); +implementedProperties.add("flex"); +implementedProperties.add("flex-basis"); +implementedProperties.add("flex-grow"); +implementedProperties.add("flex-shrink"); +implementedProperties.add("float"); +implementedProperties.add("flood-color"); +implementedProperties.add("font"); +implementedProperties.add("font-family"); +implementedProperties.add("font-size"); +implementedProperties.add("font-style"); +implementedProperties.add("font-variant"); +implementedProperties.add("font-weight"); +implementedProperties.add("height"); +implementedProperties.add("left"); +implementedProperties.add("lighting-color"); +implementedProperties.add("line-height"); +implementedProperties.add("margin"); +implementedProperties.add("margin-bottom"); +implementedProperties.add("margin-left"); +implementedProperties.add("margin-right"); +implementedProperties.add("margin-top"); +implementedProperties.add("opacity"); +implementedProperties.add("outline-color"); +implementedProperties.add("padding"); +implementedProperties.add("padding-bottom"); +implementedProperties.add("padding-left"); +implementedProperties.add("padding-right"); +implementedProperties.add("padding-top"); +implementedProperties.add("right"); +implementedProperties.add("stop-color"); +implementedProperties.add("text-line-through-color"); +implementedProperties.add("text-overline-color"); +implementedProperties.add("text-underline-color"); +implementedProperties.add("top"); +implementedProperties.add("webkit-border-after-color"); +implementedProperties.add("webkit-border-before-color"); +implementedProperties.add("webkit-border-end-color"); +implementedProperties.add("webkit-border-start-color"); +implementedProperties.add("webkit-column-rule-color"); +implementedProperties.add("webkit-match-nearest-mail-blockquote-color"); +implementedProperties.add("webkit-tap-highlight-color"); +implementedProperties.add("webkit-text-emphasis-color"); +implementedProperties.add("webkit-text-fill-color"); +implementedProperties.add("webkit-text-stroke-color"); +implementedProperties.add("width"); +module.exports = implementedProperties; diff --git a/node_modules/cssstyle/lib/named_colors.json b/node_modules/cssstyle/lib/named_colors.json new file mode 100644 index 0000000..63667a5 --- /dev/null +++ b/node_modules/cssstyle/lib/named_colors.json @@ -0,0 +1,152 @@ +[ + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgreen", + "darkgrey", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "green", + "greenyellow", + "grey", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgreen", + "lightgrey", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "rebeccapurple", + "red", + "rosybrown", + "royalblue", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen", + "transparent", + "currentcolor" +] diff --git a/node_modules/cssstyle/lib/parsers.js b/node_modules/cssstyle/lib/parsers.js new file mode 100644 index 0000000..24021ba --- /dev/null +++ b/node_modules/cssstyle/lib/parsers.js @@ -0,0 +1,697 @@ +/********************************************************************* + * These are commonly used parsers for CSS Values they take a string * + * to parse and return a string after it's been converted, if needed * + ********************************************************************/ +'use strict'; + +const namedColors = require('./named_colors.json'); + +exports.TYPES = { + INTEGER: 1, + NUMBER: 2, + LENGTH: 3, + PERCENT: 4, + URL: 5, + COLOR: 6, + STRING: 7, + ANGLE: 8, + KEYWORD: 9, + NULL_OR_EMPTY_STR: 10, +}; + +// rough regular expressions +var integerRegEx = /^[-+]?[0-9]+$/; +var numberRegEx = /^[-+]?[0-9]*\.[0-9]+$/; +var lengthRegEx = /^(0|[-+]?[0-9]*\.?[0-9]+(in|cm|em|mm|pt|pc|px|ex|rem|vh|vw))$/; +var percentRegEx = /^[-+]?[0-9]*\.?[0-9]+%$/; +var urlRegEx = /^url\(\s*([^)]*)\s*\)$/; +var stringRegEx = /^("[^"]*"|'[^']*')$/; +var colorRegEx1 = /^#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])?$/; +var colorRegEx2 = /^rgb\(([^)]*)\)$/; +var colorRegEx3 = /^rgba\(([^)]*)\)$/; +var colorRegEx4 = /^hsla?\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*(,\s*(-?\d+|-?\d*.\d+)\s*)?\)/; +var angleRegEx = /^([-+]?[0-9]*\.?[0-9]+)(deg|grad|rad)$/; + +// This will return one of the above types based on the passed in string +exports.valueType = function valueType(val) { + if (val === '' || val === null) { + return exports.TYPES.NULL_OR_EMPTY_STR; + } + if (typeof val === 'number') { + val = val.toString(); + } + + if (typeof val !== 'string') { + return undefined; + } + + if (integerRegEx.test(val)) { + return exports.TYPES.INTEGER; + } + if (numberRegEx.test(val)) { + return exports.TYPES.NUMBER; + } + if (lengthRegEx.test(val)) { + return exports.TYPES.LENGTH; + } + if (percentRegEx.test(val)) { + return exports.TYPES.PERCENT; + } + if (urlRegEx.test(val)) { + return exports.TYPES.URL; + } + if (stringRegEx.test(val)) { + return exports.TYPES.STRING; + } + if (angleRegEx.test(val)) { + return exports.TYPES.ANGLE; + } + if (colorRegEx1.test(val)) { + return exports.TYPES.COLOR; + } + var res = colorRegEx2.exec(val); + var parts; + if (res !== null) { + parts = res[1].split(/\s*,\s*/); + if (parts.length !== 3) { + return undefined; + } + if ( + parts.every(percentRegEx.test.bind(percentRegEx)) || + parts.every(integerRegEx.test.bind(integerRegEx)) + ) { + return exports.TYPES.COLOR; + } + return undefined; + } + res = colorRegEx3.exec(val); + if (res !== null) { + parts = res[1].split(/\s*,\s*/); + if (parts.length !== 4) { + return undefined; + } + if ( + parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx)) || + parts.every(integerRegEx.test.bind(integerRegEx)) + ) { + if (numberRegEx.test(parts[3])) { + return exports.TYPES.COLOR; + } + } + return undefined; + } + + if (colorRegEx4.test(val)) { + return exports.TYPES.COLOR; + } + + // could still be a color, one of the standard keyword colors + val = val.toLowerCase(); + + if (namedColors.includes(val)) { + return exports.TYPES.COLOR; + } + + switch (val) { + // the following are deprecated in CSS3 + case 'activeborder': + case 'activecaption': + case 'appworkspace': + case 'background': + case 'buttonface': + case 'buttonhighlight': + case 'buttonshadow': + case 'buttontext': + case 'captiontext': + case 'graytext': + case 'highlight': + case 'highlighttext': + case 'inactiveborder': + case 'inactivecaption': + case 'inactivecaptiontext': + case 'infobackground': + case 'infotext': + case 'menu': + case 'menutext': + case 'scrollbar': + case 'threeddarkshadow': + case 'threedface': + case 'threedhighlight': + case 'threedlightshadow': + case 'threedshadow': + case 'window': + case 'windowframe': + case 'windowtext': + return exports.TYPES.COLOR; + default: + return exports.TYPES.KEYWORD; + } +}; + +exports.parseInteger = function parseInteger(val) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.INTEGER) { + return undefined; + } + return String(parseInt(val, 10)); +}; + +exports.parseNumber = function parseNumber(val) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.NUMBER && type !== exports.TYPES.INTEGER) { + return undefined; + } + return String(parseFloat(val)); +}; + +exports.parseLength = function parseLength(val) { + if (val === 0 || val === '0') { + return '0px'; + } + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.LENGTH) { + return undefined; + } + return val; +}; + +exports.parsePercent = function parsePercent(val) { + if (val === 0 || val === '0') { + return '0%'; + } + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.PERCENT) { + return undefined; + } + return val; +}; + +// either a length or a percent +exports.parseMeasurement = function parseMeasurement(val) { + var length = exports.parseLength(val); + if (length !== undefined) { + return length; + } + return exports.parsePercent(val); +}; + +exports.parseUrl = function parseUrl(val) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + var res = urlRegEx.exec(val); + // does it match the regex? + if (!res) { + return undefined; + } + var str = res[1]; + // if it starts with single or double quotes, does it end with the same? + if ((str[0] === '"' || str[0] === "'") && str[0] !== str[str.length - 1]) { + return undefined; + } + if (str[0] === '"' || str[0] === "'") { + str = str.substr(1, str.length - 2); + } + + var i; + for (i = 0; i < str.length; i++) { + switch (str[i]) { + case '(': + case ')': + case ' ': + case '\t': + case '\n': + case "'": + case '"': + return undefined; + case '\\': + i++; + break; + } + } + + return 'url(' + str + ')'; +}; + +exports.parseString = function parseString(val) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.STRING) { + return undefined; + } + var i; + for (i = 1; i < val.length - 1; i++) { + switch (val[i]) { + case val[0]: + return undefined; + case '\\': + i++; + while (i < val.length - 1 && /[0-9A-Fa-f]/.test(val[i])) { + i++; + } + break; + } + } + if (i >= val.length) { + return undefined; + } + return val; +}; + +exports.parseColor = function parseColor(val) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + var red, + green, + blue, + hue, + saturation, + lightness, + alpha = 1; + var parts; + var res = colorRegEx1.exec(val); + // is it #aaa or #ababab + if (res) { + var hex = val.substr(1); + if (hex.length === 3) { + hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; + } + red = parseInt(hex.substr(0, 2), 16); + green = parseInt(hex.substr(2, 2), 16); + blue = parseInt(hex.substr(4, 2), 16); + return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; + } + + res = colorRegEx2.exec(val); + if (res) { + parts = res[1].split(/\s*,\s*/); + if (parts.length !== 3) { + return undefined; + } + if (parts.every(percentRegEx.test.bind(percentRegEx))) { + red = Math.floor((parseFloat(parts[0].slice(0, -1)) * 255) / 100); + green = Math.floor((parseFloat(parts[1].slice(0, -1)) * 255) / 100); + blue = Math.floor((parseFloat(parts[2].slice(0, -1)) * 255) / 100); + } else if (parts.every(integerRegEx.test.bind(integerRegEx))) { + red = parseInt(parts[0], 10); + green = parseInt(parts[1], 10); + blue = parseInt(parts[2], 10); + } else { + return undefined; + } + red = Math.min(255, Math.max(0, red)); + green = Math.min(255, Math.max(0, green)); + blue = Math.min(255, Math.max(0, blue)); + return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; + } + + res = colorRegEx3.exec(val); + if (res) { + parts = res[1].split(/\s*,\s*/); + if (parts.length !== 4) { + return undefined; + } + if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx))) { + red = Math.floor((parseFloat(parts[0].slice(0, -1)) * 255) / 100); + green = Math.floor((parseFloat(parts[1].slice(0, -1)) * 255) / 100); + blue = Math.floor((parseFloat(parts[2].slice(0, -1)) * 255) / 100); + alpha = parseFloat(parts[3]); + } else if (parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx))) { + red = parseInt(parts[0], 10); + green = parseInt(parts[1], 10); + blue = parseInt(parts[2], 10); + alpha = parseFloat(parts[3]); + } else { + return undefined; + } + if (isNaN(alpha)) { + alpha = 1; + } + red = Math.min(255, Math.max(0, red)); + green = Math.min(255, Math.max(0, green)); + blue = Math.min(255, Math.max(0, blue)); + alpha = Math.min(1, Math.max(0, alpha)); + if (alpha === 1) { + return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; + } + return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')'; + } + + res = colorRegEx4.exec(val); + if (res) { + const [, _hue, _saturation, _lightness, _alphaString = ''] = res; + const _alpha = parseFloat(_alphaString.replace(',', '').trim()); + if (!_hue || !_saturation || !_lightness) { + return undefined; + } + hue = parseFloat(_hue); + saturation = parseInt(_saturation, 10); + lightness = parseInt(_lightness, 10); + if (_alpha && numberRegEx.test(_alpha)) { + alpha = parseFloat(_alpha); + } + if (!_alphaString || alpha === 1) { + return 'hsl(' + hue + ', ' + saturation + '%, ' + lightness + '%)'; + } + return 'hsla(' + hue + ', ' + saturation + '%, ' + lightness + '%, ' + alpha + ')'; + } + + if (type === exports.TYPES.COLOR) { + return val; + } + return undefined; +}; + +exports.parseAngle = function parseAngle(val) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.ANGLE) { + return undefined; + } + var res = angleRegEx.exec(val); + var flt = parseFloat(res[1]); + if (res[2] === 'rad') { + flt *= 180 / Math.PI; + } else if (res[2] === 'grad') { + flt *= 360 / 400; + } + + while (flt < 0) { + flt += 360; + } + while (flt > 360) { + flt -= 360; + } + return flt + 'deg'; +}; + +exports.parseKeyword = function parseKeyword(val, valid_keywords) { + var type = exports.valueType(val); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + return val; + } + if (type !== exports.TYPES.KEYWORD) { + return undefined; + } + val = val.toString().toLowerCase(); + var i; + for (i = 0; i < valid_keywords.length; i++) { + if (valid_keywords[i].toLowerCase() === val) { + return valid_keywords[i]; + } + } + return undefined; +}; + +// utility to translate from border-width to borderWidth +var dashedToCamelCase = function(dashed) { + var i; + var camel = ''; + var nextCap = false; + for (i = 0; i < dashed.length; i++) { + if (dashed[i] !== '-') { + camel += nextCap ? dashed[i].toUpperCase() : dashed[i]; + nextCap = false; + } else { + nextCap = true; + } + } + return camel; +}; +exports.dashedToCamelCase = dashedToCamelCase; + +var is_space = /\s/; +var opening_deliminators = ['"', "'", '(']; +var closing_deliminators = ['"', "'", ')']; +// this splits on whitespace, but keeps quoted and parened parts together +var getParts = function(str) { + var deliminator_stack = []; + var length = str.length; + var i; + var parts = []; + var current_part = ''; + var opening_index; + var closing_index; + for (i = 0; i < length; i++) { + opening_index = opening_deliminators.indexOf(str[i]); + closing_index = closing_deliminators.indexOf(str[i]); + if (is_space.test(str[i])) { + if (deliminator_stack.length === 0) { + if (current_part !== '') { + parts.push(current_part); + } + current_part = ''; + } else { + current_part += str[i]; + } + } else { + if (str[i] === '\\') { + i++; + current_part += str[i]; + } else { + current_part += str[i]; + if ( + closing_index !== -1 && + closing_index === deliminator_stack[deliminator_stack.length - 1] + ) { + deliminator_stack.pop(); + } else if (opening_index !== -1) { + deliminator_stack.push(opening_index); + } + } + } + } + if (current_part !== '') { + parts.push(current_part); + } + return parts; +}; + +/* + * this either returns undefined meaning that it isn't valid + * or returns an object where the keys are dashed short + * hand properties and the values are the values to set + * on them + */ +exports.shorthandParser = function parse(v, shorthand_for) { + var obj = {}; + var type = exports.valueType(v); + if (type === exports.TYPES.NULL_OR_EMPTY_STR) { + Object.keys(shorthand_for).forEach(function(property) { + obj[property] = ''; + }); + return obj; + } + + if (typeof v === 'number') { + v = v.toString(); + } + + if (typeof v !== 'string') { + return undefined; + } + + if (v.toLowerCase() === 'inherit') { + return {}; + } + var parts = getParts(v); + var valid = true; + parts.forEach(function(part, i) { + var part_valid = false; + Object.keys(shorthand_for).forEach(function(property) { + if (shorthand_for[property].isValid(part, i)) { + part_valid = true; + obj[property] = part; + } + }); + valid = valid && part_valid; + }); + if (!valid) { + return undefined; + } + return obj; +}; + +exports.shorthandSetter = function(property, shorthand_for) { + return function(v) { + var obj = exports.shorthandParser(v, shorthand_for); + if (obj === undefined) { + return; + } + //console.log('shorthandSetter for:', property, 'obj:', obj); + Object.keys(obj).forEach(function(subprop) { + // in case subprop is an implicit property, this will clear + // *its* subpropertiesX + var camel = dashedToCamelCase(subprop); + this[camel] = obj[subprop]; + // in case it gets translated into something else (0 -> 0px) + obj[subprop] = this[camel]; + this.removeProperty(subprop); + // don't add in empty properties + if (obj[subprop] !== '') { + this._values[subprop] = obj[subprop]; + } + }, this); + Object.keys(shorthand_for).forEach(function(subprop) { + if (!obj.hasOwnProperty(subprop)) { + this.removeProperty(subprop); + delete this._values[subprop]; + } + }, this); + // in case the value is something like 'none' that removes all values, + // check that the generated one is not empty, first remove the property + // if it already exists, then call the shorthandGetter, if it's an empty + // string, don't set the property + this.removeProperty(property); + var calculated = exports.shorthandGetter(property, shorthand_for).call(this); + if (calculated !== '') { + this._setProperty(property, calculated); + } + }; +}; + +exports.shorthandGetter = function(property, shorthand_for) { + return function() { + if (this._values[property] !== undefined) { + return this.getPropertyValue(property); + } + return Object.keys(shorthand_for) + .map(function(subprop) { + return this.getPropertyValue(subprop); + }, this) + .filter(function(value) { + return value !== ''; + }) + .join(' '); + }; +}; + +// isValid(){1,4} | inherit +// if one, it applies to all +// if two, the first applies to the top and bottom, and the second to left and right +// if three, the first applies to the top, the second to left and right, the third bottom +// if four, top, right, bottom, left +exports.implicitSetter = function(property_before, property_after, isValid, parser) { + property_after = property_after || ''; + if (property_after !== '') { + property_after = '-' + property_after; + } + var part_names = ['top', 'right', 'bottom', 'left']; + + return function(v) { + if (typeof v === 'number') { + v = v.toString(); + } + if (typeof v !== 'string') { + return undefined; + } + var parts; + if (v.toLowerCase() === 'inherit' || v === '') { + parts = [v]; + } else { + parts = getParts(v); + } + if (parts.length < 1 || parts.length > 4) { + return undefined; + } + + if (!parts.every(isValid)) { + return undefined; + } + + parts = parts.map(function(part) { + return parser(part); + }); + this._setProperty(property_before + property_after, parts.join(' ')); + if (parts.length === 1) { + parts[1] = parts[0]; + } + if (parts.length === 2) { + parts[2] = parts[0]; + } + if (parts.length === 3) { + parts[3] = parts[1]; + } + + for (var i = 0; i < 4; i++) { + var property = property_before + '-' + part_names[i] + property_after; + this.removeProperty(property); + if (parts[i] !== '') { + this._values[property] = parts[i]; + } + } + return v; + }; +}; + +// +// Companion to implicitSetter, but for the individual parts. +// This sets the individual value, and checks to see if all four +// sub-parts are set. If so, it sets the shorthand version and removes +// the individual parts from the cssText. +// +exports.subImplicitSetter = function(prefix, part, isValid, parser) { + var property = prefix + '-' + part; + var subparts = [prefix + '-top', prefix + '-right', prefix + '-bottom', prefix + '-left']; + + return function(v) { + if (typeof v === 'number') { + v = v.toString(); + } + if (typeof v !== 'string') { + return undefined; + } + if (!isValid(v)) { + return undefined; + } + v = parser(v); + this._setProperty(property, v); + var parts = []; + for (var i = 0; i < 4; i++) { + if (this._values[subparts[i]] == null || this._values[subparts[i]] === '') { + break; + } + parts.push(this._values[subparts[i]]); + } + if (parts.length === 4) { + for (i = 0; i < 4; i++) { + this.removeProperty(subparts[i]); + this._values[subparts[i]] = parts[i]; + } + this._setProperty(prefix, parts.join(' ')); + } + return v; + }; +}; + +var camel_to_dashed = /[A-Z]/g; +var first_segment = /^\([^-]\)-/; +var vendor_prefixes = ['o', 'moz', 'ms', 'webkit']; +exports.camelToDashed = function(camel_case) { + var match; + var dashed = camel_case.replace(camel_to_dashed, '-$&').toLowerCase(); + match = dashed.match(first_segment); + if (match && vendor_prefixes.indexOf(match[1]) !== -1) { + dashed = '-' + dashed; + } + return dashed; +}; diff --git a/node_modules/cssstyle/lib/properties.js b/node_modules/cssstyle/lib/properties.js new file mode 100644 index 0000000..2c3c9e9 --- /dev/null +++ b/node_modules/cssstyle/lib/properties.js @@ -0,0 +1,1826 @@ +'use strict'; + +// autogenerated - 3/27/2019 + +/* + * + * https://www.w3.org/Style/CSS/all-properties.en.html + */ + +var external_dependency_parsers_0 = require("./parsers.js"); + +var external_dependency_constants_1 = require("./constants.js"); + +var azimuth_export_definition; +azimuth_export_definition = { + set: function (v) { + var valueType = external_dependency_parsers_0.valueType(v); + + if (valueType === external_dependency_parsers_0.TYPES.ANGLE) { + return this._setProperty('azimuth', external_dependency_parsers_0.parseAngle(v)); + } + + if (valueType === external_dependency_parsers_0.TYPES.KEYWORD) { + var keywords = v.toLowerCase().trim().split(/\s+/); + var hasBehind = false; + + if (keywords.length > 2) { + return; + } + + var behindIndex = keywords.indexOf('behind'); + hasBehind = behindIndex !== -1; + + if (keywords.length === 2) { + if (!hasBehind) { + return; + } + + keywords.splice(behindIndex, 1); + } + + if (keywords[0] === 'leftwards' || keywords[0] === 'rightwards') { + if (hasBehind) { + return; + } + + return this._setProperty('azimuth', keywords[0]); + } + + if (keywords[0] === 'behind') { + return this._setProperty('azimuth', '180deg'); + } + + switch (keywords[0]) { + case 'left-side': + return this._setProperty('azimuth', '270deg'); + + case 'far-left': + return this._setProperty('azimuth', (hasBehind ? 240 : 300) + 'deg'); + + case 'left': + return this._setProperty('azimuth', (hasBehind ? 220 : 320) + 'deg'); + + case 'center-left': + return this._setProperty('azimuth', (hasBehind ? 200 : 340) + 'deg'); + + case 'center': + return this._setProperty('azimuth', (hasBehind ? 180 : 0) + 'deg'); + + case 'center-right': + return this._setProperty('azimuth', (hasBehind ? 160 : 20) + 'deg'); + + case 'right': + return this._setProperty('azimuth', (hasBehind ? 140 : 40) + 'deg'); + + case 'far-right': + return this._setProperty('azimuth', (hasBehind ? 120 : 60) + 'deg'); + + case 'right-side': + return this._setProperty('azimuth', '90deg'); + + default: + return; + } + } + }, + get: function () { + return this.getPropertyValue('azimuth'); + }, + enumerable: true, + configurable: true +}; +var backgroundColor_export_isValid, backgroundColor_export_definition; + +var backgroundColor_local_var_parse = function parse(v) { + var parsed = external_dependency_parsers_0.parseColor(v); + + if (parsed !== undefined) { + return parsed; + } + + if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'transparent' || v.toLowerCase() === 'inherit')) { + return v; + } + + return undefined; +}; + +backgroundColor_export_isValid = function isValid(v) { + return backgroundColor_local_var_parse(v) !== undefined; +}; + +backgroundColor_export_definition = { + set: function (v) { + var parsed = backgroundColor_local_var_parse(v); + + if (parsed === undefined) { + return; + } + + this._setProperty('background-color', parsed); + }, + get: function () { + return this.getPropertyValue('background-color'); + }, + enumerable: true, + configurable: true +}; +var backgroundImage_export_isValid, backgroundImage_export_definition; + +var backgroundImage_local_var_parse = function parse(v) { + var parsed = external_dependency_parsers_0.parseUrl(v); + + if (parsed !== undefined) { + return parsed; + } + + if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'none' || v.toLowerCase() === 'inherit')) { + return v; + } + + return undefined; +}; + +backgroundImage_export_isValid = function isValid(v) { + return backgroundImage_local_var_parse(v) !== undefined; +}; + +backgroundImage_export_definition = { + set: function (v) { + this._setProperty('background-image', backgroundImage_local_var_parse(v)); + }, + get: function () { + return this.getPropertyValue('background-image'); + }, + enumerable: true, + configurable: true +}; +var backgroundRepeat_export_isValid, backgroundRepeat_export_definition; + +var backgroundRepeat_local_var_parse = function parse(v) { + if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'repeat' || v.toLowerCase() === 'repeat-x' || v.toLowerCase() === 'repeat-y' || v.toLowerCase() === 'no-repeat' || v.toLowerCase() === 'inherit')) { + return v; + } + + return undefined; +}; + +backgroundRepeat_export_isValid = function isValid(v) { + return backgroundRepeat_local_var_parse(v) !== undefined; +}; + +backgroundRepeat_export_definition = { + set: function (v) { + this._setProperty('background-repeat', backgroundRepeat_local_var_parse(v)); + }, + get: function () { + return this.getPropertyValue('background-repeat'); + }, + enumerable: true, + configurable: true +}; +var backgroundAttachment_export_isValid, backgroundAttachment_export_definition; + +var backgroundAttachment_local_var_isValid = backgroundAttachment_export_isValid = function isValid(v) { + return external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'scroll' || v.toLowerCase() === 'fixed' || v.toLowerCase() === 'inherit'); +}; + +backgroundAttachment_export_definition = { + set: function (v) { + if (!backgroundAttachment_local_var_isValid(v)) { + return; + } + + this._setProperty('background-attachment', v); + }, + get: function () { + return this.getPropertyValue('background-attachment'); + }, + enumerable: true, + configurable: true +}; +var backgroundPosition_export_isValid, backgroundPosition_export_definition; +var backgroundPosition_local_var_valid_keywords = ['top', 'center', 'bottom', 'left', 'right']; + +var backgroundPosition_local_var_parse = function parse(v) { + if (v === '' || v === null) { + return undefined; + } + + var parts = v.split(/\s+/); + + if (parts.length > 2 || parts.length < 1) { + return undefined; + } + + var types = []; + parts.forEach(function (part, index) { + types[index] = external_dependency_parsers_0.valueType(part); + }); + + if (parts.length === 1) { + if (types[0] === external_dependency_parsers_0.TYPES.LENGTH || types[0] === external_dependency_parsers_0.TYPES.PERCENT) { + return v; + } + + if (types[0] === external_dependency_parsers_0.TYPES.KEYWORD) { + if (backgroundPosition_local_var_valid_keywords.indexOf(v.toLowerCase()) !== -1 || v.toLowerCase() === 'inherit') { + return v; + } + } + + return undefined; + } + + if ((types[0] === external_dependency_parsers_0.TYPES.LENGTH || types[0] === external_dependency_parsers_0.TYPES.PERCENT) && (types[1] === external_dependency_parsers_0.TYPES.LENGTH || types[1] === external_dependency_parsers_0.TYPES.PERCENT)) { + return v; + } + + if (types[0] !== external_dependency_parsers_0.TYPES.KEYWORD || types[1] !== external_dependency_parsers_0.TYPES.KEYWORD) { + return undefined; + } + + if (backgroundPosition_local_var_valid_keywords.indexOf(parts[0]) !== -1 && backgroundPosition_local_var_valid_keywords.indexOf(parts[1]) !== -1) { + return v; + } + + return undefined; +}; + +backgroundPosition_export_isValid = function isValid(v) { + return backgroundPosition_local_var_parse(v) !== undefined; +}; + +backgroundPosition_export_definition = { + set: function (v) { + this._setProperty('background-position', backgroundPosition_local_var_parse(v)); + }, + get: function () { + return this.getPropertyValue('background-position'); + }, + enumerable: true, + configurable: true +}; +var background_export_definition; +var background_local_var_shorthand_for = { + 'background-color': { + isValid: backgroundColor_export_isValid, + definition: backgroundColor_export_definition + }, + 'background-image': { + isValid: backgroundImage_export_isValid, + definition: backgroundImage_export_definition + }, + 'background-repeat': { + isValid: backgroundRepeat_export_isValid, + definition: backgroundRepeat_export_definition + }, + 'background-attachment': { + isValid: backgroundAttachment_export_isValid, + definition: backgroundAttachment_export_definition + }, + 'background-position': { + isValid: backgroundPosition_export_isValid, + definition: backgroundPosition_export_definition + } +}; +background_export_definition = { + set: external_dependency_parsers_0.shorthandSetter('background', background_local_var_shorthand_for), + get: external_dependency_parsers_0.shorthandGetter('background', background_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var borderWidth_export_isValid, borderWidth_export_definition; +// the valid border-widths: +var borderWidth_local_var_widths = ['thin', 'medium', 'thick']; + +borderWidth_export_isValid = function parse(v) { + var length = external_dependency_parsers_0.parseLength(v); + + if (length !== undefined) { + return true; + } + + if (typeof v !== 'string') { + return false; + } + + if (v === '') { + return true; + } + + v = v.toLowerCase(); + + if (borderWidth_local_var_widths.indexOf(v) === -1) { + return false; + } + + return true; +}; + +var borderWidth_local_var_isValid = borderWidth_export_isValid; + +var borderWidth_local_var_parser = function (v) { + var length = external_dependency_parsers_0.parseLength(v); + + if (length !== undefined) { + return length; + } + + if (borderWidth_local_var_isValid(v)) { + return v.toLowerCase(); + } + + return undefined; +}; + +borderWidth_export_definition = { + set: external_dependency_parsers_0.implicitSetter('border', 'width', borderWidth_local_var_isValid, borderWidth_local_var_parser), + get: function () { + return this.getPropertyValue('border-width'); + }, + enumerable: true, + configurable: true +}; +var borderStyle_export_isValid, borderStyle_export_definition; +// the valid border-styles: +var borderStyle_local_var_styles = ['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']; + +borderStyle_export_isValid = function parse(v) { + return typeof v === 'string' && (v === '' || borderStyle_local_var_styles.indexOf(v) !== -1); +}; + +var borderStyle_local_var_isValid = borderStyle_export_isValid; + +var borderStyle_local_var_parser = function (v) { + if (borderStyle_local_var_isValid(v)) { + return v.toLowerCase(); + } + + return undefined; +}; + +borderStyle_export_definition = { + set: external_dependency_parsers_0.implicitSetter('border', 'style', borderStyle_local_var_isValid, borderStyle_local_var_parser), + get: function () { + return this.getPropertyValue('border-style'); + }, + enumerable: true, + configurable: true +}; +var borderColor_export_isValid, borderColor_export_definition; + +borderColor_export_isValid = function parse(v) { + if (typeof v !== 'string') { + return false; + } + + return v === '' || v.toLowerCase() === 'transparent' || external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.COLOR; +}; + +var borderColor_local_var_isValid = borderColor_export_isValid; + +var borderColor_local_var_parser = function (v) { + if (borderColor_local_var_isValid(v)) { + return v.toLowerCase(); + } + + return undefined; +}; + +borderColor_export_definition = { + set: external_dependency_parsers_0.implicitSetter('border', 'color', borderColor_local_var_isValid, borderColor_local_var_parser), + get: function () { + return this.getPropertyValue('border-color'); + }, + enumerable: true, + configurable: true +}; +var border_export_definition; +var border_local_var_shorthand_for = { + 'border-width': { + isValid: borderWidth_export_isValid, + definition: borderWidth_export_definition + }, + 'border-style': { + isValid: borderStyle_export_isValid, + definition: borderStyle_export_definition + }, + 'border-color': { + isValid: borderColor_export_isValid, + definition: borderColor_export_definition + } +}; +var border_local_var_myShorthandSetter = external_dependency_parsers_0.shorthandSetter('border', border_local_var_shorthand_for); +var border_local_var_myShorthandGetter = external_dependency_parsers_0.shorthandGetter('border', border_local_var_shorthand_for); +border_export_definition = { + set: function (v) { + if (v.toString().toLowerCase() === 'none') { + v = ''; + } + + border_local_var_myShorthandSetter.call(this, v); + this.removeProperty('border-top'); + this.removeProperty('border-left'); + this.removeProperty('border-right'); + this.removeProperty('border-bottom'); + this._values['border-top'] = this._values.border; + this._values['border-left'] = this._values.border; + this._values['border-right'] = this._values.border; + this._values['border-bottom'] = this._values.border; + }, + get: border_local_var_myShorthandGetter, + enumerable: true, + configurable: true +}; +var borderBottomWidth_export_isValid, borderBottomWidth_export_definition; +var borderBottomWidth_local_var_isValid = borderBottomWidth_export_isValid = borderWidth_export_isValid; +borderBottomWidth_export_definition = { + set: function (v) { + if (borderBottomWidth_local_var_isValid(v)) { + this._setProperty('border-bottom-width', v); + } + }, + get: function () { + return this.getPropertyValue('border-bottom-width'); + }, + enumerable: true, + configurable: true +}; +var borderBottomStyle_export_isValid, borderBottomStyle_export_definition; +borderBottomStyle_export_isValid = borderStyle_export_isValid; +borderBottomStyle_export_definition = { + set: function (v) { + if (borderStyle_export_isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-bottom-width'); + } + + this._setProperty('border-bottom-style', v); + } + }, + get: function () { + return this.getPropertyValue('border-bottom-style'); + }, + enumerable: true, + configurable: true +}; +var borderBottomColor_export_isValid, borderBottomColor_export_definition; +var borderBottomColor_local_var_isValid = borderBottomColor_export_isValid = borderColor_export_isValid; +borderBottomColor_export_definition = { + set: function (v) { + if (borderBottomColor_local_var_isValid(v)) { + this._setProperty('border-bottom-color', v); + } + }, + get: function () { + return this.getPropertyValue('border-bottom-color'); + }, + enumerable: true, + configurable: true +}; +var borderBottom_export_definition; +var borderBottom_local_var_shorthand_for = { + 'border-bottom-width': { + isValid: borderBottomWidth_export_isValid, + definition: borderBottomWidth_export_definition + }, + 'border-bottom-style': { + isValid: borderBottomStyle_export_isValid, + definition: borderBottomStyle_export_definition + }, + 'border-bottom-color': { + isValid: borderBottomColor_export_isValid, + definition: borderBottomColor_export_definition + } +}; +borderBottom_export_definition = { + set: external_dependency_parsers_0.shorthandSetter('border-bottom', borderBottom_local_var_shorthand_for), + get: external_dependency_parsers_0.shorthandGetter('border-bottom', borderBottom_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var borderCollapse_export_definition; + +var borderCollapse_local_var_parse = function parse(v) { + if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'collapse' || v.toLowerCase() === 'separate' || v.toLowerCase() === 'inherit')) { + return v; + } + + return undefined; +}; + +borderCollapse_export_definition = { + set: function (v) { + this._setProperty('border-collapse', borderCollapse_local_var_parse(v)); + }, + get: function () { + return this.getPropertyValue('border-collapse'); + }, + enumerable: true, + configurable: true +}; +var borderLeftWidth_export_isValid, borderLeftWidth_export_definition; +var borderLeftWidth_local_var_isValid = borderLeftWidth_export_isValid = borderWidth_export_isValid; +borderLeftWidth_export_definition = { + set: function (v) { + if (borderLeftWidth_local_var_isValid(v)) { + this._setProperty('border-left-width', v); + } + }, + get: function () { + return this.getPropertyValue('border-left-width'); + }, + enumerable: true, + configurable: true +}; +var borderLeftStyle_export_isValid, borderLeftStyle_export_definition; +borderLeftStyle_export_isValid = borderStyle_export_isValid; +borderLeftStyle_export_definition = { + set: function (v) { + if (borderStyle_export_isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-left-width'); + } + + this._setProperty('border-left-style', v); + } + }, + get: function () { + return this.getPropertyValue('border-left-style'); + }, + enumerable: true, + configurable: true +}; +var borderLeftColor_export_isValid, borderLeftColor_export_definition; +var borderLeftColor_local_var_isValid = borderLeftColor_export_isValid = borderColor_export_isValid; +borderLeftColor_export_definition = { + set: function (v) { + if (borderLeftColor_local_var_isValid(v)) { + this._setProperty('border-left-color', v); + } + }, + get: function () { + return this.getPropertyValue('border-left-color'); + }, + enumerable: true, + configurable: true +}; +var borderLeft_export_definition; +var borderLeft_local_var_shorthand_for = { + 'border-left-width': { + isValid: borderLeftWidth_export_isValid, + definition: borderLeftWidth_export_definition + }, + 'border-left-style': { + isValid: borderLeftStyle_export_isValid, + definition: borderLeftStyle_export_definition + }, + 'border-left-color': { + isValid: borderLeftColor_export_isValid, + definition: borderLeftColor_export_definition + } +}; +borderLeft_export_definition = { + set: external_dependency_parsers_0.shorthandSetter('border-left', borderLeft_local_var_shorthand_for), + get: external_dependency_parsers_0.shorthandGetter('border-left', borderLeft_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var borderRightWidth_export_isValid, borderRightWidth_export_definition; +var borderRightWidth_local_var_isValid = borderRightWidth_export_isValid = borderWidth_export_isValid; +borderRightWidth_export_definition = { + set: function (v) { + if (borderRightWidth_local_var_isValid(v)) { + this._setProperty('border-right-width', v); + } + }, + get: function () { + return this.getPropertyValue('border-right-width'); + }, + enumerable: true, + configurable: true +}; +var borderRightStyle_export_isValid, borderRightStyle_export_definition; +borderRightStyle_export_isValid = borderStyle_export_isValid; +borderRightStyle_export_definition = { + set: function (v) { + if (borderStyle_export_isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-right-width'); + } + + this._setProperty('border-right-style', v); + } + }, + get: function () { + return this.getPropertyValue('border-right-style'); + }, + enumerable: true, + configurable: true +}; +var borderRightColor_export_isValid, borderRightColor_export_definition; +var borderRightColor_local_var_isValid = borderRightColor_export_isValid = borderColor_export_isValid; +borderRightColor_export_definition = { + set: function (v) { + if (borderRightColor_local_var_isValid(v)) { + this._setProperty('border-right-color', v); + } + }, + get: function () { + return this.getPropertyValue('border-right-color'); + }, + enumerable: true, + configurable: true +}; +var borderRight_export_definition; +var borderRight_local_var_shorthand_for = { + 'border-right-width': { + isValid: borderRightWidth_export_isValid, + definition: borderRightWidth_export_definition + }, + 'border-right-style': { + isValid: borderRightStyle_export_isValid, + definition: borderRightStyle_export_definition + }, + 'border-right-color': { + isValid: borderRightColor_export_isValid, + definition: borderRightColor_export_definition + } +}; +borderRight_export_definition = { + set: external_dependency_parsers_0.shorthandSetter('border-right', borderRight_local_var_shorthand_for), + get: external_dependency_parsers_0.shorthandGetter('border-right', borderRight_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var borderSpacing_export_definition; + +// ? | inherit +// if one, it applies to both horizontal and verical spacing +// if two, the first applies to the horizontal and the second applies to vertical spacing +var borderSpacing_local_var_parse = function parse(v) { + if (v === '' || v === null) { + return undefined; + } + + if (v === 0) { + return '0px'; + } + + if (v.toLowerCase() === 'inherit') { + return v; + } + + var parts = v.split(/\s+/); + + if (parts.length !== 1 && parts.length !== 2) { + return undefined; + } + + parts.forEach(function (part) { + if (external_dependency_parsers_0.valueType(part) !== external_dependency_parsers_0.TYPES.LENGTH) { + return undefined; + } + }); + return v; +}; + +borderSpacing_export_definition = { + set: function (v) { + this._setProperty('border-spacing', borderSpacing_local_var_parse(v)); + }, + get: function () { + return this.getPropertyValue('border-spacing'); + }, + enumerable: true, + configurable: true +}; +var borderTopWidth_export_isValid, borderTopWidth_export_definition; +borderTopWidth_export_isValid = borderWidth_export_isValid; +borderTopWidth_export_definition = { + set: function (v) { + if (borderWidth_export_isValid(v)) { + this._setProperty('border-top-width', v); + } + }, + get: function () { + return this.getPropertyValue('border-top-width'); + }, + enumerable: true, + configurable: true +}; +var borderTopStyle_export_isValid, borderTopStyle_export_definition; +borderTopStyle_export_isValid = borderStyle_export_isValid; +borderTopStyle_export_definition = { + set: function (v) { + if (borderStyle_export_isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-top-width'); + } + + this._setProperty('border-top-style', v); + } + }, + get: function () { + return this.getPropertyValue('border-top-style'); + }, + enumerable: true, + configurable: true +}; +var borderTopColor_export_isValid, borderTopColor_export_definition; +var borderTopColor_local_var_isValid = borderTopColor_export_isValid = borderColor_export_isValid; +borderTopColor_export_definition = { + set: function (v) { + if (borderTopColor_local_var_isValid(v)) { + this._setProperty('border-top-color', v); + } + }, + get: function () { + return this.getPropertyValue('border-top-color'); + }, + enumerable: true, + configurable: true +}; +var borderTop_export_definition; +var borderTop_local_var_shorthand_for = { + 'border-top-width': { + isValid: borderTopWidth_export_isValid, + definition: borderTopWidth_export_definition + }, + 'border-top-style': { + isValid: borderTopStyle_export_isValid, + definition: borderTopStyle_export_definition + }, + 'border-top-color': { + isValid: borderTopColor_export_isValid, + definition: borderTopColor_export_definition + } +}; +borderTop_export_definition = { + set: external_dependency_parsers_0.shorthandSetter('border-top', borderTop_local_var_shorthand_for), + get: external_dependency_parsers_0.shorthandGetter('border-top', borderTop_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var bottom_export_definition; +bottom_export_definition = { + set: function (v) { + this._setProperty('bottom', external_dependency_parsers_0.parseMeasurement(v)); + }, + get: function () { + return this.getPropertyValue('bottom'); + }, + enumerable: true, + configurable: true +}; +var clear_export_definition; +var clear_local_var_clear_keywords = ['none', 'left', 'right', 'both', 'inherit']; +clear_export_definition = { + set: function (v) { + this._setProperty('clear', external_dependency_parsers_0.parseKeyword(v, clear_local_var_clear_keywords)); + }, + get: function () { + return this.getPropertyValue('clear'); + }, + enumerable: true, + configurable: true +}; +var clip_export_definition; +var clip_local_var_shape_regex = /^rect\((.*)\)$/i; + +var clip_local_var_parse = function (val) { + if (val === '' || val === null) { + return val; + } + + if (typeof val !== 'string') { + return undefined; + } + + val = val.toLowerCase(); + + if (val === 'auto' || val === 'inherit') { + return val; + } + + var matches = val.match(clip_local_var_shape_regex); + + if (!matches) { + return undefined; + } + + var parts = matches[1].split(/\s*,\s*/); + + if (parts.length !== 4) { + return undefined; + } + + var valid = parts.every(function (part, index) { + var measurement = external_dependency_parsers_0.parseMeasurement(part); + parts[index] = measurement; + return measurement !== undefined; + }); + + if (!valid) { + return undefined; + } + + parts = parts.join(', '); + return val.replace(matches[1], parts); +}; + +clip_export_definition = { + set: function (v) { + this._setProperty('clip', clip_local_var_parse(v)); + }, + get: function () { + return this.getPropertyValue('clip'); + }, + enumerable: true, + configurable: true +}; +var color_export_definition; +color_export_definition = { + set: function (v) { + this._setProperty('color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('color'); + }, + enumerable: true, + configurable: true +}; +var cssFloat_export_definition; +cssFloat_export_definition = { + set: function (v) { + this._setProperty('float', v); + }, + get: function () { + return this.getPropertyValue('float'); + }, + enumerable: true, + configurable: true +}; +var flexGrow_export_isValid, flexGrow_export_definition; + +flexGrow_export_isValid = function isValid(v, positionAtFlexShorthand) { + return external_dependency_parsers_0.parseNumber(v) !== undefined && positionAtFlexShorthand === external_dependency_constants_1.POSITION_AT_SHORTHAND.first; +}; + +flexGrow_export_definition = { + set: function (v) { + this._setProperty('flex-grow', external_dependency_parsers_0.parseNumber(v)); + }, + get: function () { + return this.getPropertyValue('flex-grow'); + }, + enumerable: true, + configurable: true +}; +var flexShrink_export_isValid, flexShrink_export_definition; + +flexShrink_export_isValid = function isValid(v, positionAtFlexShorthand) { + return external_dependency_parsers_0.parseNumber(v) !== undefined && positionAtFlexShorthand === external_dependency_constants_1.POSITION_AT_SHORTHAND.second; +}; + +flexShrink_export_definition = { + set: function (v) { + this._setProperty('flex-shrink', external_dependency_parsers_0.parseNumber(v)); + }, + get: function () { + return this.getPropertyValue('flex-shrink'); + }, + enumerable: true, + configurable: true +}; +var flexBasis_export_isValid, flexBasis_export_definition; + +function flexBasis_local_fn_parse(v) { + if (String(v).toLowerCase() === 'auto') { + return 'auto'; + } + + if (String(v).toLowerCase() === 'inherit') { + return 'inherit'; + } + + return external_dependency_parsers_0.parseMeasurement(v); +} + +flexBasis_export_isValid = function isValid(v) { + return flexBasis_local_fn_parse(v) !== undefined; +}; + +flexBasis_export_definition = { + set: function (v) { + this._setProperty('flex-basis', flexBasis_local_fn_parse(v)); + }, + get: function () { + return this.getPropertyValue('flex-basis'); + }, + enumerable: true, + configurable: true +}; +var flex_export_isValid, flex_export_definition; +var flex_local_var_shorthand_for = { + 'flex-grow': { + isValid: flexGrow_export_isValid, + definition: flexGrow_export_definition + }, + 'flex-shrink': { + isValid: flexShrink_export_isValid, + definition: flexShrink_export_definition + }, + 'flex-basis': { + isValid: flexBasis_export_isValid, + definition: flexBasis_export_definition + } +}; +var flex_local_var_myShorthandSetter = external_dependency_parsers_0.shorthandSetter('flex', flex_local_var_shorthand_for); + +flex_export_isValid = function isValid(v) { + return external_dependency_parsers_0.shorthandParser(v, flex_local_var_shorthand_for) !== undefined; +}; + +flex_export_definition = { + set: function (v) { + var normalizedValue = String(v).trim().toLowerCase(); + + if (normalizedValue === 'none') { + flex_local_var_myShorthandSetter.call(this, '0 0 auto'); + return; + } + + if (normalizedValue === 'initial') { + flex_local_var_myShorthandSetter.call(this, '0 1 auto'); + return; + } + + if (normalizedValue === 'auto') { + this.removeProperty('flex-grow'); + this.removeProperty('flex-shrink'); + this.setProperty('flex-basis', normalizedValue); + return; + } + + flex_local_var_myShorthandSetter.call(this, v); + }, + get: external_dependency_parsers_0.shorthandGetter('flex', flex_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var float_export_definition; +float_export_definition = { + set: function (v) { + this._setProperty('float', v); + }, + get: function () { + return this.getPropertyValue('float'); + }, + enumerable: true, + configurable: true +}; +var floodColor_export_definition; +floodColor_export_definition = { + set: function (v) { + this._setProperty('flood-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('flood-color'); + }, + enumerable: true, + configurable: true +}; +var fontFamily_export_isValid, fontFamily_export_definition; +var fontFamily_local_var_partsRegEx = /\s*,\s*/; + +fontFamily_export_isValid = function isValid(v) { + if (v === '' || v === null) { + return true; + } + + var parts = v.split(fontFamily_local_var_partsRegEx); + var len = parts.length; + var i; + var type; + + for (i = 0; i < len; i++) { + type = external_dependency_parsers_0.valueType(parts[i]); + + if (type === external_dependency_parsers_0.TYPES.STRING || type === external_dependency_parsers_0.TYPES.KEYWORD) { + return true; + } + } + + return false; +}; + +fontFamily_export_definition = { + set: function (v) { + this._setProperty('font-family', v); + }, + get: function () { + return this.getPropertyValue('font-family'); + }, + enumerable: true, + configurable: true +}; +var fontSize_export_isValid, fontSize_export_definition; +var fontSize_local_var_absoluteSizes = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large']; +var fontSize_local_var_relativeSizes = ['larger', 'smaller']; + +fontSize_export_isValid = function (v) { + var type = external_dependency_parsers_0.valueType(v.toLowerCase()); + return type === external_dependency_parsers_0.TYPES.LENGTH || type === external_dependency_parsers_0.TYPES.PERCENT || type === external_dependency_parsers_0.TYPES.KEYWORD && fontSize_local_var_absoluteSizes.indexOf(v.toLowerCase()) !== -1 || type === external_dependency_parsers_0.TYPES.KEYWORD && fontSize_local_var_relativeSizes.indexOf(v.toLowerCase()) !== -1; +}; + +fontSize_export_definition = { + set: function (v) { + this._setProperty('font-size', v); + }, + get: function () { + return this.getPropertyValue('font-size'); + }, + enumerable: true, + configurable: true +}; +var fontStyle_export_isValid, fontStyle_export_definition; +var fontStyle_local_var_valid_styles = ['normal', 'italic', 'oblique', 'inherit']; + +fontStyle_export_isValid = function (v) { + return fontStyle_local_var_valid_styles.indexOf(v.toLowerCase()) !== -1; +}; + +fontStyle_export_definition = { + set: function (v) { + this._setProperty('font-style', v); + }, + get: function () { + return this.getPropertyValue('font-style'); + }, + enumerable: true, + configurable: true +}; +var fontVariant_export_isValid, fontVariant_export_definition; +var fontVariant_local_var_valid_variants = ['normal', 'small-caps', 'inherit']; + +fontVariant_export_isValid = function isValid(v) { + return fontVariant_local_var_valid_variants.indexOf(v.toLowerCase()) !== -1; +}; + +fontVariant_export_definition = { + set: function (v) { + this._setProperty('font-variant', v); + }, + get: function () { + return this.getPropertyValue('font-variant'); + }, + enumerable: true, + configurable: true +}; +var fontWeight_export_isValid, fontWeight_export_definition; +var fontWeight_local_var_valid_weights = ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'inherit']; + +fontWeight_export_isValid = function isValid(v) { + return fontWeight_local_var_valid_weights.indexOf(v.toLowerCase()) !== -1; +}; + +fontWeight_export_definition = { + set: function (v) { + this._setProperty('font-weight', v); + }, + get: function () { + return this.getPropertyValue('font-weight'); + }, + enumerable: true, + configurable: true +}; +var lineHeight_export_isValid, lineHeight_export_definition; + +lineHeight_export_isValid = function isValid(v) { + var type = external_dependency_parsers_0.valueType(v); + return type === external_dependency_parsers_0.TYPES.KEYWORD && v.toLowerCase() === 'normal' || v.toLowerCase() === 'inherit' || type === external_dependency_parsers_0.TYPES.NUMBER || type === external_dependency_parsers_0.TYPES.LENGTH || type === external_dependency_parsers_0.TYPES.PERCENT; +}; + +lineHeight_export_definition = { + set: function (v) { + this._setProperty('line-height', v); + }, + get: function () { + return this.getPropertyValue('line-height'); + }, + enumerable: true, + configurable: true +}; +var font_export_definition; +var font_local_var_shorthand_for = { + 'font-family': { + isValid: fontFamily_export_isValid, + definition: fontFamily_export_definition + }, + 'font-size': { + isValid: fontSize_export_isValid, + definition: fontSize_export_definition + }, + 'font-style': { + isValid: fontStyle_export_isValid, + definition: fontStyle_export_definition + }, + 'font-variant': { + isValid: fontVariant_export_isValid, + definition: fontVariant_export_definition + }, + 'font-weight': { + isValid: fontWeight_export_isValid, + definition: fontWeight_export_definition + }, + 'line-height': { + isValid: lineHeight_export_isValid, + definition: lineHeight_export_definition + } +}; +var font_local_var_static_fonts = ['caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar', 'inherit']; +var font_local_var_setter = external_dependency_parsers_0.shorthandSetter('font', font_local_var_shorthand_for); +font_export_definition = { + set: function (v) { + var short = external_dependency_parsers_0.shorthandParser(v, font_local_var_shorthand_for); + + if (short !== undefined) { + return font_local_var_setter.call(this, v); + } + + if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && font_local_var_static_fonts.indexOf(v.toLowerCase()) !== -1) { + this._setProperty('font', v); + } + }, + get: external_dependency_parsers_0.shorthandGetter('font', font_local_var_shorthand_for), + enumerable: true, + configurable: true +}; +var height_export_definition; + +function height_local_fn_parse(v) { + if (String(v).toLowerCase() === 'auto') { + return 'auto'; + } + + if (String(v).toLowerCase() === 'inherit') { + return 'inherit'; + } + + return external_dependency_parsers_0.parseMeasurement(v); +} + +height_export_definition = { + set: function (v) { + this._setProperty('height', height_local_fn_parse(v)); + }, + get: function () { + return this.getPropertyValue('height'); + }, + enumerable: true, + configurable: true +}; +var left_export_definition; +left_export_definition = { + set: function (v) { + this._setProperty('left', external_dependency_parsers_0.parseMeasurement(v)); + }, + get: function () { + return this.getPropertyValue('left'); + }, + enumerable: true, + configurable: true +}; +var lightingColor_export_definition; +lightingColor_export_definition = { + set: function (v) { + this._setProperty('lighting-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('lighting-color'); + }, + enumerable: true, + configurable: true +}; +var margin_export_definition, margin_export_isValid, margin_export_parser; +var margin_local_var_TYPES = external_dependency_parsers_0.TYPES; + +var margin_local_var_isValid = function (v) { + if (v.toLowerCase() === 'auto') { + return true; + } + + var type = external_dependency_parsers_0.valueType(v); + return type === margin_local_var_TYPES.LENGTH || type === margin_local_var_TYPES.PERCENT || type === margin_local_var_TYPES.INTEGER && (v === '0' || v === 0); +}; + +var margin_local_var_parser = function (v) { + var V = v.toLowerCase(); + + if (V === 'auto') { + return V; + } + + return external_dependency_parsers_0.parseMeasurement(v); +}; + +var margin_local_var_mySetter = external_dependency_parsers_0.implicitSetter('margin', '', margin_local_var_isValid, margin_local_var_parser); +var margin_local_var_myGlobal = external_dependency_parsers_0.implicitSetter('margin', '', function () { + return true; +}, function (v) { + return v; +}); +margin_export_definition = { + set: function (v) { + if (typeof v === 'number') { + v = String(v); + } + + if (typeof v !== 'string') { + return; + } + + var V = v.toLowerCase(); + + switch (V) { + case 'inherit': + case 'initial': + case 'unset': + case '': + margin_local_var_myGlobal.call(this, V); + break; + + default: + margin_local_var_mySetter.call(this, v); + break; + } + }, + get: function () { + return this.getPropertyValue('margin'); + }, + enumerable: true, + configurable: true +}; +margin_export_isValid = margin_local_var_isValid; +margin_export_parser = margin_local_var_parser; +var marginBottom_export_definition; +marginBottom_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('margin', 'bottom', { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.isValid, { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.parser), + get: function () { + return this.getPropertyValue('margin-bottom'); + }, + enumerable: true, + configurable: true +}; +var marginLeft_export_definition; +marginLeft_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('margin', 'left', { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.isValid, { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.parser), + get: function () { + return this.getPropertyValue('margin-left'); + }, + enumerable: true, + configurable: true +}; +var marginRight_export_definition; +marginRight_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('margin', 'right', { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.isValid, { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.parser), + get: function () { + return this.getPropertyValue('margin-right'); + }, + enumerable: true, + configurable: true +}; +var marginTop_export_definition; +marginTop_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('margin', 'top', { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.isValid, { + definition: margin_export_definition, + isValid: margin_export_isValid, + parser: margin_export_parser + }.parser), + get: function () { + return this.getPropertyValue('margin-top'); + }, + enumerable: true, + configurable: true +}; +var opacity_export_definition; +opacity_export_definition = { + set: function (v) { + this._setProperty('opacity', external_dependency_parsers_0.parseNumber(v)); + }, + get: function () { + return this.getPropertyValue('opacity'); + }, + enumerable: true, + configurable: true +}; +var outlineColor_export_definition; +outlineColor_export_definition = { + set: function (v) { + this._setProperty('outline-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('outline-color'); + }, + enumerable: true, + configurable: true +}; +var padding_export_definition, padding_export_isValid, padding_export_parser; +var padding_local_var_TYPES = external_dependency_parsers_0.TYPES; + +var padding_local_var_isValid = function (v) { + var type = external_dependency_parsers_0.valueType(v); + return type === padding_local_var_TYPES.LENGTH || type === padding_local_var_TYPES.PERCENT || type === padding_local_var_TYPES.INTEGER && (v === '0' || v === 0); +}; + +var padding_local_var_parser = function (v) { + return external_dependency_parsers_0.parseMeasurement(v); +}; + +var padding_local_var_mySetter = external_dependency_parsers_0.implicitSetter('padding', '', padding_local_var_isValid, padding_local_var_parser); +var padding_local_var_myGlobal = external_dependency_parsers_0.implicitSetter('padding', '', function () { + return true; +}, function (v) { + return v; +}); +padding_export_definition = { + set: function (v) { + if (typeof v === 'number') { + v = String(v); + } + + if (typeof v !== 'string') { + return; + } + + var V = v.toLowerCase(); + + switch (V) { + case 'inherit': + case 'initial': + case 'unset': + case '': + padding_local_var_myGlobal.call(this, V); + break; + + default: + padding_local_var_mySetter.call(this, v); + break; + } + }, + get: function () { + return this.getPropertyValue('padding'); + }, + enumerable: true, + configurable: true +}; +padding_export_isValid = padding_local_var_isValid; +padding_export_parser = padding_local_var_parser; +var paddingBottom_export_definition; +paddingBottom_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('padding', 'bottom', { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.isValid, { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.parser), + get: function () { + return this.getPropertyValue('padding-bottom'); + }, + enumerable: true, + configurable: true +}; +var paddingLeft_export_definition; +paddingLeft_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('padding', 'left', { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.isValid, { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.parser), + get: function () { + return this.getPropertyValue('padding-left'); + }, + enumerable: true, + configurable: true +}; +var paddingRight_export_definition; +paddingRight_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('padding', 'right', { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.isValid, { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.parser), + get: function () { + return this.getPropertyValue('padding-right'); + }, + enumerable: true, + configurable: true +}; +var paddingTop_export_definition; +paddingTop_export_definition = { + set: external_dependency_parsers_0.subImplicitSetter('padding', 'top', { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.isValid, { + definition: padding_export_definition, + isValid: padding_export_isValid, + parser: padding_export_parser + }.parser), + get: function () { + return this.getPropertyValue('padding-top'); + }, + enumerable: true, + configurable: true +}; +var right_export_definition; +right_export_definition = { + set: function (v) { + this._setProperty('right', external_dependency_parsers_0.parseMeasurement(v)); + }, + get: function () { + return this.getPropertyValue('right'); + }, + enumerable: true, + configurable: true +}; +var stopColor_export_definition; +stopColor_export_definition = { + set: function (v) { + this._setProperty('stop-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('stop-color'); + }, + enumerable: true, + configurable: true +}; +var textLineThroughColor_export_definition; +textLineThroughColor_export_definition = { + set: function (v) { + this._setProperty('text-line-through-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('text-line-through-color'); + }, + enumerable: true, + configurable: true +}; +var textOverlineColor_export_definition; +textOverlineColor_export_definition = { + set: function (v) { + this._setProperty('text-overline-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('text-overline-color'); + }, + enumerable: true, + configurable: true +}; +var textUnderlineColor_export_definition; +textUnderlineColor_export_definition = { + set: function (v) { + this._setProperty('text-underline-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('text-underline-color'); + }, + enumerable: true, + configurable: true +}; +var top_export_definition; +top_export_definition = { + set: function (v) { + this._setProperty('top', external_dependency_parsers_0.parseMeasurement(v)); + }, + get: function () { + return this.getPropertyValue('top'); + }, + enumerable: true, + configurable: true +}; +var webkitBorderAfterColor_export_definition; +webkitBorderAfterColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-border-after-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-border-after-color'); + }, + enumerable: true, + configurable: true +}; +var webkitBorderBeforeColor_export_definition; +webkitBorderBeforeColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-border-before-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-border-before-color'); + }, + enumerable: true, + configurable: true +}; +var webkitBorderEndColor_export_definition; +webkitBorderEndColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-border-end-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-border-end-color'); + }, + enumerable: true, + configurable: true +}; +var webkitBorderStartColor_export_definition; +webkitBorderStartColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-border-start-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-border-start-color'); + }, + enumerable: true, + configurable: true +}; +var webkitColumnRuleColor_export_definition; +webkitColumnRuleColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-column-rule-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-column-rule-color'); + }, + enumerable: true, + configurable: true +}; +var webkitMatchNearestMailBlockquoteColor_export_definition; +webkitMatchNearestMailBlockquoteColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-match-nearest-mail-blockquote-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-match-nearest-mail-blockquote-color'); + }, + enumerable: true, + configurable: true +}; +var webkitTapHighlightColor_export_definition; +webkitTapHighlightColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-tap-highlight-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-tap-highlight-color'); + }, + enumerable: true, + configurable: true +}; +var webkitTextEmphasisColor_export_definition; +webkitTextEmphasisColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-text-emphasis-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-text-emphasis-color'); + }, + enumerable: true, + configurable: true +}; +var webkitTextFillColor_export_definition; +webkitTextFillColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-text-fill-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-text-fill-color'); + }, + enumerable: true, + configurable: true +}; +var webkitTextStrokeColor_export_definition; +webkitTextStrokeColor_export_definition = { + set: function (v) { + this._setProperty('-webkit-text-stroke-color', external_dependency_parsers_0.parseColor(v)); + }, + get: function () { + return this.getPropertyValue('-webkit-text-stroke-color'); + }, + enumerable: true, + configurable: true +}; +var width_export_definition; + +function width_local_fn_parse(v) { + if (String(v).toLowerCase() === 'auto') { + return 'auto'; + } + + if (String(v).toLowerCase() === 'inherit') { + return 'inherit'; + } + + return external_dependency_parsers_0.parseMeasurement(v); +} + +width_export_definition = { + set: function (v) { + this._setProperty('width', width_local_fn_parse(v)); + }, + get: function () { + return this.getPropertyValue('width'); + }, + enumerable: true, + configurable: true +}; + +module.exports = function (prototype) { + Object.defineProperties(prototype, { + azimuth: azimuth_export_definition, + backgroundColor: backgroundColor_export_definition, + "background-color": backgroundColor_export_definition, + backgroundImage: backgroundImage_export_definition, + "background-image": backgroundImage_export_definition, + backgroundRepeat: backgroundRepeat_export_definition, + "background-repeat": backgroundRepeat_export_definition, + backgroundAttachment: backgroundAttachment_export_definition, + "background-attachment": backgroundAttachment_export_definition, + backgroundPosition: backgroundPosition_export_definition, + "background-position": backgroundPosition_export_definition, + background: background_export_definition, + borderWidth: borderWidth_export_definition, + "border-width": borderWidth_export_definition, + borderStyle: borderStyle_export_definition, + "border-style": borderStyle_export_definition, + borderColor: borderColor_export_definition, + "border-color": borderColor_export_definition, + border: border_export_definition, + borderBottomWidth: borderBottomWidth_export_definition, + "border-bottom-width": borderBottomWidth_export_definition, + borderBottomStyle: borderBottomStyle_export_definition, + "border-bottom-style": borderBottomStyle_export_definition, + borderBottomColor: borderBottomColor_export_definition, + "border-bottom-color": borderBottomColor_export_definition, + borderBottom: borderBottom_export_definition, + "border-bottom": borderBottom_export_definition, + borderCollapse: borderCollapse_export_definition, + "border-collapse": borderCollapse_export_definition, + borderLeftWidth: borderLeftWidth_export_definition, + "border-left-width": borderLeftWidth_export_definition, + borderLeftStyle: borderLeftStyle_export_definition, + "border-left-style": borderLeftStyle_export_definition, + borderLeftColor: borderLeftColor_export_definition, + "border-left-color": borderLeftColor_export_definition, + borderLeft: borderLeft_export_definition, + "border-left": borderLeft_export_definition, + borderRightWidth: borderRightWidth_export_definition, + "border-right-width": borderRightWidth_export_definition, + borderRightStyle: borderRightStyle_export_definition, + "border-right-style": borderRightStyle_export_definition, + borderRightColor: borderRightColor_export_definition, + "border-right-color": borderRightColor_export_definition, + borderRight: borderRight_export_definition, + "border-right": borderRight_export_definition, + borderSpacing: borderSpacing_export_definition, + "border-spacing": borderSpacing_export_definition, + borderTopWidth: borderTopWidth_export_definition, + "border-top-width": borderTopWidth_export_definition, + borderTopStyle: borderTopStyle_export_definition, + "border-top-style": borderTopStyle_export_definition, + borderTopColor: borderTopColor_export_definition, + "border-top-color": borderTopColor_export_definition, + borderTop: borderTop_export_definition, + "border-top": borderTop_export_definition, + bottom: bottom_export_definition, + clear: clear_export_definition, + clip: clip_export_definition, + color: color_export_definition, + cssFloat: cssFloat_export_definition, + "css-float": cssFloat_export_definition, + flexGrow: flexGrow_export_definition, + "flex-grow": flexGrow_export_definition, + flexShrink: flexShrink_export_definition, + "flex-shrink": flexShrink_export_definition, + flexBasis: flexBasis_export_definition, + "flex-basis": flexBasis_export_definition, + flex: flex_export_definition, + float: float_export_definition, + floodColor: floodColor_export_definition, + "flood-color": floodColor_export_definition, + fontFamily: fontFamily_export_definition, + "font-family": fontFamily_export_definition, + fontSize: fontSize_export_definition, + "font-size": fontSize_export_definition, + fontStyle: fontStyle_export_definition, + "font-style": fontStyle_export_definition, + fontVariant: fontVariant_export_definition, + "font-variant": fontVariant_export_definition, + fontWeight: fontWeight_export_definition, + "font-weight": fontWeight_export_definition, + lineHeight: lineHeight_export_definition, + "line-height": lineHeight_export_definition, + font: font_export_definition, + height: height_export_definition, + left: left_export_definition, + lightingColor: lightingColor_export_definition, + "lighting-color": lightingColor_export_definition, + margin: margin_export_definition, + marginBottom: marginBottom_export_definition, + "margin-bottom": marginBottom_export_definition, + marginLeft: marginLeft_export_definition, + "margin-left": marginLeft_export_definition, + marginRight: marginRight_export_definition, + "margin-right": marginRight_export_definition, + marginTop: marginTop_export_definition, + "margin-top": marginTop_export_definition, + opacity: opacity_export_definition, + outlineColor: outlineColor_export_definition, + "outline-color": outlineColor_export_definition, + padding: padding_export_definition, + paddingBottom: paddingBottom_export_definition, + "padding-bottom": paddingBottom_export_definition, + paddingLeft: paddingLeft_export_definition, + "padding-left": paddingLeft_export_definition, + paddingRight: paddingRight_export_definition, + "padding-right": paddingRight_export_definition, + paddingTop: paddingTop_export_definition, + "padding-top": paddingTop_export_definition, + right: right_export_definition, + stopColor: stopColor_export_definition, + "stop-color": stopColor_export_definition, + textLineThroughColor: textLineThroughColor_export_definition, + "text-line-through-color": textLineThroughColor_export_definition, + textOverlineColor: textOverlineColor_export_definition, + "text-overline-color": textOverlineColor_export_definition, + textUnderlineColor: textUnderlineColor_export_definition, + "text-underline-color": textUnderlineColor_export_definition, + top: top_export_definition, + webkitBorderAfterColor: webkitBorderAfterColor_export_definition, + "webkit-border-after-color": webkitBorderAfterColor_export_definition, + webkitBorderBeforeColor: webkitBorderBeforeColor_export_definition, + "webkit-border-before-color": webkitBorderBeforeColor_export_definition, + webkitBorderEndColor: webkitBorderEndColor_export_definition, + "webkit-border-end-color": webkitBorderEndColor_export_definition, + webkitBorderStartColor: webkitBorderStartColor_export_definition, + "webkit-border-start-color": webkitBorderStartColor_export_definition, + webkitColumnRuleColor: webkitColumnRuleColor_export_definition, + "webkit-column-rule-color": webkitColumnRuleColor_export_definition, + webkitMatchNearestMailBlockquoteColor: webkitMatchNearestMailBlockquoteColor_export_definition, + "webkit-match-nearest-mail-blockquote-color": webkitMatchNearestMailBlockquoteColor_export_definition, + webkitTapHighlightColor: webkitTapHighlightColor_export_definition, + "webkit-tap-highlight-color": webkitTapHighlightColor_export_definition, + webkitTextEmphasisColor: webkitTextEmphasisColor_export_definition, + "webkit-text-emphasis-color": webkitTextEmphasisColor_export_definition, + webkitTextFillColor: webkitTextFillColor_export_definition, + "webkit-text-fill-color": webkitTextFillColor_export_definition, + webkitTextStrokeColor: webkitTextStrokeColor_export_definition, + "webkit-text-stroke-color": webkitTextStrokeColor_export_definition, + width: width_export_definition + }); +}; diff --git a/node_modules/cssstyle/lib/properties/azimuth.js b/node_modules/cssstyle/lib/properties/azimuth.js new file mode 100644 index 0000000..f23a68d --- /dev/null +++ b/node_modules/cssstyle/lib/properties/azimuth.js @@ -0,0 +1,67 @@ +'use strict'; + +var parsers = require('../parsers'); + +module.exports.definition = { + set: function(v) { + var valueType = parsers.valueType(v); + if (valueType === parsers.TYPES.ANGLE) { + return this._setProperty('azimuth', parsers.parseAngle(v)); + } + if (valueType === parsers.TYPES.KEYWORD) { + var keywords = v + .toLowerCase() + .trim() + .split(/\s+/); + var hasBehind = false; + if (keywords.length > 2) { + return; + } + var behindIndex = keywords.indexOf('behind'); + hasBehind = behindIndex !== -1; + + if (keywords.length === 2) { + if (!hasBehind) { + return; + } + keywords.splice(behindIndex, 1); + } + if (keywords[0] === 'leftwards' || keywords[0] === 'rightwards') { + if (hasBehind) { + return; + } + return this._setProperty('azimuth', keywords[0]); + } + if (keywords[0] === 'behind') { + return this._setProperty('azimuth', '180deg'); + } + switch (keywords[0]) { + case 'left-side': + return this._setProperty('azimuth', '270deg'); + case 'far-left': + return this._setProperty('azimuth', (hasBehind ? 240 : 300) + 'deg'); + case 'left': + return this._setProperty('azimuth', (hasBehind ? 220 : 320) + 'deg'); + case 'center-left': + return this._setProperty('azimuth', (hasBehind ? 200 : 340) + 'deg'); + case 'center': + return this._setProperty('azimuth', (hasBehind ? 180 : 0) + 'deg'); + case 'center-right': + return this._setProperty('azimuth', (hasBehind ? 160 : 20) + 'deg'); + case 'right': + return this._setProperty('azimuth', (hasBehind ? 140 : 40) + 'deg'); + case 'far-right': + return this._setProperty('azimuth', (hasBehind ? 120 : 60) + 'deg'); + case 'right-side': + return this._setProperty('azimuth', '90deg'); + default: + return; + } + } + }, + get: function() { + return this.getPropertyValue('azimuth'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/background.js b/node_modules/cssstyle/lib/properties/background.js new file mode 100644 index 0000000..b843e0c --- /dev/null +++ b/node_modules/cssstyle/lib/properties/background.js @@ -0,0 +1,19 @@ +'use strict'; + +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'background-color': require('./backgroundColor'), + 'background-image': require('./backgroundImage'), + 'background-repeat': require('./backgroundRepeat'), + 'background-attachment': require('./backgroundAttachment'), + 'background-position': require('./backgroundPosition'), +}; + +module.exports.definition = { + set: shorthandSetter('background', shorthand_for), + get: shorthandGetter('background', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/backgroundAttachment.js b/node_modules/cssstyle/lib/properties/backgroundAttachment.js new file mode 100644 index 0000000..98c8f76 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/backgroundAttachment.js @@ -0,0 +1,24 @@ +'use strict'; + +var parsers = require('../parsers'); + +var isValid = (module.exports.isValid = function isValid(v) { + return ( + parsers.valueType(v) === parsers.TYPES.KEYWORD && + (v.toLowerCase() === 'scroll' || v.toLowerCase() === 'fixed' || v.toLowerCase() === 'inherit') + ); +}); + +module.exports.definition = { + set: function(v) { + if (!isValid(v)) { + return; + } + this._setProperty('background-attachment', v); + }, + get: function() { + return this.getPropertyValue('background-attachment'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/backgroundColor.js b/node_modules/cssstyle/lib/properties/backgroundColor.js new file mode 100644 index 0000000..5cee717 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/backgroundColor.js @@ -0,0 +1,36 @@ +'use strict'; + +var parsers = require('../parsers'); + +var parse = function parse(v) { + var parsed = parsers.parseColor(v); + if (parsed !== undefined) { + return parsed; + } + if ( + parsers.valueType(v) === parsers.TYPES.KEYWORD && + (v.toLowerCase() === 'transparent' || v.toLowerCase() === 'inherit') + ) { + return v; + } + return undefined; +}; + +module.exports.isValid = function isValid(v) { + return parse(v) !== undefined; +}; + +module.exports.definition = { + set: function(v) { + var parsed = parse(v); + if (parsed === undefined) { + return; + } + this._setProperty('background-color', parsed); + }, + get: function() { + return this.getPropertyValue('background-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/backgroundImage.js b/node_modules/cssstyle/lib/properties/backgroundImage.js new file mode 100644 index 0000000..b6479a1 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/backgroundImage.js @@ -0,0 +1,32 @@ +'use strict'; + +var parsers = require('../parsers'); + +var parse = function parse(v) { + var parsed = parsers.parseUrl(v); + if (parsed !== undefined) { + return parsed; + } + if ( + parsers.valueType(v) === parsers.TYPES.KEYWORD && + (v.toLowerCase() === 'none' || v.toLowerCase() === 'inherit') + ) { + return v; + } + return undefined; +}; + +module.exports.isValid = function isValid(v) { + return parse(v) !== undefined; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('background-image', parse(v)); + }, + get: function() { + return this.getPropertyValue('background-image'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/backgroundPosition.js b/node_modules/cssstyle/lib/properties/backgroundPosition.js new file mode 100644 index 0000000..4405fe6 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/backgroundPosition.js @@ -0,0 +1,58 @@ +'use strict'; + +var parsers = require('../parsers'); + +var valid_keywords = ['top', 'center', 'bottom', 'left', 'right']; + +var parse = function parse(v) { + if (v === '' || v === null) { + return undefined; + } + var parts = v.split(/\s+/); + if (parts.length > 2 || parts.length < 1) { + return undefined; + } + var types = []; + parts.forEach(function(part, index) { + types[index] = parsers.valueType(part); + }); + if (parts.length === 1) { + if (types[0] === parsers.TYPES.LENGTH || types[0] === parsers.TYPES.PERCENT) { + return v; + } + if (types[0] === parsers.TYPES.KEYWORD) { + if (valid_keywords.indexOf(v.toLowerCase()) !== -1 || v.toLowerCase() === 'inherit') { + return v; + } + } + return undefined; + } + if ( + (types[0] === parsers.TYPES.LENGTH || types[0] === parsers.TYPES.PERCENT) && + (types[1] === parsers.TYPES.LENGTH || types[1] === parsers.TYPES.PERCENT) + ) { + return v; + } + if (types[0] !== parsers.TYPES.KEYWORD || types[1] !== parsers.TYPES.KEYWORD) { + return undefined; + } + if (valid_keywords.indexOf(parts[0]) !== -1 && valid_keywords.indexOf(parts[1]) !== -1) { + return v; + } + return undefined; +}; + +module.exports.isValid = function isValid(v) { + return parse(v) !== undefined; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('background-position', parse(v)); + }, + get: function() { + return this.getPropertyValue('background-position'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/backgroundRepeat.js b/node_modules/cssstyle/lib/properties/backgroundRepeat.js new file mode 100644 index 0000000..379ade0 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/backgroundRepeat.js @@ -0,0 +1,32 @@ +'use strict'; + +var parsers = require('../parsers'); + +var parse = function parse(v) { + if ( + parsers.valueType(v) === parsers.TYPES.KEYWORD && + (v.toLowerCase() === 'repeat' || + v.toLowerCase() === 'repeat-x' || + v.toLowerCase() === 'repeat-y' || + v.toLowerCase() === 'no-repeat' || + v.toLowerCase() === 'inherit') + ) { + return v; + } + return undefined; +}; + +module.exports.isValid = function isValid(v) { + return parse(v) !== undefined; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('background-repeat', parse(v)); + }, + get: function() { + return this.getPropertyValue('background-repeat'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/border.js b/node_modules/cssstyle/lib/properties/border.js new file mode 100644 index 0000000..bf5b5d6 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/border.js @@ -0,0 +1,33 @@ +'use strict'; + +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'border-width': require('./borderWidth'), + 'border-style': require('./borderStyle'), + 'border-color': require('./borderColor'), +}; + +var myShorthandSetter = shorthandSetter('border', shorthand_for); +var myShorthandGetter = shorthandGetter('border', shorthand_for); + +module.exports.definition = { + set: function(v) { + if (v.toString().toLowerCase() === 'none') { + v = ''; + } + myShorthandSetter.call(this, v); + this.removeProperty('border-top'); + this.removeProperty('border-left'); + this.removeProperty('border-right'); + this.removeProperty('border-bottom'); + this._values['border-top'] = this._values.border; + this._values['border-left'] = this._values.border; + this._values['border-right'] = this._values.border; + this._values['border-bottom'] = this._values.border; + }, + get: myShorthandGetter, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderBottom.js b/node_modules/cssstyle/lib/properties/borderBottom.js new file mode 100644 index 0000000..aae2e5f --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderBottom.js @@ -0,0 +1,17 @@ +'use strict'; + +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'border-bottom-width': require('./borderBottomWidth'), + 'border-bottom-style': require('./borderBottomStyle'), + 'border-bottom-color': require('./borderBottomColor'), +}; + +module.exports.definition = { + set: shorthandSetter('border-bottom', shorthand_for), + get: shorthandGetter('border-bottom', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderBottomColor.js b/node_modules/cssstyle/lib/properties/borderBottomColor.js new file mode 100644 index 0000000..da5a4b5 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderBottomColor.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderColor').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-bottom-color', v); + } + }, + get: function() { + return this.getPropertyValue('border-bottom-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderBottomStyle.js b/node_modules/cssstyle/lib/properties/borderBottomStyle.js new file mode 100644 index 0000000..35c44f0 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderBottomStyle.js @@ -0,0 +1,21 @@ +'use strict'; + +var isValid = require('./borderStyle').isValid; +module.exports.isValid = isValid; + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-bottom-width'); + } + this._setProperty('border-bottom-style', v); + } + }, + get: function() { + return this.getPropertyValue('border-bottom-style'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderBottomWidth.js b/node_modules/cssstyle/lib/properties/borderBottomWidth.js new file mode 100644 index 0000000..db2e3b8 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderBottomWidth.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderWidth').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-bottom-width', v); + } + }, + get: function() { + return this.getPropertyValue('border-bottom-width'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderCollapse.js b/node_modules/cssstyle/lib/properties/borderCollapse.js new file mode 100644 index 0000000..49bdeb0 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderCollapse.js @@ -0,0 +1,26 @@ +'use strict'; + +var parsers = require('../parsers'); + +var parse = function parse(v) { + if ( + parsers.valueType(v) === parsers.TYPES.KEYWORD && + (v.toLowerCase() === 'collapse' || + v.toLowerCase() === 'separate' || + v.toLowerCase() === 'inherit') + ) { + return v; + } + return undefined; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('border-collapse', parse(v)); + }, + get: function() { + return this.getPropertyValue('border-collapse'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderColor.js b/node_modules/cssstyle/lib/properties/borderColor.js new file mode 100644 index 0000000..6605e07 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderColor.js @@ -0,0 +1,30 @@ +'use strict'; + +var parsers = require('../parsers'); +var implicitSetter = require('../parsers').implicitSetter; + +module.exports.isValid = function parse(v) { + if (typeof v !== 'string') { + return false; + } + return ( + v === '' || v.toLowerCase() === 'transparent' || parsers.valueType(v) === parsers.TYPES.COLOR + ); +}; +var isValid = module.exports.isValid; + +var parser = function(v) { + if (isValid(v)) { + return v.toLowerCase(); + } + return undefined; +}; + +module.exports.definition = { + set: implicitSetter('border', 'color', isValid, parser), + get: function() { + return this.getPropertyValue('border-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderLeft.js b/node_modules/cssstyle/lib/properties/borderLeft.js new file mode 100644 index 0000000..a05945e --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderLeft.js @@ -0,0 +1,17 @@ +'use strict'; + +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'border-left-width': require('./borderLeftWidth'), + 'border-left-style': require('./borderLeftStyle'), + 'border-left-color': require('./borderLeftColor'), +}; + +module.exports.definition = { + set: shorthandSetter('border-left', shorthand_for), + get: shorthandGetter('border-left', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderLeftColor.js b/node_modules/cssstyle/lib/properties/borderLeftColor.js new file mode 100644 index 0000000..eb3f273 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderLeftColor.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderColor').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-left-color', v); + } + }, + get: function() { + return this.getPropertyValue('border-left-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderLeftStyle.js b/node_modules/cssstyle/lib/properties/borderLeftStyle.js new file mode 100644 index 0000000..5e8a113 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderLeftStyle.js @@ -0,0 +1,21 @@ +'use strict'; + +var isValid = require('./borderStyle').isValid; +module.exports.isValid = isValid; + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-left-width'); + } + this._setProperty('border-left-style', v); + } + }, + get: function() { + return this.getPropertyValue('border-left-style'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderLeftWidth.js b/node_modules/cssstyle/lib/properties/borderLeftWidth.js new file mode 100644 index 0000000..8c680b1 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderLeftWidth.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderWidth').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-left-width', v); + } + }, + get: function() { + return this.getPropertyValue('border-left-width'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderRight.js b/node_modules/cssstyle/lib/properties/borderRight.js new file mode 100644 index 0000000..17e26df --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderRight.js @@ -0,0 +1,17 @@ +'use strict'; + +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'border-right-width': require('./borderRightWidth'), + 'border-right-style': require('./borderRightStyle'), + 'border-right-color': require('./borderRightColor'), +}; + +module.exports.definition = { + set: shorthandSetter('border-right', shorthand_for), + get: shorthandGetter('border-right', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderRightColor.js b/node_modules/cssstyle/lib/properties/borderRightColor.js new file mode 100644 index 0000000..7c188f2 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderRightColor.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderColor').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-right-color', v); + } + }, + get: function() { + return this.getPropertyValue('border-right-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderRightStyle.js b/node_modules/cssstyle/lib/properties/borderRightStyle.js new file mode 100644 index 0000000..68e8209 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderRightStyle.js @@ -0,0 +1,21 @@ +'use strict'; + +var isValid = require('./borderStyle').isValid; +module.exports.isValid = isValid; + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-right-width'); + } + this._setProperty('border-right-style', v); + } + }, + get: function() { + return this.getPropertyValue('border-right-style'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderRightWidth.js b/node_modules/cssstyle/lib/properties/borderRightWidth.js new file mode 100644 index 0000000..d1090d7 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderRightWidth.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderWidth').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-right-width', v); + } + }, + get: function() { + return this.getPropertyValue('border-right-width'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderSpacing.js b/node_modules/cssstyle/lib/properties/borderSpacing.js new file mode 100644 index 0000000..ff1ce88 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderSpacing.js @@ -0,0 +1,41 @@ +'use strict'; + +var parsers = require('../parsers'); + +// ? | inherit +// if one, it applies to both horizontal and verical spacing +// if two, the first applies to the horizontal and the second applies to vertical spacing + +var parse = function parse(v) { + if (v === '' || v === null) { + return undefined; + } + if (v === 0) { + return '0px'; + } + if (v.toLowerCase() === 'inherit') { + return v; + } + var parts = v.split(/\s+/); + if (parts.length !== 1 && parts.length !== 2) { + return undefined; + } + parts.forEach(function(part) { + if (parsers.valueType(part) !== parsers.TYPES.LENGTH) { + return undefined; + } + }); + + return v; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('border-spacing', parse(v)); + }, + get: function() { + return this.getPropertyValue('border-spacing'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderStyle.js b/node_modules/cssstyle/lib/properties/borderStyle.js new file mode 100644 index 0000000..6e3e674 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderStyle.js @@ -0,0 +1,38 @@ +'use strict'; + +var implicitSetter = require('../parsers').implicitSetter; + +// the valid border-styles: +var styles = [ + 'none', + 'hidden', + 'dotted', + 'dashed', + 'solid', + 'double', + 'groove', + 'ridge', + 'inset', + 'outset', +]; + +module.exports.isValid = function parse(v) { + return typeof v === 'string' && (v === '' || styles.indexOf(v) !== -1); +}; +var isValid = module.exports.isValid; + +var parser = function(v) { + if (isValid(v)) { + return v.toLowerCase(); + } + return undefined; +}; + +module.exports.definition = { + set: implicitSetter('border', 'style', isValid, parser), + get: function() { + return this.getPropertyValue('border-style'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderTop.js b/node_modules/cssstyle/lib/properties/borderTop.js new file mode 100644 index 0000000..c56d592 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderTop.js @@ -0,0 +1,17 @@ +'use strict'; + +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'border-top-width': require('./borderTopWidth'), + 'border-top-style': require('./borderTopStyle'), + 'border-top-color': require('./borderTopColor'), +}; + +module.exports.definition = { + set: shorthandSetter('border-top', shorthand_for), + get: shorthandGetter('border-top', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderTopColor.js b/node_modules/cssstyle/lib/properties/borderTopColor.js new file mode 100644 index 0000000..cc35392 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderTopColor.js @@ -0,0 +1,16 @@ +'use strict'; + +var isValid = (module.exports.isValid = require('./borderColor').isValid); + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-top-color', v); + } + }, + get: function() { + return this.getPropertyValue('border-top-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderTopStyle.js b/node_modules/cssstyle/lib/properties/borderTopStyle.js new file mode 100644 index 0000000..938ea40 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderTopStyle.js @@ -0,0 +1,21 @@ +'use strict'; + +var isValid = require('./borderStyle').isValid; +module.exports.isValid = isValid; + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + if (v.toLowerCase() === 'none') { + v = ''; + this.removeProperty('border-top-width'); + } + this._setProperty('border-top-style', v); + } + }, + get: function() { + return this.getPropertyValue('border-top-style'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderTopWidth.js b/node_modules/cssstyle/lib/properties/borderTopWidth.js new file mode 100644 index 0000000..9407253 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderTopWidth.js @@ -0,0 +1,17 @@ +'use strict'; + +var isValid = require('./borderWidth').isValid; +module.exports.isValid = isValid; + +module.exports.definition = { + set: function(v) { + if (isValid(v)) { + this._setProperty('border-top-width', v); + } + }, + get: function() { + return this.getPropertyValue('border-top-width'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/borderWidth.js b/node_modules/cssstyle/lib/properties/borderWidth.js new file mode 100644 index 0000000..2b6d871 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/borderWidth.js @@ -0,0 +1,46 @@ +'use strict'; + +var parsers = require('../parsers'); +var implicitSetter = require('../parsers').implicitSetter; + +// the valid border-widths: +var widths = ['thin', 'medium', 'thick']; + +module.exports.isValid = function parse(v) { + var length = parsers.parseLength(v); + if (length !== undefined) { + return true; + } + if (typeof v !== 'string') { + return false; + } + if (v === '') { + return true; + } + v = v.toLowerCase(); + if (widths.indexOf(v) === -1) { + return false; + } + return true; +}; +var isValid = module.exports.isValid; + +var parser = function(v) { + var length = parsers.parseLength(v); + if (length !== undefined) { + return length; + } + if (isValid(v)) { + return v.toLowerCase(); + } + return undefined; +}; + +module.exports.definition = { + set: implicitSetter('border', 'width', isValid, parser), + get: function() { + return this.getPropertyValue('border-width'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/bottom.js b/node_modules/cssstyle/lib/properties/bottom.js new file mode 100644 index 0000000..e9d72b2 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/bottom.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +module.exports.definition = { + set: function(v) { + this._setProperty('bottom', parseMeasurement(v)); + }, + get: function() { + return this.getPropertyValue('bottom'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/clear.js b/node_modules/cssstyle/lib/properties/clear.js new file mode 100644 index 0000000..22d9802 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/clear.js @@ -0,0 +1,16 @@ +'use strict'; + +var parseKeyword = require('../parsers').parseKeyword; + +var clear_keywords = ['none', 'left', 'right', 'both', 'inherit']; + +module.exports.definition = { + set: function(v) { + this._setProperty('clear', parseKeyword(v, clear_keywords)); + }, + get: function() { + return this.getPropertyValue('clear'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/clip.js b/node_modules/cssstyle/lib/properties/clip.js new file mode 100644 index 0000000..91ba675 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/clip.js @@ -0,0 +1,47 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +var shape_regex = /^rect\((.*)\)$/i; + +var parse = function(val) { + if (val === '' || val === null) { + return val; + } + if (typeof val !== 'string') { + return undefined; + } + val = val.toLowerCase(); + if (val === 'auto' || val === 'inherit') { + return val; + } + var matches = val.match(shape_regex); + if (!matches) { + return undefined; + } + var parts = matches[1].split(/\s*,\s*/); + if (parts.length !== 4) { + return undefined; + } + var valid = parts.every(function(part, index) { + var measurement = parseMeasurement(part); + parts[index] = measurement; + return measurement !== undefined; + }); + if (!valid) { + return undefined; + } + parts = parts.join(', '); + return val.replace(matches[1], parts); +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('clip', parse(v)); + }, + get: function() { + return this.getPropertyValue('clip'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/color.js b/node_modules/cssstyle/lib/properties/color.js new file mode 100644 index 0000000..1b5ca3d --- /dev/null +++ b/node_modules/cssstyle/lib/properties/color.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/cssFloat.js b/node_modules/cssstyle/lib/properties/cssFloat.js new file mode 100644 index 0000000..1c619cc --- /dev/null +++ b/node_modules/cssstyle/lib/properties/cssFloat.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports.definition = { + set: function(v) { + this._setProperty('float', v); + }, + get: function() { + return this.getPropertyValue('float'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/flex.js b/node_modules/cssstyle/lib/properties/flex.js new file mode 100644 index 0000000..b56fd55 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/flex.js @@ -0,0 +1,45 @@ +'use strict'; + +var shorthandParser = require('../parsers').shorthandParser; +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'flex-grow': require('./flexGrow'), + 'flex-shrink': require('./flexShrink'), + 'flex-basis': require('./flexBasis'), +}; + +var myShorthandSetter = shorthandSetter('flex', shorthand_for); + +module.exports.isValid = function isValid(v) { + return shorthandParser(v, shorthand_for) !== undefined; +}; + +module.exports.definition = { + set: function(v) { + var normalizedValue = String(v) + .trim() + .toLowerCase(); + + if (normalizedValue === 'none') { + myShorthandSetter.call(this, '0 0 auto'); + return; + } + if (normalizedValue === 'initial') { + myShorthandSetter.call(this, '0 1 auto'); + return; + } + if (normalizedValue === 'auto') { + this.removeProperty('flex-grow'); + this.removeProperty('flex-shrink'); + this.setProperty('flex-basis', normalizedValue); + return; + } + + myShorthandSetter.call(this, v); + }, + get: shorthandGetter('flex', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/flexBasis.js b/node_modules/cssstyle/lib/properties/flexBasis.js new file mode 100644 index 0000000..0c7cddf --- /dev/null +++ b/node_modules/cssstyle/lib/properties/flexBasis.js @@ -0,0 +1,28 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +function parse(v) { + if (String(v).toLowerCase() === 'auto') { + return 'auto'; + } + if (String(v).toLowerCase() === 'inherit') { + return 'inherit'; + } + return parseMeasurement(v); +} + +module.exports.isValid = function isValid(v) { + return parse(v) !== undefined; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('flex-basis', parse(v)); + }, + get: function() { + return this.getPropertyValue('flex-basis'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/flexGrow.js b/node_modules/cssstyle/lib/properties/flexGrow.js new file mode 100644 index 0000000..6e29663 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/flexGrow.js @@ -0,0 +1,19 @@ +'use strict'; + +var parseNumber = require('../parsers').parseNumber; +var POSITION_AT_SHORTHAND = require('../constants').POSITION_AT_SHORTHAND; + +module.exports.isValid = function isValid(v, positionAtFlexShorthand) { + return parseNumber(v) !== undefined && positionAtFlexShorthand === POSITION_AT_SHORTHAND.first; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('flex-grow', parseNumber(v)); + }, + get: function() { + return this.getPropertyValue('flex-grow'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/flexShrink.js b/node_modules/cssstyle/lib/properties/flexShrink.js new file mode 100644 index 0000000..63ff86f --- /dev/null +++ b/node_modules/cssstyle/lib/properties/flexShrink.js @@ -0,0 +1,19 @@ +'use strict'; + +var parseNumber = require('../parsers').parseNumber; +var POSITION_AT_SHORTHAND = require('../constants').POSITION_AT_SHORTHAND; + +module.exports.isValid = function isValid(v, positionAtFlexShorthand) { + return parseNumber(v) !== undefined && positionAtFlexShorthand === POSITION_AT_SHORTHAND.second; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('flex-shrink', parseNumber(v)); + }, + get: function() { + return this.getPropertyValue('flex-shrink'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/float.js b/node_modules/cssstyle/lib/properties/float.js new file mode 100644 index 0000000..1c619cc --- /dev/null +++ b/node_modules/cssstyle/lib/properties/float.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports.definition = { + set: function(v) { + this._setProperty('float', v); + }, + get: function() { + return this.getPropertyValue('float'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/floodColor.js b/node_modules/cssstyle/lib/properties/floodColor.js new file mode 100644 index 0000000..8a4f29c --- /dev/null +++ b/node_modules/cssstyle/lib/properties/floodColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('flood-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('flood-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/font.js b/node_modules/cssstyle/lib/properties/font.js new file mode 100644 index 0000000..9492dc6 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/font.js @@ -0,0 +1,43 @@ +'use strict'; + +var TYPES = require('../parsers').TYPES; +var valueType = require('../parsers').valueType; +var shorthandParser = require('../parsers').shorthandParser; +var shorthandSetter = require('../parsers').shorthandSetter; +var shorthandGetter = require('../parsers').shorthandGetter; + +var shorthand_for = { + 'font-family': require('./fontFamily'), + 'font-size': require('./fontSize'), + 'font-style': require('./fontStyle'), + 'font-variant': require('./fontVariant'), + 'font-weight': require('./fontWeight'), + 'line-height': require('./lineHeight'), +}; + +var static_fonts = [ + 'caption', + 'icon', + 'menu', + 'message-box', + 'small-caption', + 'status-bar', + 'inherit', +]; + +var setter = shorthandSetter('font', shorthand_for); + +module.exports.definition = { + set: function(v) { + var short = shorthandParser(v, shorthand_for); + if (short !== undefined) { + return setter.call(this, v); + } + if (valueType(v) === TYPES.KEYWORD && static_fonts.indexOf(v.toLowerCase()) !== -1) { + this._setProperty('font', v); + } + }, + get: shorthandGetter('font', shorthand_for), + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/fontFamily.js b/node_modules/cssstyle/lib/properties/fontFamily.js new file mode 100644 index 0000000..40bd1c1 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/fontFamily.js @@ -0,0 +1,33 @@ +'use strict'; + +var TYPES = require('../parsers').TYPES; +var valueType = require('../parsers').valueType; + +var partsRegEx = /\s*,\s*/; +module.exports.isValid = function isValid(v) { + if (v === '' || v === null) { + return true; + } + var parts = v.split(partsRegEx); + var len = parts.length; + var i; + var type; + for (i = 0; i < len; i++) { + type = valueType(parts[i]); + if (type === TYPES.STRING || type === TYPES.KEYWORD) { + return true; + } + } + return false; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('font-family', v); + }, + get: function() { + return this.getPropertyValue('font-family'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/fontSize.js b/node_modules/cssstyle/lib/properties/fontSize.js new file mode 100644 index 0000000..287c82a --- /dev/null +++ b/node_modules/cssstyle/lib/properties/fontSize.js @@ -0,0 +1,28 @@ +'use strict'; + +var TYPES = require('../parsers').TYPES; +var valueType = require('../parsers').valueType; + +var absoluteSizes = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large']; +var relativeSizes = ['larger', 'smaller']; + +module.exports.isValid = function(v) { + var type = valueType(v.toLowerCase()); + return ( + type === TYPES.LENGTH || + type === TYPES.PERCENT || + (type === TYPES.KEYWORD && absoluteSizes.indexOf(v.toLowerCase()) !== -1) || + (type === TYPES.KEYWORD && relativeSizes.indexOf(v.toLowerCase()) !== -1) + ); +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('font-size', v); + }, + get: function() { + return this.getPropertyValue('font-size'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/fontStyle.js b/node_modules/cssstyle/lib/properties/fontStyle.js new file mode 100644 index 0000000..63d5e92 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/fontStyle.js @@ -0,0 +1,18 @@ +'use strict'; + +var valid_styles = ['normal', 'italic', 'oblique', 'inherit']; + +module.exports.isValid = function(v) { + return valid_styles.indexOf(v.toLowerCase()) !== -1; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('font-style', v); + }, + get: function() { + return this.getPropertyValue('font-style'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/fontVariant.js b/node_modules/cssstyle/lib/properties/fontVariant.js new file mode 100644 index 0000000..f03b5ea --- /dev/null +++ b/node_modules/cssstyle/lib/properties/fontVariant.js @@ -0,0 +1,18 @@ +'use strict'; + +var valid_variants = ['normal', 'small-caps', 'inherit']; + +module.exports.isValid = function isValid(v) { + return valid_variants.indexOf(v.toLowerCase()) !== -1; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('font-variant', v); + }, + get: function() { + return this.getPropertyValue('font-variant'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/fontWeight.js b/node_modules/cssstyle/lib/properties/fontWeight.js new file mode 100644 index 0000000..b854f6a --- /dev/null +++ b/node_modules/cssstyle/lib/properties/fontWeight.js @@ -0,0 +1,33 @@ +'use strict'; + +var valid_weights = [ + 'normal', + 'bold', + 'bolder', + 'lighter', + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900', + 'inherit', +]; + +module.exports.isValid = function isValid(v) { + return valid_weights.indexOf(v.toLowerCase()) !== -1; +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('font-weight', v); + }, + get: function() { + return this.getPropertyValue('font-weight'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/height.js b/node_modules/cssstyle/lib/properties/height.js new file mode 100644 index 0000000..82543c0 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/height.js @@ -0,0 +1,24 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +function parse(v) { + if (String(v).toLowerCase() === 'auto') { + return 'auto'; + } + if (String(v).toLowerCase() === 'inherit') { + return 'inherit'; + } + return parseMeasurement(v); +} + +module.exports.definition = { + set: function(v) { + this._setProperty('height', parse(v)); + }, + get: function() { + return this.getPropertyValue('height'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/left.js b/node_modules/cssstyle/lib/properties/left.js new file mode 100644 index 0000000..72bb2fa --- /dev/null +++ b/node_modules/cssstyle/lib/properties/left.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +module.exports.definition = { + set: function(v) { + this._setProperty('left', parseMeasurement(v)); + }, + get: function() { + return this.getPropertyValue('left'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/lightingColor.js b/node_modules/cssstyle/lib/properties/lightingColor.js new file mode 100644 index 0000000..9f9643d --- /dev/null +++ b/node_modules/cssstyle/lib/properties/lightingColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('lighting-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('lighting-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/lineHeight.js b/node_modules/cssstyle/lib/properties/lineHeight.js new file mode 100644 index 0000000..6f7a037 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/lineHeight.js @@ -0,0 +1,26 @@ +'use strict'; + +var TYPES = require('../parsers').TYPES; +var valueType = require('../parsers').valueType; + +module.exports.isValid = function isValid(v) { + var type = valueType(v); + return ( + (type === TYPES.KEYWORD && v.toLowerCase() === 'normal') || + v.toLowerCase() === 'inherit' || + type === TYPES.NUMBER || + type === TYPES.LENGTH || + type === TYPES.PERCENT + ); +}; + +module.exports.definition = { + set: function(v) { + this._setProperty('line-height', v); + }, + get: function() { + return this.getPropertyValue('line-height'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/margin.js b/node_modules/cssstyle/lib/properties/margin.js new file mode 100644 index 0000000..2a8f972 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/margin.js @@ -0,0 +1,68 @@ +'use strict'; + +var parsers = require('../parsers.js'); +var TYPES = parsers.TYPES; + +var isValid = function(v) { + if (v.toLowerCase() === 'auto') { + return true; + } + var type = parsers.valueType(v); + return ( + type === TYPES.LENGTH || + type === TYPES.PERCENT || + (type === TYPES.INTEGER && (v === '0' || v === 0)) + ); +}; + +var parser = function(v) { + var V = v.toLowerCase(); + if (V === 'auto') { + return V; + } + return parsers.parseMeasurement(v); +}; + +var mySetter = parsers.implicitSetter('margin', '', isValid, parser); +var myGlobal = parsers.implicitSetter( + 'margin', + '', + function() { + return true; + }, + function(v) { + return v; + } +); + +module.exports.definition = { + set: function(v) { + if (typeof v === 'number') { + v = String(v); + } + if (typeof v !== 'string') { + return; + } + var V = v.toLowerCase(); + switch (V) { + case 'inherit': + case 'initial': + case 'unset': + case '': + myGlobal.call(this, V); + break; + + default: + mySetter.call(this, v); + break; + } + }, + get: function() { + return this.getPropertyValue('margin'); + }, + enumerable: true, + configurable: true, +}; + +module.exports.isValid = isValid; +module.exports.parser = parser; diff --git a/node_modules/cssstyle/lib/properties/marginBottom.js b/node_modules/cssstyle/lib/properties/marginBottom.js new file mode 100644 index 0000000..378172e --- /dev/null +++ b/node_modules/cssstyle/lib/properties/marginBottom.js @@ -0,0 +1,13 @@ +'use strict'; + +var margin = require('./margin.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('margin', 'bottom', margin.isValid, margin.parser), + get: function() { + return this.getPropertyValue('margin-bottom'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/marginLeft.js b/node_modules/cssstyle/lib/properties/marginLeft.js new file mode 100644 index 0000000..0c67317 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/marginLeft.js @@ -0,0 +1,13 @@ +'use strict'; + +var margin = require('./margin.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('margin', 'left', margin.isValid, margin.parser), + get: function() { + return this.getPropertyValue('margin-left'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/marginRight.js b/node_modules/cssstyle/lib/properties/marginRight.js new file mode 100644 index 0000000..6cdf26b --- /dev/null +++ b/node_modules/cssstyle/lib/properties/marginRight.js @@ -0,0 +1,13 @@ +'use strict'; + +var margin = require('./margin.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('margin', 'right', margin.isValid, margin.parser), + get: function() { + return this.getPropertyValue('margin-right'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/marginTop.js b/node_modules/cssstyle/lib/properties/marginTop.js new file mode 100644 index 0000000..6a57621 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/marginTop.js @@ -0,0 +1,13 @@ +'use strict'; + +var margin = require('./margin.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('margin', 'top', margin.isValid, margin.parser), + get: function() { + return this.getPropertyValue('margin-top'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/opacity.js b/node_modules/cssstyle/lib/properties/opacity.js new file mode 100644 index 0000000..b26a3b6 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/opacity.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseNumber = require('../parsers').parseNumber; + +module.exports.definition = { + set: function(v) { + this._setProperty('opacity', parseNumber(v)); + }, + get: function() { + return this.getPropertyValue('opacity'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/outlineColor.js b/node_modules/cssstyle/lib/properties/outlineColor.js new file mode 100644 index 0000000..fc8093d --- /dev/null +++ b/node_modules/cssstyle/lib/properties/outlineColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('outline-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('outline-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/padding.js b/node_modules/cssstyle/lib/properties/padding.js new file mode 100644 index 0000000..1287b19 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/padding.js @@ -0,0 +1,61 @@ +'use strict'; + +var parsers = require('../parsers.js'); +var TYPES = parsers.TYPES; + +var isValid = function(v) { + var type = parsers.valueType(v); + return ( + type === TYPES.LENGTH || + type === TYPES.PERCENT || + (type === TYPES.INTEGER && (v === '0' || v === 0)) + ); +}; + +var parser = function(v) { + return parsers.parseMeasurement(v); +}; + +var mySetter = parsers.implicitSetter('padding', '', isValid, parser); +var myGlobal = parsers.implicitSetter( + 'padding', + '', + function() { + return true; + }, + function(v) { + return v; + } +); + +module.exports.definition = { + set: function(v) { + if (typeof v === 'number') { + v = String(v); + } + if (typeof v !== 'string') { + return; + } + var V = v.toLowerCase(); + switch (V) { + case 'inherit': + case 'initial': + case 'unset': + case '': + myGlobal.call(this, V); + break; + + default: + mySetter.call(this, v); + break; + } + }, + get: function() { + return this.getPropertyValue('padding'); + }, + enumerable: true, + configurable: true, +}; + +module.exports.isValid = isValid; +module.exports.parser = parser; diff --git a/node_modules/cssstyle/lib/properties/paddingBottom.js b/node_modules/cssstyle/lib/properties/paddingBottom.js new file mode 100644 index 0000000..3ce88e5 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/paddingBottom.js @@ -0,0 +1,13 @@ +'use strict'; + +var padding = require('./padding.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('padding', 'bottom', padding.isValid, padding.parser), + get: function() { + return this.getPropertyValue('padding-bottom'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/paddingLeft.js b/node_modules/cssstyle/lib/properties/paddingLeft.js new file mode 100644 index 0000000..0436338 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/paddingLeft.js @@ -0,0 +1,13 @@ +'use strict'; + +var padding = require('./padding.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('padding', 'left', padding.isValid, padding.parser), + get: function() { + return this.getPropertyValue('padding-left'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/paddingRight.js b/node_modules/cssstyle/lib/properties/paddingRight.js new file mode 100644 index 0000000..ff9bd34 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/paddingRight.js @@ -0,0 +1,13 @@ +'use strict'; + +var padding = require('./padding.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('padding', 'right', padding.isValid, padding.parser), + get: function() { + return this.getPropertyValue('padding-right'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/paddingTop.js b/node_modules/cssstyle/lib/properties/paddingTop.js new file mode 100644 index 0000000..eca8781 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/paddingTop.js @@ -0,0 +1,13 @@ +'use strict'; + +var padding = require('./padding.js'); +var parsers = require('../parsers.js'); + +module.exports.definition = { + set: parsers.subImplicitSetter('padding', 'top', padding.isValid, padding.parser), + get: function() { + return this.getPropertyValue('padding-top'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/right.js b/node_modules/cssstyle/lib/properties/right.js new file mode 100644 index 0000000..eb4c3d4 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/right.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +module.exports.definition = { + set: function(v) { + this._setProperty('right', parseMeasurement(v)); + }, + get: function() { + return this.getPropertyValue('right'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/stopColor.js b/node_modules/cssstyle/lib/properties/stopColor.js new file mode 100644 index 0000000..912d8e2 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/stopColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('stop-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('stop-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/textLineThroughColor.js b/node_modules/cssstyle/lib/properties/textLineThroughColor.js new file mode 100644 index 0000000..ae53dbb --- /dev/null +++ b/node_modules/cssstyle/lib/properties/textLineThroughColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('text-line-through-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('text-line-through-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/textOverlineColor.js b/node_modules/cssstyle/lib/properties/textOverlineColor.js new file mode 100644 index 0000000..c6adf7c --- /dev/null +++ b/node_modules/cssstyle/lib/properties/textOverlineColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('text-overline-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('text-overline-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/textUnderlineColor.js b/node_modules/cssstyle/lib/properties/textUnderlineColor.js new file mode 100644 index 0000000..a243a9c --- /dev/null +++ b/node_modules/cssstyle/lib/properties/textUnderlineColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('text-underline-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('text-underline-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/top.js b/node_modules/cssstyle/lib/properties/top.js new file mode 100644 index 0000000..f71986f --- /dev/null +++ b/node_modules/cssstyle/lib/properties/top.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +module.exports.definition = { + set: function(v) { + this._setProperty('top', parseMeasurement(v)); + }, + get: function() { + return this.getPropertyValue('top'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitBorderAfterColor.js b/node_modules/cssstyle/lib/properties/webkitBorderAfterColor.js new file mode 100644 index 0000000..ed02194 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitBorderAfterColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-border-after-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-border-after-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitBorderBeforeColor.js b/node_modules/cssstyle/lib/properties/webkitBorderBeforeColor.js new file mode 100644 index 0000000..a4507a1 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitBorderBeforeColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-border-before-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-border-before-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitBorderEndColor.js b/node_modules/cssstyle/lib/properties/webkitBorderEndColor.js new file mode 100644 index 0000000..499545d --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitBorderEndColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-border-end-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-border-end-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitBorderStartColor.js b/node_modules/cssstyle/lib/properties/webkitBorderStartColor.js new file mode 100644 index 0000000..8429e32 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitBorderStartColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-border-start-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-border-start-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitColumnRuleColor.js b/node_modules/cssstyle/lib/properties/webkitColumnRuleColor.js new file mode 100644 index 0000000..7130d5f --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitColumnRuleColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-column-rule-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-column-rule-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitMatchNearestMailBlockquoteColor.js b/node_modules/cssstyle/lib/properties/webkitMatchNearestMailBlockquoteColor.js new file mode 100644 index 0000000..e075891 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitMatchNearestMailBlockquoteColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-match-nearest-mail-blockquote-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-match-nearest-mail-blockquote-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitTapHighlightColor.js b/node_modules/cssstyle/lib/properties/webkitTapHighlightColor.js new file mode 100644 index 0000000..d019329 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitTapHighlightColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-tap-highlight-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-tap-highlight-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitTextEmphasisColor.js b/node_modules/cssstyle/lib/properties/webkitTextEmphasisColor.js new file mode 100644 index 0000000..cdeab53 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitTextEmphasisColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-text-emphasis-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-text-emphasis-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitTextFillColor.js b/node_modules/cssstyle/lib/properties/webkitTextFillColor.js new file mode 100644 index 0000000..ef5bd67 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitTextFillColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-text-fill-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-text-fill-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/webkitTextStrokeColor.js b/node_modules/cssstyle/lib/properties/webkitTextStrokeColor.js new file mode 100644 index 0000000..72a2277 --- /dev/null +++ b/node_modules/cssstyle/lib/properties/webkitTextStrokeColor.js @@ -0,0 +1,14 @@ +'use strict'; + +var parseColor = require('../parsers').parseColor; + +module.exports.definition = { + set: function(v) { + this._setProperty('-webkit-text-stroke-color', parseColor(v)); + }, + get: function() { + return this.getPropertyValue('-webkit-text-stroke-color'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/properties/width.js b/node_modules/cssstyle/lib/properties/width.js new file mode 100644 index 0000000..a8c365d --- /dev/null +++ b/node_modules/cssstyle/lib/properties/width.js @@ -0,0 +1,24 @@ +'use strict'; + +var parseMeasurement = require('../parsers').parseMeasurement; + +function parse(v) { + if (String(v).toLowerCase() === 'auto') { + return 'auto'; + } + if (String(v).toLowerCase() === 'inherit') { + return 'inherit'; + } + return parseMeasurement(v); +} + +module.exports.definition = { + set: function(v) { + this._setProperty('width', parse(v)); + }, + get: function() { + return this.getPropertyValue('width'); + }, + enumerable: true, + configurable: true, +}; diff --git a/node_modules/cssstyle/lib/utils/getBasicPropertyDescriptor.js b/node_modules/cssstyle/lib/utils/getBasicPropertyDescriptor.js new file mode 100644 index 0000000..ded2cc4 --- /dev/null +++ b/node_modules/cssstyle/lib/utils/getBasicPropertyDescriptor.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function getBasicPropertyDescriptor(name) { + return { + set: function(v) { + this._setProperty(name, v); + }, + get: function() { + return this.getPropertyValue(name); + }, + enumerable: true, + configurable: true, + }; +}; diff --git a/node_modules/cssstyle/package.json b/node_modules/cssstyle/package.json new file mode 100644 index 0000000..225bb72 --- /dev/null +++ b/node_modules/cssstyle/package.json @@ -0,0 +1,105 @@ +{ + "_from": "cssstyle@^1.1.1", + "_id": "cssstyle@1.2.2", + "_inBundle": false, + "_integrity": "sha512-43wY3kl1CVQSvL7wUY1qXkxVGkStjpkDmVjiIKX8R97uhajy8Bybay78uOtqvh7Q5GK75dNPfW0geWjE6qQQow==", + "_location": "/cssstyle", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cssstyle@^1.1.1", + "name": "cssstyle", + "escapedName": "cssstyle", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/jsdom" + ], + "_resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-1.2.2.tgz", + "_shasum": "427ea4d585b18624f6fdbf9de7a2a1a3ba713077", + "_spec": "cssstyle@^1.1.1", + "_where": "F:\\projects\\vanillajs-seed\\node_modules\\jsdom", + "bugs": { + "url": "https://github.com/jsakas/CSSStyleDeclaration/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Chad Walker", + "email": "chad@chad-cat-lore-eddie.com", + "url": "https://github.com/chad3814" + }, + { + "name": "Rafał Ruciński", + "email": "fatfisz@gmail.com", + "url": "https://fatfisz.com" + }, + { + "name": "Nikita Vasilyev", + "email": "me@elv1s.ru" + }, + { + "name": "Davide P. Cervone" + }, + { + "name": "Forbes Lindesay" + } + ], + "dependencies": { + "cssom": "0.3.x" + }, + "deprecated": false, + "description": "CSSStyleDeclaration Object Model implementation", + "devDependencies": { + "babel-generator": "~6.26.1", + "babel-traverse": "~6.26.0", + "babel-types": "~6.26.0", + "babylon": "~6.18.0", + "eslint": "5.13.0", + "eslint-config-prettier": "4.0.0", + "eslint-plugin-prettier": "3.0.1", + "nodeunit": "~0.11.3", + "npm-run-all": "^4.1.5", + "prettier": "1.16.4", + "request": "^2.88.0", + "resolve": "~1.8.1" + }, + "directories": { + "lib": "./lib" + }, + "homepage": "https://github.com/jsakas/CSSStyleDeclaration", + "keywords": [ + "CSS", + "CSSStyleDeclaration", + "StyleSheet" + ], + "license": "MIT", + "main": "./lib/CSSStyleDeclaration.js", + "maintainers": [ + { + "name": "Jon Sakas", + "email": "jon.sakas@gmail.com", + "url": "https://jon.sakas.co/" + } + ], + "name": "cssstyle", + "repository": { + "type": "git", + "url": "git+https://github.com/jsakas/CSSStyleDeclaration.git" + }, + "scripts": { + "download": "node ./scripts/download_latest_properties.js && eslint lib/allProperties.js --fix", + "generate": "run-p generate:*", + "generate:implemented_properties": "node ./scripts/generate_implemented_properties.js", + "generate:properties": "node ./scripts/generate_properties.js", + "lint": "npm run generate && eslint . --max-warnings 0", + "lint:fix": "eslint . --fix --max-warnings 0", + "prepublishOnly": "npm run test-ci", + "test": "npm run generate && nodeunit tests", + "test-ci": "npm run lint && npm run test" + }, + "version": "1.2.2" +} diff --git a/node_modules/cssstyle/scripts/download_latest_properties.js b/node_modules/cssstyle/scripts/download_latest_properties.js new file mode 100644 index 0000000..5f17ef5 --- /dev/null +++ b/node_modules/cssstyle/scripts/download_latest_properties.js @@ -0,0 +1,88 @@ +'use strict'; + +/* + * W3C provides JSON list of all CSS properties and their status in the standard + * + * documentation: https://www.w3.org/Style/CSS/all-properties.en.html + * JSON url: ( https://www.w3.org/Style/CSS/all-properties.en.json ) + * + * Download that file, filter out duplicates and filter the properties based on the wanted standard level + * + * ED - Editors' Draft (not a W3C Technical Report) + * FPWD - First Public Working Draft + * WD - Working Draft + * LC - Last Call Working Draft + * CR - Candidate Recommendation + * PR - Proposed Recommendation + * REC - Recommendation + * NOTE - Working Group Note + */ + +var fs = require('fs'); +var path = require('path'); + +var request = require('request'); + +const { camelToDashed } = require('../lib/parsers'); + +var url = 'https://www.w3.org/Style/CSS/all-properties.en.json'; + +console.log('Downloading CSS properties...'); + +function toCamelCase(propName) { + return propName.replace(/-([a-z])/g, function(g) { + return g[1].toUpperCase(); + }); +} + +request(url, function(error, response, body) { + if (!error && response.statusCode === 200) { + var allCSSProperties = JSON.parse(body); + + // Filter out all properties newer than Working Draft + var workingDraftAndOlderProperties = allCSSProperties.filter(function(cssProp) { + // TODO: --* css Needs additional logic to this module, so filter it out for now + return cssProp.status !== 'ED' && cssProp.status !== 'FPWD' && cssProp.property !== '--*'; + }); + + // Remove duplicates, there can be many properties in different states of standard + // and add only property names to the list + var CSSpropertyNames = []; + workingDraftAndOlderProperties.forEach(function(cssProp) { + const camelCaseName = toCamelCase(cssProp.property); + + if (CSSpropertyNames.indexOf(camelCaseName) === -1) { + CSSpropertyNames.push(camelCaseName); + } + }); + + var out_file = fs.createWriteStream(path.resolve(__dirname, './../lib/allProperties.js'), { + encoding: 'utf-8', + }); + + var date_today = new Date(); + out_file.write( + "'use strict';\n\n// autogenerated - " + + (date_today.getMonth() + 1 + '/' + date_today.getDate() + '/' + date_today.getFullYear()) + + '\n\n' + ); + out_file.write('/*\n *\n * https://www.w3.org/Style/CSS/all-properties.en.html\n */\n\n'); + + out_file.write('var allProperties = new Set();\n'); + out_file.write('module.exports = allProperties;\n'); + + CSSpropertyNames.forEach(function(property) { + out_file.write('allProperties.add(' + JSON.stringify(camelToDashed(property)) + ');\n'); + }); + + out_file.end(function(err) { + if (err) { + throw err; + } + + console.log('Generated ' + Object.keys(CSSpropertyNames).length + ' properties.'); + }); + } else { + throw error; + } +}); diff --git a/node_modules/cssstyle/scripts/generate_implemented_properties.js b/node_modules/cssstyle/scripts/generate_implemented_properties.js new file mode 100644 index 0000000..caa88f1 --- /dev/null +++ b/node_modules/cssstyle/scripts/generate_implemented_properties.js @@ -0,0 +1,61 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const t = require('babel-types'); +const generate = require('babel-generator').default; +const camelToDashed = require('../lib/parsers').camelToDashed; + +const dashedProperties = fs + .readdirSync(path.resolve(__dirname, '../lib/properties')) + .filter(propertyFile => propertyFile.substr(-3) === '.js') + .map(propertyFile => camelToDashed(propertyFile.replace('.js', ''))); + +const out_file = fs.createWriteStream(path.resolve(__dirname, '../lib/implementedProperties.js'), { + encoding: 'utf-8', +}); +var date_today = new Date(); +out_file.write( + "'use strict';\n\n// autogenerated - " + + (date_today.getMonth() + 1 + '/' + date_today.getDate() + '/' + date_today.getFullYear()) + + '\n\n' +); +out_file.write('/*\n *\n * https://www.w3.org/Style/CSS/all-properties.en.html\n */\n\n'); + +const statements = []; +statements.push( + t.variableDeclaration('var', [ + t.variableDeclarator( + t.identifier('implementedProperties'), + t.newExpression(t.identifier('Set'), []) + ), + ]) +); + +dashedProperties.forEach(property => { + statements.push( + t.expressionStatement( + t.callExpression( + t.memberExpression(t.identifier('implementedProperties'), t.identifier('add')), + [t.stringLiteral(property)] + ) + ) + ); +}); + +statements.push( + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression(t.identifier('module'), t.identifier('exports')), + t.identifier('implementedProperties') + ) + ) +); + +out_file.write(generate(t.program(statements)).code + '\n'); +out_file.end(function(err) { + if (err) { + throw err; + } +}); diff --git a/node_modules/cssstyle/scripts/generate_properties.js b/node_modules/cssstyle/scripts/generate_properties.js new file mode 100644 index 0000000..33a4272 --- /dev/null +++ b/node_modules/cssstyle/scripts/generate_properties.js @@ -0,0 +1,292 @@ +'use strict'; + +var fs = require('fs'); +var path = require('path'); +var babylon = require('babylon'); +var t = require('babel-types'); +var generate = require('babel-generator').default; +var traverse = require('babel-traverse').default; +var resolve = require('resolve'); + +var camelToDashed = require('../lib/parsers').camelToDashed; + +var basename = path.basename; +var dirname = path.dirname; + +var uniqueIndex = 0; +function getUniqueIndex() { + return uniqueIndex++; +} + +var property_files = fs + .readdirSync(path.resolve(__dirname, '../lib/properties')) + .filter(function(property) { + return property.substr(-3) === '.js'; + }); +var out_file = fs.createWriteStream(path.resolve(__dirname, '../lib/properties.js'), { + encoding: 'utf-8', +}); +var date_today = new Date(); +out_file.write( + "'use strict';\n\n// autogenerated - " + + (date_today.getMonth() + 1 + '/' + date_today.getDate() + '/' + date_today.getFullYear()) + + '\n\n' +); +out_file.write('/*\n *\n * https://www.w3.org/Style/CSS/all-properties.en.html\n */\n\n'); + +function isModuleDotExports(node) { + return ( + t.isMemberExpression(node, { computed: false }) && + t.isIdentifier(node.object, { name: 'module' }) && + t.isIdentifier(node.property, { name: 'exports' }) + ); +} +function isRequire(node, filename) { + if ( + t.isCallExpression(node) && + t.isIdentifier(node.callee, { name: 'require' }) && + node.arguments.length === 1 && + t.isStringLiteral(node.arguments[0]) + ) { + var relative = node.arguments[0].value; + var fullPath = resolve.sync(relative, { basedir: dirname(filename) }); + return { relative: relative, fullPath: fullPath }; + } else { + return false; + } +} + +// step 1: parse all files and figure out their dependencies +var parsedFilesByPath = {}; +property_files.map(function(property) { + var filename = path.resolve(__dirname, '../lib/properties/' + property); + var src = fs.readFileSync(filename, 'utf8'); + property = basename(property, '.js'); + var ast = babylon.parse(src); + var dependencies = []; + traverse(ast, { + enter(path) { + var r; + if ((r = isRequire(path.node, filename))) { + dependencies.push(r.fullPath); + } + }, + }); + parsedFilesByPath[filename] = { + filename: filename, + property: property, + ast: ast, + dependencies: dependencies, + }; +}); + +// step 2: serialize the files in an order where dependencies are always above +// the files they depend on +var externalDependencies = []; +var parsedFiles = []; +var addedFiles = {}; +function addFile(filename, dependencyPath) { + if (dependencyPath.indexOf(filename) !== -1) { + throw new Error( + 'Circular dependency: ' + + dependencyPath + .slice(dependencyPath.indexOf(filename)) + .concat([filename]) + .join(' -> ') + ); + } + var file = parsedFilesByPath[filename]; + if (addedFiles[filename]) { + return; + } + if (!file) { + externalDependencies.push(filename); + } else { + file.dependencies.forEach(function(dependency) { + addFile(dependency, dependencyPath.concat([filename])); + }); + parsedFiles.push(parsedFilesByPath[filename]); + } + addedFiles[filename] = true; +} +Object.keys(parsedFilesByPath).forEach(function(filename) { + addFile(filename, []); +}); +// Step 3: add files to output +// renaming exports to local variables `moduleName_export_exportName` +// and updating require calls as appropriate +var moduleExportsByPath = {}; +var statements = []; +externalDependencies.forEach(function(filename, i) { + var id = t.identifier( + 'external_dependency_' + basename(filename, '.js').replace(/[^A-Za-z]/g, '') + '_' + i + ); + moduleExportsByPath[filename] = { defaultExports: id }; + var relativePath = path.relative(path.resolve(__dirname + '/../lib'), filename); + if (relativePath[0] !== '.') { + relativePath = './' + relativePath; + } + statements.push( + t.variableDeclaration('var', [ + t.variableDeclarator( + id, + t.callExpression(t.identifier('require'), [t.stringLiteral(relativePath)]) + ), + ]) + ); +}); +function getRequireValue(node, file) { + var r, e; + // replace require("./foo").bar with the named export from foo + if ( + t.isMemberExpression(node, { computed: false }) && + (r = isRequire(node.object, file.filename)) + ) { + e = moduleExportsByPath[r.fullPath]; + if (!e) { + return; + } + if (!e.namedExports) { + return t.memberExpression(e.defaultExports, node.property); + } + if (!e.namedExports[node.property.name]) { + throw new Error(r.relative + ' does not export ' + node.property.name); + } + return e.namedExports[node.property.name]; + + // replace require("./foo") with the default export of foo + } else if ((r = isRequire(node, file.filename))) { + e = moduleExportsByPath[r.fullPath]; + if (!e) { + if (/^\.\.\//.test(r.relative)) { + node.arguments[0].value = r.relative.substr(1); + } + return; + } + return e.defaultExports; + } +} +parsedFiles.forEach(function(file) { + var namedExports = {}; + var localVariableMap = {}; + + traverse(file.ast, { + enter(path) { + // replace require calls with the corresponding value + var r; + if ((r = getRequireValue(path.node, file))) { + path.replaceWith(r); + return; + } + + // if we see `var foo = require('bar')` we can just inline the variable + // representing `require('bar')` wherever `foo` was used. + if ( + t.isVariableDeclaration(path.node) && + path.node.declarations.length === 1 && + t.isIdentifier(path.node.declarations[0].id) && + (r = getRequireValue(path.node.declarations[0].init, file)) + ) { + var newName = 'compiled_local_variable_reference_' + getUniqueIndex(); + path.scope.rename(path.node.declarations[0].id.name, newName); + localVariableMap[newName] = r; + path.remove(); + return; + } + + // rename all top level functions to keep them local to the module + if (t.isFunctionDeclaration(path.node) && t.isProgram(path.parent)) { + path.scope.rename(path.node.id.name, file.property + '_local_fn_' + path.node.id.name); + return; + } + + // rename all top level variables to keep them local to the module + if (t.isVariableDeclaration(path.node) && t.isProgram(path.parent)) { + path.node.declarations.forEach(function(declaration) { + path.scope.rename( + declaration.id.name, + file.property + '_local_var_' + declaration.id.name + ); + }); + return; + } + + // replace module.exports.bar with a variable for the named export + if ( + t.isMemberExpression(path.node, { computed: false }) && + isModuleDotExports(path.node.object) + ) { + var name = path.node.property.name; + var identifier = t.identifier(file.property + '_export_' + name); + path.replaceWith(identifier); + namedExports[name] = identifier; + } + }, + }); + traverse(file.ast, { + enter(path) { + if ( + t.isIdentifier(path.node) && + Object.prototype.hasOwnProperty.call(localVariableMap, path.node.name) + ) { + path.replaceWith(localVariableMap[path.node.name]); + } + }, + }); + var defaultExports = t.objectExpression( + Object.keys(namedExports).map(function(name) { + return t.objectProperty(t.identifier(name), namedExports[name]); + }) + ); + moduleExportsByPath[file.filename] = { + namedExports: namedExports, + defaultExports: defaultExports, + }; + statements.push( + t.variableDeclaration( + 'var', + Object.keys(namedExports).map(function(name) { + return t.variableDeclarator(namedExports[name]); + }) + ) + ); + statements.push.apply(statements, file.ast.program.body); +}); +var propertyDefinitions = []; +parsedFiles.forEach(function(file) { + var dashed = camelToDashed(file.property); + propertyDefinitions.push( + t.objectProperty( + t.identifier(file.property), + t.identifier(file.property + '_export_definition') + ) + ); + if (file.property !== dashed) { + propertyDefinitions.push( + t.objectProperty(t.stringLiteral(dashed), t.identifier(file.property + '_export_definition')) + ); + } +}); +var definePropertiesCall = t.callExpression( + t.memberExpression(t.identifier('Object'), t.identifier('defineProperties')), + [t.identifier('prototype'), t.objectExpression(propertyDefinitions)] +); +statements.push( + t.expressionStatement( + t.assignmentExpression( + '=', + t.memberExpression(t.identifier('module'), t.identifier('exports')), + t.functionExpression( + null, + [t.identifier('prototype')], + t.blockStatement([t.expressionStatement(definePropertiesCall)]) + ) + ) + ) +); +out_file.write(generate(t.program(statements)).code + '\n'); +out_file.end(function(err) { + if (err) { + throw err; + } +}); diff --git a/node_modules/cssstyle/tests/tests.js b/node_modules/cssstyle/tests/tests.js new file mode 100644 index 0000000..945040c --- /dev/null +++ b/node_modules/cssstyle/tests/tests.js @@ -0,0 +1,669 @@ +'use strict'; +var cssstyle = require('../lib/CSSStyleDeclaration'); + +var { dashedToCamelCase } = require('../lib/parsers'); + +var dashedProperties = [ + ...require('../lib/allProperties'), + ...require('../lib/allExtraProperties'), +]; +var allowedProperties = dashedProperties.map(dashedToCamelCase); +var implementedProperties = Array.from(require('../lib/implementedProperties')).map( + dashedToCamelCase +); +var invalidProperties = implementedProperties.filter(function(property) { + return !allowedProperties.includes(property); +}); + +module.exports = { + 'Verify Has Only Valid Properties Implemented': function(test) { + test.expect(1); + test.ok( + invalidProperties.length === 0, + invalidProperties.length + + ' invalid properties implemented: ' + + Array.from(invalidProperties).join(', ') + ); + test.done(); + }, + 'Verify Has All Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(allowedProperties.length * 2); + allowedProperties.forEach(function(property) { + test.ok(style.__lookupGetter__(property), 'missing ' + property + ' property'); + test.ok(style.__lookupSetter__(property), 'missing ' + property + ' property'); + }); + test.done(); + }, + 'Verify Has All Dashed Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(dashedProperties.length * 2); + dashedProperties.forEach(function(property) { + test.ok(style.__lookupGetter__(property), 'missing ' + property + ' property'); + test.ok(style.__lookupSetter__(property), 'missing ' + property + ' property'); + }); + test.done(); + }, + 'Verify Has Functions': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(6); + test.ok(typeof style.getPropertyValue === 'function', 'missing getPropertyValue()'); + test.ok(typeof style.getPropertyCSSValue === 'function', 'missing getPropertyCSSValue()'); + test.ok(typeof style.removeProperty === 'function', 'missing removeProperty()'); + test.ok(typeof style.getPropertyPriority === 'function', 'missing getPropertyPriority()'); + test.ok(typeof style.setProperty === 'function', 'missing setProperty()'); + test.ok(typeof style.item === 'function', 'missing item()'); + test.done(); + }, + 'Verify Has Special Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(5); + test.ok(style.__lookupGetter__('cssText'), 'missing cssText getter'); + test.ok(style.__lookupSetter__('cssText'), 'missing cssText setter'); + test.ok(style.__lookupGetter__('length'), 'missing length getter'); + test.ok(style.__lookupSetter__('length'), 'missing length setter'); + test.ok(style.__lookupGetter__('parentRule'), 'missing parentRule getter'); + test.done(); + }, + 'Test From Style String': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(8); + style.cssText = 'color: blue; background-color: red; width: 78%; height: 50vh;'; + test.ok(4 === style.length, 'length is not 4'); + test.ok( + 'color: blue; background-color: red; width: 78%; height: 50vh;' === style.cssText, + 'cssText is wrong' + ); + test.ok('blue' === style.getPropertyValue('color'), "getPropertyValue('color') failed"); + test.ok('color' === style.item(0), 'item(0) failed'); + test.ok('background-color' === style[1], 'style[1] failed'); + test.ok( + 'red' === style.backgroundColor, + 'style.backgroundColor failed with "' + style.backgroundColor + '"' + ); + style.cssText = ''; + test.ok('' === style.cssText, 'cssText is not empty'); + test.ok(0 === style.length, 'length is not 0'); + test.done(); + }, + 'Test From Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(11); + style.color = 'blue'; + test.ok(1 === style.length, 'length is not 1'); + test.ok('color' === style[0], 'style[0] is not color'); + test.ok('color: blue;' === style.cssText, 'cssText is wrong'); + test.ok('color' === style.item(0), 'item(0) is not color'); + test.ok('blue' === style.color, 'color is not blue'); + style.backgroundColor = 'red'; + test.ok(2 === style.length, 'length is not 2'); + test.ok('color' === style[0], 'style[0] is not color'); + test.ok('background-color' === style[1], 'style[1] is not background-color'); + test.ok('color: blue; background-color: red;' === style.cssText, 'cssText is wrong'); + test.ok('red' === style.backgroundColor, 'backgroundColor is not red'); + style.removeProperty('color'); + test.ok('background-color' === style[0], 'style[0] is not background-color'); + test.done(); + }, + 'Test Shorthand Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(11); + style.background = 'blue url(http://www.example.com/some_img.jpg)'; + test.ok('blue' === style.backgroundColor, 'backgroundColor is not blue'); + test.ok( + 'url(http://www.example.com/some_img.jpg)' === style.backgroundImage, + 'backgroundImage is wrong' + ); + test.ok( + 'blue url(http://www.example.com/some_img.jpg)' === style.background, + 'background is different' + ); + style.border = '0 solid black'; + test.ok('0px' === style.borderWidth, 'borderWidth is not 0px'); + test.ok('solid' === style.borderStyle, 'borderStyle is not solid'); + test.ok('black' === style.borderColor, 'borderColor is not black'); + test.ok('0px' === style.borderTopWidth, 'borderTopWidth is not 0px'); + test.ok('solid' === style.borderLeftStyle, 'borderLeftStyle is not solid'); + test.ok('black' === style.borderBottomColor, 'borderBottomColor is not black'); + style.font = '12em monospace'; + test.ok('12em' === style.fontSize, 'fontSize is not 12em'); + test.ok('monospace' === style.fontFamily, 'fontFamily is not monospace'); + test.done(); + }, + 'Test width and height Properties and null and empty strings': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(9); + style.height = 6; + test.ok('' === style.height, 'height does not remain unset'); + style.width = 0; + test.ok('0px' === style.width, 'width is not 0px'); + style.height = '34%'; + test.ok('34%' === style.height, 'height is not 34%'); + style.height = '100vh'; + test.ok('100vh' === style.height, 'height is not 100vh'); + style.height = '100vw'; + test.ok('100vw' === style.height, 'height is not 100vw'); + style.height = ''; + test.ok(style.length === 1, 'length is not 1'); + test.ok('width: 0px;' === style.cssText, 'cssText is not "width: 0px;"'); + style.width = null; + test.ok(style.length === 0, 'length is not 0'); + test.ok('' === style.cssText, 'cssText is not empty string'); + test.done(); + }, + 'Test Implicit Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(7); + style.borderWidth = 0; + test.ok(1 === style.length, 'length is not 1'); + test.ok('0px' === style.borderWidth, 'borderWidth is not 0px'); + test.ok('0px' === style.borderTopWidth, 'borderTopWidth is not 0px'); + test.ok('0px' === style.borderBottomWidth, 'borderBottomWidth is not 0px'); + test.ok('0px' === style.borderLeftWidth, 'borderLeftWidth is not 0px'); + test.ok('0px' === style.borderRightWidth, 'borderRightWidth is not 0px'); + test.ok( + 'border-width: 0px;' === style.cssText, + 'cssText is not "border-width: 0px", "' + style.cssText + '"' + ); + test.done(); + }, + 'Test Top, Left, Right, Bottom Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(6); + style.top = 0; + style.left = '0%'; + style.right = '5em'; + style.bottom = '12pt'; + test.ok('0px' === style.top, 'top is not 0px'); + test.ok('0%' === style.left, 'left is not 0%'); + test.ok('5em' === style.right, 'right is not 5em'); + test.ok('12pt' === style.bottom, 'bottom is not 12pt'); + test.ok(4 === style.length, 'length is not 4'); + test.ok( + 'top: 0px; left: 0%; right: 5em; bottom: 12pt;' === style.cssText, + 'text is not "top: 0px; left: 0%; right: 5em; bottom: 12pt;"' + ); + test.done(); + }, + 'Test Clear and Clip Properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(10); + style.clear = 'none'; + test.ok('none' === style.clear, 'clear is not none'); + style.clear = 'lfet'; // intentionally wrong + test.ok('none' === style.clear, 'clear is not still none'); + style.clear = 'left'; + test.ok('left' === style.clear, 'clear is not left'); + style.clear = 'right'; + test.ok('right' === style.clear, 'clear is not right'); + style.clear = 'both'; + test.ok('both' === style.clear, 'clear is not both'); + style.clip = 'elipse(5px, 10px)'; + test.ok('' === style.clip, 'clip should not be set'); + test.ok(1 === style.length, 'length is not 1'); + style.clip = 'rect(0, 3Em, 2pt, 50%)'; + test.ok( + 'rect(0px, 3em, 2pt, 50%)' === style.clip, + 'clip is not "rect(0px, 3em, 2pt, 50%)", "' + style.clip + '"' + ); + test.ok(2 === style.length, 'length is not 2'); + test.ok( + 'clear: both; clip: rect(0px, 3em, 2pt, 50%);' === style.cssText, + 'cssText is not "clear: both; clip: rect(0px, 3em, 2pt, 50%);"' + ); + test.done(); + }, + 'Test colors': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(9); + style.color = 'rgba(0,0,0,0)'; + test.ok('rgba(0, 0, 0, 0)' === style.color, 'color is not rgba(0, 0, 0, 0)'); + style.color = 'rgba(5%, 10%, 20%, 0.4)'; + test.ok('rgba(12, 25, 51, 0.4)' === style.color, 'color is not rgba(12, 25, 51, 0.4)'); + style.color = 'rgb(33%, 34%, 33%)'; + test.ok('rgb(84, 86, 84)' === style.color, 'color is not rgb(84, 86, 84)'); + style.color = 'rgba(300, 200, 100, 1.5)'; + test.ok('rgb(255, 200, 100)' === style.color, 'color is not rgb(255, 200, 100) ' + style.color); + style.color = 'hsla(0, 1%, 2%, 0.5)'; + test.ok( + 'hsla(0, 1%, 2%, 0.5)' === style.color, + 'color is not hsla(0, 1%, 2%, 0.5) ' + style.color + ); + style.color = 'hsl(0, 1%, 2%)'; + test.ok('hsl(0, 1%, 2%)' === style.color, 'color is not hsl(0, 1%, 2%) ' + style.color); + style.color = 'rebeccapurple'; + test.ok('rebeccapurple' === style.color, 'color is not rebeccapurple ' + style.color); + style.color = 'transparent'; + test.ok('transparent' === style.color, 'color is not transparent ' + style.color); + style.color = 'currentcolor'; + test.ok('currentcolor' === style.color, 'color is not currentcolor ' + style.color); + test.done(); + }, + 'Test short hand properties with embedded spaces': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(4); + style.background = 'rgb(0, 0, 0) url(/something/somewhere.jpg)'; + test.ok( + 'rgb(0, 0, 0)' === style.backgroundColor, + 'backgroundColor is not rgb(0, 0, 0): ' + style.backgroundColor + ); + test.ok( + 'url(/something/somewhere.jpg)' === style.backgroundImage, + 'backgroundImage is not url(/something/somewhere.jpg): ' + style.backgroundImage + ); + test.ok( + 'background: rgb(0, 0, 0) url(/something/somewhere.jpg);' === style.cssText, + 'cssText is not correct: ' + style.cssText + ); + style = new cssstyle.CSSStyleDeclaration(); + style.border = ' 1px solid black '; + test.ok( + '1px solid black' === style.border, + 'multiple spaces not properly parsed: ' + style.border + ); + test.done(); + }, + 'Setting shorthand properties to an empty string should clear all dependent properties': function( + test + ) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.borderWidth = '1px'; + test.ok( + 'border-width: 1px;' === style.cssText, + 'cssText is not "border-width: 1px;": ' + style.cssText + ); + style.border = ''; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + test.done(); + }, + 'Setting implicit properties to an empty string should clear all dependent properties': function( + test + ) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.borderTopWidth = '1px'; + test.ok( + 'border-top-width: 1px;' === style.cssText, + 'cssText is not "border-top-width: 1px;": ' + style.cssText + ); + style.borderWidth = ''; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + test.done(); + }, + 'Setting a shorthand property, whose shorthands are implicit properties, to an empty string should clear all dependent properties': function( + test + ) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(4); + style.borderTopWidth = '1px'; + test.ok( + 'border-top-width: 1px;' === style.cssText, + 'cssText is not "border-top-width: 1px;": ' + style.cssText + ); + style.border = ''; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + style.borderTop = '1px solid black'; + test.ok( + 'border-top: 1px solid black;' === style.cssText, + 'cssText is not "border-top: 1px solid black;": ' + style.cssText + ); + style.border = ''; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + test.done(); + }, + 'Setting border values to "none" should clear dependent values': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(8); + style.borderTopWidth = '1px'; + test.ok( + 'border-top-width: 1px;' === style.cssText, + 'cssText is not "border-top-width: 1px;": ' + style.cssText + ); + style.border = 'none'; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + style.borderTopWidth = '1px'; + test.ok( + 'border-top-width: 1px;' === style.cssText, + 'cssText is not "border-top-width: 1px;": ' + style.cssText + ); + style.borderTopStyle = 'none'; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + style.borderTopWidth = '1px'; + test.ok( + 'border-top-width: 1px;' === style.cssText, + 'cssText is not "border-top-width: 1px;": ' + style.cssText + ); + style.borderTop = 'none'; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + style.borderTopWidth = '1px'; + style.borderLeftWidth = '1px'; + test.ok( + 'border-top-width: 1px; border-left-width: 1px;' === style.cssText, + 'cssText is not "border-top-width: 1px; border-left-width: 1px;": ' + style.cssText + ); + style.borderTop = 'none'; + test.ok( + 'border-left-width: 1px;' === style.cssText, + 'cssText is not "border-left-width: 1px;": ' + style.cssText + ); + test.done(); + }, + 'Setting border to 0 should be okay': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(1); + style.border = 0; + test.ok('border: 0px;' === style.cssText, 'cssText is not "border: 0px;": ' + style.cssText); + test.done(); + }, + 'Setting values implicit and shorthand properties via cssText and setProperty should propagate to dependent properties': function( + test + ) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(4); + style.cssText = 'border: 1px solid black;'; + test.ok( + 'border: 1px solid black;' === style.cssText, + 'cssText is not "border: 1px solid black;": ' + style.cssText + ); + test.ok( + '1px solid black' === style.borderTop, + 'borderTop is not "1px solid black": ' + style.borderTop + ); + style.border = ''; + test.ok('' === style.cssText, 'cssText is not "": ' + style.cssText); + style.setProperty('border', '1px solid black'); + test.ok( + 'border: 1px solid black;' === style.cssText, + 'cssText is not "border: 1px solid black;": ' + style.cssText + ); + test.done(); + }, + 'Setting opacity should work': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(3); + style.setProperty('opacity', 0.75); + test.ok( + 'opacity: 0.75;' === style.cssText, + 'cssText is not "opacity: 0.75;": ' + style.cssText + ); + style.opacity = '0.50'; + test.ok('opacity: 0.5;' === style.cssText, 'cssText is not "opacity: 0.5;": ' + style.cssText); + style.opacity = 1.0; + test.ok('opacity: 1;' === style.cssText, 'cssText is not "opacity: 1;": ' + style.cssText); + test.done(); + }, + 'Width and height of auto should work': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(4); + style.width = 'auto'; + test.equal(style.cssText, 'width: auto;', 'cssText is not "width: auto;": ' + style.cssText); + test.equal(style.width, 'auto', 'width is not "auto": ' + style.width); + style = new cssstyle.CSSStyleDeclaration(); + style.height = 'auto'; + test.equal(style.cssText, 'height: auto;', 'cssText is not "height: auto;": ' + style.cssText); + test.equal(style.height, 'auto', 'height is not "auto": ' + style.height); + test.done(); + }, + 'Padding and margin should set/clear shorthand properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + var parts = ['Top', 'Right', 'Bottom', 'Left']; + var testParts = function(name, v, V) { + style[name] = v; + for (var i = 0; i < 4; i++) { + var part = name + parts[i]; + test.equal(V[i], style[part], part + ' is not "' + V[i] + '": "' + style[part] + '"'); + } + test.equal(v, style[name], name + ' is not "' + v + '": "' + style[name] + '"'); + style[name] = ''; + }; + test.expect(50); + testParts('padding', '1px', ['1px', '1px', '1px', '1px']); + testParts('padding', '1px 2%', ['1px', '2%', '1px', '2%']); + testParts('padding', '1px 2px 3px', ['1px', '2px', '3px', '2px']); + testParts('padding', '1px 2px 3px 4px', ['1px', '2px', '3px', '4px']); + style.paddingTop = style.paddingRight = style.paddingBottom = style.paddingLeft = '1px'; + testParts('padding', '', ['', '', '', '']); + testParts('margin', '1px', ['1px', '1px', '1px', '1px']); + testParts('margin', '1px auto', ['1px', 'auto', '1px', 'auto']); + testParts('margin', '1px 2% 3px', ['1px', '2%', '3px', '2%']); + testParts('margin', '1px 2px 3px 4px', ['1px', '2px', '3px', '4px']); + style.marginTop = style.marginRight = style.marginBottom = style.marginLeft = '1px'; + testParts('margin', '', ['', '', '', '']); + test.done(); + }, + 'Padding and margin shorthands should set main properties': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + var parts = ['Top', 'Right', 'Bottom', 'Left']; + var testParts = function(name, v, V) { + var expect; + for (var i = 0; i < 4; i++) { + style[name] = v; + style[name + parts[i]] = V; + expect = v.split(/ /); + expect[i] = V; + expect = expect.join(' '); + test.equal(expect, style[name], name + ' is not "' + expect + '": "' + style[name] + '"'); + } + }; + test.expect(12); + testParts('padding', '1px 2px 3px 4px', '10px'); + testParts('margin', '1px 2px 3px 4px', '10px'); + testParts('margin', '1px 2px 3px 4px', 'auto'); + test.done(); + }, + 'Setting a value to 0 should return the string value': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(1); + style.setProperty('fill-opacity', 0); + test.ok('0' === style.fillOpacity, 'fillOpacity is not "0": ' + style.fillOpacity); + test.done(); + }, + 'onChange callback should be called when the cssText changes': function(test) { + var style = new cssstyle.CSSStyleDeclaration(function(cssText) { + test.ok('opacity: 0;' === cssText, 'cssText is not "opacity: 0;": ' + cssText); + test.done(); + }); + test.expect(1); + style.setProperty('opacity', 0); + }, + 'Setting float should work the same as cssFloat': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(1); + style.float = 'left'; + test.ok('left' === style.cssFloat, 'cssFloat is not "left": ' + style.cssFloat); + test.done(); + }, + 'Setting improper css to cssText should not throw': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.cssText = 'color: '; + test.ok('' === style.cssText, "cssText wasn't cleared: " + style.cssText); + style.color = 'black'; + style.cssText = 'float: '; + test.ok('' === style.cssText, "cssText wasn't cleared: " + style.cssText); + test.done(); + }, + 'Make sure url parsing works with quotes': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(3); + style.backgroundImage = 'url(http://some/url/here1.png)'; + test.ok( + 'url(http://some/url/here1.png)' === style.backgroundImage, + "background-image wasn't url(http://some/url/here1.png): " + style.backgroundImage + ); + style.backgroundImage = "url('http://some/url/here2.png')"; + test.ok( + 'url(http://some/url/here2.png)' === style.backgroundImage, + "background-image wasn't url(http://some/url/here2.png): " + style.backgroundImage + ); + style.backgroundImage = 'url("http://some/url/here3.png")'; + test.ok( + 'url(http://some/url/here3.png)' === style.backgroundImage, + "background-image wasn't url(http://some/url/here3.png): " + style.backgroundImage + ); + test.done(); + }, + 'Make sure setting 0 to a padding or margin works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.padding = 0; + test.equal(style.cssText, 'padding: 0px;', 'padding is not 0px'); + style.margin = '1em'; + style.marginTop = '0'; + test.equal(style.marginTop, '0px', 'margin-top is not 0px'); + test.done(); + }, + 'Make sure setting ex units to a padding or margin works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.padding = '1ex'; + test.equal(style.cssText, 'padding: 1ex;', 'padding is not 1ex'); + style.margin = '1em'; + style.marginTop = '0.5ex'; + test.equal(style.marginTop, '0.5ex', 'margin-top is not 0.5ex'); + test.done(); + }, + 'Make sure setting null to background works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.background = 'red'; + test.equal(style.cssText, 'background: red;', 'background is not red'); + style.background = null; + test.equal(style.cssText, '', 'cssText is not empty'); + test.done(); + }, + 'Flex properties should keep their values': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.flexDirection = 'column'; + test.equal(style.cssText, 'flex-direction: column;', 'flex-direction is not column'); + style.flexDirection = 'row'; + test.equal(style.cssText, 'flex-direction: row;', 'flex-direction is not column'); + test.done(); + }, + 'Make sure camelCase properties are not assigned with `.setProperty()`': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(1); + style.setProperty('fontSize', '12px'); + test.equal(style.cssText, '', 'cssText is not empty'); + test.done(); + }, + 'Make sure casing is ignored in `.setProperty()`': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.setProperty('FoNt-SiZe', '12px'); + test.equal(style.fontSize, '12px', 'font-size: 12px'); + test.equal(style.getPropertyValue('font-size'), '12px', 'font-size: 12px'); + test.done(); + }, + 'Support non string entries in border-spacing': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(1); + style.borderSpacing = 0; + test.equal(style.cssText, 'border-spacing: 0px;', 'border-spacing is not 0'); + test.done(); + }, + 'Float should be valid property for `.setProperty()`': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.setProperty('float', 'left'); + test.equal(style.float, 'left'); + test.equal(style.getPropertyValue('float'), 'left', 'float: left'); + test.done(); + }, + 'Make sure flex-shrink works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(3); + style.setProperty('flex-shrink', 0); + test.equal(style.getPropertyValue('flex-shrink'), '0', 'flex-shrink is not 0'); + style.setProperty('flex-shrink', 1); + test.equal(style.getPropertyValue('flex-shrink'), '1', 'flex-shrink is not 1'); + test.equal(style.cssText, 'flex-shrink: 1;', 'flex-shrink cssText is incorrect'); + test.done(); + }, + 'Make sure flex-grow works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(2); + style.setProperty('flex-grow', 2); + test.equal(style.getPropertyValue('flex-grow'), '2', 'flex-grow is not 2'); + test.equal(style.cssText, 'flex-grow: 2;', 'flex-grow cssText is incorrect'); + test.done(); + }, + 'Make sure flex-basis works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(5); + + style.setProperty('flex-basis', 0); + test.equal(style.getPropertyValue('flex-basis'), '0px', 'flex-basis is not 0px'); + + style.setProperty('flex-basis', '250px'); + test.equal(style.getPropertyValue('flex-basis'), '250px', 'flex-basis is not 250px'); + + style.setProperty('flex-basis', '10em'); + test.equal(style.getPropertyValue('flex-basis'), '10em', 'flex-basis is not 10em'); + + style.setProperty('flex-basis', '30%'); + test.equal(style.getPropertyValue('flex-basis'), '30%', 'flex-basis is not 30%'); + + test.equal(style.cssText, 'flex-basis: 30%;', 'flex-basis cssText is incorrect'); + + test.done(); + }, + 'Make sure shorthand flex works': function(test) { + var style = new cssstyle.CSSStyleDeclaration(); + test.expect(19); + + style.setProperty('flex', 'none'); + test.equal(style.getPropertyValue('flex-grow'), '0', 'flex-grow is not 0 if flex: none;'); + test.equal(style.getPropertyValue('flex-shrink'), '0', 'flex-shrink is not 0 if flex: none;'); + test.equal( + style.getPropertyValue('flex-basis'), + 'auto', + 'flex-basis is not `auto` if flex: none;' + ); + style.removeProperty('flex'); + style.removeProperty('flex-basis'); + + style.setProperty('flex', 'auto'); + test.equal(style.getPropertyValue('flex-grow'), '', 'flex-grow is not empty if flex: auto;'); + test.equal( + style.getPropertyValue('flex-shrink'), + '', + 'flex-shrink is not empty if flex: auto;' + ); + test.equal( + style.getPropertyValue('flex-basis'), + 'auto', + 'flex-basis is not `auto` if flex: auto;' + ); + style.removeProperty('flex'); + + style.setProperty('flex', '0 1 250px'); + test.equal(style.getPropertyValue('flex'), '0 1 250px', 'flex value is not `0 1 250px`'); + test.equal(style.getPropertyValue('flex-grow'), '0', 'flex-grow is not 0'); + test.equal(style.getPropertyValue('flex-shrink'), '1', 'flex-shrink is not 1'); + test.equal(style.getPropertyValue('flex-basis'), '250px', 'flex-basis is not 250px'); + style.removeProperty('flex'); + + style.setProperty('flex', '2'); + test.equal(style.getPropertyValue('flex-grow'), '2', 'flex-grow is not 2'); + test.equal(style.getPropertyValue('flex-shrink'), '', 'flex-shrink is not empty'); + test.equal(style.getPropertyValue('flex-basis'), '', 'flex-basis is not empty'); + style.removeProperty('flex'); + + style.setProperty('flex', '20%'); + test.equal(style.getPropertyValue('flex-grow'), '', 'flex-grow is not empty'); + test.equal(style.getPropertyValue('flex-shrink'), '', 'flex-shrink is not empty'); + test.equal(style.getPropertyValue('flex-basis'), '20%', 'flex-basis is not 20%'); + style.removeProperty('flex'); + + style.setProperty('flex', '2 2'); + test.equal(style.getPropertyValue('flex-grow'), '2', 'flex-grow is not 2'); + test.equal(style.getPropertyValue('flex-shrink'), '2', 'flex-shrink is not 2'); + test.equal(style.getPropertyValue('flex-basis'), '', 'flex-basis is not empty'); + style.removeProperty('flex'); + + test.done(); + }, +}; diff --git a/node_modules/dashdash/CHANGES.md b/node_modules/dashdash/CHANGES.md new file mode 100644 index 0000000..d7c8f4e --- /dev/null +++ b/node_modules/dashdash/CHANGES.md @@ -0,0 +1,364 @@ +# node-dashdash changelog + +## not yet released + +(nothing yet) + +## 1.14.1 + +- [issue #30] Change the output used by dashdash's Bash completion support to + indicate "there are no completions for this argument" to cope with different + sorting rules on different Bash/platforms. For example: + + $ triton -v -p test2 package get # before + ##-no -tritonpackage- completions-## + + $ triton -v -p test2 package get # after + ##-no-completion- -results-## + +## 1.14.0 + +- New `synopsisFromOpt(