node_modules

This commit is contained in:
saeid
2019-07-15 13:07:31 +04:30
parent d3735c6d30
commit ce1a3ebf9c
35713 changed files with 3639219 additions and 1 deletions
+274
View File
@@ -0,0 +1,274 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="2.1.1"></a>
## [2.1.1](https://github.com/webpack-contrib/css-loader/compare/v2.1.0...v2.1.1) (2019-03-07)
### Bug Fixes
* do not break selector with escaping ([#896](https://github.com/webpack-contrib/css-loader/issues/896)) ([0ba8c66](https://github.com/webpack-contrib/css-loader/commit/0ba8c66))
* source map generation when `sourceRoot` is present ([#901](https://github.com/webpack-contrib/css-loader/issues/901)) ([e9ce745](https://github.com/webpack-contrib/css-loader/commit/e9ce745))
* sourcemap generating when previous loader pass sourcemap as string ([#905](https://github.com/webpack-contrib/css-loader/issues/905)) ([3797e4d](https://github.com/webpack-contrib/css-loader/commit/3797e4d))
<a name="2.1.0"></a>
# [2.1.0](https://github.com/webpack-contrib/css-loader/compare/v2.0.2...v2.1.0) (2018-12-25)
### Features
* support `image-set` without `url` ([#879](https://github.com/webpack-contrib/css-loader/issues/879)) ([21884e2](https://github.com/webpack-contrib/css-loader/commit/21884e2))
<a name="2.0.2"></a>
## [2.0.2](https://github.com/webpack-contrib/css-loader/compare/v2.0.1...v2.0.2) (2018-12-21)
### Bug Fixes
* inappropriate modification of animation keywords ([#876](https://github.com/webpack-contrib/css-loader/issues/876)) ([dfb2f8e](https://github.com/webpack-contrib/css-loader/commit/dfb2f8e))
<a name="2.0.1"></a>
# [2.0.1](https://github.com/webpack-contrib/css-loader/compare/v2.0.0...v2.0.1) (2018-12-14)
### Bug Fixes
* safe checking if params are present for at rule ([#871](https://github.com/webpack-contrib/css-loader/issues/871)) ([a88fed1](https://github.com/webpack-contrib/css-loader/commit/a88fed1))
* `getLocalIdent` now accepts `false` value ([#865](https://github.com/webpack-contrib/css-loader/issues/865)) ([1825e8a](https://github.com/webpack-contrib/css-loader/commit/1825e8a))
<a name="2.0.0"></a>
# [2.0.0](https://github.com/webpack-contrib/css-loader/compare/v1.0.1...v2.0.0) (2018-12-07)
### Bug Fixes
* broken unucode characters ([#850](https://github.com/webpack-contrib/css-loader/issues/850)) ([f599c70](https://github.com/webpack-contrib/css-loader/commit/f599c70))
* correctly processing `urls()` with `?#hash` ([#803](https://github.com/webpack-contrib/css-loader/issues/803)) ([417d105](https://github.com/webpack-contrib/css-loader/commit/417d105))
* don't break loader on invalid or not exists url or import token ([#827](https://github.com/webpack-contrib/css-loader/issues/827)) ([9e52d26](https://github.com/webpack-contrib/css-loader/commit/9e52d26))
* don't duplicate import with same media in different case ([#819](https://github.com/webpack-contrib/css-loader/issues/819)) ([9f66e33](https://github.com/webpack-contrib/css-loader/commit/9f66e33))
* emit warnings on broken `import` at-rules ([#806](https://github.com/webpack-contrib/css-loader/issues/806)) ([4bdf08b](https://github.com/webpack-contrib/css-loader/commit/4bdf08b))
* handle uppercase `URL` in `import` at-rules ([#818](https://github.com/webpack-contrib/css-loader/issues/818)) ([3ebdcd5](https://github.com/webpack-contrib/css-loader/commit/3ebdcd5))
* inconsistent generate class names for css modules on difference os ([#812](https://github.com/webpack-contrib/css-loader/issues/812)) ([0bdf9b7](https://github.com/webpack-contrib/css-loader/commit/0bdf9b7))
* reduce number of `require` for `urls()` ([#854](https://github.com/webpack-contrib/css-loader/issues/854)) ([3338656](https://github.com/webpack-contrib/css-loader/commit/3338656))
* support deduplication of string module ids (optimization.namedModules) ([#789](https://github.com/webpack-contrib/css-loader/issues/789)) ([e3bb83a](https://github.com/webpack-contrib/css-loader/commit/e3bb83a))
* support module resolution in `composes` ([#845](https://github.com/webpack-contrib/css-loader/issues/845)) ([453248f](https://github.com/webpack-contrib/css-loader/commit/453248f))
* same `urls()` resolving logic for `modules` (`local` and `global`) and without modules ([#843](https://github.com/webpack-contrib/css-loader/issues/843)) ([fdcf687](https://github.com/webpack-contrib/css-loader/commit/fdcf687))
### Features
* allow to disable css modules and **disable their by default** ([#842](https://github.com/webpack-contrib/css-loader/issues/842)) ([889dc7f](https://github.com/webpack-contrib/css-loader/commit/889dc7f))
* disable `import` option doesn't affect on `composes` ([#822](https://github.com/webpack-contrib/css-loader/issues/822)) ([f9aa73c](https://github.com/webpack-contrib/css-loader/commit/f9aa73c))
* allow to filter `urls` ([#856](https://github.com/webpack-contrib/css-loader/issues/856)) ([5e702e7](https://github.com/webpack-contrib/css-loader/commit/5e702e7))
* allow to filter `import` at-rules ([#857](https://github.com/webpack-contrib/css-loader/issues/857)) ([5e6034c](https://github.com/webpack-contrib/css-loader/commit/5e6034c))
* emit warning on invalid `urls()` ([#832](https://github.com/webpack-contrib/css-loader/issues/832)) ([da95db8](https://github.com/webpack-contrib/css-loader/commit/da95db8))
* added `exportOnlyLocals` option ([#824](https://github.com/webpack-contrib/css-loader/issues/824)) ([e9327c0](https://github.com/webpack-contrib/css-loader/commit/e9327c0))
* reuse `postcss` ast from other loaders (i.e `postcss-loader`) ([#840](https://github.com/webpack-contrib/css-loader/issues/840)) ([1dad1fb](https://github.com/webpack-contrib/css-loader/commit/1dad1fb))
* schema options ([b97d997](https://github.com/webpack-contrib/css-loader/commit/b97d997))
### BREAKING CHANGES
* resolving logic for `url()` and `import` at-rules works the same everywhere, it does not matter whether css modules are enabled (with `global` and `local` module) or not. Examples - `url('image.png')` as `require('./image.png')`, `url('./image.png')` as `require('./image.png')`, `url('~module/image.png')` as `require('module/image.png')`.
* by default css modules are disabled (now `modules: false` disable all css modules features), you can return old behaviour change this on `modules: 'global'`
* `css-loader/locals` was dropped in favor `exportOnlyLocals` option
* `import` option only affect on `import` at-rules and doesn't affect on `composes` declarations
* invalid `@import` at rules now emit warnings
* use `postcss@7`
<a name="1.0.1"></a>
## [1.0.1](https://github.com/webpack-contrib/css-loader/compare/v1.0.0...v1.0.1) (2018-10-29)
### Bug Fixes
* **loader:** trim unquoted import urls ([#783](https://github.com/webpack-contrib/css-loader/issues/783)) ([21fcddf](https://github.com/webpack-contrib/css-loader/commit/21fcddf))
<a name="1.0.0"></a>
# [1.0.0](https://github.com/webpack-contrib/css-loader/compare/v0.28.11...v1.0.0) (2018-07-06)
### BREAKING CHANGES
* remove `minimize` option, use [`postcss-loader`](https://github.com/postcss/postcss-loader) with [`cssnano`](https://github.com/cssnano/cssnano) or use [`optimize-cssnano-plugin`](https://github.com/intervolga/optimize-cssnano-plugin) plugin
* remove `module` option, use `modules` option instead
* remove `camelcase` option, use `camelCase` option instead
* remove `root` option, use [`postcss-loader`](https://github.com/postcss/postcss-loader) with [`postcss-url`](https://github.com/postcss/postcss-url) plugin
* remove `alias` option, use [`resolve.alias`](https://webpack.js.org/configuration/resolve/) feature or use [`postcss-loader`](https://github.com/postcss/postcss-loader) with [`postcss-url`](https://github.com/postcss/postcss-url) plugin
* update `postcss` to `6` version
* minimum require `nodejs` version is `6.9`
* minimum require `webpack` version is `4`
<a name="0.28.11"></a>
## [0.28.11](https://github.com/webpack-contrib/css-loader/compare/v0.28.10...v0.28.11) (2018-03-16)
### Bug Fixes
* **lib/processCss:** don't check `mode` for `url` handling (`options.modules`) ([#698](https://github.com/webpack-contrib/css-loader/issues/698)) ([c788450](https://github.com/webpack-contrib/css-loader/commit/c788450))
<a name="0.28.10"></a>
## [0.28.10](https://github.com/webpack-contrib/css-loader/compare/v0.28.9...v0.28.10) (2018-02-22)
### Bug Fixes
* **getLocalIdent:** add `rootContext` support (`webpack >= v4.0.0`) ([#681](https://github.com/webpack-contrib/css-loader/issues/681)) ([9f876d2](https://github.com/webpack-contrib/css-loader/commit/9f876d2))
<a name="0.28.9"></a>
## [0.28.9](https://github.com/webpack-contrib/css-loader/compare/v0.28.8...v0.28.9) (2018-01-17)
### Bug Fixes
* ignore invalid URLs (`url()`) ([#663](https://github.com/webpack-contrib/css-loader/issues/663)) ([d1d8221](https://github.com/webpack-contrib/css-loader/commit/d1d8221))
<a name="0.28.8"></a>
## [0.28.8](https://github.com/webpack-contrib/css-loader/compare/v0.28.7...v0.28.8) (2018-01-05)
### Bug Fixes
* **loader:** correctly check if source map is `undefined` ([#641](https://github.com/webpack-contrib/css-loader/issues/641)) ([0dccfa9](https://github.com/webpack-contrib/css-loader/commit/0dccfa9))
* proper URL escaping and wrapping (`url()`) ([#627](https://github.com/webpack-contrib/css-loader/issues/627)) ([8897d44](https://github.com/webpack-contrib/css-loader/commit/8897d44))
<a name="0.28.7"></a>
## [0.28.7](https://github.com/webpack/css-loader/compare/v0.28.6...v0.28.7) (2017-08-30)
### Bug Fixes
* pass resolver to `localsLoader` (`options.alias`) ([#601](https://github.com/webpack/css-loader/issues/601)) ([8f1b57c](https://github.com/webpack/css-loader/commit/8f1b57c))
<a name="0.28.6"></a>
## [0.28.6](https://github.com/webpack/css-loader/compare/v0.28.5...v0.28.6) (2017-08-30)
### Bug Fixes
* add support for aliases starting with `/` (`options.alias`) ([#597](https://github.com/webpack/css-loader/issues/597)) ([63567f2](https://github.com/webpack/css-loader/commit/63567f2))
<a name="0.28.5"></a>
## [0.28.5](https://github.com/webpack/css-loader/compare/v0.28.4...v0.28.5) (2017-08-17)
### Bug Fixes
* match mutliple dashes (`options.camelCase`) ([#556](https://github.com/webpack/css-loader/issues/556)) ([1fee601](https://github.com/webpack/css-loader/commit/1fee601))
* stricter `[@import](https://github.com/import)` tolerance ([#593](https://github.com/webpack/css-loader/issues/593)) ([2e4ec09](https://github.com/webpack/css-loader/commit/2e4ec09))
<a name="0.28.4"></a>
## [0.28.4](https://github.com/webpack/css-loader/compare/v0.28.3...v0.28.4) (2017-05-30)
### Bug Fixes
* preserve leading underscore in class names ([#543](https://github.com/webpack/css-loader/issues/543)) ([f6673c8](https://github.com/webpack/css-loader/commit/f6673c8))
<a name="0.28.3"></a>
## [0.28.3](https://github.com/webpack/css-loader/compare/v0.28.2...v0.28.3) (2017-05-25)
### Bug Fixes
* correct plugin order for CSS Modules ([#534](https://github.com/webpack/css-loader/issues/534)) ([b90f492](https://github.com/webpack/css-loader/commit/b90f492))
<a name="0.28.2"></a>
## [0.28.2](https://github.com/webpack/css-loader/compare/v0.28.1...v0.28.2) (2017-05-22)
### Bug Fixes
* source maps path on `windows` ([#532](https://github.com/webpack/css-loader/issues/532)) ([c3d0d91](https://github.com/webpack/css-loader/commit/c3d0d91))
<a name="0.28.1"></a>
## [0.28.1](https://github.com/webpack/css-loader/compare/v0.28.0...v0.28.1) (2017-05-02)
### Bug Fixes
* allow to specify a full hostname as a root URL ([#521](https://github.com/webpack/css-loader/issues/521)) ([06d27a1](https://github.com/webpack/css-loader/commit/06d27a1))
* case insensitivity of [@import](https://github.com/import) ([#514](https://github.com/webpack/css-loader/issues/514)) ([de4356b](https://github.com/webpack/css-loader/commit/de4356b))
* don't handle empty [@import](https://github.com/import) and url() ([#513](https://github.com/webpack/css-loader/issues/513)) ([868fc94](https://github.com/webpack/css-loader/commit/868fc94))
* imported variables are replaced in exports if followed by a comma ([#504](https://github.com/webpack/css-loader/issues/504)) ([956bad7](https://github.com/webpack/css-loader/commit/956bad7))
* loader now correctly handles `url` with space(s) ([#495](https://github.com/webpack/css-loader/issues/495)) ([534ea55](https://github.com/webpack/css-loader/commit/534ea55))
* url with a trailing space is now handled correctly ([#494](https://github.com/webpack/css-loader/issues/494)) ([e1ec4f2](https://github.com/webpack/css-loader/commit/e1ec4f2))
* use `btoa` instead `Buffer` ([#501](https://github.com/webpack/css-loader/issues/501)) ([fbb0714](https://github.com/webpack/css-loader/commit/fbb0714))
### Performance Improvements
* generate source maps only when explicitly set ([#478](https://github.com/webpack/css-loader/issues/478)) ([b8f5c8f](https://github.com/webpack/css-loader/commit/b8f5c8f))
<a name="0.28.0"></a>
# [0.28.0](https://github.com/webpack/css-loader/compare/v0.27.3...v0.28.0) (2017-03-30)
### Features
* add alias feature to rewrite URLs ([#274](https://github.com/webpack/css-loader/issues/274)) ([c8db489](https://github.com/webpack/css-loader/commit/c8db489))
<a name="0.27.3"></a>
## [0.27.3](https://github.com/webpack/css-loader/compare/v0.27.2...v0.27.3) (2017-03-13)
<a name="0.27.2"></a>
# [0.27.2](https://github.com/webpack/css-loader/compare/v0.27.1...v0.27.2) (2017-03-12)
<a name="0.27.1"></a>
# [0.27.1](https://github.com/webpack/css-loader/compare/v0.27.0...v0.27.1) (2017-03-10)
<a name="0.27.0"></a>
# [0.27.0](https://github.com/webpack/css-loader/compare/v0.26.2...v0.27.0) (2017-03-10)
### Bug Fixes
* **sourcemaps:** use abs paths & remove sourceRoot ([c769ac3](https://github.com/webpack/css-loader/commit/c769ac3))
* `minimizeOptions` should be `query.minimize`! ([16c0858](https://github.com/webpack/css-loader/commit/16c0858))
* do not export duplicate keys ([#420](https://github.com/webpack/css-loader/issues/420)) ([a2b85d7](https://github.com/webpack/css-loader/commit/a2b85d7))
### Features
* allow removal of original class name ([#445](https://github.com/webpack/css-loader/issues/445)) ([3f78361](https://github.com/webpack/css-loader/commit/3f78361))
* Include the sourceMappingURL & sourceURL when toString() ([6da7e90](https://github.com/webpack/css-loader/commit/6da7e90))
+20
View File
@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+744
View File
@@ -0,0 +1,744 @@
<div align="center">
<img width="180" height="180" vspace="20"
src="https://cdn.worldvectorlogo.com/logos/css-3.svg">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
</div>
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]
[![size][size]][size-url]
# css-loader
The `css-loader` interprets `@import` and `url()` like `import/require()` and will resolve them.
## Getting Started
To begin, you'll need to install `css-loader`:
```console
npm install --save-dev css-loader
```
Then add the plugin to your `webpack` config. For example:
**file.js**
```js
import css from 'file.css';
```
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
```
Good loaders for requiring your assets are the [file-loader](https://github.com/webpack/file-loader) and the [url-loader](https://github.com/webpack/url-loader) which you should specify in your config (see [below](https://github.com/webpack-contrib/css-loader#assets)).
And run `webpack` via your preferred method.
### `toString`
You can also use the css-loader results directly as a string, such as in Angular's component style.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['to-string-loader', 'css-loader'],
},
],
},
};
```
or
```js
const css = require('./test.css').toString();
console.log(css); // {String}
```
If there are SourceMaps, they will also be included in the result string.
If, for one reason or another, you need to extract CSS as a
plain string resource (i.e. not wrapped in a JS module) you
might want to check out the [extract-loader](https://github.com/peerigon/extract-loader).
It's useful when you, for instance, need to post process the CSS as a string.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'handlebars-loader', // handlebars loader expects raw resource string
'extract-loader',
'css-loader',
],
},
],
},
};
```
## Options
| Name | Type | Default | Description |
| :-----------------------------------------: | :-------------------: | :-------------: | :----------------------------------------------------------------------- |
| **[`url`](#url)** | `{Boolean\|Function}` | `true` | Enable/Disable `url()` handling |
| **[`import`](#import)** | `{Boolean\/Function}` | `true` | Enable/Disable @import handling |
| **[`modules`](#modules)** | `{Boolean\|String}` | `false` | Enable/Disable CSS Modules and setup mode |
| **[`localIdentName`](#localidentname)** | `{String}` | `[hash:base64]` | Configure the generated ident |
| **[`context`](#context)** | `{String}` | `undefined` | Allow to redefine basic loader context for local ident name |
| **[`hashPrefix`](#hashprefix)** | `{String}` | `undefined` | Allow to add custom hash to generate more unique classes |
| **[`getLocalIdent`](#getlocalident)** | `{Function}` | `undefined` | Configure the function to generate classname based on a different schema |
| **[`sourceMap`](#sourcemap)** | `{Boolean}` | `false` | Enable/Disable Sourcemaps |
| **[`camelCase`](#camelcase)** | `{Boolean\|String}` | `false` | Export Classnames in CamelCase |
| **[`importLoaders`](#importloaders)** | `{Number}` | `0` | Number of loaders applied before CSS loader |
| **[`exportOnlyLocals`](#exportonlylocals)** | `{Boolean}` | `false` | Export only locals |
### `url`
Type: `Boolean|Function`
Default: `true`
Control `url()` resolving. Absolute URLs and root-relative URLs are not resolving.
Examples resolutions:
```
url(image.png) => require('./image.png')
url('image.png') => require('./image.png')
url(./image.png) => require('./image.png')
url('./image.png') => require('./image.png')
url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png')
image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')
```
To import assets from a `node_modules` path (include `resolve.modules`) and for `alias`, prefix it with a `~`:
```
url(~module/image.png) => require('module/image.png')
url('~module/image.png') => require('module/image.png')
url(~aliasDirectory/image.png) => require('otherDirectory/image.png')
```
#### `Boolean`
Enable/disable `url()` resolving.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
url: true,
},
},
],
},
};
```
#### `Function`
Allow to filter `url()`. All filtered `url()` will not be resolved (left in the code as they were written).
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
url: (url, resourcePath) => {
// resourcePath - path to css file
// `url()` with `img.png` stay untouched
return url.includes('img.png');
},
},
},
],
},
};
```
### `import`
Type: `Boolean`
Default: `true`
Control `@import` resolving. Absolute urls in `@import` will be moved in runtime code.
Examples resolutions:
```
@import 'style.css' => require('./style.css')
@import url(style.css) => require('./style.css')
@import url('style.css') => require('./style.css')
@import './style.css' => require('./style.css')
@import url(./style.css) => require('./style.css')
@import url('./style.css') => require('./style.css')
@import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime
```
To import styles from a `node_modules` path (include `resolve.modules`) and for `alias`, prefix it with a `~`:
```
@import url(~module/style.css) => require('module/style.css')
@import url('~module/style.css') => require('module/style.css')
@import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')
```
#### `Boolean`
Enable/disable `@import` resolving.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
import: true,
},
},
],
},
};
```
#### `Function`
Allow to filter `@import`. All filtered `@import` will not be resolved (left in the code as they were written).
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
import: (parsedImport, resourcePath) => {
// parsedImport.url - url of `@import`
// parsedImport.media - media query of `@import`
// resourcePath - path to css file
// `@import` with `style.css` stay untouched
return parsedImport.url.includes('style.css');
},
},
},
],
},
};
```
### [`modules`](https://github.com/css-modules/css-modules)
Type: `Boolean|String`
Default: `false`
The `modules` option enables/disables the **CSS Modules** spec and setup basic behaviour.
| Name | Type | Description |
| :------------: | :---------: | :------------------------------------------------------------------------------------------------------------------------------- |
| **`true`** | `{Boolean}` | Enables local scoped CSS by default (use **local** mode by default) |
| **`false`** | `{Boolean}` | Disable the **CSS Modules** spec, all **CSS Modules** features (like `@value`, `:local`, `:global` and `composes`) will not work |
| **`'local'`** | `{String}` | Enables local scoped CSS by default (same as `true` value) |
| **`'global'`** | `{String}` | Enables global scoped CSS by default |
Using `false` value increase performance because we avoid parsing **CSS Modules** features, it will be useful for developers who use vanilla css or use other technologies.
You can read about **modes** below.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
};
```
##### `Scope`
Using `local` value requires you to specify `:global` classes.
Using `global` value requires you to specify `:local` classes.
You can find more information [here](https://github.com/css-modules/css-modules).
Styles can be locally scoped to avoid globally scoping styles.
The syntax `:local(.className)` can be used to declare `className` in the local scope. The local identifiers are exported by the module.
With `:local` (without brackets) local mode can be switched on for this selector.
The `:global(.className)` nocation can be used to declare an explicit global selector.
With `:global` (without brackets) global mode can be switched on for this selector.
The loader replaces local selectors with unique identifiers. The chosen unique identifiers are exported by the module.
```css
:local(.className) {
background: red;
}
:local .className {
color: green;
}
:local(.className .subClass) {
color: green;
}
:local .className .subClass :global(.global-class-name) {
color: blue;
}
```
```css
._23_aKvs-b8bW2Vg3fwHozO {
background: red;
}
._23_aKvs-b8bW2Vg3fwHozO {
color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {
color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {
color: blue;
}
```
> ℹ️ Identifiers are exported
```js
exports.locals = {
className: '_23_aKvs-b8bW2Vg3fwHozO',
subClass: '_13LGdX8RMStbBE9w-t0gZ1',
};
```
CamelCase is recommended for local selectors. They are easier to use within the imported JS module.
You can use `:local(#someId)`, but this is not recommended. Use classes instead of ids.
##### `Composing`
When declaring a local classname you can compose a local class from another local classname.
```css
:local(.className) {
background: red;
color: yellow;
}
:local(.subClass) {
composes: className;
background: blue;
}
```
This doesn't result in any change to the CSS itself but exports multiple classnames.
```js
exports.locals = {
className: '_23_aKvs-b8bW2Vg3fwHozO',
subClass: '_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO',
};
```
```css
._23_aKvs-b8bW2Vg3fwHozO {
background: red;
color: yellow;
}
._13LGdX8RMStbBE9w-t0gZ1 {
background: blue;
}
```
##### `Importing`
To import a local classname from another module.
```css
:local(.continueButton) {
composes: button from 'library/button.css';
background: red;
}
```
```css
:local(.nameEdit) {
composes: edit highlight from './edit.css';
background: red;
}
```
To import from multiple modules use multiple `composes:` rules.
```css
:local(.className) {
composes: edit hightlight from './edit.css';
composes: button from 'module/button.css';
composes: classFromThisModule;
background: red;
}
```
### `localIdentName`
Type: `String`
Default: `[hash:base64]`
You can configure the generated ident with the `localIdentName` query parameter.
See [loader-utils's documentation](https://github.com/webpack/loader-utils#interpolatename) for more information on options.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
},
},
],
},
};
```
### `context`
Type: `String`
Default: `undefined`
Allow to redefine basic loader context for local ident name.
By default we use `rootContext` of loader.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
modules: true,
context: path.resolve(__dirname, 'context'),
},
},
],
},
};
```
### `hashPrefix`
Type: `String`
Default: `undefined`
Allow to add custom hash to generate more unique classes.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
modules: true,
hashPrefix: 'hash',
},
},
],
},
};
```
### `getLocalIdent`
Type: `Function`
Default: `undefined`
You can also specify the absolute path to your custom `getLocalIdent` function to generate classname based on a different schema.
By default we use built-in function to generate a classname.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
modules: true,
getLocalIdent: (context, localIdentName, localName, options) => {
return 'whatever_random_class_name';
},
},
},
],
},
};
```
### `sourceMap`
Type: `Boolean`
Default: `false`
To include source maps set the `sourceMap` option.
I.e. the `mini-css-extract-plugin` can handle them.
They are not enabled by default because they expose a runtime overhead and increase in bundle size (JS source maps do not). In addition to that relative paths are buggy and you need to use an absolute public path which includes the server URL.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
sourceMap: true,
},
},
],
},
};
```
### `camelCase`
Type: `Boolean|String`
Default: `false`
By default, the exported JSON keys mirror the class names. If you want to camelize class names (useful in JS), pass the query parameter `camelCase` to css-loader.
| Name | Type | Description |
| :----------------: | :---------: | :----------------------------------------------------------------------------------------------------------------------- |
| **`false`** | `{Boolean}` | Class names will be camelized, the original class name will not to be removed from the locals |
| **`true`** | `{Boolean}` | Class names will be camelized |
| **`'dashes'`** | `{String}` | Only dashes in class names will be camelized |
| **`'only'`** | `{String}` | Introduced in `0.27.1`. Class names will be camelized, the original class name will be removed from the locals |
| **`'dashesOnly'`** | `{String}` | Introduced in `0.27.1`. Dashes in class names will be camelized, the original class name will be removed from the locals |
**file.css**
```css
.class-name {
}
```
**file.js**
```js
import { className } from 'file.css';
```
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
camelCase: true,
},
},
],
},
};
```
### `importLoaders`
Type: `Number`
Default: `0`
The option `importLoaders` allows you to configure how many loaders before `css-loader` should be applied to `@import`ed resources.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2, // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
},
},
'postcss-loader',
'sass-loader',
],
},
],
},
};
```
This may change in the future when the module system (i. e. webpack) supports loader matching by origin.
### `exportOnlyLocals`
Type: `Boolean`
Default: `false`
Export only locals (**useful** when you use **css modules**).
For pre-rendering with `mini-css-extract-plugin` you should use this option instead of `style-loader!css-loader` **in the pre-rendering bundle**.
It doesn't embed CSS but only exports the identifier mappings.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: 'css-loader',
options: {
exportOnlyLocals: true,
},
},
],
},
};
```
## Examples
### Assets
The following `webpack.config.js` can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as [Data URLs](https://tools.ietf.org/html/rfc2397) and copy larger files to the output directory.
**webpack.config.js**
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000,
},
},
],
},
};
```
### Extract
For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
- This can be achieved by using the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) to extract the CSS when running in production mode.
- As an alternative, if seeking better development performance and css outputs that mimic production. [extract-css-chunks-webpack-plugin](https://github.com/faceyspacey/extract-css-chunks-webpack-plugin) offers a hot module reload friendly, extended version of mini-css-extract-plugin. HMR real CSS files in dev, works like mini-css in non-dev
## Contributing
Please take a moment to read our contributing guidelines if you haven't yet done so.
[CONTRIBUTING](./.github/CONTRIBUTING.md)
## License
[MIT](./LICENSE)
[npm]: https://img.shields.io/npm/v/css-loader.svg
[npm-url]: https://npmjs.com/package/css-loader
[node]: https://img.shields.io/node/v/css-loader.svg
[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack-contrib/css-loader.svg
[deps-url]: https://david-dm.org/webpack-contrib/css-loader
[tests]: https://img.shields.io/circleci/project/github/webpack-contrib/css-loader.svg
[tests-url]: https://circleci.com/gh/webpack-contrib/css-loader
[cover]: https://codecov.io/gh/webpack-contrib/css-loader/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack-contrib/css-loader
[chat]: https://badges.gitter.im/webpack/webpack.svg
[chat-url]: https://gitter.im/webpack/webpack
[size]: https://packagephobia.now.sh/badge?p=css-loader
[size-url]: https://packagephobia.now.sh/result?p=css-loader
+38
View File
@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class CssSyntaxError extends Error {
constructor(error) {
super(error);
const {
reason,
line,
column
} = error;
this.name = 'CssSyntaxError'; // Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
// We don't need `plugin` and `file` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== 'undefined') {
this.message += `(${line}:${column}) `;
}
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
} // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
exports.default = CssSyntaxError;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class Warning extends Error {
constructor(warning) {
super(warning);
const {
text,
line,
column
} = warning;
this.name = 'Warning'; // Based on https://github.com/postcss/postcss/blob/master/lib/warning.es6#L74
// We don't need `plugin` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== 'undefined') {
this.message += `(${line}:${column}) `;
}
this.message += `${text}`; // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
exports.default = Warning;
+5
View File
@@ -0,0 +1,5 @@
"use strict";
const loader = require('./index');
module.exports = loader.default;
+260
View File
@@ -0,0 +1,260 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loader;
var _schemaUtils = _interopRequireDefault(require("schema-utils"));
var _postcss = _interopRequireDefault(require("postcss"));
var _package = _interopRequireDefault(require("postcss/package.json"));
var _postcssModulesLocalByDefault = _interopRequireDefault(require("postcss-modules-local-by-default"));
var _postcssModulesExtractImports = _interopRequireDefault(require("postcss-modules-extract-imports"));
var _postcssModulesScope = _interopRequireDefault(require("postcss-modules-scope"));
var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
var _loaderUtils = require("loader-utils");
var _normalizePath = _interopRequireDefault(require("normalize-path"));
var _options = _interopRequireDefault(require("./options.json"));
var _plugins = require("./plugins");
var _utils = require("./utils");
var _Warning = _interopRequireDefault(require("./Warning"));
var _CssSyntaxError = _interopRequireDefault(require("./CssSyntaxError"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function loader(content, map, meta) {
const options = (0, _loaderUtils.getOptions)(this) || {};
(0, _schemaUtils.default)(_options.default, options, 'CSS Loader');
const callback = this.async();
const sourceMap = options.sourceMap || false;
/* eslint-disable no-param-reassign */
if (sourceMap) {
if (map) {
// Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof map === 'string') {
map = JSON.parse(map.replace(/^\)]}'[^\n]*\n/, ''));
} // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
if (map.file) {
map.file = (0, _normalizePath.default)(map.file);
}
if (map.sourceRoot) {
map.sourceRoot = (0, _normalizePath.default)(map.sourceRoot);
}
if (map.sources) {
map.sources = map.sources.map(source => (0, _normalizePath.default)(source));
}
}
} else {
// Some loaders (example `"postcss-loader": "1.x.x"`) always generates source map, we should remove it
map = null;
}
/* eslint-enable no-param-reassign */
// Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
if (meta) {
const {
ast
} = meta;
if (ast && ast.type === 'postcss' && ast.version === _package.default.version) {
// eslint-disable-next-line no-param-reassign
content = ast.root;
}
}
const plugins = [];
if (options.modules) {
const loaderContext = this;
const mode = typeof options.modules === 'boolean' ? 'local' : options.modules;
plugins.push(_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
mode
}), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
generateScopedName: function generateScopedName(exportName) {
const localIdentName = options.localIdentName || '[hash:base64]';
const customGetLocalIdent = options.getLocalIdent || _utils.getLocalIdent;
return customGetLocalIdent(loaderContext, localIdentName, exportName, {
regExp: options.localIdentRegExp,
hashPrefix: options.hashPrefix || '',
context: options.context
});
}
}));
}
if (options.import !== false) {
plugins.push((0, _plugins.importParser)({
filter: (0, _utils.getFilter)(options.import, this.resourcePath)
}));
}
if (options.url !== false) {
plugins.push((0, _plugins.urlParser)({
filter: (0, _utils.getFilter)(options.url, this.resourcePath, value => (0, _loaderUtils.isUrlRequest)(value))
}));
}
plugins.push((0, _plugins.icssParser)());
(0, _postcss.default)(plugins).process(content, {
from: (0, _loaderUtils.getRemainingRequest)(this).split('!').pop(),
to: (0, _loaderUtils.getCurrentRequest)(this).split('!').pop(),
map: options.sourceMap ? {
prev: map,
inline: false,
annotation: false
} : null
}).then(result => {
result.warnings().forEach(warning => this.emitWarning(new _Warning.default(warning)));
const messages = result.messages || []; // Run other loader (`postcss-loader`, `sass-loader` and etc) for importing CSS
const importUrlPrefix = (0, _utils.getImportPrefix)(this, options.importLoaders); // Prepare replacer to change from `___CSS_LOADER_IMPORT___INDEX___` to `require('./file.css').locals`
const importItemReplacer = placeholder => {
const match = _utils.placholderRegExps.importItem.exec(placeholder);
const idx = Number(match[1]);
const message = messages.find( // eslint-disable-next-line no-shadow
message => message.type === 'icss-import' && message.item && message.item.index === idx);
if (!message) {
return placeholder;
}
const {
item
} = message;
const importUrl = importUrlPrefix + (0, _loaderUtils.urlToRequest)(item.url);
if (options.exportOnlyLocals) {
return `" + require(${(0, _loaderUtils.stringifyRequest)(this, importUrl)})[${JSON.stringify(item.export)}] + "`;
}
return `" + require(${(0, _loaderUtils.stringifyRequest)(this, importUrl)}).locals[${JSON.stringify(item.export)}] + "`;
};
const exports = messages.filter(message => message.type === 'export').reduce((accumulator, message) => {
const {
key,
value
} = message.item;
let valueAsString = JSON.stringify(value);
valueAsString = valueAsString.replace(_utils.placholderRegExps.importItemG, importItemReplacer);
function addEntry(k) {
accumulator.push(`\t${JSON.stringify(k)}: ${valueAsString}`);
}
let targetKey;
switch (options.camelCase) {
case true:
addEntry(key);
targetKey = (0, _utils.camelCase)(key);
if (targetKey !== key) {
addEntry(targetKey);
}
break;
case 'dashes':
addEntry(key);
targetKey = (0, _utils.dashesCamelCase)(key);
if (targetKey !== key) {
addEntry(targetKey);
}
break;
case 'only':
addEntry((0, _utils.camelCase)(key));
break;
case 'dashesOnly':
addEntry((0, _utils.dashesCamelCase)(key));
break;
default:
addEntry(key);
break;
}
return accumulator;
}, []);
if (options.exportOnlyLocals) {
return callback(null, exports.length > 0 ? `module.exports = {\n${exports.join(',\n')}\n};` : '');
}
const imports = messages.filter(message => message.type === 'import').map(message => {
const {
url
} = message.item;
const media = message.item.media || '';
if (!(0, _loaderUtils.isUrlRequest)(url)) {
return `exports.push([module.id, ${JSON.stringify(`@import url(${url});`)}, ${JSON.stringify(media)}]);`;
}
const importUrl = importUrlPrefix + (0, _loaderUtils.urlToRequest)(url);
return `exports.i(require(${(0, _loaderUtils.stringifyRequest)(this, importUrl)}), ${JSON.stringify(media)});`;
}, this);
let cssAsString = JSON.stringify(result.css).replace(_utils.placholderRegExps.importItemG, importItemReplacer); // Helper for ensuring valid CSS strings from requires
let hasUrlEscapeHelper = false;
messages.filter(message => message.type === 'url').forEach(message => {
if (!hasUrlEscapeHelper) {
imports.push(`var urlEscape = require(${(0, _loaderUtils.stringifyRequest)(this, require.resolve('./runtime/url-escape.js'))});`);
hasUrlEscapeHelper = true;
}
const {
item
} = message;
const {
url,
placeholder,
needQuotes
} = item; // Remove `#hash` and `?#hash` from `require`
const [normalizedUrl, singleQuery, hashValue] = url.split(/(\?)?#/);
const hash = singleQuery || hashValue ? `"${singleQuery ? '?' : ''}${hashValue ? `#${hashValue}` : ''}"` : '';
imports.push(`var ${placeholder} = urlEscape(require(${(0, _loaderUtils.stringifyRequest)(this, (0, _loaderUtils.urlToRequest)(normalizedUrl))})${hash ? ` + ${hash}` : ''}${needQuotes ? ', true' : ''});`);
cssAsString = cssAsString.replace(new RegExp(placeholder, 'g'), () => `" + ${placeholder} + "`);
});
const runtimeCode = `exports = module.exports = require(${(0, _loaderUtils.stringifyRequest)(this, require.resolve('./runtime/api'))})(${!!sourceMap});\n`;
const importCode = imports.length > 0 ? `// Imports\n${imports.join('\n')}\n\n` : '';
const moduleCode = `// Module\nexports.push([module.id, ${cssAsString}, ""${result.map ? `,${result.map}` : ''}]);\n\n`;
const exportsCode = exports.length > 0 ? `// Exports\nexports.locals = {\n${exports.join(',\n')}\n};` : ''; // Embed runtime
return callback(null, runtimeCode + importCode + moduleCode + exportsCode);
}).catch(error => {
callback(error.name === 'CssSyntaxError' ? new _CssSyntaxError.default(error) : error);
});
}
+93
View File
@@ -0,0 +1,93 @@
{
"additionalProperties": false,
"properties": {
"url": {
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
]
},
"import": {
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
]
},
"modules": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string",
"enum": ["local", "global"]
}
]
},
"localIdentName": {
"type": "string"
},
"localIdentRegExp": {
"anyOf": [
{
"type": "string"
},
{
"instanceof": "RegExp"
}
]
},
"context": {
"type": "string"
},
"hashPrefix": {
"type": "string"
},
"getLocalIdent": {
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
]
},
"sourceMap": {
"type": "boolean"
},
"camelCase": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string",
"enum": ["dashes", "only", "dashesOnly"]
}
]
},
"importLoaders": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "number"
}
]
},
"exportOnlyLocals": {
"type": "boolean"
}
},
"type": "object"
}
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "importParser", {
enumerable: true,
get: function () {
return _postcssImportParser.default;
}
});
Object.defineProperty(exports, "icssParser", {
enumerable: true,
get: function () {
return _postcssIcssParser.default;
}
});
Object.defineProperty(exports, "urlParser", {
enumerable: true,
get: function () {
return _postcssUrlParser.default;
}
});
var _postcssImportParser = _interopRequireDefault(require("./postcss-import-parser"));
var _postcssIcssParser = _interopRequireDefault(require("./postcss-icss-parser"));
var _postcssUrlParser = _interopRequireDefault(require("./postcss-url-parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+101
View File
@@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _icssUtils = require("icss-utils");
var _loaderUtils = _interopRequireDefault(require("loader-utils"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-icss-parser';
var _default = _postcss.default.plugin(pluginName, () => function process(css, result) {
const imports = {};
const icss = (0, _icssUtils.extractICSS)(css);
const exports = icss.icssExports;
Object.keys(icss.icssImports).forEach(key => {
const url = _loaderUtils.default.parseString(key);
Object.keys(icss.icssImports[key]).forEach(prop => {
const index = Object.keys(imports).length;
imports[`$${prop}`] = index;
result.messages.push({
pluginName,
type: 'icss-import',
item: {
url,
export: icss.icssImports[key][prop],
index
}
});
const alreadyIncluded = result.messages.find(message => message.pluginName === pluginName && message.type === 'import' && message.item.url === url && message.item.media === '');
if (alreadyIncluded) {
return;
}
result.messages.push({
pluginName,
type: 'import',
item: {
url,
media: ''
}
});
});
});
function replaceImportsInString(str) {
const tokens = (0, _postcssValueParser.default)(str);
tokens.walk(node => {
if (node.type !== 'word') {
return;
}
const token = node.value;
const importIndex = imports[`$${token}`];
if (typeof importIndex === 'number') {
// eslint-disable-next-line no-param-reassign
node.value = `___CSS_LOADER_IMPORT___${importIndex}___`;
}
});
return tokens.toString();
} // Replace tokens in declarations
css.walkDecls(decl => {
// eslint-disable-next-line no-param-reassign
decl.value = replaceImportsInString(decl.value.toString());
}); // Replace tokens in at-rules
css.walkAtRules(atrule => {
// Due reusing `ast` from `postcss-loader` some plugins may lack
// `params` property, we need to account for this possibility
if (atrule.params) {
// eslint-disable-next-line no-param-reassign
atrule.params = replaceImportsInString(atrule.params.toString());
}
}); // Replace tokens in export
Object.keys(exports).forEach(exportName => {
result.messages.push({
pluginName,
type: 'export',
item: {
key: exportName,
value: replaceImportsInString(exports[exportName])
}
});
});
});
exports.default = _default;
+110
View File
@@ -0,0 +1,110 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-import-parser';
function getArg(nodes) {
return nodes.length !== 0 && nodes[0].type === 'string' ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
}
function getUrl(node) {
if (node.type === 'function' && node.value.toLowerCase() === 'url') {
return getArg(node.nodes);
}
if (node.type === 'string') {
return node.value;
}
return null;
}
function parseImport(params) {
const {
nodes
} = (0, _postcssValueParser.default)(params);
if (nodes.length === 0) {
return null;
}
const url = getUrl(nodes[0]);
if (!url || url.trim().length === 0) {
return null;
}
return {
url,
media: _postcssValueParser.default.stringify(nodes.slice(1)).trim().toLowerCase()
};
}
function walkAtRules(css, result, filter) {
const items = [];
css.walkAtRules(/^import$/i, atRule => {
// Convert only top-level @import
if (atRule.parent.type !== 'root') {
return;
}
if (atRule.nodes) {
result.warn("It looks like you didn't end your @import statement correctly. " + 'Child nodes are attached to it.', {
node: atRule
});
return;
}
const parsed = parseImport(atRule.params);
if (!parsed) {
// eslint-disable-next-line consistent-return
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
node: atRule
});
}
if (filter && !filter(parsed)) {
return;
}
atRule.remove();
const {
url,
media
} = parsed;
items.push({
url,
media
});
});
return items;
}
function uniq(array) {
return array.reduce((acc, d) => !acc.find(el => el.url === d.url && el.media === d.media) ? [...acc, d] : acc, []);
}
var _default = _postcss.default.plugin(pluginName, (options = {}) => function process(css, result) {
const traversed = walkAtRules(css, result, options.filter);
const paths = uniq(traversed);
paths.forEach(item => {
result.messages.push({
pluginName,
type: 'import',
item
});
});
});
exports.default = _default;
+159
View File
@@ -0,0 +1,159 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-url-parser';
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDecl = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function getUrlFromUrlFunc(node) {
return node.nodes.length !== 0 && node.nodes[0].type === 'string' ? node.nodes[0].value : _postcssValueParser.default.stringify(node.nodes);
}
function walkUrls(parsed, callback) {
parsed.walk(node => {
if (node.type !== 'function') {
return;
}
if (isUrlFunc.test(node.value)) {
callback(getNodeFromUrlFunc(node), getUrlFromUrlFunc(node), false); // Do not traverse inside `url`
// eslint-disable-next-line consistent-return
return false;
}
if (isImageSetFunc.test(node.value)) {
node.nodes.forEach(nNode => {
if (nNode.type === 'function' && isUrlFunc.test(nNode.value)) {
callback(getNodeFromUrlFunc(nNode), getUrlFromUrlFunc(nNode), false);
}
if (nNode.type === 'string') {
callback(nNode, nNode.value, true);
}
}); // Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
}
function walkDeclsWithUrl(css, result, filter) {
const items = [];
css.walkDecls(decl => {
if (!needParseDecl.test(decl.value)) {
return;
}
const parsed = (0, _postcssValueParser.default)(decl.value);
const urls = [];
walkUrls(parsed, (node, url, needQuotes) => {
if (url.trim().replace(/\\[\r\n]/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl.toString()}'`, {
node: decl
});
return;
}
if (filter && !filter(url)) {
return;
}
urls.push({
url,
needQuotes
});
});
if (urls.length === 0) {
return;
}
items.push({
decl,
parsed,
urls
});
});
return items;
}
function uniqWith(array, comparator) {
return array.reduce((acc, d) => !acc.some(item => comparator(d, item)) ? [...acc, d] : acc, []);
}
function flatten(array) {
return array.reduce((a, b) => a.concat(b), []);
}
function isEqual(value, other) {
return value.url === other.url && value.needQuotes === other.needQuotes;
}
var _default = _postcss.default.plugin(pluginName, (options = {}) => function process(css, result) {
const traversed = walkDeclsWithUrl(css, result, options.filter);
const paths = uniqWith(flatten(traversed.map(item => item.urls)), isEqual);
if (paths.length === 0) {
return;
}
const placeholders = [];
paths.forEach((path, index) => {
const placeholder = `___CSS_LOADER_URL___${index}___`;
const {
url,
needQuotes
} = path;
placeholders.push({
placeholder,
path
});
result.messages.push({
pluginName,
type: 'url',
item: {
url,
placeholder,
needQuotes
}
});
});
traversed.forEach(item => {
walkUrls(item.parsed, (node, url, needQuotes) => {
const value = placeholders.find(placeholder => placeholder.path.url === url && placeholder.path.needQuotes === needQuotes);
if (!value) {
return;
}
const {
placeholder
} = value; // eslint-disable-next-line no-param-reassign
node.type = 'word'; // eslint-disable-next-line no-param-reassign
node.value = placeholder;
}); // eslint-disable-next-line no-param-reassign
item.decl.value = item.parsed.toString();
});
});
exports.default = _default;
+85
View File
@@ -0,0 +1,85 @@
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return '@media ' + item[2] + '{' + content + '}';
} else {
return content;
}
}).join('');
}; // import a list of modules into the list
list.i = function (modules, mediaQuery) {
if (typeof modules === 'string') {
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
for (var i = 0; i < this.length; i++) {
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
for (i = 0; i < modules.length; i++) {
var item = modules[i]; // skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if (item[0] == null || !alreadyImportedModules[item[0]]) {
if (mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if (mediaQuery) {
item[2] = '(' + item[2] + ') and (' + mediaQuery + ')';
}
list.push(item);
}
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || '';
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */';
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
return '/*# ' + data + ' */';
}
+20
View File
@@ -0,0 +1,20 @@
"use strict";
module.exports = function escape(url, needQuotes) {
if (typeof url !== 'string') {
return url;
} // If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
url = url.slice(1, -1);
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || needQuotes) {
return '"' + url.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"';
}
return url;
};
+97
View File
@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getImportPrefix = getImportPrefix;
exports.getLocalIdent = getLocalIdent;
exports.camelCase = camelCase;
exports.dashesCamelCase = dashesCamelCase;
exports.getFilter = getFilter;
exports.placholderRegExps = void 0;
var _path = _interopRequireDefault(require("path"));
var _camelcase = _interopRequireDefault(require("camelcase"));
var _loaderUtils = _interopRequireDefault(require("loader-utils"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/* eslint-disable line-comment-position */
const placholderRegExps = {
importItemG: /___CSS_LOADER_IMPORT___([0-9]+)___/g,
importItem: /___CSS_LOADER_IMPORT___([0-9]+)___/
};
exports.placholderRegExps = placholderRegExps;
function getImportPrefix(loaderContext, importLoaders) {
if (importLoaders === false) {
return '';
}
const numberImportedLoaders = parseInt(importLoaders, 10) || 0;
const loadersRequest = loaderContext.loaders.slice(loaderContext.loaderIndex, loaderContext.loaderIndex + 1 + numberImportedLoaders).map(x => x.request).join('!');
return `-!${loadersRequest}!`;
}
function camelCase(str) {
return (0, _camelcase.default)(str);
}
function dashesCamelCase(str) {
return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
}
const whitespace = '[\\x20\\t\\r\\n\\f]';
const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, 'ig');
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
const high = `0x${escaped}` - 0x10000; // NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
// eslint-disable-next-line no-self-compare
return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint
String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair)
// eslint-disable-next-line no-bitwise
String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
});
}
function getLocalIdent(loaderContext, localIdentName, localName, options) {
if (!options.context) {
// eslint-disable-next-line no-param-reassign
options.context = loaderContext.rootContext;
}
const request = _path.default.relative(options.context, loaderContext.resourcePath).replace(/\\/g, '/'); // eslint-disable-next-line no-param-reassign
options.content = `${options.hashPrefix + request}+${unescape(localName)}`; // eslint-disable-next-line no-param-reassign
localIdentName = localIdentName.replace(/\[local\]/gi, localName);
const hash = _loaderUtils.default.interpolateName(loaderContext, localIdentName, options);
return hash.replace(new RegExp('[^a-zA-Z0-9\\-_\u00A0-\uFFFF]', 'g'), '-').replace(/^((-?[0-9])|--)/, '_$1');
}
function getFilter(filter, resourcePath, defaultFilter = null) {
return content => {
if (defaultFilter && !defaultFilter(content)) {
return false;
}
if (typeof filter === 'function') {
return !filter(content, resourcePath);
}
return true;
};
}
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../cssesc/bin/cssesc" "$@"
ret=$?
else
node "$basedir/../cssesc/bin/cssesc" "$@"
ret=$?
fi
exit $ret
+7
View File
@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\cssesc\bin\cssesc" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\cssesc\bin\cssesc" %*
)
+20
View File
@@ -0,0 +1,20 @@
Copyright Mathias Bynens <https://mathiasbynens.be/>
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.
+201
View File
@@ -0,0 +1,201 @@
# cssesc [![Build status](https://travis-ci.org/mathiasbynens/cssesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/cssesc) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/cssesc.svg)](https://codecov.io/gh/mathiasbynens/cssesc)
A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.
This is a JavaScript library for [escaping text for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](https://mothereff.in/css-escapes)
[A polyfill for the CSSOM `CSS.escape()` method is available in a separate repository.](https://mths.be/cssescape) (In comparison, _cssesc_ is much more powerful.)
Feel free to fork if you see possible improvements!
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install cssesc
```
In a browser:
```html
<script src="cssesc.js"></script>
```
In [Node.js](https://nodejs.org/):
```js
const cssesc = require('cssesc');
```
In Ruby using [the `ruby-cssesc` wrapper gem](https://github.com/borodean/ruby-cssesc):
```bash
gem install ruby-cssesc
```
```ruby
require 'ruby-cssesc'
CSSEsc.escape('I ♥ Ruby', is_identifier: true)
```
In Sass using [`sassy-escape`](https://github.com/borodean/sassy-escape):
```bash
gem install sassy-escape
```
```scss
body {
content: escape('I ♥ Sass', $is-identifier: true);
}
```
## API
### `cssesc(value, options)`
This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes).
```js
cssesc('Ich ♥ Bücher');
// → 'Ich \\2665 B\\FC cher'
cssesc('foo 𝌆 bar');
// → 'foo \\1D306 bar'
```
By default, `cssesc` returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the `isIdentifier: true` setting (see below).
The optional `options` argument accepts an object with the following options:
#### `isIdentifier`
The default value for the `isIdentifier` option is `false`. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to `true`.
```js
cssesc('123a2b');
// → '123a2b'
cssesc('123a2b', {
'isIdentifier': true
});
// → '\\31 23a2b'
```
#### `quotes`
The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input text will be escaped as `\'`, so that the output can be used in a CSS string literal wrapped in single quotes.
```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.');
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'single'
});
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
```
If you want to use the output as part of a CSS string literal wrapped in double quotes, set the `quotes` option to `'double'`.
```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'double'
});
// → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.'
// → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc."
```
#### `wrap`
The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting.
```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'single',
'wrap': true
});
// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'double',
'wrap': true
});
// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
```
#### `escapeEverything`
The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols.
```js
cssesc('lolwat"foo\'bar', {
'escapeEverything': true
});
// → '\\6C\\6F\\6C\\77\\61\\74\\"\\66\\6F\\6F\\\'\\62\\61\\72'
// → "\\6C\\6F\\6C\\77\\61\\74\\\"\\66\\6F\\6F\\'\\62\\61\\72"
```
#### Overriding the default options globally
The global default settings can be overridden by modifying the `css.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting.
```js
// Read the global default setting for `escapeEverything`:
cssesc.options.escapeEverything;
// → `false` by default
// Override the global default setting for `escapeEverything`:
cssesc.options.escapeEverything = true;
// Using the global default setting for `escapeEverything`, which is now `true`:
cssesc('foo © bar ≠ baz 𝌆 qux');
// → '\\66\\6F\\6F\\ \\A9\\ \\62\\61\\72\\ \\2260\\ \\62\\61\\7A\\ \\1D306\\ \\71\\75\\78'
```
### `cssesc.version`
A string representing the semantic version number.
### Using the `cssesc` binary
To use the `cssesc` binary in your shell, simply install cssesc globally using npm:
```bash
npm install -g cssesc
```
After that you will be able to escape text for use in CSS strings or identifiers from the command line:
```bash
$ cssesc 'föo ♥ bår 𝌆 baz'
f\F6o \2665 b\E5r \1D306 baz
```
If the output needs to be a CSS identifier rather than part of a string literal, use the `-i`/`--identifier` option:
```bash
$ cssesc --identifier 'föo ♥ bår 𝌆 baz'
f\F6o\ \2665\ b\E5r\ \1D306\ baz
```
See `cssesc --help` for the full list of options.
## Support
This library supports the Node.js and browser versions mentioned in [`.babelrc`](https://github.com/mathiasbynens/cssesc/blob/master/.babelrc). For a version that supports a wider variety of legacy browsers and environments out-of-the-box, [see v0.1.0](https://github.com/mathiasbynens/cssesc/releases/tag/v0.1.0).
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
This library is available under the [MIT](https://mths.be/mit) license.
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env node
const fs = require('fs');
const cssesc = require('../cssesc.js');
const strings = process.argv.splice(2);
const stdin = process.stdin;
const options = {};
const log = console.log;
const main = function() {
const option = strings[0];
if (/^(?:-h|--help|undefined)$/.test(option)) {
log(
'cssesc v%s - https://mths.be/cssesc',
cssesc.version
);
log([
'\nUsage:\n',
'\tcssesc [string]',
'\tcssesc [-i | --identifier] [string]',
'\tcssesc [-s | --single-quotes] [string]',
'\tcssesc [-d | --double-quotes] [string]',
'\tcssesc [-w | --wrap] [string]',
'\tcssesc [-e | --escape-everything] [string]',
'\tcssesc [-v | --version]',
'\tcssesc [-h | --help]',
'\nExamples:\n',
'\tcssesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\tcssesc --identifier \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\tcssesc --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\tcssesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
'\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | cssesc'
].join('\n'));
return process.exit(1);
}
if (/^(?:-v|--version)$/.test(option)) {
log('v%s', cssesc.version);
return process.exit(1);
}
strings.forEach(function(string) {
// Process options
if (/^(?:-i|--identifier)$/.test(string)) {
options.isIdentifier = true;
return;
}
if (/^(?:-s|--single-quotes)$/.test(string)) {
options.quotes = 'single';
return;
}
if (/^(?:-d|--double-quotes)$/.test(string)) {
options.quotes = 'double';
return;
}
if (/^(?:-w|--wrap)$/.test(string)) {
options.wrap = true;
return;
}
if (/^(?:-e|--escape-everything)$/.test(string)) {
options.escapeEverything = true;
return;
}
// Process string(s)
let result;
try {
result = cssesc(string, options);
log(result);
} catch (exception) {
log(exception.message + '\n');
log('Error: failed to escape.');
log('If you think this is a bug in cssesc, please report it:');
log('https://github.com/mathiasbynens/cssesc/issues/new');
log(
'\nStack trace using cssesc@%s:\n',
cssesc.version
);
log(exception.stack);
return process.exit(1);
}
});
// Return with exit status 0 outside of the `forEach` loop, in case
// multiple strings were passed in.
return process.exit(0);
};
if (stdin.isTTY) {
// handle shell arguments
main();
} else {
let timeout;
// Either the script is called from within a non-TTY context, or `stdin`
// content is being piped in.
if (!process.stdout.isTTY) {
// The script was called from a non-TTY context. This is a rather uncommon
// use case we don’t actively support. However, we don’t want the script
// to wait forever in such cases, so…
timeout = setTimeout(function() {
// …if no piped data arrived after a whole minute, handle shell
// arguments instead.
main();
}, 60000);
}
let data = '';
stdin.on('data', function(chunk) {
clearTimeout(timeout);
data += chunk;
});
stdin.on('end', function() {
strings.push(data.trim());
main();
});
stdin.resume();
}
+110
View File
@@ -0,0 +1,110 @@
/*! https://mths.be/cssesc v3.0.0 by @mathias */
'use strict';
var object = {};
var hasOwnProperty = object.hasOwnProperty;
var merge = function merge(options, defaults) {
if (!options) {
return defaults;
}
var result = {};
for (var key in defaults) {
// `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
// only recognized option names are used.
result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
}
return result;
};
var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
var regexAlwaysEscape = /['"\\]/;
var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
// https://mathiasbynens.be/notes/css-escapes#css
var cssesc = function cssesc(string, options) {
options = merge(options, cssesc.options);
if (options.quotes != 'single' && options.quotes != 'double') {
options.quotes = 'single';
}
var quote = options.quotes == 'double' ? '"' : '\'';
var isIdentifier = options.isIdentifier;
var firstChar = string.charAt(0);
var output = '';
var counter = 0;
var length = string.length;
while (counter < length) {
var character = string.charAt(counter++);
var codePoint = character.charCodeAt();
var value = void 0;
// If it’s not a printable ASCII character…
if (codePoint < 0x20 || codePoint > 0x7E) {
if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
// It’s a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) {
// next character is low surrogate
codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
} else {
// It’s an unmatched surrogate; only append this code unit, in case
// the next code unit is the high surrogate of a surrogate pair.
counter--;
}
}
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
} else {
if (options.escapeEverything) {
if (regexAnySingleEscape.test(character)) {
value = '\\' + character;
} else {
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
}
} else if (/[\t\n\f\r\x0B]/.test(character)) {
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
} else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
value = '\\' + character;
} else {
value = character;
}
}
output += value;
}
if (isIdentifier) {
if (/^-[-\d]/.test(output)) {
output = '\\-' + output.slice(1);
} else if (/\d/.test(firstChar)) {
output = '\\3' + firstChar + ' ' + output.slice(1);
}
}
// Remove spaces after `\HEX` escapes that are not followed by a hex digit,
// since they’re redundant. Note that this is only possible if the escape
// sequence isn’t preceded by an odd number of backslashes.
output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
if ($1 && $1.length % 2) {
// It’s not safe to remove the space, so don’t.
return $0;
}
// Strip the space.
return ($1 || '') + $2;
});
if (!isIdentifier && options.wrap) {
return quote + output + quote;
}
return output;
};
// Expose default options (so they can be overridden globally).
cssesc.options = {
'escapeEverything': false,
'isIdentifier': false,
'quotes': 'single',
'wrap': false
};
cssesc.version = '3.0.0';
module.exports = cssesc;
+70
View File
@@ -0,0 +1,70 @@
.Dd August 9, 2013
.Dt cssesc 1
.Sh NAME
.Nm cssesc
.Nd escape text for use in CSS string literals or identifiers
.Sh SYNOPSIS
.Nm
.Op Fl i | -identifier Ar string
.br
.Op Fl s | -single-quotes Ar string
.br
.Op Fl d | -double-quotes Ar string
.br
.Op Fl w | -wrap Ar string
.br
.Op Fl e | -escape-everything Ar string
.br
.Op Fl v | -version
.br
.Op Fl h | -help
.Sh DESCRIPTION
.Nm
escapes strings for use in CSS string literals or identifiers while generating the shortest possible valid ASCII-only output.
.Sh OPTIONS
.Bl -ohang -offset
.It Sy "-s, --single-quotes"
Escape any occurences of ' in the input string as \\', so that the output can be used in a CSS string literal wrapped in single quotes.
.It Sy "-d, --double-quotes"
Escape any occurences of " in the input string as \\", so that the output can be used in a CSS string literal wrapped in double quotes.
.It Sy "-w, --wrap"
Make sure the output is a valid CSS string literal wrapped in quotes. The type of quotes can be specified using the
.Ar -s | --single-quotes
or
.Ar -d | --double-quotes
settings.
.It Sy "-e, --escape-everything"
Escape all the symbols in the output, even printable ASCII symbols.
.It Sy "-v, --version"
Print cssesc's version.
.It Sy "-h, --help"
Show the help screen.
.El
.Sh EXIT STATUS
The
.Nm cssesc
utility exits with one of the following values:
.Pp
.Bl -tag -width flag -compact
.It Li 0
.Nm
successfully escaped the given text and printed the result.
.It Li 1
.Nm
wasn't instructed to escape anything (for example, the
.Ar --help
flag was set); or, an error occurred.
.El
.Sh EXAMPLES
.Bl -ohang -offset
.It Sy "cssesc 'foo bar baz'"
Print an escaped version of the given text.
.It Sy echo\ 'foo bar baz'\ |\ cssesc
Print an escaped version of the text that gets piped in.
.El
.Sh BUGS
cssesc's bug tracker is located at <https://github.com/mathiasbynens/cssesc/issues>.
.Sh AUTHOR
Mathias Bynens <https://mathiasbynens.be/>
.Sh WWW
<https://mths.be/cssesc>
+82
View File
@@ -0,0 +1,82 @@
{
"_from": "cssesc@^3.0.0",
"_id": "cssesc@3.0.0",
"_inBundle": false,
"_integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"_location": "/css-loader/cssesc",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cssesc@^3.0.0",
"name": "cssesc",
"escapedName": "cssesc",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/css-loader/postcss-selector-parser"
],
"_resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
"_shasum": "37741919903b868565e1c09ea747445cd18983ee",
"_spec": "cssesc@^3.0.0",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\css-loader\\node_modules\\postcss-selector-parser",
"author": {
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
},
"bin": {
"cssesc": "bin/cssesc"
},
"bugs": {
"url": "https://github.com/mathiasbynens/cssesc/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"codecov": "^1.0.1",
"grunt": "^1.0.1",
"grunt-template": "^1.0.0",
"istanbul": "^0.4.4",
"mocha": "^2.5.3",
"regenerate": "^1.2.1",
"requirejs": "^2.1.16"
},
"engines": {
"node": ">=4"
},
"files": [
"LICENSE-MIT.txt",
"cssesc.js",
"bin/",
"man/"
],
"homepage": "https://mths.be/cssesc",
"keywords": [
"css",
"escape",
"identifier",
"string",
"tool"
],
"license": "MIT",
"main": "cssesc.js",
"man": [
"man/cssesc.1"
],
"name": "cssesc",
"repository": {
"type": "git",
"url": "git+https://github.com/mathiasbynens/cssesc.git"
},
"scripts": {
"build": "grunt template && babel cssesc.js -o cssesc.js",
"cover": "istanbul cover --report html node_modules/.bin/_mocha tests -- -u exports -R spec",
"test": "mocha tests"
},
"version": "3.0.0"
}
+6
View File
@@ -0,0 +1,6 @@
ISC License (ISC)
Copyright 2018 Glen Maddern
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+84
View File
@@ -0,0 +1,84 @@
[![Build Status](https://travis-ci.org/css-modules/icss-utils.svg)](https://travis-ci.org/css-modules/icss-utils)
# ICSS Utils
## replaceSymbols
Governs the way tokens are searched & replaced during the linking stage of ICSS loading.
This is broken into its own module in case the behaviour needs to be replicated in other PostCSS plugins
(i.e. [CSS Modules Values](https://github.com/css-modules/postcss-modules-values))
```js
import { replaceSymbols, replaceValueSymbols } from "icss-utils";
replaceSymbols(css, replacements);
replaceValueSymbols(string, replacements);
```
Where:
- `css` is the PostCSS tree you're working with
- `replacements` is an JS object of `symbol: "replacement"` pairs, where all occurrences of `symbol` are replaced with `replacement`.
A symbol is a string of alphanumeric, `-` or `_` characters. A replacement can be any string. They are replaced in the following places:
- In the value of a declaration, i.e. `color: my_symbol;` or `box-shadow: 0 0 blur spread shadow-color`
- In a media expression i.e. `@media small {}` or `@media screen and not-large {}`
## extractICSS(css, removeRules = true)
Extracts and remove (if removeRules is equal true) from PostCSS tree `:import` and `:export` statements.
```js
import postcss from "postcss";
import { extractICSS } from "icss-utils";
const css = postcss.parse(`
:import(colors) {
a: b;
}
:export {
c: d;
}
`);
extractICSS(css);
/*
{
icssImports: {
colors: {
a: 'b'
}
},
icssExports: {
c: 'd'
}
}
*/
```
## createICSSRules(icssImports, icssExports)
Converts icss imports and exports definitions to postcss ast
```js
createICSSRules(
{
colors: {
a: "b"
}
},
{
c: "d"
}
);
```
## License
ISC
---
Glen Maddern, Bogdan Chadkin and Evilebottnawi 2015-present.
+65
View File
@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const createImports = imports => {
return Object.keys(imports).map(path => {
const aliases = imports[path];
const declarations = Object.keys(aliases).map(key => _postcss.default.decl({
prop: key,
value: aliases[key],
raws: {
before: "\n "
}
}));
const hasDeclarations = declarations.length > 0;
const rule = _postcss.default.rule({
selector: `:import('${path}')`,
raws: {
after: hasDeclarations ? "\n" : ""
}
});
if (hasDeclarations) {
rule.append(declarations);
}
return rule;
});
};
const createExports = exports => {
const declarations = Object.keys(exports).map(key => _postcss.default.decl({
prop: key,
value: exports[key],
raws: {
before: "\n "
}
}));
if (declarations.length === 0) {
return [];
}
const rule = _postcss.default.rule({
selector: `:export`,
raws: {
after: "\n"
}
}).append(declarations);
return [rule];
};
const createICSSRules = (imports, exports) => [...createImports(imports), ...createExports(exports)];
var _default = createICSSRules;
exports.default = _default;
+52
View File
@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
const getDeclsObject = rule => {
const object = {};
rule.walkDecls(decl => {
const before = decl.raws.before ? decl.raws.before.trim() : "";
object[before + decl.prop] = decl.value;
});
return object;
};
const extractICSS = (css, removeRules = true) => {
const icssImports = {};
const icssExports = {};
css.each(node => {
if (node.type === "rule") {
if (node.selector.slice(0, 7) === ":import") {
const matches = importPattern.exec(node.selector);
if (matches) {
const path = matches[1].replace(/'|"/g, "");
icssImports[path] = Object.assign(icssImports[path] || {}, getDeclsObject(node));
if (removeRules) {
node.remove();
}
}
}
if (node.selector === ":export") {
Object.assign(icssExports, getDeclsObject(node));
if (removeRules) {
node.remove();
}
}
}
});
return {
icssImports,
icssExports
};
};
var _default = extractICSS;
exports.default = _default;
+39
View File
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "replaceValueSymbols", {
enumerable: true,
get: function get() {
return _replaceValueSymbols.default;
}
});
Object.defineProperty(exports, "replaceSymbols", {
enumerable: true,
get: function get() {
return _replaceSymbols.default;
}
});
Object.defineProperty(exports, "extractICSS", {
enumerable: true,
get: function get() {
return _extractICSS.default;
}
});
Object.defineProperty(exports, "createICSSRules", {
enumerable: true,
get: function get() {
return _createICSSRules.default;
}
});
var _replaceValueSymbols = _interopRequireDefault(require("./replaceValueSymbols.js"));
var _replaceSymbols = _interopRequireDefault(require("./replaceSymbols.js"));
var _extractICSS = _interopRequireDefault(require("./extractICSS.js"));
var _createICSSRules = _interopRequireDefault(require("./createICSSRules.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+25
View File
@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _replaceValueSymbols = _interopRequireDefault(require("./replaceValueSymbols.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const replaceSymbols = (css, replacements) => {
css.walk(node => {
if (node.type === "decl") {
node.value = (0, _replaceValueSymbols.default)(node.value, replacements);
} else if (node.type === "rule") {
node.selector = (0, _replaceValueSymbols.default)(node.selector, replacements);
} else if (node.type === "atrule" && ["media", "supports"].includes(node.name.toLowerCase())) {
node.params = (0, _replaceValueSymbols.default)(node.params, replacements);
}
});
};
var _default = replaceSymbols;
exports.default = _default;
@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const matchValueName = /[$]?[\w-]+/g;
const replaceValueSymbols = (value, replacements) => {
let matches;
while (matches = matchValueName.exec(value)) {
const replacement = replacements[matches[0]];
if (replacement) {
value = value.slice(0, matches.index) + replacement + value.slice(matchValueName.lastIndex);
matchValueName.lastIndex -= matches[0].length - replacement.length;
}
}
return value;
};
var _default = replaceValueSymbols;
exports.default = _default;
+113
View File
@@ -0,0 +1,113 @@
{
"_from": "icss-utils@^4.1.0",
"_id": "icss-utils@4.1.0",
"_inBundle": false,
"_integrity": "sha512-3DEun4VOeMvSczifM3F2cKQrDQ5Pj6WKhkOq6HD4QTnDUAq8MQRxy5TX6Sy1iY6WPBe4gQ3p5vTECjbIkglkkQ==",
"_location": "/css-loader/icss-utils",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "icss-utils@^4.1.0",
"name": "icss-utils",
"escapedName": "icss-utils",
"rawSpec": "^4.1.0",
"saveSpec": null,
"fetchSpec": "^4.1.0"
},
"_requiredBy": [
"/css-loader"
],
"_resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-4.1.0.tgz",
"_shasum": "339dbbffb9f8729a243b701e1c29d4cc58c52f0e",
"_spec": "icss-utils@^4.1.0",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\css-loader",
"author": {
"name": "Glen Maddern"
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": 6
}
}
]
]
},
"bugs": {
"url": "https://github.com/css-modules/icss-utils/issues"
},
"bundleDependencies": false,
"dependencies": {
"postcss": "^7.0.14"
},
"deprecated": false,
"description": "ICSS utils for postcss ast",
"devDependencies": {
"@babel/cli": "^7.1.0",
"@babel/core": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.1.0",
"eslint": "^5.14.1",
"husky": "^1.3.1",
"jest": "^24.1.0",
"lint-staged": "^8.1.4",
"prettier": "^1.16.4"
},
"engines": {
"node": ">= 6"
},
"eslintConfig": {
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module"
},
"env": {
"es6": true,
"jest": true
},
"extends": "eslint:recommended"
},
"files": [
"lib"
],
"homepage": "https://github.com/css-modules/icss-utils#readme",
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"keywords": [
"css",
"modules",
"icss",
"postcss"
],
"license": "ISC",
"lint-staged": {
"*.js": [
"prettier --write",
"eslint",
"git add"
]
},
"main": "lib/index.js",
"name": "icss-utils",
"repository": {
"type": "git",
"url": "git+https://github.com/css-modules/icss-utils.git"
},
"scripts": {
"build": "babel --out-dir lib src",
"lint": "eslint . --ignore-path .gitignore",
"prepublish": "yarn test && yarn run build",
"pretest": "npm run lint",
"test": "npm run test:only",
"test:only": "jest"
},
"version": "4.1.0"
}
@@ -0,0 +1,5 @@
Copyright 2015 Glen Maddern
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,79 @@
# CSS Modules: Extract Imports
[![Build Status](https://travis-ci.org/css-modules/postcss-modules-extract-imports.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-extract-imports)
Transforms:
```css
:local(.continueButton) {
composes: button from "library/button.css";
color: green;
}
```
into:
```css
:import("library/button.css") {
button: __tmp_487387465fczSDGHSABb;
}
:local(.continueButton) {
composes: __tmp_487387465fczSDGHSABb;
color: green;
}
```
## Specification
- Only a certain whitelist of properties are inspected. Currently, that whitelist is `['composes']` alone.
- An extend-import has the following format:
```
composes: className [... className] from "path/to/file.css";
```
## Options
- `failOnWrongOrder` `bool` generates exception for unpredictable imports order.
```css
.aa {
composes: b from './b.css';
composes: c from './c.css';
}
.bb {
/* "b.css" should be before "c.css" in this case */
composes: c from './c.css';
composes: b from './b.css';
}
```
## Building
```
npm install
npm test
```
[![Build Status](https://travis-ci.org/css-modules/postcss-modules-extract-imports.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-extract-imports)
* Lines: [![Coverage Status](https://coveralls.io/repos/css-modules/postcss-modules-extract-imports/badge.svg?branch=master)](https://coveralls.io/r/css-modules/postcss-modules-extract-imports?branch=master)
* Statements: [![codecov.io](http://codecov.io/github/css-modules/postcss-modules-extract-imports/coverage.svg?branch=master)](http://codecov.io/github/css-modules/postcss-modules-extract-imports?branch=master)
## Development
- `npm watch` will watch `src` for changes and rebuild
- `npm autotest` will watch `src` and `test` for changes and retest
## License
ISC
## With thanks
- Mark Dalgleish
- Tobias Koppers
- Guy Bedford
---
Glen Maddern, 2015.
@@ -0,0 +1,76 @@
{
"_from": "postcss-modules-extract-imports@^2.0.0",
"_id": "postcss-modules-extract-imports@2.0.0",
"_inBundle": false,
"_integrity": "sha512-LaYLDNS4SG8Q5WAWqIJgdHPJrDDr/Lv775rMBFUbgjTz6j34lUznACHcdRWroPvXANP2Vj7yNK57vp9eFqzLWQ==",
"_location": "/css-loader/postcss-modules-extract-imports",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "postcss-modules-extract-imports@^2.0.0",
"name": "postcss-modules-extract-imports",
"escapedName": "postcss-modules-extract-imports",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/css-loader"
],
"_resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-2.0.0.tgz",
"_shasum": "818719a1ae1da325f9832446b01136eeb493cd7e",
"_spec": "postcss-modules-extract-imports@^2.0.0",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\css-loader",
"author": {
"name": "Glen Maddern"
},
"bugs": {
"url": "https://github.com/css-modules/postcss-modules-extract-imports/issues"
},
"bundleDependencies": false,
"dependencies": {
"postcss": "^7.0.5"
},
"deprecated": false,
"description": "A CSS Modules transform to extract local aliases for inline imports",
"devDependencies": {
"codecov.io": "^0.1.2",
"coveralls": "^2.11.2",
"husky": "^0.13.3",
"jest": "^20.0.3",
"lint-staged": "^3.4.2",
"prettier": "^1.3.1"
},
"engines": {
"node": ">= 6"
},
"files": [
"src"
],
"homepage": "https://github.com/css-modules/postcss-modules-extract-imports",
"keywords": [
"css-modules",
"postcss",
"plugin"
],
"license": "ISC",
"lint-staged": {
"*.js": [
"prettier --single-quote --no-semi --write",
"git add"
]
},
"main": "src/index.js",
"name": "postcss-modules-extract-imports",
"repository": {
"type": "git",
"url": "git+https://github.com/css-modules/postcss-modules-extract-imports.git"
},
"scripts": {
"precommit": "lint-staged",
"prepublish": "yarn run test",
"test": "jest --coverage"
},
"version": "2.0.0"
}
@@ -0,0 +1,180 @@
const postcss = require('postcss')
const topologicalSort = require('./topologicalSort')
const declWhitelist = ['composes']
const declFilter = new RegExp(`^(${declWhitelist.join('|')})$`)
const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/
const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/
const VISITED_MARKER = 1
function createParentName(rule, root) {
return `__${root.index(rule.parent)}_${rule.selector}`
}
function serializeImports(imports) {
return imports.map(importPath => '`' + importPath + '`').join(', ')
}
/**
* :import('G') {}
*
* Rule
* composes: ... from 'A'
* composes: ... from 'B'
* Rule
* composes: ... from 'A'
* composes: ... from 'A'
* composes: ... from 'C'
*
* Results in:
*
* graph: {
* G: [],
* A: [],
* B: ['A'],
* C: ['A'],
* }
*/
function addImportToGraph(importId, parentId, graph, visited) {
const siblingsId = parentId + '_' + 'siblings'
const visitedId = parentId + '_' + importId
if (visited[visitedId] !== VISITED_MARKER) {
if (!Array.isArray(visited[siblingsId])) visited[siblingsId] = []
const siblings = visited[siblingsId]
if (Array.isArray(graph[importId]))
graph[importId] = graph[importId].concat(siblings)
else graph[importId] = siblings.slice()
visited[visitedId] = VISITED_MARKER
siblings.push(importId)
}
}
module.exports = postcss.plugin('modules-extract-imports', function(
options = {}
) {
const failOnWrongOrder = options.failOnWrongOrder
return css => {
const graph = {}
const visited = {}
const existingImports = {}
const importDecls = {}
const imports = {}
let importIndex = 0
const createImportedName = typeof options.createImportedName !== 'function'
? (importName /*, path*/) =>
`i__imported_${importName.replace(/\W/g, '_')}_${importIndex++}`
: options.createImportedName
// Check the existing imports order and save refs
css.walkRules(rule => {
const matches = icssImport.exec(rule.selector)
if (matches) {
const [, /*match*/ doubleQuotePath, singleQuotePath] = matches
const importPath = doubleQuotePath || singleQuotePath
addImportToGraph(importPath, 'root', graph, visited)
existingImports[importPath] = rule
}
})
// Find any declaration that supports imports
css.walkDecls(declFilter, decl => {
let matches = decl.value.match(matchImports)
let tmpSymbols
if (matches) {
let [
,
/*match*/ symbols,
doubleQuotePath,
singleQuotePath,
global
] = matches
if (global) {
// Composing globals simply means changing these classes to wrap them in global(name)
tmpSymbols = symbols.split(/\s+/).map(s => `global(${s})`)
} else {
const importPath = doubleQuotePath || singleQuotePath
const parentRule = createParentName(decl.parent, css)
addImportToGraph(importPath, parentRule, graph, visited)
importDecls[importPath] = decl
imports[importPath] = imports[importPath] || {}
tmpSymbols = symbols.split(/\s+/).map(s => {
if (!imports[importPath][s]) {
imports[importPath][s] = createImportedName(s, importPath)
}
return imports[importPath][s]
})
}
decl.value = tmpSymbols.join(' ')
}
})
const importsOrder = topologicalSort(graph, failOnWrongOrder)
if (importsOrder instanceof Error) {
const importPath = importsOrder.nodes.find(importPath =>
importDecls.hasOwnProperty(importPath)
)
const decl = importDecls[importPath]
const errMsg =
'Failed to resolve order of composed modules ' +
serializeImports(importsOrder.nodes) +
'.'
throw decl.error(errMsg, {
plugin: 'modules-extract-imports',
word: 'composes'
})
}
let lastImportRule
importsOrder.forEach(path => {
const importedSymbols = imports[path]
let rule = existingImports[path]
if (!rule && importedSymbols) {
rule = postcss.rule({
selector: `:import("${path}")`,
raws: { after: '\n' }
})
if (lastImportRule) css.insertAfter(lastImportRule, rule)
else css.prepend(rule)
}
lastImportRule = rule
if (!importedSymbols) return
Object.keys(importedSymbols).forEach(importedSymbol => {
rule.append(
postcss.decl({
value: importedSymbol,
prop: importedSymbols[importedSymbol],
raws: { before: '\n ' }
})
)
})
})
}
})
@@ -0,0 +1,54 @@
const PERMANENT_MARKER = 2
const TEMPORARY_MARKER = 1
function createError(node, graph) {
const er = new Error("Nondeterministic import's order")
const related = graph[node]
const relatedNode = related.find(
relatedNode => graph[relatedNode].indexOf(node) > -1
)
er.nodes = [node, relatedNode]
return er
}
function walkGraph(node, graph, state, result, strict) {
if (state[node] === PERMANENT_MARKER) return
if (state[node] === TEMPORARY_MARKER) {
if (strict) return createError(node, graph)
return
}
state[node] = TEMPORARY_MARKER
const children = graph[node]
const length = children.length
for (let i = 0; i < length; ++i) {
const er = walkGraph(children[i], graph, state, result, strict)
if (er instanceof Error) return er
}
state[node] = PERMANENT_MARKER
result.push(node)
}
function topologicalSort(graph, strict) {
const result = []
const state = {}
const nodes = Object.keys(graph)
const length = nodes.length
for (let i = 0; i < length; ++i) {
const er = walkGraph(nodes[i], graph, state, result, strict)
if (er instanceof Error) return er
}
return result
}
module.exports = topologicalSort
@@ -0,0 +1,100 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [2.0.6] - 2019-03-05
### Fixed
- handles properly selector with escaping characters (like: `.\31 a2b3c { color: red }`)
## [2.0.5] - 2019-02-06
### Fixed
- Path to `index.js`
## [2.0.4] - 2019-01-04
### Fixed
- Inappropriate modification of `steps` function arguments
## [2.0.3] - 2018-12-21
### Fixed
- Don't modify inappropriate animation keywords
## [2.0.2] - 2018-12-05
### Fixed
- Don't break unicode characters.
## [2.0.1] - 2018-11-23
### Fixed
- Handle uppercase `keyframes` at rule.
## [2.0.0] - 2018-11-23
### Changed
- Drop support `nodejs@4`.
- Update `postcss` version to `7`.
## [0.0.11] - 2015-07-19
### Fixed
- Localisation of animation properties.
## [0.0.10] - 2015-06-17
### Added
- Localised at-rules.
## [0.0.9] - 2015-06-12
### Changed
- Using global selectors outside of a global context no longer triggers warnings. Instead, this functionality will be provided by a CSS Modules linter.
### Fixed
- Keyframe rules.
## [0.0.8] - 2015-06-11
### Added
- Pure mode where only local scope is allowed.
### Changed
- Using global selectors outside of a global context now triggers warnings.
## [0.0.7] - 2015-05-30
### Changed
- Migrated to `css-selector-tokenizer`.
## [0.0.6] - 2015-05-28
### Changed
- Renamed project to `postcss-modules-local-by-default`.
## [0.0.5] - 2015-05-22
### Added
- Support for css-loader [inheritance](https://github.com/webpack/css-loader#inheriting) and [local imports](https://github.com/webpack/css-loader#importing-local-class-names).
## [0.0.4] - 2015-05-22
### Changed
- Hide global leak detection behind undocumented `lint` option until it's more robust.
## [0.0.3] - 2015-05-22
### Changed
- Transformer output now uses the new `:local(.identifier)` syntax.
### Added
- Simple global leak detection. Non-local selectors like `input{}` and `[data-foobar]` now throw when not marked as global.
## [0.0.2] - 2015-05-14
### Added
- Support for global selectors appended directly to locals, e.g. `.foo:global(.bar)`
## 0.0.1 - 2015-05-12
### Added
- Automatic local classes
- Explicit global selectors with `:global`
[unreleased]: https://github.com/postcss-modules-local-by-default/compare/v0.0.10...HEAD
[0.0.2]: https://github.com/postcss-modules-local-by-default/compare/v0.0.1...v0.0.2
[0.0.3]: https://github.com/postcss-modules-local-by-default/compare/v0.0.2...v0.0.3
[0.0.4]: https://github.com/postcss-modules-local-by-default/compare/v0.0.3...v0.0.4
[0.0.5]: https://github.com/postcss-modules-local-by-default/compare/v0.0.4...v0.0.5
[0.0.6]: https://github.com/postcss-modules-local-by-default/compare/v0.0.5...v0.0.6
[0.0.7]: https://github.com/postcss-modules-local-by-default/compare/v0.0.6...v0.0.7
[0.0.8]: https://github.com/postcss-modules-local-by-default/compare/v0.0.7...v0.0.8
[0.0.9]: https://github.com/postcss-modules-local-by-default/compare/v0.0.8...v0.0.9
[0.0.10]: https://github.com/postcss-modules-local-by-default/compare/v0.0.9...v0.0.10
[0.0.11]: https://github.com/postcss-modules-local-by-default/compare/v0.0.10...v0.0.11
[2.0.0]: https://github.com/postcss-modules-local-by-default/compare/v1.3.1...v2.0.0
[2.0.1]: https://github.com/postcss-modules-local-by-default/compare/v2.0.0...v2.0.1
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2015 Mark Dalgleish <mark.john.dalgleish@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,65 @@
[![Build Status][ci-img]][ci] [![codecov][codecov-img]][codecov] [![npm][npm-img]][npm]
# CSS Modules: Local by Default
Transformation examples:
```css
.foo { ... } /* => */ :local(.foo) { ... }
.foo .bar { ... } /* => */ :local(.foo) :local(.bar) { ... }
/* Shorthand global selector */
:global .foo .bar { ... } /* => */ .foo .bar { ... }
.foo :global .bar { ... } /* => */ :local(.foo) .bar { ... }
/* Targeted global selector */
:global(.foo) .bar { ... } /* => */ .foo :local(.bar) { ... }
.foo:global(.bar) { ... } /* => */ :local(.foo).bar { ... }
.foo :global(.bar) .baz { ... } /* => */ :local(.foo) .bar :local(.baz) { ... }
.foo:global(.bar) .baz { ... } /* => */ :local(.foo).bar :local(.baz) { ... }
```
## Building
```bash
$ npm install
$ npm test
```
- Build: [![Build Status][ci-img]][ci]
- Lines: [![coveralls][coveralls-img]][coveralls]
- Statements: [![codecov][codecov-img]][codecov]
## Development
```bash
$ npm run autotest
```
## License
MIT
## With thanks
- [Tobias Koppers](https://github.com/sokra)
- [Glen Maddern](https://github.com/geelen)
---
Mark Dalgleish, 2015.
[ci-img]: https://img.shields.io/travis/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square
[ci]: https://travis-ci.org/css-modules/postcss-modules-local-by-default
[npm-img]: https://img.shields.io/npm/v/postcss-modules-local-by-default.svg?style=flat-square
[npm]: https://www.npmjs.com/package/postcss-modules-local-by-default
[coveralls-img]: https://img.shields.io/coveralls/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square
[coveralls]: https://coveralls.io/r/css-modules/postcss-modules-local-by-default?branch=master
[codecov-img]: https://img.shields.io/codecov/c/github/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square
[codecov]: https://codecov.io/github/css-modules/postcss-modules-local-by-default?branch=master
@@ -0,0 +1,502 @@
'use strict';
const postcss = require('postcss');
const selectorParser = require('postcss-selector-parser');
const valueParser = require('postcss-value-parser');
const isSpacing = node => node.type === 'combinator' && node.value === ' ';
function normalizeNodeArray(nodes) {
const array = [];
nodes.forEach(function(x) {
if (Array.isArray(x)) {
normalizeNodeArray(x).forEach(function(item) {
array.push(item);
});
} else if (x) {
array.push(x);
}
});
if (array.length > 0 && isSpacing(array[array.length - 1])) {
array.pop();
}
return array;
}
function localizeNode(rule, mode, options) {
const isScopePseudo = node =>
node.value === ':local' || node.value === ':global';
const transform = (node, context) => {
if (context.ignoreNextSpacing && !isSpacing(node)) {
throw new Error('Missing whitespace after ' + context.ignoreNextSpacing);
}
if (context.enforceNoSpacing && isSpacing(node)) {
throw new Error('Missing whitespace before ' + context.enforceNoSpacing);
}
let newNodes;
switch (node.type) {
case 'root': {
let resultingGlobal;
context.hasPureGlobals = false;
newNodes = node.nodes.map(function(n) {
const nContext = {
global: context.global,
lastWasSpacing: true,
hasLocals: false,
explicit: false,
};
n = transform(n, nContext);
if (typeof resultingGlobal === 'undefined') {
resultingGlobal = nContext.global;
} else if (resultingGlobal !== nContext.global) {
throw new Error(
'Inconsistent rule global/local result in rule "' +
node +
'" (multiple selectors must result in the same mode for the rule)'
);
}
if (!nContext.hasLocals) {
context.hasPureGlobals = true;
}
return n;
});
context.global = resultingGlobal;
node.nodes = normalizeNodeArray(newNodes);
break;
}
case 'selector': {
newNodes = node.map(childNode => transform(childNode, context));
node = node.clone();
node.nodes = normalizeNodeArray(newNodes);
break;
}
case 'combinator': {
if (isSpacing(node)) {
if (context.ignoreNextSpacing) {
context.ignoreNextSpacing = false;
context.lastWasSpacing = false;
context.enforceNoSpacing = false;
return null;
}
context.lastWasSpacing = true;
return node;
}
break;
}
case 'pseudo': {
let childContext;
const isNested = !!node.length;
const isScoped = isScopePseudo(node);
// :local(.foo)
if (isNested) {
if (isScoped) {
if (context.inside) {
throw new Error(
`A ${node.value} is not allowed inside of a ${
context.inside
}(...)`
);
}
childContext = {
global: node.value === ':global',
inside: node.value,
hasLocals: false,
explicit: true,
};
newNodes = node
.map(childNode => transform(childNode, childContext))
.reduce((acc, next) => acc.concat(next.nodes), []);
if (newNodes.length) {
const { before, after } = node.spaces;
const first = newNodes[0];
const last = newNodes[newNodes.length - 1];
first.spaces = { before, after: first.spaces.after };
last.spaces = { before: last.spaces.before, after };
}
node = newNodes;
break;
} else {
childContext = {
global: context.global,
inside: context.inside,
lastWasSpacing: true,
hasLocals: false,
explicit: context.explicit,
};
newNodes = node.map(childNode =>
transform(childNode, childContext)
);
node = node.clone();
node.nodes = normalizeNodeArray(newNodes);
if (childContext.hasLocals) {
context.hasLocals = true;
}
}
break;
//:local .foo .bar
} else if (isScoped) {
if (context.inside) {
throw new Error(
`A ${node.value} is not allowed inside of a ${
context.inside
}(...)`
);
}
const addBackSpacing = !!node.spaces.before;
context.ignoreNextSpacing = context.lastWasSpacing
? node.value
: false;
context.enforceNoSpacing = context.lastWasSpacing
? false
: node.value;
context.global = node.value === ':global';
context.explicit = true;
// because this node has spacing that is lost when we remove it
// we make up for it by adding an extra combinator in since adding
// spacing on the parent selector doesn't work
return addBackSpacing
? selectorParser.combinator({ value: ' ' })
: null;
}
break;
}
case 'id':
case 'class': {
if (!context.global) {
const innerNode = node.clone();
innerNode.spaces = { before: '', after: '' };
node = selectorParser.pseudo({
value: ':local',
nodes: [innerNode],
spaces: node.spaces,
});
context.hasLocals = true;
}
break;
}
}
context.lastWasSpacing = false;
context.ignoreNextSpacing = false;
context.enforceNoSpacing = false;
return node;
};
const rootContext = {
global: mode === 'global',
hasPureGlobals: false,
};
rootContext.selector = selectorParser(root => {
transform(root, rootContext);
}).processSync(rule, { updateSelector: false, lossless: true });
return rootContext;
}
function localizeDeclNode(node, context) {
switch (node.type) {
case 'word':
if (context.localizeNextItem) {
node.value = ':local(' + node.value + ')';
context.localizeNextItem = false;
}
break;
case 'function':
if (
context.options &&
context.options.rewriteUrl &&
node.value.toLowerCase() === 'url'
) {
node.nodes.map(nestedNode => {
if (nestedNode.type !== 'string' && nestedNode.type !== 'word') {
return;
}
let newUrl = context.options.rewriteUrl(
context.global,
nestedNode.value
);
switch (nestedNode.type) {
case 'string':
if (nestedNode.quote === "'") {
newUrl = newUrl.replace(/(\\)/g, '\\$1').replace(/'/g, "\\'");
}
if (nestedNode.quote === '"') {
newUrl = newUrl.replace(/(\\)/g, '\\$1').replace(/"/g, '\\"');
}
break;
case 'word':
newUrl = newUrl.replace(/("|'|\)|\\)/g, '\\$1');
break;
}
nestedNode.value = newUrl;
});
}
break;
}
return node;
}
function isWordAFunctionArgument(wordNode, functionNode) {
return functionNode
? functionNode.nodes.some(
functionNodeChild =>
functionNodeChild.sourceIndex === wordNode.sourceIndex
)
: false;
}
function localizeAnimationShorthandDeclValues(decl, context) {
const validIdent = /^-?[_a-z][_a-z0-9-]*$/i;
/*
The spec defines some keywords that you can use to describe properties such as the timing
function. These are still valid animation names, so as long as there is a property that accepts
a keyword, it is given priority. Only when all the properties that can take a keyword are
exhausted can the animation name be set to the keyword. I.e.
animation: infinite infinite;
The animation will repeat an infinite number of times from the first argument, and will have an
animation name of infinite from the second.
*/
const animationKeywords = {
$alternate: 1,
'$alternate-reverse': 1,
$backwards: 1,
$both: 1,
$ease: 1,
'$ease-in': 1,
'$ease-in-out': 1,
'$ease-out': 1,
$forwards: 1,
$infinite: 1,
$linear: 1,
$none: Infinity, // No matter how many times you write none, it will never be an animation name
$normal: 1,
$paused: 1,
$reverse: 1,
$running: 1,
'$step-end': 1,
'$step-start': 1,
$initial: Infinity,
$inherit: Infinity,
$unset: Infinity,
};
const didParseAnimationName = false;
let parsedAnimationKeywords = {};
let stepsFunctionNode = null;
const valueNodes = valueParser(decl.value).walk(node => {
/* If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh. */
if (node.type === 'div') {
parsedAnimationKeywords = {};
}
if (node.type === 'function' && node.value.toLowerCase() === 'steps') {
stepsFunctionNode = node;
}
const value =
node.type === 'word' && !isWordAFunctionArgument(node, stepsFunctionNode)
? node.value.toLowerCase()
: null;
let shouldParseAnimationName = false;
if (!didParseAnimationName && value && validIdent.test(value)) {
if ('$' + value in animationKeywords) {
parsedAnimationKeywords['$' + value] =
'$' + value in parsedAnimationKeywords
? parsedAnimationKeywords['$' + value] + 1
: 0;
shouldParseAnimationName =
parsedAnimationKeywords['$' + value] >=
animationKeywords['$' + value];
} else {
shouldParseAnimationName = true;
}
}
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: shouldParseAnimationName && !context.global,
};
return localizeDeclNode(node, subContext);
});
decl.value = valueNodes.toString();
}
function localizeDeclValues(localize, decl, context) {
const valueNodes = valueParser(decl.value);
valueNodes.walk((node, index, nodes) => {
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: localize && !context.global,
};
nodes[index] = localizeDeclNode(node, subContext);
});
decl.value = valueNodes.toString();
}
function localizeDecl(decl, context) {
const isAnimation = /animation$/i.test(decl.prop);
if (isAnimation) {
return localizeAnimationShorthandDeclValues(decl, context);
}
const isAnimationName = /animation(-name)?$/i.test(decl.prop);
if (isAnimationName) {
return localizeDeclValues(true, decl, context);
}
const hasUrl = /url\(/i.test(decl.value);
if (hasUrl) {
return localizeDeclValues(false, decl, context);
}
}
module.exports = postcss.plugin('postcss-modules-local-by-default', function(
options
) {
if (typeof options !== 'object') {
options = {}; // If options is undefined or not an object the plugin fails
}
if (options && options.mode) {
if (
options.mode !== 'global' &&
options.mode !== 'local' &&
options.mode !== 'pure'
) {
throw new Error(
'options.mode must be either "global", "local" or "pure" (default "local")'
);
}
}
const pureMode = options && options.mode === 'pure';
const globalMode = options && options.mode === 'global';
return function(css) {
css.walkAtRules(function(atrule) {
if (/keyframes$/i.test(atrule.name)) {
const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(atrule.params);
const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(atrule.params);
let globalKeyframes = globalMode;
if (globalMatch) {
if (pureMode) {
throw atrule.error(
'@keyframes :global(...) is not allowed in pure mode'
);
}
atrule.params = globalMatch[1];
globalKeyframes = true;
} else if (localMatch) {
atrule.params = localMatch[0];
globalKeyframes = false;
} else if (!globalMode) {
atrule.params = ':local(' + atrule.params + ')';
}
atrule.walkDecls(function(decl) {
localizeDecl(decl, {
options: options,
global: globalKeyframes,
});
});
} else if (atrule.nodes) {
atrule.nodes.forEach(function(decl) {
if (decl.type === 'decl') {
localizeDecl(decl, {
options: options,
global: globalMode,
});
}
});
}
});
css.walkRules(function(rule) {
if (
rule.parent.type === 'atrule' &&
/keyframes$/i.test(rule.parent.name)
) {
// ignore keyframe rules
return;
}
if (
rule.nodes &&
rule.selector.slice(0, 2) === '--' &&
rule.selector.slice(-1) === ':'
) {
// ignore custom property set
return;
}
const context = localizeNode(rule, options.mode);
context.options = options;
if (pureMode && context.hasPureGlobals) {
throw rule.error(
'Selector "' +
rule.selector +
'" is not pure ' +
'(pure selectors must contain at least one local class or id)'
);
}
rule.selector = context.selector;
// Less-syntax mixins parse as rules with no nodes
if (rule.nodes) {
rule.nodes.forEach(decl => localizeDecl(decl, context));
}
});
};
});
@@ -0,0 +1,82 @@
{
"_from": "postcss-modules-local-by-default@^2.0.6",
"_id": "postcss-modules-local-by-default@2.0.6",
"_inBundle": false,
"_integrity": "sha512-oLUV5YNkeIBa0yQl7EYnxMgy4N6noxmiwZStaEJUSe2xPMcdNc8WmBQuQCx18H5psYbVxz8zoHk0RAAYZXP9gA==",
"_location": "/css-loader/postcss-modules-local-by-default",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "postcss-modules-local-by-default@^2.0.6",
"name": "postcss-modules-local-by-default",
"escapedName": "postcss-modules-local-by-default",
"rawSpec": "^2.0.6",
"saveSpec": null,
"fetchSpec": "^2.0.6"
},
"_requiredBy": [
"/css-loader"
],
"_resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-2.0.6.tgz",
"_shasum": "dd9953f6dd476b5fd1ef2d8830c8929760b56e63",
"_spec": "postcss-modules-local-by-default@^2.0.6",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\css-loader",
"author": {
"name": "Mark Dalgleish"
},
"bugs": {
"url": "https://github.com/css-modules/postcss-modules-local-by-default/issues"
},
"bundleDependencies": false,
"dependencies": {
"postcss": "^7.0.6",
"postcss-selector-parser": "^6.0.0",
"postcss-value-parser": "^3.3.1"
},
"deprecated": false,
"description": "A CSS Modules transform to make local scope the default",
"devDependencies": {
"chokidar-cli": "^1.0.1",
"codecov.io": "^0.1.2",
"coveralls": "^3.0.2",
"eslint": "^5.9.0",
"istanbul": "^0.4.5",
"tape": "^4.0.0"
},
"engines": {
"node": ">= 6"
},
"files": [
"index.js"
],
"homepage": "https://github.com/css-modules/postcss-modules-local-by-default#readme",
"keywords": [
"css-modules",
"postcss",
"css",
"postcss-plugin"
],
"license": "MIT",
"main": "index.js",
"name": "postcss-modules-local-by-default",
"prettier": {
"singleQuote": true,
"trailingComma": "es5"
},
"repository": {
"type": "git",
"url": "git+https://github.com/css-modules/postcss-modules-local-by-default.git"
},
"scripts": {
"autotest": "chokidar index.js test.js -c 'yarn test'",
"cover": "istanbul cover test.js",
"lint": "eslint index.js test.js",
"precover": "yarn lint",
"prepublish": "yarn test",
"pretest": "yarn lint",
"test": "tape test.js",
"travis": "yarn lint && yarn cover -- --report lcovonly"
},
"version": "2.0.6"
}
@@ -0,0 +1,9 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [2.1.0] - 2019-03-05
### Fixed
- handles properly selector with escaping characters (like: `.\31 a2b3c { color: red }`)
### Feature
- `generateExportEntry` option (allow to setup key and value for `:export {}` rule)
+7
View File
@@ -0,0 +1,7 @@
ISC License (ISC)
Copyright (c) 2015, Glen Maddern
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+100
View File
@@ -0,0 +1,100 @@
# CSS Modules: Scope Locals & Extend
[![Build Status](https://travis-ci.org/css-modules/postcss-modules-scope.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-scope)
Transforms:
```css
:local(.continueButton) {
color: green;
}
```
into:
```css
:export {
continueButton: __buttons_continueButton_djd347adcxz9;
}
.__buttons_continueButton_djd347adcxz9 {
color: green;
}
```
so it doesn't pollute CSS global scope and can be simply used in JS like so:
```js
import styles from './buttons.css'
elem.innerHTML = `<button class="${styles.continueButton}">Continue</button>`
```
## Composition
Since we're exporting class names, there's no reason to export only one. This can give us some really useful reuse of styles:
```css
.globalButtonStyle {
background: white;
border: 1px solid;
border-radius: 0.25rem;
}
.globalButtonStyle:hover {
box-shadow: 0 0 4px -2px;
}
:local(.continueButton) {
compose-with: globalButtonStyle;
color: green;
}
```
becomes:
```
.globalButtonStyle {
background: white;
border: 1px solid;
border-radius: 0.25rem;
}
.globalButtonStyle:hover {
box-shadow: 0 0 4px -2px;
}
:local(.continueButton) {
compose-with: globalButtonStyle;
color: green;
}
```
**Note:** you can also use `composes` as a shorthand for `compose-with`
## Local-by-default & reuse across files
You're looking for [CSS Modules](https://github.com/css-modules/css-modules). It uses this plugin as well as a few others, and it's amazing.
## Building
```
npm install
npm test
```
[![Build Status](https://travis-ci.org/css-modules/postcss-modules-scope.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-scope)
* Lines: [![Coverage Status](https://coveralls.io/repos/css-modules/postcss-modules-scope/badge.svg?branch=master)](https://coveralls.io/r/css-modules/postcss-modules-scope?branch=master)
* Statements: [![codecov.io](http://codecov.io/github/css-modules/postcss-modules-scope/coverage.svg?branch=master)](http://codecov.io/github/css-modules/postcss-modules-scope?branch=master)
## Development
- `npm autotest` will watch `src` and `test` for changes and run the tests, and transpile the ES6 to ES5 on success
## License
ISC
## With thanks
- Mark Dalgleish
- Tobias Koppers
- Guy Bedford
---
Glen Maddern, 2015.
@@ -0,0 +1,81 @@
{
"_from": "postcss-modules-scope@^2.1.0",
"_id": "postcss-modules-scope@2.1.0",
"_inBundle": false,
"_integrity": "sha512-91Rjps0JnmtUB0cujlc8KIKCsJXWjzuxGeT/+Q2i2HXKZ7nBUeF9YQTZZTNvHVoNYj1AthsjnGLtqDUE0Op79A==",
"_location": "/css-loader/postcss-modules-scope",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "postcss-modules-scope@^2.1.0",
"name": "postcss-modules-scope",
"escapedName": "postcss-modules-scope",
"rawSpec": "^2.1.0",
"saveSpec": null,
"fetchSpec": "^2.1.0"
},
"_requiredBy": [
"/css-loader"
],
"_resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-2.1.0.tgz",
"_shasum": "ad3f5bf7856114f6fcab901b0502e2a2bc39d4eb",
"_spec": "postcss-modules-scope@^2.1.0",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\css-loader",
"author": {
"name": "Glen Maddern"
},
"bugs": {
"url": "https://github.com/css-modules/postcss-modules-scope/issues"
},
"bundleDependencies": false,
"dependencies": {
"postcss": "^7.0.6",
"postcss-selector-parser": "^6.0.0"
},
"deprecated": false,
"description": "A CSS Modules transform to extract export statements from local-scope classes",
"devDependencies": {
"chokidar-cli": "^1.0.1",
"codecov.io": "^0.1.2",
"coveralls": "^3.0.2",
"eslint": "^5.9.0",
"mocha": "^6.0.2",
"nyc": "^13.1.0"
},
"engines": {
"node": ">= 6"
},
"files": [
"src"
],
"homepage": "https://github.com/css-modules/postcss-modules-scope",
"keywords": [
"css-modules",
"postcss",
"plugin"
],
"license": "ISC",
"main": "src/index.js",
"name": "postcss-modules-scope",
"prettier": {
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"repository": {
"type": "git",
"url": "git+https://github.com/css-modules/postcss-modules-scope.git"
},
"scripts": {
"autotest": "chokidar src test -c 'yarn test'",
"cover": "nyc mocha",
"lint": "eslint src test",
"precover": "yarn lint",
"prepublish": "yarn run test",
"pretest": "yarn lint",
"test": "mocha",
"travis": "yarn cover"
},
"version": "2.1.0"
}
+297
View File
@@ -0,0 +1,297 @@
'use strict';
const postcss = require('postcss');
const selectorParser = require('postcss-selector-parser');
const hasOwnProperty = Object.prototype.hasOwnProperty;
function getSingleLocalNamesForComposes(root) {
return root.nodes.map(node => {
if (node.type !== 'selector' || node.nodes.length !== 1) {
throw new Error(
`composition is only allowed when selector is single :local class name not in "${root}"`
);
}
node = node.nodes[0];
if (
node.type !== 'pseudo' ||
node.value !== ':local' ||
node.nodes.length !== 1
) {
throw new Error(
'composition is only allowed when selector is single :local class name not in "' +
root +
'", "' +
node +
'" is weird'
);
}
node = node.first;
if (node.type !== 'selector' || node.length !== 1) {
throw new Error(
'composition is only allowed when selector is single :local class name not in "' +
root +
'", "' +
node +
'" is weird'
);
}
node = node.first;
if (node.type !== 'class') {
// 'id' is not possible, because you can't compose ids
throw new Error(
'composition is only allowed when selector is single :local class name not in "' +
root +
'", "' +
node +
'" is weird'
);
}
return node.value;
});
}
const whitespace = '[\\x20\\t\\r\\n\\f]';
const unescapeRegExp = new RegExp(
'\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)',
'ig'
);
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
const high = '0x' + escaped - 0x10000;
// NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace
? escaped
: high < 0
? // BMP codepoint
String.fromCharCode(high + 0x10000)
: // Supplemental Plane codepoint (surrogate pair)
String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
});
}
const processor = postcss.plugin('postcss-modules-scope', function(options) {
return css => {
const generateScopedName =
(options && options.generateScopedName) || processor.generateScopedName;
const generateExportEntry =
(options && options.generateExportEntry) || processor.generateExportEntry;
const exports = Object.create(null);
function exportScopedName(name, rawName) {
const scopedName = generateScopedName(
rawName ? rawName : name,
css.source.input.from,
css.source.input.css
);
const exportEntry = generateExportEntry(
rawName ? rawName : name,
scopedName,
css.source.input.from,
css.source.input.css
);
const { key, value } = exportEntry;
exports[key] = exports[key] || [];
if (exports[key].indexOf(value) < 0) {
exports[key].push(value);
}
return scopedName;
}
function localizeNode(node) {
switch (node.type) {
case 'selector':
node.nodes = node.map(localizeNode);
return node;
case 'class':
return selectorParser.className({
value: exportScopedName(
node.value,
node.raws && node.raws.value ? node.raws.value : null
),
});
case 'id': {
return selectorParser.id({
value: exportScopedName(
node.value,
node.raws && node.raws.value ? node.raws.value : null
),
});
}
}
throw new Error(
`${node.type} ("${node}") is not allowed in a :local block`
);
}
function traverseNode(node) {
switch (node.type) {
case 'pseudo':
if (node.value === ':local') {
if (node.nodes.length !== 1) {
throw new Error('Unexpected comma (",") in :local block');
}
const selector = localizeNode(node.first, node.spaces);
// move the spaces that were around the psuedo selector to the first
// non-container node
selector.first.spaces = node.spaces;
node.replaceWith(selector);
return;
}
/* falls through */
case 'root':
case 'selector': {
node.each(traverseNode);
break;
}
}
return node;
}
// Find any :import and remember imported names
const importedNames = {};
css.walkRules(rule => {
if (/^:import\(.+\)$/.test(rule.selector)) {
rule.walkDecls(decl => {
importedNames[decl.prop] = true;
});
}
});
// Find any :local classes
css.walkRules(rule => {
if (
rule.nodes &&
rule.selector.slice(0, 2) === '--' &&
rule.selector.slice(-1) === ':'
) {
// ignore custom property set
return;
}
let parsedSelector = selectorParser().astSync(rule);
rule.selector = traverseNode(parsedSelector.clone()).toString();
rule.walkDecls(/composes|compose-with/, decl => {
const localNames = getSingleLocalNamesForComposes(parsedSelector);
const classes = decl.value.split(/\s+/);
classes.forEach(className => {
const global = /^global\(([^\)]+)\)$/.exec(className);
if (global) {
localNames.forEach(exportedName => {
exports[exportedName].push(global[1]);
});
} else if (hasOwnProperty.call(importedNames, className)) {
localNames.forEach(exportedName => {
exports[exportedName].push(className);
});
} else if (hasOwnProperty.call(exports, className)) {
localNames.forEach(exportedName => {
exports[className].forEach(item => {
exports[exportedName].push(item);
});
});
} else {
throw decl.error(
`referenced class name "${className}" in ${decl.prop} not found`
);
}
});
decl.remove();
});
rule.walkDecls(decl => {
let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
tokens = tokens.map((token, idx) => {
if (idx === 0 || tokens[idx - 1] === ',') {
const localMatch = /^(\s*):local\s*\((.+?)\)/.exec(token);
if (localMatch) {
return (
localMatch[1] +
exportScopedName(localMatch[2]) +
token.substr(localMatch[0].length)
);
} else {
return token;
}
} else {
return token;
}
});
decl.value = tokens.join('');
});
});
// Find any :local keyframes
css.walkAtRules(atrule => {
if (/keyframes$/i.test(atrule.name)) {
const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atrule.params);
if (localMatch) {
atrule.params = exportScopedName(localMatch[1]);
}
}
});
// If we found any :locals, insert an :export rule
const exportedNames = Object.keys(exports);
if (exportedNames.length > 0) {
const exportRule = postcss.rule({ selector: ':export' });
exportedNames.forEach(exportedName =>
exportRule.append({
prop: exportedName,
value: exports[exportedName].join(' '),
raws: { before: '\n ' },
})
);
css.append(exportRule);
}
};
});
processor.generateScopedName = function(name, path) {
const sanitisedPath = path
.replace(/\.[^\.\/\\]+$/, '')
.replace(/[\W_]+/g, '_')
.replace(/^_|_$/g, '');
return `_${sanitisedPath}__${name}`.trim();
};
processor.generateExportEntry = function(name, scopedName) {
return {
key: unescape(name),
value: unescape(scopedName),
};
};
module.exports = processor;
+7
View File
@@ -0,0 +1,7 @@
ISC License (ISC)
Copyright (c) 2015, Glen Maddern
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+77
View File
@@ -0,0 +1,77 @@
# CSS Modules: Values
Pass arbitrary values between your module files
### Usage
```css
/* colors.css */
@value primary: #BF4040;
@value secondary: #1F4F7F;
.text-primary {
color: primary;
}
.text-secondary {
color: secondary;
}
```
```css
/* breakpoints.css */
@value small: (max-width: 599px);
@value medium: (min-width: 600px) and (max-width: 959px);
@value large: (min-width: 960px);
```
```css
/* my-component.css */
/* alias paths for other values or composition */
@value colors: "./colors.css";
/* import multiple from a single file */
@value primary, secondary from colors;
/* make local aliases to imported values */
@value small as bp-small, large as bp-large from "./breakpoints.css";
.header {
composes: text-primary from colors;
box-shadow: 0 0 10px secondary;
}
@media bp-small {
.header {
box-shadow: 0 0 4px secondary;
}
}
@media bp-large {
.header {
box-shadow: 0 0 20px secondary;
}
}
```
**If you are using Sass** along with this PostCSS plugin, do not use the colon `:` in your `@value` definitions. It will cause Sass to crash.
Note also you can _import_ multiple values at once but can only _define_ one value per line.
```css
@value a: b, c: d; /* defines a as "b, c: d" */
```
### Justification
See [this PR](https://github.com/css-modules/css-modules-loader-core/pull/28) for more background
## License
ISC
## With thanks
- Mark Dalgleish
- Tobias Koppers
- Josh Johnston
---
Glen Maddern, 2015.
@@ -0,0 +1,72 @@
{
"_from": "postcss-modules-values@^2.0.0",
"_id": "postcss-modules-values@2.0.0",
"_inBundle": false,
"_integrity": "sha512-Ki7JZa7ff1N3EIMlPnGTZfUMe69FFwiQPnVSXC9mnn3jozCRBYIxiZd44yJOV2AmabOo4qFf8s0dC/+lweG7+w==",
"_location": "/css-loader/postcss-modules-values",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "postcss-modules-values@^2.0.0",
"name": "postcss-modules-values",
"escapedName": "postcss-modules-values",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/css-loader"
],
"_resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-2.0.0.tgz",
"_shasum": "479b46dc0c5ca3dc7fa5270851836b9ec7152f64",
"_spec": "postcss-modules-values@^2.0.0",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\css-loader",
"author": {
"name": "Glen Maddern"
},
"bugs": {
"url": "https://github.com/css-modules/postcss-modules-values/issues"
},
"bundleDependencies": false,
"dependencies": {
"icss-replace-symbols": "^1.1.0",
"postcss": "^7.0.6"
},
"deprecated": false,
"description": "PostCSS plugin for CSS Modules to pass arbitrary values between your module files",
"devDependencies": {
"chokidar-cli": "^1.0.1",
"codecov.io": "^0.1.2",
"coveralls": "^3.0.2",
"eslint": "^5.9.0",
"mocha": "^5.2.0",
"nyc": "^13.1.0"
},
"files": [
"src"
],
"homepage": "https://github.com/css-modules/postcss-modules-values#readme",
"keywords": [
"css",
"modules",
"postcss"
],
"license": "ISC",
"main": "src/index.js",
"name": "postcss-modules-values",
"repository": {
"type": "git",
"url": "git+https://github.com/css-modules/postcss-modules-values.git"
},
"scripts": {
"autotest": "chokidar src test -c 'npm test'",
"cover": "nyc mocha",
"lint": "eslint src test",
"prepublish": "yarn test",
"pretest": "yarn lint",
"test": "mocha",
"travis": "yarn lint && yarn cover"
},
"version": "2.0.0"
}
@@ -0,0 +1,119 @@
'use strict';
const postcss = require('postcss');
const ICSSReplaceSymbols = require('icss-replace-symbols');
const replaceSymbols = require('icss-replace-symbols');
const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
const matchValueDefinition = /(?:\s+|^)([\w-]+):?\s+(.+?)\s*$/g;
const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
let options = {};
let importIndex = 0;
let createImportedName =
(options && options.createImportedName) ||
((importName /*, path*/) =>
`i__const_${importName.replace(/\W/g, '_')}_${importIndex++}`);
module.exports = postcss.plugin(
'postcss-modules-values',
() => (css, result) => {
const importAliases = [];
const definitions = {};
const addDefinition = atRule => {
let matches;
while ((matches = matchValueDefinition.exec(atRule.params))) {
let [, /*match*/ key, value] = matches;
// Add to the definitions, knowing that values can refer to each other
definitions[key] = replaceSymbols.replaceAll(definitions, value);
atRule.remove();
}
};
const addImport = atRule => {
const matches = matchImports.exec(atRule.params);
if (matches) {
let [, /*match*/ aliases, path] = matches;
// We can use constants for path names
if (definitions[path]) {
path = definitions[path];
}
const imports = aliases
.replace(/^\(\s*([\s\S]+)\s*\)$/, '$1')
.split(/\s*,\s*/)
.map(alias => {
const tokens = matchImport.exec(alias);
if (tokens) {
const [, /*match*/ theirName, myName = theirName] = tokens;
const importedName = createImportedName(myName);
definitions[myName] = importedName;
return { theirName, importedName };
} else {
throw new Error(`@import statement "${alias}" is invalid!`);
}
});
importAliases.push({ path, imports });
atRule.remove();
}
};
/* Look at all the @value statements and treat them as locals or as imports */
css.walkAtRules('value', atRule => {
if (matchImports.exec(atRule.params)) {
addImport(atRule);
} else {
if (atRule.params.indexOf('@value') !== -1) {
result.warn('Invalid value definition: ' + atRule.params);
}
addDefinition(atRule);
}
});
/* We want to export anything defined by now, but don't add it to the CSS yet or
it well get picked up by the replacement stuff */
const exportDeclarations = Object.keys(definitions).map(key =>
postcss.decl({
value: definitions[key],
prop: key,
raws: { before: '\n ' }
})
);
/* If we have no definitions, don't continue */
if (!Object.keys(definitions).length) {
return;
}
/* Perform replacements */
ICSSReplaceSymbols.default(css, definitions);
/* Add export rules if any */
if (exportDeclarations.length > 0) {
const exportRule = postcss.rule({
selector: ':export',
raws: { after: '\n' }
});
exportRule.append(exportDeclarations);
css.prepend(exportRule);
}
/* Add import rules */
importAliases.reverse().forEach(({ path, imports }) => {
const importRule = postcss.rule({
selector: `:import(${path})`,
raws: { after: '\n' }
});
imports.forEach(({ theirName, importedName }) => {
importRule.append({
value: theirName,
prop: importedName,
raws: { before: '\n ' }
});
});
css.prepend(importRule);
});
}
);
+873
View File
@@ -0,0 +1,873 @@
# API Documentation
*Please use only this documented API when working with the parser. Methods
not documented here are subject to change at any point.*
## `parser` function
This is the module's main entry point.
```js
const parser = require('postcss-selector-parser');
```
### `parser([transform], [options])`
Creates a new `processor` instance
```js
const processor = parser();
```
Or, with optional transform function
```js
const transform = selectors => {
selectors.walkUniversals(selector => {
selector.remove();
});
};
const processor = parser(transform)
// Example
const result = processor.processSync('*.class');
// => .class
```
[See processor documentation](#processor)
Arguments:
* `transform (function)`: Provide a function to work with the parsed AST.
* `options (object)`: Provide default options for all calls on the returned `Processor`.
### `parser.attribute([props])`
Creates a new attribute selector.
```js
parser.attribute({attribute: 'href'});
// => [href]
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.className([props])`
Creates a new class selector.
```js
parser.className({value: 'button'});
// => .button
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.combinator([props])`
Creates a new selector combinator.
```js
parser.combinator({value: '+'});
// => +
```
Arguments:
* `props (object)`: The new node's properties.
Notes:
* **Descendant Combinators** The value of descendant combinators created by the
parser always just a single space (`" "`). For descendant selectors with no
comments, additional space is now stored in `node.spaces.before`. Depending
on the location of comments, additional spaces may be stored in
`node.raws.spaces.before`, `node.raws.spaces.after`, or `node.raws.value`.
* **Named Combinators** Although, nonstandard and unlikely to ever become a standard,
named combinators like `/deep/` and `/for/` are parsed as combinators. The
`node.value` is name after being unescaped and normalized as lowercase. The
original value for the combinator name is stored in `node.raws.value`.
### `parser.comment([props])`
Creates a new comment.
```js
parser.comment({value: '/* Affirmative, Dave. I read you. */'});
// => /* Affirmative, Dave. I read you. */
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.id([props])`
Creates a new id selector.
```js
parser.id({value: 'search'});
// => #search
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.nesting([props])`
Creates a new nesting selector.
```js
parser.nesting();
// => &
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.pseudo([props])`
Creates a new pseudo selector.
```js
parser.pseudo({value: '::before'});
// => ::before
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.root([props])`
Creates a new root node.
```js
parser.root();
// => (empty)
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.selector([props])`
Creates a new selector node.
```js
parser.selector();
// => (empty)
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.string([props])`
Creates a new string node.
```js
parser.string();
// => (empty)
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.tag([props])`
Creates a new tag selector.
```js
parser.tag({value: 'button'});
// => button
```
Arguments:
* `props (object)`: The new node's properties.
### `parser.universal([props])`
Creates a new universal selector.
```js
parser.universal();
// => *
```
Arguments:
* `props (object)`: The new node's properties.
## Node types
### `node.type`
A string representation of the selector type. It can be one of the following;
`attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`,
`root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience,
these constants are exposed on the main `parser` as uppercased keys. So for
example you can get `id` by querying `parser.ID`.
```js
parser.attribute({attribute: 'href'}).type;
// => 'attribute'
```
### `node.parent`
Returns the parent node.
```js
root.nodes[0].parent === root;
```
### `node.toString()`, `String(node)`, or `'' + node`
Returns a string representation of the node.
```js
const id = parser.id({value: 'search'});
console.log(String(id));
// => #search
```
### `node.next()` & `node.prev()`
Returns the next/previous child of the parent node.
```js
const next = id.next();
if (next && next.type !== 'combinator') {
throw new Error('Qualified IDs are not allowed!');
}
```
### `node.replaceWith(node)`
Replace a node with another.
```js
const attr = selectors.first.first;
const className = parser.className({value: 'test'});
attr.replaceWith(className);
```
Arguments:
* `node`: The node to substitute the original with.
### `node.remove()`
Removes the node from its parent node.
```js
if (node.type === 'id') {
node.remove();
}
```
### `node.clone()`
Returns a copy of a node, detached from any parent containers that the
original might have had.
```js
const cloned = parser.id({value: 'search'});
String(cloned);
// => #search
```
### `node.isAtPosition(line, column)`
Return a `boolean` indicating whether this node includes the character at the
position of the given line and column. Returns `undefined` if the nodes lack
sufficient source metadata to determine the position.
Arguments:
* `line`: 1-index based line number relative to the start of the selector.
* `column`: 1-index based column number relative to the start of the selector.
### `node.spaces`
Extra whitespaces around the node will be moved into `node.spaces.before` and
`node.spaces.after`. So for example, these spaces will be moved as they have
no semantic meaning:
```css
h1 , h2 {}
```
For descendent selectors, the value is always a single space.
```css
h1 h2 {}
```
Additional whitespace is found in either the `node.spaces.before` and `node.spaces.after` depending on the presence of comments or other whitespace characters. If the actual whitespace does not start or end with a single space, the node's raw value is set to the actual space(s) found in the source.
### `node.source`
An object describing the node's start/end, line/column source position.
Within the following CSS, the `.bar` class node ...
```css
.foo,
.bar {}
```
... will contain the following `source` object.
```js
source: {
start: {
line: 2,
column: 3
},
end: {
line: 2,
column: 6
}
}
```
### `node.sourceIndex`
The zero-based index of the node within the original source string.
Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`.
```css
.foo, .bar, .baz {}
```
## Container types
The `root`, `selector`, and `pseudo` nodes have some helper methods for working
with their children.
### `container.nodes`
An array of the container's children.
```js
// Input: h1 h2
selectors.at(0).nodes.length // => 3
selectors.at(0).nodes[0].value // => 'h1'
selectors.at(0).nodes[1].value // => ' '
```
### `container.first` & `container.last`
The first/last child of the container.
```js
selector.first === selector.nodes[0];
selector.last === selector.nodes[selector.nodes.length - 1];
```
### `container.at(index)`
Returns the node at position `index`.
```js
selector.at(0) === selector.first;
selector.at(0) === selector.nodes[0];
```
Arguments:
* `index`: The index of the node to return.
### `container.atPosition(line, column)`
Returns the node at the source position `index`.
```js
selector.at(0) === selector.first;
selector.at(0) === selector.nodes[0];
```
Arguments:
* `index`: The index of the node to return.
### `container.index(node)`
Return the index of the node within its container.
```js
selector.index(selector.nodes[2]) // => 2
```
Arguments:
* `node`: A node within the current container.
### `container.length`
Proxy to the length of the container's nodes.
```js
container.length === container.nodes.length
```
### `container` Array iterators
The container class provides proxies to certain Array methods; these are:
* `container.map === container.nodes.map`
* `container.reduce === container.nodes.reduce`
* `container.every === container.nodes.every`
* `container.some === container.nodes.some`
* `container.filter === container.nodes.filter`
* `container.sort === container.nodes.sort`
Note that these methods only work on a container's immediate children; recursive
iteration is provided by `container.walk`.
### `container.each(callback)`
Iterate the container's immediate children, calling `callback` for each child.
You may return `false` within the callback to break the iteration.
```js
let className;
selectors.each((selector, index) => {
if (selector.type === 'class') {
className = selector.value;
return false;
}
});
```
Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding
or removing nodes from the container.
Arguments:
* `callback (function)`: A function to call for each node, which receives `node`
and `index` arguments.
### `container.walk(callback)`
Like `container#each`, but will also iterate child nodes as long as they are
`container` types.
```js
selectors.walk((selector, index) => {
// all nodes
});
```
Arguments:
* `callback (function)`: A function to call for each node, which receives `node`
and `index` arguments.
This iterator is safe to use whilst mutating `container.nodes`,
like `container#each`.
### `container.walk` proxies
The container class provides proxy methods for iterating over types of nodes,
so that it is easier to write modules that target specific selectors. Those
methods are:
* `container.walkAttributes`
* `container.walkClasses`
* `container.walkCombinators`
* `container.walkComments`
* `container.walkIds`
* `container.walkNesting`
* `container.walkPseudos`
* `container.walkTags`
* `container.walkUniversals`
### `container.split(callback)`
This method allows you to split a group of nodes by returning `true` from
a callback. It returns an array of arrays, where each inner array corresponds
to the groups that you created via the callback.
```js
// (input) => h1 h2>>h3
const list = selectors.first.split(selector => {
return selector.type === 'combinator';
});
// (node values) => [['h1', ' '], ['h2', '>>'], ['h3']]
```
Arguments:
* `callback (function)`: A function to call for each node, which receives `node`
as an argument.
### `container.prepend(node)` & `container.append(node)`
Add a node to the start/end of the container. Note that doing so will set
the parent property of the node to this container.
```js
const id = parser.id({value: 'search'});
selector.append(id);
```
Arguments:
* `node`: The node to add.
### `container.insertBefore(old, new)` & `container.insertAfter(old, new)`
Add a node before or after an existing node in a container:
```js
selectors.walk(selector => {
if (selector.type !== 'class') {
const className = parser.className({value: 'theme-name'});
selector.parent.insertAfter(selector, className);
}
});
```
Arguments:
* `old`: The existing node in the container.
* `new`: The new node to add before/after the existing node.
### `container.removeChild(node)`
Remove the node from the container. Note that you can also use
`node.remove()` if you would like to remove just a single node.
```js
selector.length // => 2
selector.remove(id)
selector.length // => 1;
id.parent // undefined
```
Arguments:
* `node`: The node to remove.
### `container.removeAll()` or `container.empty()`
Remove all children from the container.
```js
selector.removeAll();
selector.length // => 0
```
## Root nodes
A root node represents a comma separated list of selectors. Indeed, all
a root's `toString()` method does is join its selector children with a ','.
Other than this, it has no special functionality and acts like a container.
### `root.trailingComma`
This will be set to `true` if the input has a trailing comma, in order to
support parsing of legacy CSS hacks.
## Selector nodes
A selector node represents a single complex selector. For example, this
selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes.
It has no special functionality of its own.
## Pseudo nodes
A pseudo selector extends a container node; if it has any parameters of its
own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo
`value` will always contain the colons preceding the pseudo identifier. This
is so that both `:before` and `::before` are properly represented in the AST.
## Attribute nodes
### `attribute.quoted`
Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not.
Remains `undefined` if there is no attribute value.
```css
[href=foo] /* false */
[href='foo'] /* true */
[href="foo"] /* true */
[href] /* undefined */
```
### `attribute.qualifiedAttribute`
Returns the attribute name qualified with the namespace if one is given.
### `attribute.offsetOf(part)`
Returns the offset of the attribute part specified relative to the
start of the node of the output string. This is useful in raising
error messages about a specific part of the attribute, especially
in combination with `attribute.sourceIndex`.
Returns `-1` if the name is invalid or the value doesn't exist in this
attribute.
The legal values for `part` are:
* `"ns"` - alias for "namespace"
* `"namespace"` - the namespace if it exists.
* `"attribute"` - the attribute name
* `"attributeNS"` - the start of the attribute or its namespace
* `"operator"` - the match operator of the attribute
* `"value"` - The value (string or identifier)
* `"insensitive"` - the case insensitivity flag
### `attribute.raws.unquoted`
Returns the unquoted content of the attribute's value.
Remains `undefined` if there is no attribute value.
```css
[href=foo] /* foo */
[href='foo'] /* foo */
[href="foo"] /* foo */
[href] /* undefined */
```
### `attribute.spaces`
Like `node.spaces` with the `before` and `after` values containing the spaces
around the element, the parts of the attribute can also have spaces before
and after them. The for each of `attribute`, `operator`, `value` and
`insensitive` there is corresponding property of the same nam in
`node.spaces` that has an optional `before` or `after` string containing only
whitespace.
Note that corresponding values in `attributes.raws.spaces` contain values
including any comments. If set, these values will override the
`attribute.spaces` value. Take care to remove them if changing
`attribute.spaces`.
### `attribute.raws`
The raws object stores comments and other information necessary to re-render
the node exactly as it was in the source.
If a comment is embedded within the identifiers for the `namespace`, `attribute`
or `value` then a property is placed in the raws for that value containing the full source of the propery including comments.
If a comment is embedded within the space between parts of the attribute
then the raw for that space is set accordingly.
Setting an attribute's property `raws` value to be deleted.
For now, changing the spaces required also updating or removing any of the
raws values that override them.
Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as:
```js
{
attribute: "href",
operatator: "=",
value: "test",
spaces: {
before: '',
after: '',
attribute: { before: ' ', after: ' ' },
operator: { after: ' ' },
value: { after: ' ' },
insensitive: { after: ' ' }
},
raws: {
spaces: {
attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' },
operator: { after: ' /* after-operator */ ' },
value: { after: '/* wow */ /*omg*/' },
insensitive: { after: '/*bbq*/ /*whodoesthis*/' }
},
unquoted: 'test',
value: 'te/*inside-value*/st'
}
}
```
## `Processor`
### `ProcessorOptions`
* `lossless` - When `true`, whitespace is preserved. Defaults to `true`.
* `updateSelector` - When `true`, if any processor methods are passed a postcss
`Rule` node instead of a string, then that Rule's selector is updated
with the results of the processing. Defaults to `true`.
### `process|processSync(selectors, [options])`
Processes the `selectors`, returning a string from the result of processing.
Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.
**Example:**
```js
const parser = require("postcss-selector-parser");
const processor = parser();
let result = processor.processSync(' .class');
console.log(result);
// => .class
// Asynchronous operation
let promise = processor.process(' .class').then(result => {
console.log(result)
// => .class
});
// To have the parser normalize whitespace values, utilize the options
result = processor.processSync(' .class ', {lossless: false});
console.log(result);
// => .class
// For better syntax errors, pass a PostCSS Rule node.
const postcss = require('postcss');
rule = postcss.rule({selector: ' #foo > a, .class '});
processor.process(rule, {lossless: false, updateSelector: true}).then(result => {
console.log(result);
// => #foo>a,.class
console.log("rule:", rule.selector);
// => rule: #foo>a,.class
})
```
Arguments:
* `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule
node.
* `[options] (object)`: Process options
### `ast|astSync(selectors, [options])`
Like `process()` and `processSync()` but after
processing the `selectors` these methods return the `Root` node of the result
instead of a string.
Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.
### `transform|transformSync(selectors, [options])`
Like `process()` and `processSync()` but after
processing the `selectors` these methods return the value returned by the
processor callback.
Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.
### Error Handling Within Selector Processors
The root node passed to the selector processor callback
has a method `error(message, options)` that returns an
error object. This method should always be used to raise
errors relating to the syntax of selectors. The options
to this method are passed to postcss's error constructor
([documentation](http://api.postcss.org/Container.html#error)).
#### Async Error Example
```js
let processor = (root) => {
return new Promise((resolve, reject) => {
root.walkClasses((classNode) => {
if (/^(.*)[-_]/.test(classNode.value)) {
let msg = "classes may not have underscores or dashes in them";
reject(root.error(msg, {
index: classNode.sourceIndex + RegExp.$1.length + 1,
word: classNode.value
}));
}
});
resolve();
});
};
const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
return (root) => {
let promises = [];
root.walkRules(rule => {
promises.push(selectorProcessor.process(rule));
});
return Promise.all(promises);
};
});
postcss(plugin()).process(`
.foo-bar {
color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));
// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
// | ^
// 2 | color: red;
// 3 | }
```
#### Synchronous Error Example
```js
let processor = (root) => {
root.walkClasses((classNode) => {
if (/.*[-_]/.test(classNode.value)) {
let msg = "classes may not have underscores or dashes in them";
throw root.error(msg, {
index: classNode.sourceIndex,
word: classNode.value
});
}
});
};
const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
return (root) => {
root.walkRules(rule => {
selectorProcessor.processSync(rule);
});
};
});
postcss(plugin()).process(`
.foo-bar {
color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));
// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
// | ^
// 2 | color: red;
// 3 | }
```
@@ -0,0 +1,479 @@
# 6.0.2
- Fixed an issue with parsing and stringifying an empty attribute value
# 6.0.1
- Fixed an issue with unicode surrogate pair parsing
# 6.0.0
- Updated: `cssesc` to 3.0.0 (major)
- Fixed: Issues with escaped `id` and `class` selectors
# 5.0.0
- Allow escaped dot within class name.
- Update PostCSS to 7.0.7 (patch)
# 5.0.0-rc.4
- Fixed an issue where comments immediately after an insensitive (in attribute)
were not parsed correctly.
- Updated `cssesc` to 2.0.0 (major).
- Removed outdated integration tests.
- Added tests for custom selectors, tags with attributes, the universal
selector with pseudos, and tokens after combinators.
# 5.0.0-rc.1
To ease adoption of the v5.0 release, we have relaxed the node version
check performed by npm at installation time to allow for node 4, which
remains officially unsupported, but likely to continue working for the
time being.
# 5.0.0-rc.0
This release has **BREAKING CHANGES** that were required to fix regressions
in 4.0.0 and to make the Combinator Node API consistent for all combinator
types. Please read carefully.
## Summary of Changes
* The way a descendent combinator that isn't a single space character (E.g. `.a .b`) is stored in the AST has changed.
* Named Combinators (E.g. `.a /for/ .b`) are now properly parsed as a combinator.
* It is now possible to look up a node based on the source location of a character in that node and to query nodes if they contain some character.
* Several bug fixes that caused the parser to hang and run out of memory when a `/` was encountered have been fixed.
* The minimum supported version of Node is now `v6.0.0`.
### Changes to the Descendent Combinator
In prior releases, the value of a descendant combinator with multiple spaces included all the spaces.
* `.a .b`: Extra spaces are now stored as space before.
- Old & Busted:
- `combinator.value === " "`
- New hotness:
- `combinator.value === " " && combinator.spaces.before === " "`
* `.a /*comment*/.b`: A comment at the end of the combinator causes extra space to become after space.
- Old & Busted:
- `combinator.value === " "`
- `combinator.raws.value === " /*comment/"`
- New hotness:
- `combinator.value === " "`
- `combinator.spaces.after === " "`
- `combinator.raws.spaces.after === " /*comment*/"`
* `.a<newline>.b`: whitespace that doesn't start or end with a single space character is stored as a raw value.
- Old & Busted:
- `combinator.value === "\n"`
- `combinator.raws.value === undefined`
- New hotness:
- `combinator.value === " "`
- `combinator.raws.value === "\n"`
### Support for "Named Combinators"
Although, nonstandard and unlikely to ever become a standard, combinators like `/deep/` and `/for/` are now properly supported.
Because they've been taken off the standardization track, there is no spec-official name for combinators of the form `/<ident>/`. However, I talked to [Tab Atkins](https://twitter.com/tabatkins) and we agreed to call them "named combinators" so now they are called that.
Before this release such named combinators were parsed without intention and generated three nodes of type `"tag"` where the first and last nodes had a value of `"/"`.
* `.a /for/ .b` is parsed as a combinator.
- Old & Busted:
- `root.nodes[0].nodes[1].type === "tag"`
- `root.nodes[0].nodes[1].value === "/"`
- New hotness:
- `root.nodes[0].nodes[1].type === "combinator"`
- `root.nodes[0].nodes[1].value === "/for/"`
* `.a /F\6fR/ .b` escapes are handled and uppercase is normalized.
- Old & Busted:
- `root.nodes[0].nodes[2].type === "tag"`
- `root.nodes[0].nodes[2].value === "F\\6fR"`
- New hotness:
- `root.nodes[0].nodes[1].type === "combinator"`
- `root.nodes[0].nodes[1].value === "/for/"`
- `root.nodes[0].nodes[1].raws.value === "/F\\6fR/"`
### Source position checks and lookups
A new API was added to look up a node based on the source location.
```js
const selectorParser = require("postcss-selector-parser");
// You can find the most specific node for any given character
let combinator = selectorParser.astSync(".a > .b").atPosition(1,4);
combinator.toString() === " > ";
// You can check if a node includes a specific character
// Whitespace surrounding the node that is owned by that node
// is included in the check.
[2,3,4,5,6].map(column => combinator.isAtPosition(1, column));
// => [false, true, true, true, false]
```
# 4.0.0
This release has **BREAKING CHANGES** that were required to fix bugs regarding values with escape sequences. Please read carefully.
* **Identifiers with escapes** - CSS escape sequences are now hidden from the public API by default.
The normal value of a node like a class name or ID, or an aspect of a node such as attribute
selector's value, is unescaped. Escapes representing Non-ascii characters are unescaped into
unicode characters. For example: `bu\tton, .\31 00, #i\2764\FE0Fu, [attr="value is \"quoted\""]`
will parse respectively to the values `button`, `100`, `i❤️u`, `value is "quoted"`.
The original escape sequences for these values can be found in the corresponding property name
in `node.raws`. Where possible, deprecation warnings were added, but the nature
of escape handling makes it impossible to detect what is escaped or not. Our expectation is
that most users are neither expecting nor handling escape sequences in their use of this library,
and so for them, this is a bug fix. Users who are taking care to handle escapes correctly can
now update their code to remove the escape handling and let us do it for them.
* **Mutating values with escapes** - When you make an update to a node property that has escape handling
The value is assumed to be unescaped, and any special characters are escaped automatically and
the corresponding `raws` value is immediately updated. This can result in changes to the original
escape format. Where the exact value of the escape sequence is important there are methods that
allow both values to be set in conjunction. There are a number of new convenience methods for
manipulating values that involve escapes, especially for attributes values where the quote mark
is involved. See https://github.com/postcss/postcss-selector-parser/pull/133 for an extensive
write-up on these changes.
**Upgrade/API Example**
In `3.x` there was no unescape handling and internal consistency of several properties was the caller's job to maintain. It was very easy for the developer
to create a CSS file that did not parse correctly when some types of values
were in use.
```js
const selectorParser = require("postcss-selector-parser");
let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value"});
attr.value; // => "a-value"
attr.toString(); // => [id=a-value]
// Add quotes to an attribute's value.
// All these values have to be set by the caller to be consistent:
// no internal consistency is maintained.
attr.raws.unquoted = attr.value
attr.value = "'" + attr.value + "'";
attr.value; // => "'a-value'"
attr.quoted = true;
attr.toString(); // => "[id='a-value']"
```
In `4.0` there is a convenient API for setting and mutating values
that may need escaping. Especially for attributes.
```js
const selectorParser = require("postcss-selector-parser");
// The constructor requires you specify the exact escape sequence
let className = selectorParser.className({value: "illegal class name", raws: {value: "illegal\\ class\\ name"}});
className.toString(); // => '.illegal\\ class\\ name'
// So it's better to set the value as a property
className = selectorParser.className();
// Most properties that deal with identifiers work like this
className.value = "escape for me";
className.value; // => 'escape for me'
className.toString(); // => '.escape\\ for\\ me'
// emoji and all non-ascii are escaped to ensure it works in every css file.
className.value = "😱🦄😍";
className.value; // => '😱🦄😍'
className.toString(); // => '.\\1F631\\1F984\\1F60D'
// you can control the escape sequence if you want, or do bad bad things
className.setPropertyAndEscape('value', 'xxxx', 'yyyy');
className.value; // => "xxxx"
className.toString(); // => ".yyyy"
// Pass a value directly through to the css output without escaping it.
className.setPropertyWithoutEscape('value', '$REPLACE_ME$');
className.value; // => "$REPLACE_ME$"
className.toString(); // => ".$REPLACE_ME$"
// The biggest changes are to the Attribute class
// passing quoteMark explicitly is required to avoid a deprecation warning.
let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value", quoteMark: null});
attr.toString(); // => "[id=a-value]"
// Get the value with quotes on it and any necessary escapes.
// This is the same as reading attr.value in 3.x.
attr.getQuotedValue(); // => "a-value";
attr.quoteMark; // => null
// Add quotes to an attribute's value.
attr.quoteMark = "'"; // This is all that's required.
attr.toString(); // => "[id='a-value']"
attr.quoted; // => true
// The value is still the same, only the quotes have changed.
attr.value; // => a-value
attr.getQuotedValue(); // => "'a-value'";
// deprecated assignment, no warning because there's no escapes
attr.value = "new-value";
// no quote mark is needed so it is removed
attr.getQuotedValue(); // => "new-value";
// deprecated assignment,
attr.value = "\"a 'single quoted' value\"";
// > (node:27859) DeprecationWarning: Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead.
attr.getQuotedValue(); // => '"a \'single quoted\' value"';
// quote mark inferred from first and last characters.
attr.quoteMark; // => '"'
// setValue takes options to make manipulating the value simple.
attr.setValue('foo', {smart: true});
// foo doesn't require any escapes or quotes.
attr.toString(); // => '[id=foo]'
attr.quoteMark; // => null
// An explicit quote mark can be specified
attr.setValue('foo', {quoteMark: '"'});
attr.toString(); // => '[id="foo"]'
// preserves quote mark by default
attr.setValue('bar');
attr.toString(); // => '[id="bar"]'
attr.quoteMark = null;
attr.toString(); // => '[id=bar]'
// with no arguments, it preserves quote mark even when it's not a great idea
attr.setValue('a value \n that should be quoted');
attr.toString(); // => '[id=a\\ value\\ \\A\\ that\\ should\\ be\\ quoted]'
// smart preservation with a specified default
attr.setValue('a value \n that should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => "[id='a value \\A that should be quoted']"
attr.quoteMark = '"';
// => '[id="a value \\A that should be quoted"]'
// this keeps double quotes because it wants to quote the value and the existing value has double quotes.
attr.setValue('this should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => '[id="this should be quoted"]'
// picks single quotes because the value has double quotes
attr.setValue('a "double quoted" value', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => "[id='a "double quoted" value']"
// setPropertyAndEscape lets you do anything you want. Even things that are a bad idea and illegal.
attr.setPropertyAndEscape('value', 'xxxx', 'the password is 42');
attr.value; // => "xxxx"
attr.toString(); // => "[id=the password is 42]"
// Pass a value directly through to the css output without escaping it.
attr.setPropertyWithoutEscape('value', '$REPLACEMENT$');
attr.value; // => "$REPLACEMENT$"
attr.toString(); // => "[id=$REPLACEMENT$]"
```
# 3.1.2
* Fix: Removed dot-prop dependency since it's no longer written in es5.
# 3.1.1
* Fix: typescript definitions weren't in the published package.
# 3.1.0
* Fixed numerous bugs in attribute nodes relating to the handling of comments
and whitespace. There's significant changes to `attrNode.spaces` and `attrNode.raws` since the `3.0.0` release.
* Added `Attribute#offsetOf(part)` to get the offset location of
attribute parts like `"operator"` and `"value"`. This is most
often added to `Attribute#sourceIndex` for error reporting.
# 3.0.0
## Breaking changes
* Some tweaks to the tokenizer/attribute selector parsing mean that whitespace
locations might be slightly different to the 2.x code.
* Better attribute selector parsing with more validation; postcss-selector-parser
no longer uses regular expressions to parse attribute selectors.
* Added an async API (thanks to @jacobp100); the default `process` API is now
async, and the sync API is now accessed through `processSync` instead.
* `process()` and `processSync()` now return a string instead of the Processor
instance.
* Tweaks handling of Less interpolation (thanks to @jwilsson).
* Removes support for Node 0.12.
## Other changes
* `ast()` and `astSync()` methods have been added to the `Processor`. These
return the `Root` node of the selectors after processing them.
* `transform()` and `transformSync()` methods have been added to the
`Processor`. These return the value returned by the processor callback
after processing the selectors.
* Set the parent when inserting a node (thanks to @chriseppstein).
* Correctly adjust indices when using insertBefore/insertAfter (thanks to @tivac).
* Fixes handling of namespaces with qualified tag selectors.
* `process`, `ast` and `transform` (and their sync variants) now accept a
`postcss` rule node. When provided, better errors are generated and selector
processing is automatically set back to the rule selector (unless the `updateSelector` option is set to `false`.)
* Now more memory efficient when tokenizing selectors.
### Upgrade hints
The pattern of:
`rule.selector = processor.process(rule.selector).result.toString();`
is now:
`processor.processSync(rule)`
# 2.2.3
* Resolves an issue where the parser would not reduce multiple spaces between an
ampersand and another simple selector in lossy mode (thanks to @adam-26).
# 2.2.2
* No longer hangs on an unescaped semicolon; instead the parser will throw
an exception for these cases.
# 2.2.1
* Allows a consumer to specify whitespace tokens when creating a new Node
(thanks to @Semigradsky).
# 2.2.0
* Added a new option to normalize whitespace when parsing the selector string
(thanks to @adam-26).
# 2.1.1
* Better unquoted value handling within attribute selectors
(thanks to @evilebottnawi).
# 2.1.0
* Added: Use string constants for all node types & expose them on the main
parser instance (thanks to @Aweary).
# 2.0.0
This release contains the following breaking changes:
* Renamed all `eachInside` iterators to `walk`. For example, `eachTag` is now
`walkTags`, and `eachInside` is now `walk`.
* Renamed `Node#removeSelf()` to `Node#remove()`.
* Renamed `Container#remove()` to `Container#removeChild()`.
* Renamed `Node#raw` to `Node#raws` (thanks to @davidtheclark).
* Now parses `&` as the *nesting* selector, rather than a *tag* selector.
* Fixes misinterpretation of Sass interpolation (e.g. `#{foo}`) as an
id selector (thanks to @davidtheclark).
and;
* Fixes parsing of attribute selectors with equals signs in them
(e.g. `[data-attr="foo=bar"]`) (thanks to @montmanu).
* Adds `quoted` and `raw.unquoted` properties to attribute nodes
(thanks to @davidtheclark).
# 1.3.3
* Fixes an infinite loop on `)` and `]` tokens when they had no opening pairs.
Now postcss-selector-parser will throw when it encounters these lone tokens.
# 1.3.2
* Now uses plain integers rather than `str.charCodeAt(0)` for compiled builds.
# 1.3.1
* Update flatten to v1.x (thanks to @shinnn).
# 1.3.0
* Adds a new node type, `String`, to fix a crash on selectors such as
`foo:bar("test")`.
# 1.2.1
* Fixes a crash when the parser encountered a trailing combinator.
# 1.2.0
* A more descriptive error is thrown when the parser expects to find a
pseudo-class/pseudo-element (thanks to @ashelley).
* Adds support for line/column locations for selector nodes, as well as a
`Node#sourceIndex` method (thanks to @davidtheclark).
# 1.1.4
* Fixes a crash when a selector started with a `>` combinator. The module will
now no longer throw if a selector has a leading/trailing combinator node.
# 1.1.3
* Fixes a crash on `@` tokens.
# 1.1.2
* Fixes an infinite loop caused by using parentheses in a non-pseudo element
context.
# 1.1.1
* Fixes a crash when a backslash ended a selector string.
# 1.1.0
* Adds support for replacing multiple nodes at once with `replaceWith`
(thanks to @jonathantneal).
* Parser no longer throws on sequential IDs and trailing commas, to support
parsing of selector hacks.
# 1.0.1
* Fixes using `insertAfter` and `insertBefore` during iteration.
# 1.0.0
* Adds `clone` and `replaceWith` methods to nodes.
* Adds `insertBefore` and `insertAfter` to containers.
* Stabilises API.
# 0.0.5
* Fixes crash on extra whitespace inside a pseudo selector's parentheses.
* Adds sort function to the container class.
* Enables the parser to pass its input through without transforming.
* Iteration-safe `each` and `eachInside`.
# 0.0.4
* Tidy up redundant duplication.
* Fixes a bug where the parser would loop infinitely on universal selectors
inside pseudo selectors.
* Adds `length` getter and `eachInside`, `map`, `reduce` to the container class.
* When a selector has been removed from the tree, the root node will no longer
cast it to a string.
* Adds node type iterators to the container class (e.g. `eachComment`).
* Adds filter function to the container class.
* Adds split function to the container class.
* Create new node types by doing `parser.id(opts)` etc.
* Adds support for pseudo classes anywhere in the selector.
# 0.0.3
* Adds `next` and `prev` to the node class.
* Adds `first` and `last` getters to the container class.
* Adds `every` and `some` iterators to the container class.
* Add `empty` alias for `removeAll`.
* Combinators are now types of node.
* Fixes the at method so that it is not an alias for `index`.
* Tidy up creation of new nodes in the parser.
* Refactors how namespaces are handled for consistency & less redundant code.
* Refactors AST to use `nodes` exclusively, and eliminates excessive nesting.
* Fixes nested pseudo parsing.
* Fixes whitespace parsing.
# 0.0.2
* Adds support for namespace selectors.
* Adds support for selectors joined by escaped spaces - such as `.\31\ 0`.
# 0.0.1
* Initial release.
@@ -0,0 +1,22 @@
Copyright (c) Ben Briggs <beneb.info@gmail.com> (http://beneb.info)
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.
+49
View File
@@ -0,0 +1,49 @@
# postcss-selector-parser [![Build Status](https://travis-ci.org/postcss/postcss-selector-parser.svg?branch=master)](https://travis-ci.org/postcss/postcss-selector-parser)
> Selector parser with built in methods for working with selector strings.
## Install
With [npm](https://npmjs.com/package/postcss-selector-parser) do:
```
npm install postcss-selector-parser
```
## Quick Start
```js
const parser = require('postcss-selector-parser');
const transform = selectors => {
selectors.walk(selector => {
// do something with the selector
console.log(String(selector))
});
};
const transformed = parser(transform).processSync('h1, h2, h3');
```
To normalize selector whitespace:
```js
const parser = require('postcss-selector-parser');
const normalized = parser().processSync('h1, h2, h3', {lossless: false});
// -> h1,h2,h3
```
Async support is provided through `parser.process` and will resolve a Promise
with the resulting selector string.
## API
Please see [API.md](API.md).
## Credits
* Huge thanks to Andrey Sitnik (@ai) for work on PostCSS which helped
accelerate this module's development.
## License
MIT
@@ -0,0 +1,477 @@
"use strict";
var _process = _interopRequireDefault(require("process"));
var _attribute = _interopRequireDefault(require("../selectors/attribute"));
var _helpers = require("./util/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_process.default.throwDeprecation = true;
(0, _helpers.test)('attribute selector', '[href]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].type, 'attribute');
t.falsy(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('attribute selector spaces (before)', '[ href]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].spaces.attribute.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].type, 'attribute');
t.falsy(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('attribute selector spaces (after)', '[href ]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].spaces.attribute.after, ' ');
t.deepEqual(tree.nodes[0].nodes[0].type, 'attribute');
t.falsy(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('attribute selector spaces with namespace (both)', '[ foo|bar ]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].ns, 'foo');
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'bar');
t.deepEqual(tree.nodes[0].nodes[0].spaces.attribute.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.attribute.after, ' ');
t.deepEqual(tree.nodes[0].nodes[0].type, 'attribute');
t.falsy(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('attribute selector spaces (both)', '[ href ]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].spaces.attribute.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.attribute.after, ' ');
t.deepEqual(tree.nodes[0].nodes[0].type, 'attribute');
t.falsy(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('multiple attribute selectors', '[href][class][name]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'class');
t.deepEqual(tree.nodes[0].nodes[2].attribute, 'name');
});
(0, _helpers.test)('select elements with or without a namespace', '[*|href]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, '*');
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
});
(0, _helpers.test)('namespace with escapes', '[\\31 \\#\\32 |href]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.namespace, '1#2');
t.deepEqual(attr.raws.namespace, '\\31 \\#\\32 ');
attr.namespace = "foo";
t.deepEqual(attr.namespace, 'foo');
t.deepEqual(attr.raws.namespace, undefined);
attr.namespace = "1";
t.deepEqual(attr.namespace, '1');
t.deepEqual(attr.raws.namespace, '\\31');
});
(0, _helpers.test)('attribute selector with a empty value', '[href=""]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, '');
t.true(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('attribute selector with a value', '[name=james]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'name');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'james');
t.falsy(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('attribute selector with quoted value', '[name="james"]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.attribute, 'name');
t.deepEqual(attr.operator, '=');
t.deepEqual(attr.value, 'james');
t.deepEqual(attr.quoteMark, '"');
t.truthy(attr.quoted);
t.deepEqual(attr.getQuotedValue(), '"james"');
});
(0, _helpers.test)('attribute selector with escaped quote', '[title="Something \\"weird\\""]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.value, 'Something "weird"');
t.deepEqual(attr.getQuotedValue(), '\"Something \\"weird\\"\"');
t.deepEqual(attr.getQuotedValue({
smart: true
}), '\'Something "weird"\'');
t.deepEqual(attr.getQuotedValue({
quoteMark: null
}), 'Something\\ \\"weird\\"');
t.deepEqual(attr.quoteMark, '"');
t.truthy(attr.quoted);
t.deepEqual(attr.raws.value, '"Something \\"weird\\""');
t.deepEqual(tree.toString(), '[title="Something \\"weird\\""]');
});
(0, _helpers.test)('attribute selector with escaped colon', '[ng\\:cloak]', function (t, tree) {
t.deepEqual(tree.toString(), '[ng\\:cloak]');
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.raws.attribute, 'ng\\:cloak');
t.deepEqual(attr.attribute, 'ng:cloak');
});
(0, _helpers.test)('attribute selector with short hex escape', '[ng\\3a cloak]', function (t, tree) {
t.deepEqual(tree.toString(), '[ng\\3a cloak]');
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.raws.attribute, 'ng\\3a cloak');
t.deepEqual(attr.attribute, 'ng:cloak');
});
(0, _helpers.test)('attribute selector with hex escape', '[ng\\00003acloak]', function (t, tree) {
t.deepEqual(tree.toString(), '[ng\\00003acloak]');
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.raws.attribute, 'ng\\00003acloak');
t.deepEqual(attr.attribute, 'ng:cloak');
});
(0, _helpers.test)('assign attribute name requiring escape', '[ng\\:cloak]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
attr.attribute = "ng:foo";
t.deepEqual(attr.raws.attribute, 'ng\\:foo');
t.deepEqual(attr.attribute, 'ng:foo');
t.deepEqual(tree.toString(), '[ng\\:foo]');
});
(0, _helpers.test)('multiple attribute selectors + combinator', '[href][class][name] h1 > h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[2].attribute, 'name');
t.deepEqual(tree.nodes[0].nodes[3].value, ' ');
t.deepEqual(tree.nodes[0].nodes[5].value, '>');
t.deepEqual(tree.nodes[0].nodes[6].value, 'h2');
});
(0, _helpers.test)('attribute, class, combinator', '[href] > h2.test', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[1].value, '>');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
t.deepEqual(tree.nodes[0].nodes[3].value, 'test');
});
(0, _helpers.test)('attribute selector with quoted value & combinator', '[name="james"] > h1', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'james');
t.deepEqual(tree.nodes[0].nodes[0].quoteMark, '"');
t.deepEqual(tree.nodes[0].nodes[1].value, '>');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h1');
});
(0, _helpers.test)('multiple quoted attribute selectors', '[href*="test.com"][rel=\'external\'][id][class~="test"] > [name]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].value, 'test.com');
t.is(tree.nodes[0].nodes[0].quoteMark, '"');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'rel');
t.deepEqual(tree.nodes[0].nodes[1].value, 'external');
t.is(tree.nodes[0].nodes[1].quoteMark, "'");
t.deepEqual(tree.nodes[0].nodes[2].attribute, 'id');
t.falsy(tree.nodes[0].nodes[2].value, 'should not have a value');
t.is(tree.nodes[0].nodes[2].quoteMark, undefined, 'should not have a quoteMark set');
t.deepEqual(tree.nodes[0].nodes[3].attribute, 'class');
t.deepEqual(tree.nodes[0].nodes[3].value, 'test');
t.deepEqual(tree.nodes[0].nodes[3].quoteMark, '"');
t.deepEqual(tree.nodes[0].nodes[4].value, '>');
t.deepEqual(tree.nodes[0].nodes[5].attribute, 'name');
t.falsy(tree.nodes[0].nodes[5].value, 'should not have a value');
t.is(tree.nodes[0].nodes[5].quoteMark, undefined, 'should not have a quoteMark set');
});
(0, _helpers.test)('more attribute operators', '[href*=test],[href^=test],[href$=test],[href|=test]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].operator, '*=');
t.deepEqual(tree.nodes[1].nodes[0].operator, '^=');
t.deepEqual(tree.nodes[2].nodes[0].operator, '$=');
t.deepEqual(tree.nodes[3].nodes[0].operator, '|=');
});
(0, _helpers.test)('attribute selector with quoted value containing "="', '[data-weird-attr="Something=weird"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'Something=weird');
t.is(tree.nodes[0].nodes[0].quoteMark, '"');
t.deepEqual(tree.nodes[0].nodes[0].getQuotedValue(), '"Something=weird"');
});
var selector = '[data-weird-attr*="Something=weird"],' + '[data-weird-attr^="Something=weird"],' + '[data-weird-attr$="Something=weird"],' + '[data-weird-attr|="Something=weird"]';
(0, _helpers.test)('more attribute selector with quoted value containing "="', selector, function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[0].nodes[0].operator, '*=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'Something=weird');
t.deepEqual(tree.nodes[1].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[1].nodes[0].operator, '^=');
t.deepEqual(tree.nodes[1].nodes[0].value, 'Something=weird');
t.deepEqual(tree.nodes[2].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[2].nodes[0].operator, '$=');
t.deepEqual(tree.nodes[2].nodes[0].value, 'Something=weird');
t.deepEqual(tree.nodes[3].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[3].nodes[0].operator, '|=');
t.deepEqual(tree.nodes[3].nodes[0].value, 'Something=weird');
});
(0, _helpers.test)('attribute selector with quoted value containing multiple "="', '[data-weird-attr="Something=weird SomethingElse=weirder"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'Something=weird SomethingElse=weirder');
});
selector = '[data-weird-attr*="Something=weird SomethingElse=weirder"],' + '[data-weird-attr^="Something=weird SomethingElse=weirder"],' + '[data-weird-attr$="Something=weird SomethingElse=weirder"],' + '[data-weird-attr|="Something=weird SomethingElse=weirder"]';
(0, _helpers.test)('more attribute selector with quoted value containing multiple "="', selector, function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[0].nodes[0].operator, '*=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'Something=weird SomethingElse=weirder');
t.deepEqual(tree.nodes[1].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[1].nodes[0].operator, '^=');
t.deepEqual(tree.nodes[1].nodes[0].value, 'Something=weird SomethingElse=weirder');
t.deepEqual(tree.nodes[2].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[2].nodes[0].operator, '$=');
t.deepEqual(tree.nodes[2].nodes[0].value, 'Something=weird SomethingElse=weirder');
t.deepEqual(tree.nodes[3].nodes[0].attribute, 'data-weird-attr');
t.deepEqual(tree.nodes[3].nodes[0].operator, '|=');
t.deepEqual(tree.nodes[3].nodes[0].value, 'Something=weird SomethingElse=weirder');
});
(0, _helpers.test)('multiple attribute selectors with quoted value containing "="', '[data-weird-foo="foo=weird"][data-weird-bar="bar=weird"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo=weird');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[0].nodes[1].operator, '=');
t.deepEqual(tree.nodes[0].nodes[1].value, 'bar=weird');
});
(0, _helpers.test)('multiple attribute selectors with value containing escaped "="', '[data-weird-foo=foo\\=weird][data-weird-bar=bar\\3d weird]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo=weird');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[0].nodes[1].operator, '=');
t.deepEqual(tree.nodes[0].nodes[1].value, 'bar=weird');
});
selector = '[data-weird-foo*="foo2=weirder"][data-weird-bar*="bar2=weirder"],' + '[data-weird-foo^="foo2=weirder"][data-weird-bar^="bar2=weirder"],' + '[data-weird-foo$="foo2=weirder"][data-weird-bar$="bar2=weirder"],' + '[data-weird-foo|="foo2=weirder"][data-weird-bar|="bar2=weirder"]';
(0, _helpers.test)('more multiple attribute selectors with quoted value containing "="', selector, function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[0].nodes[0].operator, '*=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo2=weirder');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[0].nodes[1].operator, '*=');
t.deepEqual(tree.nodes[0].nodes[1].value, 'bar2=weirder');
t.deepEqual(tree.nodes[1].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[1].nodes[0].operator, '^=');
t.deepEqual(tree.nodes[1].nodes[0].value, 'foo2=weirder');
t.deepEqual(tree.nodes[1].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[1].nodes[1].operator, '^=');
t.deepEqual(tree.nodes[1].nodes[1].value, 'bar2=weirder');
t.deepEqual(tree.nodes[2].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[2].nodes[0].operator, '$=');
t.deepEqual(tree.nodes[2].nodes[0].value, 'foo2=weirder');
t.deepEqual(tree.nodes[2].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[2].nodes[1].operator, '$=');
t.deepEqual(tree.nodes[2].nodes[1].value, 'bar2=weirder');
t.deepEqual(tree.nodes[3].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[3].nodes[0].operator, '|=');
t.deepEqual(tree.nodes[3].nodes[0].value, 'foo2=weirder');
t.deepEqual(tree.nodes[3].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[3].nodes[1].operator, '|=');
t.deepEqual(tree.nodes[3].nodes[1].value, 'bar2=weirder');
});
(0, _helpers.test)('multiple attribute selectors with quoted value containing multiple "="', '[data-weird-foo="foo1=weirder foo2=weirder"][data-weird-bar="bar1=weirder bar2=weirder"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo1=weirder foo2=weirder');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[0].nodes[1].operator, '=');
t.deepEqual(tree.nodes[0].nodes[1].value, 'bar1=weirder bar2=weirder');
});
selector = '[data-weird-foo*="foo1=weirder foo2=weirder"][data-weird-bar*="bar1=weirder bar2=weirder"],' + '[data-weird-foo^="foo1=weirder foo2=weirder"][data-weird-bar^="bar1=weirder bar2=weirder"],' + '[data-weird-foo$="foo1=weirder foo2=weirder"][data-weird-bar$="bar1=weirder bar2=weirder"],' + '[data-weird-foo|="foo1=weirder foo2=weirder"][data-weird-bar|="bar1=weirder bar2=weirder"]';
(0, _helpers.test)('more multiple attribute selectors with quoted value containing multiple "="', selector, function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[0].nodes[0].operator, '*=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo1=weirder foo2=weirder');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[0].nodes[1].operator, '*=');
t.deepEqual(tree.nodes[0].nodes[1].value, 'bar1=weirder bar2=weirder');
t.deepEqual(tree.nodes[1].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[1].nodes[0].operator, '^=');
t.deepEqual(tree.nodes[1].nodes[0].value, 'foo1=weirder foo2=weirder');
t.deepEqual(tree.nodes[1].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[1].nodes[1].operator, '^=');
t.deepEqual(tree.nodes[1].nodes[1].value, 'bar1=weirder bar2=weirder');
t.deepEqual(tree.nodes[2].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[2].nodes[0].operator, '$=');
t.deepEqual(tree.nodes[2].nodes[0].value, 'foo1=weirder foo2=weirder');
t.deepEqual(tree.nodes[2].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[2].nodes[1].operator, '$=');
t.deepEqual(tree.nodes[2].nodes[1].value, 'bar1=weirder bar2=weirder');
t.deepEqual(tree.nodes[3].nodes[0].attribute, 'data-weird-foo');
t.deepEqual(tree.nodes[3].nodes[0].operator, '|=');
t.deepEqual(tree.nodes[3].nodes[0].value, 'foo1=weirder foo2=weirder');
t.deepEqual(tree.nodes[3].nodes[1].attribute, 'data-weird-bar');
t.deepEqual(tree.nodes[3].nodes[1].operator, '|=');
t.deepEqual(tree.nodes[3].nodes[1].value, 'bar1=weirder bar2=weirder');
});
(0, _helpers.test)('spaces in attribute selectors', 'h1[ href *= "test" ]', function (t, tree) {
var attr = tree.nodes[0].nodes[1];
t.deepEqual(attr.attribute, 'href');
t.deepEqual(attr.spaces.attribute.before, ' ');
t.deepEqual(attr.spaces.attribute.after, ' ');
t.deepEqual(attr.operator, '*=');
t.deepEqual(attr.spaces.operator.after, ' ');
t.deepEqual(attr.value, 'test');
t.deepEqual(attr.spaces.value.after, ' ');
t.truthy(tree.nodes[0].nodes[1].quoted);
});
(0, _helpers.test)('insensitive attribute selector 1', '[href="test" i]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
t.deepEqual(tree.nodes[0].nodes[0].insensitive, true);
t.deepEqual(tree.nodes[0].nodes[0].insensitive, true);
});
(0, _helpers.test)('insensitive attribute selector with a empty value', '[href="" i]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, '');
t.deepEqual(tree.nodes[0].nodes[0].insensitive, true);
t.true(tree.nodes[0].nodes[0].quoted);
});
(0, _helpers.test)('insensitive attribute selector 2', '[href=TEsT i ]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'TEsT');
t.deepEqual(tree.nodes[0].nodes[0].insensitive, true);
t.deepEqual(tree.nodes[0].nodes[0].spaces.value.after, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.insensitive.after, ' ');
});
(0, _helpers.test)('insensitive attribute selector 3', '[href=test i]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
t.deepEqual(tree.nodes[0].nodes[0].insensitive, true);
});
(0, _helpers.test)('capitalized insensitive attribute selector 3', '[href=test I]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
t.deepEqual(tree.nodes[0].nodes[0].insensitive, true);
});
(0, _helpers.test)('extraneous non-combinating whitespace', ' [href] , [class] ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.after, ' ');
t.deepEqual(tree.nodes[1].nodes[0].attribute, 'class');
t.deepEqual(tree.nodes[1].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[1].nodes[0].spaces.after, ' ');
});
(0, _helpers.test)('comments within attribute selectors', '[href/* wow */=/* wow */test]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
t.deepEqual(tree.nodes[0].nodes[0].raws.attribute, 'href/* wow */');
t.deepEqual(tree.nodes[0].nodes[0].raws.operator, '=/* wow */');
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
});
(0, _helpers.test)('comments within attribute selectors (2)', '[/* wow */href=test/* wow */]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
t.deepEqual(tree.nodes[0].nodes[0].raws.spaces.attribute.before, '/* wow */');
t.deepEqual(tree.nodes[0].nodes[0].operator, '=');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'test/* wow */');
});
(0, _helpers.test)('comments within attribute selectors (3)', '[href=test/* wow */i]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
t.deepEqual(tree.nodes[0].nodes[0].value, 'testi');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'test/* wow */i');
t.falsy(tree.nodes[0].nodes[0].insensitive);
});
(0, _helpers.test)('comments within attribute selectors (4)', '[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
t.deepEqual(attr.attribute, 'href');
t.deepEqual(attr.value, 'test');
t.deepEqual(attr.getQuotedValue(), 'test');
t.deepEqual(attr.raws.value, 'te/*inside-value*/st');
t.deepEqual(attr.raws.spaces.value.after, '/* wow */ /*omg*/');
t.truthy(attr.insensitive);
t.deepEqual(attr.offsetOf("attribute"), 13);
t.deepEqual(attr.offsetOf("operator"), 35);
t.deepEqual(attr.offsetOf("insensitive"), 95);
t.deepEqual(attr.raws.spaces.insensitive.after, '/*bbq*/ /*whodoesthis*/');
attr.value = "foo";
t.is(attr.raws.value, undefined);
});
(0, _helpers.test)('non standard modifiers', '[href="foo" y]', function (t, tree) {
var attr = tree.atPosition(1, 13);
t.deepEqual(attr.insensitive, false);
t.deepEqual(attr.insensitiveFlag, '');
t.deepEqual(attr.raws.insensitiveFlag, 'y');
t.deepEqual(tree.toString(), '[href="foo" y]');
});
(0, _helpers.test)('comment after insensitive(non space)', '[href="foo" i/**/]', function (t, tree) {
// https://github.com/postcss/postcss-selector-parser/issues/150
var attr = tree.atPosition(1, 13);
t.deepEqual(attr.insensitive, true);
t.deepEqual(attr.insensitiveFlag, 'i');
t.is(attr.raws.insensitiveFlag, undefined);
t.deepEqual(attr.raws.spaces.insensitive.after, '/**/');
t.deepEqual(tree.toString(), '[href="foo" i/**/]');
});
(0, _helpers.test)('comment after insensitive(space after)', '[href="foo" i/**/ ]', function (t, tree) {
var attr = tree.atPosition(1, 13);
t.deepEqual(attr.insensitive, true);
t.deepEqual(attr.insensitiveFlag, 'i');
t.deepEqual(attr.raws.spaces.insensitive.after, '/**/ ');
t.deepEqual(tree.toString(), '[href="foo" i/**/ ]');
});
(0, _helpers.test)('comment after insensitive(space before)', '[href="foo" i /**/]', function (t, tree) {
var attr = tree.atPosition(1, 13);
t.deepEqual(attr.insensitive, true);
t.deepEqual(attr.insensitiveFlag, 'i');
t.deepEqual(attr.raws.spaces.insensitive.after, ' /**/');
t.deepEqual(tree.toString(), '[href="foo" i /**/]');
});
var testDeprecation = (0, _helpers.nodeVersionAtLeast)('7.0.0') || (0, _helpers.nodeVersionBefore)('6.0.0') ? _helpers.test : _helpers.test.skip;
testDeprecation('deprecated constructor', '', function (t) {
t.throws(function () {
return new _attribute.default({
value: '"foo"',
attribute: "data-bar"
});
}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
});
testDeprecation('deprecated get of raws.unquoted ', '', function (t) {
t.throws(function () {
var attr = new _attribute.default({
value: 'foo',
quoteMark: '"',
attribute: "data-bar"
});
return attr.raws.unquoted;
}, "attr.raws.unquoted is deprecated. Call attr.value instead.");
});
testDeprecation('deprecated set of raws.unquoted ', '', function (t) {
t.throws(function () {
var attr = new _attribute.default({
value: 'foo',
quoteMark: '"',
attribute: "data-bar"
});
attr.raws.unquoted = 'fooooo';
}, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.");
});
testDeprecation('smart quotes', '[data-foo=bar]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
attr.setValue('changed', {
quoteMark: '"'
});
t.deepEqual(attr.toString(), '[data-foo="changed"]');
attr.setValue('changed again', {
quoteMark: "'",
preferCurrentQuoteMark: true
});
t.deepEqual(attr.toString(), '[data-foo="changed again"]');
attr.setValue('smart-ident', {
smart: true
});
t.deepEqual(attr.toString(), '[data-foo=smart-ident]');
attr.setValue('smart quoted', {
smart: true
});
t.deepEqual(attr.toString(), '[data-foo=smart\\ quoted]');
attr.setValue('smart quoted three spaces', {
smart: true
});
t.deepEqual(attr.toString(), '[data-foo="smart quoted three spaces"]');
attr.setValue('smart quoted three spaces', {
smart: true,
quoteMark: "'"
});
t.deepEqual(attr.toString(), "[data-foo='smart quoted three spaces']");
attr.setValue("smart with 'single quotes'", {
smart: true
});
t.deepEqual(attr.toString(), "[data-foo=\"smart with 'single quotes'\"]");
attr.setValue('smart with "double quotes"', {
smart: true
});
t.deepEqual(attr.toString(), "[data-foo='smart with \"double quotes\"']");
});
testDeprecation('set Attribute#quoteMark', '[data-foo=bar]', function (t, tree) {
var attr = tree.nodes[0].nodes[0];
attr.quoteMark = '"';
t.deepEqual(attr.toString(), '[data-foo="bar"]');
attr.quoteMark = "'";
t.deepEqual(attr.toString(), "[data-foo='bar']");
attr.quoteMark = null;
t.deepEqual(attr.toString(), "[data-foo=bar]");
attr.value = "has space";
t.deepEqual(attr.toString(), "[data-foo=has\\ space]");
attr.quoteMark = '"';
t.deepEqual(attr.toString(), '[data-foo="has space"]');
});
@@ -0,0 +1,216 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('class name', '.one', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'one');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('multiple class names', '.one.two.three', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'one');
t.deepEqual(tree.nodes[0].nodes[1].value, 'two');
t.deepEqual(tree.nodes[0].nodes[2].value, 'three');
});
(0, _helpers.test)('qualified class', 'button.btn-primary', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[1].type, 'class');
});
(0, _helpers.test)('escaped numbers in class name', '.\\31\\ 0', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].value, '1 0');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\31\\ 0');
});
(0, _helpers.test)('extraneous non-combinating whitespace', ' .h1 , .h2 ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.after, ' ');
t.deepEqual(tree.nodes[1].nodes[0].value, 'h2');
t.deepEqual(tree.nodes[1].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[1].nodes[0].spaces.after, ' ');
});
(0, _helpers.test)('Less interpolation within a class', '.foo@{bar}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.length, 1);
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo@{bar}');
});
(0, _helpers.test)('ClassName#set value', ".fo\\o", function (t, selectors) {
var className = selectors.first.first;
t.deepEqual(className.raws, {
value: "fo\\o"
});
className.value = "bar";
t.deepEqual(className.raws, {});
});
(0, _helpers.test)('escaped dot in class name', '.foo\\.bar', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo.bar');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'foo\\.bar');
});
(0, _helpers.test)('class selector with escaping', '.♥', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '♥');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (1)', '.©', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '©');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (2)', '.“‘’”', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '“‘’”');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (3)', '.☺☃', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '☺☃');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (4)', '.⌘⌥', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '⌘⌥');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (5)', '.𝄞♪♩♫♬', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '𝄞♪♩♫♬');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (6)', '.💩', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '💩');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('class selector with escaping (7)', '.\\?', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '?');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\?');
});
(0, _helpers.test)('class selector with escaping (8)', '.\\@', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '@');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\@');
});
(0, _helpers.test)('class selector with escaping (9)', '.\\.', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '.');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\.');
});
(0, _helpers.test)('class selector with escaping (10)', '.\\3A \\)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':)');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A \\)');
});
(0, _helpers.test)('class selector with escaping (11)', '.\\3A \\`\\(', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':`(');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A \\`\\(');
});
(0, _helpers.test)('class selector with escaping (12)', '.\\31 23', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '123');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\31 23');
});
(0, _helpers.test)('class selector with escaping (13)', '.\\31 a2b3c', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '1a2b3c');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\31 a2b3c');
});
(0, _helpers.test)('class selector with escaping (14)', '.\\<p\\>', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '<p>');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\<p\\>');
});
(0, _helpers.test)('class selector with escaping (15)', '.\\<\\>\\<\\<\\<\\>\\>\\<\\>', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '<><<<>><>');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\<\\>\\<\\<\\<\\>\\>\\<\\>');
});
(0, _helpers.test)('class selector with escaping (16)', '.\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\[\\>\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\>\\+\\<\\<\\<\\<\\-\\]\\>\\+\\+\\.\\>\\+\\.\\+\\+\\+\\+\\+\\+\\+\\.\\.\\+\\+\\+\\.\\>\\+\\+\\.\\<\\<\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\.\\>\\.\\+\\+\\+\\.\\-\\-\\-\\-\\-\\-\\.\\-\\-\\-\\-\\-\\-\\-\\-\\.\\>\\+\\.\\>\\.', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\[\\>\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\>\\+\\<\\<\\<\\<\\-\\]\\>\\+\\+\\.\\>\\+\\.\\+\\+\\+\\+\\+\\+\\+\\.\\.\\+\\+\\+\\.\\>\\+\\+\\.\\<\\<\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\.\\>\\.\\+\\+\\+\\.\\-\\-\\-\\-\\-\\-\\.\\-\\-\\-\\-\\-\\-\\-\\-\\.\\>\\+\\.\\>\\.');
});
(0, _helpers.test)('class selector with escaping (17)', '.\\#', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '#');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#');
});
(0, _helpers.test)('class selector with escaping (18)', '.\\#\\#', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '##');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#\\#');
});
(0, _helpers.test)('class selector with escaping (19)', '.\\#\\.\\#\\.\\#', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '#.#.#');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#\\.\\#\\.\\#');
});
(0, _helpers.test)('class selector with escaping (20)', '.\\_', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '_');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\_');
});
(0, _helpers.test)('class selector with escaping (21)', '.\\{\\}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '{}');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\{\\}');
});
(0, _helpers.test)('class selector with escaping (22)', '.\\#fake\\-id', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '#fake-id');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#fake\\-id');
});
(0, _helpers.test)('class selector with escaping (23)', '.foo\\.bar', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo.bar');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'foo\\.bar');
});
(0, _helpers.test)('class selector with escaping (24)', '.\\3A hover', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':hover');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A hover');
});
(0, _helpers.test)('class selector with escaping (25)', '.\\3A hover\\3A focus\\3A active', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':hover:focus:active');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A hover\\3A focus\\3A active');
});
(0, _helpers.test)('class selector with escaping (26)', '.\\[attr\\=value\\]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '[attr=value]');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\[attr\\=value\\]');
});
(0, _helpers.test)('class selector with escaping (27)', '.f\\/o\\/o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f/o/o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\/o\\/o');
});
(0, _helpers.test)('class selector with escaping (28)', '.f\\\\o\\\\o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f\\o\\o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\\\o\\\\o');
});
(0, _helpers.test)('class selector with escaping (29)', '.f\\*o\\*o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f*o*o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\*o\\*o');
});
(0, _helpers.test)('class selector with escaping (30)', '.f\\!o\\!o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f!o!o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\!o\\!o');
});
(0, _helpers.test)('class selector with escaping (31)', '.f\\\'o\\\'o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f\'o\'o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\\'o\\\'o');
});
(0, _helpers.test)('class selector with escaping (32)', '.f\\~o\\~o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f~o~o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\~o\\~o');
});
(0, _helpers.test)('class selector with escaping (33)', '.f\\+o\\+o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f+o+o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\+o\\+o');
});
(0, _helpers.test)('class selector with escaping (34)', '.\\1D306', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '𝌆');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\1D306');
});
@@ -0,0 +1,148 @@
"use strict";
var _types = require("../selectors/types");
var _helpers = require("./util/helpers");
(0, _helpers.test)('multiple combinating spaces', 'h1 h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].value, ' ');
t.deepEqual(tree.nodes[0].nodes[1].toString(), ' ');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
});
(0, _helpers.test)('column combinator', '.selected||td', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'selected');
t.deepEqual(tree.nodes[0].nodes[1].value, '||');
t.deepEqual(tree.nodes[0].nodes[2].value, 'td');
});
(0, _helpers.test)('column combinator (2)', '.selected || td', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'selected');
t.deepEqual(tree.nodes[0].nodes[1].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[1].value, '||');
t.deepEqual(tree.nodes[0].nodes[1].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[2].value, 'td');
});
(0, _helpers.test)('descendant combinator', 'h1 h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].value, ' ');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
});
(0, _helpers.test)('multiple descendant combinators', 'h1 h2 h3 h4', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, ' ', 'should have a combinator');
t.deepEqual(tree.nodes[0].nodes[3].value, ' ', 'should have a combinator');
t.deepEqual(tree.nodes[0].nodes[5].value, ' ', 'should have a combinator');
});
(0, _helpers.test)('adjacent sibling combinator', 'h1~h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].value, '~');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
});
(0, _helpers.test)('adjacent sibling combinator (2)', 'h1 ~h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[1].value, '~');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
});
(0, _helpers.test)('adjacent sibling combinator (3)', 'h1~ h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].value, '~');
t.deepEqual(tree.nodes[0].nodes[1].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
});
(0, _helpers.test)('adjacent sibling combinator (4)', 'h1 ~ h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[1].value, '~');
t.deepEqual(tree.nodes[0].nodes[1].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
});
(0, _helpers.test)('adjacent sibling combinator (5)', 'h1~h2~h3', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[1].value, '~');
t.deepEqual(tree.nodes[0].nodes[2].value, 'h2');
t.deepEqual(tree.nodes[0].nodes[3].value, '~');
t.deepEqual(tree.nodes[0].nodes[4].value, 'h3');
});
(0, _helpers.test)('piercing combinator', '.a >>> .b', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'a');
t.deepEqual(tree.nodes[0].nodes[1].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[1].value, '>>>');
t.deepEqual(tree.nodes[0].nodes[1].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[2].value, 'b');
});
(0, _helpers.test)('named combinators', 'a /deep/ b', function (t, tree) {
var nodes = tree.nodes[0].nodes;
t.deepEqual(nodes[0].value, 'a');
t.deepEqual(nodes[1].type, _types.COMBINATOR);
t.deepEqual(nodes[1].toString(), ' /deep/ ');
t.deepEqual(nodes[1].value, '/deep/');
t.deepEqual(nodes[2].value, 'b');
});
(0, _helpers.test)('named combinators with escapes', 'a /dee\\p/ b', function (t, tree) {
var nodes = tree.nodes[0].nodes;
t.deepEqual(nodes[0].value, 'a');
t.deepEqual(nodes[1].type, _types.COMBINATOR);
t.deepEqual(nodes[1].toString(), ' /dee\\p/ ');
t.deepEqual(nodes[1].value, '/deep/');
t.deepEqual(nodes[2].value, 'b');
});
(0, _helpers.test)('named combinators with escapes and uppercase', 'a /DeE\\p/ b', function (t, tree) {
var nodes = tree.nodes[0].nodes;
t.deepEqual(nodes[0].value, 'a');
t.deepEqual(nodes[1].type, _types.COMBINATOR);
t.deepEqual(nodes[1].toString(), ' /DeE\\p/ ');
t.deepEqual(nodes[1].value, '/deep/');
t.deepEqual(nodes[2].value, 'b');
});
(0, _helpers.test)('multiple combinators', 'h1~h2>h3', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, '~', 'should have a combinator');
t.deepEqual(tree.nodes[0].nodes[3].value, '>', 'should have a combinator');
});
(0, _helpers.test)('multiple combinators with whitespaces', 'h1 + h2 > h3', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, '+', 'should have a combinator');
t.deepEqual(tree.nodes[0].nodes[3].value, '>', 'should have a combinator');
});
(0, _helpers.test)('multiple combinators with whitespaces (2)', 'h1+ h2 >h3', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, '+', 'should have a combinator');
t.deepEqual(tree.nodes[0].nodes[3].value, '>', 'should have a combinator');
});
(0, _helpers.test)('trailing combinator & spaces', 'p + ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'p', 'should be a paragraph');
t.deepEqual(tree.nodes[0].nodes[1].value, '+', 'should have a combinator');
});
(0, _helpers.test)('trailing sibling combinator', 'p ~', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'p', 'should be a paragraph');
t.deepEqual(tree.nodes[0].nodes[1].value, '~', 'should have a combinator');
});
(0, _helpers.test)('ending in comment has no trailing combinator', ".bar /* comment 3 */", function (t, tree) {
var nodeTypes = tree.nodes[0].map(function (n) {
return n.type;
});
t.deepEqual(nodeTypes, ["class"]);
});
(0, _helpers.test)('The combinating space is not a space character', ".bar\n.baz", function (t, tree) {
var nodeTypes = tree.nodes[0].map(function (n) {
return n.type;
});
t.deepEqual(nodeTypes, ["class", "combinator", "class"]);
t.deepEqual(tree.nodes[0].nodes[1].value, ' ', 'should have a combinator');
t.deepEqual(tree.nodes[0].nodes[1].raws.value, '\n', 'should have a raw combinator value');
});
(0, _helpers.test)('with spaces and a comment has only one combinator', ".bar /* comment 3 */ > .foo", function (t, tree) {
var nodeTypes = tree.nodes[0].map(function (n) {
return n.type;
});
t.deepEqual(nodeTypes, ["class", "combinator", "class"]);
});
(0, _helpers.test)('with a meaningful comment in the middle of a compound selector', "div/* wtf */.foo", function (t, tree) {
var nodeTypes = tree.nodes[0].map(function (n) {
return n.type;
});
t.deepEqual(nodeTypes, ["tag", "comment", "class"]);
});
(0, _helpers.test)('with a comment in the middle of a descendant selector', "div/* wtf */ .foo", function (t, tree) {
var nodeTypes = tree.nodes[0].map(function (n) {
return n.type;
});
t.deepEqual(nodeTypes, ["tag", "comment", "combinator", "class"]);
});
@@ -0,0 +1,38 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('comments', '/*test comment*/h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '/*test comment*/');
t.deepEqual(tree.nodes[0].nodes[1].value, 'h2');
});
(0, _helpers.test)('comments (2)', '.a /*test comment*/label', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[1].type, 'combinator');
t.deepEqual(tree.nodes[0].nodes[1].value, ' ');
t.deepEqual(tree.nodes[0].nodes[1].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[1].rawSpaceAfter, ' /*test comment*/');
t.deepEqual(tree.nodes[0].nodes[2].type, 'tag');
});
(0, _helpers.test)('comments (3)', '.a /*test comment*/ label', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[1].type, 'combinator');
t.deepEqual(tree.nodes[0].nodes[1].value, ' ');
t.deepEqual(tree.nodes[0].nodes[1].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[1].rawSpaceBefore, ' /*test comment*/ ');
t.deepEqual(tree.nodes[0].nodes[2].type, 'tag');
});
(0, _helpers.test)('multiple comments and other things', 'h1/*test*/h2/*test*/.test/*test*/', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag', 'should have a tag');
t.deepEqual(tree.nodes[0].nodes[1].type, 'comment', 'should have a comment');
t.deepEqual(tree.nodes[0].nodes[2].type, 'tag', 'should have a tag');
t.deepEqual(tree.nodes[0].nodes[3].type, 'comment', 'should have a comment');
t.deepEqual(tree.nodes[0].nodes[4].type, 'class', 'should have a class name');
t.deepEqual(tree.nodes[0].nodes[5].type, 'comment', 'should have a comment');
});
(0, _helpers.test)('ending in comment', ".bar /* comment 3 */", function (t, tree) {
var classname = tree.nodes[0].nodes[0];
t.deepEqual(classname.type, 'class', 'should have a tag');
t.deepEqual(classname.spaces.after, ' ');
t.deepEqual(classname.raws.spaces.after, ' /* comment 3 */');
});
@@ -0,0 +1,393 @@
"use strict";
var _ava = _interopRequireDefault(require("ava"));
var _ = _interopRequireDefault(require(".."));
var _helpers = require("./util/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _ava.default)('container#append', function (t) {
var out = (0, _helpers.parse)('h1', function (selectors) {
var selector = selectors.first;
var clone = selector.first.clone({
value: 'h2'
});
selectors.append(clone);
});
t.deepEqual(out, 'h1,h2');
});
(0, _ava.default)('container#prepend', function (t) {
var out = (0, _helpers.parse)('h2', function (selectors) {
var selector = selectors.first;
var clone = selector.first.clone({
value: 'h1'
});
selectors.prepend(clone);
});
t.deepEqual(out, 'h1,h2');
});
(0, _ava.default)('container#each', function (t) {
var str = '';
(0, _helpers.parse)('h1, h2:not(h3, h4)', function (selectors) {
selectors.each(function (selector) {
if (selector.first.type === 'tag') {
str += selector.first.value;
}
});
});
t.deepEqual(str, 'h1h2');
});
(0, _ava.default)('container#each (safe iteration)', function (t) {
var out = (0, _helpers.parse)('.x, .y', function (selectors) {
selectors.each(function (selector) {
selector.parent.insertBefore(selector, _.default.className({
value: 'b'
}));
selector.parent.insertAfter(selector, _.default.className({
value: 'a'
}));
});
});
t.deepEqual(out, '.b,.x,.a,.b, .y,.a');
});
(0, _ava.default)('container#each (early exit)', function (t) {
var str = '';
(0, _helpers.parse)('h1, h2, h3, h4', function (selectors) {
var eachReturn = selectors.each(function (selector) {
var tag = selector.first.value;
str += tag;
return tag !== 'h2';
});
t.false(eachReturn);
});
t.deepEqual(str, 'h1h2');
});
(0, _ava.default)('container#walk', function (t) {
var str = '';
(0, _helpers.parse)('h1, h2:not(h3, h4)', function (selectors) {
selectors.walk(function (selector) {
if (selector.type === 'tag') {
str += selector.value;
}
});
});
t.deepEqual(str, 'h1h2h3h4');
});
(0, _ava.default)('container#walk (safe iteration)', function (t) {
var out = (0, _helpers.parse)('[class] + *[href] *:not(*.green)', function (selectors) {
selectors.walkUniversals(function (selector) {
var next = selector.next();
if (next && next.type !== 'combinator') {
selector.remove();
}
});
});
t.deepEqual(out, '[class] + [href] :not(.green)');
});
(0, _ava.default)('container#walk (early exit)', function (t) {
var str = '';
(0, _helpers.parse)('h1, h2:not(h3, h4)', function (selectors) {
var walkReturn = selectors.walk(function (selector) {
if (selector.type === 'tag') {
var tag = selector.value;
str += tag;
return tag !== 'h3';
}
});
t.false(walkReturn);
});
t.deepEqual(str, 'h1h2h3');
});
(0, _ava.default)('container#walkAttribute', function (t) {
var out = (0, _helpers.parse)('[href][class].class', function (selectors) {
selectors.walkAttributes(function (attr) {
if (attr.attribute === 'class') {
attr.remove();
}
});
});
t.deepEqual(out, '[href].class');
});
(0, _ava.default)('container#walkClass', function (t) {
var out = (0, _helpers.parse)('.one, .two, .three:not(.four, .five)', function (selectors) {
selectors.walkClasses(function (className) {
className.value = className.value.slice(0, 1);
});
});
t.deepEqual(out, '.o, .t, .t:not(.f, .f)');
});
(0, _ava.default)('container#walkCombinator', function (t) {
var out = (0, _helpers.parse)('h1 h2 h3 h4', function (selectors) {
selectors.walkCombinators(function (comment) {
comment.remove();
});
});
t.deepEqual(out, 'h1h2h3h4');
});
(0, _ava.default)('container#walkComment', function (t) {
var out = (0, _helpers.parse)('.one/*test*/.two', function (selectors) {
selectors.walkComments(function (comment) {
comment.remove();
});
});
t.deepEqual(out, '.one.two');
});
(0, _ava.default)('container#walkId', function (t) {
var out = (0, _helpers.parse)('h1#one, h2#two', function (selectors) {
selectors.walkIds(function (id) {
id.value = id.value.slice(0, 1);
});
});
t.deepEqual(out, 'h1#o, h2#t');
});
(0, _ava.default)('container#walkNesting', function (t) {
var out = (0, _helpers.parse)('& h1', function (selectors) {
selectors.walkNesting(function (node) {
node.replaceWith(_.default.tag({
value: 'body'
}));
});
});
t.deepEqual(out, 'body h1');
});
(0, _ava.default)('container#walkPseudo', function (t) {
var out = (0, _helpers.parse)('a:before, a:after', function (selectors) {
selectors.walkPseudos(function (pseudo) {
pseudo.value = pseudo.value.slice(0, 2);
});
});
t.deepEqual(out, 'a:b, a:a');
});
(0, _ava.default)('container#walkTag', function (t) {
var out = (0, _helpers.parse)('1 2 3', function (selectors) {
selectors.walkTags(function (tag) {
tag.value = 'h' + tag.value;
});
});
t.deepEqual(out, 'h1 h2 h3');
});
(0, _ava.default)('container#walkUniversal', function (t) {
var out = (0, _helpers.parse)('*.class,*.class,*.class', function (selectors) {
selectors.walkUniversals(function (universal) {
universal.remove();
});
});
t.deepEqual(out, '.class,.class,.class');
});
(0, _ava.default)('container#map', function (t) {
(0, _helpers.parse)('1 2 3', function (selectors) {
var arr = selectors.first.map(function (selector) {
if (/[0-9]/.test(selector.value)) {
return 'h' + selector.value;
}
return selector.value;
});
t.deepEqual(arr, ['h1', ' ', 'h2', ' ', 'h3']);
});
});
(0, _ava.default)('container#every', function (t) {
(0, _helpers.parse)('.one.two.three', function (selectors) {
var allClasses = selectors.first.every(function (selector) {
return selector.type === 'class';
});
t.truthy(allClasses);
});
});
(0, _ava.default)('container#some', function (t) {
(0, _helpers.parse)('one#two.three', function (selectors) {
var someClasses = selectors.first.some(function (selector) {
return selector.type === 'class';
});
t.truthy(someClasses);
});
});
(0, _ava.default)('container#reduce', function (t) {
(0, _helpers.parse)('h1, h2, h3, h4', function (selectors) {
var str = selectors.reduce(function (memo, selector) {
if (selector.first.type === 'tag') {
memo += selector.first.value;
}
return memo;
}, '');
t.deepEqual(str, 'h1h2h3h4');
});
});
(0, _ava.default)('container#filter', function (t) {
(0, _helpers.parse)('h1, h2, c1, c2', function (selectors) {
var ast = selectors.filter(function (selector) {
return ~selector.first.value.indexOf('h');
});
t.deepEqual(String(ast), 'h1, h2');
});
});
(0, _ava.default)('container#split', function (t) {
(0, _helpers.parse)('h1 h2 >> h3', function (selectors) {
var list = selectors.first.split(function (selector) {
return selector.value === '>>';
}).map(function (group) {
return group.map(String);
});
t.deepEqual(list, [['h1', ' ', 'h2', ' >> '], ['h3']]);
t.deepEqual(list.length, 2);
});
});
(0, _ava.default)('container#sort', function (t) {
var out = (0, _helpers.parse)('h2,h3,h1,h4', function (selectors) {
selectors.sort(function (a, b) {
return a.first.value.slice(-1) - b.first.value.slice(-1);
});
});
t.deepEqual(out, 'h1,h2,h3,h4');
});
(0, _ava.default)('container#at', function (t) {
(0, _helpers.parse)('h1, h2, h3', function (selectors) {
t.deepEqual(selectors.at(1).first.value, 'h2');
});
});
(0, _ava.default)('container#first, container#last', function (t) {
(0, _helpers.parse)('h1, h2, h3, h4', function (selectors) {
t.deepEqual(selectors.first.first.value, 'h1');
t.deepEqual(selectors.last.last.value, 'h4');
});
});
(0, _ava.default)('container#index', function (t) {
(0, _helpers.parse)('h1 h2 h3', function (selectors) {
var middle = selectors.first.at(1);
t.deepEqual(selectors.first.index(middle), 1);
});
});
(0, _ava.default)('container#length', function (t) {
(0, _helpers.parse)('h1, h2, h3', function (selectors) {
t.deepEqual(selectors.length, 3);
});
});
(0, _ava.default)('container#removeChild', function (t) {
var out = (0, _helpers.parse)('h1.class h2.class h3.class', function (selectors) {
selectors.walk(function (selector) {
if (selector.type === 'class') {
selector.parent.removeChild(selector);
}
});
});
t.deepEqual(out, 'h1 h2 h3');
});
(0, _ava.default)('container#removeAll, container#empty', function (t) {
var wipe = function wipe(method) {
return function (selectors) {
return selectors[method]();
};
};
var out1 = (0, _helpers.parse)('h1 h2, h2 h3, h3 h4', wipe('empty'));
var out2 = (0, _helpers.parse)('h1 h2, h2 h3, h3 h4', wipe('removeAll'));
t.deepEqual(out1, '');
t.deepEqual(out2, '');
});
(0, _ava.default)('container#insertBefore', function (t) {
var out = (0, _helpers.parse)('h2', function (selectors) {
var selector = selectors.first;
var clone = selector.first.clone({
value: 'h1'
});
selectors.insertBefore(selector, clone);
});
t.deepEqual(out, 'h1,h2');
});
(0, _ava.default)('container#insertBefore and node#remove', function (t) {
var out = (0, _helpers.parse)('h2', function (selectors) {
var selector = selectors.first;
var newSel = _.default.tag({
value: 'h1'
});
selectors.insertBefore(selector, newSel);
newSel.remove();
});
t.deepEqual(out, 'h2');
});
(0, _ava.default)('container#insertAfter', function (t) {
var out = (0, _helpers.parse)('h1', function (selectors) {
var selector = selectors.first;
var clone = selector.first.clone({
value: 'h2'
});
selectors.insertAfter(selector, clone);
});
t.deepEqual(out, 'h1,h2');
});
(0, _ava.default)('container#insertAfter and node#remove', function (t) {
var out = (0, _helpers.parse)('h2', function (selectors) {
var selector = selectors.first;
var newSel = _.default.tag({
value: 'h1'
});
selectors.insertAfter(selector, newSel);
newSel.remove();
});
t.deepEqual(out, 'h2');
});
(0, _ava.default)('container#insertAfter (during iteration)', function (t) {
var out = (0, _helpers.parse)('h1, h2, h3', function (selectors) {
selectors.walkTags(function (selector) {
var attribute = _.default.attribute({
attribute: 'class'
});
selector.parent.insertAfter(selector, attribute);
});
});
t.deepEqual(out, 'h1[class], h2[class], h3[class]');
});
(0, _ava.default)('Container#atPosition first pseudo', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
var node = root.atPosition(1, 1);
t.deepEqual(node.type, "pseudo");
t.deepEqual(node.toString(), ":not(.foo)");
});
});
(0, _ava.default)('Container#atPosition class in pseudo', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
var node = root.atPosition(1, 6);
t.deepEqual(node.type, "class");
t.deepEqual(node.toString(), ".foo");
});
});
(0, _ava.default)('Container#atPosition id in second selector', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
var node = root.atPosition(2, 1);
t.deepEqual(node.type, "id");
t.deepEqual(node.toString(), "\n#foo");
});
});
(0, _ava.default)('Container#atPosition combinator in second selector', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
var node = root.atPosition(2, 6);
t.deepEqual(node.type, "combinator");
t.deepEqual(node.toString(), " > ");
var nodeSpace = root.atPosition(2, 5);
t.deepEqual(nodeSpace.type, "selector");
t.deepEqual(nodeSpace.toString(), "\n#foo > :matches(ol, ul)");
});
});
(0, _ava.default)('Container#atPosition tag in second selector pseudo', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
var node = root.atPosition(2, 17);
t.deepEqual(node.type, "tag");
t.deepEqual(node.toString(), "ol");
});
});
(0, _ava.default)('Container#atPosition comma in second selector pseudo', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
var node = root.atPosition(2, 19);
t.deepEqual(node.type, "pseudo");
t.deepEqual(node.toString(), ":matches(ol, ul)");
});
});
@@ -0,0 +1,19 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('escaped semicolon in class', '.\\;', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ';');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\;');
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
});
(0, _helpers.test)('escaped semicolon in id', '#\\;', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ';');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\;');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
}); // This is a side-effect of allowing media queries to be parsed. Not sure it shouldn't just be an error.
(0, _helpers.test)('bare parens capture contents as a string', '(h1)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '(h1)');
t.deepEqual(tree.nodes[0].nodes[0].type, 'string');
});
@@ -0,0 +1,24 @@
"use strict";
var _helpers = require("./util/helpers");
// Unclosed elements
(0, _helpers.throws)('unclosed string', 'a[href="wow]');
(0, _helpers.throws)('unclosed comment', '/* oops');
(0, _helpers.throws)('unclosed pseudo element', 'button::');
(0, _helpers.throws)('unclosed pseudo class', 'a:');
(0, _helpers.throws)('unclosed attribute selector', '[name="james"][href');
(0, _helpers.throws)('no opening parenthesis', ')');
(0, _helpers.throws)('no opening parenthesis (2)', ':global.foo)');
(0, _helpers.throws)('no opening parenthesis (3)', 'h1:not(h2:not(h3)))');
(0, _helpers.throws)('no opening square bracket', ']');
(0, _helpers.throws)('no opening square bracket (2)', ':global.foo]');
(0, _helpers.throws)('no opening square bracket (3)', '[global]]');
(0, _helpers.throws)('bad pseudo element', 'button::"after"');
(0, _helpers.throws)('missing closing parenthesis in pseudo', ':not([attr="test"]:not([attr="test"])');
(0, _helpers.throws)('bad syntax', '-moz-osx-font-smoothing: grayscale');
(0, _helpers.throws)('bad syntax (2)', '! .body');
(0, _helpers.throws)('missing backslash for semicolon', '.;');
(0, _helpers.throws)('missing backslash for semicolon (2)', '.\;');
(0, _helpers.throws)('unexpected / foo', '-Option\/root', "Unexpected '/'. Escaping special characters with \\ may help.");
(0, _helpers.throws)('bang in selector', '.foo !optional', "Unexpected '!'. Escaping special characters with \\ may help.");
@@ -0,0 +1,118 @@
"use strict";
var _ = _interopRequireDefault(require("../"));
var _helpers = require("./util/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var node = function node(tree, n) {
if (n === void 0) {
n = 0;
}
return tree.nodes[0].nodes[n];
};
(0, _helpers.test)('attribute guard', '[foo]', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isAttribute(undefined));
t.true(_.default.isAttribute(n));
t.false(_.default.isContainer(n));
t.true(_.default.isNamespace(n));
});
(0, _helpers.test)('className guard', '.foo', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isClassName(undefined));
t.true(_.default.isClassName(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('combinator guard', '.foo > .bar', function (t, tree) {
var n = node(tree, 1);
t.true(_.default.isNode(n));
t.false(_.default.isCombinator(undefined));
t.true(_.default.isCombinator(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('comment guard', '/* foo */.foo > .bar', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isComment(undefined));
t.true(_.default.isComment(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('id guard', '#ident', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isIdentifier(undefined));
t.true(_.default.isIdentifier(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('nesting guard', '&.foo', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isNesting(undefined));
t.true(_.default.isNesting(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('pseudo class guard', ':hover', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isPseudo(undefined));
t.true(_.default.isPseudo(n));
t.true(_.default.isPseudoClass(n));
t.false(_.default.isPseudoElement(n));
t.true(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('pseudo element guard', '::first-line', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isPseudo(undefined));
t.true(_.default.isPseudo(n));
t.false(_.default.isPseudoClass(n));
t.true(_.default.isPseudoElement(n));
t.true(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('special pseudo element guard', ':before:after', function (t, tree) {
[node(tree), node(tree, 1)].forEach(function (n) {
t.true(_.default.isPseudo(n));
t.false(_.default.isPseudoClass(n));
t.true(_.default.isPseudoElement(n));
t.true(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
});
(0, _helpers.test)('string guard', '"string"', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isString(undefined));
t.true(_.default.isString(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
(0, _helpers.test)('tag guard', 'h1', function (t, tree) {
var n = node(tree);
t.false(_.default.isNode(undefined));
t.true(_.default.isNode(n));
t.false(_.default.isTag(undefined));
t.true(_.default.isTag(n));
t.false(_.default.isContainer(n));
t.true(_.default.isNamespace(n));
});
(0, _helpers.test)('universal guard', '*', function (t, tree) {
var n = node(tree);
t.true(_.default.isNode(n));
t.false(_.default.isUniversal(undefined));
t.true(_.default.isUniversal(n));
t.false(_.default.isContainer(n));
t.false(_.default.isNamespace(n));
});
@@ -0,0 +1,229 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('id selector', '#one', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'one');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id hack', '#one#two', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[1].type, 'id');
});
(0, _helpers.test)('id and class names mixed', '#one.two.three', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'one');
t.deepEqual(tree.nodes[0].nodes[1].value, 'two');
t.deepEqual(tree.nodes[0].nodes[2].value, 'three');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[1].type, 'class');
t.deepEqual(tree.nodes[0].nodes[2].type, 'class');
});
(0, _helpers.test)('qualified id', 'button#one', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[1].type, 'id');
});
(0, _helpers.test)('qualified id & class name', 'h1#one.two', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[1].type, 'id');
t.deepEqual(tree.nodes[0].nodes[2].type, 'class');
});
(0, _helpers.test)('extraneous non-combinating whitespace', ' #h1 , #h2 ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.after, ' ');
t.deepEqual(tree.nodes[1].nodes[0].value, 'h2');
t.deepEqual(tree.nodes[1].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[1].nodes[0].spaces.after, ' ');
});
(0, _helpers.test)('Sass interpolation within a class', '.#{foo}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.length, 1);
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
t.deepEqual(tree.nodes[0].nodes[0].value, '#{foo}');
});
(0, _helpers.test)('Sass interpolation within an id', '#foo#{bar}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.length, 1);
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo#{bar}');
});
(0, _helpers.test)('Less interpolation within an id', '#foo@{bar}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.length, 1);
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo@{bar}');
});
(0, _helpers.test)('id selector with escaping', '#\\#test', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '#test');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#test');
});
(0, _helpers.test)('id selector with escaping (2)', '#-a-b-c-', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '-a-b-c-');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (3)', '#u-m\\00002b', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'u-m+');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'u-m\\00002b');
});
(0, _helpers.test)('id selector with escaping (4)', '#♥', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '♥');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (5)', '#©', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '©');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (6)', '#“‘’”', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '“‘’”');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (7)', '#☺☃', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '☺☃');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (8)', '#⌘⌥', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '⌘⌥');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (9)', '#𝄞♪♩♫♬', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '𝄞♪♩♫♬');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (10)', '#💩', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '💩');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
});
(0, _helpers.test)('id selector with escaping (11)', '#\\?', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '?');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\?');
});
(0, _helpers.test)('id selector with escaping (12)', '#\\@', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '@');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\@');
});
(0, _helpers.test)('id selector with escaping (13)', '#\\.', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '.');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\.');
});
(0, _helpers.test)('id selector with escaping (14)', '#\\3A \\)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':)');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A \\)');
});
(0, _helpers.test)('id selector with escaping (15)', '#\\3A \\`\\(', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':`(');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A \\`\\(');
});
(0, _helpers.test)('id selector with escaping (16)', '#\\31 23', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '123');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\31 23');
});
(0, _helpers.test)('id selector with escaping (17)', '#\\31 a2b3c', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '1a2b3c');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\31 a2b3c');
});
(0, _helpers.test)('id selector with escaping (18)', '#\\<p\\>', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '<p>');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\<p\\>');
});
(0, _helpers.test)('id selector with escaping (19)', '#\\<\\>\\<\\<\\<\\>\\>\\<\\>', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '<><<<>><>');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\<\\>\\<\\<\\<\\>\\>\\<\\>');
});
(0, _helpers.test)('id selector with escaping (20)', '#\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\[\\>\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\>\\+\\<\\<\\<\\<\\-\\]\\>\\+\\+\\.\\>\\+\\.\\+\\+\\+\\+\\+\\+\\+\\.\\.\\+\\+\\+\\.\\>\\+\\+\\.\\<\\<\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\.\\>\\.\\+\\+\\+\\.\\-\\-\\-\\-\\-\\-\\.\\-\\-\\-\\-\\-\\-\\-\\-\\.\\>\\+\\.\\>\\.', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\[\\>\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\>\\+\\+\\+\\>\\+\\<\\<\\<\\<\\-\\]\\>\\+\\+\\.\\>\\+\\.\\+\\+\\+\\+\\+\\+\\+\\.\\.\\+\\+\\+\\.\\>\\+\\+\\.\\<\\<\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\+\\.\\>\\.\\+\\+\\+\\.\\-\\-\\-\\-\\-\\-\\.\\-\\-\\-\\-\\-\\-\\-\\-\\.\\>\\+\\.\\>\\.');
});
(0, _helpers.test)('id selector with escaping (21)', '#\\#', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '#');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#');
});
(0, _helpers.test)('id selector with escaping (22)', '#\\#\\#', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '##');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#\\#');
});
(0, _helpers.test)('id selector with escaping (23)', '#\\#\\.\\#\\.\\#', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '#.#.#');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\#\\.\\#\\.\\#');
});
(0, _helpers.test)('id selector with escaping (24)', '#\\_', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '_');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\_');
});
(0, _helpers.test)('id selector with escaping (25)', '#\\{\\}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '{}');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\{\\}');
});
(0, _helpers.test)('id selector with escaping (26)', '#\\.fake\\-class', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '.fake-class');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\.fake\\-class');
});
(0, _helpers.test)('id selector with escaping (27)', '#foo\\.bar', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo.bar');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'foo\\.bar');
});
(0, _helpers.test)('id selector with escaping (28)', '#\\3A hover', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':hover');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A hover');
});
(0, _helpers.test)('id selector with escaping (29)', '#\\3A hover\\3A focus\\3A active', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':hover:focus:active');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\3A hover\\3A focus\\3A active');
});
(0, _helpers.test)('id selector with escaping (30)', '#\\[attr\\=value\\]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '[attr=value]');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, '\\[attr\\=value\\]');
});
(0, _helpers.test)('id selector with escaping (31)', '#f\\/o\\/o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f/o/o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\/o\\/o');
});
(0, _helpers.test)('id selector with escaping (32)', '#f\\\\o\\\\o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f\\o\\o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\\\o\\\\o');
});
(0, _helpers.test)('id selector with escaping (33)', '#f\\*o\\*o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f*o*o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\*o\\*o');
});
(0, _helpers.test)('id selector with escaping (34)', '#f\\!o\\!o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f!o!o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\!o\\!o');
});
(0, _helpers.test)('id selector with escaping (35)', '#f\\\'o\\\'o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f\'o\'o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\\'o\\\'o');
});
(0, _helpers.test)('id selector with escaping (36)', '#f\\~o\\~o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f~o~o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\~o\\~o');
});
(0, _helpers.test)('id selector with escaping (37)', '#f\\+o\\+o', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'f+o+o');
t.deepEqual(tree.nodes[0].nodes[0].type, 'id');
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'f\\+o\\+o');
});
@@ -0,0 +1,88 @@
"use strict";
exports.__esModule = true;
exports.testLossy = exports.parse = void 0;
var _ava = _interopRequireDefault(require("ava"));
var _index = _interopRequireDefault(require("../index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var parse = function parse(input, options, transform) {
return (0, _index.default)(transform).processSync(input, options);
};
exports.parse = parse;
var testLossy = function testLossy(t, input, expected) {
var result = parse(input, {
lossless: false
});
t.deepEqual(result, expected);
};
exports.testLossy = testLossy;
(0, _ava.default)('combinator, descendant - single', testLossy, '.one .two', '.one .two');
(0, _ava.default)('combinator, descendant - multiple', testLossy, '.one .two', '.one .two');
(0, _ava.default)('combinator, child - space before', testLossy, '.one >.two', '.one>.two');
(0, _ava.default)('combinator, child - space after', testLossy, '.one> .two', '.one>.two');
(0, _ava.default)('combinator, sibling - space before', testLossy, '.one ~.two', '.one~.two');
(0, _ava.default)('combinator, sibling - space after', testLossy, '.one~ .two', '.one~.two');
(0, _ava.default)('combinator, adj sibling - space before', testLossy, '.one +.two', '.one+.two');
(0, _ava.default)('combinator, adj sibling - space after', testLossy, '.one+ .two', '.one+.two');
(0, _ava.default)('classes, extraneous spaces', testLossy, ' .h1 , .h2 ', '.h1,.h2');
(0, _ava.default)('ids, extraneous spaces', testLossy, ' #h1 , #h2 ', '#h1,#h2');
(0, _ava.default)('attribute, spaces in selector', testLossy, 'h1[ href *= "test" ]', 'h1[href*="test"]');
(0, _ava.default)('attribute, insensitive flag 1', testLossy, '[href="test" i ]', '[href="test"i]');
(0, _ava.default)('attribute, insensitive flag 2', testLossy, '[href=TEsT i ]', '[href=TEsT i]');
(0, _ava.default)('attribute, insensitive flag 3', testLossy, '[href=test i ]', '[href=test i]');
(0, _ava.default)('attribute, extreneous whitespace', testLossy, ' [href] , [class] ', '[href],[class]');
(0, _ava.default)('namespace, space before', testLossy, ' postcss|button', 'postcss|button');
(0, _ava.default)('namespace, space after', testLossy, 'postcss|button ', 'postcss|button');
(0, _ava.default)('namespace - all elements, space before', testLossy, ' postcss|*', 'postcss|*');
(0, _ava.default)('namespace - all elements, space after', testLossy, 'postcss|* ', 'postcss|*');
(0, _ava.default)('namespace - all namespaces, space before', testLossy, ' *|button', '*|button');
(0, _ava.default)('namespace - all namespaces, space after', testLossy, '*|button ', '*|button');
(0, _ava.default)('namespace - all elements in all namespaces, space before', testLossy, ' *|*', '*|*');
(0, _ava.default)('namespace - all elements in all namespaces, space after', testLossy, '*|* ', '*|*');
(0, _ava.default)('namespace - all elements without namespace, space before', testLossy, ' |*', '|*');
(0, _ava.default)('namespace - all elements without namespace, space after', testLossy, '|* ', '|*');
(0, _ava.default)('namespace - tag with no namespace, space before', testLossy, ' |button', '|button');
(0, _ava.default)('namespace - tag with no namespace, space after', testLossy, '|button ', '|button');
(0, _ava.default)('namespace - inside attribute, space before', testLossy, ' [ postcss|href=test]', '[postcss|href=test]');
(0, _ava.default)('namespace - inside attribute, space after', testLossy, '[postcss|href= test ] ', '[postcss|href=test]');
(0, _ava.default)('namespace - inside attribute (2), space before', testLossy, ' [ postcss|href]', '[postcss|href]');
(0, _ava.default)('namespace - inside attribute (2), space after', testLossy, '[postcss|href ] ', '[postcss|href]');
(0, _ava.default)('namespace - inside attribute (3), space before', testLossy, ' [ *|href=test]', '[*|href=test]');
(0, _ava.default)('namespace - inside attribute (3), space after', testLossy, '[*|href= test ] ', '[*|href=test]');
(0, _ava.default)('namespace - inside attribute (4), space after', testLossy, '[|href= test ] ', '[|href=test]');
(0, _ava.default)('tag - extraneous whitespace', testLossy, ' h1 , h2 ', 'h1,h2');
(0, _ava.default)('tag - trailing comma', testLossy, 'h1, ', 'h1,');
(0, _ava.default)('tag - trailing comma (1)', testLossy, 'h1,', 'h1,');
(0, _ava.default)('tag - trailing comma (2)', testLossy, 'h1', 'h1');
(0, _ava.default)('tag - trailing slash (1)', testLossy, 'h1\\ ', 'h1\\ ');
(0, _ava.default)('tag - trailing slash (2)', testLossy, 'h1\\ h2\\', 'h1\\ h2\\');
(0, _ava.default)('universal - combinator', testLossy, ' * + * ', '*+*');
(0, _ava.default)('universal - extraneous whitespace', testLossy, ' * , * ', '*,*');
(0, _ava.default)('universal - qualified universal selector', testLossy, '*[href] *:not(*.green)', '*[href] *:not(*.green)');
(0, _ava.default)('nesting - spacing before', testLossy, ' &.class', '&.class');
(0, _ava.default)('nesting - spacing after', testLossy, '&.class ', '&.class');
(0, _ava.default)('nesting - spacing between', testLossy, '& .class ', '& .class');
(0, _ava.default)('pseudo (single) - spacing before', testLossy, ' :after', ':after');
(0, _ava.default)('pseudo (single) - spacing after', testLossy, ':after ', ':after');
(0, _ava.default)('pseudo (double) - spacing before', testLossy, ' ::after', '::after');
(0, _ava.default)('pseudo (double) - spacing after', testLossy, '::after ', '::after');
(0, _ava.default)('pseudo - multiple', testLossy, ' *:target::before , a:after ', '*:target::before,a:after');
(0, _ava.default)('pseudo - negated', testLossy, 'h1:not( .heading )', 'h1:not(.heading)');
(0, _ava.default)('pseudo - negated with combinators (1)', testLossy, 'h1:not(.heading > .title) > h1', 'h1:not(.heading>.title)>h1');
(0, _ava.default)('pseudo - negated with combinators (2)', testLossy, '.foo:nth-child(2n + 1)', '.foo:nth-child(2n+1)');
(0, _ava.default)('pseudo - extra whitespace', testLossy, 'a:not( h2 )', 'a:not(h2)');
(0, _ava.default)('comments - comment inside descendant selector', testLossy, "div /* wtf */.foo", "div /* wtf */.foo");
(0, _ava.default)('comments - comment inside complex selector', testLossy, "div /* wtf */ > .foo", "div/* wtf */>.foo");
(0, _ava.default)('comments - comment inside compound selector with space', testLossy, "div /* wtf */ .foo", "div /* wtf */.foo");
(0, _ava.default)('@words - space before', testLossy, ' @media', '@media');
(0, _ava.default)('@words - space after', testLossy, '@media ', '@media');
(0, _ava.default)('@words - maintains space between', testLossy, '@media (min-width: 700px) and (orientation: landscape)', '@media (min-width: 700px) and (orientation: landscape)');
(0, _ava.default)('@words - extraneous space between', testLossy, '@media (min-width: 700px) and (orientation: landscape)', '@media (min-width: 700px) and (orientation: landscape)');
(0, _ava.default)('@words - multiple', testLossy, '@media (min-width: 700px), (min-height: 400px)', '@media (min-width: 700px),(min-height: 400px)');
@@ -0,0 +1,66 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('match tags in the postcss namespace', 'postcss|button', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'postcss');
t.deepEqual(tree.nodes[0].nodes[0].value, 'button');
});
(0, _helpers.test)('match everything in the postcss namespace', 'postcss|*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'postcss');
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
});
(0, _helpers.test)('match any namespace', '*|button', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, '*');
t.deepEqual(tree.nodes[0].nodes[0].value, 'button');
});
(0, _helpers.test)('match all elements within the postcss namespace', 'postcss|*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'postcss');
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
});
(0, _helpers.test)('match all elements in all namespaces', '*|*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, '*');
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
});
(0, _helpers.test)('match all elements without a namespace', '|*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, true);
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
});
(0, _helpers.test)('match tags with no namespace', '|button', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, true);
t.deepEqual(tree.nodes[0].nodes[0].value, 'button');
});
(0, _helpers.test)('match namespace inside attribute selector', '[postcss|href=test]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'postcss');
t.deepEqual(tree.nodes[0].nodes[0].value, 'test');
});
(0, _helpers.test)('match namespace inside attribute selector (2)', '[postcss|href]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'postcss');
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
});
(0, _helpers.test)('match namespace inside attribute selector (3)', '[*|href]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, '*');
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
});
(0, _helpers.test)('match default namespace inside attribute selector', '[|href]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, true);
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
});
(0, _helpers.test)('match default namespace inside attribute selector with spaces', '[ |href ]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, true);
t.deepEqual(tree.nodes[0].nodes[0].attribute, 'href');
});
(0, _helpers.test)('namespace with qualified id selector', 'ns|h1#foo', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'ns');
});
(0, _helpers.test)('namespace with qualified class selector', 'ns|h1.foo', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].namespace, 'ns');
});
(0, _helpers.test)('ns alias for namespace', 'f\\oo|h1.foo', function (t, tree) {
var tag = tree.nodes[0].nodes[0];
t.deepEqual(tag.namespace, 'foo');
t.deepEqual(tag.ns, 'foo');
tag.ns = "bar";
t.deepEqual(tag.namespace, 'bar');
t.deepEqual(tag.ns, 'bar');
});
@@ -0,0 +1,40 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('nesting selector', '&', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '&');
t.deepEqual(tree.nodes[0].nodes[0].type, 'nesting');
});
(0, _helpers.test)('nesting selector followed by a class', '& .class', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '&');
t.deepEqual(tree.nodes[0].nodes[0].type, 'nesting');
t.deepEqual(tree.nodes[0].nodes[1].value, ' ');
t.deepEqual(tree.nodes[0].nodes[1].type, 'combinator');
t.deepEqual(tree.nodes[0].nodes[2].value, 'class');
t.deepEqual(tree.nodes[0].nodes[2].type, 'class');
});
(0, _helpers.test)('&foo', '&foo', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '&');
t.deepEqual(tree.nodes[0].nodes[0].type, 'nesting');
t.deepEqual(tree.nodes[0].nodes[1].value, 'foo');
t.deepEqual(tree.nodes[0].nodes[1].type, 'tag');
});
(0, _helpers.test)('&-foo', '&-foo', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '&');
t.deepEqual(tree.nodes[0].nodes[0].type, 'nesting');
t.deepEqual(tree.nodes[0].nodes[1].value, '-foo');
t.deepEqual(tree.nodes[0].nodes[1].type, 'tag');
});
(0, _helpers.test)('&_foo', '&_foo', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '&');
t.deepEqual(tree.nodes[0].nodes[0].type, 'nesting');
t.deepEqual(tree.nodes[0].nodes[1].value, '_foo');
t.deepEqual(tree.nodes[0].nodes[1].type, 'tag');
});
(0, _helpers.test)('&|foo', '&|foo', function (t, tree) {
var element = tree.nodes[0].nodes[0];
t.deepEqual(element.value, 'foo');
t.deepEqual(element.type, 'tag');
t.deepEqual(element.namespace, '&');
});
@@ -0,0 +1,139 @@
"use strict";
var _ava = _interopRequireDefault(require("ava"));
var _ = _interopRequireDefault(require(".."));
var _helpers = require("./util/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _ava.default)('node#clone', function (t) {
(0, _helpers.parse)('[href="test"]', function (selectors) {
var selector = selectors.first.first;
var clone = selector.clone();
delete selector.parent;
t.deepEqual(clone, selectors.first.first);
});
});
(0, _ava.default)('node#clone of attribute', function (t) {
(0, _helpers.parse)('[href=test]', function (selectors) {
var selector = selectors.first.first;
var clone = selector.clone();
delete selector.parent;
t.deepEqual(clone, selectors.first.first);
});
});
(0, _ava.default)('node#replaceWith', function (t) {
var out = (0, _helpers.parse)('[href="test"]', function (selectors) {
var attr = selectors.first.first;
var id = _.default.id({
value: 'test'
});
var className = _.default.className({
value: 'test'
});
attr.replaceWith(id, className);
});
t.deepEqual(out, '#test.test');
});
(0, _ava.default)('Node#appendToPropertyAndEscape', function (t) {
var out = (0, _helpers.parse)('.fo\\o', function (selectors) {
var className = selectors.first.first;
t.deepEqual(className.raws, {
value: "fo\\o"
});
className.appendToPropertyAndEscape("value", "bar", "ba\\r");
t.deepEqual(className.raws, {
value: "fo\\oba\\r"
});
});
t.deepEqual(out, '.fo\\oba\\r');
});
(0, _ava.default)('Node#setPropertyAndEscape with existing raws', function (t) {
var out = (0, _helpers.parse)('.fo\\o', function (selectors) {
var className = selectors.first.first;
t.deepEqual(className.raws, {
value: "fo\\o"
});
className.setPropertyAndEscape("value", "bar", "ba\\r");
t.deepEqual(className.raws, {
value: "ba\\r"
});
});
t.deepEqual(out, '.ba\\r');
});
(0, _ava.default)('Node#setPropertyAndEscape without existing raws', function (t) {
var out = (0, _helpers.parse)('.foo', function (selectors) {
var className = selectors.first.first;
t.deepEqual(className.raws, undefined);
className.setPropertyAndEscape("value", "bar", "ba\\r");
t.deepEqual(className.raws, {
value: "ba\\r"
});
});
t.deepEqual(out, '.ba\\r');
});
(0, _ava.default)('Node#setPropertyWithoutEscape with existing raws', function (t) {
var out = (0, _helpers.parse)('.fo\\o', function (selectors) {
var className = selectors.first.first;
t.deepEqual(className.raws, {
value: "fo\\o"
});
className.setPropertyWithoutEscape("value", "w+t+f");
t.deepEqual(className.raws, {});
});
t.deepEqual(out, '.w+t+f');
});
(0, _ava.default)('Node#setPropertyWithoutEscape without existing raws', function (t) {
var out = (0, _helpers.parse)('.foo', function (selectors) {
var className = selectors.first.first;
t.deepEqual(className.raws, undefined);
className.setPropertyWithoutEscape("value", "w+t+f");
t.deepEqual(className.raws, {});
t.deepEqual(className.value, "w+t+f");
});
t.deepEqual(out, '.w+t+f');
});
(0, _ava.default)('Node#isAtPosition', function (t) {
(0, _helpers.parse)(':not(.foo),\n#foo > :matches(ol, ul)', function (root) {
t.deepEqual(root.isAtPosition(1, 1), true);
t.deepEqual(root.isAtPosition(1, 10), true);
t.deepEqual(root.isAtPosition(2, 23), true);
t.deepEqual(root.isAtPosition(2, 24), false);
var selector = root.first;
t.deepEqual(selector.isAtPosition(1, 1), true);
t.deepEqual(selector.isAtPosition(1, 10), true);
t.deepEqual(selector.isAtPosition(1, 11), false);
var pseudoNot = selector.first;
t.deepEqual(pseudoNot.isAtPosition(1, 1), true);
t.deepEqual(pseudoNot.isAtPosition(1, 7), true);
t.deepEqual(pseudoNot.isAtPosition(1, 10), true);
t.deepEqual(pseudoNot.isAtPosition(1, 11), false);
var notSelector = pseudoNot.first;
t.deepEqual(notSelector.isAtPosition(1, 1), false);
t.deepEqual(notSelector.isAtPosition(1, 4), false);
t.deepEqual(notSelector.isAtPosition(1, 5), true);
t.deepEqual(notSelector.isAtPosition(1, 6), true);
t.deepEqual(notSelector.isAtPosition(1, 9), true);
t.deepEqual(notSelector.isAtPosition(1, 10), true);
t.deepEqual(notSelector.isAtPosition(1, 11), false);
var notClass = notSelector.first;
t.deepEqual(notClass.isAtPosition(1, 5), false);
t.deepEqual(notClass.isAtPosition(1, 6), true);
t.deepEqual(notClass.isAtPosition(1, 9), true);
t.deepEqual(notClass.isAtPosition(1, 10), false);
var secondSel = root.at(1);
t.deepEqual(secondSel.isAtPosition(1, 11), false);
t.deepEqual(secondSel.isAtPosition(2, 1), true);
t.deepEqual(secondSel.isAtPosition(2, 23), true);
t.deepEqual(secondSel.isAtPosition(2, 24), false);
var combinator = secondSel.at(1);
t.deepEqual(combinator.isAtPosition(2, 5), false);
t.deepEqual(combinator.isAtPosition(2, 6), true);
t.deepEqual(combinator.isAtPosition(2, 7), false);
});
});
@@ -0,0 +1,38 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('non-standard selector', '.icon.is-$(network)', function (t, tree) {
var class1 = tree.nodes[0].nodes[0];
t.deepEqual(class1.value, 'icon');
t.deepEqual(class1.type, 'class');
var class2 = tree.nodes[0].nodes[1];
t.deepEqual(class2.value, 'is-$(network)');
t.deepEqual(class2.type, 'class');
});
(0, _helpers.test)('at word in selector', 'em@il.com', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'em@il');
t.deepEqual(tree.nodes[0].nodes[1].value, 'com');
});
(0, _helpers.test)('leading combinator', '> *', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '>');
t.deepEqual(tree.nodes[0].nodes[1].value, '*');
});
(0, _helpers.test)('sass escapes', '.#{$classname}', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.map(function (n) {
return n.type;
}), ["class"]);
t.deepEqual(tree.nodes[0].nodes[0].value, "#{$classname}");
});
(0, _helpers.test)('sass escapes (2)', '[lang=#{$locale}]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.map(function (n) {
return n.type;
}), ["attribute"]);
t.deepEqual(tree.nodes[0].nodes[0].value, "#{$locale}");
});
(0, _helpers.test)('placeholder', '%foo', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes.map(function (n) {
return n.type;
}), ["tag"]);
t.deepEqual(tree.nodes[0].nodes[0].value, "%foo");
});
@@ -0,0 +1,259 @@
"use strict";
var _ava = _interopRequireDefault(require("ava"));
var _index = _interopRequireDefault(require("../index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Node creation
var nodeTypes = [['attribute', '[href]', {
attribute: 'href'
}], ['className', '.classy', {
value: 'classy'
}], ['combinator', ' >> ', {
value: '>>',
spaces: {
before: ' ',
after: ' '
}
}], ['comment', '/* comment */', {
value: '/* comment */'
}], ['id', '#test', {
value: 'test'
}], ['nesting', '&'], ['pseudo', '::before', {
value: '::before'
}], ['string', '"wow"', {
value: '"wow"'
}], ['tag', 'button', {
value: 'button'
}], ['universal', '*']];
nodeTypes.forEach(function (type) {
(0, _ava.default)("parser#" + type[0], function (t) {
var node = _index.default[type[0]](type[2] || {});
t.deepEqual(String(node), type[1]);
});
});
(0, _ava.default)('string constants', function (t) {
t.truthy(_index.default.TAG);
t.truthy(_index.default.STRING);
t.truthy(_index.default.SELECTOR);
t.truthy(_index.default.ROOT);
t.truthy(_index.default.PSEUDO);
t.truthy(_index.default.NESTING);
t.truthy(_index.default.ID);
t.truthy(_index.default.COMMENT);
t.truthy(_index.default.COMBINATOR);
t.truthy(_index.default.CLASS);
t.truthy(_index.default.ATTRIBUTE);
t.truthy(_index.default.UNIVERSAL);
});
(0, _ava.default)('construct a whole tree', function (t) {
var root = _index.default.root();
var selector = _index.default.selector();
selector.append(_index.default.id({
value: 'tree'
}));
root.append(selector);
t.deepEqual(String(root), '#tree');
});
(0, _ava.default)('no operation', function (t) {
t.notThrows(function () {
return (0, _index.default)().processSync('h1 h2 h3');
});
});
(0, _ava.default)('empty selector string', function (t) {
t.notThrows(function () {
return (0, _index.default)(function (selectors) {
selectors.walk(function (selector) {
selector.type = 'tag';
});
}).processSync('');
});
});
(0, _ava.default)('async parser', function (t) {
return (0, _index.default)(function (selectors) {
return new Promise(function (res) {
setTimeout(function () {
selectors.first.nodes[0].value = 'bar';
res();
}, 1);
});
}).process('foo').then(function (result) {
t.deepEqual(result, 'bar');
});
});
(0, _ava.default)('parse errors with the async parser', function (t) {
return (0, _index.default)(function (selectors) {
return new Promise(function (res) {
setTimeout(function () {
selectors.first.nodes[0].value = 'bar';
res();
}, 1);
});
}).process('a b: c').catch(function (err) {
return t.truthy(err);
});
});
(0, _ava.default)('parse errors within the async processor', function (t) {
return (0, _index.default)(function (selectors) {
return new Promise(function (res, rej) {
setTimeout(function () {
rej(selectors.error("async error"));
}, 1);
});
}).process('.foo').catch(function (err) {
return t.truthy(err);
});
});
(0, _ava.default)('parse errors within the async processor before the promise returns', function (t) {
return (0, _index.default)(function (selectors) {
throw selectors.error("async error");
}).process('.foo').catch(function (err) {
return t.truthy(err);
});
});
(0, _ava.default)('returning a promise to the sync processor fails', function (t) {
t.throws(function () {
return (0, _index.default)(function () {
return new Promise(function (res) {
setTimeout(function () {
res();
}, 1);
});
}).processSync('.foo');
});
});
(0, _ava.default)('Passing a rule works async', function (t) {
var rule = {
selector: '.foo'
};
return (0, _index.default)(function (root) {
return new Promise(function (res) {
setTimeout(function () {
root.walkClasses(function (node) {
node.value = "bar";
});
res();
}, 1);
});
}).process(rule).then(function (newSel) {
t.deepEqual(newSel, ".bar");
t.deepEqual(rule.selector, ".bar");
});
});
(0, _ava.default)('Passing a rule with mutation disabled works async', function (t) {
var rule = {
selector: '.foo'
};
return (0, _index.default)(function (root) {
return new Promise(function (res) {
setTimeout(function () {
root.walkClasses(function (node) {
node.value = "bar";
});
res();
}, 1);
});
}).process(rule, {
updateSelector: false
}).then(function (newSel) {
t.deepEqual(newSel, ".bar");
t.deepEqual(rule.selector, ".foo");
});
});
(0, _ava.default)('Passing a rule with mutation works sync', function (t) {
var rule = {
selector: '.foo'
};
var newSel = (0, _index.default)(function (root) {
root.walkClasses(function (node) {
node.value = "bar";
});
}).processSync(rule, {
updateSelector: true
});
t.deepEqual(newSel, ".bar");
t.deepEqual(rule.selector, ".bar");
});
(0, _ava.default)('Transform a selector synchronously', function (t) {
var rule = {
selector: '.foo'
};
var count = (0, _index.default)(function (root) {
var classCount = 0;
root.walkClasses(function (node) {
classCount++;
node.value = "bar";
});
return classCount;
}).transformSync(rule, {
updateSelector: true
});
t.deepEqual(count, 1);
t.deepEqual(rule.selector, ".bar");
});
(0, _ava.default)('Transform a selector asynchronously', function (t) {
var rule = {
selector: '.foo'
};
return (0, _index.default)(function (root) {
return new Promise(function (res) {
setTimeout(function () {
var classCount = 0;
root.walkClasses(function (node) {
classCount++;
node.value = "bar";
});
res(classCount);
}, 1);
});
}).transform(rule, {
updateSelector: true
}).then(function (count) {
t.deepEqual(count, 1);
t.deepEqual(rule.selector, ".bar");
});
});
(0, _ava.default)('get AST of a selector synchronously', function (t) {
var rule = {
selector: '.foo'
};
var ast = (0, _index.default)(function (root) {
var classCount = 0;
root.walkClasses(function (node) {
classCount++;
node.value = "bar";
});
return classCount;
}).astSync(rule, {
updateSelector: true
});
t.deepEqual(ast.nodes[0].nodes[0].value, "bar");
t.deepEqual(rule.selector, ".bar");
});
(0, _ava.default)('get AST a selector asynchronously', function (t) {
var rule = {
selector: '.foo'
};
return (0, _index.default)(function (root) {
return new Promise(function (res) {
setTimeout(function () {
var classCount = 0;
root.walkClasses(function (node) {
classCount++;
node.value = "bar";
});
res(classCount);
}, 1);
});
}).ast(rule, {
updateSelector: true
}).then(function (ast) {
t.deepEqual(ast.nodes[0].nodes[0].value, "bar");
t.deepEqual(rule.selector, ".bar");
});
});
@@ -0,0 +1,46 @@
"use strict";
var _ava = _interopRequireDefault(require("ava"));
var _postcss = _interopRequireDefault(require("postcss"));
var _helpers = require("./util/helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var cse = 'CssSyntaxError';
function showCode(t, selector) {
var rule = _postcss.default.parse(selector).first;
try {
(0, _helpers.parse)(rule);
} catch (e) {
if (e.name !== cse) {
return;
} // Removes ANSI codes from snapshot tests as it makes them illegible.
// The formatting of this error is otherwise identical to e.toString()
t.snapshot(cse + ": " + e.message + "\n\n" + e.showSourceCode(false) + "\n");
}
}
(0, _ava.default)('missing open square bracket', showCode, 'a b c] {}');
(0, _ava.default)('missing open parenthesis', showCode, 'a b c) {}');
(0, _ava.default)('missing pseudo class or pseudo element', showCode, 'a b c: {}');
(0, _ava.default)('space in between colon and word (incorrect pseudo)', showCode, 'a b: c {}');
(0, _ava.default)('string after colon (incorrect pseudo)', showCode, 'a b:"wow" {}'); // attribute selectors
(0, _ava.default)('bad string attribute', showCode, '["hello"] {}');
(0, _ava.default)('bad string attribute with value', showCode, '["foo"=bar] {}');
(0, _ava.default)('bad parentheses', showCode, '[foo=(bar)] {}');
(0, _ava.default)('bad lonely asterisk', showCode, '[*] {}');
(0, _ava.default)('bad lonely pipe', showCode, '[|] {}');
(0, _ava.default)('bad lonely caret', showCode, '[^] {}');
(0, _ava.default)('bad lonely dollar', showCode, '[$] {}');
(0, _ava.default)('bad lonely tilde', showCode, '[~] {}');
(0, _ava.default)('bad lonely equals', showCode, '[=] {}');
(0, _ava.default)('bad lonely operator', showCode, '[*=] {}');
(0, _ava.default)('bad lonely operator (2)', showCode, '[|=] {}');
(0, _ava.default)('bad doubled operator', showCode, '[href=foo=bar] {}');
@@ -0,0 +1,98 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('pseudo element (single colon)', 'h1:after', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[1].type, 'pseudo');
t.deepEqual(tree.nodes[0].nodes[1].value, ':after');
});
(0, _helpers.test)('pseudo element (double colon)', 'h1::after', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[1].type, 'pseudo');
t.deepEqual(tree.nodes[0].nodes[1].value, '::after');
});
(0, _helpers.test)('multiple pseudo elements', '*:target::before, a:after', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
t.deepEqual(tree.nodes[0].nodes[1].value, ':target');
t.deepEqual(tree.nodes[0].nodes[2].value, '::before');
t.deepEqual(tree.nodes[1].nodes[1].value, ':after');
});
(0, _helpers.test)('negation pseudo element', 'h1:not(.heading)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, ':not');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, 'heading');
});
(0, _helpers.test)('negation pseudo element (2)', 'h1:not(.heading, .title, .content)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, ':not');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, 'heading');
t.deepEqual(tree.nodes[0].nodes[1].nodes[1].nodes[0].value, 'title');
t.deepEqual(tree.nodes[0].nodes[1].nodes[2].nodes[0].value, 'content');
});
(0, _helpers.test)('negation pseudo element (3)', 'h1:not(.heading > .title) > h1', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, 'heading');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[1].value, '>');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[2].value, 'title');
t.deepEqual(tree.nodes[0].nodes[2].value, '>');
t.deepEqual(tree.nodes[0].nodes[3].value, 'h1');
});
(0, _helpers.test)('negation pseudo element (4)', 'h1:not(h2:not(h3))', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[1].nodes[0].nodes[0].value, 'h3');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[1].nodes[0].nodes[0].parent.type, 'selector');
});
(0, _helpers.test)('pseudo class in the middle of a selector', 'a:link.external', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[0].value, 'a');
t.deepEqual(tree.nodes[0].nodes[1].type, 'pseudo');
t.deepEqual(tree.nodes[0].nodes[1].value, ':link');
t.deepEqual(tree.nodes[0].nodes[2].type, 'class');
t.deepEqual(tree.nodes[0].nodes[2].value, 'external');
});
(0, _helpers.test)('extra whitespace inside parentheses', 'a:not( h2 )', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, 'h2');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].spaces.before, ' ');
});
(0, _helpers.test)('escaped numbers in class name with pseudo', 'a:before.\\31\\ 0', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[2].type, 'class');
t.deepEqual(tree.nodes[0].nodes[2].value, '1 0');
t.deepEqual(tree.nodes[0].nodes[2].raws.value, '\\31\\ 0');
});
(0, _helpers.test)('nested pseudo', '.btn-group>.btn:last-child:not(:first-child)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[4].value, ':not');
});
(0, _helpers.test)('extraneous non-combinating whitespace', ' h1:after , h2:after ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[1].value, ':after');
t.deepEqual(tree.nodes[0].nodes[1].spaces.after, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[1].nodes[1].value, ':after');
t.deepEqual(tree.nodes[1].nodes[1].spaces.after, ' ');
});
(0, _helpers.test)('negation pseudo element with quotes', 'h1:not(".heading")', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, ':not');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, '".heading"');
});
(0, _helpers.test)('negation pseudo element with single quotes', "h1:not('.heading')", function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, ':not');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, "'.heading'");
});
(0, _helpers.test)('Issue #116', "svg:not(:root)", function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].value, ':not');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].value, ':root');
});
(0, _helpers.test)('alone pseudo class', ':root', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'pseudo');
t.deepEqual(tree.nodes[0].nodes[0].value, ':root');
});
(0, _helpers.test)('non standard pseudo (@custom-selector)', ":--foobar, a", function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, ':--foobar');
t.deepEqual(tree.nodes[0].nodes[0].type, 'pseudo');
t.deepEqual(tree.nodes[1].nodes[0].value, 'a');
t.deepEqual(tree.nodes[1].nodes[0].type, 'tag');
});
(0, _helpers.test)('non standard pseudo (@custom-selector) (1)', "a, :--foobar", function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'a');
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[1].nodes[0].value, ':--foobar');
t.deepEqual(tree.nodes[1].nodes[0].type, 'pseudo');
});
@@ -0,0 +1,229 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('universal selector', '*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
});
(0, _helpers.test)('lobotomized owl selector', ' * + * ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 2);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 2);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 4);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 4);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 3);
t.deepEqual(tree.nodes[0].nodes[2].source.start.column, 6);
t.deepEqual(tree.nodes[0].nodes[2].source.end.column, 6);
t.deepEqual(tree.nodes[0].nodes[2].sourceIndex, 5);
});
(0, _helpers.test)('comment', '/**\n * Hello!\n */', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 3);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
});
(0, _helpers.test)('comment & universal selectors', '*/*test*/*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 2);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 9);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 1);
t.deepEqual(tree.nodes[0].nodes[2].source.start.column, 10);
t.deepEqual(tree.nodes[0].nodes[2].source.end.column, 10);
t.deepEqual(tree.nodes[0].nodes[2].sourceIndex, 9);
});
(0, _helpers.test)('tag selector', 'h1', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 2);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
});
(0, _helpers.test)('id selector', '#id', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 3);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
});
(0, _helpers.test)('tag selector followed by id selector', 'h1, #id', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 2);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
t.deepEqual(tree.nodes[1].nodes[0].source.start.column, 5);
t.deepEqual(tree.nodes[1].nodes[0].source.end.column, 7);
t.deepEqual(tree.nodes[1].nodes[0].sourceIndex, 4);
});
(0, _helpers.test)('multiple id selectors', '#one#two', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 4);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 5);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 8);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 4);
});
(0, _helpers.test)('multiple id selectors (2)', '#one#two#three#four', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[2].source.start.column, 9);
t.deepEqual(tree.nodes[0].nodes[2].source.end.column, 14);
t.deepEqual(tree.nodes[0].nodes[2].sourceIndex, 8);
t.deepEqual(tree.nodes[0].nodes[3].source.start.column, 15);
t.deepEqual(tree.nodes[0].nodes[3].source.end.column, 19);
t.deepEqual(tree.nodes[0].nodes[3].sourceIndex, 14);
});
(0, _helpers.test)('multiple id selectors (3)', '#one#two,#three#four', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 5);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 8);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 4);
t.deepEqual(tree.nodes[1].nodes[1].source.start.column, 16);
t.deepEqual(tree.nodes[1].nodes[1].source.end.column, 20);
t.deepEqual(tree.nodes[1].nodes[1].sourceIndex, 15);
});
(0, _helpers.test)('multiple class selectors', '.one.two,.three.four', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 5);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 8);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 4);
t.deepEqual(tree.nodes[1].nodes[1].source.start.column, 16);
t.deepEqual(tree.nodes[1].nodes[1].source.end.column, 20);
t.deepEqual(tree.nodes[1].nodes[1].sourceIndex, 15);
});
(0, _helpers.test)('attribute selector', '[name="james"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 14);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
});
(0, _helpers.test)('multiple attribute selectors', '[name="james"][name="ed"],[name="snakeman"][name="a"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.line, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 14);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 15);
t.deepEqual(tree.nodes[0].nodes[1].source.end.line, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 25);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 14);
t.deepEqual(tree.nodes[1].nodes[0].source.start.line, 1);
t.deepEqual(tree.nodes[1].nodes[0].source.start.column, 27);
t.deepEqual(tree.nodes[1].nodes[0].source.end.line, 1);
t.deepEqual(tree.nodes[1].nodes[0].source.end.column, 43);
t.deepEqual(tree.nodes[1].nodes[0].sourceIndex, 26);
t.deepEqual(tree.nodes[1].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[1].nodes[1].source.start.column, 44);
t.deepEqual(tree.nodes[1].nodes[1].source.end.line, 1);
t.deepEqual(tree.nodes[1].nodes[1].source.end.column, 53);
t.deepEqual(tree.nodes[1].nodes[1].sourceIndex, 43);
});
(0, _helpers.test)('pseudo-class', 'h1:first-child', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 3);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 14);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 2);
});
(0, _helpers.test)('pseudo-class with argument', 'h1:not(.strudel, .food)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 3);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 23);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 2);
});
(0, _helpers.test)('pseudo-element', 'h1::before', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 3);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 10);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 2);
});
(0, _helpers.test)('multiple pseudos', 'h1:not(.food)::before, a:first-child', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 3);
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 13);
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 2);
t.deepEqual(tree.nodes[0].nodes[2].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[2].source.start.column, 14);
t.deepEqual(tree.nodes[0].nodes[2].source.end.column, 21);
t.deepEqual(tree.nodes[0].nodes[2].sourceIndex, 13);
t.deepEqual(tree.nodes[1].nodes[1].source.start.line, 1);
t.deepEqual(tree.nodes[1].nodes[1].source.start.column, 25);
t.deepEqual(tree.nodes[1].nodes[1].source.end.column, 36);
t.deepEqual(tree.nodes[1].nodes[1].sourceIndex, 24);
});
(0, _helpers.test)('combinators', 'div > h1 span', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1, "> start line");
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 5, "> start column");
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 5, "> end column");
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 4, "> sourceIndex");
t.deepEqual(tree.nodes[0].nodes[3].source.start.line, 1, "' ' start line");
t.deepEqual(tree.nodes[0].nodes[3].source.start.column, 9, "' ' start column");
t.deepEqual(tree.nodes[0].nodes[3].source.end.column, 9, "' ' end column");
t.deepEqual(tree.nodes[0].nodes[3].sourceIndex, 8, "' ' sourceIndex");
});
(0, _helpers.test)('combinators surrounded by superfluous spaces', 'div > h1 ~ span a', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1, "> start line");
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 7, "> start column");
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 7, "> end column");
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 6, "> sourceIndex");
t.deepEqual(tree.nodes[0].nodes[3].source.start.line, 1, "~ start line");
t.deepEqual(tree.nodes[0].nodes[3].source.start.column, 13, "~ start column");
t.deepEqual(tree.nodes[0].nodes[3].source.end.column, 13, "~ end column");
t.deepEqual(tree.nodes[0].nodes[3].sourceIndex, 12, "~ sourceIndex");
t.deepEqual(tree.nodes[0].nodes[5].source.start.line, 1, "' ' start line");
t.deepEqual(tree.nodes[0].nodes[5].source.start.column, 21, "' ' start column");
t.deepEqual(tree.nodes[0].nodes[5].source.end.column, 23, "' ' end column");
t.deepEqual(tree.nodes[0].nodes[5].sourceIndex, 20, "' ' sourceIndex");
});
(0, _helpers.test)('multiple id selectors on different lines', '#one,\n#two', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.line, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 4);
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0);
t.deepEqual(tree.nodes[1].nodes[0].source.start.line, 2);
t.deepEqual(tree.nodes[1].nodes[0].source.start.column, 1);
t.deepEqual(tree.nodes[1].nodes[0].source.end.column, 4);
t.deepEqual(tree.nodes[1].nodes[0].sourceIndex, 6);
});
(0, _helpers.test)('multiple id selectors on different CRLF lines', '#one,\r\n#two,\r\n#three', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.line, 1, '#one start line');
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 1, '#one start column');
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 4, '#one end column');
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 0, '#one sourceIndex');
t.deepEqual(tree.nodes[1].nodes[0].source.start.line, 2, '#two start line');
t.deepEqual(tree.nodes[1].nodes[0].source.start.column, 1, '#two start column');
t.deepEqual(tree.nodes[1].nodes[0].source.end.column, 4, '#two end column');
t.deepEqual(tree.nodes[1].nodes[0].sourceIndex, 7, '#two sourceIndex');
t.deepEqual(tree.nodes[2].nodes[0].source.start.line, 3, '#three start line');
t.deepEqual(tree.nodes[2].nodes[0].source.start.column, 1, '#three start column');
t.deepEqual(tree.nodes[2].nodes[0].source.end.column, 6, '#three end column');
t.deepEqual(tree.nodes[2].nodes[0].sourceIndex, 14, '#three sourceIndex');
});
(0, _helpers.test)('id, tag, pseudo, and class selectors on different lines with indentation', '\t#one,\n\th1:after,\n\t\t.two', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].source.start.line, 1, '#one start line');
t.deepEqual(tree.nodes[0].nodes[0].source.start.column, 2, '#one start column');
t.deepEqual(tree.nodes[0].nodes[0].source.end.column, 5, '#one end column');
t.deepEqual(tree.nodes[0].nodes[0].sourceIndex, 1, '#one sourceIndex');
t.deepEqual(tree.nodes[1].nodes[0].source.start.line, 2, 'h1 start line');
t.deepEqual(tree.nodes[1].nodes[0].source.start.column, 2, 'h1 start column');
t.deepEqual(tree.nodes[1].nodes[0].source.end.column, 3, 'h1 end column');
t.deepEqual(tree.nodes[1].nodes[0].sourceIndex, 8, 'h1 sourceIndex');
t.deepEqual(tree.nodes[1].nodes[1].source.start.line, 2, ':after start line');
t.deepEqual(tree.nodes[1].nodes[1].source.start.column, 4, ':after start column');
t.deepEqual(tree.nodes[1].nodes[1].source.end.column, 9, ':after end column');
t.deepEqual(tree.nodes[1].nodes[1].sourceIndex, 10, ':after sourceIndex');
t.deepEqual(tree.nodes[2].nodes[0].source.start.line, 3, '.two start line');
t.deepEqual(tree.nodes[2].nodes[0].source.start.column, 3, '.two start column');
t.deepEqual(tree.nodes[2].nodes[0].source.end.column, 6, '.two end column');
t.deepEqual(tree.nodes[2].nodes[0].sourceIndex, 20, '.two sourceIndex');
});
(0, _helpers.test)('pseudo with arguments spanning multiple lines', 'h1:not(\n\t.one,\n\t.two\n)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[1].source.start.line, 1, ':not start line');
t.deepEqual(tree.nodes[0].nodes[1].source.start.column, 3, ':not start column');
t.deepEqual(tree.nodes[0].nodes[1].source.end.line, 4, ':not end line');
t.deepEqual(tree.nodes[0].nodes[1].source.end.column, 1, ':not end column');
t.deepEqual(tree.nodes[0].nodes[1].sourceIndex, 2, ':not sourceIndex');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].source.start.line, 2, '.one start line');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].source.start.column, 2, '.one start column');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].source.end.line, 2, '.one end line');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].source.end.column, 5, '.one end column');
t.deepEqual(tree.nodes[0].nodes[1].nodes[0].nodes[0].sourceIndex, 9, '.one sourceIndex');
t.deepEqual(tree.nodes[0].nodes[1].nodes[1].nodes[0].source.start.line, 3, '.two start line');
t.deepEqual(tree.nodes[0].nodes[1].nodes[1].nodes[0].source.start.column, 2, '.two start column');
t.deepEqual(tree.nodes[0].nodes[1].nodes[1].nodes[0].source.end.line, 3, '.two end line');
t.deepEqual(tree.nodes[0].nodes[1].nodes[1].nodes[0].source.end.column, 5, '.two end column');
t.deepEqual(tree.nodes[0].nodes[1].nodes[1].nodes[0].sourceIndex, 16, '.two sourceIndex');
});
@@ -0,0 +1,17 @@
"use strict";
var _ava = _interopRequireDefault(require("ava"));
var _stripComments = _interopRequireDefault(require("../../src/util/stripComments"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _ava.default)("stripComments()", function (t) {
t.deepEqual((0, _stripComments.default)("aaa/**/bbb"), "aaabbb");
t.deepEqual((0, _stripComments.default)("aaa/*bbb"), "aaa");
t.deepEqual((0, _stripComments.default)("aaa/*xxx*/bbb"), "aaabbb");
t.deepEqual((0, _stripComments.default)("aaa/*/xxx/*/bbb"), "aaabbb");
t.deepEqual((0, _stripComments.default)("aaa/*x*/bbb/**/"), "aaabbb");
t.deepEqual((0, _stripComments.default)("/**/aaa/*x*/bbb/**/"), "aaabbb");
t.deepEqual((0, _stripComments.default)("/**/"), "");
});
@@ -0,0 +1,35 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('tag selector', 'h1', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
});
(0, _helpers.test)('multiple tag selectors', 'h1, h2', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[1].nodes[0].value, 'h2');
});
(0, _helpers.test)('extraneous non-combinating whitespace', ' h1 , h2 ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1');
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.after, ' ');
t.deepEqual(tree.nodes[1].nodes[0].value, 'h2');
t.deepEqual(tree.nodes[1].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[1].nodes[0].spaces.after, ' ');
});
(0, _helpers.test)('tag with trailing comma', 'h1,', function (t, tree) {
t.deepEqual(tree.trailingComma, true);
});
(0, _helpers.test)('tag with trailing slash', 'h1\\', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'h1\\');
});
(0, _helpers.test)('tag with attribute', 'label[for="email"]', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, 'label');
t.deepEqual(tree.nodes[0].nodes[0].type, 'tag');
t.deepEqual(tree.nodes[0].nodes[1].value, 'email');
t.deepEqual(tree.nodes[0].nodes[1].attribute, 'for');
t.deepEqual(tree.nodes[0].nodes[1].operator, '=');
t.deepEqual(tree.nodes[0].nodes[1].type, 'attribute');
t.deepEqual(tree.nodes[0].nodes[1].quoteMark, '"');
});
@@ -0,0 +1,32 @@
"use strict";
var _helpers = require("./util/helpers");
(0, _helpers.test)('universal selector', '*', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
t.deepEqual(tree.nodes[0].nodes[0].type, 'universal');
});
(0, _helpers.test)('lobotomized owl', '* + *', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].type, 'universal');
t.deepEqual(tree.nodes[0].nodes[1].type, 'combinator');
t.deepEqual(tree.nodes[0].nodes[2].type, 'universal');
});
(0, _helpers.test)('extraneous non-combinating whitespace', ' * , * ', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
t.deepEqual(tree.nodes[0].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[0].nodes[0].spaces.after, ' ');
t.deepEqual(tree.nodes[1].nodes[0].value, '*');
t.deepEqual(tree.nodes[1].nodes[0].spaces.before, ' ');
t.deepEqual(tree.nodes[1].nodes[0].spaces.after, ' ');
});
(0, _helpers.test)('qualified universal selector', '*[href] *:not(*.green)', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
t.deepEqual(tree.nodes[0].nodes[3].value, '*');
t.deepEqual(tree.nodes[0].nodes[4].nodes[0].nodes[0].value, '*');
});
(0, _helpers.test)('universal selector with pseudo', '*::--webkit-media-controls-play-button', function (t, tree) {
t.deepEqual(tree.nodes[0].nodes[0].value, '*');
t.deepEqual(tree.nodes[0].nodes[0].type, 'universal');
t.deepEqual(tree.nodes[0].nodes[1].value, '::--webkit-media-controls-play-button');
t.deepEqual(tree.nodes[0].nodes[1].type, 'pseudo');
});
@@ -0,0 +1,90 @@
"use strict";
exports.__esModule = true;
exports.test = test;
exports.nodeVersionAtLeast = nodeVersionAtLeast;
exports.nodeVersionBefore = nodeVersionBefore;
exports.throws = exports.parse = void 0;
var _process = _interopRequireDefault(require("process"));
var _util = _interopRequireDefault(require("util"));
var _ava = _interopRequireDefault(require("ava"));
var _semver = _interopRequireDefault(require("semver"));
var _index = _interopRequireDefault(require("../../index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var parse = function parse(input, transform) {
return (0, _index.default)(transform).processSync(input);
};
exports.parse = parse;
function test(spec, input, callback, only, disabled, serial) {
var _this = this;
if (only === void 0) {
only = false;
}
if (disabled === void 0) {
disabled = false;
}
if (serial === void 0) {
serial = false;
}
var tester = only ? _ava.default.only : _ava.default;
tester = disabled ? tester.skip : tester;
tester = serial ? tester.serial : tester;
if (callback) {
tester(spec + " (tree)", function (t) {
var tree = (0, _index.default)().astSync(input);
var debug = _util.default.inspect(tree, false, null);
return callback.call(_this, t, tree, debug);
});
}
tester(spec + " (toString)", function (t) {
var result = (0, _index.default)().processSync(input);
t.deepEqual(result, input);
});
}
test.only = function (spec, input, callback) {
return test(spec, input, callback, true);
};
test.skip = function (spec, input, callback) {
return test(spec, input, callback, false, true);
};
test.serial = function (spec, input, callback) {
return test(spec, input, callback, false, false, true);
};
var throws = function throws(spec, input, validator) {
(0, _ava.default)(spec + " (throws)", function (t) {
t.throws(function () {
return (0, _index.default)().processSync(input);
}, validator || Error);
});
};
exports.throws = throws;
function nodeVersionAtLeast(version) {
return _semver.default.gte(_process.default.versions.node, version);
}
function nodeVersionBefore(version) {
return _semver.default.lt(_process.default.versions.node, version);
}
@@ -0,0 +1,22 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _processor = _interopRequireDefault(require("./processor"));
var selectors = _interopRequireWildcard(require("./selectors"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var parser = function parser(processor) {
return new _processor.default(processor);
};
Object.assign(parser, selectors);
delete parser.__esModule;
var _default = parser;
exports.default = _default;
module.exports = exports.default;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,208 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _parser = _interopRequireDefault(require("./parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Processor =
/*#__PURE__*/
function () {
function Processor(func, options) {
this.func = func || function noop() {};
this.funcRes = null;
this.options = options;
}
var _proto = Processor.prototype;
_proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
if (options === void 0) {
options = {};
}
var merged = Object.assign({}, this.options, options);
if (merged.updateSelector === false) {
return false;
} else {
return typeof rule !== "string";
}
};
_proto._isLossy = function _isLossy(options) {
if (options === void 0) {
options = {};
}
var merged = Object.assign({}, this.options, options);
if (merged.lossless === false) {
return true;
} else {
return false;
}
};
_proto._root = function _root(rule, options) {
if (options === void 0) {
options = {};
}
var parser = new _parser.default(rule, this._parseOptions(options));
return parser.root;
};
_proto._parseOptions = function _parseOptions(options) {
return {
lossy: this._isLossy(options)
};
};
_proto._run = function _run(rule, options) {
var _this = this;
if (options === void 0) {
options = {};
}
return new Promise(function (resolve, reject) {
try {
var root = _this._root(rule, options);
Promise.resolve(_this.func(root)).then(function (transform) {
var string = undefined;
if (_this._shouldUpdateSelector(rule, options)) {
string = root.toString();
rule.selector = string;
}
return {
transform: transform,
root: root,
string: string
};
}).then(resolve, reject);
} catch (e) {
reject(e);
return;
}
});
};
_proto._runSync = function _runSync(rule, options) {
if (options === void 0) {
options = {};
}
var root = this._root(rule, options);
var transform = this.func(root);
if (transform && typeof transform.then === "function") {
throw new Error("Selector processor returned a promise to a synchronous call.");
}
var string = undefined;
if (options.updateSelector && typeof rule !== "string") {
string = root.toString();
rule.selector = string;
}
return {
transform: transform,
root: root,
string: string
};
}
/**
* Process rule into a selector AST.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {Promise<parser.Root>} The AST of the selector after processing it.
*/
;
_proto.ast = function ast(rule, options) {
return this._run(rule, options).then(function (result) {
return result.root;
});
}
/**
* Process rule into a selector AST synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {parser.Root} The AST of the selector after processing it.
*/
;
_proto.astSync = function astSync(rule, options) {
return this._runSync(rule, options).root;
}
/**
* Process a selector into a transformed value asynchronously
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {Promise<any>} The value returned by the processor.
*/
;
_proto.transform = function transform(rule, options) {
return this._run(rule, options).then(function (result) {
return result.transform;
});
}
/**
* Process a selector into a transformed value synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {any} The value returned by the processor.
*/
;
_proto.transformSync = function transformSync(rule, options) {
return this._runSync(rule, options).transform;
}
/**
* Process a selector into a new selector string asynchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {string} the selector after processing.
*/
;
_proto.process = function process(rule, options) {
return this._run(rule, options).then(function (result) {
return result.string || result.root.toString();
});
}
/**
* Process a selector into a new selector string synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {string} the selector after processing.
*/
;
_proto.processSync = function processSync(rule, options) {
var result = this._runSync(rule, options);
return result.string || result.root.toString();
};
return Processor;
}();
exports.default = Processor;
module.exports = exports.default;
@@ -0,0 +1,516 @@
"use strict";
exports.__esModule = true;
exports.unescapeValue = unescapeValue;
exports.default = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _unesc = _interopRequireDefault(require("../util/unesc"));
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
var _CSSESC_QUOTE_OPTIONS;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var _require = require("util"),
deprecate = _require.deprecate;
var WRAPPED_IN_QUOTES = /^('|")(.*)\1$/;
var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
function unescapeValue(value) {
var deprecatedUsage = false;
var quoteMark = null;
var unescaped = value;
var m = unescaped.match(WRAPPED_IN_QUOTES);
if (m) {
quoteMark = m[1];
unescaped = m[2];
}
unescaped = (0, _unesc.default)(unescaped);
if (unescaped !== value) {
deprecatedUsage = true;
}
return {
deprecatedUsage: deprecatedUsage,
unescaped: unescaped,
quoteMark: quoteMark
};
}
function handleDeprecatedContructorOpts(opts) {
if (opts.quoteMark !== undefined) {
return opts;
}
if (opts.value === undefined) {
return opts;
}
warnOfDeprecatedConstructor();
var _unescapeValue = unescapeValue(opts.value),
quoteMark = _unescapeValue.quoteMark,
unescaped = _unescapeValue.unescaped;
if (!opts.raws) {
opts.raws = {};
}
if (opts.raws.value === undefined) {
opts.raws.value = opts.value;
}
opts.value = unescaped;
opts.quoteMark = quoteMark;
return opts;
}
var Attribute =
/*#__PURE__*/
function (_Namespace) {
_inheritsLoose(Attribute, _Namespace);
function Attribute(opts) {
var _this;
if (opts === void 0) {
opts = {};
}
_this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
_this.type = _types.ATTRIBUTE;
_this.raws = _this.raws || {};
Object.defineProperty(_this.raws, 'unquoted', {
get: deprecate(function () {
return _this.value;
}, "attr.raws.unquoted is deprecated. Call attr.value instead."),
set: deprecate(function () {
return _this.value;
}, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
});
_this._constructed = true;
return _this;
}
/**
* Returns the Attribute's value quoted such that it would be legal to use
* in the value of a css file. The original value's quotation setting
* used for stringification is left unchanged. See `setValue(value, options)`
* if you want to control the quote settings of a new value for the attribute.
*
* You can also change the quotation used for the current value by setting quoteMark.
*
* Options:
* * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
* option is not set, the original value for quoteMark will be used. If
* indeterminate, a double quote is used. The legal values are:
* * `null` - the value will be unquoted and characters will be escaped as necessary.
* * `'` - the value will be quoted with a single quote and single quotes are escaped.
* * `"` - the value will be quoted with a double quote and double quotes are escaped.
* * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
* over the quoteMark option value.
* * smart {boolean} - if true, will select a quote mark based on the value
* and the other options specified here. See the `smartQuoteMark()`
* method.
**/
var _proto = Attribute.prototype;
_proto.getQuotedValue = function getQuotedValue(options) {
if (options === void 0) {
options = {};
}
var quoteMark = this._determineQuoteMark(options);
var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
var escaped = (0, _cssesc.default)(this._value, cssescopts);
return escaped;
};
_proto._determineQuoteMark = function _determineQuoteMark(options) {
return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
}
/**
* Set the unescaped value with the specified quotation options. The value
* provided must not include any wrapping quote marks -- those quotes will
* be interpreted as part of the value and escaped accordingly.
*/
;
_proto.setValue = function setValue(value, options) {
if (options === void 0) {
options = {};
}
this._value = value;
this._quoteMark = this._determineQuoteMark(options);
this._syncRawValue();
}
/**
* Intelligently select a quoteMark value based on the value's contents. If
* the value is a legal CSS ident, it will not be quoted. Otherwise a quote
* mark will be picked that minimizes the number of escapes.
*
* If there's no clear winner, the quote mark from these options is used,
* then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
* true). If the quoteMark is unspecified, a double quote is used.
*
* @param options This takes the quoteMark and preferCurrentQuoteMark options
* from the quoteValue method.
*/
;
_proto.smartQuoteMark = function smartQuoteMark(options) {
var v = this.value;
var numSingleQuotes = v.replace(/[^']/g, '').length;
var numDoubleQuotes = v.replace(/[^"]/g, '').length;
if (numSingleQuotes + numDoubleQuotes === 0) {
var escaped = (0, _cssesc.default)(v, {
isIdentifier: true
});
if (escaped === v) {
return Attribute.NO_QUOTE;
} else {
var pref = this.preferredQuoteMark(options);
if (pref === Attribute.NO_QUOTE) {
// pick a quote mark that isn't none and see if it's smaller
var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
var opts = CSSESC_QUOTE_OPTIONS[quote];
var quoteValue = (0, _cssesc.default)(v, opts);
if (quoteValue.length < escaped.length) {
return quote;
}
}
return pref;
}
} else if (numDoubleQuotes === numSingleQuotes) {
return this.preferredQuoteMark(options);
} else if (numDoubleQuotes < numSingleQuotes) {
return Attribute.DOUBLE_QUOTE;
} else {
return Attribute.SINGLE_QUOTE;
}
}
/**
* Selects the preferred quote mark based on the options and the current quote mark value.
* If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
* instead.
*/
;
_proto.preferredQuoteMark = function preferredQuoteMark(options) {
var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
if (quoteMark === undefined) {
quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
}
if (quoteMark === undefined) {
quoteMark = Attribute.DOUBLE_QUOTE;
}
return quoteMark;
};
_proto._syncRawValue = function _syncRawValue() {
var rawValue = (0, _cssesc.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
if (rawValue === this._value) {
if (this.raws) {
delete this.raws.value;
}
} else {
this.raws.value = rawValue;
}
};
_proto._handleEscapes = function _handleEscapes(prop, value) {
if (this._constructed) {
var escaped = (0, _cssesc.default)(value, {
isIdentifier: true
});
if (escaped !== value) {
this.raws[prop] = escaped;
} else {
delete this.raws[prop];
}
}
};
_proto._spacesFor = function _spacesFor(name) {
var attrSpaces = {
before: '',
after: ''
};
var spaces = this.spaces[name] || {};
var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
return Object.assign(attrSpaces, spaces, rawSpaces);
};
_proto._stringFor = function _stringFor(name, spaceName, concat) {
if (spaceName === void 0) {
spaceName = name;
}
if (concat === void 0) {
concat = defaultAttrConcat;
}
var attrSpaces = this._spacesFor(spaceName);
return concat(this.stringifyProperty(name), attrSpaces);
}
/**
* returns the offset of the attribute part specified relative to the
* start of the node of the output string.
*
* * "ns" - alias for "namespace"
* * "namespace" - the namespace if it exists.
* * "attribute" - the attribute name
* * "attributeNS" - the start of the attribute or its namespace
* * "operator" - the match operator of the attribute
* * "value" - The value (string or identifier)
* * "insensitive" - the case insensitivity flag;
* @param part One of the possible values inside an attribute.
* @returns -1 if the name is invalid or the value doesn't exist in this attribute.
*/
;
_proto.offsetOf = function offsetOf(name) {
var count = 1;
var attributeSpaces = this._spacesFor("attribute");
count += attributeSpaces.before.length;
if (name === "namespace" || name === "ns") {
return this.namespace ? count : -1;
}
if (name === "attributeNS") {
return count;
}
count += this.namespaceString.length;
if (this.namespace) {
count += 1;
}
if (name === "attribute") {
return count;
}
count += this.stringifyProperty("attribute").length;
count += attributeSpaces.after.length;
var operatorSpaces = this._spacesFor("operator");
count += operatorSpaces.before.length;
var operator = this.stringifyProperty("operator");
if (name === "operator") {
return operator ? count : -1;
}
count += operator.length;
count += operatorSpaces.after.length;
var valueSpaces = this._spacesFor("value");
count += valueSpaces.before.length;
var value = this.stringifyProperty("value");
if (name === "value") {
return value ? count : -1;
}
count += value.length;
count += valueSpaces.after.length;
var insensitiveSpaces = this._spacesFor("insensitive");
count += insensitiveSpaces.before.length;
if (name === "insensitive") {
return this.insensitive ? count : -1;
}
return -1;
};
_proto.toString = function toString() {
var _this2 = this;
var selector = [this.rawSpaceBefore, '['];
selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
if (this.operator && (this.value || this.value === '')) {
selector.push(this._stringFor('operator'));
selector.push(this._stringFor('value'));
selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
attrSpaces.before = " ";
}
return defaultAttrConcat(attrValue, attrSpaces);
}));
}
selector.push(']');
selector.push(this.rawSpaceAfter);
return selector.join('');
};
_createClass(Attribute, [{
key: "quoted",
get: function get() {
var qm = this.quoteMark;
return qm === "'" || qm === '"';
},
set: function set(value) {
warnOfDeprecatedQuotedAssignment();
}
/**
* returns a single (`'`) or double (`"`) quote character if the value is quoted.
* returns `null` if the value is not quoted.
* returns `undefined` if the quotation state is unknown (this can happen when
* the attribute is constructed without specifying a quote mark.)
*/
}, {
key: "quoteMark",
get: function get() {
return this._quoteMark;
}
/**
* Set the quote mark to be used by this attribute's value.
* If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
* value is updated accordingly.
*
* @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
*/
,
set: function set(quoteMark) {
if (!this._constructed) {
this._quoteMark = quoteMark;
return;
}
if (this._quoteMark !== quoteMark) {
this._quoteMark = quoteMark;
this._syncRawValue();
}
}
}, {
key: "qualifiedAttribute",
get: function get() {
return this.qualifiedName(this.raws.attribute || this.attribute);
}
}, {
key: "insensitiveFlag",
get: function get() {
return this.insensitive ? 'i' : '';
}
}, {
key: "value",
get: function get() {
return this._value;
}
/**
* Before 3.0, the value had to be set to an escaped value including any wrapped
* quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
* is unescaped during parsing and any quote marks are removed.
*
* Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
* a deprecation warning is raised when the new value contains any characters that would
* require escaping (including if it contains wrapped quotes).
*
* Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
* how the new value is quoted.
*/
,
set: function set(v) {
if (this._constructed) {
var _unescapeValue2 = unescapeValue(v),
deprecatedUsage = _unescapeValue2.deprecatedUsage,
unescaped = _unescapeValue2.unescaped,
quoteMark = _unescapeValue2.quoteMark;
if (deprecatedUsage) {
warnOfDeprecatedValueAssignment();
}
if (unescaped === this._value && quoteMark === this._quoteMark) {
return;
}
this._value = unescaped;
this._quoteMark = quoteMark;
this._syncRawValue();
} else {
this._value = v;
}
}
}, {
key: "attribute",
get: function get() {
return this._attribute;
},
set: function set(name) {
this._handleEscapes("attribute", name);
this._attribute = name;
}
}]);
return Attribute;
}(_namespace.default);
exports.default = Attribute;
Attribute.NO_QUOTE = null;
Attribute.SINGLE_QUOTE = "'";
Attribute.DOUBLE_QUOTE = '"';
var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
"'": {
quotes: 'single',
wrap: true
},
'"': {
quotes: 'double',
wrap: true
}
}, _CSSESC_QUOTE_OPTIONS[null] = {
isIdentifier: true
}, _CSSESC_QUOTE_OPTIONS);
function defaultAttrConcat(attrValue, attrSpaces) {
return "" + attrSpaces.before + attrValue + attrSpaces.after;
}
@@ -0,0 +1,69 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _util = require("../util");
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var ClassName =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(ClassName, _Node);
function ClassName(opts) {
var _this;
_this = _Node.call(this, opts) || this;
_this.type = _types.CLASS;
_this._constructed = true;
return _this;
}
var _proto = ClassName.prototype;
_proto.toString = function toString() {
return [this.rawSpaceBefore, String('.' + this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
_createClass(ClassName, [{
key: "value",
set: function set(v) {
if (this._constructed) {
var escaped = (0, _cssesc.default)(v, {
isIdentifier: true
});
if (escaped !== v) {
(0, _util.ensureObject)(this, "raws");
this.raws.value = escaped;
} else if (this.raws) {
delete this.raws.value;
}
}
this._value = v;
},
get: function get() {
return this._value;
}
}]);
return ClassName;
}(_node.default);
exports.default = ClassName;
module.exports = exports.default;
@@ -0,0 +1,31 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Combinator =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(Combinator, _Node);
function Combinator(opts) {
var _this;
_this = _Node.call(this, opts) || this;
_this.type = _types.COMBINATOR;
return _this;
}
return Combinator;
}(_node.default);
exports.default = Combinator;
module.exports = exports.default;
@@ -0,0 +1,31 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Comment =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(Comment, _Node);
function Comment(opts) {
var _this;
_this = _Node.call(this, opts) || this;
_this.type = _types.COMMENT;
return _this;
}
return Comment;
}(_node.default);
exports.default = Comment;
module.exports = exports.default;
@@ -0,0 +1,102 @@
"use strict";
exports.__esModule = true;
exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
var _attribute = _interopRequireDefault(require("./attribute"));
var _className = _interopRequireDefault(require("./className"));
var _combinator = _interopRequireDefault(require("./combinator"));
var _comment = _interopRequireDefault(require("./comment"));
var _id = _interopRequireDefault(require("./id"));
var _nesting = _interopRequireDefault(require("./nesting"));
var _pseudo = _interopRequireDefault(require("./pseudo"));
var _root = _interopRequireDefault(require("./root"));
var _selector = _interopRequireDefault(require("./selector"));
var _string = _interopRequireDefault(require("./string"));
var _tag = _interopRequireDefault(require("./tag"));
var _universal = _interopRequireDefault(require("./universal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var attribute = function attribute(opts) {
return new _attribute.default(opts);
};
exports.attribute = attribute;
var className = function className(opts) {
return new _className.default(opts);
};
exports.className = className;
var combinator = function combinator(opts) {
return new _combinator.default(opts);
};
exports.combinator = combinator;
var comment = function comment(opts) {
return new _comment.default(opts);
};
exports.comment = comment;
var id = function id(opts) {
return new _id.default(opts);
};
exports.id = id;
var nesting = function nesting(opts) {
return new _nesting.default(opts);
};
exports.nesting = nesting;
var pseudo = function pseudo(opts) {
return new _pseudo.default(opts);
};
exports.pseudo = pseudo;
var root = function root(opts) {
return new _root.default(opts);
};
exports.root = root;
var selector = function selector(opts) {
return new _selector.default(opts);
};
exports.selector = selector;
var string = function string(opts) {
return new _string.default(opts);
};
exports.string = string;
var tag = function tag(opts) {
return new _tag.default(opts);
};
exports.tag = tag;
var universal = function universal(opts) {
return new _universal.default(opts);
};
exports.universal = universal;
@@ -0,0 +1,398 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _node = _interopRequireDefault(require("./node"));
var types = _interopRequireWildcard(require("./types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Container =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(Container, _Node);
function Container(opts) {
var _this;
_this = _Node.call(this, opts) || this;
if (!_this.nodes) {
_this.nodes = [];
}
return _this;
}
var _proto = Container.prototype;
_proto.append = function append(selector) {
selector.parent = this;
this.nodes.push(selector);
return this;
};
_proto.prepend = function prepend(selector) {
selector.parent = this;
this.nodes.unshift(selector);
return this;
};
_proto.at = function at(index) {
return this.nodes[index];
};
_proto.index = function index(child) {
if (typeof child === 'number') {
return child;
}
return this.nodes.indexOf(child);
};
_proto.removeChild = function removeChild(child) {
child = this.index(child);
this.at(child).parent = undefined;
this.nodes.splice(child, 1);
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
_proto.removeAll = function removeAll() {
for (var _iterator = this.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
node.parent = undefined;
}
this.nodes = [];
return this;
};
_proto.empty = function empty() {
return this.removeAll();
};
_proto.insertAfter = function insertAfter(oldNode, newNode) {
newNode.parent = this;
var oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex + 1, 0, newNode);
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (oldIndex <= index) {
this.indexes[id] = index + 1;
}
}
return this;
};
_proto.insertBefore = function insertBefore(oldNode, newNode) {
newNode.parent = this;
var oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex, 0, newNode);
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index <= oldIndex) {
this.indexes[id] = index + 1;
}
}
return this;
};
_proto._findChildAtPosition = function _findChildAtPosition(line, col) {
var found = undefined;
this.each(function (node) {
if (node.atPosition) {
var foundChild = node.atPosition(line, col);
if (foundChild) {
found = foundChild;
return false;
}
} else if (node.isAtPosition(line, col)) {
found = node;
return false;
}
});
return found;
}
/**
* Return the most specific node at the line and column number given.
* The source location is based on the original parsed location, locations aren't
* updated as selector nodes are mutated.
*
* Note that this location is relative to the location of the first character
* of the selector, and not the location of the selector in the overall document
* when used in conjunction with postcss.
*
* If not found, returns undefined.
* @param {number} line The line number of the node to find. (1-based index)
* @param {number} col The column number of the node to find. (1-based index)
*/
;
_proto.atPosition = function atPosition(line, col) {
if (this.isAtPosition(line, col)) {
return this._findChildAtPosition(line, col) || this;
} else {
return undefined;
}
};
_proto._inferEndPosition = function _inferEndPosition() {
if (this.last && this.last.source && this.last.source.end) {
this.source = this.source || {};
this.source.end = this.source.end || {};
Object.assign(this.source.end, this.last.source.end);
}
};
_proto.each = function each(callback) {
if (!this.lastEach) {
this.lastEach = 0;
}
if (!this.indexes) {
this.indexes = {};
}
this.lastEach++;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.length) {
return undefined;
}
var index, result;
while (this.indexes[id] < this.length) {
index = this.indexes[id];
result = callback(this.at(index), index);
if (result === false) {
break;
}
this.indexes[id] += 1;
}
delete this.indexes[id];
if (result === false) {
return false;
}
};
_proto.walk = function walk(callback) {
return this.each(function (node, i) {
var result = callback(node, i);
if (result !== false && node.length) {
result = node.walk(callback);
}
if (result === false) {
return false;
}
});
};
_proto.walkAttributes = function walkAttributes(callback) {
var _this2 = this;
return this.walk(function (selector) {
if (selector.type === types.ATTRIBUTE) {
return callback.call(_this2, selector);
}
});
};
_proto.walkClasses = function walkClasses(callback) {
var _this3 = this;
return this.walk(function (selector) {
if (selector.type === types.CLASS) {
return callback.call(_this3, selector);
}
});
};
_proto.walkCombinators = function walkCombinators(callback) {
var _this4 = this;
return this.walk(function (selector) {
if (selector.type === types.COMBINATOR) {
return callback.call(_this4, selector);
}
});
};
_proto.walkComments = function walkComments(callback) {
var _this5 = this;
return this.walk(function (selector) {
if (selector.type === types.COMMENT) {
return callback.call(_this5, selector);
}
});
};
_proto.walkIds = function walkIds(callback) {
var _this6 = this;
return this.walk(function (selector) {
if (selector.type === types.ID) {
return callback.call(_this6, selector);
}
});
};
_proto.walkNesting = function walkNesting(callback) {
var _this7 = this;
return this.walk(function (selector) {
if (selector.type === types.NESTING) {
return callback.call(_this7, selector);
}
});
};
_proto.walkPseudos = function walkPseudos(callback) {
var _this8 = this;
return this.walk(function (selector) {
if (selector.type === types.PSEUDO) {
return callback.call(_this8, selector);
}
});
};
_proto.walkTags = function walkTags(callback) {
var _this9 = this;
return this.walk(function (selector) {
if (selector.type === types.TAG) {
return callback.call(_this9, selector);
}
});
};
_proto.walkUniversals = function walkUniversals(callback) {
var _this10 = this;
return this.walk(function (selector) {
if (selector.type === types.UNIVERSAL) {
return callback.call(_this10, selector);
}
});
};
_proto.split = function split(callback) {
var _this11 = this;
var current = [];
return this.reduce(function (memo, node, index) {
var split = callback.call(_this11, node);
current.push(node);
if (split) {
memo.push(current);
current = [];
} else if (index === _this11.length - 1) {
memo.push(current);
}
return memo;
}, []);
};
_proto.map = function map(callback) {
return this.nodes.map(callback);
};
_proto.reduce = function reduce(callback, memo) {
return this.nodes.reduce(callback, memo);
};
_proto.every = function every(callback) {
return this.nodes.every(callback);
};
_proto.some = function some(callback) {
return this.nodes.some(callback);
};
_proto.filter = function filter(callback) {
return this.nodes.filter(callback);
};
_proto.sort = function sort(callback) {
return this.nodes.sort(callback);
};
_proto.toString = function toString() {
return this.map(String).join('');
};
_createClass(Container, [{
key: "first",
get: function get() {
return this.at(0);
}
}, {
key: "last",
get: function get() {
return this.at(this.length - 1);
}
}, {
key: "length",
get: function get() {
return this.nodes.length;
}
}]);
return Container;
}(_node.default);
exports.default = Container;
module.exports = exports.default;
@@ -0,0 +1,64 @@
"use strict";
exports.__esModule = true;
exports.isNode = isNode;
exports.isPseudoElement = isPseudoElement;
exports.isPseudoClass = isPseudoClass;
exports.isContainer = isContainer;
exports.isNamespace = isNamespace;
exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
var _types = require("./types");
var _IS_TYPE;
var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
function isNode(node) {
return typeof node === "object" && IS_TYPE[node.type];
}
function isNodeType(type, node) {
return isNode(node) && node.type === type;
}
var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
exports.isAttribute = isAttribute;
var isClassName = isNodeType.bind(null, _types.CLASS);
exports.isClassName = isClassName;
var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
exports.isCombinator = isCombinator;
var isComment = isNodeType.bind(null, _types.COMMENT);
exports.isComment = isComment;
var isIdentifier = isNodeType.bind(null, _types.ID);
exports.isIdentifier = isIdentifier;
var isNesting = isNodeType.bind(null, _types.NESTING);
exports.isNesting = isNesting;
var isPseudo = isNodeType.bind(null, _types.PSEUDO);
exports.isPseudo = isPseudo;
var isRoot = isNodeType.bind(null, _types.ROOT);
exports.isRoot = isRoot;
var isSelector = isNodeType.bind(null, _types.SELECTOR);
exports.isSelector = isSelector;
var isString = isNodeType.bind(null, _types.STRING);
exports.isString = isString;
var isTag = isNodeType.bind(null, _types.TAG);
exports.isTag = isTag;
var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
exports.isUniversal = isUniversal;
function isPseudoElement(node) {
return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value === ":before" || node.value === ":after");
}
function isPseudoClass(node) {
return isPseudo(node) && !isPseudoElement(node);
}
function isContainer(node) {
return !!(isNode(node) && node.walk);
}
function isNamespace(node) {
return isAttribute(node) || isTag(node);
}
@@ -0,0 +1,37 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var ID =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(ID, _Node);
function ID(opts) {
var _this;
_this = _Node.call(this, opts) || this;
_this.type = _types.ID;
return _this;
}
var _proto = ID.prototype;
_proto.toString = function toString() {
return [this.rawSpaceBefore, String('#' + this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
return ID;
}(_node.default);
exports.default = ID;
module.exports = exports.default;
@@ -0,0 +1,24 @@
"use strict";
exports.__esModule = true;
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
exports[key] = _types[key];
});
var _constructors = require("./constructors");
Object.keys(_constructors).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
exports[key] = _constructors[key];
});
var _guards = require("./guards");
Object.keys(_guards).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
exports[key] = _guards[key];
});
@@ -0,0 +1,101 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _util = require("../util");
var _node = _interopRequireDefault(require("./node"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Namespace =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(Namespace, _Node);
function Namespace() {
return _Node.apply(this, arguments) || this;
}
var _proto = Namespace.prototype;
_proto.qualifiedName = function qualifiedName(value) {
if (this.namespace) {
return this.namespaceString + "|" + value;
} else {
return value;
}
};
_proto.toString = function toString() {
return [this.rawSpaceBefore, this.qualifiedName(this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
_createClass(Namespace, [{
key: "namespace",
get: function get() {
return this._namespace;
},
set: function set(namespace) {
if (namespace === true || namespace === "*" || namespace === "&") {
this._namespace = namespace;
if (this.raws) {
delete this.raws.namespace;
}
return;
}
var escaped = (0, _cssesc.default)(namespace, {
isIdentifier: true
});
this._namespace = namespace;
if (escaped !== namespace) {
(0, _util.ensureObject)(this, "raws");
this.raws.namespace = escaped;
} else if (this.raws) {
delete this.raws.namespace;
}
}
}, {
key: "ns",
get: function get() {
return this._namespace;
},
set: function set(namespace) {
this.namespace = namespace;
}
}, {
key: "namespaceString",
get: function get() {
if (this.namespace) {
var ns = this.stringifyProperty("namespace");
if (ns === true) {
return '';
} else {
return ns;
}
} else {
return '';
}
}
}]);
return Namespace;
}(_node.default);
exports.default = Namespace;
;
module.exports = exports.default;
@@ -0,0 +1,32 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Nesting =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(Nesting, _Node);
function Nesting(opts) {
var _this;
_this = _Node.call(this, opts) || this;
_this.type = _types.NESTING;
_this.value = '&';
return _this;
}
return Nesting;
}(_node.default);
exports.default = Nesting;
module.exports = exports.default;
@@ -0,0 +1,237 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _util = require("../util");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var cloneNode = function cloneNode(obj, parent) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) {
continue;
}
var value = obj[i];
var type = typeof value;
if (i === 'parent' && type === 'object') {
if (parent) {
cloned[i] = parent;
}
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else {
cloned[i] = cloneNode(value, cloned);
}
}
return cloned;
};
var Node =
/*#__PURE__*/
function () {
function Node(opts) {
if (opts === void 0) {
opts = {};
}
Object.assign(this, opts);
this.spaces = this.spaces || {};
this.spaces.before = this.spaces.before || '';
this.spaces.after = this.spaces.after || '';
}
var _proto = Node.prototype;
_proto.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
_proto.replaceWith = function replaceWith() {
if (this.parent) {
for (var index in arguments) {
this.parent.insertBefore(this, arguments[index]);
}
this.remove();
}
return this;
};
_proto.next = function next() {
return this.parent.at(this.parent.index(this) + 1);
};
_proto.prev = function prev() {
return this.parent.at(this.parent.index(this) - 1);
};
_proto.clone = function clone(overrides) {
if (overrides === void 0) {
overrides = {};
}
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
}
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows non standard syntax to be appended to an existing property
* by specifying the escaped value. By specifying the escaped value,
* illegal characters are allowed to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped optional. the escaped value of the property.
*/
;
_proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
if (!this.raws) {
this.raws = {};
}
var originalValue = this[name];
var originalEscaped = this.raws[name];
this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
if (originalEscaped || valueEscaped !== value) {
this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
} else {
delete this.raws[name]; // delete any escaped value that was created by the setter.
}
}
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows the escaped value to be specified directly, allowing illegal
* characters to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped the escaped value of the property.
*/
;
_proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
if (!this.raws) {
this.raws = {};
}
this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
this.raws[name] = valueEscaped;
}
/**
* When you want a value to passed through to CSS directly. This method
* deletes the corresponding raw value causing the stringifier to fallback
* to the unescaped value.
* @param {string} name the property to set.
* @param {any} value The value that is both escaped and unescaped.
*/
;
_proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
if (this.raws) {
delete this.raws[name];
}
}
/**
*
* @param {number} line The number (starting with 1)
* @param {number} column The column number (starting with 1)
*/
;
_proto.isAtPosition = function isAtPosition(line, column) {
if (this.source && this.source.start && this.source.end) {
if (this.source.start.line > line) {
return false;
}
if (this.source.end.line < line) {
return false;
}
if (this.source.start.line === line && this.source.start.column > column) {
return false;
}
if (this.source.end.line === line && this.source.end.column < column) {
return false;
}
return true;
}
return undefined;
};
_proto.stringifyProperty = function stringifyProperty(name) {
return this.raws && this.raws[name] || this[name];
};
_proto.toString = function toString() {
return [this.rawSpaceBefore, String(this.stringifyProperty("value")), this.rawSpaceAfter].join('');
};
_createClass(Node, [{
key: "rawSpaceBefore",
get: function get() {
var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
if (rawSpace === undefined) {
rawSpace = this.spaces && this.spaces.before;
}
return rawSpace || "";
},
set: function set(raw) {
(0, _util.ensureObject)(this, "raws", "spaces");
this.raws.spaces.before = raw;
}
}, {
key: "rawSpaceAfter",
get: function get() {
var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
if (rawSpace === undefined) {
rawSpace = this.spaces.after;
}
return rawSpace || "";
},
set: function set(raw) {
(0, _util.ensureObject)(this, "raws", "spaces");
this.raws.spaces.after = raw;
}
}]);
return Node;
}();
exports.default = Node;
module.exports = exports.default;
@@ -0,0 +1,38 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Pseudo =
/*#__PURE__*/
function (_Container) {
_inheritsLoose(Pseudo, _Container);
function Pseudo(opts) {
var _this;
_this = _Container.call(this, opts) || this;
_this.type = _types.PSEUDO;
return _this;
}
var _proto = Pseudo.prototype;
_proto.toString = function toString() {
var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
};
return Pseudo;
}(_container.default);
exports.default = Pseudo;
module.exports = exports.default;
@@ -0,0 +1,60 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Root =
/*#__PURE__*/
function (_Container) {
_inheritsLoose(Root, _Container);
function Root(opts) {
var _this;
_this = _Container.call(this, opts) || this;
_this.type = _types.ROOT;
return _this;
}
var _proto = Root.prototype;
_proto.toString = function toString() {
var str = this.reduce(function (memo, selector) {
memo.push(String(selector));
return memo;
}, []).join(',');
return this.trailingComma ? str + ',' : str;
};
_proto.error = function error(message, options) {
if (this._error) {
return this._error(message, options);
} else {
return new Error(message);
}
};
_createClass(Root, [{
key: "errorGenerator",
set: function set(handler) {
this._error = handler;
}
}]);
return Root;
}(_container.default);
exports.default = Root;
module.exports = exports.default;
@@ -0,0 +1,31 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Selector =
/*#__PURE__*/
function (_Container) {
_inheritsLoose(Selector, _Container);
function Selector(opts) {
var _this;
_this = _Container.call(this, opts) || this;
_this.type = _types.SELECTOR;
return _this;
}
return Selector;
}(_container.default);
exports.default = Selector;
module.exports = exports.default;
@@ -0,0 +1,31 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var String =
/*#__PURE__*/
function (_Node) {
_inheritsLoose(String, _Node);
function String(opts) {
var _this;
_this = _Node.call(this, opts) || this;
_this.type = _types.STRING;
return _this;
}
return String;
}(_node.default);
exports.default = String;
module.exports = exports.default;
@@ -0,0 +1,31 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Tag =
/*#__PURE__*/
function (_Namespace) {
_inheritsLoose(Tag, _Namespace);
function Tag(opts) {
var _this;
_this = _Namespace.call(this, opts) || this;
_this.type = _types.TAG;
return _this;
}
return Tag;
}(_namespace.default);
exports.default = Tag;
module.exports = exports.default;
@@ -0,0 +1,28 @@
"use strict";
exports.__esModule = true;
exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0;
var TAG = 'tag';
exports.TAG = TAG;
var STRING = 'string';
exports.STRING = STRING;
var SELECTOR = 'selector';
exports.SELECTOR = SELECTOR;
var ROOT = 'root';
exports.ROOT = ROOT;
var PSEUDO = 'pseudo';
exports.PSEUDO = PSEUDO;
var NESTING = 'nesting';
exports.NESTING = NESTING;
var ID = 'id';
exports.ID = ID;
var COMMENT = 'comment';
exports.COMMENT = COMMENT;
var COMBINATOR = 'combinator';
exports.COMBINATOR = COMBINATOR;
var CLASS = 'class';
exports.CLASS = CLASS;
var ATTRIBUTE = 'attribute';
exports.ATTRIBUTE = ATTRIBUTE;
var UNIVERSAL = 'universal';
exports.UNIVERSAL = UNIVERSAL;
@@ -0,0 +1,32 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Universal =
/*#__PURE__*/
function (_Namespace) {
_inheritsLoose(Universal, _Namespace);
function Universal(opts) {
var _this;
_this = _Namespace.call(this, opts) || this;
_this.type = _types.UNIVERSAL;
_this.value = '*';
return _this;
}
return Universal;
}(_namespace.default);
exports.default = Universal;
module.exports = exports.default;
@@ -0,0 +1,13 @@
"use strict";
exports.__esModule = true;
exports.default = sortAscending;
function sortAscending(list) {
return list.sort(function (a, b) {
return a - b;
});
}
;
module.exports = exports.default;
@@ -0,0 +1,95 @@
"use strict";
exports.__esModule = true;
exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0;
var ampersand = 38; // `&`.charCodeAt(0);
exports.ampersand = ampersand;
var asterisk = 42; // `*`.charCodeAt(0);
exports.asterisk = asterisk;
var at = 64; // `@`.charCodeAt(0);
exports.at = at;
var comma = 44; // `,`.charCodeAt(0);
exports.comma = comma;
var colon = 58; // `:`.charCodeAt(0);
exports.colon = colon;
var semicolon = 59; // `;`.charCodeAt(0);
exports.semicolon = semicolon;
var openParenthesis = 40; // `(`.charCodeAt(0);
exports.openParenthesis = openParenthesis;
var closeParenthesis = 41; // `)`.charCodeAt(0);
exports.closeParenthesis = closeParenthesis;
var openSquare = 91; // `[`.charCodeAt(0);
exports.openSquare = openSquare;
var closeSquare = 93; // `]`.charCodeAt(0);
exports.closeSquare = closeSquare;
var dollar = 36; // `$`.charCodeAt(0);
exports.dollar = dollar;
var tilde = 126; // `~`.charCodeAt(0);
exports.tilde = tilde;
var caret = 94; // `^`.charCodeAt(0);
exports.caret = caret;
var plus = 43; // `+`.charCodeAt(0);
exports.plus = plus;
var equals = 61; // `=`.charCodeAt(0);
exports.equals = equals;
var pipe = 124; // `|`.charCodeAt(0);
exports.pipe = pipe;
var greaterThan = 62; // `>`.charCodeAt(0);
exports.greaterThan = greaterThan;
var space = 32; // ` `.charCodeAt(0);
exports.space = space;
var singleQuote = 39; // `'`.charCodeAt(0);
exports.singleQuote = singleQuote;
var doubleQuote = 34; // `"`.charCodeAt(0);
exports.doubleQuote = doubleQuote;
var slash = 47; // `/`.charCodeAt(0);
exports.slash = slash;
var bang = 33; // `!`.charCodeAt(0);
exports.bang = bang;
var backslash = 92; // '\\'.charCodeAt(0);
exports.backslash = backslash;
var cr = 13; // '\r'.charCodeAt(0);
exports.cr = cr;
var feed = 12; // '\f'.charCodeAt(0);
exports.feed = feed;
var newline = 10; // '\n'.charCodeAt(0);
exports.newline = newline;
var tab = 9; // '\t'.charCodeAt(0);
// Expose aliases primarily for readability.
exports.tab = tab;
var str = singleQuote; // No good single character representation!
exports.str = str;
var comment = -1;
exports.comment = comment;
var word = -2;
exports.word = word;
var combinator = -3;
exports.combinator = combinator;

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