Repository: katiefenn/parker
Branch: master
Commit: 7658d1b8741a
Files: 62
Total size: 96.3 KB
Directory structure:
gitextract_ipjvopnp/
├── .gitignore
├── .jshintrc
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── docs/
│ ├── contributing/
│ │ └── readme.md
│ ├── installation/
│ │ └── readme.md
│ ├── metrics/
│ │ └── readme.md
│ ├── readme.md
│ ├── usage/
│ │ └── readme.md
│ └── usage-package/
│ └── readme.md
├── lib/
│ ├── ArraySelectorSpecificity.js
│ ├── ClassicalSelectorSpecificity.js
│ ├── CliController.js
│ ├── CliFormatter.js
│ ├── CssDeclaration.js
│ ├── CssMediaQuery.js
│ ├── CssRule.js
│ ├── CssSelector.js
│ ├── CssStylesheet.js
│ ├── Formatters.js
│ ├── Info.js
│ ├── Parker.js
│ └── PreciseSelectorSpecificity.js
├── metrics/
│ ├── All.js
│ ├── DeclarationsPerRule.js
│ ├── IdentifiersPerSelector.js
│ ├── MediaQueries.js
│ ├── PreciseSpecificityPerSelector.js
│ ├── PreciseTopSelectorSpecificity.js
│ ├── SelectorsPerRule.js
│ ├── SpecificityPerSelector.js
│ ├── StringTopSelectorSpecificity.js
│ ├── TopSelectorSpecificity.js
│ ├── TopSelectorSpecificitySelector.js
│ ├── TotalDeclarations.js
│ ├── TotalIdSelectors.js
│ ├── TotalIdentifiers.js
│ ├── TotalImportantKeywords.js
│ ├── TotalMediaQueries.js
│ ├── TotalRules.js
│ ├── TotalSelectors.js
│ ├── TotalStylesheetSize.js
│ ├── TotalStylesheets.js
│ ├── TotalUniqueColours.js
│ ├── UniqueColours.js
│ └── ZIndexes.js
├── package.json
├── parker.js
└── test/
├── CliController.js
├── CssDeclaration.js
├── CssMediaQuery.js
├── CssRule.js
├── CssSelector.js
├── CssStylesheet.js
├── DeclarationsPerRule.js
├── IdentifiersPerSelector.js
├── Parker.js
├── TopSelectorSpecificity.js
├── TotalIdSelectors.js
└── ZIndexes.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules
================================================
FILE: .jshintrc
================================================
{
"browser": true,
"node": true,
"esnext": true,
"bitwise": false,
"curly": false,
"eqeqeq": true,
"eqnull": true,
"immed": true,
"latedef": false,
"laxcomma": true,
"newcap": true,
"noarg": true,
"undef": true,
"strict": true,
"trailing": true,
"smarttabs": true,
"white": true
}
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "0.10"
- "0.12"
================================================
FILE: CHANGELOG.md
================================================
== HEAD
================================================
FILE: LICENSE.md
================================================
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# Parker
Parker is a stylesheet analysis tool. It runs metrics on your stylesheets and will report on their complexity.
[](http://travis-ci.org/katiefenn/parker)
## Installation
Install with npm:
```
npm install -g parker
```
## Usage
### Measuring Local Stylesheets
```
parker a.css b.css c.css
```
```
parker css/
```
### Measuring a Remote Stylesheet Using Curl
```
curl http://www.katiefenn.co.uk/css/shuttle.css -s | parker -s
```
### Output JSON
```
parker example.css --format=json
```
### Programmatic usage
After installing parker as a dependency in your project, you can use it as follows:
```js
var Parker = require('parker/lib/Parker');
var metrics = require('parker/metrics/All'); // Or an array of the metrics you want to measure
var file = fs.readFile('test.css', function (err, data) {
if (err) throw err;
var parker = new Parker(metrics);
var results = parker.run(data.toString());
// Do something with results
});
```
## Documentation
Documentation can be found in markdown format the [docs folder](https://github.com/katiefenn/parker/tree/master/docs).
## Testing
From the repo root:
```
npm install
npm test
```
## Contributing
Pull requests, issues, new unit tests, code reviews and good advice are all things that would make a difference to Parker. You can even contribute by telling me how useful Parker is to you; please let me know on Twitter at @katie_fenn. Any time generously donated to helping make Parker better is gratefully accepted, and in return I shall do my best to merge contributions.
Please target pull requests at the "develop" branch.
## About
Parker is my first open source project, and your suggestions and feedback are welcome. The project is in a pre-beta phase and is liable to change at any time. Parker is named for the character Parker from Gerry Anderson's Thunderbirds, without which my interest in technology and computers would certainly not be what it is today. Parker is Nosey about your stylesheets.
================================================
FILE: docs/contributing/readme.md
================================================
# Contributing
Pull requests, issues, new unit tests, code reviews and good advice are all things that would make a difference to Parker. You can even contribute by telling me how useful Parker is to you; please let me know on Twitter at @katie_fenn. Any time generously donated to helping make Parker better is gratefully accepted, and in return I shall do my best to merge contributions.
<a name="github"></a>
## GitHub
The source-code is hosted at [GitHub](https://github.com/katiefenn/Parker).
When creating pull requests, please target the develop branch.
<a name="testing"></a>
## Testing
A suite of unit tests are maintained to test Parker. The tools Mocha, Chai and Sinon are among the tools used for testing.
From the project root, dependencies can be installed using the following command:
npm install
Unit tests can be run using the following command:
npm test
================================================
FILE: docs/installation/readme.md
================================================
# Installation
Parker requires Node.JS and npm to be installed before it can be installed itself.
<a name="install-node-js"></a>
## Install Node.JS
Node.JS is a Javascript software platform for use outside of the web browser. It allows tools like Parker to be written in JavaScript and run from the command-line on your computer.
npm is a package manager for Node.JS and is also installed by Node.JS installer packages.
Installer packages for Node.JS can be found at the [Node.JS Website](http://nodejs.org/download/) for many operating systems. Node.JS can also be installed using a range of [package managers](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager).
<a name="install-parker"></a>
## Install Parker
Install with npm:
npm install -g parker
================================================
FILE: docs/metrics/readme.md
================================================
# Metrics
Parker has a suite of metrics that are useful for measuring stylesheets. What follows is a list of all the metrics that are bundled with Parker. Parker's metrics are modular and it's easy to write your own - find out how [here](#authoring-metrics).
1. [Bundled Metrics](#bundled-metrics)
1. [Stylesheet Totals](#stylesheet-totals)
1. [Total Stylesheets](#total-stylesheets)
2. [Total Stylesheet Size](#total-stylesheet-size)
2. [Stylesheet Elements](#stylesheet-elements)
1. [Total Rules](#total-rules)
2. [Total Selectors](#total-selectors)
3. [Total Identifiers](#total-identifiers)
4. [Total Declarations](#total-declarations)
5. [Selectors Per Rule](#selectors-per-rule)
6. [Identifiers Per Selectors](#identifiers-per-selector)
3. [Specificity](#specificity)
1. [Specificity Per Selector](#specificity-per-selector)
2. [Top Selector Specificity](#top-selector-specificity)
3. [Top Selector Specificity Selector](#top-selector-specificity-selector)
4. [Important Keywords](#important-keywords)
1. [Total Important Keywords](#total-important-keywords)
5. [Colors](#colours)
1. [Total Unique Colours](#total-unique-colours)
2. [Unique Colours](#unique-colours)
6. [Media Queries](#media-queries-heading)
1. [Media Queries](#media-queries)
2. [Total Media Queries](#total-media-queries)
2. [Authoring Metrics](#authoring-metrics)
1. [Attributes](#attributes)
1. [id](#id)
2. [name](#name)
3. [type](#type)
4. [aggregate](#aggregate)
5. [format](#format)
2. [Methods](#methods)
1. [measure](#measure)
2. [filter](#filter)
3. [iterator](#iterator)
<a name="bundled-metrics"></a>
## [Bundled Metrics](#bundled-metrics)
<a name="stylesheet-totals"></a>
### Stylesheet Totals
Basic metrics that influence stylesheet and HTTP performance.
<a name="total-stylesheets"></a>
#### Total Stylesheets
The number of stylesheets measured. This is the number of stylesheets submitted to Parker in a single report, and can be used to track how many stylesheets are requested in your application. Each stylesheet is downloaded over a HTTP request, which affects performance. Generally, fewer HTTP requests improves performance.
- __id__: total-stylesheets
- __name__: Total Stylesheets
- __type__: stylesheet
- __aggregate__: sum
- __format__: number
<a name="stylesheet-size"></a>
#### Total Stylesheet Size
Measures the total file size of stylesheets measured. Each stylesheet is downloaded over a HTTP request, and the size of the request affects performance. Smaller HTTP request file sizes improves performance.
- __id__: total-stylesheet-size
- __name__: Total Stylesheet Size
- __type__: stylesheet
- __aggregate__: sum
- __format__: number
<a name="stylesheet-elements"></a>
### Stylesheet Elements
Stylesheet size can be broken down into the total number of its parts: rules, selectors, identifiers and declarations.
<a name="total-rules"></a>
#### Total Rules
Measures the total number of rules. Each rule defines a specific behaviour of the design. Stylesheets with fewer rules are simpler.
- __id__: total-rules
- __name__: Total Rules
- __type__: rule
- __aggregate__: sum
- __format__: number
#### Total Selectors
Measures the total number of selectors. Each selector defines a group of elements affected by the design. Stylesheets with fewer selectors are simpler.
- __id__: total-selectors
- __name__: Total Selectors
- __type__: selector
- __aggregate__: sum
- __format__: number
<a name="total-identifiers"></a>
#### Total Identifiers
Measures the total number of identifiers. Each identifier defines a group of elements affected by the design. Stylesheets with fewer identifiers are simpler. It can be useful to break measure identifiers as well as identifiers so that small code changes to selectors can be tracked.
- __id__: total-identifiers
- __name__: Total Identifiers
- __type__: identifier
- __aggregate__: sum
- __format__: number
<a name="total-declarations"></a>
#### Total Declarations
Measures the total number of property declarations. Each property declaration defines a modification of the appearance or function of an element. Stylesheets with fewer property declarations are simpler.
- __id__: total-declarations
- __name__: Total Declarations
- __type__: declaration
- __aggregate__: sum
- __format__: number
#### Selectors Per Rule
Measures the average number of selectors in every rule. Stylesheet rules can be applied to several groups of elements using multiple selectors, separated by a comma. Fewer selectors in a rule makes its properties specific to a smaller group of elements, and also makes a rule easier to read in text editors and developer tools.
- __id__: total-important-keywords
- __name__: Total Important Keywords
- __type__: value
- __aggregate__: sum
- __format__: number
#### Identifiers Per Selector
Measures the average number of identifiers in every selector. Selectors can be made more specific to combinations of elements by adding more identifiers to a selector. Fewer identifiers in a given selector reduces its dependency on certain DOM structures, allowing more changes to your HTML before being forced to change your CSS. Selectors with fewer identifiers are also more readable.
- __id__: identifiers-per-selector
- __name__: Identifiers Per Selector
- __type__: selector
- __aggregate__: mean
- __format__: number
<a name="specificity"></a>
### Specificity
A rule can be overrided by another rule with a more specific selector. Complexity is added to stylesheets when multiple levels of cascading rules are used in stylesheets, because it becomes more difficult to predict which properties apply to a given element without keeping in mind other rules.
<a name="specificity-per-selector"></a>
#### Specificity Per Selector
Measures the average specificity of selectors. Lower average specificity makes it easier to combine and re-use properties defined in other, less-specific rules.
- __id__: specificity-per-selector
- __name__: Specificity Per Selector
- __type__: selector
- __aggregate__: mean
- __format__: number
<a name="top-selector-specificity"></a>
#### Top Selector Specificity
Measures the specificity of the most specific selector. Reducing the specificity of the most complex selectors is a good way to reducing the overall complexity of a stylesheet.
- __id__: top-selector-specificity
- __name__: Top Selector Specificity
- __type__: selector
- __aggregate__: max
- __format__: number
<a name="top-selector-specificity-selector"></a>
#### Top Selector Specificity Selector
Displays the most specific selector. Reducing the specificity of the most complex selectors is a good way to reducing the overall complexity of a stylesheet.
- __id__: top-selector-specificity-selector
- __name__: Top Selector Specificity Selector
- __type__: selector
- __aggregate__: max
- __format__: string
<a name="important-keywords"></a>
### Important Keywords
The !important keyword supersedes selector specificity, even allowing properties to be enforced over properties of rules with high specificity selectors. Because !important is so powerful, it should be reserved for use for architectural purposes, enforcing styles in user stylesheets and utility classes. Using !important to overcome issues with specificity exacerbates the problem.
<a name="total-important-keywords"></a>
#### Total Important Keywords
Measures the total instances of the !important keyword. Fewer !important keywords indicates a simpler stylesheet.
- __id__: total-important-keywords
- __name__: Total Important Keywords
- __type__: value
- __aggregate__: sum
- __format__: number
<a name="colours"></a>
### Colours
Colour is an important part of design, and highlights important elements such as buttons, sections and text. A consistent colour scheme is a good way of guiding users around a site. An excessive number of colours indicates an overly-complex colour scheme, or inconsistent use of colour that forces an over-reliance of developers on design documents.
<a name="total-unique-colours"></a>
#### Total Unique Colours
Measures the number of unique colour hashes used in a stylesheet. Fewer colours indicates a simpler colour scheme.
- __id__: total-unique-colours
- __name__: Total Unique Colors
- __type__: value
- __aggregate__: length
- __format__: number
<a name="unique-colours"></a>
#### Unique Colours
Lists the unique colour hashes used in a stylesheet. Identifying and reducing unique colours is a good way to simplify colour schemes.
- __id__: unique-colours
- __name__: Unique Colors
- __type__: value
- __aggregate__: list
- __format__: list
<a name="media-queries-heading"></a>
### Media Queries
Media queries contain rules that change the behaviour of documents according to the sort of device or its state. They're commonly used to create breakpoints in responsive web design behaviour. Each unique media query adds complexity by changing behaviour when a given criteria is met by the device.
<a name="media-queries"></a>
#### Media Queries
Lists every unique media query used. Reducing unique media queries is a good way to simplify stylesheets.
- __id__: media-queries
- __name__: Media Queries
- __type__: mediaquery
- __aggregate__: list'
- __format__: list
<a name="total-media-queries"></a>
#### Total Media Queries
Measures the number of unique media queries used. Fewer media queries indicates a simpler stylesheet.
- __id__: total-media-queries
- __name__: Total Media Queries
- __type__: mediaquery
- __aggregate__: length
- __format__: number
<a name="authoring-metrics"></a>
## Authoring Metrics
Parker's stylesheets are modular, and there are several attributes and methods a metric can implement to access Parker's metric features.
<a name="attributes"></a>
### Attributes
<a name="id"></a>
#### id
The unique identifier of the metric and is used when selecting metrics to be run.
<a name="name"></a>
#### name
The natural language name of the metric and is used when reporting results.
<a name="type"></a>
#### type
The type of stylesheet elements the metric is run against.
Available types:
- stylesheet
- rule
- selector
- identifier
- declaration
- property
- value
- mediaquery
<a name="aggregate"></a>
#### aggregate
The operation applied to data collected by metrics on elements before results are reported.
Available aggregates:
- __sum__: will sum number values
- __mean__: will average number values by mean
- __max__: will select the maximum of number values after iterator function is applied
- __list__: will list all collected values after filter function is applied
- __length__: will display the number of collected values after filter function is applied
<a name="format"></a>
#### format
The output format of the end result. Used for selecting metrics for use in scripts.
Available formats:
- number
- list
- string
<a name="methods"></a>
### Methods
<a name="measure"></a>
#### measure
metric.measure(element)
Measures an element of css "element" and returns a measurement to be reported. This is the main method that measures elements that all metrics must implement.
Example:
The Stylesheet Size measure method returns a simple number measurement, which is summed on aggregate.
module.exports = {
id: 'total-stylesheet-size',
name: 'Total Stylesheet Size',
type: 'stylesheet',
aggregate: 'sum',
format: 'number',
measure: function (stylesheet) {
return byteCount(stylesheet);
}
};
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}
<a name="filter"></a>
#### filter
metric.filter(predicate)
Filters list-aggregated results based on the truth-test "predicate" function.
Predicate parameters:
- __value__: the value of the measurement
- __index__: the index of the item in all measurements the metric has collected
- __list__: the current list of all measurements to compare the current item to
Example:
The Total Media Queries returns the query to be collected into a list. Before reporting, the filter method is run on the list, removing duplicate queries by returning a true or false value according to whether it is the only such item in the list. The length aggregate returns the number of queries collected after filtering.
module.exports = {
id: 'total-media-queries',
name: 'Total Media Queries',
type: 'mediaquery',
aggregate: 'length',
format: 'number',
measure: function (query) {
return query;
},
filter: function (value, index, list) {
return self.indexOf(value) === index;
}
};
<a name="iterator"></a>
#### iterator
metric.iterator(element)
A helper method of "max" aggregated metrics that returns a number value for the given element. Used to determine which item should be selected as the maximum value when the measurement returned by the measurement method is not a number value. When the method is not defined, the measurement returned by "measure" is used instead.
Example:
The Top Selector Specificity Selector metric returns the most specific selector, but does not report a number value. An iterator method is used to determine the selector's specificity when results are aggregated.
module.exports = {
id: 'top-selector-specificity-selector',
name: 'Top Selector Specificity Selector',
type: 'selector',
aggregate: 'max',
format: 'string',
measure: function (selector) {
return selector;
},
iterator: function (selector) {
var identifiers = getIdentifiers(selector),
specificity = 0;
/*
Implementation calculating specificity cut for brevity
...
*/
return specificity;
}
};
================================================
FILE: docs/readme.md
================================================
# Parker
Parker is a stylesheet analysis tool. It runs metrics on your stylesheets and will report on their complexity.
## Table of Contents
1. [Installation](installation/readme.md)
1. [Installing Node.JS](installation/readme.md#install-node-js)
2. [Installing Parker](installation/readme.md#install-parker)
2. [Usage](usage/readme.md)
1. [Options](usage/readme.md#options)
3. [Using Parker as a Package](usage-package/readme.md)
3. [Metrics](metrics/readme.md)
1. [Bundled Metrics](metrics/readme.md#bundled-metrics)
2. [Authoring Metrics](metrics/readme.md#authoring-metrics)
4. [Contributing](contributing/readme.md)
1. [GitHub](contributing/readme.md#github)
2. [Testing](contributing/readme.md#testing)
================================================
FILE: docs/usage/readme.md
================================================
# Usage
Parker is a command-line tool. Switches and options are used to control how it works. By default Parker runs with recommended settings for beginners to aid discoverability. To make the most of Parker, it is recommended users read about the available options and choose which metrics are most useful to them.
parker [arguments] [file...]
Measuring local stylesheets:
parker a.css b.css c.css
Measuring all local stylesheets in a directory:
parker css/
Measuring a remote stylesheet using curl:
curl http://www.katiefenn.co.uk/css/shuttle.css | parker -s
<a name="options"></a>
## Options
### -f --format
Set output format.
Formats:
- __human__: Default. Human-readable format.
- __json__: JSON format for integration with scripts.
- __csv__: Comma-separated-value format for output to spreadsheets.
### -h --help
Shows help.
### -n --numeric
Run numeric-format metrics only. Useful for making benchmarks.
### -s --stdin
Input CSS using stdin.
### -v --version
Show version number of Parker.
================================================
FILE: docs/usage-package/readme.md
================================================
# Using Parker as a Package
Parker can be used as a package in scripts. It can be installed using npm like so:
npm install --save parker
Parker can then be used to run metrics on CSS on strings of stylesheet content:
var Parker = require('parker'),
metrics = require('./node_modules/parker/metrics/all'),
parker = new Parker(metrics);
console.log(parker.run('body {background: #fff;}'));
/*
{ 'total-stylesheets': 1,
'total-stylesheet-size': 24,
'total-rules': 1,
'selectors-per-rule': 1,
'total-selectors': 1,
'identifiers-per-selector': 1,
'specificity-per-selector': 1,
'top-selector-specificity': 1,
'top-selector-specificity-selector': 'body',
'total-id-selectors': 0,
'total-identifiers': 1,
'total-declarations': 1,
'total-unique-colours': 1,
'unique-colours': [ '#FFFFFF' ],
'total-important-keywords': 0,
'total-media-queries': 0,
'media-queries': [] }
*/
Metrics have a bunch of properties that can help you select which ones you want to use:
var metrics = require('./node_modules/parker/metrics/all'),
numericMetrics = metrics.filter(metricIsNumeric),
topSelectorSpecificityMetric = metrics.filter(metricIsTopSelectorSpecificity),
selectorMetrics = metrics.filter(metricIsSelectorType);
function metricIsNumeric(metric) {
return metric.format == 'number';
}
function metricIsTopSelectorSpecificity(metric) {
return metric.id == 'top-selector-specificity';
}
function metricIsSelectorType(metric) {
return metric.type == 'selector';
}
================================================
FILE: lib/ArraySelectorSpecificity.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var CssSelector = require('../lib/CssSelector');
var _ = require('lodash');
module.exports = function (rawSelector) {
var idIdentifiers = 0,
classIdentifiers = 0,
attributeIdentifiers = 0,
pseudoClassIdentifiers = 0,
typeIdentifiers = 0,
pseudoElementIdentifiers = 0,
selector = new CssSelector(rawSelector);
_.each(selector.getIdentifiers(), function (identifier) {
idIdentifiers += countIdIdentifiers(identifier);
classIdentifiers += countClassIdentifiers(identifier);
attributeIdentifiers += countAttributeIdentifiers(identifier);
pseudoClassIdentifiers += countPseudoClassIdentifiers(identifier);
typeIdentifiers += countTypeIdentifiers(identifier);
pseudoElementIdentifiers = countPseudoElementIdentifiers(identifier);
});
return [
idIdentifiers,
classIdentifiers + attributeIdentifiers + pseudoClassIdentifiers,
typeIdentifiers + pseudoElementIdentifiers
];
}
var countIdIdentifiers = function (identifier) {
var regex = /#/,
matches = regex.exec(identifier);
if (matches && !countAttributeIdentifiers(identifier)) {
return matches.length;
}
return 0;
};
var countClassIdentifiers = function (identifier) {
var regex = /\./,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countAttributeIdentifiers = function (identifier) {
var regex = /\[/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countPseudoClassIdentifiers = function (identifier) {
var regex = /^:[^:]/,
matches = regex.exec(identifier);
// :not pseudo-class identifier itself is ignored
// only selectors inside it are counted
if (identifier.match(/:not/)) {
return 0;
}
if (matches) {
return matches.length;
}
return 0;
};
var countTypeIdentifiers = function (identifier) {
var regex = /^[a-zA-Z_]/;
if (regex.exec(identifier)) {
return 1;
}
return 0;
};
var countPseudoElementIdentifiers = function (identifier) {
var regex = /::/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var stripNotIdentifier = function (identifier) {
if (identifier.match(/:not/)) {
return identifier.replace(/:not\(|\)/g, '');
}
return identifier;
};
================================================
FILE: lib/ClassicalSelectorSpecificity.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var CssSelector = require('../lib/CssSelector');
var _ = require('lodash');
module.exports = function (rawSelector) {
var totalSpecificity = 0,
selector = new CssSelector(rawSelector);
_.each(selector.getIdentifiers(), function (identifier) {
var idIdentifiers = countIdIdentifiers(identifier),
classIdentifiers = countClassIdentifiers(identifier),
attributeIdentifiers = countAttributeIdentifiers(identifier),
pseudoClassIdentifiers = countPseudoClassIdentifiers(identifier),
typeIdentifiers = countTypeIdentifiers(identifier),
pseudoElementIdentifiers = countPseudoElementIdentifiers(identifier);
totalSpecificity += Number(
String(idIdentifiers) +
String(classIdentifiers + attributeIdentifiers + pseudoClassIdentifiers) +
String(typeIdentifiers + pseudoElementIdentifiers));
});
return totalSpecificity;
}
var countIdIdentifiers = function (identifier) {
var regex = /#/,
matches = regex.exec(identifier);
if (matches && !countAttributeIdentifiers(identifier)) {
return matches.length;
}
return 0;
};
var countClassIdentifiers = function (identifier) {
var regex = /\./,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countAttributeIdentifiers = function (identifier) {
var regex = /\[/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countPseudoClassIdentifiers = function (identifier) {
var regex = /^:[^:]/,
matches = regex.exec(identifier);
// :not pseudo-class identifier itself is ignored
// only selectors inside it are counted
if (identifier.match(/:not/)) {
return 0;
}
if (matches) {
return matches.length;
}
return 0;
};
var countTypeIdentifiers = function (identifier) {
var regex = /^[a-zA-Z_]/;
if (regex.exec(identifier)) {
return 1;
}
return 0;
};
var countPseudoElementIdentifiers = function (identifier) {
var regex = /::/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var stripNotIdentifier = function (identifier) {
if (identifier.match(/:not/)) {
return identifier.replace(/:not\(|\)/g, '');
}
return identifier;
};
================================================
FILE: lib/CliController.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var util = require('util'),
events = require('events');
function CliController() {
events.EventEmitter.call(this);
}
util.inherits(CliController, events.EventEmitter);
CliController.prototype.dispatch = function (argv) {
if (argv.v || argv.version) {
this.emit('showVersion');
}
if (argv.h || argv.help) {
this.emit('showHelp');
}
if (argv.f || argv.format) {
var format = argv.f || argv.format;
this.emit('setFormat', format);
}
if (argv.n || argv.numeric) {
this.emit('showNumericOnly');
}
if (argv._ && argv._.length) {
this.emit('runPaths', argv._);
}
else if (argv.s || argv.stdin) {
this.emit('runStdin');
}
else {
// No data supplied - show help
this.emit('showHelp');
}
};
module.exports = CliController;
================================================
FILE: lib/CliFormatter.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
function CliFormatter() {
}
CliFormatter.prototype.format = function (data, metrics) {
var output = '';
_.each(metrics, function(metric) {
output += metric.name + ": " + data[metric.id];
output += "\n";
});
return output;
};
module.exports = CliFormatter;
================================================
FILE: lib/CssDeclaration.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
function CssDeclaration(raw) {
this.raw = raw;
}
CssDeclaration.prototype.getProperty = function () {
if (this.raw.indexOf(':') === -1) {
return '';
}
return this.raw.split(':')[0].trim();
};
CssDeclaration.prototype.getValue = function () {
if (this.raw.indexOf(':') === -1) {
return '';
}
return this.raw.split(':')[1].trim();
};
module.exports = CssDeclaration;
================================================
FILE: lib/CssMediaQuery.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
function CssMediaQuery(raw) {
this.raw = raw;
}
CssMediaQuery.prototype.getQueries = function () {
var pattern = /@media\w*(.+?)\s?{/,
queries = pattern.exec(this.raw)[1];
return queries.split(/ or |,/g).map(trimQuery);
};
CssMediaQuery.prototype.getRules = function () {
var rules = [],
depth = 0,
rule = '';
for (var index = 0; index < this.raw.length; index++) {
if (depth > 0) {
rule += this.raw.charAt(index);
}
if (this.raw.charAt(index) === '{') {
depth ++;
}
else if (this.raw.charAt(index) == '}') {
depth --;
}
if (depth === 1 && this.raw.charAt(index) == '}') {
rules.push(rule.trim());
rule = '';
}
}
return rules;
};
var trimQuery = function (query) {
return query.trim();
};
module.exports = CssMediaQuery;
================================================
FILE: lib/CssRule.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
function CssRule(raw) {
this.raw = raw;
}
CssRule.prototype.getSelectors = function () {
return getSelectors(getSelectorBlock(this.raw));
};
CssRule.prototype.getDeclarations = function () {
return getDeclarations(getDeclarationBlock(this.raw));
};
var getSelectorBlock = function (rule) {
var pattern = /([^{]+)\{/g,
results = pattern.exec(rule);
return results[1];
};
var getSelectors = function (selectorBlock) {
var untrimmedSelectors = selectorBlock.split(','),
trimmedSelectors = untrimmedSelectors.map(function (untrimmed) {
return untrimmed.trim();
});
return _.compact(trimmedSelectors);
};
var getDeclarationBlock = function (rule) {
var pattern = /\{(.+)\}/g,
results = pattern.exec(rule);
if (_.isNull(results)) {
return '';
}
return results[1];
};
var getDeclarations = function (declarationBlock) {
var untrimmedDeclarations = _.compact(declarationBlock.trim().split(';')),
trimmedDeclarations = untrimmedDeclarations.map(function (untrimmed) {
return untrimmed.trim();
});
return trimmedDeclarations;
};
module.exports = CssRule;
================================================
FILE: lib/CssSelector.js
================================================
/*! Parker v0.1.0 - MIT license */
'use strict';
var _ = require('lodash'),
DELIMITERS = ['.', '#', '>', '[', ' ', ':', '*'];
function CssSelector(raw) {
this.raw = raw;
this.identifiers = [];
}
CssSelector.prototype.getIdentifiers = function () {
var identifier = '',
bracketDepth = 0,
parenDepth = 0;
_.each(this.raw, function (character, index) {
var insideBrackets = bracketDepth || parenDepth,
isSecondColon = character == ':' && this.raw[index - 1] == ':';
if (!insideBrackets && isDelimiter(character) && !isSecondColon) {
this.addIdentifier(identifier);
identifier = '';
}
switch(character) {
case '(': parenDepth++; break;
case ')': parenDepth--; break;
case '[': bracketDepth++; break;
case ']': bracketDepth--; break;
}
if (!_.contains([' ', '>'], character)) {
identifier += character;
}
}, this);
this.addIdentifier(identifier);
return _.without(this.identifiers, ' ', '', '[]');
}
CssSelector.prototype.addIdentifier = function (identifier) {
this.identifiers.push(identifier);
};
function isDelimiter(character) {
return _.contains(DELIMITERS, character)
}
module.exports = CssSelector;
================================================
FILE: lib/CssStylesheet.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
function CssStylesheet(raw) {
this.raw = raw;
}
CssStylesheet.prototype.getRules = function () {
this.children = this.children || getChildren(this.raw);
return this.children.filter(function (child) {
return isRule(child);
});
};
CssStylesheet.prototype.getMalformedStatements = function () {
this.children = this.children || getChildren(this.raw);
return this.children.filter(function (child) {
return isMalformedStatement(child);
});
};
CssStylesheet.prototype.getMediaQueries = function () {
this.children = this.children || getChildren(this.raw);
return this.children.filter(function (child) {
return isMediaQuery(child);
});
};
var getChildren = function (raw) {
var children = [],
depth = 0,
child = '',
stylesheet = stripComments(stripFormatting(raw));
for (var index = 0; index < stylesheet.length; index++) {
child += stylesheet.charAt(index);
if (stylesheet.charAt(index) === '{') {
depth ++;
}
else if (stylesheet.charAt(index) == '}') {
depth --;
}
if (depth === 0 && stylesheet.charAt(index).match(/\}|;/g)) {
children.push(child.trim());
child = '';
}
}
return children;
};
var stripComments = function (string) {
return string.replace(/\/\*.+?\*\//g, '');
};
var stripFormatting = function (string) {
return stripNewlines(trimWhitespace(string));
};
var trimWhitespace = function (string) {
return string.replace(/[ ]+/g, ' ');
};
var stripNewlines = function (string) {
return string.replace(/\n|\r|\r\n/g, '');
};
var isRule = function (string) {
return !isMediaQuery(string) && hasRuleBlock(string) && hasSelectorBlock(string);
}
var isMalformedStatement = function (string) {
return !isRule(string) && !isMediaQuery(string);
}
var hasRuleBlock = function (string) {
return string.indexOf('{') !== -1 && string.indexOf('}') !== -1;
}
var hasSelectorBlock = function (string) {
return string.match(/^[^\{]+/g)
}
var isMediaQuery = function (string) {
return string.match(/^@media/g);
}
module.exports = CssStylesheet;
================================================
FILE: lib/Formatters.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash'),
clc = require('cli-color');
// formats output as human-friendly text
exports.human = function (metrics, results) {
var logo = clc.red('PA') + clc.yellow('RK') + clc.green('ER') + '-JS' + "\n";
return logo + _.reduce(metrics, function (str, metric) {
return str + metric.name + ': ' + results[metric.id] + '\n';
}, '');
};
// formats output as JSON
exports.json = function (metrics, results) {
var ids = _.map(metrics, function (metric) {
return metric.id;
});
var obj = _.reduce(ids, function (obj, id) {
obj[id] = results[id];
return obj;
}, {});
return JSON.stringify(obj, null, 4);
};
exports.csv = function (metrics, results) {
var lineItems = [];
_.each(metrics, function (metric) {
lineItems.push('"' + results[metric.id] + '"');
});
return lineItems.join(',');
}
================================================
FILE: lib/Info.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var pkg = require('../package.json');
module.exports = {
version: function() {
console.log(pkg.name + ' v' + pkg.version);
},
help: function() {
module.exports.version();
[
pkg.description,
'',
'Usage:',
'parker [arguments] [file...] Run Parker on specified files',
'',
'Example Local Usage:',
'parker styles.css',
'',
'Example Stdin Usage:',
'curl http://www.katiefenn.co.uk/css/shuttle.css -s | parker -s',
'',
'Arguments:',
'',
'-f Set output format (see list of formats)',
'-h Shows help',
'-n Show numeric results only',
'-s Input CSS using stdin',
'-v Show version number of Parker',
'',
'Formats Usage:',
'parker -f "human"',
'',
'Formats List:',
'human Human-readable, newline separated format (default)',
'json JSON',
'csv CSV',
'',
'For more information, see ' + pkg.homepage
].forEach(function(str) { console.log(str); });
}
};
================================================
FILE: lib/Parker.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash'),
CssStylesheet = require('./CssStylesheet.js'),
CssRule = require('./CssRule.js'),
CssSelector = require('./CssSelector.js'),
CssDeclaration = require('./CssDeclaration.js'),
CssMediaQuery = require('./CssMediaQuery.js');
var VALID_METRIC_TYPE = /stylesheet|rule|selector|identifier|declaration|property|value|mediaquery/g;
function Parker(metrics) {
this.metrics = metrics;
}
Parker.prototype.run = function () {
var args = arguments;
if (arguments.length === 1 && _.isArray(arguments[0])) {
args = arguments[0];
}
args = _.filter(args, function (argument) {return _.isString(argument); });
var metrics = _.filter(this.metrics, function (metric) {return metric.type.match(VALID_METRIC_TYPE); });
if (args.length > 0) {
return runMetrics(metrics, args);
}
throw {'message': 'No valid stylesheet data supplied', 'name': 'DataTypeException'};
};
var runMetrics = function (metrics, stylesheets) {
var readings = [];
_.each(stylesheets, function (rawStylesheet) {
readings.push(runMetricsOnNode(metrics, rawStylesheet, 'stylesheet'));
var stylesheet = new CssStylesheet(rawStylesheet),
rules = stylesheet.getRules() || [];
_.each(stylesheet.getMediaQueries(), function (rawMediaQuery) {
var mediaQuery = new CssMediaQuery(rawMediaQuery);
_.each(mediaQuery.getQueries(), function (query) {
readings.push(runMetricsOnNode(metrics, query, 'mediaquery'));
});
rules = rules.concat(mediaQuery.getRules());
});
_.each(rules, function (rawRule) {
readings.push(runMetricsOnNode(metrics, rawRule, 'rule'));
var rule = new CssRule(rawRule);
_.each(rule.getSelectors(), function (rawSelector) {
var selector = new CssSelector(rawSelector);
readings.push(runMetricsOnNode(metrics, rawSelector, 'selector'));
_.each(selector.getIdentifiers(), function (rawIdentifier) {
readings.push(runMetricsOnNode(metrics, rawIdentifier, 'identifier'));
});
});
_.each(rule.getDeclarations(), function (rawDeclaration) {
var declaration = new CssDeclaration(rawDeclaration);
readings.push(runMetricsOnNode(metrics, rawDeclaration, 'declaration'));
readings.push(runMetricsOnNode(metrics, declaration.getProperty(), 'property'));
readings.push(runMetricsOnNode(metrics, declaration.getValue(), 'value'));
});
});
});
var data = readings.reduce(mergeArrayAttributes);
data = aggregateData(data, metrics);
return data;
};
var runMetricsOnNode = function (metrics, node, type) {
var data = {};
_.each(filterMetricsByType(metrics, type), function (metric) {
var measurement = metric.measure(node);
if (!_.isArray(measurement)) {
measurement = [measurement];
}
data[metric.id] = measurement;
});
return data;
};
var aggregateData = function (data, metrics) {
_.each(metrics, function (metric) {
if (!data[metric.id]) {
data[metric.id] = [];
}
switch (metric.aggregate) {
case 'sum':
data[metric.id] = aggregateSum(data[metric.id]);
break;
case 'mean':
data[metric.id] = aggregateMean(data[metric.id]);
break;
case 'max':
data[metric.id] = aggregateMax(data[metric.id], metric.iterator);
break;
case 'list':
data[metric.id] = aggregateList(data[metric.id], metric.filter);
break;
case 'length':
data[metric.id] = aggregateLength(data[metric.id], metric.filter);
break;
case 'reduce':
data[metric.id] = aggregateReduce(data[metric.id], metric.reduce, metric.initial);
break;
}
});
return data;
};
var aggregateSum = function (data) {
return sum(data);
};
var aggregateMean = function (data) {
if (data.length === 0) {
return 0;
}
return mean(data);
};
var aggregateMax = function (data, iterator) {
if (data.length === 0) {
return 0;
}
if (_.isUndefined(iterator)) {
return _.max(data);
}
return _.max(data, iterator);
};
var aggregateList = function (data, filter) {
if (!_.isUndefined(filter)) {
return _.compact(data.filter(filter));
}
return _.compact(data);
};
var aggregateLength = function (data, filter) {
if (!_.isUndefined(filter)) {
return data.filter(filter).length;
}
return _.compact(data).length;
};
var aggregateReduce = function (data, reduce, initial) {
return data.reduce(reduce, initial);
};
var mergeArrayAttributes = function (target, source) {
_.each(source, function (attribute, attributeName) {
if (!_.has(target, attributeName)) {
target[attributeName] = [];
}
if (!_.isUndefined(attribute)) {
if (_.isString(attribute)) {
attribute = [attribute];
}
target[attributeName] = target[attributeName].concat(attribute);
}
});
return target;
};
var sum = function (values) {
if (values.length === 0) {
return 0;
}
return values.reduce(function (previous, current) {return previous + current; });
};
var mean = function (values) {
var valuesSum = sum(values);
return valuesSum / values.length;
};
var filterMetricsByType = function (metrics, type) {
if (type) {
return metrics.filter(function (metric) {return metric.type === type; });
}
return metrics;
};
module.exports = Parker;
================================================
FILE: lib/PreciseSelectorSpecificity.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var CssSelector = require('../lib/CssSelector');
var _ = require('lodash');
var CLASS_A = 1;
var CLASS_B = 256;
var CLASS_C = 65536;
module.exports = function (rawSelector) {
var totalSpecificity = 0,
selector = new CssSelector(rawSelector);
_.each(selector.getIdentifiers(), function (identifier) {
var idIdentifiers = countIdIdentifiers(identifier),
classIdentifiers = countClassIdentifiers(identifier),
attributeIdentifiers = countAttributeIdentifiers(identifier),
pseudoClassIdentifiers = countPseudoClassIdentifiers(identifier),
typeIdentifiers = countTypeIdentifiers(identifier),
pseudoElementIdentifiers = countPseudoElementIdentifiers(identifier);
totalSpecificity += Number(
(idIdentifiers * CLASS_C) +
((classIdentifiers + attributeIdentifiers + pseudoClassIdentifiers) * CLASS_B) +
((typeIdentifiers + pseudoElementIdentifiers) * CLASS_A));
});
return totalSpecificity;
}
var countIdIdentifiers = function (identifier) {
var regex = /#/,
matches = regex.exec(identifier);
if (matches && !countAttributeIdentifiers(identifier)) {
return matches.length;
}
return 0;
};
var countClassIdentifiers = function (identifier) {
var regex = /\./,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countAttributeIdentifiers = function (identifier) {
var regex = /\[/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countPseudoClassIdentifiers = function (identifier) {
var regex = /^:[^:]/,
matches = regex.exec(identifier);
// :not pseudo-class identifier itself is ignored
// only selectors inside it are counted
if (identifier.match(/:not/)) {
return 0;
}
if (matches) {
return matches.length;
}
return 0;
};
var countTypeIdentifiers = function (identifier) {
var regex = /^[a-zA-Z_]/;
if (regex.exec(identifier)) {
return 1;
}
return 0;
};
var countPseudoElementIdentifiers = function (identifier) {
var regex = /::/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var stripNotIdentifier = function (identifier) {
if (identifier.match(/:not/)) {
return identifier.replace(/:not\(|\)/g, '');
}
return identifier;
};
================================================
FILE: metrics/All.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
module.exports = [
// Stylesheet Totals
require('./TotalStylesheets.js'),
require('./TotalStylesheetSize.js'),
// Stylesheet Element Totals
require('./TotalRules.js'),
require('./TotalSelectors.js'),
require('./TotalIdentifiers.js'),
require('./TotalDeclarations.js'),
// Stylesheet Element Averages
require('./SelectorsPerRule.js'),
require('./IdentifiersPerSelector.js'),
require('./DeclarationsPerRule.js'),
// Specificity
require('./SpecificityPerSelector.js'),
require('./PreciseSpecificityPerSelector.js'),
require('./TopSelectorSpecificity.js'),
require('./PreciseTopSelectorSpecificity.js'),
require('./StringTopSelectorSpecificity.js'),
require('./TopSelectorSpecificitySelector.js'),
require('./TotalIdSelectors.js'),
// Colour
require('./TotalUniqueColours.js'),
require('./UniqueColours.js'),
// Important Keywords
require('./TotalImportantKeywords.js'),
// Media Queries
require('./TotalMediaQueries.js'),
require('./MediaQueries.js'),
// Z-Index
require('./ZIndexes.js')
];
================================================
FILE: metrics/DeclarationsPerRule.js
================================================
'use strict';
var CssRule = require('../lib/CssRule');
var _ = require('lodash');
module.exports = {
id: 'declarations-per-rule',
name: 'Declarations Per Rule',
type: 'rule',
aggregate: 'mean',
format: 'number',
measure: function (raw) {
var rule = new CssRule(raw);
return rule.getDeclarations().length;
}
};
================================================
FILE: metrics/IdentifiersPerSelector.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'identifiers-per-selector',
name: 'Identifiers Per Selector',
type: 'selector',
aggregate: 'mean',
format: 'number',
measure: function (selector) {
var identifiers = getIdentifiers(selector);
if (identifiers.length === 1 && identifiers[0] === '') {
return 0;
}
return identifiers.length;
}
};
var getIdentifiers = function (selector) {
var identifiers = [],
segments = selector.split(/\s+[\s\+>]\s?|~^=/g);
_.each(segments, function (segment) {
identifiers = identifiers.concat(segment.match(/[#\.:]?[\w\-\*]+|\[[\w=\-~'"\|]+\]|:{2}[\w-]+/g) || []);
});
return identifiers;
};
================================================
FILE: metrics/MediaQueries.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'media-queries',
name: 'Media Queries',
type: 'mediaquery',
aggregate: 'list',
format: 'list',
measure: function (query) {
return query;
},
filter: function (value, index, self) {
return self.indexOf(value) === index;
}
};
================================================
FILE: metrics/PreciseSpecificityPerSelector.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var CssSelector = require('../lib/CssSelector');
var getSpecificity = require('../lib/PreciseSelectorSpecificity');
module.exports = {
id: 'precise-specificity-per-selector',
name: 'Specificity Per Selector (Precise)',
type: 'selector',
aggregate: 'mean',
format: 'number',
measure: getSpecificity
};
================================================
FILE: metrics/PreciseTopSelectorSpecificity.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var CssSelector = require('../lib/CssSelector');
var getSpecificity = require('../lib/PreciseSelectorSpecificity');
module.exports = {
id: 'precise-top-selector-specificity',
name: 'Top Selector Specificity (Precise)',
type: 'selector',
aggregate: 'max',
format: 'number',
measure: getSpecificity
};
================================================
FILE: metrics/SelectorsPerRule.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
module.exports = {
id: 'selectors-per-rule',
name: 'Selectors Per Rule',
type: 'rule',
aggregate: 'mean',
format: 'number',
measure: function (rule) {
return getSelectors(getSelectorBlock(rule)).length;
}
};
var getSelectorBlock = function (rule) {
var pattern = /([^{]+)\{/g,
results = pattern.exec(rule);
return results[1];
};
var getSelectors = function (selectorBlock) {
var untrimmedSelectors = selectorBlock.split(','),
trimmedSelectors = untrimmedSelectors.map(function (untrimmed) {
return untrimmed.trim();
});
return trimmedSelectors;
};
================================================
FILE: metrics/SpecificityPerSelector.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var CssSelector = require('../lib/CssSelector');
var getSpecificity = require('../lib/ClassicalSelectorSpecificity');
module.exports = {
id: 'specificity-per-selector',
name: 'Specificity Per Selector (Classical)',
type: 'selector',
aggregate: 'mean',
format: 'number',
measure: getSpecificity
};
================================================
FILE: metrics/StringTopSelectorSpecificity.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var CssSelector = require('../lib/CssSelector');
var getSpecificity = require('../lib/ArraySelectorSpecificity');
module.exports = {
id: 'string-top-selector-specificity',
name: 'Top Selector Specificity (String)',
type: 'selector',
aggregate: 'reduce',
format: 'string',
initial: '0,0,0',
measure: function(selector) {
return selector;
},
reduce: function(previous, current) {
var previousSpecificity = fromString(previous);
var currentSpecificity = getSpecificity(current);
return toString(mostSpecific(previousSpecificity, currentSpecificity));
}
};
function toString(arr) {
return arr.map(function(item) {
return item.toString();
}).join(',');
}
function fromString(str) {
return str.split(',').map(function(item) {
return parseInt(item);
});
}
function mostSpecific(arr1, arr2) {
var arr1Specificity = (arr1[0] * 65536) + (arr1[1] * 256) + (arr1[2] * 1);
var arr2Specificity = (arr2[0] * 65536) + (arr2[1] * 256) + (arr2[2] * 1);
if (arr1Specificity > arr2Specificity) {
return arr1;
}
return arr2;
}
================================================
FILE: metrics/TopSelectorSpecificity.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var CssSelector = require('../lib/CssSelector');
module.exports = {
id: 'top-selector-specificity',
name: 'Top Selector Specificity (Classical)',
type: 'selector',
aggregate: 'max',
format: 'number',
measure: function (rawSelector) {
var selector = new CssSelector(rawSelector),
identifiers = selector.getIdentifiers(),
specificity = 0;
_.each(identifiers, function (identifier) {
identifier = stripNotIdentifier(identifier);
var idIdentifiers = countIdIdentifiers(identifier),
classIdentifiers = countClassIdentifiers(identifier),
attributeIdentifiers = countAttributeIdentifiers(identifier),
pseudoClassIdentifiers = countPseudoClassIdentifiers(identifier),
typeIdentifiers = countTypeIdentifiers(identifier),
pseudoElementIdentifiers = countPseudoElementIdentifiers(identifier);
specificity += getSpecificity(idIdentifiers, classIdentifiers, attributeIdentifiers, pseudoClassIdentifiers, typeIdentifiers, pseudoElementIdentifiers);
}, this);
return specificity;
}
};
var getSpecificity = function (idIdentifiers, classIdentifiers, attributeIdentifiers, pseudoClassIdentifiers, typeIdentifiers, pseudoElementIdentifiers) {
return Number(
String(idIdentifiers) +
String(classIdentifiers + attributeIdentifiers + pseudoClassIdentifiers) +
String(typeIdentifiers + pseudoElementIdentifiers)
);
};
var countIdIdentifiers = function (identifier) {
var regex = /#/,
matches = regex.exec(identifier);
if (matches && !countAttributeIdentifiers(identifier)) {
return matches.length;
}
return 0;
};
var countClassIdentifiers = function (identifier) {
var regex = /\./,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countAttributeIdentifiers = function (identifier) {
var regex = /\[/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countPseudoClassIdentifiers = function (identifier) {
var regex = /^:[^:]/,
matches = regex.exec(identifier);
// :not pseudo-class identifier itself is ignored
// only selectors inside it are counted
if (identifier.match(/:not/)) {
return 0;
}
if (matches) {
return matches.length;
}
return 0;
};
var countTypeIdentifiers = function (identifier) {
var regex = /^[a-zA-Z_]/;
if (regex.exec(identifier)) {
return 1;
}
return 0;
};
var countPseudoElementIdentifiers = function (identifier) {
var regex = /::/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var stripNotIdentifier = function (identifier) {
if (identifier.match(/:not/)) {
return identifier.replace(/:not\(|\)/g, '');
}
return identifier;
};
================================================
FILE: metrics/TopSelectorSpecificitySelector.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var CssSelector = require('../lib/CssSelector');
var getSpecificity = require('../lib/PreciseSelectorSpecificity');
module.exports = {
id: 'top-selector-specificity-selector',
name: 'Top Selector Specificity Selector',
type: 'selector',
aggregate: 'max',
format: 'string',
measure: function(selector) {
return selector;
},
iterator: getSpecificity
};
var getSpecificity = function (idIdentifiers, classIdentifiers, attributeIdentifiers, pseudoClassIdentifiers, typeIdentifiers, pseudoElementIdentifiers) {
return Number(
String(idIdentifiers) +
String(classIdentifiers + attributeIdentifiers + pseudoClassIdentifiers) +
String(typeIdentifiers + pseudoElementIdentifiers)
);
};
var countIdIdentifiers = function (identifier) {
var regex = /#/,
matches = regex.exec(identifier);
if (matches && !countAttributeIdentifiers(identifier)) {
return matches.length;
}
return 0;
};
var countClassIdentifiers = function (identifier) {
var regex = /\./,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countAttributeIdentifiers = function (identifier) {
var regex = /\[/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var countPseudoClassIdentifiers = function (identifier) {
var regex = /^:[^:]/,
matches = regex.exec(identifier);
// :not pseudo-class identifier itself is ignored
// only selectors inside it are counted
if (identifier.match(/:not/)) {
return 0;
}
if (matches) {
return matches.length;
}
return 0;
};
var countTypeIdentifiers = function (identifier) {
var regex = /^[a-zA-Z_]/;
if (regex.exec(identifier)) {
return 1;
}
return 0;
};
var countPseudoElementIdentifiers = function (identifier) {
var regex = /::/,
matches = regex.exec(identifier);
if (matches) {
return matches.length;
}
return 0;
};
var stripNotIdentifier = function (identifier) {
if (identifier.match(/:not/)) {
return identifier.replace(/:not\(|\)/g, '');
}
return identifier;
};
================================================
FILE: metrics/TotalDeclarations.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
module.exports = {
id: 'total-declarations',
name: 'Total Declarations',
type: 'declaration',
aggregate: 'sum',
format: 'number',
measure: function (declaration) {
return 1;
}
};
================================================
FILE: metrics/TotalIdSelectors.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'total-id-selectors',
name: 'Total Id Selectors',
type: 'selector',
aggregate: 'sum',
format: 'number',
measure: function (selector) {
var ids = 0;
var inBrackets = false;
_.forOwn(selector, function (char) {
if (char === '[') {
inBrackets = true;
} else if (char === ']') {
inBrackets = false;
} else if (char === '#' && !inBrackets) {
ids++;
}
});
return ids;
}
};
================================================
FILE: metrics/TotalIdentifiers.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'total-identifiers',
name: 'Total Identifiers',
type: 'identifier',
aggregate: 'sum',
format: 'number',
measure: function (identifier) {
return 1;
}
};
================================================
FILE: metrics/TotalImportantKeywords.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'total-important-keywords',
name: 'Total Important Keywords',
type: 'value',
aggregate: 'sum',
format: 'number',
measure: function (value) {
if (value.match(/!important/g))
return 1;
return 0;
}
};
================================================
FILE: metrics/TotalMediaQueries.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'total-media-queries',
name: 'Total Media Queries',
type: 'mediaquery',
aggregate: 'length',
format: 'number',
measure: function (query) {
return query;
},
filter: function (value, index, self) {
return self.indexOf(value) === index;
}
};
================================================
FILE: metrics/TotalRules.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
module.exports = {
id: 'total-rules',
name: 'Total Rules',
type: 'rule',
aggregate: 'sum',
format: 'number',
measure: function (rule) {
return 1;
}
};
================================================
FILE: metrics/TotalSelectors.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'total-selectors',
name: 'Total Selectors',
type: 'selector',
aggregate: 'sum',
format: 'number',
measure: function (selector) {
return 1;
}
};
================================================
FILE: metrics/TotalStylesheetSize.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
module.exports = {
id: 'total-stylesheet-size',
name: 'Total Stylesheet Size',
type: 'stylesheet',
aggregate: 'sum',
format: 'number',
measure: function (stylesheet) {
return byteCount(stylesheet);
}
};
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}
================================================
FILE: metrics/TotalStylesheets.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
module.exports = {
id: 'total-stylesheets',
name: 'Total Stylesheets',
type: 'stylesheet',
aggregate: 'sum',
format: 'number',
measure: function (stylesheet) {
return 1;
}
};
================================================
FILE: metrics/TotalUniqueColours.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'total-unique-colours',
name: 'Total Unique Colors',
type: 'value',
aggregate: 'length',
format: 'number',
measure: function (value) {
return getColourHexes(value).map(function (colourHex) {
return getLongHashForm(colourHex).toUpperCase();
});
},
filter: function (value, index, self) {
return self.indexOf(value) === index;
}
};
var getColourHexes = function (value) {
var colourHexes = value.match(/#[0-9a-fA-F]{3,6}/g);
if (_.isNull(colourHexes)) {
colourHexes = [];
}
return colourHexes;
};
var getLongHashForm = function (string) {
if (string.length === 4) {
var r = string.substring(1, 2),
g = string.substring(2, 3),
b = string.substring(3);
return '#' + r + r + g + g + b + b;
}
return string;
};
================================================
FILE: metrics/UniqueColours.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
module.exports = {
id: 'unique-colours',
name: 'Unique Colors',
type: 'value',
aggregate: 'list',
format: 'list',
measure: function (value) {
return getColourHexes(value).map(function (colourHex) {
return getLongHashForm(colourHex).toUpperCase();
});
},
filter: function (value, index, self) {
return self.indexOf(value) === index;
}
};
var getColourHexes = function (value) {
var colourHexes = value.match(/#[0-9a-fA-F]{3,6}/g);
if (_.isNull(colourHexes)) {
colourHexes = [];
}
return colourHexes;
};
var getLongHashForm = function (string) {
if (string.length === 4) {
var r = string.substring(1, 2),
g = string.substring(2, 3),
b = string.substring(3);
return '#' + r + r + g + g + b + b;
}
return string;
};
================================================
FILE: metrics/ZIndexes.js
================================================
/*! Parker v0.0.0 - MIT license */
'use strict';
var CssDeclaration = require('../lib/CssDeclaration');
module.exports = {
id: 'z-indexes',
name: 'Z-Indexes',
type: 'declaration',
aggregate: 'list',
format: 'list',
measure: function (raw) {
var declaration = new CssDeclaration(raw);
if (declaration.getProperty() == "z-index") {
return declaration.getValue();
}
},
filter: function (value, index, self) {
return value != undefined && self.indexOf(value) === index;
}
};
================================================
FILE: package.json
================================================
{
"name": "parker",
"description": "Stylesheet analysis tool for CSS",
"keywords": [
"css",
"stylesheet",
"analysis"
],
"version": "1.0.0-alpha.0",
"main": "parker.js",
"dependencies": {
"async": "~0.2.10",
"cli-color": "*",
"graceful-fs": "~3.0.2",
"lodash": "^3.2.0",
"minimist": "0.0.7"
},
"devDependencies": {
"chai": "*",
"mocha": "*",
"sinon": "*",
"sinon-chai": "*"
},
"scripts": {
"test": "mocha --no-colors --reporter spec"
},
"bin": {
"parker": "./parker.js"
},
"homepage": "https://github.com/katiefenn/parker",
"bugs": "https://github.com/katiefenn/parker/issues",
"author": "Katie Fenn",
"repository": "https://github.com/katiefenn/parker",
"preferGlobal": true,
"license": "MIT"
}
================================================
FILE: parker.js
================================================
#!/usr/bin/env node
/*! csstool v0.0.0 - MIT license */
'use strict';
/**
* Module dependencies
*/
var _ = require('lodash'),
Parker = require('./lib/Parker'),
CliController = require('./lib/CliController'),
metrics = require('./metrics/All'),
formatters = require('./lib/Formatters'),
argv = require('minimist')(process.argv.slice(2)),
fs = require('graceful-fs'),
async = require('async'),
path = require('path'),
info = require('./lib/Info');
var cliController = new CliController();
cliController.on('runPaths', function (filePaths) {
var stylesheets = [];
async.each(filePaths, function (filePath, onAllLoad) {
var onFileLoad = function (err, data) {
stylesheets.push(data);
};
read(filePath, onFileLoad, onAllLoad);
}, function (err) {
runReport(stylesheets, metrics);
});
});
cliController.on('runStdin', function () {
process.stdin.resume();
process.stdin.setEncoding('utf8');
var stdinData = '';
process.stdin.on('data', function(chunk) {
stdinData += chunk;
});
process.stdin.on('end', function() {
runReport(stdinData, metrics);
});
});
cliController.on('showVersion', function () {
info.version();
process.exit();
});
cliController.on('showHelp', function () {
info.help();
process.exit();
});
cliController.on('setFormat', function (format) {
formatter = formatters[format];
if (!formatter) {
console.error('Unknown output format: %s', argv.format);
console.error(' available: ' + Object.keys(formatters).join(' '));
process.exit(1);
}
});
cliController.on('showNumericOnly', function () {
metrics = _.filter(metrics, function (metric) {
return metric.format == 'number';
});
});
var read = function (filePath, onFileLoad, onAllLoad) {
if (fs.lstatSync(filePath).isDirectory()) {
readDirectory(filePath, onFileLoad, onAllLoad);
}
else if (fileIsStylesheet(filePath)) {
readFile(filePath, function (err, data) {
onFileLoad(err, data);
onAllLoad();
});
} else {
onAllLoad();
}
}
var readDirectory = function (directoryPath, onFileLoad, onAllLoad) {
fs.readdir(directoryPath, function (err, files) {
async.each(files, function (file, fileDone) {
read(path.join(directoryPath, file), onFileLoad, fileDone);
}, onAllLoad);
});
};
var readFile = function (filePath, onLoad) {
fs.readFile(filePath, {encoding: 'utf8'}, function (err, fileData) {
onLoad(err, fileData);
});
};
var fileIsStylesheet = function (filePath) {
return filePath.indexOf('.css') !== -1;
};
var runReport = function (stylesheets, metrics) {
var results = parker.run(stylesheets);
console.log(formatter(metrics, results));
};
if (module.parent) {
module.exports = Parker;
} else {
var parker = new Parker(metrics),
formatter = formatters['human'];
cliController.dispatch(argv);
}
================================================
FILE: test/CliController.js
================================================
/*! Parker v0.0.0 - MIT license */
var chai = require('chai'),
expect = require('chai').expect,
CliController = require('../lib/CliController.js'),
sinon = require('sinon'),
sinonChai = require('sinon-chai');
chai.use(sinonChai);
describe('The CLI Controller', function() {
it('responds to a -v switch by dispatching a version event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showVersion', callback);
cliController.dispatch({'v': true});
expect(callback).to.have.been.called;
});
it('responds to a --version switch by dispatching a version event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showVersion', callback);
cliController.dispatch({'version': true});
expect(callback).to.have.been.called;
});
it('responds to a -h switch by dispatching a version event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showHelp', callback);
cliController.dispatch({'h': true});
expect(callback).to.have.been.called;
});
it('responds to a --help switch by dispatching a version event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showHelp', callback);
cliController.dispatch({'help': true});
expect(callback).to.have.been.called;
});
it('responds to a -h switch by dispatching a help event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showHelp', callback);
cliController.dispatch({'h': true});
expect(callback).to.have.been.called;
});
it('responds to a --help switch by dispatching a help event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showHelp', callback);
cliController.dispatch({'h': true});
expect(callback).to.have.been.called;
});
it('responds to a -f switch by dispatching a format event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('setFormat', callback);
cliController.dispatch({'f': 'json'});
expect(callback).to.have.been.calledWith('json');
});
it('responds to a --format switch by dispatching a format event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('setFormat', callback);
cliController.dispatch({'format': 'json'});
expect(callback).to.have.been.calledWith('json');
});
it('responds to no data supplied by dispatching a help event', function () {
var callback = sinon.spy(),
cliController = new CliController();
cliController.on('showHelp', callback);
cliController.dispatch({});
expect(callback).to.have.been.called;
});
it('responds to unnamed arguments by dispatching file event, then a run event', function () {
var pathsCallback = sinon.spy(),
cliController = new CliController();
cliController.on('runPaths', pathsCallback);
cliController.dispatch({'_': ['styles.css', 'ie.css']});
expect(pathsCallback).to.have.been.calledWith(['styles.css', 'ie.css']);
});
});
================================================
FILE: test/CssDeclaration.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
CssDeclaration = require('../lib/CssDeclaration.js');
describe('The Declaration Parser', function() {
beforeEach(function() {
cssDeclaration = new CssDeclaration('color: #fff');
});
it('should return a property and a value for a declaration', function() {
expect(cssDeclaration.getProperty()).to.equal('color');
expect(cssDeclaration.getValue()).to.equal('#fff');
});
});
================================================
FILE: test/CssMediaQuery.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
CssMediaQuery = require('../lib/CssMediaQuery.js');
describe('The Css Media Query object', function () {
it('should return (n) queries for a media query of (n) queries', function () {
var cssMediaQuery = new CssMediaQuery('@media print {a {color: #000;}}');
expect(cssMediaQuery.getQueries()[0]).to.equal('print');
cssMediaQuery = new CssMediaQuery('@media (min-width: 700px) and (orientation: landscape) {.blogroll {display: none;}}');
expect(cssMediaQuery.getQueries()[0]).to.equal('(min-width: 700px) and (orientation: landscape)');
cssMediaQuery = new CssMediaQuery('@media handheld, (min-width: 700px) {.blogroll {display: none;}}');
expect(cssMediaQuery.getQueries()[0]).to.equal('handheld');
expect(cssMediaQuery.getQueries()[1]).to.equal('(min-width: 700px)');
cssMediaQuery = new CssMediaQuery('@media handheld or (min-width: 700px) {.blogroll {display: none;}}');
expect(cssMediaQuery.getQueries()[0]).to.equal('handheld');
expect(cssMediaQuery.getQueries()[1]).to.equal('(min-width: 700px)');
});
it('should return (n) queries for a media query of (n) rules', function () {
var cssMediaQuery = new CssMediaQuery('@media print {a {color: #000;} header {display: none;}}');
expect(cssMediaQuery.getRules()[0]).to.equal('a {color: #000;}');
expect(cssMediaQuery.getRules()[1]).to.equal('header {display: none;}');
});
});
================================================
FILE: test/CssRule.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
CssRule = require('../lib/CssRule.js');
describe('The Rule Parser', function () {
it('should return a collection of (n) items of selectors for a rule of (n) selectors', function () {
var cssRule = new CssRule('body {border: 0;}');
expect(cssRule.getSelectors()).to.have.length(1);
var complexRule = 'body, html, .container .wrapper, #container, .container a[rel="blah"]'
+ '{background: url(img.png); background-color: #ffffff;}';
cssRule = new CssRule(complexRule);
expect(cssRule.getSelectors()).to.have.length(5);
});
it('should return a collection of (n) items of declarations for a rule of (n) declarations', function () {
var cssRule = new CssRule('body {border: 0;}');
expect(cssRule.getDeclarations()).to.have.length(1);
var complexRule = 'body, html, .container .wrapper, #container, .container a[rel="blah"]'
+ '{background: url(img.png); background-color: linear-gradient(45deg, #00f, #f00)}';
cssRule = new CssRule(complexRule);
expect(cssRule.getDeclarations()).to.have.length(2);
});
});
================================================
FILE: test/CssSelector.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
CssSelector = require('../lib/CssSelector.js');
describe('The Selector Parser', function() {
it('returns a collection of (n) items for a selector of (n) identifiers', function() {
var cssSelector = new CssSelector('#my-form');
expect(cssSelector.getIdentifiers()).to.have.length(1);
cssSelector = new CssSelector('#my-form #username.error');
expect(cssSelector.getIdentifiers()).to.have.length(3);
cssSelector = new CssSelector('#my-form input[name=username]');
expect(cssSelector.getIdentifiers()).to.have.length(3);
});
it('correctly parses universal identifiers in a selector', function() {
var cssSelector = new CssSelector('body .list *:first-child');
expect(cssSelector.getIdentifiers()).to.have.length(4);
});
it('correctly parses type identifiers in a selector', function() {
var cssSelector = new CssSelector('body form input');
expect(cssSelector.getIdentifiers()).to.have.length(3);
});
it('correctly parses class identifiers in a selector', function() {
var cssSelector = new CssSelector('.login-form .checkbox.error');
expect(cssSelector.getIdentifiers()).to.have.length(3);
});
it('correctly parses id identifiers in a selector', function() {
var cssSelector = new CssSelector('#login-page #form#login-form input#password.error');
expect(cssSelector.getIdentifiers()).to.have.length(6);
});
it('correctly parses attribute identifiers in a selector', function() {
var cssSelector = new CssSelector('form[name=login-form]');
expect(cssSelector.getIdentifiers()).to.have.length(2);
cssSelector = new CssSelector('a[rel][]');
expect(cssSelector.getIdentifiers()).to.have.length(2);
cssSelector = new CssSelector('a[rel~="copyright"]');
expect(cssSelector.getIdentifiers()).to.have.length(2);
cssSelector = new CssSelector('a[hreflang|="en"]');
expect(cssSelector.getIdentifiers()).to.have.length(2);
cssSelector = new CssSelector('a[hreflang=fr]');
expect(cssSelector.getIdentifiers()).to.have.length(2);
});
it('correctly parses pseudo-class identifiers in a selector', function() {
var cssSelector = new CssSelector('a:first-child');
expect(cssSelector.getIdentifiers()).to.have.length(2);
});
it('correctly parses pseudo-element identifiers in a selector', function() {
var cssSelector = new CssSelector('p::first-line');
expect(cssSelector.getIdentifiers()).to.have.length(2);
});
});
================================================
FILE: test/CssStylesheet.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
CssStylesheet = require('../lib/CssStylesheet.js');
describe('The Stylesheet Parser', function() {
it('should return an empty array of child rules for an empty string', function () {
var cssStylesheet = new CssStylesheet('');
expect(cssStylesheet.getRules()).to.be.an('array');
expect(cssStylesheet.getRules()).to.be.empty;
});
it('should return (n) items of child rules for a stylesheet of (n) rules', function() {
var cssStylesheet = new CssStylesheet("body {border: 0} h1 {font-weight: bold;}");
expect(cssStylesheet.getRules()).to.have.length(2);
var multipleRules = "body {border: 0;} h1 {font-weight: bold;}"
+ " p {color: #333333; font-size: 1.2em; width: 100%} input {border: 1px solid #333333;"
+ " background-color: 1px solid #CCCCCC; padding: 0.1em; linear-gradient(45deg, #00f, #f00)}";
cssStylesheet = new CssStylesheet(multipleRules);
expect(cssStylesheet.getRules()).to.have.length(4);
var multipleSelectors = "body section :first-child {background: #FFF;}"
+ "form#registration-form > input.username {font-weight: bold;}";
cssStylesheet = new CssStylesheet(multipleSelectors);
expect(cssStylesheet.getRules()).to.have.length(2);
});
it('should distinguish between media-queries and at-rules', function () {
var cssStylesheet = new CssStylesheet("@media screen { body {border: 0;} } @include (styles.css); body { margin: 0; }");
expect(cssStylesheet.getMediaQueries()[0]).to.equal('@media screen { body {border: 0;} }');
expect(cssStylesheet.getMediaQueries()).to.have.length(1);
expect(cssStylesheet.getRules()[0]).to.equal('body { margin: 0; }');
});
it('should return (n) items of child media-queries for a stylesheet of (n) media-queries', function () {
var cssStylesheet = new CssStylesheet("@media screen { body {border: 0;} } @media print { a {color: #000;} } @include (styles.css);");
expect(cssStylesheet.getMediaQueries()).to.have.length(2);
expect(cssStylesheet.getMediaQueries()[0]).to.equal('@media screen { body {border: 0;} }');
expect(cssStylesheet.getMediaQueries()[1]).to.equal('@media print { a {color: #000;} }');
});
it('should ignore comments', function () {
var cssStylesheet = new CssStylesheet("body {border: 0;} /* ./* */ a {color: #fff; /* comment */} * {margin: 0;}");
expect(cssStylesheet.getRules()).to.have.length(3);
});
it('should ignore newline characters', function () {
var cssStylesheet = new CssStylesheet("body {\nborder: 0;\n}\na{\ncolor: #fff;\n}");
expect(cssStylesheet.getRules()[0]).to.equal("body {border: 0;}");
expect(cssStylesheet.getRules()[1]).to.equal("a{color: #fff;}");
var cssStylesheet = new CssStylesheet("body {\r\nborder: 0;\r\n}\r\na{\r\ncolor: #fff;\r\n}");
expect(cssStylesheet.getRules()[0]).to.equal("body {border: 0;}");
expect(cssStylesheet.getRules()[1]).to.equal("a{color: #fff;}");
});
it('should return an array of malformed statements for a string containing malformed statements', function () {
var cssStylesheet = new CssStylesheet('body {border: 0;} h1; h2 {font-weight: bold;}');
expect(cssStylesheet.getRules()).to.be.an('array');
expect(cssStylesheet.getMalformedStatements()[0]).to.equal('h1;');
});
it('should identify a rule with an unexpected colon as a malformed statement', function () {
var cssStylesheet = new CssStylesheet('body {border: 0;} h1;{font-weight: bold;}');
expect(cssStylesheet.getRules()).to.be.an('array');
expect(cssStylesheet.getMalformedStatements()[0]).to.equal('h1;');
expect(cssStylesheet.getMalformedStatements()[1]).to.equal('{font-weight: bold;}');
});
});
================================================
FILE: test/DeclarationsPerRule.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
metric = require('../metrics/DeclarationsPerRule.js');
describe('The declarations-per-rule metric', function () {
it('should provide a string identifier for the metric', function() {
expect(metric.id).to.be.a('string');
});
it('should provide a metric type', function() {
expect(metric.aggregate).to.match(/sum|mean/g);
});
it('should return 0 for an empty string', function () {
expect(metric.measure('')).to.equal(0);
});
it('should return 1 for the selector "body { color: #222 }"', function() {
expect(metric.measure('body { color: 1 }')).to.equal(1);
});
it('should return 2 for the selector "body { color: #222; backgrund: #333; }"', function() {
expect(metric.measure('body { color: #222; backgrund: #333; }')).to.equal(2);
});
it('should return 3 for the selector "body { color: #222; backgrund: #333; margin: 0; }"', function() {
expect(metric.measure('body { color: #222; backgrund: #333; margin: 0; }')).to.equal(3);
});
it('should return 4 for the selector "body { color: #222; backgrund: #333; margin: 0; padding: 0; }"', function() {
expect(metric.measure('body { color: #222; backgrund: #333; margin: 0; padding: 0; }')).to.equal(4);
});
});
================================================
FILE: test/IdentifiersPerSelector.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
metric = require('../metrics/IdentifiersPerSelector.js');
describe('The identifiers-per-selector metric', function () {
it('should provide a string identifier for the metric', function() {
expect(metric.id).to.be.a('string');
});
it('should provide a metric type', function() {
expect(metric.aggregate).to.match(/sum|mean/g);
});
it('should return 0 for an empty string', function () {
expect(metric.measure('')).to.equal(0);
});
it('should return 1 for the selector "body"', function() {
expect(metric.measure('body')).to.equal(1);
});
it('should return 2 for the selector "body section"', function() {
expect(metric.measure('body section')).to.equal(2);
});
it('should return 3 for the selector "body section.articles"', function() {
expect(metric.measure('body section.acticles')).to.equal(3);
});
it('should return 4 for the selector "body section.articles>article"', function() {
expect(metric.measure('body section.articles>article')).to.equal(4);
});
it('should return 5 for the selector "body section.articles>article:first-child"', function() {
expect(metric.measure('body section.articles>article:first-child')).to.equal(5);
})
it('should return 7 for the selector "body section.articles>article:first-child p::first-line', function() {
expect(metric.measure('body section.articles>article:first-child p::first-line')).to.equal(7);
});
it('should return 3 for the selector "form[name=login] input"', function() {
expect(metric.measure('form[name=login] input')).to.equal(3);
expect(metric.measure('form[name="login"] input')).to.equal(3);
expect(metric.measure("form[name='login'] input")).to.equal(3);
});
it('should return 2 for the selector "input[checked]"', function() {
expect(metric.measure('input[checked]')).to.equal(2);
});
it('should return 2 for the selector "input[value~=Mrs]"', function() {
expect(metric.measure('input[value~=Mrs]')).to.equal(2);
expect(metric.measure('input[value~="Mrs"]')).to.equal(2);
expect(metric.measure("input[value~='Mrs']")).to.equal(2);
});
});
================================================
FILE: test/Parker.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
Parker = require('../lib/Parker.js');
describe('The Parker tool', function() {
it('should throw an exception if stylesheet data not supplied as string, array or multi-param strings', function() {
parker = new Parker([]);
expect(function() {parker.run({})}).to.throw();
expect(function() {parker.run(0)}).to.throw();
expect(function() {parker.run(1, [], {})}).to.throw();
});
it('should not throw an exception if stylesheet data is supplied as string, array or multi-param strings', function() {
parker = new Parker([]);
expect(function() {parker.run('body {background: #FFF;}')});
expect(function() {parker.run(array('body {background: #FFF;}'))});
expect(function() {parker.run('body {background: #FFF;}', 'body {background: #FFF;}')});
});
it('should run metrics on stylesheets', function() {
var mockMetric = {id: 'mock-stylesheet-metric', type: 'stylesheet', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]);
expect(parker.run('body {background: #FFF;}')).to.have.property('mock-stylesheet-metric');
});
it('should return sum values for sum metrics', function() {
var mockMetric = {id: 'mock-stylesheet-metric', type: 'stylesheet', aggregate: 'sum', measure: function() {return 1}},
stylesheet = 'body {background: #FFF;}';
parker = new Parker([mockMetric]);
var report = parker.run([stylesheet, stylesheet, stylesheet]);
expect(report).to.have.property('mock-stylesheet-metric');
expect(report['mock-stylesheet-metric']).to.equal(3);
});
it('should return 0 for sum metrics with no data to report on', function() {
var mockMetric = {id: 'mock-stylesheet-metric', type: 'rule', aggregate: 'sum', measure: function() {return 1}},
stylesheet = '/* comment */';
parker = new Parker([mockMetric]);
var report = parker.run([stylesheet, stylesheet, stylesheet]);
expect(report).to.have.property('mock-stylesheet-metric');
expect(report['mock-stylesheet-metric']).to.equal(0);
});
it('should return mean values for mean metrics', function() {
var mockMetric = {id: 'mock-stylesheet-metric', type: 'stylesheet', aggregate: 'mean', measure: function() {return 1}},
stylesheet = 'body {background: #FFF;}';
parker = new Parker([mockMetric]);
var report = parker.run([stylesheet, stylesheet, stylesheet]);
expect(report).to.have.property('mock-stylesheet-metric');
expect(report['mock-stylesheet-metric']).to.equal(1);
});
it('should return 0 for mean metrics with no data to report on', function () {
var mockMetric = {id: 'mock-stylesheet-metric', type: 'rule', aggregate: 'mean', measure: function() {return 1}},
stylesheet = '/* comment */';
parker = new Parker([mockMetric]);
var report = parker.run([stylesheet]);
expect(report).to.have.property('mock-stylesheet-metric');
expect(report['mock-stylesheet-metric']).to.equal(0);
});
it('should return max values for max metrics', function () {
var mockIntMetric = {id: 'mock-int-metric', type: 'stylesheet', aggregate: 'max', measure: function(stylesheet) {return stylesheet.length;}},
parker = new Parker([mockIntMetric]),
report = parker.run(['body {background: #FFF;}', 'body {background: #FFFFFF;}']);
expect(report).to.have.property('mock-int-metric');
expect(report['mock-int-metric']).to.equal(27);
});
it('should return 0 for max metrics with no data to report on', function () {
var mockIntMetric = {id: 'mock-int-metric', type: 'rule', aggregate: 'max', measure: function(stylesheet) {return stylesheet.length;}},
parker = new Parker([mockIntMetric]),
report = parker.run(['/* comment */']);
expect(report).to.have.property('mock-int-metric');
expect(report['mock-int-metric']).to.equal(0);
});
it('should return max values determined by an iterator function if one is present', function() {
var mockStringMetric = {id: 'mock-string-metric', type: 'stylesheet', aggregate: 'max', measure: function(stylesheet) {return stylesheet;}, iterator: function(string) {return string.length}},
parker = new Parker([mockStringMetric]),
report = parker.run(['body {background: #FFF;}', 'body {background: #FFFFFF;}']);
expect(report).to.have.property('mock-string-metric');
expect(report['mock-string-metric']).to.equal('body {background: #FFFFFF;}');
});
it('should return list values for list metrics', function () {
var mockSingleMetric = {id: 'mock-single-list-item-metric', type: 'stylesheet', aggregate: 'list', measure: function(stylesheet) {return stylesheet}},
mockMultipleMetric = {id: 'mock-multiple-list-item-metric', type: 'stylesheet', aggregate: 'list', measure: function(stylesheet) {return ['a', 'b']}},
parker = new Parker([mockSingleMetric, mockMultipleMetric]),
report = parker.run(['body {background: #FFF;}', 'body {background: #FFF;}']);
expect(report).to.have.property('mock-single-list-item-metric');
expect(report['mock-single-list-item-metric']).to.be.an('array');
expect(report['mock-single-list-item-metric']).to.have.length(2);
expect(report['mock-single-list-item-metric'][0]).to.equal('body {background: #FFF;}');
expect(report['mock-single-list-item-metric'][1]).to.equal('body {background: #FFF;}');
expect(report['mock-multiple-list-item-metric']).to.be.an('array');
expect(report['mock-multiple-list-item-metric']).to.have.length(4);
expect(report['mock-multiple-list-item-metric'][0]).to.equal('a');
expect(report['mock-multiple-list-item-metric'][1]).to.equal('b');
expect(report['mock-multiple-list-item-metric'][0]).to.equal('a');
expect(report['mock-multiple-list-item-metric'][1]).to.equal('b');
});
it('should return list values filtered by a filter function if one is present', function() {
var mockMetric = {id: 'mock-list-metric', type: 'stylesheet', aggregate: 'list', measure: function(stylesheet) {return stylesheet}, filter: function(value, index, self) {return self.indexOf(value) === index;}},
parker = new Parker([mockMetric]),
report = parker.run(['body {background: #FFF;}', 'body {background: #FFF;}']);
expect(report).to.have.property('mock-list-metric');
expect(report['mock-list-metric']).to.be.an('array');
expect(report['mock-list-metric']).to.have.length(1);
expect(report['mock-list-metric'][0]).to.equal('body {background: #FFF;}');
});
it('should return length values for length metrics', function () {
var mockMetric = {id: 'mock-length-metric', type: 'stylesheet', aggregate: 'length', measure: function(stylesheet) {return stylesheet}},
parker = new Parker([mockMetric]);
report = parker.run(['body {background: #FFF;}', 'body {background: #FFF;}', '']);
expect(report).to.have.property('mock-length-metric');
expect(report['mock-length-metric']).to.equal(2);
});
it('should run metrics on rules', function() {
var mockMetric = {id: 'mock-rule-metric', type: 'rule', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]),
report = parker.run('body {background: #FFF;} h1 {font-weight: bold;}');
expect(report).to.have.property('mock-rule-metric');
expect(report['mock-rule-metric']).to.equal(2);
});
it('should run metrics on media queries', function () {
var mockMetric = {id: 'mock-media-query-metric', type: 'mediaquery', aggregate: 'list', measure: function(query) {return query;}};
parker = new Parker([mockMetric]),
report = parker.run('@media handheld, (max-width: 700px) { body { margin: 100px; }} @import url(css/styles.css); body { margin: 0; }');
expect(report).to.have.property('mock-media-query-metric');
expect(report['mock-media-query-metric'][0]).to.equal('handheld');
expect(report['mock-media-query-metric'][1]).to.equal('(max-width: 700px)');
});
it('should run metrics on rules inside media query blocks', function () {
var mockMetric = {id: 'mock-media-query-metric', type: 'rule', aggregate: 'list', measure: function(rule) {return rule;}},
parker = new Parker([mockMetric]),
report = parker.run('@media print {a {color: #000;} header {display: none;}}');
expect(report).to.have.property('mock-media-query-metric');
expect(report['mock-media-query-metric'][0]).to.equal('a {color: #000;}');
expect(report['mock-media-query-metric'][1]).to.equal('header {display: none;}');
});
it('should run metrics on selectors', function() {
var mockMetric = {id: 'mock-selector-metric', type: 'selector', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]);
report = parker.run('body section {background: #FFF;} h1 {font-weight: bold;}');
expect(report).to.have.property('mock-selector-metric');
expect(report['mock-selector-metric']).to.equal(2);
});
it('should run metrics on identifiers', function() {
var mockMetric = {id: 'mock-identifier-metric', type: 'identifier', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]);
report = parker.run("body section :first-child {background: #FFF;} form#registration-form > input.username {font-weight: bold;}");
expect(report).to.have.property('mock-identifier-metric');
expect(report['mock-identifier-metric']).to.equal(7);
});
it('should run metrics on declarations', function() {
var mockMetric = {id: 'mock-declaration-metric', type: 'declaration', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]);
report = parker.run("body {margin: 0; padding: 0} a {color: #00f} h1 {font-weight: bold; color: #000;}");
expect(report).to.have.property('mock-declaration-metric');
expect(report['mock-declaration-metric']).to.equal(5);
});
it('should run metrics on properties', function() {
var mockMetric = {id: 'mock-property-metric', type: 'property', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]);
report = parker.run("body {margin: 0; padding: 0} a {color: #00f} h1 {font-weight: bold; color: #000;}");
expect(report).to.have.property('mock-property-metric');
expect(report['mock-property-metric']).to.equal(5);
});
it('should run metrics on values', function() {
var mockMetric = {id: 'mock-value-metric', type: 'value', aggregate: 'sum', measure: function() {return 1}};
parker = new Parker([mockMetric]);
report = parker.run("body {margin: 0; padding: 0} a {color: #00f} h1 {font-weight: bold; color: #000;}");
expect(report).to.have.property('mock-value-metric');
expect(report['mock-value-metric']).to.equal(5);
});
it('should return results for metrics measuring optional elements when those elements are not found', function () {
var mockMetric = {id: 'mock-media-query-metric', type: 'mediaquery', aggregate: 'length', measure: function(query) {return query;}};
parker = new Parker([mockMetric]),
report = parker.run('body { margin: 0; }');
expect(report).to.have.property('mock-media-query-metric');
expect(report['mock-media-query-metric']).to.equal(0);
});
});
================================================
FILE: test/TopSelectorSpecificity.js
================================================
var expect = require('chai').expect,
metric = require('../metrics/TopSelectorSpecificity.js');
describe('The top-selector-specificity metric', function () {
it('should return a specificity of "1" for the selector "table"', function () {
expect(metric.measure("table")).to.equal(1);
});
it('should return a specificity of "1" for the selector "::first-line"', function () {
expect(metric.measure('::before')).to.equal(1);
});
it('should return a specificity of "10" for the selector ".class"', function () {
expect(metric.measure('.class')).to.equal(10);
});
it('should return a specificity of "10" for the selector "[href="/"]"', function () {
expect(metric.measure('[href="/"]')).to.equal(10);
});
it('should return a specificity of "10" for the selector ":first"', function () {
expect(metric.measure(':first')).to.equal(10);
});
it('should return a specificity of "100" for the selector "#main"', function () {
expect(metric.measure('#main')).to.equal(100);
});
it('should return a specificity of "0" for the selector "*"', function () {
expect(metric.measure('*')).to.equal(0);
});
it('should count only the specificity of the child selector of a :not identifier', function () {
expect(metric.measure(':not(body)')).to.equal(1);
expect(metric.measure(':not(.sidebar)')).to.equal(10);
expect(metric.measure(':not(h1#main)')).to.equal(101);
});
it('should ignore identifier tokens inside attribute selectors', function () {
expect(metric.measure('[href="#main"]')).to.equal(10);
});
});
================================================
FILE: test/TotalIdSelectors.js
================================================
/*! Parker v0.0.0 - MIT license */
var expect = require('chai').expect,
metric = require('../metrics/TotalIdSelectors.js');
describe('The total-id-selectors metric', function () {
it('should provide a string identifier for the metric', function() {
expect(metric.id).to.be.a('string');
});
it('should provide a metric type', function() {
expect(metric.aggregate).to.match(/sum|mean/g);
});
it('should return 0 for an empty string', function () {
expect(metric.measure('')).to.equal(0);
});
it('should return 1 for the selector "#test"', function() {
expect(metric.measure('#test')).to.equal(1);
});
it('should return 1 for the selector "foo#test"', function() {
expect(metric.measure('foo#test')).to.equal(1);
});
it('should return 1 for the selector "foo #test"', function() {
expect(metric.measure('foo #test')).to.equal(1);
});
it('should return 0 for the selector "[href="#foo"]"', function () {
expect(metric.measure('[href="#foo"]')).to.equal(0);
});
it('should return 1 for the selector "[href="#foo"] #foo"', function () {
expect(metric.measure('[href="#foo"] #foo')).to.equal(1);
});
it('should return 2 for the selector "#foo #bar"', function () {
expect(metric.measure('#foo #bar')).to.equal(2);
});
});
================================================
FILE: test/ZIndexes.js
================================================
var expect = require('chai').expect,
metric = require('../metrics/ZIndexes.js');
describe("The Z-Indexes metric", function() {
it('should return 1 for "z-index: 1"', function () {
expect(metric.measure('z-index: 1')).to.equal('1');
});
});
gitextract_ipjvopnp/
├── .gitignore
├── .jshintrc
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── docs/
│ ├── contributing/
│ │ └── readme.md
│ ├── installation/
│ │ └── readme.md
│ ├── metrics/
│ │ └── readme.md
│ ├── readme.md
│ ├── usage/
│ │ └── readme.md
│ └── usage-package/
│ └── readme.md
├── lib/
│ ├── ArraySelectorSpecificity.js
│ ├── ClassicalSelectorSpecificity.js
│ ├── CliController.js
│ ├── CliFormatter.js
│ ├── CssDeclaration.js
│ ├── CssMediaQuery.js
│ ├── CssRule.js
│ ├── CssSelector.js
│ ├── CssStylesheet.js
│ ├── Formatters.js
│ ├── Info.js
│ ├── Parker.js
│ └── PreciseSelectorSpecificity.js
├── metrics/
│ ├── All.js
│ ├── DeclarationsPerRule.js
│ ├── IdentifiersPerSelector.js
│ ├── MediaQueries.js
│ ├── PreciseSpecificityPerSelector.js
│ ├── PreciseTopSelectorSpecificity.js
│ ├── SelectorsPerRule.js
│ ├── SpecificityPerSelector.js
│ ├── StringTopSelectorSpecificity.js
│ ├── TopSelectorSpecificity.js
│ ├── TopSelectorSpecificitySelector.js
│ ├── TotalDeclarations.js
│ ├── TotalIdSelectors.js
│ ├── TotalIdentifiers.js
│ ├── TotalImportantKeywords.js
│ ├── TotalMediaQueries.js
│ ├── TotalRules.js
│ ├── TotalSelectors.js
│ ├── TotalStylesheetSize.js
│ ├── TotalStylesheets.js
│ ├── TotalUniqueColours.js
│ ├── UniqueColours.js
│ └── ZIndexes.js
├── package.json
├── parker.js
└── test/
├── CliController.js
├── CssDeclaration.js
├── CssMediaQuery.js
├── CssRule.js
├── CssSelector.js
├── CssStylesheet.js
├── DeclarationsPerRule.js
├── IdentifiersPerSelector.js
├── Parker.js
├── TopSelectorSpecificity.js
├── TotalIdSelectors.js
└── ZIndexes.js
SYMBOL INDEX (13 symbols across 10 files)
FILE: lib/CliController.js
function CliController (line 8) | function CliController() {
FILE: lib/CliFormatter.js
function CliFormatter (line 7) | function CliFormatter() {
FILE: lib/CssDeclaration.js
function CssDeclaration (line 5) | function CssDeclaration(raw) {
FILE: lib/CssMediaQuery.js
function CssMediaQuery (line 5) | function CssMediaQuery(raw) {
FILE: lib/CssRule.js
function CssRule (line 7) | function CssRule(raw) {
FILE: lib/CssSelector.js
function CssSelector (line 8) | function CssSelector(raw) {
function isDelimiter (line 47) | function isDelimiter(character) {
FILE: lib/CssStylesheet.js
function CssStylesheet (line 7) | function CssStylesheet(raw) {
FILE: lib/Parker.js
function Parker (line 14) | function Parker(metrics) {
FILE: metrics/StringTopSelectorSpecificity.js
function toString (line 27) | function toString(arr) {
function fromString (line 33) | function fromString(str) {
function mostSpecific (line 39) | function mostSpecific(arr1, arr2) {
FILE: metrics/TotalStylesheetSize.js
function byteCount (line 16) | function byteCount(s) {
Condensed preview — 62 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (106K chars).
[
{
"path": ".gitignore",
"chars": 13,
"preview": "node_modules\n"
},
{
"path": ".jshintrc",
"chars": 349,
"preview": "{\n \"browser\": true,\n \"node\": true,\n \"esnext\": true,\n \"bitwise\": false,\n \"curly\": false,\n \"eqeqeq\": tru"
},
{
"path": ".travis.yml",
"chars": 51,
"preview": "language: node_js\nnode_js:\n - \"0.10\"\n - \"0.12\"\n"
},
{
"path": "CHANGELOG.md",
"chars": 8,
"preview": "== HEAD\n"
},
{
"path": "LICENSE.md",
"chars": 1072,
"preview": "This software is released under the MIT license:\n\nPermission is hereby granted, free of charge, to any person obtaining "
},
{
"path": "README.md",
"chars": 2069,
"preview": "# Parker\n\nParker is a stylesheet analysis tool. It runs metrics on your stylesheets and will report on their complexity."
},
{
"path": "docs/contributing/readme.md",
"chars": 881,
"preview": "# Contributing\nPull requests, issues, new unit tests, code reviews and good advice are all things that would make a diff"
},
{
"path": "docs/installation/readme.md",
"chars": 782,
"preview": "# Installation\nParker requires Node.JS and npm to be installed before it can be installed itself.\n\n<a name=\"install-node"
},
{
"path": "docs/metrics/readme.md",
"chars": 13675,
"preview": "# Metrics\nParker has a suite of metrics that are useful for measuring stylesheets. What follows is a list of all the met"
},
{
"path": "docs/readme.md",
"chars": 723,
"preview": "# Parker\nParker is a stylesheet analysis tool. It runs metrics on your stylesheets and will report on their complexity.\n"
},
{
"path": "docs/usage/readme.md",
"chars": 1016,
"preview": "# Usage\nParker is a command-line tool. Switches and options are used to control how it works. By default Parker runs wit"
},
{
"path": "docs/usage-package/readme.md",
"chars": 1586,
"preview": "# Using Parker as a Package\n\nParker can be used as a package in scripts. It can be installed using npm like so:\n\n\tnpm in"
},
{
"path": "lib/ArraySelectorSpecificity.js",
"chars": 2565,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar CssSelector = require('../lib/CssSelector');\nvar _ = require('lod"
},
{
"path": "lib/ClassicalSelectorSpecificity.js",
"chars": 2512,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar CssSelector = require('../lib/CssSelector');\nvar _ = require('lod"
},
{
"path": "lib/CliController.js",
"chars": 903,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar util = require('util'),\n events = require('events');\n\nfunction"
},
{
"path": "lib/CliFormatter.js",
"chars": 365,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nfunction CliFormatter() {\n\n}\n\nCliFormatte"
},
{
"path": "lib/CssDeclaration.js",
"chars": 465,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nfunction CssDeclaration(raw) {\n\n this.raw = raw;\n}\n\nCssDeclaration"
},
{
"path": "lib/CssMediaQuery.js",
"chars": 931,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nfunction CssMediaQuery(raw) {\n\tthis.raw = raw;\n}\n\nCssMediaQuery.proto"
},
{
"path": "lib/CssRule.js",
"chars": 1268,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nfunction CssRule(raw) {\n this.raw = ra"
},
{
"path": "lib/CssSelector.js",
"chars": 1322,
"preview": "/*! Parker v0.1.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash'),\n DELIMITERS = ['.', '#', '>', '[', ' ',"
},
{
"path": "lib/CssStylesheet.js",
"chars": 2275,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nfunction CssStylesheet(raw) {\n this.ra"
},
{
"path": "lib/Formatters.js",
"chars": 945,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash'),\n clc = require('cli-color');\n\n\n// forma"
},
{
"path": "lib/Info.js",
"chars": 1406,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar pkg = require('../package.json');\n\nmodule.exports = {\n version"
},
{
"path": "lib/Parker.js",
"chars": 5967,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash'),\n CssStylesheet = require('./CssStyleshe"
},
{
"path": "lib/PreciseSelectorSpecificity.js",
"chars": 2586,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar CssSelector = require('../lib/CssSelector');\nvar _ = require('lod"
},
{
"path": "metrics/All.js",
"chars": 1166,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nmodule.exports = [\n // Stylesheet Totals\n require('./TotalStyle"
},
{
"path": "metrics/DeclarationsPerRule.js",
"chars": 356,
"preview": "'use strict';\n\nvar CssRule = require('../lib/CssRule');\n\nvar _ = require('lodash');\nmodule.exports = {\n id: 'declarat"
},
{
"path": "metrics/IdentifiersPerSelector.js",
"chars": 787,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'identifiers-p"
},
{
"path": "metrics/MediaQueries.js",
"chars": 376,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'media-queries"
},
{
"path": "metrics/PreciseSpecificityPerSelector.js",
"chars": 404,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\nvar CssSelector = require('../lib/CssSelec"
},
{
"path": "metrics/PreciseTopSelectorSpecificity.js",
"chars": 403,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\nvar CssSelector = require('../lib/CssSelec"
},
{
"path": "metrics/SelectorsPerRule.js",
"chars": 690,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nmodule.exports = {\n id: 'selectors-per-rule',\n name: 'Selectors"
},
{
"path": "metrics/SpecificityPerSelector.js",
"chars": 400,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\nvar CssSelector = require('../lib/CssSelec"
},
{
"path": "metrics/StringTopSelectorSpecificity.js",
"chars": 1219,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\nvar CssSelector = require('../lib/CssSelec"
},
{
"path": "metrics/TopSelectorSpecificity.js",
"chars": 3124,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\nvar CssSelector = require('../lib/CssSelec"
},
{
"path": "metrics/TopSelectorSpecificitySelector.js",
"chars": 2340,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\nvar CssSelector = require('../lib/CssSelec"
},
{
"path": "metrics/TotalDeclarations.js",
"chars": 265,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nmodule.exports = {\n id: 'total-declarations',\n name: 'Total Dec"
},
{
"path": "metrics/TotalIdSelectors.js",
"chars": 534,
"preview": "\n/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'total-id-sel"
},
{
"path": "metrics/TotalIdentifiers.js",
"chars": 289,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'total-identif"
},
{
"path": "metrics/TotalImportantKeywords.js",
"chars": 356,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'total-importa"
},
{
"path": "metrics/TotalMediaQueries.js",
"chars": 392,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'total-media-q"
},
{
"path": "metrics/TotalRules.js",
"chars": 237,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nmodule.exports = {\n id: 'total-rules',\n name: 'Total Rules',\n "
},
{
"path": "metrics/TotalSelectors.js",
"chars": 281,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'total-selecto"
},
{
"path": "metrics/TotalStylesheetSize.js",
"chars": 367,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nmodule.exports = {\n id: 'total-stylesheet-size',\n name: 'Total "
},
{
"path": "metrics/TotalStylesheets.js",
"chars": 261,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nmodule.exports = {\n id: 'total-stylesheets',\n name: 'Total Styl"
},
{
"path": "metrics/TotalUniqueColours.js",
"chars": 959,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'total-unique-"
},
{
"path": "metrics/UniqueColours.js",
"chars": 943,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar _ = require('lodash');\n\nmodule.exports = {\n id: 'unique-colour"
},
{
"path": "metrics/ZIndexes.js",
"chars": 553,
"preview": "/*! Parker v0.0.0 - MIT license */\n\n'use strict';\n\nvar CssDeclaration = require('../lib/CssDeclaration');\n\nmodule.export"
},
{
"path": "package.json",
"chars": 791,
"preview": "{\n \"name\": \"parker\",\n \"description\": \"Stylesheet analysis tool for CSS\",\n \"keywords\": [\n \"css\",\n \"stylesheet\",\n"
},
{
"path": "parker.js",
"chars": 3045,
"preview": "#!/usr/bin/env node\n\n/*! csstool v0.0.0 - MIT license */\n\n'use strict';\n\n/**\n * Module dependencies\n */\n\nvar _ = require"
},
{
"path": "test/CliController.js",
"chars": 3645,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar chai = require('chai'),\n expect = require('chai').expect,\n CliController ="
},
{
"path": "test/CssDeclaration.js",
"chars": 490,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n CssDeclaration = require('../lib/CssDeclara"
},
{
"path": "test/CssMediaQuery.js",
"chars": 1531,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n CssMediaQuery = require('../lib/CssMediaQue"
},
{
"path": "test/CssRule.js",
"chars": 1212,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n CssRule = require('../lib/CssRule.js');\n\nde"
},
{
"path": "test/CssSelector.js",
"chars": 2671,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n CssSelector = require('../lib/CssSelector.j"
},
{
"path": "test/CssStylesheet.js",
"chars": 3938,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n CssStylesheet = require('../lib/CssStyleshe"
},
{
"path": "test/DeclarationsPerRule.js",
"chars": 1355,
"preview": "\n/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n metric = require('../metrics/DeclarationsP"
},
{
"path": "test/IdentifiersPerSelector.js",
"chars": 2313,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n metric = require('../metrics/IdentifiersPer"
},
{
"path": "test/Parker.js",
"chars": 11964,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n Parker = require('../lib/Parker.js');\n\ndesc"
},
{
"path": "test/TopSelectorSpecificity.js",
"chars": 1662,
"preview": "var expect = require('chai').expect,\n metric = require('../metrics/TopSelectorSpecificity.js');\n\ndescribe('The top-se"
},
{
"path": "test/TotalIdSelectors.js",
"chars": 1262,
"preview": "/*! Parker v0.0.0 - MIT license */\n\nvar expect = require('chai').expect,\n\tmetric = require('../metrics/TotalIdSelectors."
},
{
"path": "test/ZIndexes.js",
"chars": 261,
"preview": "var expect = require('chai').expect,\n metric = require('../metrics/ZIndexes.js');\n\ndescribe(\"The Z-Indexes metric\", f"
}
]
About this extraction
This page contains the full source code of the katiefenn/parker GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 62 files (96.3 KB), approximately 24.6k tokens, and a symbol index with 13 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.