1
0
mirror of https://github.com/S2-/minifyfromhtml.git synced 2025-08-03 04:10:04 +02:00

update packages to latest version

This commit is contained in:
s2
2022-08-20 18:51:33 +02:00
parent 09663a35a5
commit 806ebf9a57
4513 changed files with 366205 additions and 92512 deletions

1321
node_modules/clean-css/History.md generated vendored

File diff suppressed because it is too large Load Diff

199
node_modules/clean-css/README.md generated vendored
View File

@@ -1,17 +1,17 @@
<h1 align="center">
<br/>
<img src="https://cdn.rawgit.com/jakubpawlowicz/clean-css/master/logo.v2.svg" alt="clean-css logo" width="525px"/>
<img src="./logo.v2.svg" alt="clean-css logo" width="525px"/>
<br/>
<br/>
</h1>
[![npm version](https://img.shields.io/npm/v/clean-css.svg?style=flat)](https://www.npmjs.com/package/clean-css)
[![Build Status](https://img.shields.io/github/workflow/status/jakubpawlowicz/clean-css/Tests/master)](https://github.com/jakubpawlowicz/clean-css/actions?query=workflow%3ATests+branch%3Amaster)
[![PPC Linux Build Status](https://img.shields.io/travis/jakubpawlowicz/clean-css/master.svg?style=flat&label=PPC%20Linux%20build)](https://travis-ci.org/jakubpawlowicz/clean-css)
[![Dependency Status](https://img.shields.io/david/jakubpawlowicz/clean-css.svg?style=flat)](https://david-dm.org/jakubpawlowicz/clean-css)
[![Build Status](https://img.shields.io/github/workflow/status/clean-css/clean-css/Tests/master)](https://github.com/clean-css/clean-css/actions?query=workflow%3ATests+branch%3Amaster)
[![PPC Linux Build Status](https://img.shields.io/travis/clean-css/clean-css/master.svg?style=flat&label=PPC%20Linux%20build)](https://travis-ci.org/clean-css/clean-css)
[![Dependency Status](https://img.shields.io/david/clean-css/clean-css.svg?style=flat)](https://david-dm.org/clean-css/clean-css)
[![npm Downloads](https://img.shields.io/npm/dm/clean-css.svg)](https://npmcharts.com/compare/clean-css?minimal=true)
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).
clean-css is a fast and efficient CSS optimizer for [Node.js](http://nodejs.org/) platform and [any modern browser](https://clean-css.github.io/).
According to [tests](http://goalsmashers.github.io/css-minification-benchmark/) it is one of the best available.
@@ -20,6 +20,7 @@ According to [tests](http://goalsmashers.github.io/css-minification-benchmark/)
- [Node.js version support](#nodejs-version-support)
- [Install](#install)
- [Use](#use)
* [What's new in version 5.3](#whats-new-in-version-53)
* [What's new in version 5.0](#whats-new-in-version-50)
* [What's new in version 4.2](#whats-new-in-version-42)
* [What's new in version 4.1](#whats-new-in-version-41)
@@ -49,6 +50,7 @@ According to [tests](http://goalsmashers.github.io/css-minification-benchmark/)
* [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)
* [What errors and warnings are?](#what-errors-and-warnings-are)
* [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)
@@ -58,7 +60,7 @@ According to [tests](http://goalsmashers.github.io/css-minification-benchmark/)
# Node.js version support
clean-css requires Node.js 6.0+ (tested on Linux, OS X, and Windows)
clean-css requires Node.js 10.0+ (tested on Linux, OS X, and Windows)
# Install
@@ -75,9 +77,15 @@ var options = { /* options */ };
var output = new CleanCSS(options).minify(input);
```
## What's new in version 5.3
clean-css 5.3 introduces one new feature:
* variables can be optimized using level 1's `variableValueOptimizers` option, which accepts a list of [value optimizers](https://github.com/clean-css/clean-css/blob/master/lib/optimizer/level-1/value-optimizers.js) or a list of their names, e.g. `variableValueOptimizers: ['color', 'fraction']`.
## What's new in version 5.0
clean-css 5.0 will introduce some breaking changes:
clean-css 5.0 introduced some breaking changes:
* Node.js 6.x and 8.x are officially no longer supported;
* `transform` callback in level-1 optimizations is removed in favor of new [plugins](#plugins) interface;
@@ -116,13 +124,13 @@ clean-css 4.1 introduces the following changes / features:
* `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.
* the [web interface](https://clean-css.github.io/) gets an improved settings panel with "reset to defaults", instant option changes, and settings being persisted across sessions.
## 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);
* API and CLI interfaces are split, so API stays in this repository while CLI moves to [clean-css-cli](https://github.com/clean-css/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;
@@ -166,7 +174,7 @@ There is a certain number of compatibility mode shortcuts, namely:
* `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:
Each of these modes is an alias to a [fine grained configuration](https://github.com/clean-css/clean-css/blob/master/lib/options/compatibility.js), with the following options available:
```js
new CleanCSS({
@@ -245,7 +253,7 @@ new CleanCSS({
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.
Unless given, the default [loadRemoteResource](https://github.com/clean-css/clean-css/blob/master/lib/reader/load-remote-resource.js) logic is used.
## Formatting options
@@ -408,7 +416,8 @@ new CleanCSS({
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`
tidySelectors: true, // controls selectors optimizing; defaults to `true`,
variableValueOptimizers: [] // controls value optimizers which are applied to variables
}
}
});
@@ -494,7 +503,7 @@ new CleanCSS({plugins: [myPlugin]})
Search `test\module-test.js` for `plugins` or check out `lib/optimizer/level-1/property-optimizers` and `lib/optimizer/level-1/value-optimizers` for more examples.
__Important__: To rewrite your old `transform` as a plugin, check out [this commit](https://github.com/jakubpawlowicz/clean-css/commit/b6ddc523267fc42cf0f6bd1626a79cad97319e17#diff-a71ef45f934725cdb25860dc0b606bcd59e3acee9788cd6df4f9d05339e8a153).
__Important__: To rewrite your old `transform` as a plugin, check out [this commit](https://github.com/clean-css/clean-css/commit/b6ddc523267fc42cf0f6bd1626a79cad97319e17#diff-a71ef45f934725cdb25860dc0b606bcd59e3acee9788cd6df4f9d05339e8a153).
## Minify method
@@ -516,6 +525,38 @@ 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
```
Example: Minifying a CSS string:
```js
const CleanCSS = require("clean-css");
const output = new CleanCSS().minify(`
a {
color: blue;
}
div {
margin: 5px
}
`);
console.log(output);
// Log:
{
styles: 'a{color:#00f}div{margin:5px}',
stats: {
efficiency: 0.6704545454545454,
minifiedSize: 29,
originalSize: 88,
timeSpent: 6
},
errors: [],
inlinedStylesheets: [],
warnings: []
}
```
The `minify` method also accepts an input source map, e.g.
@@ -531,6 +572,16 @@ new CleanCSS(options).minify(source, function (error, output) {
});
```
To optimize a single file, without reading it first, pass a path to it to `minify` method as follows:
```js
var output = new CleanCSS(options).minify(['path/to/file.css'])
```
(if you won't enclose the path in an array, it will be treated as a CSS source instead).
There are several ways to optimize multiple files at the same time, see [How to optimize multiple files?](#how-to-optimize-multiple-files).
## Promise interface
If you prefer clean-css to return a Promise object then you need to explicitely ask for it, e.g.
@@ -544,7 +595,7 @@ new CleanCSS({ returnPromise: true })
## 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.
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/clean-css/clean-css-cli.
# FAQ
@@ -623,7 +674,7 @@ which sets all units rounding precision to 3 digits except `px` unit precision o
## How to optimize a stylesheet with custom `rpx` units?
Since `rpx` is a non standard unit (see [#1074](https://github.com/jakubpawlowicz/clean-css/issues/1074)), it will be dropped by default as an invalid value.
Since `rpx` is a non standard unit (see [#1074](https://github.com/clean-css/clean-css/issues/1074)), it will be dropped by default as an invalid value.
However you can treat `rpx` units as regular ones:
@@ -746,7 +797,7 @@ will apply level 1 optimizations, except url normalization, and default level 2
## 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:
All level 2 optimizations are dispatched [here](https://github.com/clean-css/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;
@@ -760,6 +811,108 @@ All level 2 optimizations are dispatched [here](https://github.com/jakubpawlowic
* `removeDuplicateMediaQueries` - removes duplicated `@media` nested blocks;
* `mergeMediaQueries` - merges non-adjacent `@media` at-rules by the same rules as `mergeNonAdjacentBy*` above;
## What errors and warnings are?
If clean-css encounters invalid CSS, it will try to remove the invalid part and continue optimizing the rest of the code. It will make you aware of the problem by generating an error or warning. Although clean-css can work with invalid CSS, it is always recommended that you fix warnings and errors in your CSS.
Example: Minify invalid CSS, resulting in two warnings:
```js
const CleanCSS = require("clean-css");
const output = new CleanCSS().minify(`
a {
-notarealproperty-: 5px;
color:
}
div {
margin: 5px
}
`);
console.log(output);
// Log:
{
styles: 'div{margin:5px}',
stats: {
efficiency: 0.8695652173913043,
minifiedSize: 15,
originalSize: 115,
timeSpent: 1
},
errors: [],
inlinedStylesheets: [],
warnings: [
"Invalid property name '-notarealproperty-' at 4:8. Ignoring.",
"Empty property 'color' at 5:8. Ignoring."
]
}
```
Example: Minify invalid CSS, resulting in one error:
```js
const CleanCSS = require("clean-css");
const output = new CleanCSS().minify(`
@import "idontexist.css";
a {
color: blue;
}
div {
margin: 5px
}
`);
console.log(output);
// Log:
{
styles: 'a{color:#00f}div{margin:5px}',
stats: {
efficiency: 0.7627118644067796,
minifiedSize: 28,
originalSize: 118,
timeSpent: 2
},
errors: [
'Ignoring local @import of "idontexist.css" as resource is missing.'
],
inlinedStylesheets: [],
warnings: []
}
```
## Clean-css for Gulp
An example of how you can include clean-css in gulp
```js
const { src, dest, series } = require('gulp');
const CleanCSS = require('clean-css');
const concat = require('gulp-concat');
function css() {
const options = {
compatibility: '*', // (default) - Internet Explorer 10+ compatibility mode
inline: ['all'], // enables all inlining, same as ['local', 'remote']
level: 2 // Optimization levels. The level option can be either 0, 1 (default), or 2, e.g.
// Please note that level 1 optimization options are generally safe while level 2 optimizations should be safe for most users.
};
return src('app/**/*.css')
.pipe(concat('style.min.css'))
.on('data', function(file) {
const buferFile = new CleanCSS(options).minify(file.contents)
return file.contents = Buffer.from(buferFile.styles)
})
.pipe(dest('build'))
}
exports.css = series(css)
```
## How to use clean-css with build tools?
There is a number of 3rd party plugins to popular build tools:
@@ -768,7 +921,7 @@ There is a number of 3rd party plugins to popular build tools:
* [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)
* [Gulp](http://gulpjs.com/): [using vinyl-map as a wrapper - courtesy of @sogko](https://github.com/clean-css/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)
@@ -776,20 +929,20 @@ There is a number of 3rd party plugins to popular build tools:
## How to use clean-css from web browser?
* https://jakubpawlowicz.github.io/clean-css/ (official web interface)
* https://clean-css.github.io/ (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).
See [CONTRIBUTING.md](https://github.com/clean-css/clean-css/blob/master/CONTRIBUTING.md).
## How to get started?
First clone the sources:
```bash
git clone git@github.com:jakubpawlowicz/clean-css.git
git clone git@github.com:clean-css/clean-css.git
```
then install dependencies:
@@ -802,7 +955,7 @@ 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 bench # for clean-css benchmarks (see [test/bench.js](https://github.com/clean-css/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
@@ -821,7 +974,7 @@ Sorted alphabetically by GitHub handle:
* [@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;
Plus everyone else involved in [#125](https://github.com/clean-css/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;
@@ -831,4 +984,4 @@ Sorted alphabetically by GitHub handle:
# License
clean-css is released under the [MIT License](https://github.com/jakubpawlowicz/clean-css/blob/master/LICENSE).
clean-css is released under the [MIT License](https://github.com/clean-css/clean-css/blob/master/LICENSE).

125
node_modules/clean-css/lib/clean.js generated vendored
View File

@@ -1,8 +1,6 @@
/**
* Clean-css - https://github.com/jakubpawlowicz/clean-css
* Clean-css - https://github.com/clean-css/clean-css
* Released under the terms of MIT license
*
* Copyright (C) 2017 JakubPawlowicz.com
*/
var level0Optimize = require('./optimizer/level-0/optimize');
@@ -50,14 +48,15 @@ var CleanCSS = module.exports = function CleanCSS(options) {
};
};
// for compatibility with optimize-css-assets-webpack-plugin
CleanCSS.process = function (input, opts) {
CleanCSS.process = function(input, opts) {
var cleanCss;
var optsTo = opts.to;
delete opts.to;
cleanCss = new CleanCSS(Object.assign({ returnPromise: true, rebaseTo: optsTo }, opts));
cleanCss = new CleanCSS(Object.assign({
returnPromise: true, rebaseTo: optsTo
}, opts));
return cleanCss.minify(input)
.then(function(output) {
@@ -65,37 +64,34 @@ CleanCSS.process = function (input, opts) {
});
};
CleanCSS.prototype.minify = function (input, maybeSourceMap, maybeCallback) {
CleanCSS.prototype.minify = function(input, maybeSourceMap, maybeCallback) {
var options = this.options;
if (options.returnPromise) {
return new Promise(function (resolve, reject) {
minifyAll(input, options, maybeSourceMap, function (errors, output) {
return errors ?
reject(errors) :
resolve(output);
return new Promise(function(resolve, reject) {
minifyAll(input, options, maybeSourceMap, function(errors, output) {
return errors
? reject(errors)
: resolve(output);
});
});
} else {
return minifyAll(input, options, maybeSourceMap, maybeCallback);
}
return minifyAll(input, options, maybeSourceMap, maybeCallback);
};
function minifyAll(input, options, maybeSourceMap, maybeCallback) {
if (options.batch && Array.isArray(input)) {
return minifyInBatchesFromArray(input, options, maybeSourceMap, maybeCallback);
} else if (options.batch && (typeof input == 'object')) {
} if (options.batch && (typeof input == 'object')) {
return minifyInBatchesFromHash(input, options, maybeSourceMap, maybeCallback);
} else {
return minify(input, options, maybeSourceMap, maybeCallback);
}
return minify(input, options, maybeSourceMap, maybeCallback);
}
function minifyInBatchesFromArray(input, options, maybeSourceMap, maybeCallback) {
var callback = typeof maybeCallback == 'function' ?
maybeCallback :
(typeof maybeSourceMap == 'function' ? maybeSourceMap : null);
var callback = typeof maybeCallback == 'function'
? maybeCallback
: (typeof maybeSourceMap == 'function' ? maybeSourceMap : null);
var errors = [];
var outputAsHash = {};
var inputValue;
@@ -103,7 +99,10 @@ function minifyInBatchesFromArray(input, options, maybeSourceMap, maybeCallback)
function whenHashBatchDone(innerErrors, output) {
outputAsHash = Object.assign(outputAsHash, output);
errors.concat(innerErrors);
if (innerErrors !== null) {
errors = errors.concat(innerErrors);
}
}
for (i = 0, l = input.length; i < l; i++) {
@@ -113,19 +112,19 @@ function minifyInBatchesFromArray(input, options, maybeSourceMap, maybeCallback)
inputValue = input[i];
outputAsHash[inputValue] = minify([inputValue], options);
errors.concat(outputAsHash[inputValue].errors);
errors = errors.concat(outputAsHash[inputValue].errors);
}
}
return callback ?
callback(errors.length > 0 ? errors : null, outputAsHash) :
outputAsHash;
return callback
? callback(errors.length > 0 ? errors : null, outputAsHash)
: outputAsHash;
}
function minifyInBatchesFromHash(input, options, maybeSourceMap, maybeCallback) {
var callback = typeof maybeCallback == 'function' ?
maybeCallback :
(typeof maybeSourceMap == 'function' ? maybeSourceMap : null);
var callback = typeof maybeCallback == 'function'
? maybeCallback
: (typeof maybeSourceMap == 'function' ? maybeSourceMap : null);
var errors = [];
var outputAsHash = {};
var inputKey;
@@ -135,21 +134,21 @@ function minifyInBatchesFromHash(input, options, maybeSourceMap, maybeCallback)
inputValue = input[inputKey];
outputAsHash[inputKey] = minify(inputValue.styles, options, inputValue.sourceMap);
errors.concat(outputAsHash[inputKey].errors);
errors = errors.concat(outputAsHash[inputKey].errors);
}
return callback ?
callback(errors.length > 0 ? errors : null, outputAsHash) :
outputAsHash;
return callback
? callback(errors.length > 0 ? errors : null, outputAsHash)
: outputAsHash;
}
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 sourceMap = typeof maybeSourceMap != 'function'
? maybeSourceMap
: null;
var callback = typeof maybeCallback == 'function'
? maybeCallback
: (typeof maybeSourceMap == 'function' ? maybeSourceMap : null);
var context = {
stats: {
efficiency: 0,
@@ -158,9 +157,7 @@ function minify(input, options, maybeSourceMap, maybeCallback) {
startedAt: Date.now(),
timeSpent: 0
},
cache: {
specificity: {}
},
cache: { specificity: {} },
errors: [],
inlinedStylesheets: [],
inputSourceMapTracker: inputSourceMapTracker(),
@@ -178,26 +175,25 @@ function minify(input, options, maybeSourceMap, maybeCallback) {
}
if (options.rebase && !options.explicitRebaseTo) {
implicitRebaseToWarning =
'You have set `rebase: true` without giving `rebaseTo` option, which, in this case, defaults to the current working directory. ' +
'You are then warned this can lead to unexpected URL rebasing (aka here be dragons)! ' +
'If you are OK with the clean-css output, then you can get rid of this warning by giving clean-css a `rebaseTo: process.cwd()` option.';
implicitRebaseToWarning = 'You have set `rebase: true` without giving `rebaseTo` option, which, in this case, defaults to the current working directory. '
+ 'You are then warned this can lead to unexpected URL rebasing (aka here be dragons)! '
+ 'If you are OK with the clean-css output, then you can get rid of this warning by giving clean-css a `rebaseTo: process.cwd()` option.';
context.warnings.push(implicitRebaseToWarning);
}
return runner(context.localOnly)(function () {
return readSources(input, context, function (tokens) {
var serialize = context.options.sourceMap ?
serializeStylesAndSourceMap :
serializeStyles;
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;
return callback
? callback(context.errors.length > 0 ? context.errors : null, output)
: output;
});
});
}
@@ -205,21 +201,20 @@ function minify(input, options, maybeSourceMap, maybeCallback) {
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;
return localOnly
? function(callback) { return callback(); }
: process.nextTick;
}
function optimize(tokens, context) {
var optimized;
var optimized = level0Optimize(tokens, context);
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;
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;
}

View File

@@ -38,7 +38,7 @@ var override = require('../utils/override');
// Puts the shorthand together from its components.
//
var configuration = {
'animation': {
animation: {
canOverride: canOverride.generic.components([
canOverride.generic.time,
canOverride.generic.timingFunction,
@@ -200,7 +200,7 @@ var configuration = {
'-webkit-'
]
},
'background': {
background: {
canOverride: canOverride.generic.components([
canOverride.generic.image,
canOverride.property.backgroundPosition,
@@ -341,7 +341,7 @@ var configuration = {
valueOptimizers.zero
]
},
'bottom': {
bottom: {
canOverride: canOverride.property.bottom,
defaultValue: 'auto',
valueOptimizers: [
@@ -352,7 +352,7 @@ var configuration = {
valueOptimizers.zero
]
},
'border': {
border: {
breakUp: breakUp.border,
canOverride: canOverride.generic.components([
canOverride.generic.unit,
@@ -829,11 +829,11 @@ var configuration = {
'-webkit-'
]
},
'clear': {
clear: {
canOverride: canOverride.property.clear,
defaultValue: 'none'
},
'clip': {
clip: {
valueOptimizers: [
valueOptimizers.whiteSpace,
valueOptimizers.fraction,
@@ -842,7 +842,7 @@ var configuration = {
valueOptimizers.zero
]
},
'color': {
color: {
canOverride: canOverride.generic.color,
defaultValue: 'transparent',
shortestValue: 'red',
@@ -861,24 +861,22 @@ var configuration = {
valueOptimizers.zero
]
},
'cursor': {
cursor: {
canOverride: canOverride.property.cursor,
defaultValue: 'auto'
},
'display': {
canOverride: canOverride.property.display,
},
'filter': {
display: { canOverride: canOverride.property.display },
filter: {
propertyOptimizer: propertyOptimizers.filter,
valueOptimizers: [
valueOptimizers.fraction
]
},
'float': {
float: {
canOverride: canOverride.property.float,
defaultValue: 'none'
},
'font': {
font: {
breakUp: breakUp.font,
canOverride: canOverride.generic.components([
canOverride.property.fontStyle,
@@ -937,7 +935,7 @@ var configuration = {
propertyOptimizer: propertyOptimizers.fontWeight,
shortestValue: '400'
},
'gap': {
gap: {
valueOptimizers: [
valueOptimizers.whiteSpace,
valueOptimizers.fraction,
@@ -946,7 +944,7 @@ var configuration = {
valueOptimizers.zero
]
},
'height': {
height: {
canOverride: canOverride.generic.unit,
defaultValue: 'auto',
shortestValue: '0',
@@ -958,7 +956,7 @@ var configuration = {
valueOptimizers.zero
]
},
'left': {
left: {
canOverride: canOverride.property.left,
defaultValue: 'auto',
valueOptimizers: [
@@ -1001,14 +999,14 @@ var configuration = {
shortestValue: 'none',
shorthand: true
},
'list-style-image' : {
'list-style-image': {
canOverride: canOverride.generic.image,
componentOf: [
'list-style'
],
defaultValue: 'none'
},
'list-style-position' : {
'list-style-position': {
canOverride: canOverride.property.listStylePosition,
componentOf: [
'list-style'
@@ -1016,7 +1014,7 @@ var configuration = {
defaultValue: 'outside',
shortestValue: 'inside'
},
'list-style-type' : {
'list-style-type': {
canOverride: canOverride.property.listStyleType,
componentOf: [
'list-style'
@@ -1027,7 +1025,7 @@ var configuration = {
defaultValue: 'decimal|disc',
shortestValue: 'none'
},
'margin': {
margin: {
breakUp: breakUp.fourValues,
canOverride: canOverride.generic.components([
canOverride.generic.unit,
@@ -1183,13 +1181,13 @@ var configuration = {
valueOptimizers.zero
]
},
'opacity': {
opacity: {
valueOptimizers: [
valueOptimizers.fraction,
valueOptimizers.precision
]
},
'outline': {
outline: {
canOverride: canOverride.generic.components([
canOverride.generic.color,
canOverride.property.outlineStyle,
@@ -1248,7 +1246,7 @@ var configuration = {
valueOptimizers.zero
]
},
'overflow': {
overflow: {
canOverride: canOverride.property.overflow,
defaultValue: 'visible'
},
@@ -1260,7 +1258,7 @@ var configuration = {
canOverride: canOverride.property.overflow,
defaultValue: 'visible'
},
'padding': {
padding: {
breakUp: breakUp.fourValues,
canOverride: canOverride.generic.components([
canOverride.generic.unit,
@@ -1326,7 +1324,7 @@ var configuration = {
defaultValue: '0',
oppositeTo: 'padding-left',
propertyOptimizer: propertyOptimizers.padding,
valueOptimizers: [
valueOptimizers: [
valueOptimizers.whiteSpace,
valueOptimizers.fraction,
valueOptimizers.precision,
@@ -1350,11 +1348,11 @@ var configuration = {
valueOptimizers.zero
]
},
'position': {
position: {
canOverride: canOverride.property.position,
defaultValue: 'static'
},
'right': {
right: {
canOverride: canOverride.property.right,
defaultValue: 'auto',
valueOptimizers: [
@@ -1374,7 +1372,7 @@ var configuration = {
valueOptimizers.zero
]
},
'src': {
src: {
valueOptimizers: [
valueOptimizers.urlWhiteSpace,
valueOptimizers.urlPrefix,
@@ -1423,7 +1421,7 @@ var configuration = {
valueOptimizers.color
]
},
'top': {
top: {
canOverride: canOverride.property.top,
defaultValue: 'auto',
valueOptimizers: [
@@ -1434,7 +1432,7 @@ var configuration = {
valueOptimizers.zero
]
},
'transform': {
transform: {
canOverride: canOverride.property.transform,
valueOptimizers: [
valueOptimizers.whiteSpace,
@@ -1451,7 +1449,7 @@ var configuration = {
'-webkit-'
]
},
'transition': {
transition: {
breakUp: breakUp.multiplex(breakUp.transition),
canOverride: canOverride.generic.components([
canOverride.property.transitionProperty,
@@ -1555,7 +1553,7 @@ var configuration = {
valueOptimizers.zero
]
},
'visibility': {
visibility: {
canOverride: canOverride.property.visibility,
defaultValue: 'visible'
},
@@ -1578,7 +1576,7 @@ var configuration = {
canOverride: canOverride.property.whiteSpace,
defaultValue: 'normal'
},
'width': {
width: {
canOverride: canOverride.generic.unit,
defaultValue: 'auto',
shortestValue: '0',
@@ -1603,13 +1601,13 @@ function cloneDescriptor(propertyName, prefix) {
var clonedDescriptor = override(configuration[propertyName], {});
if ('componentOf' in clonedDescriptor) {
clonedDescriptor.componentOf = clonedDescriptor.componentOf.map(function (shorthandName) {
clonedDescriptor.componentOf = clonedDescriptor.componentOf.map(function(shorthandName) {
return prefix + shorthandName;
});
}
if ('components' in clonedDescriptor) {
clonedDescriptor.components = clonedDescriptor.components.map(function (longhandName) {
clonedDescriptor.components = clonedDescriptor.components.map(function(longhandName) {
return prefix + longhandName;
});
}
@@ -1621,8 +1619,6 @@ function cloneDescriptor(propertyName, prefix) {
return clonedDescriptor;
}
var vendorPrefixedConfiguration = {};
for (var propertyName in configuration) {
var descriptor = configuration[propertyName];

View File

@@ -20,13 +20,13 @@ function _anyIsInherit(values) {
}
function _colorFilter(validator) {
return function (value) {
return function(value) {
return value[1] == 'invert' || validator.isColor(value[1]) || validator.isPrefixed(value[1]);
};
}
function _styleFilter(validator) {
return function (value) {
return function(value) {
return value[1] != 'inherit' && validator.isStyleKeyword(value[1]) && !validator.isColorFunction(value[1]);
};
}
@@ -40,27 +40,26 @@ function _wrapDefault(name, property, configuration) {
[Token.PROPERTY_VALUE, descriptor.defaultValue[0]],
[Token.PROPERTY_VALUE, descriptor.defaultValue[1]]
]);
} else if (descriptor.doubleValues && descriptor.defaultValue.length == 1) {
} 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]
]);
}
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]);
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]);
};
}
@@ -88,6 +87,7 @@ function animation(property, configuration, validator) {
var l;
if (property.value.length == 1 && property.value[0][1] == 'inherit') {
// eslint-disable-next-line max-len
duration.value = timing.value = delay.value = iteration.value = direction.value = fill.value = play.value = name.value = property.value;
return components;
}
@@ -108,7 +108,9 @@ function animation(property, configuration, validator) {
} 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) {
} else if ((validator.isAnimationIterationCountKeyword(value[1])
|| validator.isPositiveNumber(value[1]))
&& !iterationSet) {
iteration.value = [value];
iterationSet = true;
} else if (validator.isAnimationDirectionKeyword(value[1]) && !directionSet) {
@@ -152,7 +154,7 @@ function background(property, configuration, validator) {
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;
color.value = image.value = repeat.value = position.value = size.value = origin.value = clip.value = property.value;
return components;
}
@@ -183,7 +185,10 @@ function background(property, configuration, validator) {
repeatSet = true;
}
anyValueSet = true;
} else if (validator.isBackgroundPositionKeyword(value[1]) || validator.isBackgroundSizeKeyword(value[1]) || validator.isUnit(value[1]) || validator.isDynamicUnit(value[1])) {
} 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];
@@ -193,15 +198,13 @@ function background(property, configuration, validator) {
size.value = [previousValue, value];
i -= 2;
} else {
if (!positionSet)
position.value = [];
if (!positionSet) { position.value = []; }
position.value.unshift(value);
positionSet = true;
}
} else {
if (!positionSet)
position.value = [];
if (!positionSet) { position.value = []; }
position.value.unshift(value);
positionSet = true;
@@ -216,8 +219,7 @@ function background(property, configuration, validator) {
}
}
if (clipSet && !originSet)
origin.value = clip.value.slice(0);
if (clipSet && !originSet) { origin.value = clip.value.slice(0); }
if (!anyValueSet) {
throw new InvalidPropertyError('Invalid background value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
@@ -242,15 +244,15 @@ function borderRadius(property, configuration) {
}
var target = _wrapDefault(property.name, property, configuration);
target.value = splitAt > -1 ?
values.slice(0, splitAt) :
values.slice(0);
target.value = splitAt > -1
? values.slice(0, splitAt)
: values.slice(0);
target.components = fourValues(target, configuration);
var remainder = _wrapDefault(property.name, property, configuration);
remainder.value = splitAt > -1 ?
values.slice(splitAt + 1) :
values.slice(0);
remainder.value = splitAt > -1
? values.slice(splitAt + 1)
: values.slice(0);
remainder.components = fourValues(remainder, configuration);
for (var j = 0; j < 4; j++) {
@@ -281,7 +283,6 @@ function font(property, configuration, validator) {
var isVariantValid;
var isWeightSet = false;
var isWeightValid;
var isSizeSet = false;
var appendableFamilyName = false;
if (!values[index]) {
@@ -293,7 +294,11 @@ function font(property, configuration, validator) {
return components;
}
if (values.length == 1 && (validator.isFontKeyword(values[0][1]) || validator.isGlobal(values[0][1]) || validator.isPrefixed(values[0][1]))) {
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;
@@ -326,7 +331,14 @@ function font(property, configuration, validator) {
} else if (isStretchValid && !isStretchSet) {
stretch.value = [values[index]];
isStretchSet = true;
} else if (isStyleValid && isStyleSet || isVariantValid && isVariantSet || isWeightValid && isWeightSet || isStretchValid && isStretchSet) {
} 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;
@@ -336,9 +348,10 @@ function font(property, configuration, validator) {
}
// now comes font-size ...
if (validator.isFontSizeKeyword(values[index][1]) || validator.isUnit(values[index][1]) && !validator.isDynamicUnit(values[index][1])) {
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.');
@@ -349,7 +362,12 @@ function font(property, configuration, validator) {
}
// ... 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]))) {
if (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++;
@@ -388,7 +406,10 @@ function _anyIsFontSize(values, validator) {
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])) {
if (validator.isFontSizeKeyword(value[1])
|| validator.isUnit(value[1])
&& !validator.isDynamicUnit(value[1])
|| validator.isFunction(value[1])) {
return true;
}
}
@@ -416,15 +437,11 @@ function fourValues(property, configuration) {
var components = [];
var value = property.value;
if (value.length < 1)
return [];
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);
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([
@@ -439,19 +456,17 @@ function fourValues(property, configuration) {
}
function multiplex(splitWith) {
return function (property, configuration, validator) {
return function(property, configuration, 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 (values[i][1] == ',') { splitsAt.push(i); }
}
if (splitsAt.length === 0)
return splitWith(property, configuration, validator);
if (splitsAt.length === 0) { return splitWith(property, configuration, validator); }
var splitComponents = [];
@@ -463,7 +478,9 @@ function multiplex(splitWith) {
var _property = _wrapDefault(property.name, property, configuration);
_property.value = values.slice(from, to);
splitComponents.push(splitWith(_property, configuration, validator));
if (_property.value.length > 0) {
splitComponents.push(splitWith(_property, configuration, validator));
}
}
var components = splitComponents[0];
@@ -582,16 +599,11 @@ function widthStyleColor(property, configuration, validator) {
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 (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')) {
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;
}

View File

@@ -1,9 +1,10 @@
var understandable = require('./properties/understandable');
function animationIterationCount(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2))) {
if (!understandable(validator, value1, value2, 0, true)
&& !(validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2))) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -11,9 +12,10 @@ function animationIterationCount(validator, value1, value2) {
}
function animationName(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2))) {
if (!understandable(validator, value1, value2, 0, true)
&& !(validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2))) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -33,17 +35,17 @@ function areSameFunction(validator, value1, value2) {
if (validator.isFunction(function1Value) || validator.isFunction(function2Value)) {
return function1Name === function2Name && areSameFunction(validator, function1Value, function2Value);
} else {
return function1Name === function2Name;
}
return function1Name === function2Name;
}
function backgroundPosition(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2))) {
if (!understandable(validator, value1, value2, 0, true)
&& !(validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2))) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2)) {
} if (validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2)) {
return true;
}
@@ -51,11 +53,12 @@ function backgroundPosition(validator, value1, value2) {
}
function backgroundSize(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))) {
if (!understandable(validator, value1, value2, 0, true)
&& !(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2)) {
} if (validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2)) {
return true;
}
@@ -65,15 +68,15 @@ function backgroundSize(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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (!validator.colorOpacity && (validator.isRgbColor(value1) || validator.isHslColor(value1))) {
} if (!validator.colorOpacity && (validator.isRgbColor(value1) || validator.isHslColor(value1))) {
return false;
} else if (!validator.colorOpacity && (validator.isRgbColor(value2) || validator.isHslColor(value2))) {
} if (!validator.colorOpacity && (validator.isRgbColor(value2) || validator.isHslColor(value2))) {
return false;
} else if (!validator.colorHexAlpha && (validator.isHexAlphaColor(value1) || validator.isHexAlphaColor(value2))) {
} if (!validator.colorHexAlpha && (validator.isHexAlphaColor(value1) || validator.isHexAlphaColor(value2))) {
return false;
} else if (validator.isColor(value1) && validator.isColor(value2)) {
} if (validator.isColor(value1) && validator.isColor(value2)) {
return true;
}
@@ -81,7 +84,7 @@ function color(validator, value1, value2) {
}
function components(overrideCheckers) {
return function (validator, value1, value2, position) {
return function(validator, value1, value2, position) {
return overrideCheckers[position](validator, value1, value2);
};
}
@@ -93,11 +96,11 @@ function fontFamily(validator, value1, value2) {
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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isImage(value2)) {
} if (validator.isImage(value2)) {
return true;
} else if (validator.isImage(value1)) {
} if (validator.isImage(value1)) {
return false;
}
@@ -108,7 +111,7 @@ 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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -118,9 +121,10 @@ function keyword(propertyName) {
function keywordWithGlobal(propertyName) {
return function(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isKeyword(propertyName)(value2) || validator.isGlobal(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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -131,7 +135,7 @@ function keywordWithGlobal(propertyName) {
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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -139,15 +143,18 @@ function propertyName(validator, value1, value2) {
}
function sameFunctionOrValue(validator, value1, value2) {
return areSameFunction(validator, value1, value2) ?
true :
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))) {
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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -157,15 +164,18 @@ function textShadow(validator, value1, 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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isTime(value1) && !validator.isTime(value2)) {
} if (validator.isTime(value1) && !validator.isTime(value2)) {
return false;
} else if (validator.isTime(value2)) {
} if (validator.isTime(value2)) {
return true;
} else if (validator.isTime(value1)) {
} if (validator.isTime(value1)) {
return false;
} else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
} if (validator.isFunction(value1)
&& !validator.isPrefixed(value1)
&& validator.isFunction(value2)
&& !validator.isPrefixed(value2)) {
return true;
}
@@ -173,9 +183,10 @@ function time(validator, value1, value2) {
}
function timingFunction(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isTimingFunction(value2) || validator.isGlobal(value2))) {
if (!understandable(validator, value1, value2, 0, true)
&& !(validator.isTimingFunction(value2) || validator.isGlobal(value2))) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
@@ -185,15 +196,18 @@ function timingFunction(validator, value1, 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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isUnit(value1) && !validator.isUnit(value2)) {
} if (validator.isUnit(value1) && !validator.isUnit(value2)) {
return false;
} else if (validator.isUnit(value2)) {
} if (validator.isUnit(value2)) {
return true;
} else if (validator.isUnit(value1)) {
} if (validator.isUnit(value1)) {
return false;
} else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
} if (validator.isFunction(value1)
&& !validator.isPrefixed(value1)
&& validator.isFunction(value2)
&& !validator.isPrefixed(value2)) {
return true;
}
@@ -209,17 +223,25 @@ function unitOrKeywordWithGlobal(propertyName) {
}
function unitOrNumber(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isNumber(value2))) {
if (!understandable(validator, value1, value2, 0, true)
&& !(validator.isUnit(value2)
|| validator.isNumber(value2))) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if ((validator.isUnit(value1) || validator.isNumber(value1)) && !(validator.isUnit(value2) || validator.isNumber(value2))) {
} if ((validator.isUnit(value1)
|| validator.isNumber(value1))
&& !(validator.isUnit(value2)
|| validator.isNumber(value2))) {
return false;
} else if (validator.isUnit(value2) || validator.isNumber(value2)) {
} if (validator.isUnit(value2) || validator.isNumber(value2)) {
return true;
} else if (validator.isUnit(value1) || validator.isNumber(value1)) {
} if (validator.isUnit(value1) || validator.isNumber(value1)) {
return false;
} else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
} if (validator.isFunction(value1)
&& !validator.isPrefixed(value1)
&& validator.isFunction(value2)
&& !validator.isPrefixed(value2)) {
return true;
}
@@ -229,7 +251,7 @@ function unitOrNumber(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)) {
} if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}

View File

@@ -7,8 +7,7 @@ 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;
if (value != 'inherit' && value != Marker.COMMA && value != Marker.FORWARD_SLASH) { return false; }
}
return true;
@@ -27,12 +26,16 @@ function background(property, configuration, lastInMultiplex) {
var descriptor = configuration[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;
return component.value[0][1] == descriptor.defaultValue[0]
&& (component.value[1]
? component.value[1][1] == descriptor.defaultValue[0]
: true);
} 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]);
}
return component.value[0][1] == descriptor.defaultValue;
}
for (var i = components.length - 1; i >= 0; i--) {
@@ -46,9 +49,9 @@ function background(property, configuration, lastInMultiplex) {
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]));
(isOriginDefault && !isDefault)
|| (!isOriginDefault && !isDefault)
|| (!isOriginDefault && isDefault && component.value[0][1] != originComponent.value[0][1]));
if (needsOne) {
restoreValue(originComponent);
@@ -64,8 +67,8 @@ function background(property, configuration, lastInMultiplex) {
needsOne = !isPositionDefault && isDefault;
needsBoth = !needsOne &&
(isPositionDefault && !isDefault || !isPositionDefault && !isDefault);
needsBoth = !needsOne
&& (isPositionDefault && !isDefault || !isPositionDefault && !isDefault);
if (needsOne) {
restoreValue(positionComponent);
@@ -79,26 +82,22 @@ function background(property, configuration, lastInMultiplex) {
i--;
} else {
if (isDefault || configuration[component.name].multiplexLastOnly && !lastInMultiplex)
continue;
if (isDefault || configuration[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 && property.value.length == 1 && property.value[0][1] == '0') { restored.push(property.value[0]); }
if (restored.length === 0)
restored.push([Token.PROPERTY_VALUE, configuration[property.name].defaultValue]);
if (restored.length === 0) { restored.push([Token.PROPERTY_VALUE, configuration[property.name].defaultValue]); }
if (isInheritOnly(restored))
return [restored[0]];
if (isInheritOnly(restored)) { return [restored[0]]; }
return restored;
}
function borderRadius(property, configuration) {
function borderRadius(property) {
if (property.multiplex) {
var horizontal = shallowClone(property);
var vertical = shallowClone(property);
@@ -118,21 +117,19 @@ function borderRadius(property, configuration) {
vertical.components.push(verticalComponent);
}
var horizontalValues = fourValues(horizontal, configuration);
var verticalValues = fourValues(vertical, configuration);
var horizontalValues = fourValues(horizontal);
var verticalValues = fourValues(vertical);
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)) {
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, configuration);
return horizontalValues.concat([[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]).concat(verticalValues);
}
return fourValues(property);
}
function font(property, configuration) {
@@ -197,19 +194,17 @@ function fourValues(property) {
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]) {
} if (value1[1] == value3[1] && value2[1] == value4[1]) {
return [value1, value2];
} else if (value2[1] == value4[1]) {
} if (value2[1] == value4[1]) {
return [value1, value2, value3];
} else {
return [value1, value2, value3, value4];
}
return [value1, value2, value3, value4];
}
function multiplex(restoreWith) {
return function (property, configuration) {
if (!property.multiplex)
return restoreWith(property, configuration, true);
return function(property, configuration) {
if (!property.multiplex) { return restoreWith(property, configuration, true); }
var multiplexSize = 0;
var restored = [];
@@ -218,8 +213,7 @@ function multiplex(restoreWith) {
// 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++;
if (property.components[0].value[i][1] == Marker.COMMA) { multiplexSize++; }
}
for (i = 0; i <= multiplexSize; i++) {
@@ -248,8 +242,7 @@ function multiplex(restoreWith) {
var _restored = restoreWith(_property, configuration, lastInMultiplex);
Array.prototype.push.apply(restored, _restored);
if (i < multiplexSize)
restored.push([Token.PROPERTY_VALUE, Marker.COMMA]);
if (i < multiplexSize) { restored.push([Token.PROPERTY_VALUE, Marker.COMMA]); }
}
return restored;
@@ -269,11 +262,9 @@ function withoutDefaults(property, configuration) {
}
}
if (restored.length === 0)
restored.push([Token.PROPERTY_VALUE, configuration[property.name].defaultValue]);
if (restored.length === 0) { restored.push([Token.PROPERTY_VALUE, configuration[property.name].defaultValue]); }
if (isInheritOnly(restored))
return [restored[0]];
if (isInheritOnly(restored)) { return [restored[0]]; }
return restored;
}

View File

@@ -25,10 +25,10 @@ var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i');
var DEFAULT_ROUNDING_PRECISION = require('../../options/rounding-precision').DEFAULT;
var PROPERTY_NAME_PATTERN = /^(?:\-chrome\-|\-[\w\-]+\w|\w[\w\-]+\w|\w{1,}|\-\-\S+)$/;
var VARIABLE_PROPERTY_NAME_PATTERN = /^--\S+$/;
var PROPERTY_NAME_PATTERN = /^(?:-chrome-|-[\w-]+\w|\w[\w-]+\w|\w{1,})$/;
var IMPORT_PREFIX_PATTERN = /^@import/i;
var URL_PREFIX_PATTERN = /^url\(/i;
var VARIABLE_NAME_PATTERN = /^--\S+$/;
function startsAsUrl(value) {
return URL_PREFIX_PATTERN.test(value);
@@ -44,16 +44,17 @@ function isLegacyFilter(property) {
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;
return value.indexOf('progid') > -1
|| value.indexOf('alpha') === 0
|| value.indexOf('chroma') === 0;
}
return false;
}
function noop() {}
function noopValueOptimizer(_name, value, _options) { return value; }
function optimizeBody(rule, properties, context) {
var options = context.options;
var valueOptimizers;
@@ -64,9 +65,9 @@ function optimizeBody(rule, properties, context) {
var _properties = wrapForOptimizing(properties);
var pluginValueOptimizers = context.options.plugins.level1Value;
var pluginPropertyOptimizers = context.options.plugins.level1Property;
var isVariable;
var i, l;
propertyLoop:
for (i = 0, l = _properties.length; i < l; i++) {
var j, k, m, n;
@@ -74,8 +75,15 @@ function optimizeBody(rule, properties, context) {
name = property.name;
propertyOptimizer = configuration[name] && configuration[name].propertyOptimizer || noop;
valueOptimizers = configuration[name] && configuration[name].valueOptimizers || [optimizers.whiteSpace];
isVariable = VARIABLE_PROPERTY_NAME_PATTERN.test(name);
if (!PROPERTY_NAME_PATTERN.test(name)) {
if (isVariable) {
valueOptimizers = options.variableOptimizers.length > 0
? options.variableOptimizers
: [optimizers.whiteSpace];
}
if (!isVariable && !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;
@@ -90,9 +98,10 @@ function optimizeBody(rule, properties, context) {
}
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.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;
continue;
}
@@ -107,11 +116,6 @@ function optimizeBody(rule, properties, context) {
continue;
}
if (VARIABLE_NAME_PATTERN.test(name)) {
continue;
}
valuesLoop:
for (j = 0, m = property.value.length; j < m; j++) {
type = property.value[j][0];
value = property.value[j][1];
@@ -186,11 +190,9 @@ function cleanupCharsets(tokens) {
for (var i = 0, l = tokens.length; i < l; i++) {
var token = tokens[i];
if (token[0] != Token.AT_RULE)
continue;
if (token[0] != Token.AT_RULE) { continue; }
if (!CHARSET_REGEXP.test(token[1]))
continue;
if (!CHARSET_REGEXP.test(token[1])) { continue; }
if (hasCharset || token[1].indexOf(CHARSET_TOKEN) == -1) {
tokens.splice(i, 1);
@@ -208,7 +210,7 @@ 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) {
otherUnits.forEach(function(unit) {
if (options.compatibility.units[unit]) {
units.push(unit);
}
@@ -220,7 +222,7 @@ function buildUnitRegexp(options) {
function buildPrecisionOptions(roundingPrecision) {
var precisionOptions = {
matcher: null,
units: {},
units: {}
};
var optimizable = [];
var unit;
@@ -232,7 +234,7 @@ function buildPrecisionOptions(roundingPrecision) {
if (value != DEFAULT_ROUNDING_PRECISION) {
precisionOptions.units[unit] = {};
precisionOptions.units[unit].value = value;
precisionOptions.units[unit].multiplier = Math.pow(10, value);
precisionOptions.units[unit].multiplier = 10 ** value;
optimizable.push(unit);
}
@@ -240,13 +242,23 @@ function buildPrecisionOptions(roundingPrecision) {
if (optimizable.length > 0) {
precisionOptions.enabled = true;
precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\W)', 'g');
precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\\W)', 'g');
precisionOptions.zeroMatcher = new RegExp('(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')', 'g');
}
return precisionOptions;
}
function buildVariableOptimizers(options) {
return options.level[OptimizationLevel.One].variableValueOptimizers.map(function(optimizer) {
if (typeof (optimizer) == 'string') {
return optimizers[optimizer] || noopValueOptimizer;
}
return optimizer;
});
}
function level1Optimize(tokens, context) {
var options = context.options;
var levelOptions = options.level[OptimizationLevel.One];
@@ -260,37 +272,43 @@ function level1Optimize(tokens, context) {
options.unitsRegexp = options.unitsRegexp || buildUnitRegexp(options);
options.precision = options.precision || buildPrecisionOptions(levelOptions.roundingPrecision);
options.commentsKept = options.commentsKept || 0;
options.variableOptimizers = options.variableOptimizers || buildVariableOptimizers(options);
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;
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))) {
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--;

View File

@@ -16,9 +16,12 @@ var plugin = {
}
if (property.value.length == 1) {
property.value[0][1] = property.value[0][1].replace(ALPHA_OR_CHROMA_FILTER_PATTERN, function (match, filter, suffix) {
return filter.toLowerCase() + suffix;
});
property.value[0][1] = property.value[0][1].replace(
ALPHA_OR_CHROMA_FILTER_PATTERN,
function(match, filter, suffix) {
return filter.toLowerCase() + suffix;
}
);
}
property.value[0][1] = property.value[0][1]

View File

@@ -16,7 +16,13 @@ var plugin = {
}
// remove negative paddings
if (options.level[OptimizationLevel.One].removeNegativePaddings && (isNegative(property.value[0]) || isNegative(property.value[1]) || isNegative(property.value[2]) || isNegative(property.value[3]))) {
if (options.level[OptimizationLevel.One].removeNegativePaddings
&& (
isNegative(property.value[0])
|| isNegative(property.value[1])
|| isNegative(property.value[2])
|| isNegative(property.value[3])
)) {
property.unused = true;
}
}

View File

@@ -10,13 +10,13 @@ function standardSorter(scope1, scope2) {
function sortSelectors(selectors, method) {
switch (method) {
case 'natural':
return selectors.sort(naturalSorter);
case 'standard':
return selectors.sort(standardSorter);
case 'none':
case false:
return selectors;
case 'natural':
return selectors.sort(naturalSorter);
case 'standard':
return selectors.sort(standardSorter);
case 'none':
case false:
return selectors;
}
}

View File

@@ -9,7 +9,7 @@ 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 RELATION_PATTERN = /[>+~]/;
var WHITESPACE_PATTERN = /\s/;
var ASTERISK_PLUS_HTML_HACK = '*+html ';
@@ -42,7 +42,12 @@ function hasInvalidCharacters(value) {
// 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)) {
} 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)) {
@@ -86,9 +91,10 @@ function removeWhitespace(value, format) {
isQuoted = isSingleQuoted || isDoubleQuoted;
isRelation = !isAttribute && !isEscaped && roundBracketLevel === 0 && RELATION_PATTERN.test(character);
isWhitespace = WHITESPACE_PATTERN.test(character);
isSpaceAwarePseudoClass = roundBracketLevel == 1 && character == Marker.CLOSE_ROUND_BRACKET ?
false :
isSpaceAwarePseudoClass || (roundBracketLevel === 0 && character == Marker.COLON && isPseudoClassWithSelectors(value, i));
isSpaceAwarePseudoClass = roundBracketLevel == 1 && character == Marker.CLOSE_ROUND_BRACKET
? false
: isSpaceAwarePseudoClass
|| (roundBracketLevel === 0 && character == Marker.COLON && isPseudoClassWithSelectors(value, i));
if (wasEscaped && isQuoted && isNewLineWin) {
// swallow escaped new windows lines in comments
@@ -157,9 +163,9 @@ function removeWhitespace(value, format) {
wasComma = character == Marker.COMMA;
}
return withCaseAttribute ?
stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]') :
stripped.join('');
return withCaseAttribute
? stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]')
: stripped.join('');
}
function isPseudoClassWithSelectors(value, colonPosition) {
@@ -180,6 +186,22 @@ function removeQuotes(value) {
.replace(DOUBLE_QUOTE_PATTERN, '=$1$2');
}
function replacePseudoClasses(value) {
return value
.replace('nth-child(1)', 'first-child')
.replace('nth-of-type(1)', 'first-of-type')
.replace('nth-of-type(even)', 'nth-of-type(2n)')
.replace('nth-child(even)', 'nth-child(2n)')
.replace('nth-of-type(2n+1)', 'nth-of-type(odd)')
.replace('nth-child(2n+1)', 'nth-child(odd)')
.replace('nth-last-child(1)', 'last-child')
.replace('nth-last-of-type(1)', 'last-of-type')
.replace('nth-last-of-type(even)', 'nth-last-of-type(2n)')
.replace('nth-last-child(even)', 'nth-last-child(2n)')
.replace('nth-last-of-type(2n+1)', 'nth-last-of-type(odd)')
.replace('nth-last-child(2n+1)', 'nth-last-child(odd)');
}
function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
var list = [];
var repeated = [];
@@ -217,14 +239,16 @@ function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
if (reduced.indexOf('*') > -1) {
reduced = reduced
.replace(/\*([:#\.\[])/g, '$1')
.replace(/^(\:first\-child)?\+html/, '*$1+html');
.replace(/\*([:#.[])/g, '$1')
.replace(/^(:first-child)?\+html/, '*$1+html');
}
if (repeated.indexOf(reduced) > -1) {
continue;
}
reduced = replacePseudoClasses(reduced);
rule[1] = reduced;
repeated.push(reduced);
list.push(rule);

View File

@@ -4,14 +4,14 @@ var shortenRgb = require('./color/shorten-rgb');
var split = require('../../../utils/split');
var ANY_COLOR_FUNCTION_PATTERN = /(rgb|rgba|hsl|hsla)\(([^\(\)]+)\)/gi;
var ANY_COLOR_FUNCTION_PATTERN = /(rgb|rgba|hsl|hsla)\(([^()]+)\)/gi;
var COLOR_PREFIX_PATTERN = /#|rgb|hsl/gi;
var HEX_LONG_PATTERN = /(^|[^='"])#([0-9a-f]{6})/gi;
var HEX_SHORT_PATTERN = /(^|[^='"])#([0-9a-f]{3})/gi;
var HEX_VALUE_PATTERN = /[0-9a-f]/i;
var HSL_PATTERN = /hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/gi;
var RGBA_HSLA_PATTERN = /(rgb|hsl)a?\((\-?\d+),(\-?\d+\%?),(\-?\d+\%?),(0*[1-9]+[0-9]*(\.?\d*)?)\)/gi;
var RGB_PATTERN = /rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/gi;
var RGBA_HSLA_PATTERN = /(rgb|hsl)a?\((-?\d+),(-?\d+%?),(-?\d+%?),(0*[1-9]+[0-9]*(\.?\d*)?)\)/gi;
var RGB_PATTERN = /rgb\((-?\d+),(-?\d+),(-?\d+)\)/gi;
var TRANSPARENT_FUNCTION_PATTERN = /(?:rgba|hsla)\(0,0%?,0%?,0\)/g;
var plugin = {
@@ -26,36 +26,35 @@ var plugin = {
}
value = value
.replace(RGBA_HSLA_PATTERN, function (match, colorFn, p1, p2, p3, alpha) {
return (parseInt(alpha, 10) >= 1 ? colorFn + '(' + [p1,p2,p3].join(',') + ')' : match);
.replace(RGBA_HSLA_PATTERN, function(match, colorFn, p1, p2, p3, alpha) {
return (parseInt(alpha) >= 1 ? colorFn + '(' + [p1, p2, p3].join(',') + ')' : match);
})
.replace(RGB_PATTERN, function (match, red, green, blue) {
.replace(RGB_PATTERN, function(match, red, green, blue) {
return shortenRgb(red, green, blue);
})
.replace(HSL_PATTERN, function (match, hue, saturation, lightness) {
.replace(HSL_PATTERN, function(match, hue, saturation, lightness) {
return shortenHsl(hue, saturation, lightness);
})
.replace(HEX_LONG_PATTERN, function (match, prefix, color, at, inputValue) {
.replace(HEX_LONG_PATTERN, 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]) {
} 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();
}
return (prefix + '#' + color).toLowerCase();
})
.replace(HEX_SHORT_PATTERN, function (match, prefix, color) {
.replace(HEX_SHORT_PATTERN, function(match, prefix, color) {
return prefix + '#' + color.toLowerCase();
})
.replace(ANY_COLOR_FUNCTION_PATTERN, function (match, colorFunction, colorDef) {
.replace(ANY_COLOR_FUNCTION_PATTERN, function(match, colorFunction, colorDef) {
var tokens = colorDef.split(',');
var colorFnLowercase = colorFunction && colorFunction.toLowerCase();
var applies = (colorFnLowercase == 'hsl' && tokens.length == 3) ||
(colorFnLowercase == 'hsla' && tokens.length == 4) ||
(colorFnLowercase == 'rgb' && tokens.length === 3 && colorDef.indexOf('%') > 0) ||
(colorFnLowercase == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0);
var applies = (colorFnLowercase == 'hsl' && tokens.length == 3)
|| (colorFnLowercase == 'hsla' && tokens.length == 4)
|| (colorFnLowercase == 'rgb' && tokens.length === 3 && colorDef.indexOf('%') > 0)
|| (colorFnLowercase == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0);
if (!applies) {
return match;
@@ -73,7 +72,7 @@ var plugin = {
});
if (options.compatibility.colors.opacity && name.indexOf('background') == -1) {
value = value.replace(TRANSPARENT_FUNCTION_PATTERN, function (match) {
value = value.replace(TRANSPARENT_FUNCTION_PATTERN, function(match) {
if (split(value, ',').pop().indexOf('gradient(') > -1) {
return match;
}

View File

@@ -181,9 +181,9 @@ function shortenHex(value) {
shortened = shortened.replace(toHexPattern, hexConverter);
}
return hasHex ?
shortened.replace(toNamePattern, nameConverter) :
shortened;
return hasHex
? shortened.replace(toNamePattern, nameConverter)
: shortened;
}
module.exports = shortenHex;

View File

@@ -5,44 +5,37 @@ 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 %= 360;
if (h < 0) { h += 360; }
h = ~~h / 360;
if (s < 0)
s = 0;
else if (s > 100)
s = 100;
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;
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 q = l < 0.5
? l * (1 + s)
: l + s - l * s;
var p = 2 * l - q;
r = hueToRgb(p, q, h + 1/3);
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1/3);
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;
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;
}
@@ -52,10 +45,10 @@ function shortenHsl(hue, saturation, lightness) {
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);
return '#'
+ ((redAsHex.length == 1 ? '0' : '') + redAsHex)
+ ((greenAsHex.length == 1 ? '0' : '') + greenAsHex)
+ ((blueAsHex.length == 1 ? '0' : '') + blueAsHex);
}
module.exports = shortenHsl;

View File

@@ -1,13 +1,62 @@
var split = require('../../../utils/split');
var startsAsUrl = require('./starts-as-url');
var OptimizationLevel = require('../../../options/optimization-level').OptimizationLevel;
var EXPRESSION_PATTERN = /^expression\(.*\)$/;
var ANY_FUNCTION_PATTERN = /^(-(?:moz|ms|o|webkit)-[a-z-]+|[a-z-]+)\((.+)\)$/;
var TOKEN_SEPARATOR_PATTERN = /([\s,/])/;
var DOT_ZERO_PATTERN = /(^|\D)\.0+(\D|$)/g;
var FRACTION_PATTERN = /\.([1-9]*)0+(\D|$)/g;
var LEADING_ZERO_FRACTION_PATTERN = /(^|\D)0\.(\d)/g;
var MINUS_ZERO_FRACTION_PATTERN = /([^\w\d\-]|^)\-0([^\.]|$)/g;
var MINUS_ZERO_FRACTION_PATTERN = /([^\w\d-]|^)-0([^.]|$)/g;
var ZERO_PREFIXED_UNIT_PATTERN = /(^|\s)0+([1-9])/g;
function optimizeRecursively(value) {
var functionTokens;
var tokens;
if (startsAsUrl(value)) {
return value;
}
if (EXPRESSION_PATTERN.test(value)) {
return value;
}
functionTokens = ANY_FUNCTION_PATTERN.exec(value);
if (!functionTokens) {
return optimizeFractions(value);
}
tokens = split(functionTokens[2], TOKEN_SEPARATOR_PATTERN)
.map(function(token) { return optimizeRecursively(token); });
return functionTokens[1] + '(' + tokens.join('') + ')';
}
function optimizeFractions(value) {
if (value.indexOf('0') == -1) {
return value;
}
if (value.indexOf('-') > -1) {
value = value
.replace(MINUS_ZERO_FRACTION_PATTERN, '$10$2')
.replace(MINUS_ZERO_FRACTION_PATTERN, '$10$2');
}
return value
.replace(ZERO_PREFIXED_UNIT_PATTERN, '$1$2')
.replace(DOT_ZERO_PATTERN, '$10$2')
.replace(FRACTION_PATTERN, function(match, nonZeroPart, suffix) {
return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix;
})
.replace(LEADING_ZERO_FRACTION_PATTERN, '$1.$2');
}
var plugin = {
level1: {
value: function fraction(name, value, options) {
@@ -15,27 +64,7 @@ var plugin = {
return value;
}
if (startsAsUrl(value)) {
return value;
}
if (value.indexOf('0') == -1) {
return value;
}
if (value.indexOf('-') > -1) {
value = value
.replace(MINUS_ZERO_FRACTION_PATTERN, '$10$2')
.replace(MINUS_ZERO_FRACTION_PATTERN, '$10$2');
}
return value
.replace(ZERO_PREFIXED_UNIT_PATTERN, '$1$2')
.replace(DOT_ZERO_PATTERN, '$10$2')
.replace(FRACTION_PATTERN, function (match, nonZeroPart, suffix) {
return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix;
})
.replace(LEADING_ZERO_FRACTION_PATTERN, '$1.$2');
return optimizeRecursively(value);
}
}
};

View File

@@ -7,10 +7,10 @@ var plugin = {
return value
.replace(options.precision.decimalPointMatcher, '$1$2$3')
.replace(options.precision.zeroMatcher, function (match, integerPart, fractionPart, unit) {
.replace(options.precision.zeroMatcher, function(match, integerPart, fractionPart, unit) {
var multiplier = options.precision.units[unit].multiplier;
var parsedInteger = parseInt(integerPart);
var integer = isNaN(parsedInteger) ? 0 : parsedInteger;
var integer = Number.isNaN(parsedInteger) ? 0 : parsedInteger;
var fraction = parseFloat(fractionPart);
return Math.round((integer + fraction) * multiplier) / multiplier + unit;

View File

@@ -3,10 +3,16 @@ var OptimizationLevel = require('../../../options/optimization-level').Optimizat
var LOCAL_PREFIX_PATTERN = /^local\(/i;
var QUOTED_PATTERN = /^('.*'|".*")$/;
var QUOTED_BUT_SAFE_PATTERN = /^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/;
// eslint-disable-next-line max-len
var GENERIC_FONT_FAMILY_PATTERN = /^['"](?:cursive|default|emoji|fangsong|fantasy|inherit|initial|math|monospace|revert|revert-layer|sans-serif|serif|system-ui|ui-monospace|ui-rounded|ui-sans-serif|ui-serif|unset)['"]$/;
var plugin = {
level1: {
value: function textQuotes(_name, value, options) {
value: function textQuotes(name, value, options) {
if ((name == 'font-family' || name == 'font') && GENERIC_FONT_FAMILY_PATTERN.test(value)) {
return value;
}
if (!options.level[OptimizationLevel.One].removeQuotes) {
return value;
}
@@ -15,9 +21,9 @@ var plugin = {
return value;
}
return QUOTED_BUT_SAFE_PATTERN.test(value) ?
value.substring(1, value.length - 1) :
value;
return QUOTED_BUT_SAFE_PATTERN.test(value)
? value.substring(1, value.length - 1)
: value;
}
}
};

View File

@@ -1,6 +1,6 @@
var OptimizationLevel = require('../../../options/optimization-level').OptimizationLevel;
var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/;
var TIME_VALUE = /^(-?[\d.]+)(m?s)$/;
var plugin = {
level1: {
@@ -13,7 +13,7 @@ var plugin = {
return value;
}
return value.replace(TIME_VALUE, function (match, val, unit) {
return value.replace(TIME_VALUE, function(match, val, unit) {
var newValue;
if (unit == 'ms') {

View File

@@ -7,7 +7,7 @@ var plugin = {
return value;
}
return value.replace(WHOLE_PIXEL_VALUE, function (match, val) {
return value.replace(WHOLE_PIXEL_VALUE, function(match, val) {
var newValue;
var intVal = parseInt(val);
@@ -15,15 +15,21 @@ var plugin = {
return match;
}
if (options.compatibility.properties.shorterLengthUnits && options.compatibility.units.pt && intVal * 3 % 4 === 0) {
if (options.compatibility.properties.shorterLengthUnits
&& options.compatibility.units.pt
&& intVal * 3 % 4 === 0) {
newValue = intVal * 3 / 4 + 'pt';
}
if (options.compatibility.properties.shorterLengthUnits && options.compatibility.units.pc && intVal % 16 === 0) {
if (options.compatibility.properties.shorterLengthUnits
&& options.compatibility.units.pc
&& intVal % 16 === 0) {
newValue = intVal / 16 + 'pc';
}
if (options.compatibility.properties.shorterLengthUnits && options.compatibility.units.in && intVal % 96 === 0) {
if (options.compatibility.properties.shorterLengthUnits
&& options.compatibility.units.in
&& intVal % 96 === 0) {
newValue = intVal / 96 + 'in';
}

View File

@@ -1,5 +1,5 @@
var QUOTED_URL_PATTERN = /^url\(['"].+['"]\)$/;
var QUOTED_URL_WITH_WHITESPACE_PATTERN = /^url\(['"].*[\*\s\(\)'"].*['"]\)$/;
var QUOTED_URL_WITH_WHITESPACE_PATTERN = /^url\(['"].*[*\s()'"].*['"]\)$/;
var QUOTES_PATTERN = /["']/g;
var URL_DATA_PATTERN = /^url\(['"]data:[^;]+;charset/;
@@ -10,9 +10,11 @@ var plugin = {
return value;
}
return QUOTED_URL_PATTERN.test(value) && !QUOTED_URL_WITH_WHITESPACE_PATTERN.test(value) && !URL_DATA_PATTERN.test(value) ?
value.replace(QUOTES_PATTERN, '') :
value;
return QUOTED_URL_PATTERN.test(value)
&& !QUOTED_URL_WITH_WHITESPACE_PATTERN.test(value)
&& !URL_DATA_PATTERN.test(value)
? value.replace(QUOTES_PATTERN, '')
: value;
}
}
};

View File

@@ -1,6 +1,8 @@
var startsAsUrl = require('./starts-as-url');
var WHITESPACE_PATTERN = /\\?\n|\\?\r\n/g;
var WHITESPACE_PREFIX_PATTERN = /(\()\s+/g;
var WHITESPACE_SUFFIX_PATTERN = /\s+(\))/g;
var plugin = {
level1: {
@@ -9,7 +11,10 @@ var plugin = {
return value;
}
return value.replace(WHITESPACE_PATTERN, '');
return value
.replace(WHITESPACE_PATTERN, '')
.replace(WHITESPACE_PREFIX_PATTERN, '$1')
.replace(WHITESPACE_SUFFIX_PATTERN, '$1');
}
}
};

View File

@@ -4,9 +4,12 @@ var Marker = require('../../../tokenizer/marker');
var CALC_DIVISION_WHITESPACE_PATTERN = /\) ?\/ ?/g;
var COMMA_AND_SPACE_PATTERN = /, /g;
var LINE_BREAK_PATTERN = /\r?\n/g;
var MULTI_WHITESPACE_PATTERN = /\s+/g;
var FUNCTION_CLOSING_BRACE_WHITESPACE_PATTERN = /\s+(;?\))/g;
var FUNCTION_OPENING_BRACE_WHITESPACE_PATTERN = /(\(;?)\s+/g;
var VARIABLE_NAME_PATTERN = /^--\S+$/;
var VARIABLE_VALUE_PATTERN = /^var\(\s*--\S+\s*\)$/;
var plugin = {
level1: {
@@ -15,7 +18,11 @@ var plugin = {
return value;
}
if (value.indexOf(' ') == -1 || value.indexOf('expression') === 0) {
if (VARIABLE_NAME_PATTERN.test(name) && !VARIABLE_VALUE_PATTERN.test(value)) {
return value;
}
if ((value.indexOf(' ') == -1 && value.indexOf('\n') == -1) || value.indexOf('expression') === 0) {
return value;
}
@@ -23,6 +30,7 @@ var plugin = {
return value;
}
value = value.replace(LINE_BREAK_PATTERN, '');
value = value.replace(MULTI_WHITESPACE_PATTERN, ' ');
if (value.indexOf('calc') > -1) {

View File

@@ -1,4 +1,34 @@
var FUNCTION_PATTERN = /^(?:\-moz\-calc|\-webkit\-calc|calc|rgb|hsl|rgba|hsla|min|max|clamp)\(/;
var split = require('../../../utils/split');
var ANY_FUNCTION_PATTERN = /^(-(?:moz|ms|o|webkit)-[a-z-]+|[a-z-]+)\((.+)\)$/;
var SKIP_FUNCTION_PATTERN = /^(?:-moz-calc|-webkit-calc|calc|rgb|hsl|rgba|hsla|min|max|clamp|expression)\(/;
var TOKEN_SEPARATOR_PATTERN = /([\s,/])/;
function removeRecursively(value, options) {
var functionTokens;
var tokens;
if (SKIP_FUNCTION_PATTERN.test(value)) {
return value;
}
functionTokens = ANY_FUNCTION_PATTERN.exec(value);
if (!functionTokens) {
return removeZeros(value, options);
}
tokens = split(functionTokens[2], TOKEN_SEPARATOR_PATTERN)
.map(function(token) { return removeRecursively(token, options); });
return functionTokens[1] + '(' + tokens.join('') + ')';
}
function removeZeros(value, options) {
return value
.replace(options.unitsRegexp, '$10$2')
.replace(options.unitsRegexp, '$10$2');
}
var plugin = {
level1: {
@@ -7,17 +37,11 @@ var plugin = {
return value;
}
if (FUNCTION_PATTERN.test(value)) {
return value;
}
if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height' || name == 'width' || name == 'max-width')) {
return value;
}
return value
.replace(options.unitsRegexp, '$1' + '0' + '$2')
.replace(options.unitsRegexp, '$1' + '0' + '$2');
return removeRecursively(value, options);
}
}
};

View File

@@ -15,17 +15,15 @@ function extractProperties(token) {
var i, l;
if (token[0] == Token.RULE) {
inSpecificSelector = !/[\.\+>~]/.test(serializeRules(token[1]));
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;
if (property[0] != Token.PROPERTY) { continue; }
name = property[1][1];
if (name.length === 0)
continue;
if (name.length === 0) { continue; }
value = serializeValue(property, i);
@@ -49,22 +47,15 @@ function extractProperties(token) {
}
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;
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();
return name.replace(/^-\w+-/, '').match(/([a-zA-Z]+)/)[0].toLowerCase();
}
module.exports = extractProperties;

View File

@@ -15,7 +15,7 @@ var PSEUDO_CLASSES_WITH_ARGUMENTS = [
':nth-last-of-type',
':nth-of-type'
];
var RELATION_PATTERN = /[>\+~]/;
var RELATION_PATTERN = /[>+~]/;
var UNMIXABLE_PSEUDO_CLASSES = [
':after',
':before',
@@ -44,10 +44,17 @@ function isMergeable(selector, mergeablePseudoClasses, mergeablePseudoElements,
for (i = 0, l = singleSelectors.length; i < l; i++) {
singleSelector = singleSelectors[i];
if (singleSelector.length === 0 ||
isDeepSelector(singleSelector) ||
isVendorPrefixed(singleSelector) ||
(singleSelector.indexOf(Marker.COLON) > -1 && !areMergeable(singleSelector, extractPseudoFrom(singleSelector), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging))) {
if (singleSelector.length === 0
|| isDeepSelector(singleSelector)
|| isVendorPrefixed(singleSelector)
|| (singleSelector.indexOf(Marker.COLON) > -1
&& !areMergeable(
singleSelector,
extractPseudoFrom(singleSelector),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
))) {
return false;
}
}
@@ -143,10 +150,10 @@ function extractPseudoFrom(selector) {
}
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));
return areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements)
&& needArguments(matches)
&& (matches.length < 2 || !someIncorrectlyChained(selector, matches))
&& (matches.length < 2 || multiplePseudoMerging && allMixable(matches));
}
function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) {
@@ -156,9 +163,9 @@ function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) {
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;
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;
@@ -180,9 +187,9 @@ function needArguments(matches) {
bracketOpensAt = match.indexOf(Marker.OPEN_ROUND_BRACKET);
hasArguments = bracketOpensAt > -1;
name = hasArguments ?
match.substring(0, bracketOpensAt) :
match;
name = hasArguments
? match.substring(0, bracketOpensAt)
: match;
if (hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) == -1) {
return false;
@@ -221,12 +228,12 @@ function someIncorrectlyChained(selector, matches) {
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;
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;

View File

@@ -34,10 +34,15 @@ function mergeAdjacent(tokens, context) {
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) {
} 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] = [];

View File

@@ -53,17 +53,18 @@ function mergeMediaQueries(tokens, context) {
var traversedProperties = extractProperties(tokens[from]);
from += delta;
if (mergeSemantically && allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache)) {
if (mergeSemantically
&& allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache)
) {
continue;
}
if (!canReorder(movedProperties, traversedProperties, specificityCache))
continue directionLoop;
if (!canReorder(movedProperties, traversedProperties, specificityCache)) { continue directionLoop; }
}
target[2] = topToBottom ?
source[2].concat(target[2]) :
target[2].concat(source[2]);
target[2] = topToBottom
? source[2].concat(target[2])
: target[2].concat(source[2]);
source[2] = [];
reduced.push(target);
@@ -91,7 +92,8 @@ function allSameRulePropertiesCanBeReordered(movedProperties, traversedPropertie
traversedProperty = traversedProperties[j];
traversedRule = traversedProperty[5];
if (rulesOverlap(movedRule, traversedRule, true) && !canReorderSingle(movedProperty, traversedProperty, specificityCache)) {
if (rulesOverlap(movedRule, traversedRule, true)
&& !canReorderSingle(movedProperty, traversedProperty, specificityCache)) {
return false;
}
}

View File

@@ -20,7 +20,7 @@ function isBemElement(token) {
}
function withoutModifier(selector) {
return selector.replace(/--[^ ,>\+~:]+/g, '');
return selector.replace(/--[^ ,>+~:]+/g, '');
}
function removeAnyUnsafeElements(left, candidates) {
@@ -30,8 +30,9 @@ function removeAnyUnsafeElements(left, candidates) {
var right = candidates[body];
var rightSelector = withoutModifier(serializeRules(right[1]));
if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1)
if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1) {
delete candidates[body];
}
}
}
@@ -47,21 +48,28 @@ function mergeNonAdjacentByBody(tokens, context) {
for (var i = tokens.length - 1; i >= 0; i--) {
var token = tokens[i];
if (token[0] != Token.RULE)
continue;
if (token[0] != Token.RULE) { continue; }
if (token[2].length > 0 && (!mergeSemantically && unsafeSelector(serializeRules(token[1]))))
candidates = {};
if (token[2].length > 0 && (!mergeSemantically && unsafeSelector(serializeRules(token[1])))) { candidates = {}; }
if (token[2].length > 0 && mergeSemantically && isBemElement(token))
removeAnyUnsafeElements(token, 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 (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];

View File

@@ -14,16 +14,13 @@ function mergeNonAdjacentBySelector(tokens, context) {
var i;
for (i = tokens.length - 1; i >= 0; i--) {
if (tokens[i][0] != Token.RULE)
continue;
if (tokens[i][2].length === 0)
continue;
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);
if (allSelectors[selector].length == 2) { repeatedSelectors.push(selector); }
}
for (i = repeatedSelectors.length - 1; i >= 0; i--) {
@@ -51,14 +48,12 @@ function mergeNonAdjacentBySelector(tokens, context) {
from += delta;
// traversed then moved as we move selectors towards the start
var reorderable = topToBottom ?
canReorder(movedProperties, traversedProperties, specificityCache) :
canReorder(traversedProperties, movedProperties, specificityCache);
var reorderable = topToBottom
? canReorder(movedProperties, traversedProperties, specificityCache)
: canReorder(traversedProperties, movedProperties, specificityCache);
if (!reorderable && !topToBottom)
continue selectorIterator;
if (!reorderable && topToBottom)
continue directionIterator;
if (!reorderable && !topToBottom) { continue selectorIterator; }
if (!reorderable && topToBottom) { continue directionIterator; }
}
if (topToBottom) {

View File

@@ -21,18 +21,18 @@ function removeEmpty(tokens) {
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;
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) {
@@ -59,11 +59,11 @@ function recursivelyOptimizeProperties(tokens, context) {
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);
case Token.RULE:
optimizeProperties(token[2], true, true, context);
break;
case Token.NESTED_BLOCK:
recursivelyOptimizeProperties(token[2], context);
}
}
}

View File

@@ -7,7 +7,7 @@ function findComponentIn(shorthand, longhand) {
}
function nameComparator(to) {
return function (property) {
return function(property) {
return to.name === property.name;
};
}
@@ -33,8 +33,6 @@ function findInSubComponents(shorthand, comparator) {
return longhandMatch;
}
}
return;
}
module.exports = findComponentIn;

View File

@@ -1,7 +1,6 @@
function hasInherit(property) {
for (var i = property.value.length - 1; i >= 0; i--) {
if (property.value[i][1] == 'inherit')
return true;
if (property.value[i][1] == 'inherit') { return true; }
}
return false;

View File

@@ -1,7 +1,6 @@
function hasUnset(property) {
for (var i = property.value.length - 1; i >= 0; i--) {
if (property.value[i][1] == 'unset')
return true;
if (property.value[i][1] == 'unset') { return true; }
}
return false;

View File

@@ -1,8 +1,8 @@
var configuration = require('../../configuration');
function isComponentOf(property1, property2, shallow) {
return isDirectComponentOf(property1, property2) ||
!shallow && !!configuration[property1.name].shorthandComponents && isSubComponentOf(property1, property2);
return isDirectComponentOf(property1, property2)
|| !shallow && !!configuration[property1.name].shorthandComponents && isSubComponentOf(property1, property2);
}
function isDirectComponentOf(property1, property2) {
@@ -14,7 +14,7 @@ function isDirectComponentOf(property1, property2) {
function isSubComponentOf(property1, property2) {
return property1
.components
.some(function (component) {
.some(function(component) {
return isDirectComponentOf(component, property2);
});
}

View File

@@ -336,9 +336,8 @@ function inferComponentValue(components, propertyName) {
if ('oppositeTo' in descriptor) {
return components[descriptor.oppositeTo].value;
} else {
return [[Token.PROPERTY_VALUE, descriptor.defaultValue]];
}
return [[Token.PROPERTY_VALUE, descriptor.defaultValue]];
}
function joinMetadata(components, at) {
@@ -367,11 +366,10 @@ function metadataSorter(metadata1, metadata2) {
if (line1 < line2) {
return -1;
} else if (line1 === line2) {
} if (line1 === line2) {
return column1 < column2 ? -1 : 1;
} else {
return 1;
}
return 1;
}
function buildSequenceWithInheritShorthand(components, shorthandName, validator) {
@@ -481,9 +479,8 @@ function inferInsertAtFrom(properties, candidateComponents, shorthandName) {
if (shorthandName == 'border' && traversesVia(properties.slice(firstCandidatePosition, lastCandidatePosition), 'border-image')) {
return firstCandidatePosition;
} else {
return lastCandidatePosition;
}
return lastCandidatePosition;
}
function traversesVia(properties, propertyName) {

View File

@@ -59,19 +59,20 @@ function overrideSimple(property, by) {
}
function override(property, by) {
if (by.multiplex)
if (by.multiplex) {
overrideByMultiplex(property, by);
else if (property.multiplex)
} else if (property.multiplex) {
overrideIntoMultiplex(property, by);
else
} 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);
override(property.components[i], by.components[i]);
}
}
@@ -101,9 +102,9 @@ function turnShorthandValueIntoMultiplex(property, size) {
function turnLonghandValueIntoMultiplex(property, size) {
var descriptor = configuration[property.name];
var withRealValue = descriptor.intoMultiplexMode == 'real';
var withValue = descriptor.intoMultiplexMode == 'real' ?
property.value.slice(0) :
(descriptor.intoMultiplexMode == 'placeholder' ? descriptor.placeholderValue : descriptor.defaultValue);
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;
@@ -125,8 +126,7 @@ 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++;
if (component.value[i][1] == Marker.COMMA) { size++; }
}
return size + 1;
@@ -147,10 +147,8 @@ function moreSameShorthands(properties, startAt, name) {
var count = 0;
for (var i = startAt; i >= 0; i--) {
if (properties[i].name == name && !properties[i].unused)
count++;
if (count > 1)
break;
if (properties[i].name == name && !properties[i].unused) { count++; }
if (count > 1) { break; }
}
return count > 1;
@@ -158,9 +156,8 @@ function moreSameShorthands(properties, startAt, name) {
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;
}
if (!anyValue(validator.isUrl, shorthand.components[i])
&& anyValue(validator.isFunction, shorthand.components[i])) { return true; }
}
return false;
@@ -168,19 +165,16 @@ function overridingFunction(shorthand, validator) {
function anyValue(fn, property) {
for (var i = 0, l = property.value.length; i < l; i++) {
if (property.value[i][1] == Marker.COMMA)
continue;
if (property.value[i][1] == Marker.COMMA) { continue; }
if (fn(property.value[i][1]))
return true;
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;
if (!left.multiplex && !right.multiplex || left.multiplex && right.multiplex) { return false; }
var multiplex = left.multiplex ? left : right;
var simple = left.multiplex ? right : left;
@@ -215,19 +209,18 @@ function isCompactable(property) {
}
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);
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;
if (layers[i].length == 1 && layers[i][0][1] == 'none') { return true; }
}
return false;
@@ -262,11 +255,9 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
for (i = properties.length - 1; i >= 0; i--) {
right = properties[i];
if (!isCompactable(right))
continue;
if (!isCompactable(right)) { continue; }
if (right.block)
continue;
if (right.block) { continue; }
mayOverride = configuration[right.name].canOverride || sameValue;
@@ -274,43 +265,32 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
for (j = i - 1; j >= 0; j--) {
left = properties[j];
if (!isCompactable(left))
continue;
if (!isCompactable(left)) { continue; }
if (left.block)
continue;
if (left.block) { continue; }
if (left.dynamic || right.dynamic)
continue;
if (left.dynamic || right.dynamic) { continue; }
if (left.unused || right.unused)
continue;
if (left.unused || right.unused) { continue; }
if (left.hack && !right.hack && !right.important || !left.hack && !left.important && right.hack)
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]) { continue; }
if (left.important == right.important && (left.hack[0] != right.hack[0] || (left.hack[1] && left.hack[1] != right.hack[1])))
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 (hasInherit(right)) { continue; }
if (noneOverrideHack(left, 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 (!right.important && left.important) { continue; }
if (!sameVendorPrefixesIn([left], right.components))
continue;
if (!sameVendorPrefixesIn([left], right.components)) { continue; }
if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator))
continue;
if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) { continue; }
if (!isMergeableShorthand(right)) {
left.unused = true;
@@ -336,9 +316,9 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
continue;
}
overriddenComponents = left.shorthand ?
left.components:
[left];
overriddenComponents = left.shorthand
? left.components
: [left];
for (k = overriddenComponents.length - 1; k >= 0; k--) {
overriddenComponent = overriddenComponents[k];
@@ -353,8 +333,7 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
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) { continue; }
if (!right.important && left.important) {
right.unused = true;
@@ -362,40 +341,30 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
}
// Pending more clever algorithm in #527
if (moreSameShorthands(properties, i - 1, left.name))
continue;
if (moreSameShorthands(properties, i - 1, left.name)) { continue; }
if (overridingFunction(left, validator))
continue;
if (overridingFunction(left, validator)) { continue; }
if (!isMergeableShorthand(left))
continue;
if (!isMergeableShorthand(left)) { continue; }
if (hasUnset(left) || hasUnset(right))
continue;
if (hasUnset(left) || hasUnset(right)) { 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 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 = configuration[right.name].nonMergeableValue === right.value[0][1];
if (disabledBackgroundMerging || nonMergeableValue)
continue;
if (disabledBackgroundMerging || nonMergeableValue) { continue; }
if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator))
continue;
if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator)) { continue; }
if (component.value[0][1] != right.value[0][1] && (hasInherit(left) || hasInherit(right)))
continue;
if (component.value[0][1] != right.value[0][1] && (hasInherit(left) || hasInherit(right))) { continue; }
if (wouldResultInLongerValue(left, right))
continue;
if (wouldResultInLongerValue(left, right)) { continue; }
if (!left.multiplex && right.multiplex)
turnIntoMultiplex(left, multiplexSize(right));
if (!left.multiplex && right.multiplex) { turnIntoMultiplex(left, multiplexSize(right)); }
override(component, right);
left.dirty = true;
@@ -403,8 +372,7 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
} 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 (!left.multiplex && right.multiplex) { continue; }
if (!right.important && left.important) {
right.unused = true;
@@ -426,8 +394,9 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
var rightComponent = right.components[k];
mayOverride = configuration[leftComponent.name].canOverride || sameValue;
if (!everyValuesPair(mayOverride.bind(null, validator), leftComponent, rightComponent))
if (!everyValuesPair(mayOverride.bind(null, validator), leftComponent, rightComponent)) {
continue propertyLoop;
}
}
overrideShorthand(left, right);
@@ -435,13 +404,11 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
} 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;
if (!left.important && right.important) { continue; }
component = findComponentIn(left, right);
mayOverride = configuration[right.name].canOverride || sameValue;
if (!everyValuesPair(mayOverride.bind(null, validator), component, right))
continue;
if (!everyValuesPair(mayOverride.bind(null, validator), component, right)) { continue; }
if (left.important && !right.important) {
right.unused = true;
@@ -449,8 +416,7 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
}
var rightRestored = configuration[right.name].restore(right, configuration);
if (rightRestored.length > 1)
continue;
if (rightRestored.length > 1) { continue; }
component = findComponentIn(left, right);
override(component, right);
@@ -465,7 +431,7 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
overridingComponent = right.components[k];
mayOverride = configuration[overridingComponent.name].canOverride || sameValue;
overridable = overridable && everyValuesPair(mayOverride.bind(null, validator), overriddenComponent, overridingComponent);
overridable = everyValuesPair(mayOverride.bind(null, validator), overriddenComponent, overridingComponent);
}
} else {
mayOverride = configuration[right.name].canOverride || sameValue;

View File

@@ -1,9 +1,9 @@
var configuration = require('../../configuration');
function overridesNonComponentShorthand(property1, property2) {
return property1.name in configuration &&
'overridesShorthands' in configuration[property1.name] &&
configuration[property1.name].overridesShorthands.indexOf(property2.name) > -1;
return property1.name in configuration
&& 'overridesShorthands' in configuration[property1.name]
&& configuration[property1.name].overridesShorthands.indexOf(property2.name) > -1;
}
module.exports = overridesNonComponentShorthand;

View File

@@ -36,10 +36,11 @@ function populateComponents(properties, validator, warnings) {
}
}
if (property.components.length > 0)
if (property.components.length > 0) {
property.multiplex = property.components[0].multiplex;
else
} else {
property.unused = true;
}
}
}
}
@@ -49,7 +50,12 @@ function onlyValueIsVariable(property, validator) {
}
function moreThanOneValueIsVariable(property, validator) {
return property.value.length > 1 && property.value.filter(function (value) { return validator.isVariable(value[1]); }).length > 1;
return property.value.length > 1
&& property.value.filter(
function(value) {
return validator.isVariable(value[1]);
}
).length > 1;
}
module.exports = populateComponents;

View File

@@ -27,20 +27,17 @@ function reduceNonAdjacent(tokens, context) {
}
var selectorAsString = serializeRules(token[1]);
var isComplexAndNotSpecial = token[1].length > 1 &&
isMergeable(selectorAsString, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging);
var isComplexAndNotSpecial = token[1].length > 1
&& isMergeable(selectorAsString, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging);
var wrappedSelectors = wrappedSelectorsFrom(token[1]);
var selectors = isComplexAndNotSpecial ?
[selectorAsString].concat(wrappedSelectors) :
[selectorAsString];
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);
if (!candidates[selector]) { candidates[selector] = []; } else { repeated.push(selector); }
candidates[selector].push({
where: i,
@@ -71,8 +68,7 @@ function reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, con
}
function reduceBody(token, newBody, processedCount, tokenIdx) {
if (!data[processedCount - tokenIdx - 1].isPartial)
token[2] = newBody;
if (!data[processedCount - tokenIdx - 1].isPartial) { token[2] = newBody; }
}
for (var i = 0, l = repeated.length; i < l; i++) {
@@ -97,23 +93,21 @@ function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
}
function collectReducedBodies(token, newBody, processedCount, tokenIdx) {
if (tokenIdx === 0)
localContext.reducedBodies.push(newBody);
if (tokenIdx === 0) { localContext.reducedBodies.push(newBody); }
}
allSelectors:
for (var complexSelector in candidates) {
var into = candidates[complexSelector];
if (!into[0].isComplex)
continue;
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];
var selectors = isMergeable(complexSelector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)
? into[0].list
: [complexSelector];
localContext.intoPosition = intoPosition;
localContext.reducedBodies = reducedBodies;
@@ -122,8 +116,7 @@ function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
var selector = selectors[j];
var data = candidates[selector];
if (data.length < 2)
continue allSelectors;
if (data.length < 2) { continue allSelectors; }
localContext.data = data;
@@ -132,8 +125,9 @@ function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
callback: collectReducedBodies
}, options, context);
if (serializeBody(reducedBodies[reducedBodies.length - 1]) != serializeBody(reducedBodies[0]))
if (serializeBody(reducedBodies[reducedBodies.length - 1]) != serializeBody(reducedBodies[0])) {
continue allSelectors;
}
}
intoToken[2] = reducedBodies[0];
@@ -146,8 +140,7 @@ function reduceSelector(tokens, data, context, options, outerContext) {
var processedTokens = [];
for (var j = data.length - 1; j >= 0; j--) {
if (context.filterOut(j, bodies))
continue;
if (context.filterOut(j, bodies)) { continue; }
var where = data[j].where;
var token = tokens[where];
@@ -165,7 +158,8 @@ function reduceSelector(tokens, data, context, options, outerContext) {
var tokenIdx = processedCount - 1;
while (tokenIdx >= 0) {
if ((tokenIdx === 0 || (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) {
if ((tokenIdx === 0
|| (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) {
propertyIdx--;
continue;
}

View File

@@ -11,15 +11,11 @@ function removeDuplicates(tokens) {
for (var i = 0, l = tokens.length; i < l; i++) {
token = tokens[i];
if (token[0] != Token.RULE)
continue;
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] || [];
if (matched[id] && matched[id].length == 1) { moreThanOnce.push(id); } else { matched[id] = matched[id] || []; }
matched[id].push(i);
}
@@ -32,10 +28,7 @@ function removeDuplicates(tokens) {
token = tokens[matched[id][j]];
body = serializeBody(token[2]);
if (bodies.indexOf(body) > -1)
token[2] = [];
else
bodies.push(body);
if (bodies.indexOf(body) > -1) { token[2] = []; } else { bodies.push(body); }
}
}
}

View File

@@ -5,9 +5,9 @@ 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 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$/;
@@ -59,11 +59,11 @@ function markUsedAtRules(tokens, markCallback, atRules, context) {
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);
case Token.RULE:
boundMarkCallback(tokens[i], context);
break;
case Token.NESTED_BLOCK:
markUsedAtRules(tokens[i][2], markCallback, atRules, context);
}
}
}
@@ -79,7 +79,7 @@ function matchCounterStyle(token, atRules) {
}
function markCounterStylesAsUsed(atRules) {
return function (token, context) {
return function(token, context) {
var property;
var wrappedProperty;
var i, l;
@@ -125,7 +125,7 @@ function matchFontFace(token, atRules) {
}
function markFontFacesAsUsed(atRules) {
return function (token, context) {
return function(token, context) {
var property;
var wrappedProperty;
var component;
@@ -176,7 +176,7 @@ function matchKeyframe(token, atRules) {
}
function markKeyframesAsUsed(atRules) {
return function (token, context) {
return function(token, context) {
var property;
var wrappedProperty;
var component;
@@ -222,9 +222,9 @@ function matchNamespace(token, atRules) {
}
function markNamespacesAsUsed(atRules) {
var namespaceRegex = new RegExp(Object.keys(atRules).join('\\\||') + '\\\|', 'g');
var namespaceRegex = new RegExp(Object.keys(atRules).join('\\||') + '\\|', 'g');
return function (token) {
return function(token) {
var match;
var scope;
var normalizedMatch;

View File

@@ -3,14 +3,13 @@
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)/;
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;
if (!canReorderSingle(left[j], right[i], cache)) { return false; }
}
}
@@ -29,40 +28,41 @@ function canReorderSingle(left, right, cache) {
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;
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);
return /^-(?:moz|webkit|ms|o)-/.test(name);
}
function unprefixed(name) {
return name.replace(/^\-(?:moz|webkit|ms|o)\-/, '');
return name.replace(/^-(?:moz|webkit|ms|o)-/, '');
}
function sameBorderComponent(name1, name2) {

View File

@@ -5,9 +5,8 @@ function restoreWithComponents(property) {
if (descriptor && descriptor.shorthand) {
return descriptor.restore(property, configuration);
} else {
return property.value;
}
return property.value;
}
module.exports = restoreWithComponents;

View File

@@ -87,18 +87,25 @@ function restructure(tokens, context) {
var mergeableTokens = [];
for (var i = sourceTokens.length - 1; i >= 0; i--) {
if (!isMergeable(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
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)
if (sourceTokens[i][2].length > 0
&& uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1) {
uniqueTokensWithBody.push(sourceTokens[i]);
}
}
return uniqueTokensWithBody.length > 1 ?
mergeableTokens :
[];
return uniqueTokensWithBody.length > 1
? mergeableTokens
: [];
}
function shortenIfPossible(position, movedProperty) {
@@ -110,15 +117,13 @@ function restructure(tokens, context) {
var qualifiedTokens = [];
var mergeableTokens = tokensToMerge(movableTokens[key]);
if (mergeableTokens.length < 2)
return;
if (mergeableTokens.length < 2) { return; }
var allFits = findAllFits(mergeableTokens, valueSize, 1);
var bestFit = allFits[0];
if (bestFit[1] > 0)
return sendToMultiPropertyMoveCache(position, movedProperty, allFits);
if (bestFit[1] > 0) { return sendToMultiPropertyMoveCache(position, movedProperty, allFits); }
for (var i = bestFit[0].length - 1; i >=0; i--) {
for (var i = bestFit[0].length - 1; i >= 0; i--) {
allSelectors = bestFit[0][i][1].concat(allSelectors);
qualifiedTokens.unshift(bestFit[0][i]);
}
@@ -142,7 +147,9 @@ function restructure(tokens, context) {
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));
differenceVariants = differenceVariants.concat(
allCombinations(subVariant, propertySize, propertiesCount, level - 1)
);
}
}
@@ -152,7 +159,9 @@ function restructure(tokens, context) {
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;
allSelectorsSize += tokensVariant[i][2].length > propertiesCount
? serializeRules(tokensVariant[i][1]).length
: -1;
}
return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1;
}
@@ -194,8 +203,7 @@ function restructure(tokens, context) {
var toMove = movableTokens[key];
if (toMove && toMove.length > 1) {
if (!shortenMultiMovesIfPossible(position, movedProperty))
shortenIfPossible(position, movedProperty);
if (!shortenMultiMovesIfPossible(position, movedProperty)) { shortenIfPossible(position, movedProperty); }
}
}
@@ -206,23 +214,20 @@ function restructure(tokens, context) {
var j, k;
var mergeableTokens = tokensToMerge(movableTokens[key]);
if (mergeableTokens.length < 2)
return;
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;
if (tokensList.indexOf(mergeableTokens[j]) == -1) { continue movableLoop; }
}
candidates.push(value);
}
if (candidates.length < 2)
return false;
if (candidates.length < 2) { return false; }
for (j = candidates.length - 1; j >= 0; j--) {
for (k = movedProperties.length - 1; k >= 0; k--) {
@@ -251,8 +256,7 @@ function restructure(tokens, context) {
var mergeableTokens = propertiesAndMergableTokens[0][1];
var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0];
if (bestFit[1] > 0)
return false;
if (bestFit[1] > 0) { return false; }
var allSelectors = [];
var qualifiedTokens = [];
@@ -270,8 +274,7 @@ function restructure(tokens, context) {
delete movableTokens[property[4]];
if (index > -1 && movedToBeDropped.indexOf(index) == -1)
movedToBeDropped.push(index);
if (index > -1 && movedToBeDropped.indexOf(index) == -1) { movedToBeDropped.push(index); }
}
return true;
@@ -280,8 +283,7 @@ function restructure(tokens, context) {
function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) {
var propertyName = property[0];
var movedPropertyName = movedProperty[0];
if (propertyName != movedPropertyName)
return false;
if (propertyName != movedPropertyName) { return false; }
var key = movedProperty[4];
var toMove = movableTokens[key];
@@ -325,9 +327,12 @@ function restructure(tokens, context) {
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 && (
!canReorderSingle(property, movedProperty, specificityCache)
&& !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token)
|| movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)
) {
dropPropertiesAt(i + 1, movedProperty);
if (movedToBeDropped.indexOf(k) == -1) {
movedToBeDropped.push(k);
@@ -344,8 +349,7 @@ function restructure(tokens, context) {
}
}
if (!isRule || unmovableInCurrentToken.indexOf(j) > -1)
continue;
if (!isRule || unmovableInCurrentToken.indexOf(j) > -1) { continue; }
var key = property[4];
@@ -377,8 +381,7 @@ function restructure(tokens, context) {
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;
if (!(isImportRule || isComment)) { break; }
}
for (i = 0; i < movedProperties.length; i++) {

View File

@@ -1,4 +1,4 @@
var MODIFIER_PATTERN = /\-\-.+$/;
var MODIFIER_PATTERN = /--.+$/;
function rulesOverlap(rule1, rule2, bemMode) {
var scope1;

View File

@@ -12,7 +12,9 @@ function specificitiesOverlap(selector1, selector2, 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]) {
if (specificity1[0] === specificity2[0]
&& specificity1[1] === specificity2[1]
&& specificity1[2] === specificity2[2]) {
return true;
}
}

View File

@@ -11,7 +11,7 @@ var Selector = {
var LETTER_PATTERN = /[a-zA-Z]/;
var NOT_PREFIX = ':not(';
var SEPARATOR_PATTERN = /[\s,\(>~\+]/;
var SEPARATOR_PATTERN = /[\s,(>~+]/;
function specificity(selector) {
var result = [0, 0, 0];

View File

@@ -7,14 +7,20 @@ var calcRegex = new RegExp('^(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)$', 'i');
var decimalRegex = /[0-9]/;
var functionAnyRegex = new RegExp('^' + functionAnyRegexStr + '$', 'i');
var hexAlphaColorRegex = /^#(?:[0-9a-f]{4}|[0-9a-f]{8})$/i;
var hslColorRegex = /^hsl\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31},\s{0,31}\d*\.?\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;
// eslint-disable-next-line max-len
var hslColorRegex = /^hsl\(\s{0,31}[-.]?\d+\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[-.]?\d+\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31},\s{0,31}\d*\.?\d+%\s{0,31},\s{0,31}\.?\d+\s{0,31}\)$/;
// eslint-disable-next-line max-len
var hslColorWithSpacesRegex = /^hsl\(\s{0,31}[-.]?\d+(deg)?\s{1,31}\d*\.?\d+%\s{1,31}\d*\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[-.]?\d+(deg)?\s{1,31}\d*\.?\d+%\s{1,31}\d*\.?\d+%\s{1,31}\/\s{1,31}\d*\.?\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 quotedTextRegex = /^("[^"]*"|'[^']*')$/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}\)$/i;
// eslint-disable-next-line max-len
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}\)$/i;
// eslint-disable-next-line max-len
var rgbColorWithSpacesRegex = /^rgb\(\s{0,31}[\d]{1,3}\s{1,31}[\d]{1,3}\s{1,31}[\d]{1,3}\s{0,31}\)|rgba\(\s{0,31}[\d]{1,3}\s{1,31}[\d]{1,3}\s{1,31}[\d]{1,3}\s{1,31}\/\s{1,31}[\d]*\.?[.\d]+%?\s{0,31}\)$/i;
var timeUnitPattern = /\d+(s|ms)/;
var timingFunctionRegex = /^(cubic\-bezier|steps)\([^\)]+\)$/;
var timingFunctionRegex = /^(cubic-bezier|steps)\([^)]+\)$/;
var validTimeUnits = ['ms', 's'];
var urlRegex = /^url\([\s\S]+\)$/i;
var variableRegex = new RegExp('^' + variableRegexStr + '$', 'i');
@@ -123,19 +129,19 @@ var Keywords = {
'inherit',
'separate'
],
'bottom': [
bottom: [
'auto'
],
'clear': [
clear: [
'both',
'left',
'none',
'right'
],
'color': [
color: [
'transparent'
],
'cursor': [
cursor: [
'all-scroll',
'auto',
'col-resize',
@@ -160,7 +166,7 @@ var Keywords = {
'w-resize',
'wait'
],
'display': [
display: [
'block',
'inline',
'inline-block',
@@ -177,15 +183,15 @@ var Keywords = {
'table-row',
'table-row-group'
],
'float': [
float: [
'left',
'none',
'right'
],
'left': [
left: [
'auto'
],
'font': [
font: [
'caption',
'icon',
'menu',
@@ -265,19 +271,19 @@ var Keywords = {
'upper-latin',
'upper-roman'
],
'overflow': [
overflow: [
'auto',
'hidden',
'scroll',
'visible'
],
'position': [
position: [
'absolute',
'fixed',
'relative',
'static'
],
'right': [
right: [
'auto'
],
'text-align': [
@@ -297,7 +303,7 @@ var Keywords = {
'clip',
'ellipsis'
],
'top': [
top: [
'auto'
],
'vertical-align': [
@@ -310,7 +316,7 @@ var Keywords = {
'text-top',
'top'
],
'visibility': [
visibility: [
'collapse',
'hidden',
'visible'
@@ -320,7 +326,7 @@ var Keywords = {
'nowrap',
'pre'
],
'width': [
width: [
'inherit',
'initial',
'medium',
@@ -349,12 +355,12 @@ var Units = [
];
function isColor(value) {
return value != 'auto' &&
(
isKeyword('color')(value) ||
isHexColor(value) ||
isColorFunction(value) ||
isNamedEntity(value)
return value != 'auto'
&& (
isKeyword('color')(value)
|| isHexColor(value)
|| isColorFunction(value)
|| isNamedEntity(value)
);
}
@@ -371,11 +377,14 @@ function isFunction(value) {
}
function isHexColor(value) {
return threeValueColorRegex.test(value) || fourValueColorRegex.test(value) || sixValueColorRegex.test(value) || eightValueColorRegex.test(value);
return threeValueColorRegex.test(value)
|| fourValueColorRegex.test(value)
|| sixValueColorRegex.test(value)
|| eightValueColorRegex.test(value);
}
function isHslColor(value) {
return hslColorRegex.test(value);
return hslColorRegex.test(value) || hslColorWithSpacesRegex.test(value);
}
function isHexAlphaColor(value) {
@@ -409,7 +418,7 @@ function isNumber(value) {
}
function isRgbColor(value) {
return rgbColorRegex.test(value);
return rgbColorRegex.test(value) || rgbColorWithSpacesRegex.test(value);
}
function isPrefixed(value) {
@@ -417,8 +426,8 @@ function isPrefixed(value) {
}
function isPositiveNumber(value) {
return isNumber(value) &&
parseFloat(value) >= 0;
return isNumber(value)
&& parseFloat(value) >= 0;
}
function isVariable(value) {
@@ -428,9 +437,9 @@ function isVariable(value) {
function isTime(value) {
var numberUpTo = scanForNumber(value);
return numberUpTo == value.length && parseInt(value) === 0 ||
numberUpTo > -1 && validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1 ||
isCalculatedTime(value);
return numberUpTo == value.length && parseInt(value) === 0
|| numberUpTo > -1 && validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1
|| isCalculatedTime(value);
}
function isCalculatedTime(value) {
@@ -440,7 +449,7 @@ function isCalculatedTime(value) {
function isTimingFunction() {
var isTimingFunctionKeyword = isKeyword('*-timing-function');
return function (value) {
return function(value) {
return isTimingFunctionKeyword(value) || timingFunctionRegex.test(value);
};
}
@@ -448,10 +457,10 @@ function isTimingFunction() {
function isUnit(validUnits, value) {
var numberUpTo = scanForNumber(value);
return numberUpTo == value.length && parseInt(value) === 0 ||
numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1).toLowerCase()) > -1 ||
value == 'auto' ||
value == 'inherit';
return numberUpTo == value.length && parseInt(value) === 0
|| numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1).toLowerCase()) > -1
|| value == 'auto'
|| value == 'inherit';
}
function isUrl(value) {
@@ -459,9 +468,9 @@ function isUrl(value) {
}
function isZIndex(value) {
return value == 'auto' ||
isNumber(value) ||
isKeyword('^')(value);
return value == 'auto'
|| isNumber(value)
|| isKeyword('^')(value);
}
function scanForNumber(value) {
@@ -492,7 +501,7 @@ function scanForNumber(value) {
}
function validator(compatibility) {
var validUnits = Units.slice(0).filter(function (value) {
var validUnits = Units.slice(0).filter(function(value) {
return !(value in compatibility.units) || compatibility.units[value] === true;
});

View File

@@ -1,9 +1,10 @@
var VENDOR_PREFIX_PATTERN = /(?:^|\W)(\-\w+\-)/g;
var VENDOR_PREFIX_PATTERN = /(?:^|\W)(-\w+-)/g;
function unique(value) {
var prefixes = [];
var match;
// eslint-disable-next-line no-cond-assign
while ((match = VENDOR_PREFIX_PATTERN.exec(value)) !== null) {
if (prefixes.indexOf(match[0]) == -1) {
prefixes.push(match[0]);

View File

@@ -93,9 +93,12 @@ function hackFrom(property) {
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])) {
} 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) {
} 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)];
@@ -105,13 +108,13 @@ function hackFrom(property) {
}
function isImportant(property) {
if (property.length < 3)
return false;
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])) {
} if (Match.IMPORTANT_WORD_PATTERN.test(lastValue[1])
&& Match.SUFFIX_BANG_PATTERN.test(property[property.length - 2][1])) {
return true;
}

View File

@@ -4,9 +4,7 @@ var DEFAULTS = {
hexAlpha: false, // 4- and 8-character hex notation
opacity: true // rgba / hsla
},
customUnits: {
rpx: false
},
customUnits: { rpx: false },
properties: {
backgroundClipMerging: true, // background-clip to shorthand
backgroundOriginMerging: true, // background-origin to shorthand
@@ -79,17 +77,9 @@ var DEFAULTS = {
}
};
DEFAULTS.ie11 = merge(DEFAULTS['*'], {
properties: {
ieSuffixHack: true
}
});
DEFAULTS.ie11 = merge(DEFAULTS['*'], { properties: { ieSuffixHack: true } });
DEFAULTS.ie10 = merge(DEFAULTS['*'], {
properties: {
ieSuffixHack: true
}
});
DEFAULTS.ie10 = merge(DEFAULTS['*'], { properties: { ieSuffixHack: true } });
DEFAULTS.ie9 = merge(DEFAULTS['*'], {
properties: {
@@ -99,9 +89,7 @@ DEFAULTS.ie9 = merge(DEFAULTS['*'], {
});
DEFAULTS.ie8 = merge(DEFAULTS.ie9, {
colors: {
opacity: false
},
colors: { opacity: false },
properties: {
backgroundClipMerging: false,
backgroundOriginMerging: false,
@@ -133,9 +121,7 @@ DEFAULTS.ie8 = merge(DEFAULTS.ie9, {
});
DEFAULTS.ie7 = merge(DEFAULTS.ie8, {
properties: {
ieBangHack: true
},
properties: { ieBangHack: true },
selectors: {
ie7Hack: true,
mergeablePseudoClasses: [
@@ -144,7 +130,7 @@ DEFAULTS.ie7 = merge(DEFAULTS.ie8, {
':hover',
':visited'
]
},
}
});
function compatibilityFrom(source) {
@@ -153,12 +139,14 @@ function compatibilityFrom(source) {
function merge(source, target) {
for (var key in source) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(source, key)) {
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;
if (Object.prototype.hasOwnProperty.call(target, key) && typeof value === 'object' && !Array.isArray(value)) {
target[key] = merge(value, target[key] || {});
} else {
target[key] = key in target ? target[key] : value;
}
}
}
@@ -166,20 +154,18 @@ function merge(source, target) {
}
function calculateSource(source) {
if (typeof source == 'object')
return source;
if (typeof source == 'object') { return source; }
if (!/[,\+\-]/.test(source))
return DEFAULTS[source] || DEFAULTS['*'];
if (!/[,+-]/.test(source)) { return DEFAULTS[source] || DEFAULTS['*']; }
var parts = source.split(',');
var template = parts[0] in DEFAULTS ?
DEFAULTS[parts.shift()] :
DEFAULTS['*'];
var template = parts[0] in DEFAULTS
? DEFAULTS[parts.shift()]
: DEFAULTS['*'];
source = {};
parts.forEach(function (part) {
parts.forEach(function(part) {
var isAdd = part[0] == '+';
var key = part.substring(1).split('.');
var group = key[0];

View File

@@ -136,7 +136,7 @@ function formatFrom(source) {
function toHash(string) {
return string
.split(OPTION_SEPARATOR)
.reduce(function (accumulator, directive) {
.reduce(function(accumulator, directive) {
var parts = directive.split(OPTION_NAME_VALUE_SEPARATOR);
var name = parts[0];
var value = parts[1];
@@ -158,7 +158,7 @@ function toHash(string) {
function hashValuesToHash(string) {
return string
.split(HASH_VALUES_OPTION_SEPARATOR)
.reduce(function (accumulator, directive) {
.reduce(function(accumulator, directive) {
var parts = directive.split(HASH_VALUES_NAME_VALUE_SEPARATOR);
var name = parts[0];
var value = parts[1];
@@ -169,43 +169,42 @@ function hashValuesToHash(string) {
}, {});
}
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;
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;
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;
case 'space':
return IndentWith.Space;
case 'tab':
return IndentWith.Tab;
default:
return value;
}
}

View File

@@ -11,12 +11,12 @@ function inlineRequestFrom(option) {
}
function proxyOptionsFrom(httpProxy) {
return httpProxy ?
{
return httpProxy
? {
hostname: url.parse(httpProxy).hostname,
port: parseInt(url.parse(httpProxy).port)
} :
{};
}
: {};
}
module.exports = inlineRequestFrom;

View File

@@ -7,9 +7,9 @@ function inlineOptionsFrom(rules) {
return ['none'];
}
return undefined === rules ?
['local'] :
rules.split(',');
return undefined === rules
? ['local']
: rules.split(',');
}
module.exports = inlineOptionsFrom;

View File

@@ -31,7 +31,8 @@ DEFAULTS[OptimizationLevel.One] = {
specialComments: 'all',
tidyAtRules: true,
tidyBlockScopes: true,
tidySelectors: true
tidySelectors: true,
variableValueOptimizers: []
};
DEFAULTS[OptimizationLevel.Two] = {
mergeAdjacentRules: true,
@@ -99,7 +100,7 @@ function optimizationLevelFrom(source) {
source[One].roundingPrecision = roundingPrecisionFrom(source[One].roundingPrecision);
}
if (Two in source && 'skipProperties' in source[Two] && typeof(source[Two].skipProperties) == 'string') {
if (Two in source && 'skipProperties' in source[Two] && typeof (source[Two].skipProperties) == 'string') {
source[Two].skipProperties = source[Two].skipProperties.split(LIST_VALUE_SEPARATOR);
}
@@ -157,14 +158,14 @@ function defaults(level, value) {
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;
case FALSE_KEYWORD_1:
case FALSE_KEYWORD_2:
return false;
case TRUE_KEYWORD_1:
case TRUE_KEYWORD_2:
return true;
default:
return value;
}
}
@@ -195,7 +196,7 @@ function covertValuesToHashes(source) {
function covertToHash(asString, level) {
return asString
.split(OPTION_SEPARATOR)
.reduce(function (accumulator, directive) {
.reduce(function(accumulator, directive) {
var parts = directive.split(OPTION_VALUE_SEPARATOR);
var name = parts[0];
var value = parts[1];
@@ -213,5 +214,5 @@ function covertToHash(asString, level) {
module.exports = {
OptimizationLevel: OptimizationLevel,
optimizationLevelFrom: optimizationLevelFrom,
optimizationLevelFrom: optimizationLevelFrom
};

View File

@@ -8,16 +8,16 @@ function pluginsFrom(plugins) {
plugins = plugins || [];
flatPlugins.level1Value = plugins
.map(function (plugin) { return plugin.level1 && plugin.level1.value; })
.filter(function (plugin) { return plugin != null; });
.map(function(plugin) { return plugin.level1 && plugin.level1.value; })
.filter(function(plugin) { return plugin != null; });
flatPlugins.level1Property = plugins
.map(function (plugin) { return plugin.level1 && plugin.level1.property; })
.filter(function (plugin) { return plugin != null; });
.map(function(plugin) { return plugin.level1 && plugin.level1.property; })
.filter(function(plugin) { return plugin != null; });
flatPlugins.level2Block = plugins
.map(function (plugin) { return plugin.level2 && plugin.level2.block; })
.filter(function (plugin) { return plugin != null; });
.map(function(plugin) { return plugin.level2 && plugin.level2.block; })
.filter(function(plugin) { return plugin != null; });
return flatPlugins;
}

View File

@@ -1,11 +1,10 @@
function rebaseFrom(rebaseOption, rebaseToOption) {
if (undefined !== rebaseToOption) {
return true;
} else if (undefined === rebaseOption) {
} if (undefined === rebaseOption) {
return false;
} else {
return !!rebaseOption;
}
return !!rebaseOption;
}
module.exports = rebaseFrom;

View File

@@ -13,21 +13,21 @@ function roundingPrecisionFrom(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,
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
};
}
@@ -63,12 +63,12 @@ function buildPrecisionFrom(source) {
return source
.split(DIRECTIVES_SEPARATOR)
.reduce(function (accumulator, directive) {
.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) {
if (Number.isNaN(value) || value == -1) {
value = DEFAULT_PRECISION;
}

View File

@@ -29,9 +29,9 @@ function applySourceMaps(tokens, context, callback) {
warnings: context.warnings
};
return context.options.sourceMap && tokens.length > 0 ?
doApplySourceMaps(applyContext) :
callback(tokens);
return context.options.sourceMap && tokens.length > 0
? doApplySourceMaps(applyContext)
: callback(tokens);
}
function doApplySourceMaps(applyContext) {
@@ -76,7 +76,7 @@ function findTokenSource(token) {
}
function fetchAndApplySourceMap(sourceMapComment, source, singleSourceTokens, applyContext) {
return extractInputSourceMapFrom(sourceMapComment, applyContext, function (inputSourceMap) {
return extractInputSourceMapFrom(sourceMapComment, applyContext, function(inputSourceMap) {
if (inputSourceMap) {
applyContext.inputSourceMapTracker.track(source, inputSourceMap);
applySourceMapRecursively(singleSourceTokens, applyContext.inputSourceMapTracker);
@@ -96,8 +96,8 @@ function extractInputSourceMapFrom(sourceMapComment, applyContext, whenSourceMap
if (isDataUriResource(uri)) {
sourceMap = extractInputSourceMapFromDataUri(uri);
return whenSourceMapReady(sourceMap);
} else if (isRemoteResource(uri)) {
return loadInputSourceMapFromRemoteUri(uri, applyContext, function (sourceMap) {
} if (isRemoteResource(uri)) {
return loadInputSourceMapFromRemoteUri(uri, applyContext, function(sourceMap) {
var parsedMap;
if (sourceMap) {
@@ -108,20 +108,18 @@ function extractInputSourceMapFrom(sourceMapComment, applyContext, whenSourceMap
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);
}
}
// 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);
}
return whenSourceMapReady(null);
}
function extractInputSourceMapFromDataUri(uri) {
@@ -143,15 +141,15 @@ function loadInputSourceMapFromRemoteUri(uri, applyContext, whenLoaded) {
if (applyContext.localOnly) {
applyContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.');
return whenLoaded(null);
} else if (isRuntimeResource) {
} if (isRuntimeResource) {
applyContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.');
return whenLoaded(null);
} else if (!isAllowed) {
} 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) {
applyContext.fetch(uri, applyContext.inlineRequest, applyContext.inlineTimeout, function(error, body) {
if (error) {
applyContext.warnings.push('Missing source map at "' + uri + '" - ' + error);
return whenLoaded(null);
@@ -168,9 +166,12 @@ function loadInputSourceMapFromLocalUri(uri, applyContext) {
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) {
} if (!isAllowed) {
applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.');
return null;
} if (!fs.statSync(uri).size) {
applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is empty.');
return null;
}
sourceMap = fs.readFileSync(uri, 'utf-8');
@@ -185,44 +186,44 @@ function applySourceMapRecursively(tokens, inputSourceMapTracker) {
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);
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);
}
}

View File

@@ -3,10 +3,10 @@ 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;
var QUOTE_PREFIX_PATTERN = /['"]\s{0,31}/;
var QUOTE_SUFFIX_PATTERN = /\s{0,31}['"]/;
var URL_PREFIX_PATTERN = /^url\(\s{0,31}/i;
var URL_SUFFIX_PATTERN = /\s{0,31}\)/i;
function extractImportUrlAndMedia(atRuleValue) {
var uri;

View File

@@ -42,9 +42,9 @@ function originalPositionFor(maps, metadata, range, selectorFallbacks) {
return originalPositionFor(maps, [line - 1, column, source], range, selectorFallbacks - 1);
}
return originalPosition.line !== null ?
toMetadata(originalPosition) :
metadata;
return originalPosition.line !== null
? toMetadata(originalPosition)
: metadata;
}
function toMetadata(asHash) {

View File

@@ -9,7 +9,7 @@ var HTTP_PROTOCOL = 'http:';
function isAllowedResource(uri, isRemote, rules) {
var match;
var absoluteUri;
var allowed = isRemote ? false : true;
var allowed = !isRemote;
var rule;
var isNegated;
var normalizedRule;
@@ -23,13 +23,13 @@ function isAllowedResource(uri, isRemote, rules) {
uri = HTTP_PROTOCOL + uri;
}
match = isRemote ?
url.parse(uri).host :
uri;
match = isRemote
? url.parse(uri).host
: uri;
absoluteUri = isRemote ?
uri :
path.resolve(uri);
absoluteUri = isRemote
? uri
: path.resolve(uri);
for (i = 0; i < rules.length; i++) {
rule = rules[i];

View File

@@ -21,9 +21,9 @@ function loadOriginalSources(context, callback) {
warnings: context.warnings
};
return context.options.sourceMap && context.options.sourceMapInlineSources ?
doLoadOriginalSources(loadContext) :
callback();
return context.options.sourceMap && context.options.sourceMapInlineSources
? doLoadOriginalSources(loadContext)
: callback();
}
function uriToSourceMapping(allSourceMapConsumers) {
@@ -71,17 +71,16 @@ function loadOriginalSource(uri, loadContext) {
var content;
if (isRemoteResource(uri)) {
return loadOriginalSourceFromRemoteUri(uri, loadContext, function (content) {
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);
}
content = loadOriginalSourceFromLocalUri(uri, loadContext);
loadContext.index++;
loadContext.sourcesContent[uri] = content;
return doLoadOriginalSources(loadContext);
}
function loadOriginalSourceFromRemoteUri(uri, loadContext, whenLoaded) {
@@ -91,15 +90,15 @@ function loadOriginalSourceFromRemoteUri(uri, loadContext, whenLoaded) {
if (loadContext.localOnly) {
loadContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.');
return whenLoaded(null);
} else if (isRuntimeResource) {
} if (isRuntimeResource) {
loadContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.');
return whenLoaded(null);
} else if (!isAllowed) {
} 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) {
loadContext.fetch(uri, loadContext.inlineRequest, loadContext.inlineTimeout, function(error, content) {
if (error) {
loadContext.warnings.push('Missing original source at "' + uri + '" - ' + error);
}
@@ -115,7 +114,7 @@ function loadOriginalSourceFromLocalUri(relativeUri, loadContext) {
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) {
} if (!isAllowed) {
loadContext.warnings.push('Cannot fetch "' + absoluteUri + '" as resource is not allowed.');
return null;
}

View File

@@ -25,11 +25,11 @@ function loadRemoteResource(uri, inlineRequest, inlineTimeout, callback) {
requestOptions.path = requestOptions.href;
}
fetch = (proxyProtocol && !isHttpsResource(proxyProtocol)) || isHttpResource(uri) ?
http.get :
https.get;
fetch = (proxyProtocol && !isHttpsResource(proxyProtocol)) || isHttpResource(uri)
? http.get
: https.get;
fetch(requestOptions, function (res) {
fetch(requestOptions, function(res) {
var chunks = [];
var movedUri;
@@ -39,36 +39,36 @@ function loadRemoteResource(uri, inlineRequest, inlineTimeout, callback) {
if (res.statusCode < 200 || res.statusCode > 399) {
return callback(res.statusCode, null);
} else if (res.statusCode > 299) {
} if (res.statusCode > 299) {
movedUri = url.resolve(uri, res.headers.location);
return loadRemoteResource(movedUri, inlineRequest, inlineTimeout, callback);
}
res.on('data', function (chunk) {
res.on('data', function(chunk) {
chunks.push(chunk.toString());
});
res.on('end', function () {
res.on('end', function() {
var body = chunks.join('');
callback(null, body);
});
})
.on('error', function (res) {
if (errorHandled) {
return;
}
.on('error', function(res) {
if (errorHandled) {
return;
}
errorHandled = true;
callback(res.message, null);
})
.on('timeout', function () {
if (errorHandled) {
return;
}
errorHandled = true;
callback(res.message, null);
})
.on('timeout', function() {
if (errorHandled) {
return;
}
errorHandled = true;
callback('timeout', null);
})
.setTimeout(inlineTimeout);
errorHandled = true;
callback('timeout', null);
})
.setTimeout(inlineTimeout);
}
module.exports = loadRemoteResource;

View File

@@ -1,4 +1,4 @@
var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/;
var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=(?:(?!;charset=)[^;])+)?(;[^,]+?)?,(.+)/;
function matchDataUri(uri) {
return DATA_URI_PATTERN.exec(uri);

View File

@@ -19,11 +19,12 @@ var isImport = require('../utils/is-import');
var isRemoteResource = require('../utils/is-remote-resource');
var UNKNOWN_URI = 'uri:unknown';
var FILE_RESOURCE_PROTOCOL = 'file://';
function readSources(input, context, callback) {
return doReadSources(input, context, function (tokens) {
return applySourceMaps(tokens, context, function () {
return loadOriginalSources(context, function () { return callback(tokens); });
return doReadSources(input, context, function(tokens) {
return applySourceMaps(tokens, context, function() {
return loadOriginalSources(context, function() { return callback(tokens); });
});
});
}
@@ -31,11 +32,11 @@ function readSources(input, context, callback) {
function doReadSources(input, context, callback) {
if (typeof input == 'string') {
return fromString(input, context, callback);
} else if (Buffer.isBuffer(input)) {
} if (Buffer.isBuffer(input)) {
return fromString(input.toString(), context, callback);
} else if (Array.isArray(input)) {
} if (Array.isArray(input)) {
return fromArray(input, context, callback);
} else if (typeof input == 'object') {
} if (typeof input == 'object') {
return fromHash(input, context, callback);
}
}
@@ -49,13 +50,11 @@ function fromString(input, context, callback) {
}
function fromArray(input, context, callback) {
var inputAsImports = input.reduce(function (accumulator, uriOrHash) {
var inputAsImports = input.reduce(function(accumulator, uriOrHash) {
if (typeof uriOrHash === 'string') {
return addStringSource(uriOrHash, accumulator);
} else {
return addHashSource(uriOrHash, context, accumulator);
}
return addHashSource(uriOrHash, context, accumulator);
}, []);
return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback);
@@ -102,9 +101,9 @@ function normalizeUri(uri) {
return uri;
}
absoluteUri = path.isAbsolute(uri) ?
uri :
path.resolve(uri);
absoluteUri = path.isAbsolute(uri)
? uri
: path.resolve(uri);
relativeToCurrentPath = path.relative(currentPath, absoluteUri);
normalizedUri = normalizePath(relativeToCurrentPath);
@@ -112,12 +111,12 @@ function normalizeUri(uri) {
}
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);
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);
}
@@ -147,9 +146,9 @@ function fromStyles(styles, context, parentInlinerContext, callback) {
tokens = tokenize(styles, context);
tokens = rebase(tokens, context.options.rebase, context.validator, rebaseConfig);
return allowsAnyImports(parentInlinerContext.inline) ?
inline(tokens, context, parentInlinerContext, callback) :
callback(tokens);
return allowsAnyImports(parentInlinerContext.inline)
? inline(tokens, context, parentInlinerContext, callback)
: callback(tokens);
}
function allowsAnyImports(inline) {
@@ -188,7 +187,7 @@ function doInlineImports(inlinerContext) {
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) {
} if (token[0] == Token.AT_RULE || token[0] == Token.COMMENT) {
inlinerContext.outputTokens.push(token);
} else {
inlinerContext.outputTokens.push(token);
@@ -206,9 +205,9 @@ function inlineStylesheet(token, inlinerContext) {
var mediaQuery = uriAndMediaQuery[1];
var metadata = token[2];
return isRemoteResource(uri) ?
inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) :
inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext);
return isRemoteResource(uri)
? inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext)
: inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext);
}
function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {
@@ -221,25 +220,25 @@ function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {
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) {
} 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) {
} 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) {
} 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) {
} 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) {
} 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);
@@ -252,7 +251,7 @@ function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {
if (error) {
inlinerContext.errors.push('Broken @import declaration of "' + uri + '" - ' + error);
return process.nextTick(function () {
return process.nextTick(function() {
inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));
inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);
doInlineImports(inlinerContext);
@@ -266,7 +265,7 @@ function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {
inlinerContext.externalContext.sourcesContent[uri] = importedStyles;
inlinerContext.externalContext.stats.originalSize += importedStyles.length;
return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) {
return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function(importedTokens) {
importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata);
inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens);
@@ -276,37 +275,38 @@ function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {
});
}
return isLoaded ?
whenLoaded(null, inlinerContext.externalContext.sourcesContent[uri]) :
inlinerContext.fetch(uri, inlinerContext.inlineRequest, inlinerContext.inlineTimeout, whenLoaded);
return isLoaded
? whenLoaded(null, inlinerContext.externalContext.sourcesContent[uri])
: inlinerContext.fetch(uri, inlinerContext.inlineRequest, inlinerContext.inlineTimeout, whenLoaded);
}
function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) {
var protocolLessUri = uri.replace(FILE_RESOURCE_PROTOCOL, '');
var currentPath = path.resolve('');
var absoluteUri = path.isAbsolute(uri) ?
path.resolve(currentPath, uri[0] == '/' ? uri.substring(1) : uri) :
path.resolve(inlinerContext.rebaseTo, uri);
var absoluteUri = path.isAbsolute(protocolLessUri)
? path.resolve(currentPath, protocolLessUri[0] == '/' ? protocolLessUri.substring(1) : protocolLessUri)
: path.resolve(inlinerContext.rebaseTo, protocolLessUri);
var relativeToCurrentPath = path.relative(currentPath, absoluteUri);
var importedStyles;
var isAllowed = isAllowedResource(uri, false, inlinerContext.inline);
var isAllowed = isAllowedResource(protocolLessUri, 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.');
inlinerContext.warnings.push('Ignoring local @import of "' + protocolLessUri + '" as it has already been imported.');
} else if (isAllowed && !isLoaded && (!fs.existsSync(absoluteUri) || !fs.statSync(absoluteUri).isFile())) {
inlinerContext.errors.push('Ignoring local @import of "' + protocolLessUri + '" 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.');
inlinerContext.warnings.push('Ignoring local @import of "' + protocolLessUri + '" 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.');
inlinerContext.warnings.push('Ignoring local @import of "' + protocolLessUri + '" as after other content.');
} else if (!isAllowed) {
inlinerContext.warnings.push('Skipping local @import of "' + uri + '" as resource is not allowed.');
inlinerContext.warnings.push('Skipping local @import of "' + protocolLessUri + '" 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');
importedStyles = isLoaded
? inlinerContext.externalContext.sourcesContent[normalizedPath]
: fs.readFileSync(absoluteUri, 'utf-8');
inlinerContext.inlinedStylesheets.push(absoluteUri);
inlinerContext.inline = inlinerContext.externalContext.options.inline;
@@ -315,7 +315,7 @@ function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) {
inlinerContext.externalContext.sourcesContent[normalizedPath] = importedStyles;
inlinerContext.externalContext.stats.originalSize += importedStyles.length;
return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) {
return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function(importedTokens) {
importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata);
inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens);
@@ -333,9 +333,8 @@ function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) {
function wrapInMedia(tokens, mediaQuery, metadata) {
if (mediaQuery) {
return [[Token.NESTED_BLOCK, [[Token.NESTED_BLOCK_SCOPE, '@media ' + mediaQuery, metadata]], tokens]];
} else {
return tokens;
}
return tokens;
}
module.exports = readSources;

View File

@@ -8,9 +8,9 @@ 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);
return rebaseAll
? rebaseEverything(tokens, validator, rebaseConfig)
: rebaseAtRules(tokens, validator, rebaseConfig);
}
function rebaseEverything(tokens, validator, rebaseConfig) {
@@ -21,21 +21,21 @@ function rebaseEverything(tokens, validator, rebaseConfig) {
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;
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;
}
}
@@ -50,9 +50,9 @@ function rebaseAtRules(tokens, validator, rebaseConfig) {
token = tokens[i];
switch (token[0]) {
case Token.AT_RULE:
rebaseAtRule(token, validator, rebaseConfig);
break;
case Token.AT_RULE:
rebaseAtRule(token, validator, rebaseConfig);
break;
}
}

View File

@@ -11,7 +11,7 @@ var URL_SUFFIX = ')';
var PROTOCOL_LESS_PREFIX_PATTERN = /^[^\w\d]*\/\//;
var QUOTE_PREFIX_PATTERN = /^["']/;
var QUOTE_SUFFIX_PATTERN = /["']$/;
var ROUND_BRACKETS_PATTERN = /[\(\)]/;
var ROUND_BRACKETS_PATTERN = /[()]/;
var URL_PREFIX_PATTERN = /^url\(/i;
var URL_SUFFIX_PATTERN = /\)$/;
var WHITESPACE_PATTERN = /\s/;
@@ -35,9 +35,9 @@ function rebase(uri, rebaseConfig) {
return url.resolve(rebaseConfig.toBase, uri);
}
return rebaseConfig.absolute ?
normalize(absolute(uri, rebaseConfig)) :
normalize(relative(uri, rebaseConfig));
return rebaseConfig.absolute
? normalize(absolute(uri, rebaseConfig))
: normalize(relative(uri, rebaseConfig));
}
function isAbsolute(uri) {
@@ -73,13 +73,12 @@ function normalize(uri) {
function quoteFor(unquotedUrl) {
if (unquotedUrl.indexOf(SINGLE_QUOTE) > -1) {
return DOUBLE_QUOTE;
} else if (unquotedUrl.indexOf(DOUBLE_QUOTE) > -1) {
} if (unquotedUrl.indexOf(DOUBLE_QUOTE) > -1) {
return SINGLE_QUOTE;
} else if (hasWhitespace(unquotedUrl) || hasRoundBrackets(unquotedUrl)) {
} if (hasWhitespace(unquotedUrl) || hasRoundBrackets(unquotedUrl)) {
return SINGLE_QUOTE;
} else {
return '';
}
return '';
}
function hasWhitespace(url) {
@@ -101,13 +100,13 @@ function rewriteUrl(originalUrl, rebaseConfig, pathOnly) {
.replace(QUOTE_SUFFIX_PATTERN, '')
.trim();
var quote = strippedUrl[0] == SINGLE_QUOTE || strippedUrl[0] == DOUBLE_QUOTE ?
strippedUrl[0] :
quoteFor(unquotedUrl);
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;
return pathOnly
? rebase(unquotedUrl, rebaseConfig)
: URL_PREFIX + quote + rebase(unquotedUrl, rebaseConfig) + quote + URL_SUFFIX;
}
module.exports = rewriteUrl;

View File

@@ -28,8 +28,8 @@ var BLOCK_RULES = [
'@supports'
];
var IGNORE_END_COMMENT_PATTERN = /\/\* clean\-css ignore:end \*\/$/;
var IGNORE_START_COMMENT_PATTERN = /^\/\* clean\-css ignore:start \*\//;
var IGNORE_END_COMMENT_PATTERN = /\/\* clean-css ignore:end \*\/$/;
var IGNORE_START_COMMENT_PATTERN = /^\/\* clean-css ignore:start \*\//;
var PAGE_MARGIN_BOXES = [
'@bottom-center',
@@ -60,8 +60,8 @@ var EXTRA_PAGE_BOXES = [
];
var REPEAT_PATTERN = /^\[\s{0,31}\d+\s{0,31}\]$/;
var RULE_WORD_SEPARATOR_PATTERN = /[\s\(]/;
var TAIL_BROKEN_VALUE_PATTERN = /[\s|\}]*$/;
var TAIL_BROKEN_VALUE_PATTERN = /([^}])\}*$/;
var RULE_WORD_SEPARATOR_PATTERN = /[\s(]/;
function tokenize(source, externalContext) {
var internalContext = {
@@ -107,6 +107,8 @@ function intoTokens(source, externalContext, internalContext, isNested) {
var isEscaped;
var wasEscaped = false;
var characterWithNoSpecialMeaning;
var isPreviousDash = false;
var isVariable = false;
var isRaw = false;
var seekingValue = false;
var seekingPropertyBlockClosing = false;
@@ -119,17 +121,25 @@ function intoTokens(source, externalContext, internalContext, isNested) {
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;
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;
characterWithNoSpecialMeaning = !isSpace && !isCarriageReturn && (character >= 'A' && character <= 'Z' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '-');
isVariable = isVariable || (level != Level.COMMENT && !seekingValue && isPreviousDash && character === '-');
isPreviousDash = character === '-';
roundBracketLevel = Math.max(roundBracketLevel, 0);
metadata = isBufferEmpty ?
[position.line, position.column, position.source] :
metadata;
metadata = isBufferEmpty
? [position.line, position.column, position.source]
: metadata;
if (isEscaped) {
// previous character was a backslash
@@ -150,6 +160,15 @@ function intoTokens(source, externalContext, internalContext, isNested) {
} else if (!isCommentStart && !isCommentEnd && isRaw) {
buffer.push(character);
isBufferEmpty = false;
} else if (isCommentStart
&& isVariable
&& (level == Level.BLOCK || level == Level.RULE) && buffer.length > 1) {
// comment start within a variable, e.g. var(/*<--
buffer.push(character);
isBufferEmpty = false;
levels.push(level);
level = Level.COMMENT;
} 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);
@@ -168,10 +187,18 @@ function intoTokens(source, externalContext, internalContext, isNested) {
level = Level.COMMENT;
buffer.push(character);
isBufferEmpty = false;
} else if (isCommentEnd && isVariable) {
// comment end within a variable, e.g. var(/*!*/<--
buffer.push(character);
level = levels.pop();
} 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)]];
lastToken = [
Token.COMMENT,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
];
newTokens.push(lastToken);
isRaw = true;
@@ -184,12 +211,20 @@ function intoTokens(source, externalContext, internalContext, isNested) {
lastCommentStartAt = serializedBuffer.lastIndexOf(Marker.FORWARD_SLASH + Marker.ASTERISK);
serializedBufferPart = serializedBuffer.substring(0, lastCommentStartAt);
lastToken = [Token.RAW, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]];
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)]];
lastToken = [
Token.COMMENT,
serializedBufferPart,
[originalMetadata(metadata, serializedBufferPart, externalContext)]
];
newTokens.push(lastToken);
isRaw = false;
@@ -200,7 +235,11 @@ function intoTokens(source, externalContext, internalContext, isNested) {
} else if (isCommentEnd) {
// comment end, e.g. /* comment */<--
serializedBuffer = buffer.join('').trim() + character;
lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]];
lastToken = [
Token.COMMENT,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
];
newTokens.push(lastToken);
level = levels.pop();
@@ -233,17 +272,24 @@ function intoTokens(source, externalContext, internalContext, isNested) {
level = levels.pop();
buffer.push(character);
isBufferEmpty = false;
} else if (!isCommentStart && !isCommentEnd && character != Marker.CLOSE_ROUND_BRACKET && character != Marker.OPEN_ROUND_BRACKET && level != Level.COMMENT && !isQuoted && roundBracketLevel > 0) {
} else if (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);
isBufferEmpty = false;
} else if (character == Marker.OPEN_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) {
} else if (character == Marker.OPEN_ROUND_BRACKET
&& !isQuoted && level != Level.COMMENT
&& !seekingValue) {
// round open bracket, e.g. @import url(<--
buffer.push(character);
isBufferEmpty = false;
roundBracketLevel++;
} else if (character == Marker.CLOSE_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) {
} else if (character == Marker.CLOSE_ROUND_BRACKET
&& !isQuoted
&& level != Level.COMMENT
&& !seekingValue) {
// round open bracket, e.g. @import url(test.css)<--
buffer.push(character);
isBufferEmpty = false;
@@ -252,14 +298,22 @@ function intoTokens(source, externalContext, internalContext, isNested) {
} 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)]]);
allTokens.push([
Token.AT_RULE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
buffer = [];
isBufferEmpty = true;
} 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)]]);
ruleToken[1].push([
tokenScopeFrom(ruleToken[0]),
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]
]);
buffer = [];
isBufferEmpty = true;
@@ -272,14 +326,25 @@ function intoTokens(source, externalContext, internalContext, isNested) {
// 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)]]);
ruleToken[1].push([
tokenScopeFrom(ruleToken[0]),
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext, 0)]
]);
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && ruleToken && ruleToken[0] == Token.NESTED_BLOCK) {
} 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)]]);
ruleToken[1].push([
Token.NESTED_BLOCK_SCOPE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
allTokens.push(ruleToken);
levels.push(level);
@@ -290,11 +355,17 @@ function intoTokens(source, externalContext, internalContext, isNested) {
ruleToken[2] = intoTokens(source, externalContext, internalContext, true);
ruleToken = null;
} else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.NESTED_BLOCK) {
} 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)]]);
ruleToken[1].push([
Token.NESTED_BLOCK_SCOPE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
allTokens.push(ruleToken);
levels.push(level);
@@ -302,6 +373,7 @@ function intoTokens(source, externalContext, internalContext, isNested) {
position.index++;
buffer = [];
isBufferEmpty = true;
isVariable = false;
ruleToken[2] = intoTokens(source, externalContext, internalContext, true);
ruleToken = null;
@@ -309,7 +381,11 @@ function intoTokens(source, externalContext, internalContext, isNested) {
// 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)]]);
ruleToken[1].push([
tokenScopeFrom(ruleToken[0]),
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]
]);
newTokens = ruleToken[2];
allTokens.push(ruleToken);
@@ -332,7 +408,11 @@ function intoTokens(source, externalContext, internalContext, isNested) {
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)]]);
ruleToken[1].push([
Token.AT_RULE_BLOCK_SCOPE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
newTokens.push(ruleToken);
newTokens = ruleToken[2];
@@ -343,36 +423,75 @@ function intoTokens(source, externalContext, internalContext, isNested) {
} 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)]]];
propertyToken = [
Token.PROPERTY,
[
Token.PROPERTY_NAME,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]
];
newTokens.push(propertyToken);
seekingValue = true;
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && ruleTokens.length > 0 && !isBufferEmpty && buffer[0] == Marker.AT) {
} else if (character == Marker.SEMICOLON
&& level == Level.RULE
&& propertyToken
&& ruleTokens.length > 0
&& !isBufferEmpty
&& 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)]]);
ruleToken[1].push([
Token.AT_RULE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && !isBufferEmpty) {
// semicolon at rule level, e.g. a{color:red;<--
serializedBuffer = buffer.join('').trim();
propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
propertyToken = null;
seekingValue = false;
buffer = [];
isBufferEmpty = true;
isVariable = false;
} else if (character == Marker.SEMICOLON
&& level == Level.RULE
&& propertyToken
&& isBufferEmpty
&& isVariable
&& !propertyToken[2]) {
// semicolon after empty variable value at rule level, e.g. a{--color: ;<--
propertyToken.push([Token.PROPERTY_VALUE, ' ', [originalMetadata(metadata, ' ', externalContext)]]);
isVariable = false;
propertyToken = null;
seekingValue = false;
} else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && isBufferEmpty) {
// semicolon after bracketed value at rule level, e.g. a{color:rgb(...);<--
propertyToken = null;
seekingValue = false;
} else if (character == Marker.SEMICOLON && level == Level.RULE && !isBufferEmpty && buffer[0] == Marker.AT) {
} else if (character == Marker.SEMICOLON
&& level == Level.RULE
&& !isBufferEmpty
&& 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)]]);
newTokens.push([
Token.AT_RULE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
seekingValue = false;
buffer = [];
@@ -385,10 +504,18 @@ function intoTokens(source, externalContext, internalContext, isNested) {
} else if (character == Marker.SEMICOLON && level == Level.RULE && isBufferEmpty) {
// stray semicolon at rule level, e.g. a{;<--
// noop
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && seekingValue && !isBufferEmpty && ruleTokens.length > 0) {
} else if (character == Marker.CLOSE_CURLY_BRACKET
&& level == Level.RULE
&& propertyToken
&& seekingValue
&& !isBufferEmpty && 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.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
propertyToken = null;
ruleToken = ruleTokens.pop();
newTokens = ruleToken[2];
@@ -397,10 +524,19 @@ function intoTokens(source, externalContext, internalContext, isNested) {
seekingValue = false;
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && !isBufferEmpty && buffer[0] == Marker.AT && ruleTokens.length > 0) {
} else if (character == Marker.CLOSE_CURLY_BRACKET
&& level == Level.RULE
&& propertyToken
&& !isBufferEmpty
&& 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)]]);
ruleToken[1].push([
Token.AT_RULE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
propertyToken = null;
ruleToken = ruleTokens.pop();
newTokens = ruleToken[2];
@@ -409,7 +545,10 @@ function intoTokens(source, externalContext, internalContext, isNested) {
seekingValue = false;
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && ruleTokens.length > 0) {
} 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();
@@ -417,10 +556,17 @@ function intoTokens(source, externalContext, internalContext, isNested) {
level = levels.pop();
seekingValue = false;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && !isBufferEmpty) {
} else if (character == Marker.CLOSE_CURLY_BRACKET
&& level == Level.RULE
&& propertyToken
&& !isBufferEmpty) {
// close brace at rule level, e.g. a{color:red}<--
serializedBuffer = buffer.join('');
propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
propertyToken = null;
ruleToken = ruleTokens.pop();
newTokens = allTokens;
@@ -429,19 +575,28 @@ function intoTokens(source, externalContext, internalContext, isNested) {
seekingValue = false;
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && !isBufferEmpty && buffer[0] == Marker.AT) {
} else if (character == Marker.CLOSE_CURLY_BRACKET
&& level == Level.RULE
&& !isBufferEmpty
&& 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.push([
Token.AT_RULE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
newTokens = allTokens;
level = levels.pop();
seekingValue = false;
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && levels[levels.length - 1] == Level.RULE) {
} 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();
@@ -452,6 +607,21 @@ function intoTokens(source, externalContext, internalContext, isNested) {
seekingPropertyBlockClosing = true;
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.CLOSE_CURLY_BRACKET
&& level == Level.RULE
&& isVariable
&& propertyToken
&& !propertyToken[2]) {
// close brace after an empty variable declaration inside a rule, e.g. a{--color: }<--
propertyToken.push([Token.PROPERTY_VALUE, ' ', [originalMetadata(metadata, ' ', externalContext)]]);
isVariable = false;
propertyToken = null;
ruleToken = null;
newTokens = allTokens;
level = levels.pop();
seekingValue = false;
isVariable = false;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE) {
// close brace after a rule, e.g. a{color:red;}<--
propertyToken = null;
@@ -460,7 +630,11 @@ function intoTokens(source, externalContext, internalContext, isNested) {
level = levels.pop();
seekingValue = false;
} else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK && !isNested && position.index <= source.length - 1) {
isVariable = 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);
@@ -473,67 +647,123 @@ function intoTokens(source, externalContext, internalContext, isNested) {
buffer.push(character);
isBufferEmpty = false;
roundBracketLevel++;
} else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue && roundBracketLevel == 1) {
} 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);
isBufferEmpty = false;
serializedBuffer = buffer.join('').trim();
propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
roundBracketLevel--;
buffer = [];
isBufferEmpty = true;
isVariable = false;
} 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);
isBufferEmpty = false;
isVariable = false;
roundBracketLevel--;
} else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue && !isBufferEmpty) {
} else if (character == Marker.FORWARD_SLASH
&& source[position.index + 1] != Marker.ASTERISK
&& level == Level.RULE
&& seekingValue
&& !isBufferEmpty) {
// 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]]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
propertyToken.push([
Token.PROPERTY_VALUE,
character,
[[position.line, position.column, position.source]]
]);
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue) {
} 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]]]);
propertyToken.push([
Token.PROPERTY_VALUE,
character,
[[position.line, position.column, position.source]]
]);
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.COMMA && level == Level.RULE && seekingValue && !isBufferEmpty) {
// 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]]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
propertyToken.push([
Token.PROPERTY_VALUE,
character,
[[position.line, position.column, position.source]]
]);
buffer = [];
isBufferEmpty = true;
} 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]]]);
propertyToken.push([
Token.PROPERTY_VALUE,
character,
[[position.line, position.column, position.source]]
]);
buffer = [];
isBufferEmpty = true;
} else if (character == Marker.CLOSE_SQUARE_BRACKET && propertyToken && propertyToken.length > 1 && !isBufferEmpty && isRepeatToken(buffer)) {
} else if (character == Marker.CLOSE_SQUARE_BRACKET
&& propertyToken
&& propertyToken.length > 1
&& !isBufferEmpty
&& isRepeatToken(buffer)) {
buffer.push(character);
serializedBuffer = buffer.join('').trim();
propertyToken[propertyToken.length - 1][1] += serializedBuffer;
buffer = [];
isBufferEmpty = true;
} else if ((isSpace || (isNewLineNix && !isNewLineWin)) && level == Level.RULE && seekingValue && propertyToken && !isBufferEmpty) {
} else if ((isSpace || (isNewLineNix && !isNewLineWin))
&& level == Level.RULE
&& seekingValue
&& propertyToken
&& !isBufferEmpty) {
// 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)]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
buffer = [];
isBufferEmpty = true;
} 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)]]);
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
buffer = [];
isBufferEmpty = true;
@@ -565,8 +795,12 @@ function intoTokens(source, externalContext, internalContext, isNested) {
}
if (seekingValue && buffer.length > 0) {
serializedBuffer = buffer.join('').replace(TAIL_BROKEN_VALUE_PATTERN, '');
propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);
serializedBuffer = buffer.join('').trimRight().replace(TAIL_BROKEN_VALUE_PATTERN, '$1').trimRight();
propertyToken.push([
Token.PROPERTY_VALUE,
serializedBuffer,
[originalMetadata(metadata, serializedBuffer, externalContext)]
]);
buffer = [];
}
@@ -589,9 +823,9 @@ function isIgnoreEndComment(buffer) {
function originalMetadata(metadata, value, externalContext, selectorFallbacks) {
var source = metadata[2];
return externalContext.inputSourceMapTracker.isTracking(source) ?
externalContext.inputSourceMapTracker.originalPositionFor(metadata, value.length, selectorFallbacks) :
metadata;
return externalContext.inputSourceMapTracker.isTracking(source)
? externalContext.inputSourceMapTracker.originalPositionFor(metadata, value.length, selectorFallbacks)
: metadata;
}
function tokenTypeFrom(buffer) {
@@ -600,21 +834,20 @@ function tokenTypeFrom(buffer) {
if (isAtRule && BLOCK_RULES.indexOf(ruleWord) > -1) {
return Token.NESTED_BLOCK;
} else if (isAtRule && AT_RULES.indexOf(ruleWord) > -1) {
} if (isAtRule && AT_RULES.indexOf(ruleWord) > -1) {
return Token.AT_RULE;
} else if (isAtRule) {
} if (isAtRule) {
return Token.AT_RULE_BLOCK;
} else {
return Token.RULE;
}
return Token.RULE;
}
function tokenScopeFrom(tokenType) {
if (tokenType == Token.RULE) {
return Token.RULE_SCOPE;
} else if (tokenType == Token.NESTED_BLOCK) {
} if (tokenType == Token.NESTED_BLOCK) {
return Token.NESTED_BLOCK_SCOPE;
} else if (tokenType == Token.AT_RULE_BLOCK) {
} if (tokenType == Token.AT_RULE_BLOCK) {
return Token.AT_RULE_BLOCK_SCOPE;
}
}

View File

@@ -2,8 +2,7 @@ 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]);
if (Array.isArray(cloned[i])) { cloned[i] = cloneArray(cloned[i]); }
}
return cloned;

View File

@@ -3,9 +3,9 @@ function formatPosition(metadata) {
var column = metadata[1];
var source = metadata[2];
return source ?
source + ':' + line + ':' + column :
line + ':' + column;
return source
? source + ':' + line + ':' + column
: line + ':' + column;
}
module.exports = formatPosition;

View File

@@ -1,4 +1,4 @@
var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/;
var DATA_URI_PATTERN = /^data:(\S{0,31}?)?(;charset=(?:(?!;charset=)[^;])+)?(;[^,]+?)?,(.+)/;
function isDataUriResource(uri) {
return DATA_URI_PATTERN.test(uri);

View File

@@ -1,7 +1,8 @@
var REMOTE_RESOURCE_PATTERN = /^(\w+:\/\/|\/\/)/;
var FILE_RESOURCE_PATTERN = /^file:\/\//;
function isRemoteResource(uri) {
return REMOTE_RESOURCE_PATTERN.test(uri);
return REMOTE_RESOURCE_PATTERN.test(uri) && !FILE_RESOURCE_PATTERN.test(uri);
}
module.exports = isRemoteResource;

View File

@@ -23,9 +23,9 @@ function naturalCompare(value1, value2) {
}
function tryParseInt(value) {
return ('' + parseInt(value)) == value ?
parseInt(value) :
value;
return ('' + parseInt(value)) == value
? parseInt(value)
: value;
}
module.exports = naturalCompare;

View File

@@ -1,5 +1,11 @@
var Marker = require('../tokenizer/marker');
function is(value, separator, isSeparatorRegex) {
return isSeparatorRegex
? separator.test(value)
: value === separator;
}
function split(value, separator) {
var openLevel = Marker.OPEN_ROUND_BRACKET;
var closeLevel = Marker.CLOSE_ROUND_BRACKET;
@@ -10,8 +16,9 @@ function split(value, separator) {
var lastCharacter;
var len = value.length;
var parts = [];
var isSeparatorRegex = typeof (separator) == 'object' && 'exec' in separator;
if (value.indexOf(separator) == -1) {
if (!isSeparatorRegex && value.indexOf(separator) == -1) {
return [value];
}
@@ -26,8 +33,13 @@ function split(value, separator) {
level--;
}
if (level === 0 && cursor > 0 && cursor + 1 < len && value[cursor] == separator) {
if (level === 0 && cursor > 0 && cursor + 1 < len && is(value[cursor], separator, isSeparatorRegex)) {
parts.push(value.substring(lastStart, cursor));
if (isSeparatorRegex && separator.exec(value[cursor]).length > 1) {
parts.push(value[cursor]);
}
lastStart = cursor + 1;
}
@@ -37,7 +49,7 @@ function split(value, separator) {
if (lastStart < cursor + 1) {
lastValue = value.substring(lastStart);
lastCharacter = lastValue[lastValue.length - 1];
if (lastCharacter == separator) {
if (is(lastCharacter, separator, isSeparatorRegex)) {
lastValue = lastValue.substring(0, lastValue.length - 1);
}

View File

@@ -35,11 +35,13 @@ function inFilter(token) {
}
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);
return !context.spaceAfterClosingBrace
&& supportsAfterClosingBrace(token)
&& afterClosingBrace(token, valueIndex)
|| beforeSlash(token, valueIndex)
|| afterSlash(token, valueIndex)
|| beforeComma(token, valueIndex)
|| afterComma(token, valueIndex);
}
function rules(context, tokens) {
@@ -82,10 +84,10 @@ function property(context, tokens, position, lastPropertyAt) {
var isPropertyBlock = propertyValue && propertyValue[0] === Token.PROPERTY_BLOCK;
var needsSemicolon;
if ( context.format ) {
if ( context.format.semicolonAfterLastProperty || isPropertyBlock ) {
if (context.format) {
if (context.format.semicolonAfterLastProperty || isPropertyBlock) {
needsSemicolon = true;
} else if ( position < lastPropertyAt ) {
} else if (position < lastPropertyAt) {
needsSemicolon = true;
} else {
needsSemicolon = false;
@@ -97,30 +99,33 @@ function property(context, tokens, position, lastPropertyAt) {
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);
store(context, breakFor(context, Breaks.AfterComment) + context.indentWith);
break;
case Token.PROPERTY:
store(context, token[1]);
store(context, colon(context));
if (propertyValue) {
value(context, token);
}
store(context, needsSemicolon ? semicolon(context, Breaks.AfterProperty, isLast) : emptyCharacter);
break;
case Token.RAW:
store(context, token);
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);
store(context, breakFor(context, Breaks.AfterComment) + context.indentWith);
break;
case Token.PROPERTY:
store(context, token[1]);
store(context, colon(context));
if (propertyValue) {
value(context, token);
}
store(
context,
needsSemicolon ? semicolon(context, Breaks.AfterProperty, isLast) : emptyCharacter
);
break;
case Token.RAW:
store(context, token);
}
}
@@ -155,44 +160,47 @@ 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 +
breakFor(context, where) +
context.indentWith;
} else {
return Marker.OPEN_CURLY_BRACKET;
return (
needsPrefixSpace
&& allowsSpace(context, Spaces.BeforeBlockBegins) ? Marker.SPACE : emptyCharacter
) + Marker.OPEN_CURLY_BRACKET
+ breakFor(context, where)
+ context.indentWith;
}
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 (beforeBlockEnd ? breakFor(context, Breaks.BeforeBlockEnds) : breakFor(context, Breaks.AfterProperty)) +
context.indentWith +
Marker.CLOSE_CURLY_BRACKET +
(isLast ? emptyCharacter : breakFor(context, where) + context.indentWith);
} else {
return Marker.CLOSE_CURLY_BRACKET;
return (
beforeBlockEnd
? breakFor(context, Breaks.BeforeBlockEnds)
: breakFor(context, Breaks.AfterProperty)
) + context.indentWith
+ Marker.CLOSE_CURLY_BRACKET
+ (isLast ? emptyCharacter : breakFor(context, where) + context.indentWith);
}
return Marker.CLOSE_CURLY_BRACKET;
}
function colon(context) {
return context.format ?
Marker.COLON + (allowsSpace(context, Spaces.BeforeValue) ? Marker.SPACE : emptyCharacter) :
Marker.COLON;
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 ? emptyCharacter : (breakFor(context, where) + context.indentWith)) :
Marker.SEMICOLON;
return context.format
? Marker.SEMICOLON + (isLast ? emptyCharacter : (breakFor(context, where) + context.indentWith))
: Marker.SEMICOLON;
}
function comma(context) {
return context.format ?
Marker.COMMA + breakFor(context, Breaks.BetweenSelectors) + context.indentWith :
Marker.COMMA;
return context.format
? Marker.COMMA + breakFor(context, Breaks.BetweenSelectors) + context.indentWith
: Marker.COMMA;
}
function all(context, tokens) {
@@ -206,35 +214,35 @@ function all(context, tokens) {
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, breakFor(context, Breaks.AfterComment) + context.indentWith);
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;
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, breakFor(context, Breaks.AfterComment) + context.indentWith);
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;
}
}
}

View File

@@ -1,9 +1,9 @@
var all = require('./helpers').all;
function store(serializeContext, token) {
var value = typeof token == 'string' ?
token :
token[1];
var value = typeof token == 'string'
? token
: token[1];
var wrap = serializeContext.wrap;
wrap(serializeContext, value);
@@ -35,16 +35,14 @@ function serializeStyles(tokens, context) {
output: [],
spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace,
store: store,
wrap: context.options.format.wrapAt ?
wrap :
function () { /* noop */ }
wrap: context.options.format.wrapAt
? wrap
: function() { /* noop */ }
};
all(serializeContext, tokens);
return {
styles: serializeContext.output.join('')
};
return { styles: serializeContext.output.join('') };
}
module.exports = serializeStyles;

View File

@@ -68,7 +68,10 @@ function trackMapping(serializeContext, mapping) {
});
if (serializeContext.inlineSources && (originalSource in serializeContext.sourcesContent)) {
serializeContext.outputMap.setSourceContent(storedSource, serializeContext.sourcesContent[originalSource]);
serializeContext.outputMap.setSourceContent(
storedSource,
serializeContext.sourcesContent[originalSource]
);
}
}
@@ -85,9 +88,9 @@ function serializeStylesAndSourceMap(tokens, context) {
sourcesContent: context.sourcesContent,
spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace,
store: store,
wrap: context.options.format.wrapAt ?
wrap :
function () { /* noop */ }
wrap: context.options.format.wrapAt
? wrap
: function() { /* noop */ }
};
all(serializeContext, tokens);

37
node_modules/clean-css/package.json generated vendored
View File

@@ -1,35 +1,34 @@
{
"_from": "clean-css@5.1.2",
"_id": "clean-css@5.1.2",
"_from": "clean-css@^5.1.2",
"_id": "clean-css@5.3.1",
"_inBundle": false,
"_integrity": "sha512-QcaGg9OuMo+0Ds933yLOY+gHPWbxhxqF0HDexmToPf8pczvmvZGYzd+QqWp9/mkucAOKViI+dSFOqoZIvXbeBw==",
"_integrity": "sha512-lCr8OHhiWCTw4v8POJovCoh4T7I9U11yVsPjMWWnnMmp9ZowCxyad1Pathle/9HjaDp+fdQKjO9fQydE6RHTZg==",
"_location": "/clean-css",
"_phantomChildren": {},
"_requested": {
"type": "version",
"type": "range",
"registry": true,
"raw": "clean-css@5.1.2",
"raw": "clean-css@^5.1.2",
"name": "clean-css",
"escapedName": "clean-css",
"rawSpec": "5.1.2",
"rawSpec": "^5.1.2",
"saveSpec": null,
"fetchSpec": "5.1.2"
"fetchSpec": "^5.1.2"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/clean-css/-/clean-css-5.1.2.tgz",
"_shasum": "6ea0da7286b4ddc2469a1b776e2461a5007eed54",
"_spec": "clean-css@5.1.2",
"_resolved": "https://registry.npmjs.org/clean-css/-/clean-css-5.3.1.tgz",
"_shasum": "d0610b0b90d125196a2894d35366f734e5d7aa32",
"_spec": "clean-css@^5.1.2",
"_where": "D:\\Projects\\minifyfromhtml",
"author": {
"name": "Jakub Pawlowicz",
"email": "contact@jakubpawlowicz.com",
"url": "https://jakubpawlowicz.com"
"email": "contact@jakubpawlowicz.com"
},
"bugs": {
"url": "https://github.com/jakubpawlowicz/clean-css/issues"
"url": "https://github.com/clean-css/clean-css/issues"
},
"bundleDependencies": false,
"dependencies": {
@@ -39,8 +38,9 @@
"description": "A well-tested CSS minifier",
"devDependencies": {
"browserify": "^17.0.0",
"eslint": "^8.8.0",
"eslint-config-airbnb-base": "^15.0.0",
"http-proxy": "1.x",
"jshint": "2.x",
"nock": "^13.0.0",
"server-destroy": "1.x",
"uglify-js": ">=2.6.1",
@@ -55,7 +55,7 @@
"index.js",
"LICENSE"
],
"homepage": "https://github.com/jakubpawlowicz/clean-css",
"homepage": "https://github.com/clean-css/clean-css",
"keywords": [
"css",
"minifier"
@@ -65,14 +65,13 @@
"name": "clean-css",
"repository": {
"type": "git",
"url": "git+https://github.com/jakubpawlowicz/clean-css.git"
"url": "git+https://github.com/clean-css/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",
"lint": "eslint ./lib/ --ext .js",
"test": "vows"
},
"version": "5.1.2"
"version": "5.3.1"
}