diff --git a/README.md b/README.md index df882188..4f9ccbd3 100644 --- a/README.md +++ b/README.md @@ -9,169 +9,40 @@ CSSO (CSS Optimizer) is a CSS minifier. It performs three sort of transformation [![Originated by Yandex](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/yandex.svg)](https://www.yandex.com/) [![Sponsored by Avito](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/avito.svg)](https://www.avito.ru/) -## Usage - -``` -npm install -g csso -``` - -Or try out CSSO [right in your browser](http://css.github.io/csso/csso.html) (web interface). - -### Runners - + + +- [Ready to use](#ready-to-use) +- [Install](#install) +- [API](#api) + - [minify\(source\[, options\]\)](#minifysource-options) + - [minifyBlock\(source\[, options\]\)](#minifyblocksource-options) + - [compress\(ast\[, options\]\)](#compressast-options) + - [Source maps](#source-maps) + - [Usage data](#usage-data) + - [Selector filtering](#selector-filtering) + - [Scopes](#scopes) + - [Debugging](#debugging) +- [License](#license) + + + +## Ready to use + +- [Web interface](http://css.github.io/csso/csso.html) +- CLI: [csso-cli](/~https://github.com/css/csso-cli) - Gulp: [gulp-csso](/~https://github.com/ben-eb/gulp-csso) - Grunt: [grunt-csso](/~https://github.com/t32k/grunt-csso) - Broccoli: [broccoli-csso](/~https://github.com/sindresorhus/broccoli-csso) - PostCSS: [postcss-csso](/~https://github.com/lahmatiy/postcss-csso) - Webpack: [csso-loader](/~https://github.com/sandark7/csso-loader) -### Command line - -``` -csso [input] [output] [options] - -Options: - - --comments Comments to keep: exclamation (default), first-exclamation or none - --debug [level] Output intermediate state of CSS during compression - -h, --help Output usage information - -i, --input Input file - --input-map Input source map: none, auto (default) or - -m, --map Generate source map: none (default), inline, file or - -o, --output Output file (result outputs to stdout if not set) - --restructure-off Turns structure minimization off - --stat Output statistics in stderr - -u, --usage Usage data file - -v, --version Output version -``` - -Some examples: - -``` -> csso in.css -...output result in stdout... - -> csso in.css --output out.css - -> echo '.test { color: #ff0000; }' | csso -.test{color:red} - -> cat source1.css source2.css | csso | gzip -9 -c > production.css.gz -``` - -### Source maps - -Source map doesn't generate by default. To generate map use `--map` CLI option, that can be: - -- `none` (default) – don't generate source map -- `inline` – add source map into result CSS (via `/*# sourceMappingURL=application/json;base64,... */`) -- `file` – write source map into file with same name as output file, but with `.map` extension (in this case `--output` option is required) -- any other values treat as filename for generated source map - -Examples: +## Install ``` -> csso my.css --map inline -> csso my.css --output my.min.css --map file -> csso my.css --output my.min.css --map maps/my.min.map -``` - -Use `--input-map` option to specify input source map if needed. Possible values for option: - -- `auto` (default) - attempt to fetch input source map by follow steps: - - try to fetch inline map from input - - try to fetch source map filename from input and read its content - - (when `--input` is specified) check file with same name as input file but with `.map` extension exists and read its content -- `none` - don't use input source map; actually it's using to disable `auto`-fetching -- any other values treat as filename for input source map - -Generally you shouldn't care about the input source map since defaults behaviour (`auto`) covers most use cases. - -> NOTE: Input source map is using only if output source map is generating. - -### Usage data - -`CSSO` can use data about how `CSS` is using for better compression. File with this data (`JSON` format) can be set using `--usage` option. Usage data may contain follow sections: - -- `tags` – white list of tags -- `ids` – white list of ids -- `classes` – white list of classes -- `scopes` – groups of classes which never used with classes from other groups on single element - -All sections are optional. Value of `tags`, `ids` and `classes` should be array of strings, value of `scopes` should be an array of arrays of strings. Other values are ignoring. - -#### Selector filtering - -`tags`, `ids` and `classes` are using on clean stage to filter selectors that contains something that not in list. Selectors are filtering only by those kind of simple selector which white list is specified. For example, if only `tags` list is specified then type selectors are checking, and if selector hasn't any type selector (or even any type selector) it isn't filter. - -> `ids` and `classes` names are case sensitive, `tags` – is not. - -Input CSS: - -```css -* { color: green; } -ul, ol, li { color: blue; } -UL.foo, span.bar { color: red; } -``` - -Usage data: - -```json -{ - "tags": ["ul", "LI"] -} -``` - -Result CSS: - -```css -*{color:green}ul,li{color:blue}ul.foo{color:red} -``` - -#### Scopes - -Scopes is designed for CSS scope isolation solutions such as [css-modules](/~https://github.com/css-modules/css-modules). Scopes are similar to namespaces and defines lists of class names that exclusively used on some markup. This information allows the optimizer to move rulesets more agressive. Since it assumes selectors from different scopes can't to be matched on the same element. That leads to better ruleset merging. - -Suppose we have a file: - -```css -.module1-foo { color: red; } -.module1-bar { font-size: 1.5em; background: yellow; } - -.module2-baz { color: red; } -.module2-qux { font-size: 1.5em; background: yellow; width: 50px; } -``` - -It can be assumed that first two rules are never used with the second two on the same markup. But we can't know that for sure without markup. The optimizer doesn't know it either and will perform safe transformations only. The result will be the same as input but with no spaces and some semicolons: - -```css -.module1-foo{color:red}.module1-bar{font-size:1.5em;background:#ff0}.module2-baz{color:red}.module2-qux{font-size:1.5em;background:#ff0;width:50px} -``` - -But with usage data `CSSO` can get better output. If follow usage data is provided: - -```json -{ - "scopes": [ - ["module1-foo", "module1-bar"], - ["module2-baz", "module2-qux"] - ] -} -``` - -New result (29 bytes extra saving): - -```css -.module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px} +npm install -g csso ``` -If class name doesn't specified in `scopes` it belongs to default "scope". `scopes` doesn't affect `classes`. If class name presents in `scopes` but missed in `classes` (both sections specified) it will be filtered. - -Note that class name can't be specified in several scopes. Also selector can't has classes from different scopes. In both cases an exception throws. - -Currently the optimizer doesn't care about out-of-bounds selectors order changing safety (i.e. selectors that may be matched to elements with no class name of scope, e.g. `.scope div` or `.scope ~ :last-child`) since assumes scoped CSS modules doesn't relay on it's order. It may be fix in future if to be an issue. - -### API +## API ```js var csso = require('csso'); @@ -209,7 +80,7 @@ console.log(result.map.toString()); // '{ .. source map content .. }' ``` -#### minify(source[, options]) +### minify(source[, options]) Minify `source` CSS passed as `String`. @@ -238,7 +109,7 @@ console.log(result.css); // > .test{color:red} ``` -#### minifyBlock(source[, options]) +### minifyBlock(source[, options]) The same as `minify()` but for style block. Usually it's a `style` attribute content. @@ -249,44 +120,7 @@ console.log(result.css); // > color:red ``` -#### parse(source[, options]) - -Parse CSS to AST. - -> NOTE: Currenly parser omit redundant separators, spaces and comments (except exclamation comments, i.e. `/*! comment */`) on AST build, since those things are removing by compressor anyway. - -Options: - -- context `String` – parsing context, useful when some part of CSS is parsing (see below) -- positions `Boolean` – should AST contains node position or not, store data in `info` property of nodes (`false` by default) -- filename `String` – filename of source that adds to info when `positions` is true, uses for source map generation (`` by default) -- line `Number` – initial line number, useful when parse fragment of CSS to compute correct positions -- column `Number` – initial column number, useful when parse fragment of CSS to compute correct positions - -Contexts: - -- `stylesheet` (default) – regular stylesheet, should be suitable in most cases -- `atrule` – at-rule (e.g. `@media screen, print { ... }`) -- `atruleExpression` – at-rule expression (`screen, print` for example above) -- `ruleset` – rule (e.g. `.foo, .bar:hover { color: red; border: 1px solid black; }`) -- `selector` – selector group (`.foo, .bar:hover` for ruleset example) -- `simpleSelector` – selector (`.foo` or `.bar:hover` for ruleset example) -- `block` – block content w/o curly braces (`color: red; border: 1px solid black;` for ruleset example) -- `declaration` – declaration (`color: red` or `border: 1px solid black` for ruleset example) -- `value` – declaration value (`red` or `1px solid black` for ruleset example) - -```js -// simple parsing with no options -var ast = csso.parse('.example { color: red }'); - -// parse with options -var ast = csso.parse('.foo.bar', { - context: 'simpleSelector', - positions: true -}); -``` - -#### compress(ast[, options]) +### compress(ast[, options]) Does the main task – compress AST. @@ -303,104 +137,95 @@ Options: - usage `Object` - usage data for advanced optimisations (see [Usage data](#usage-data) for details) - logger `Function` - function to track every step of transformations -#### clone(ast) +### Source maps -Make an AST node deep copy. +> TODO -```js -var orig = csso.parse('.test { color: red }'); -var copy = csso.clone(orig); +### Usage data -csso.walk(copy, function(node) { - if (node.type === 'Class') { - node.name = 'replaced'; - } -}); +`CSSO` can use data about how `CSS` is using for better compression. File with this data (`JSON` format) can be set using `usage` option. Usage data may contain follow sections: -console.log(csso.translate(orig)); -// .test{color:red} -console.log(csso.translate(copy)); -// .replaced{color:red} -``` +- `tags` – white list of tags +- `ids` – white list of ids +- `classes` – white list of classes +- `scopes` – groups of classes which never used with classes from other groups on single element -#### translate(ast) +All sections are optional. Value of `tags`, `ids` and `classes` should be array of strings, value of `scopes` should be an array of arrays of strings. Other values are ignoring. -Converts AST to string. +#### Selector filtering -```js -var ast = csso.parse('.test { color: red }'); -console.log(csso.translate(ast)); -// > .test{color:red} +`tags`, `ids` and `classes` are using on clean stage to filter selectors that contains something that not in list. Selectors are filtering only by those kind of simple selector which white list is specified. For example, if only `tags` list is specified then type selectors are checking, and if selector hasn't any type selector (or even any type selector) it isn't filter. + +> `ids` and `classes` names are case sensitive, `tags` – is not. + +Input CSS: + +```css +* { color: green; } +ul, ol, li { color: blue; } +UL.foo, span.bar { color: red; } ``` -#### translateWithSourceMap(ast) +Usage data: -The same as `translate()` but also generates source map (nodes should contain positions in `info` property). +```json +{ + "tags": ["ul", "LI"] +} +``` -```js -var ast = csso.parse('.test { color: red }', { - filename: 'my.css', - positions: true -}); -console.log(csso.translateWithSourceMap(ast)); -// { css: '.test{color:red}', map: SourceMapGenerator {} } +Result CSS: + +```css +*{color:green}ul,li{color:blue}ul.foo{color:red} ``` -#### walk(ast, handler) +#### Scopes + +Scopes is designed for CSS scope isolation solutions such as [css-modules](/~https://github.com/css-modules/css-modules). Scopes are similar to namespaces and defines lists of class names that exclusively used on some markup. This information allows the optimizer to move rulesets more agressive. Since it assumes selectors from different scopes can't to be matched on the same element. That leads to better ruleset merging. + +Suppose we have a file: -Visit all nodes of AST and call handler for each one. `handler` receives three arguments: +```css +.module1-foo { color: red; } +.module1-bar { font-size: 1.5em; background: yellow; } -- node – current AST node -- item – node wrapper when node is a list member; this wrapper contains references to `prev` and `next` nodes in list -- list – reference to list when node is a list member; it's useful for operations on list like `remove()` or `insert()` +.module2-baz { color: red; } +.module2-qux { font-size: 1.5em; background: yellow; width: 50px; } +``` -Context for handler an object, that contains references to some parent nodes: +It can be assumed that first two rules are never used with the second two on the same markup. But we can't know that for sure without markup. The optimizer doesn't know it either and will perform safe transformations only. The result will be the same as input but with no spaces and some semicolons: -- root – refers to `ast` or root node -- stylesheet – refers to closest `StyleSheet` node, it may be a top-level or at-rule block stylesheet -- atruleExpression – refers to `AtruleExpression` node if current node inside at-rule expression -- ruleset – refers to `Rule` node if current node inside a ruleset -- selector – refers to `Selector` node if current node inside a selector -- declaration – refers to `Declaration` node if current node inside a declaration -- function – refers to closest `Function` or `FunctionalPseudo` node if current node inside one of them +```css +.module1-foo{color:red}.module1-bar{font-size:1.5em;background:#ff0}.module2-baz{color:red}.module2-qux{font-size:1.5em;background:#ff0;width:50px} +``` -```js -// collect all urls in declarations -var csso = require('./lib/index.js'); -var urls = []; -var ast = csso.parse(` - @import url(import.css); - .foo { background: url('foo.jpg'); } - .bar { background-image: url(bar.png); } -`); - -csso.walk(ast, function(node) { - if (this.declaration !== null && node.type === 'Url') { - var value = node.value; - - if (value.type === 'Raw') { - urls.push(value.value); - } else { - urls.push(value.value.substr(1, value.value.length - 2)); - } - } -}); +But with usage data `CSSO` can get better output. If follow usage data is provided: -console.log(urls); -// [ 'foo.jpg', 'bar.png' ] +```json +{ + "scopes": [ + ["module1-foo", "module1-bar"], + ["module2-baz", "module2-qux"] + ] +} ``` -#### walkRules(ast, handler) +New result (29 bytes extra saving): + +```css +.module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px} +``` -Same as `walk()` but visits `Rule` and `Atrule` nodes only. +If class name doesn't specified in `scopes` it belongs to default "scope". `scopes` doesn't affect `classes`. If class name presents in `scopes` but missed in `classes` (both sections specified) it will be filtered. -#### walkRulesRight(ast, handler) +Note that class name can't be specified in several scopes. Also selector can't has classes from different scopes. In both cases an exception throws. -Same as `walkRules()` but visits nodes in reverse order (from last to first). +Currently the optimizer doesn't care about out-of-bounds selectors order changing safety (i.e. selectors that may be matched to elements with no class name of scope, e.g. `.scope div` or `.scope ~ :last-child`) since assumes scoped CSS modules doesn't relay on it's order. It may be fix in future if to be an issue. -## More reading +### Debugging -- [Debugging](docs/debugging.md) +> TODO ## License diff --git a/bin/csso b/bin/csso deleted file mode 100755 index 79fe3842..00000000 --- a/bin/csso +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node - -var cli = require('../lib/cli.js'); - -try { - cli.run(); -} catch (e) { - // output user frendly message if cli error - if (cli.isCliError(e)) { - console.error(e.message || e); - process.exit(2); - } - - // otherwise re-throw exception - throw e; -} diff --git a/docs/debugging.md b/docs/debugging.md deleted file mode 100644 index b8ddcadd..00000000 --- a/docs/debugging.md +++ /dev/null @@ -1,94 +0,0 @@ -# Debugging - -## CLI - -All debug information outputs to `stderr`. - -To get brief info about compression use `--stat` option. - -``` -> echo '.test { color: #ff0000 }' | csso --stat >/dev/null -File: -Original: 25 bytes -Compressed: 16 bytes (64.00%) -Saving: 9 bytes (36.00%) -Time: 12 ms -Memory: 0.346 MB -``` - -To get details about compression steps use `--debug` option. - -``` -> echo '.test { color: green; color: #ff0000 } .foo { color: red }' | csso --debug -## parsing done in 10 ms - -Compress block #1 -(0.002ms) convertToInternal -(0.000ms) clean -(0.001ms) compress -(0.002ms) prepare -(0.000ms) initialRejoinRuleset -(0.000ms) rejoinAtrule -(0.000ms) disjoin -(0.000ms) buildMaps -(0.000ms) markShorthands -(0.000ms) processShorthand -(0.001ms) restructBlock -(0.000ms) rejoinRuleset -(0.000ms) restructRuleset -## compressing done in 9 ms - -.foo,.test{color:red} -``` - -More details are provided when `--debug` flag has a number greater than `1`: - -``` -> echo '.test { color: green; color: #ff0000 } .foo { color: red }' | csso --debug 2 -## parsing done in 8 ms - -Compress block #1 -(0.000ms) clean - .test{color:green;color:#ff0000}.foo{color:red} - -(0.001ms) compress - .test{color:green;color:red}.foo{color:red} - -... - -(0.002ms) restructBlock - .test{color:red}.foo{color:red} - -(0.001ms) rejoinRuleset - .foo,.test{color:red} - -## compressing done in 13 ms - -.foo,.test{color:red} -``` - -Using `--debug` option adds stack trace to CSS parse error output. That can help to find out problem in parser. - -``` -> echo '.a { color }' | csso --debug - -Parse error : Colon is expected - 1 |.a { color } -------------------^ - 2 | - -/usr/local/lib/node_modules/csso/lib/cli.js:243 - throw e; - ^ - -Error: Colon is expected - at parseError (/usr/local/lib/node_modules/csso/lib/parser/index.js:54:17) - at eat (/usr/local/lib/node_modules/csso/lib/parser/index.js:88:5) - at getDeclaration (/usr/local/lib/node_modules/csso/lib/parser/index.js:394:5) - at getBlock (/usr/local/lib/node_modules/csso/lib/parser/index.js:380:27) - ... -``` - -## API - -[TODO] diff --git a/lib/cli.js b/lib/cli.js deleted file mode 100644 index 74054634..00000000 --- a/lib/cli.js +++ /dev/null @@ -1,338 +0,0 @@ -var fs = require('fs'); -var path = require('path'); -var cli = require('clap'); -var SourceMapConsumer = require('source-map').SourceMapConsumer; -var csso = require('./index.js'); - -function readFromStream(stream, minify) { - var buffer = []; - - // NOTE: don't chain until node.js 0.10 drop, since setEncoding isn't chainable in 0.10 - stream.setEncoding('utf8'); - stream - .on('data', function(chunk) { - buffer.push(chunk); - }) - .on('end', function() { - minify(buffer.join('')); - }); -} - -function showStat(filename, source, result, inputMap, map, time, mem) { - function fmt(size) { - return String(size).split('').reverse().reduce(function(size, digit, idx) { - if (idx && idx % 3 === 0) { - size = ' ' + size; - } - return digit + size; - }, ''); - } - - map = map || 0; - result -= map; - - console.error('Source: ', filename === '' ? filename : path.relative(process.cwd(), filename)); - if (inputMap) { - console.error('Map source:', inputMap); - } - console.error('Original: ', fmt(source), 'bytes'); - console.error('Compressed:', fmt(result), 'bytes', '(' + (100 * result / source).toFixed(2) + '%)'); - console.error('Saving: ', fmt(source - result), 'bytes', '(' + (100 * (source - result) / source).toFixed(2) + '%)'); - if (map) { - console.error('Source map:', fmt(map), 'bytes', '(' + (100 * map / (result + map)).toFixed(2) + '% of total)'); - console.error('Total: ', fmt(map + result), 'bytes'); - } - console.error('Time: ', time, 'ms'); - console.error('Memory: ', (mem / (1024 * 1024)).toFixed(3), 'MB'); -} - -function showParseError(source, filename, details, message) { - function processLines(start, end) { - return lines.slice(start, end).map(function(line, idx) { - var num = String(start + idx + 1); - - while (num.length < maxNumLength) { - num = ' ' + num; - } - - return num + ' |' + line; - }).join('\n'); - } - - var lines = source.split(/\n|\r\n?|\f/); - var column = details.column; - var line = details.line; - var startLine = Math.max(1, line - 2); - var endLine = Math.min(line + 2, lines.length + 1); - var maxNumLength = Math.max(4, String(endLine).length) + 1; - - console.error('\nParse error ' + filename + ': ' + message); - console.error(processLines(startLine - 1, line)); - console.error(new Array(column + maxNumLength + 2).join('-') + '^'); - console.error(processLines(line, endLine)); - console.error(); -} - -function debugLevel(level) { - // level is undefined when no param -> 1 - return isNaN(level) ? 1 : Math.max(Number(level), 0); -} - -function resolveSourceMap(source, inputMap, map, inputFile, outputFile) { - var inputMapContent = null; - var inputMapFile = null; - var outputMapFile = null; - - switch (map) { - case 'none': - // don't generate source map - map = false; - inputMap = 'none'; - break; - - case 'inline': - // nothing to do - break; - - case 'file': - if (!outputFile) { - console.error('Output filename should be specified when `--map file` is used'); - process.exit(2); - } - - outputMapFile = outputFile + '.map'; - break; - - default: - // process filename - if (map) { - // check path is reachable - if (!fs.existsSync(path.dirname(map))) { - console.error('Directory for map file should exists:', path.dirname(path.resolve(map))); - process.exit(2); - } - - // resolve to absolute path - outputMapFile = path.resolve(process.cwd(), map); - } - } - - switch (inputMap) { - case 'none': - // nothing to do - break; - - case 'auto': - if (map) { - // try fetch source map from source - var inputMapComment = source.match(/\/\*# sourceMappingURL=(\S+)\s*\*\/\s*$/); - - if (inputFile === '') { - inputFile = false; - } - - if (inputMapComment) { - // if comment found – value is filename or base64-encoded source map - inputMapComment = inputMapComment[1]; - - if (inputMapComment.substr(0, 5) === 'data:') { - // decode source map content from comment - inputMapContent = new Buffer(inputMapComment.substr(inputMapComment.indexOf('base64,') + 7), 'base64').toString(); - } else { - // value is filename – resolve it as absolute path - if (inputFile) { - inputMapFile = path.resolve(path.dirname(inputFile), inputMapComment); - } - } - } else { - // comment doesn't found - look up file with `.map` extension nearby input file - if (inputFile && fs.existsSync(inputFile + '.map')) { - inputMapFile = inputFile + '.map'; - } - } - - } - break; - - default: - if (inputMap) { - inputMapFile = inputMap; - } - } - - // source map placed in external file - if (inputMapFile) { - inputMapContent = fs.readFileSync(inputMapFile, 'utf8'); - } - - return { - input: inputMapContent, - inputFile: inputMapFile || (inputMapContent ? '' : false), - output: map, - outputFile: outputMapFile - }; -} - -function processCommentsOption(value) { - switch (value) { - case 'exclamation': - case 'first-exclamation': - case 'none': - return value; - } - - console.error('Wrong value for `comments` option: %s', value); - process.exit(2); -} - -var command = cli.create('csso', '[input] [output]') - .version(require('../package.json').version) - .option('-i, --input ', 'Input file') - .option('-o, --output ', 'Output file (result outputs to stdout if not set)') - .option('-m, --map ', 'Generate source map: none (default), inline, file or ', 'none') - .option('-u, --usage ', 'Usage data file') - .option('--input-map ', 'Input source map: none, auto (default) or ', 'auto') - .option('--restructure-off', 'Turns structure minimization off') - .option('--comments ', 'Comments to keep: exclamation (default), first-exclamation or none', 'exclamation') - .option('--stat', 'Output statistics in stderr') - .option('--debug [level]', 'Output intermediate state of CSS during compression', debugLevel, 0) - .action(function(args) { - var options = this.values; - var inputFile = options.input || args[0]; - var outputFile = options.output || args[1]; - var usageFile = options.usage; - var usageData = false; - var map = options.map; - var inputMap = options.inputMap; - var structureOptimisationOff = options.restructureOff; - var comments = processCommentsOption(options.comments); - var debug = options.debug; - var statistics = options.stat; - var inputStream; - - if (process.stdin.isTTY && !inputFile && !outputFile) { - this.showHelp(); - return; - } - - if (!inputFile) { - inputFile = ''; - inputStream = process.stdin; - } else { - inputFile = path.resolve(process.cwd(), inputFile); - inputStream = fs.createReadStream(inputFile); - } - - if (outputFile) { - outputFile = path.resolve(process.cwd(), outputFile); - } - - if (usageFile) { - if (!fs.existsSync(usageFile)) { - console.error('Usage data file doesn\'t found (%s)', usageFile); - process.exit(2); - } - - usageData = fs.readFileSync(usageFile, 'utf-8'); - - try { - usageData = JSON.parse(usageData); - } catch (e) { - console.error('Usage data parse error (%s)', usageFile); - process.exit(2); - } - } - - readFromStream(inputStream, function(source) { - var time = process.hrtime(); - var mem = process.memoryUsage().heapUsed; - var sourceMap = resolveSourceMap(source, inputMap, map, inputFile, outputFile); - var sourceMapAnnotation = ''; - var result; - - // main action - try { - result = csso.minify(source, { - filename: inputFile, - sourceMap: sourceMap.output, - usage: usageData, - restructure: !structureOptimisationOff, - comments: comments, - debug: debug - }); - - // for backward capability minify returns a string - if (typeof result === 'string') { - result = { - css: result, - map: null - }; - } - } catch (e) { - if (e.parseError) { - showParseError(source, inputFile, e.parseError, e.message); - if (!debug) { - process.exit(2); - } - } - - throw e; - } - - if (sourceMap.output && result.map) { - // apply input map - if (sourceMap.input) { - result.map.applySourceMap( - new SourceMapConsumer(sourceMap.input), - inputFile - ); - } - - // add source map to result - if (sourceMap.outputFile) { - // write source map to file - fs.writeFileSync(sourceMap.outputFile, result.map.toString(), 'utf-8'); - sourceMapAnnotation = '\n' + - '/*# sourceMappingURL=' + - path.relative(outputFile ? path.dirname(outputFile) : process.cwd(), sourceMap.outputFile) + - ' */'; - } else { - // inline source map - sourceMapAnnotation = '\n' + - '/*# sourceMappingURL=data:application/json;base64,' + - new Buffer(result.map.toString()).toString('base64') + - ' */'; - } - - result.css += sourceMapAnnotation; - } - - // output result - if (outputFile) { - fs.writeFileSync(outputFile, result.css, 'utf-8'); - } else { - console.log(result.css); - } - - // output statistics - if (statistics) { - var timeDiff = process.hrtime(time); - showStat( - path.relative(process.cwd(), inputFile), - source.length, - result.css.length, - sourceMap.inputFile, - sourceMapAnnotation.length, - parseInt(timeDiff[0] * 1e3 + timeDiff[1] / 1e6, 10), - process.memoryUsage().heapUsed - mem - ); - } - }); - }); - -module.exports = { - run: command.run.bind(command), - isCliError: function(err) { - return err instanceof cli.Error; - } -}; diff --git a/package.json b/package.json index cd717bf9..70651f0d 100644 --- a/package.json +++ b/package.json @@ -52,9 +52,7 @@ "prepublish": "npm run browserify" }, "dependencies": { - "clap": "^1.0.9", - "css-tree": "csstree/csstree", - "source-map": "^0.5.3" + "css-tree": "csstree/csstree" }, "devDependencies": { "browserify": "^13.0.0",