Начат фронтенд

This commit is contained in:
Georgiy Syralev
2025-09-16 14:47:30 +03:00
parent f37e85e2e0
commit 40de29041d
2100 changed files with 305701 additions and 11807 deletions

136
node_modules/postcss/lib/at-rule.d.ts generated vendored
View File

@@ -1,56 +1,48 @@
import Container, {
ContainerProps,
ContainerWithChildren
} from './container.js'
import Container, { ContainerProps } from './container.js'
declare namespace AtRule {
export interface AtRuleRaws extends Record<string, unknown> {
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
interface AtRuleRaws extends Record<string, unknown> {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The space between the at-rule name and its parameters.
*/
afterName?: string
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The space between the at-rule name and its parameters.
*/
afterName?: string
/**
* The symbols between the last parameter and `{` for rules.
*/
between?: string
/**
* The symbols between the last parameter and `{` for rules.
*/
between?: string
/**
* The rules selector with comments.
*/
params?: {
raw: string
value: string
}
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
/**
* The rules selector with comments.
*/
params?: {
value: string
raw: string
}
}
export interface AtRuleProps extends ContainerProps {
/** Name of the at-rule. */
name: string
/** Parameters following the name of the at-rule. */
params?: number | string
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: AtRuleRaws
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { AtRule_ as default }
export interface AtRuleProps extends ContainerProps {
/** Name of the at-rule. */
name: string
/** Parameters following the name of the at-rule. */
params?: string | number
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: AtRuleRaws
}
/**
@@ -64,7 +56,7 @@ declare namespace AtRule {
* }
* ```
*
* If its followed in the CSS by a `{}` block, this node will have
* If its followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* ```js
@@ -78,45 +70,25 @@ declare namespace AtRule {
* media.nodes //=> []
* ```
*/
declare class AtRule_ extends Container {
/**
* An array containing the layers children.
*
* ```js
* const root = postcss.parse('@layer example { a { color: black } }')
* const layer = root.first
* layer.nodes.length //=> 1
* layer.nodes[0].selector //=> 'a'
* ```
*
* Can be `undefinded` if the at-rule has no body.
*
* ```js
* const root = postcss.parse('@layer a, b, c;')
* const layer = root.first
* layer.nodes //=> undefined
* ```
*/
nodes: Container['nodes'] | undefined
parent: ContainerWithChildren | undefined
raws: AtRule.AtRuleRaws
export default class AtRule extends Container {
type: 'atrule'
parent: Container | undefined
raws: AtRuleRaws
/**
* The at-rules name immediately follows the `@`.
*
* ```js
* const root = postcss.parse('@media print {}')
* const media = root.first
* media.name //=> 'media'
* const media = root.first
* ```
*/
get name(): string
set name(value: string)
name: string
/**
* The at-rules parameters, the values that follow the at-rules name
* but precede any `{}` block.
* but precede any {} block.
*
* ```js
* const root = postcss.parse('@media print, screen {}')
@@ -124,17 +96,11 @@ declare class AtRule_ extends Container {
* media.params //=> 'print, screen'
* ```
*/
get params(): string
params: string
set params(value: string)
constructor(defaults?: AtRule.AtRuleProps)
assign(overrides: AtRule.AtRuleProps | object): this
clone(overrides?: Partial<AtRule.AtRuleProps>): this
cloneAfter(overrides?: Partial<AtRule.AtRuleProps>): this
cloneBefore(overrides?: Partial<AtRule.AtRuleProps>): this
constructor(defaults?: AtRuleProps)
assign(overrides: object | AtRuleProps): this
clone(overrides?: Partial<AtRuleProps>): this
cloneBefore(overrides?: Partial<AtRuleProps>): this
cloneAfter(overrides?: Partial<AtRuleProps>): this
}
declare class AtRule extends AtRule_ {}
export = AtRule

View File

@@ -1,68 +1,56 @@
import Container from './container.js'
import Node, { NodeProps } from './node.js'
declare namespace Comment {
export interface CommentRaws extends Record<string, unknown> {
/**
* The space symbols before the node.
*/
before?: string
interface CommentRaws extends Record<string, unknown> {
/**
* The space symbols before the node.
*/
before?: string
/**
* The space symbols between `/*` and the comments text.
*/
left?: string
/**
* The space symbols between `/*` and the comments text.
*/
left?: string
/**
* The space symbols between the comments text.
*/
right?: string
}
/**
* The space symbols between the comments text.
*/
right?: string
}
export interface CommentProps extends NodeProps {
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: CommentRaws
/** Content of the comment. */
text: string
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Comment_ as default }
export interface CommentProps extends NodeProps {
/** Content of the comment. */
text: string
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: CommentRaws
}
/**
* It represents a class that handles
* [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
* Represents a comment between declarations or statements (rule and at-rules).
*
* ```js
* Once (root, { Comment }) {
* const note = new Comment({ text: 'Note: …' })
* let note = new Comment({ text: 'Note: …' })
* root.append(note)
* }
* ```
*
* Remember that CSS comments inside selectors, at-rule parameters,
* or declaration values will be stored in the `raws` properties
* explained above.
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*/
declare class Comment_ extends Node {
parent: Container | undefined
raws: Comment.CommentRaws
export default class Comment extends Node {
type: 'comment'
parent: Container | undefined
raws: CommentRaws
/**
* The comment's text.
*/
get text(): string
text: string
set text(value: string)
constructor(defaults?: Comment.CommentProps)
assign(overrides: Comment.CommentProps | object): this
clone(overrides?: Partial<Comment.CommentProps>): this
cloneAfter(overrides?: Partial<Comment.CommentProps>): this
cloneBefore(overrides?: Partial<Comment.CommentProps>): this
constructor(defaults?: CommentProps)
assign(overrides: object | CommentProps): this
clone(overrides?: Partial<CommentProps>): this
cloneBefore(overrides?: Partial<CommentProps>): this
cloneAfter(overrides?: Partial<CommentProps>): this
}
declare class Comment extends Comment_ {}
export = Comment

View File

@@ -1,50 +1,23 @@
import AtRule from './at-rule.js'
import Comment from './comment.js'
import Node, { ChildNode, NodeProps, ChildProps } from './node.js'
import Declaration from './declaration.js'
import Node, { ChildNode, ChildProps, NodeProps } from './node.js'
import { Root } from './postcss.js'
import Comment from './comment.js'
import AtRule from './at-rule.js'
import Rule from './rule.js'
declare namespace Container {
export type ContainerWithChildren<Child extends Node = ChildNode> = {
nodes: Child[]
} & (
| AtRule
| Root
| Rule
)
export interface ValueOptions {
/**
* String thats used to narrow down values and speed up the regexp search.
*/
fast?: string
/**
* An array of property names.
*/
props?: readonly string[]
}
export interface ContainerProps extends NodeProps {
nodes?: readonly (ChildProps | Node)[]
}
interface ValueOptions {
/**
* An array of property names.
*/
props?: string[]
/**
* All types that can be passed into container methods to create or add a new
* child node.
* String thats used to narrow down values and speed up the regexp search.
*/
export type NewChild =
| ChildProps
| Node
| readonly ChildProps[]
| readonly Node[]
| readonly string[]
| string
| undefined
fast?: string
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Container_ as default }
export interface ContainerProps extends NodeProps {
nodes?: (ChildNode | ChildProps)[]
}
/**
@@ -54,7 +27,9 @@ declare namespace Container {
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*/
declare abstract class Container_<Child extends Node = ChildNode> extends Node {
export default abstract class Container<
Child extends Node = ChildNode
> extends Node {
/**
* An array containing the containers children.
*
@@ -65,7 +40,7 @@ declare abstract class Container_<Child extends Node = ChildNode> extends Node {
* root.nodes[0].nodes[0].prop //=> 'color'
* ```
*/
nodes: Child[] | undefined
nodes: Child[]
/**
* The containers first child.
@@ -84,33 +59,7 @@ declare abstract class Container_<Child extends Node = ChildNode> extends Node {
* ```
*/
get last(): Child | undefined
/**
* Inserts new nodes to the end of the container.
*
* ```js
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
* rule.append(decl1, decl2)
*
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
* root.append({ selector: 'a' }) // rule
* rule.append({ prop: 'color', value: 'black' }) // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}')
* root.first.append('color: black; z-index: 1')
* ```
*
* @param nodes New nodes.
* @return This node for methods chain.
*/
append(...nodes: Container.NewChild[]): this
assign(overrides: Container.ContainerProps | object): this
clone(overrides?: Partial<Container.ContainerProps>): this
cloneAfter(overrides?: Partial<Container.ContainerProps>): this
cloneBefore(overrides?: Partial<Container.ContainerProps>): this
/**
* Iterates through the containers immediate children,
* calling `callback` for each child.
@@ -148,181 +97,6 @@ declare abstract class Container_<Child extends Node = ChildNode> extends Node {
callback: (node: Child, index: number) => false | void
): false | undefined
/**
* Returns `true` if callback returns `true`
* for all of the containers children.
*
* ```js
* const noPrefixes = rule.every(i => i.prop[0] !== '-')
* ```
*
* @param condition Iterator returns true or false.
* @return Is every child pass condition.
*/
every(
condition: (node: Child, index: number, nodes: Child[]) => boolean
): boolean
/**
* Returns a `child`s index within the `Container#nodes` array.
*
* ```js
* rule.index( rule.nodes[2] ) //=> 2
* ```
*
* @param child Child of the current container.
* @return Child index.
*/
index(child: Child | number): number
/**
* Insert new node after old node within the container.
*
* @param oldNode Child or childs index.
* @param newNode New node.
* @return This node for methods chain.
*/
insertAfter(oldNode: Child | number, newNode: Container.NewChild): this
/**
* Traverses the containers descendant nodes, calling callback
* for each comment node.
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* root.walkComments(comment => {
* comment.remove()
* })
* ```
*
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
/**
* Insert new node before old node within the container.
*
* ```js
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
* ```
*
* @param oldNode Child or childs index.
* @param newNode New node.
* @return This node for methods chain.
*/
insertBefore(oldNode: Child | number, newNode: Container.NewChild): this
/**
* Inserts new nodes to the start of the container.
*
* ```js
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
* rule.prepend(decl1, decl2)
*
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
* root.append({ selector: 'a' }) // rule
* rule.append({ prop: 'color', value: 'black' }) // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}')
* root.first.append('color: black; z-index: 1')
* ```
*
* @param nodes New nodes.
* @return This node for methods chain.
*/
prepend(...nodes: Container.NewChild[]): this
/**
* Add child to the end of the node.
*
* ```js
* rule.push(new Declaration({ prop: 'color', value: 'black' }))
* ```
*
* @param child New node.
* @return This node for methods chain.
*/
push(child: Child): this
/**
* Removes all children from the container
* and cleans their parent properties.
*
* ```js
* rule.removeAll()
* rule.nodes.length //=> 0
* ```
*
* @return This node for methods chain.
*/
removeAll(): this
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* ```js
* rule.nodes.length //=> 5
* rule.removeChild(decl)
* rule.nodes.length //=> 4
* decl.parent //=> undefined
* ```
*
* @param child Child or childs index.
* @return This node for methods chain.
*/
removeChild(child: Child | number): this
replaceValues(
pattern: RegExp | string,
replaced: { (substring: string, ...args: any[]): string } | string
): this
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* ```js
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px'
* })
* ```
*
* @param pattern Replace pattern.
* @param {object} options Options to speed up the search.
* @param replaced String to replace pattern or callback
* that returns a new value. The callback
* will receive the same arguments
* as those passed to a function parameter
* of `String#replace`.
* @return This node for methods chain.
*/
replaceValues(
pattern: RegExp | string,
options: Container.ValueOptions,
replaced: { (substring: string, ...args: any[]): string } | string
): this
/**
* Returns `true` if callback returns `true` for (at least) one
* of the containers children.
*
* ```js
* const hasPrefix = rule.some(i => i.prop[0] === '-')
* ```
*
* @param condition Iterator returns true or false.
* @return Is some child pass condition.
*/
some(
condition: (node: Child, index: number, nodes: Child[]) => boolean
): boolean
/**
* Traverses the containers descendant nodes, calling callback
* for each node.
@@ -346,50 +120,6 @@ declare abstract class Container_<Child extends Node = ChildNode> extends Node {
callback: (node: ChildNode, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* root.walkAtRules(rule => {
* if (isOld(rule.name)) rule.remove()
* })
*
* let first = false
* root.walkAtRules('charset', rule => {
* if (!first) {
* first = true
* } else {
* rule.remove()
* }
* })
* ```
*
* @param name String or regular expression to filter at-rules by name.
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walkAtRules(
nameFilter: RegExp | string,
callback: (atRule: AtRule, index: number) => false | void
): false | undefined
walkAtRules(
callback: (atRule: AtRule, index: number) => false | void
): false | undefined
walkComments(
callback: (comment: Comment, indexed: number) => false | void
): false | undefined
walkComments(
callback: (comment: Comment, indexed: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each declaration node.
@@ -420,12 +150,13 @@ declare abstract class Container_<Child extends Node = ChildNode> extends Node {
* @return Returns `false` if iteration was broke.
*/
walkDecls(
propFilter: RegExp | string,
propFilter: string | RegExp,
callback: (decl: Declaration, index: number) => false | void
): false | undefined
walkDecls(
callback: (decl: Declaration, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each rule node.
@@ -449,35 +180,263 @@ declare abstract class Container_<Child extends Node = ChildNode> extends Node {
* @return Returns `false` if iteration was broke.
*/
walkRules(
selectorFilter: RegExp | string,
selectorFilter: string | RegExp,
callback: (rule: Rule, index: number) => false | void
): false | undefined
walkRules(
callback: (rule: Rule, index: number) => false | void
): false | undefined
/**
* An internal method that converts a {@link NewChild} into a list of actual
* child nodes that can then be added to this container.
* Traverses the containers descendant nodes, calling callback
* for each at-rule node.
*
* This ensures that the nodes' parent is set to this container, that they use
* the correct prototype chain, and that they're marked as dirty.
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* @param mnodes The new node or nodes to add.
* @param sample A node from whose raws the new node's `before` raw should be
* taken.
* @param type This should be set to `'prepend'` if the new nodes will be
* inserted at the beginning of the container.
* @hidden
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* root.walkAtRules(rule => {
* if (isOld(rule.name)) rule.remove()
* })
*
* let first = false
* root.walkAtRules('charset', rule => {
* if (!first) {
* first = true
* } else {
* rule.remove()
* }
* })
* ```
*
* @param name String or regular expression to filter at-rules by name.
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
protected normalize(
nodes: Container.NewChild,
sample: Node | undefined,
type?: 'prepend' | false
): Child[]
walkAtRules(
nameFilter: string | RegExp,
callback: (atRule: AtRule, index: number) => false | void
): false | undefined
walkAtRules(
callback: (atRule: AtRule, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each comment node.
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* root.walkComments(comment => {
* comment.remove()
* })
* ```
*
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walkComments(
callback: (comment: Comment, indexed: number) => false | void
): false | undefined
walkComments(
callback: (comment: Comment, indexed: number) => false | void
): false | undefined
/**
* Inserts new nodes to the end of the container.
*
* ```js
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
* rule.append(decl1, decl2)
*
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
* root.append({ selector: 'a' }) // rule
* rule.append({ prop: 'color', value: 'black' }) // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}')
* root.first.append('color: black; z-index: 1')
* ```
*
* @param nodes New nodes.
* @return This node for methods chain.
*/
append(
...nodes: (Node | Node[] | ChildProps | ChildProps[] | string | string[])[]
): this
/**
* Inserts new nodes to the start of the container.
*
* ```js
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
* rule.prepend(decl1, decl2)
*
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
* root.append({ selector: 'a' }) // rule
* rule.append({ prop: 'color', value: 'black' }) // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}')
* root.first.append('color: black; z-index: 1')
* ```
*
* @param nodes New nodes.
* @return This node for methods chain.
*/
prepend(
...nodes: (Node | Node[] | ChildProps | ChildProps[] | string | string[])[]
): this
/**
* Add child to the end of the node.
*
* ```js
* rule.push(new Declaration({ prop: 'color', value: 'black' }))
* ```
*
* @param child New node.
* @return This node for methods chain.
*/
push(child: Child): this
/**
* Insert new node before old node within the container.
*
* ```js
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
* ```
*
* @param oldNode Child or childs index.
* @param newNode New node.
* @return This node for methods chain.
*/
insertBefore(
oldNode: Child | number,
newNode: Child | ChildProps | string | Child[] | ChildProps[] | string[]
): this
/**
* Insert new node after old node within the container.
*
* @param oldNode Child or childs index.
* @param newNode New node.
* @return This node for methods chain.
*/
insertAfter(
oldNode: Child | number,
newNode: Child | ChildProps | string | Child[] | ChildProps[] | string[]
): this
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* ```js
* rule.nodes.length //=> 5
* rule.removeChild(decl)
* rule.nodes.length //=> 4
* decl.parent //=> undefined
* ```
*
* @param child Child or childs index.
* @return This node for methods chain.
*/
removeChild(child: Child | number): this
/**
* Removes all children from the container
* and cleans their parent properties.
*
* ```js
* rule.removeAll()
* rule.nodes.length //=> 0
* ```
*
* @return This node for methods chain.
*/
removeAll(): this
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* ```js
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px'
* })
* ```
*
* @param pattern Replace pattern.
* @param {object} opts Options to speed up the search.
* @param callback String to replace pattern or callback
* that returns a new value. The callback
* will receive the same arguments
* as those passed to a function parameter
* of `String#replace`.
* @return This node for methods chain.
*/
replaceValues(
pattern: string | RegExp,
options: ValueOptions,
replaced: string | { (substring: string, ...args: any[]): string }
): this
replaceValues(
pattern: string | RegExp,
replaced: string | { (substring: string, ...args: any[]): string }
): this
/**
* Returns `true` if callback returns `true`
* for all of the containers children.
*
* ```js
* const noPrefixes = rule.every(i => i.prop[0] !== '-')
* ```
*
* @param condition Iterator returns true or false.
* @return Is every child pass condition.
*/
every(
condition: (node: Child, index: number, nodes: Child[]) => boolean
): boolean
/**
* Returns `true` if callback returns `true` for (at least) one
* of the containers children.
*
* ```js
* const hasPrefix = rule.some(i => i.prop[0] === '-')
* ```
*
* @param condition Iterator returns true or false.
* @return Is some child pass condition.
*/
some(
condition: (node: Child, index: number, nodes: Child[]) => boolean
): boolean
/**
* Returns a `child`s index within the `Container#nodes` array.
*
* ```js
* rule.index( rule.nodes[2] ) //=> 2
* ```
*
* @param child Child of the current container.
* @return Child index.
*/
index(child: Child | number): number
}
declare class Container<
Child extends Node = ChildNode
> extends Container_<Child> {}
export = Container

592
node_modules/postcss/lib/container.js generated vendored
View File

@@ -1,11 +1,11 @@
'use strict'
let Comment = require('./comment')
let Declaration = require('./declaration')
let Node = require('./node')
let { isClean, my } = require('./symbols')
let Declaration = require('./declaration')
let Comment = require('./comment')
let Node = require('./node')
let AtRule, parse, Root, Rule
let parse, Rule, AtRule, Root
function cleanSource(nodes) {
return nodes.map(i => {
@@ -15,44 +15,22 @@ function cleanSource(nodes) {
})
}
function markTreeDirty(node) {
function markDirtyUp(node) {
node[isClean] = false
if (node.proxyOf.nodes) {
for (let i of node.proxyOf.nodes) {
markTreeDirty(i)
markDirtyUp(i)
}
}
}
class Container extends Node {
get first() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[0]
}
get last() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
}
append(...children) {
for (let child of children) {
let nodes = this.normalize(child, this.last)
for (let node of nodes) this.proxyOf.nodes.push(node)
}
this.markDirty()
push(child) {
child.parent = this
this.proxyOf.nodes.push(child)
return this
}
cleanRaws(keepBetween) {
super.cleanRaws(keepBetween)
if (this.nodes) {
for (let node of this.nodes) node.cleanRaws(keepBetween)
}
}
each(callback) {
if (!this.proxyOf.nodes) return undefined
let iterator = this.getIterator()
@@ -70,244 +48,6 @@ class Container extends Node {
return result
}
every(condition) {
return this.nodes.every(condition)
}
getIterator() {
if (!this.lastEach) this.lastEach = 0
if (!this.indexes) this.indexes = {}
this.lastEach += 1
let iterator = this.lastEach
this.indexes[iterator] = 0
return iterator
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (!node[prop]) {
return node[prop]
} else if (
prop === 'each' ||
(typeof prop === 'string' && prop.startsWith('walk'))
) {
return (...args) => {
return node[prop](
...args.map(i => {
if (typeof i === 'function') {
return (child, index) => i(child.toProxy(), index)
} else {
return i
}
})
)
}
} else if (prop === 'every' || prop === 'some') {
return cb => {
return node[prop]((child, ...other) =>
cb(child.toProxy(), ...other)
)
}
} else if (prop === 'root') {
return () => node.root().toProxy()
} else if (prop === 'nodes') {
return node.nodes.map(i => i.toProxy())
} else if (prop === 'first' || prop === 'last') {
return node[prop].toProxy()
} else {
return node[prop]
}
},
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (prop === 'name' || prop === 'params' || prop === 'selector') {
node.markDirty()
}
return true
}
}
}
index(child) {
if (typeof child === 'number') return child
if (child.proxyOf) child = child.proxyOf
return this.proxyOf.nodes.indexOf(child)
}
insertAfter(exist, add) {
let existIndex = this.index(exist)
let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse()
existIndex = this.index(exist)
for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (existIndex < index) {
this.indexes[id] = index + nodes.length
}
}
this.markDirty()
return this
}
insertBefore(exist, add) {
let existIndex = this.index(exist)
let type = existIndex === 0 ? 'prepend' : false
let nodes = this.normalize(
add,
this.proxyOf.nodes[existIndex],
type
).reverse()
existIndex = this.index(exist)
for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (existIndex <= index) {
this.indexes[id] = index + nodes.length
}
}
this.markDirty()
return this
}
normalize(nodes, sample) {
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes)
} else if (typeof nodes === 'undefined') {
nodes = []
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0)
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore')
}
} else if (nodes.type === 'root' && this.type !== 'document') {
nodes = nodes.nodes.slice(0)
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore')
}
} else if (nodes.type) {
nodes = [nodes]
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation')
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value)
}
nodes = [new Declaration(nodes)]
} else if (nodes.selector || nodes.selectors) {
nodes = [new Rule(nodes)]
} else if (nodes.name) {
nodes = [new AtRule(nodes)]
} else if (nodes.text) {
nodes = [new Comment(nodes)]
} else {
throw new Error('Unknown node type in node creation')
}
let processed = nodes.map(i => {
/* c8 ignore next */
if (!i[my]) Container.rebuild(i)
i = i.proxyOf
if (i.parent) i.parent.removeChild(i)
if (i[isClean]) markTreeDirty(i)
if (!i.raws) i.raws = {}
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/\S/g, '')
}
}
i.parent = this.proxyOf
return i
})
return processed
}
prepend(...children) {
children = children.reverse()
for (let child of children) {
let nodes = this.normalize(child, this.first, 'prepend').reverse()
for (let node of nodes) this.proxyOf.nodes.unshift(node)
for (let id in this.indexes) {
this.indexes[id] = this.indexes[id] + nodes.length
}
}
this.markDirty()
return this
}
push(child) {
child.parent = this
this.proxyOf.nodes.push(child)
return this
}
removeAll() {
for (let node of this.proxyOf.nodes) node.parent = undefined
this.proxyOf.nodes = []
this.markDirty()
return this
}
removeChild(child) {
child = this.index(child)
this.proxyOf.nodes[child].parent = undefined
this.proxyOf.nodes.splice(child, 1)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (index >= child) {
this.indexes[id] = index - 1
}
}
this.markDirty()
return this
}
replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts
opts = {}
}
this.walkDecls(decl => {
if (opts.props && !opts.props.includes(decl.prop)) return
if (opts.fast && !decl.value.includes(opts.fast)) return
decl.value = decl.value.replace(pattern, callback)
})
this.markDirty()
return this
}
some(condition) {
return this.nodes.some(condition)
}
walk(callback) {
return this.each((child, i) => {
let result
@@ -324,37 +64,6 @@ class Container extends Node {
})
}
walkAtRules(name, callback) {
if (!callback) {
callback = name
return this.walk((child, i) => {
if (child.type === 'atrule') {
return callback(child, i)
}
})
}
if (name instanceof RegExp) {
return this.walk((child, i) => {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i)
}
})
}
return this.walk((child, i) => {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i)
}
})
}
walkComments(callback) {
return this.walk((child, i) => {
if (child.type === 'comment') {
return callback(child, i)
}
})
}
walkDecls(prop, callback) {
if (!callback) {
callback = prop
@@ -401,6 +110,289 @@ class Container extends Node {
}
})
}
walkAtRules(name, callback) {
if (!callback) {
callback = name
return this.walk((child, i) => {
if (child.type === 'atrule') {
return callback(child, i)
}
})
}
if (name instanceof RegExp) {
return this.walk((child, i) => {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i)
}
})
}
return this.walk((child, i) => {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i)
}
})
}
walkComments(callback) {
return this.walk((child, i) => {
if (child.type === 'comment') {
return callback(child, i)
}
})
}
append(...children) {
for (let child of children) {
let nodes = this.normalize(child, this.last)
for (let node of nodes) this.proxyOf.nodes.push(node)
}
this.markDirty()
return this
}
prepend(...children) {
children = children.reverse()
for (let child of children) {
let nodes = this.normalize(child, this.first, 'prepend').reverse()
for (let node of nodes) this.proxyOf.nodes.unshift(node)
for (let id in this.indexes) {
this.indexes[id] = this.indexes[id] + nodes.length
}
}
this.markDirty()
return this
}
cleanRaws(keepBetween) {
super.cleanRaws(keepBetween)
if (this.nodes) {
for (let node of this.nodes) node.cleanRaws(keepBetween)
}
}
insertBefore(exist, add) {
let existIndex = this.index(exist)
let type = existIndex === 0 ? 'prepend' : false
let nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse()
existIndex = this.index(exist)
for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (existIndex <= index) {
this.indexes[id] = index + nodes.length
}
}
this.markDirty()
return this
}
insertAfter(exist, add) {
let existIndex = this.index(exist)
let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse()
existIndex = this.index(exist)
for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (existIndex < index) {
this.indexes[id] = index + nodes.length
}
}
this.markDirty()
return this
}
removeChild(child) {
child = this.index(child)
this.proxyOf.nodes[child].parent = undefined
this.proxyOf.nodes.splice(child, 1)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (index >= child) {
this.indexes[id] = index - 1
}
}
this.markDirty()
return this
}
removeAll() {
for (let node of this.proxyOf.nodes) node.parent = undefined
this.proxyOf.nodes = []
this.markDirty()
return this
}
replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts
opts = {}
}
this.walkDecls(decl => {
if (opts.props && !opts.props.includes(decl.prop)) return
if (opts.fast && !decl.value.includes(opts.fast)) return
decl.value = decl.value.replace(pattern, callback)
})
this.markDirty()
return this
}
every(condition) {
return this.nodes.every(condition)
}
some(condition) {
return this.nodes.some(condition)
}
index(child) {
if (typeof child === 'number') return child
if (child.proxyOf) child = child.proxyOf
return this.proxyOf.nodes.indexOf(child)
}
get first() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[0]
}
get last() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
}
normalize(nodes, sample) {
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes)
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0)
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore')
}
} else if (nodes.type === 'root' && this.type !== 'document') {
nodes = nodes.nodes.slice(0)
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore')
}
} else if (nodes.type) {
nodes = [nodes]
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation')
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value)
}
nodes = [new Declaration(nodes)]
} else if (nodes.selector) {
nodes = [new Rule(nodes)]
} else if (nodes.name) {
nodes = [new AtRule(nodes)]
} else if (nodes.text) {
nodes = [new Comment(nodes)]
} else {
throw new Error('Unknown node type in node creation')
}
let processed = nodes.map(i => {
/* c8 ignore next */
if (!i[my]) Container.rebuild(i)
i = i.proxyOf
if (i.parent) i.parent.removeChild(i)
if (i[isClean]) markDirtyUp(i)
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/\S/g, '')
}
}
i.parent = this.proxyOf
return i
})
return processed
}
getProxyProcessor() {
return {
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (prop === 'name' || prop === 'params' || prop === 'selector') {
node.markDirty()
}
return true
},
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (!node[prop]) {
return node[prop]
} else if (
prop === 'each' ||
(typeof prop === 'string' && prop.startsWith('walk'))
) {
return (...args) => {
return node[prop](
...args.map(i => {
if (typeof i === 'function') {
return (child, index) => i(child.toProxy(), index)
} else {
return i
}
})
)
}
} else if (prop === 'every' || prop === 'some') {
return cb => {
return node[prop]((child, ...other) =>
cb(child.toProxy(), ...other)
)
}
} else if (prop === 'root') {
return () => node.root().toProxy()
} else if (prop === 'nodes') {
return node.nodes.map(i => i.toProxy())
} else if (prop === 'first' || prop === 'last') {
return node[prop].toProxy()
} else {
return node[prop]
}
}
}
}
getIterator() {
if (!this.lastEach) this.lastEach = 0
if (!this.indexes) this.indexes = {}
this.lastEach += 1
let iterator = this.lastEach
this.indexes[iterator] = 0
return iterator
}
}
Container.registerParse = dependant => {

View File

@@ -1,23 +1,18 @@
import { FilePosition } from './input.js'
declare namespace CssSyntaxError {
/**
* A position that is part of a range.
*/
export interface RangePosition {
/**
* A position that is part of a range.
* The line number in the input.
*/
export interface RangePosition {
/**
* The column number in the input.
*/
column: number
line: number
/**
* The line number in the input.
*/
line: number
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { CssSyntaxError_ as default }
/**
* The column number in the input.
*/
column: number
}
/**
@@ -49,97 +44,29 @@ declare namespace CssSyntaxError {
* }
* ```
*/
declare class CssSyntaxError_ extends Error {
export default class CssSyntaxError {
/**
* Source column of the error.
*
* ```js
* error.column //=> 1
* error.input.column //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.column`.
* Instantiates a CSS syntax error. Can be instantiated for a single position
* or for a range.
* @param message Error message.
* @param lineOrStartPos If for a single position, the line number, or if for
* a range, the inclusive start position of the error.
* @param columnOrEndPos If for a single position, the column number, or if for
* a range, the exclusive end position of the error.
* @param source Source code of the broken file.
* @param file Absolute path to the broken file.
* @param plugin PostCSS plugin name, if error came from plugin.
*/
column?: number
constructor(
message: string,
lineOrStartPos?: number | RangePosition,
columnOrEndPos?: number | RangePosition,
source?: string,
file?: string,
plugin?: string
)
/**
* Source column of the error's end, exclusive. Provided if the error pertains
* to a range.
*
* ```js
* error.endColumn //=> 1
* error.input.endColumn //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.endColumn`.
*/
endColumn?: number
/**
* Source line of the error's end, exclusive. Provided if the error pertains
* to a range.
*
* ```js
* error.endLine //=> 3
* error.input.endLine //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.endLine`.
*/
endLine?: number
/**
* Absolute path to the broken file.
*
* ```js
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.file`.
*/
file?: string
/**
* Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* ```js
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
* ```
*/
input?: FilePosition
/**
* Source line of the error.
*
* ```js
* error.line //=> 2
* error.input.line //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.line`.
*/
line?: number
/**
* Full error text in the GNU error format
* with plugin, file, line and column.
*
* ```js
* error.message //=> 'a.css:1:1: Unclosed block'
* ```
*/
message: string
stack: string
/**
* Always equal to `'CssSyntaxError'`. You should always check error type
@@ -155,15 +82,6 @@ declare class CssSyntaxError_ extends Error {
*/
name: 'CssSyntaxError'
/**
* Plugin name, if error came from plugin.
*
* ```js
* error.plugin //=> 'postcss-vars'
* ```
*/
plugin?: string
/**
* Error message.
*
@@ -173,6 +91,83 @@ declare class CssSyntaxError_ extends Error {
*/
reason: string
/**
* Full error text in the GNU error format
* with plugin, file, line and column.
*
* ```js
* error.message //=> 'a.css:1:1: Unclosed block'
* ```
*/
message: string
/**
* Absolute path to the broken file.
*
* ```js
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.file`.
*/
file?: string
/**
* Source line of the error.
*
* ```js
* error.line //=> 2
* error.input.line //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.line`.
*/
line?: number
/**
* Source column of the error.
*
* ```js
* error.column //=> 1
* error.input.column //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.column`.
*/
column?: number
/**
* Source line of the error's end, exclusive. Provided if the error pertains
* to a range.
*
* ```js
* error.endLine //=> 3
* error.input.endLine //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.endLine`.
*/
endLine?: number
/**
* Source column of the error's end, exclusive. Provided if the error pertains
* to a range.
*
* ```js
* error.endColumn //=> 1
* error.input.endColumn //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.endColumn`.
*/
endColumn?: number
/**
* Source code of the broken file.
*
@@ -183,28 +178,41 @@ declare class CssSyntaxError_ extends Error {
*/
source?: string
stack: string
/**
* Plugin name, if error came from plugin.
*
* ```js
* error.plugin //=> 'postcss-vars'
* ```
*/
plugin?: string
/**
* Instantiates a CSS syntax error. Can be instantiated for a single position
* or for a range.
* @param message Error message.
* @param lineOrStartPos If for a single position, the line number, or if for
* a range, the inclusive start position of the error.
* @param columnOrEndPos If for a single position, the column number, or if for
* a range, the exclusive end position of the error.
* @param source Source code of the broken file.
* @param file Absolute path to the broken file.
* @param plugin PostCSS plugin name, if error came from plugin.
* Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* ```js
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
* ```
*/
constructor(
message: string,
lineOrStartPos?: CssSyntaxError.RangePosition | number,
columnOrEndPos?: CssSyntaxError.RangePosition | number,
source?: string,
file?: string,
plugin?: string
)
input?: FilePosition
/**
* Returns error position, message and source code of the broken part.
*
* ```js
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
* ```
*
* @return Error position, message and source code.
*/
toString(): string
/**
* Returns a few lines of CSS source that caused the error.
@@ -228,21 +236,4 @@ declare class CssSyntaxError_ extends Error {
* @return Few lines of CSS source that caused the error.
*/
showSourceCode(color?: boolean): string
/**
* Returns error position, message and source code of the broken part.
*
* ```js
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
* ```
*
* @return Error position, message and source code.
*/
toString(): string
}
declare class CssSyntaxError extends CssSyntaxError_ {}
export = CssSyntaxError

View File

@@ -52,70 +52,37 @@ class CssSyntaxError extends Error {
let css = this.source
if (color == null) color = pico.isColorSupported
let aside = text => text
let mark = text => text
let highlight = text => text
if (color) {
let { bold, gray, red } = pico.createColors(true)
mark = text => bold(red(text))
aside = text => gray(text)
if (terminalHighlight) {
highlight = text => terminalHighlight(text)
}
if (terminalHighlight) {
if (color) css = terminalHighlight(css)
}
let lines = css.split(/\r?\n/)
let start = Math.max(this.line - 3, 0)
let end = Math.min(this.line + 2, lines.length)
let maxWidth = String(end).length
let mark, aside
if (color) {
let { bold, red, gray } = pico.createColors(true)
mark = text => bold(red(text))
aside = text => gray(text)
} else {
mark = aside = str => str
}
return lines
.slice(start, end)
.map((line, index) => {
let number = start + 1 + index
let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
if (number === this.line) {
if (line.length > 160) {
let padding = 20
let subLineStart = Math.max(0, this.column - padding)
let subLineEnd = Math.max(
this.column + padding,
this.endColumn + padding
)
let subLine = line.slice(subLineStart, subLineEnd)
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line
.slice(0, Math.min(this.column - 1, padding - 1))
.replace(/[^\t]/g, ' ')
return (
mark('>') +
aside(gutter) +
highlight(subLine) +
'\n ' +
spacing +
mark('^')
)
}
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
return (
mark('>') +
aside(gutter) +
highlight(line) +
'\n ' +
spacing +
mark('^')
)
return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
}
return ' ' + aside(gutter) + highlight(line)
return ' ' + aside(gutter) + line
})
.join('\n')
}

View File

@@ -1,151 +1,124 @@
import { ContainerWithChildren } from './container.js'
import Container from './container.js'
import Node from './node.js'
declare namespace Declaration {
export interface DeclarationRaws extends Record<string, unknown> {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
interface DeclarationRaws extends Record<string, unknown> {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The symbols between the property and value for declarations.
*/
between?: string
/**
* The symbols between the property and value for declarations.
*/
between?: string
/**
* The content of the important statement, if it is not just `!important`.
*/
important?: string
/**
* The content of the important statement, if it is not just `!important`.
*/
important?: string
/**
* Declaration value with comments.
*/
value?: {
raw: string
value: string
}
}
export interface DeclarationProps {
/** Whether the declaration has an `!important` annotation. */
important?: boolean
/** Name of the declaration. */
prop: string
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: DeclarationRaws
/** Value of the declaration. */
/**
* Declaration value with comments.
*/
value?: {
value: string
raw: string
}
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Declaration_ as default }
export interface DeclarationProps {
/** Name of the declaration. */
prop: string
/** Value of the declaration. */
value: string
/** Whether the declaration has an `!important` annotation. */
important?: boolean
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: DeclarationRaws
}
/**
* It represents a class that handles
* [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations)
* Represents a CSS declaration.
*
* ```js
* Once (root, { Declaration }) {
* const color = new Declaration({ prop: 'color', value: 'black' })
* let color = new Declaration({ prop: 'color', value: 'black' })
* root.append(color)
* }
* ```
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first?.first
*
* const decl = root.first.first
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
* ```
*/
declare class Declaration_ extends Node {
parent: ContainerWithChildren | undefined
raws: Declaration.DeclarationRaws
export default class Declaration extends Node {
type: 'decl'
parent: Container | undefined
raws: DeclarationRaws
/**
* It represents a specificity of the declaration.
* The declaration's property name.
*
* If true, the CSS declaration will have an
* [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important)
* specifier.
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
* decl.prop //=> 'color'
* ```
*/
prop: string
/**
* The declarations value.
*
* This value will be cleaned of comments. If the source value contained
* comments, those comments will be available in the `raws` property.
* If you have not changed the value, the result of `decl.toString()`
* will include the original raws value (comments and all).
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
* decl.value //=> 'black'
* ```
*/
value: string
/**
* `true` if the declaration has an `!important` annotation.
*
* ```js
* const root = postcss.parse('a { color: black !important; color: red }')
*
* root.first.first.important //=> true
* root.first.last.important //=> undefined
* ```
*/
get important(): boolean
set important(value: boolean)
important: boolean
/**
* The property name for a CSS declaration.
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
*
* decl.prop //=> 'color'
* ```
*/
get prop(): string
set prop(value: string)
/**
* The property value for a CSS declaration.
*
* Any CSS comments inside the value string will be filtered out.
* CSS comments present in the source value will be available in
* the `raws` property.
*
* Assigning new `value` would ignore the comments in `raws`
* property while compiling node to string.
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
*
* decl.value //=> 'black'
* ```
*/
get value(): string
set value(value: string)
/**
* It represents a getter that returns `true` if a declaration starts with
* `--` or `$`, which are used to declare variables in CSS and SASS/SCSS.
* `true` if declaration is declaration of CSS Custom Property
* or Sass variable.
*
* ```js
* const root = postcss.parse(':root { --one: 1 }')
* const one = root.first.first
*
* let one = root.first.first
* one.variable //=> true
* ```
*
* ```js
* const root = postcss.parse('$one: 1')
* const one = root.first
*
* let one = root.first
* one.variable //=> true
* ```
*/
get variable(): boolean
constructor(defaults?: Declaration.DeclarationProps)
variable: boolean
assign(overrides: Declaration.DeclarationProps | object): this
clone(overrides?: Partial<Declaration.DeclarationProps>): this
cloneAfter(overrides?: Partial<Declaration.DeclarationProps>): this
cloneBefore(overrides?: Partial<Declaration.DeclarationProps>): this
constructor(defaults?: DeclarationProps)
assign(overrides: object | DeclarationProps): this
clone(overrides?: Partial<DeclarationProps>): this
cloneBefore(overrides?: Partial<DeclarationProps>): this
cloneAfter(overrides?: Partial<DeclarationProps>): this
}
declare class Declaration extends Declaration_ {}
export = Declaration

View File

@@ -3,10 +3,6 @@
let Node = require('./node')
class Declaration extends Node {
get variable() {
return this.prop.startsWith('--') || this.prop[0] === '$'
}
constructor(defaults) {
if (
defaults &&
@@ -18,6 +14,10 @@ class Declaration extends Node {
super(defaults)
this.type = 'decl'
}
get variable() {
return this.prop.startsWith('--') || this.prop[0] === '$'
}
}
module.exports = Declaration

View File

@@ -1,25 +1,23 @@
import Container, { ContainerProps } from './container.js'
import { ProcessOptions } from './postcss.js'
import Result from './result.js'
import Root from './root.js'
import Root, { RootProps } from './root.js'
declare namespace Document {
export interface DocumentProps extends ContainerProps {
nodes?: readonly Root[]
export interface DocumentProps extends ContainerProps {
nodes?: Root[]
/**
* Information to generate byte-to-byte equal node string as it was
* in the origin input.
*
* Every parser saves its own properties.
*/
raws?: Record<string, any>
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Document_ as default }
/**
* Information to generate byte-to-byte equal node string as it was
* in the origin input.
*
* Every parser saves its own properties.
*/
raws?: Record<string, any>
}
type ChildNode = Root
type ChildProps = RootProps
/**
* Represents a file and contains all its parsed nodes.
*
@@ -34,17 +32,11 @@ declare namespace Document {
* document.nodes.length //=> 2
* ```
*/
declare class Document_ extends Container<Root> {
nodes: Root[]
parent: undefined
export default class Document extends Container<Root> {
type: 'document'
parent: undefined
constructor(defaults?: Document.DocumentProps)
assign(overrides: Document.DocumentProps | object): this
clone(overrides?: Partial<Document.DocumentProps>): this
cloneAfter(overrides?: Partial<Document.DocumentProps>): this
cloneBefore(overrides?: Partial<Document.DocumentProps>): this
constructor(defaults?: DocumentProps)
/**
* Returns a `Result` instance representing the documents CSS roots.
@@ -63,7 +55,3 @@ declare class Document_ extends Container<Root> {
*/
toResult(options?: ProcessOptions): Result
}
declare class Document extends Document_ {}
export = Document

View File

@@ -1,9 +1,5 @@
import { JSONHydrator } from './postcss.js'
interface FromJSON extends JSONHydrator {
default: FromJSON
}
declare const fromJSON: JSONHydrator
declare const fromJSON: FromJSON
export = fromJSON
export default fromJSON

View File

@@ -1,10 +1,10 @@
'use strict'
let AtRule = require('./at-rule')
let Comment = require('./comment')
let Declaration = require('./declaration')
let Input = require('./input')
let PreviousMap = require('./previous-map')
let Comment = require('./comment')
let AtRule = require('./at-rule')
let Input = require('./input')
let Root = require('./root')
let Rule = require('./rule')

210
node_modules/postcss/lib/input.d.ts generated vendored
View File

@@ -1,56 +1,41 @@
import { CssSyntaxError, ProcessOptions } from './postcss.js'
import PreviousMap from './previous-map.js'
declare namespace Input {
export interface FilePosition {
/**
* Column of inclusive start position in source file.
*/
column: number
export interface FilePosition {
/**
* URL for the source file.
*/
url: string
/**
* Column of exclusive end position in source file.
*/
endColumn?: number
/**
* Absolute path to the source file.
*/
file?: string
/**
* Line of exclusive end position in source file.
*/
endLine?: number
/**
* Line of inclusive start position in source file.
*/
line: number
/**
* Offset of exclusive end position in source file.
*/
endOffset?: number
/**
* Column of inclusive start position in source file.
*/
column: number
/**
* Absolute path to the source file.
*/
file?: string
/**
* Line of exclusive end position in source file.
*/
endLine?: number
/**
* Line of inclusive start position in source file.
*/
line: number
/**
* Column of exclusive end position in source file.
*/
endColumn?: number
/**
* Offset of inclusive start position in source file.
*/
offset: number
/**
* Source code.
*/
source?: string
/**
* URL for the source file.
*/
url: string
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Input_ as default }
/**
* Source code.
*/
source?: string
}
/**
@@ -61,7 +46,7 @@ declare namespace Input {
* const input = root.source.input
* ```
*/
declare class Input_ {
export default class Input {
/**
* Input CSS source.
*
@@ -73,15 +58,14 @@ declare class Input_ {
css: string
/**
* Input source with support for non-CSS documents.
* The input source map passed from a compilation step before PostCSS
* (for example, from Sass compiler).
*
* ```js
* const input = postcss.parse('a{}', { from: file, document: '<style>a {}</style>' }).input
* input.document //=> "<style>a {}</style>"
* input.css //=> "a{}"
* root.source.input.map.consumer().sources //=> ['a.sass']
* ```
*/
document: string
map: PreviousMap
/**
* The absolute path to the CSS source file defined
@@ -94,11 +78,6 @@ declare class Input_ {
*/
file?: string
/**
* The flag to indicate whether or not the source code has Unicode BOM.
*/
hasBOM: boolean
/**
* The unique ID of the CSS source. It will be created if `from` option
* is not provided (because PostCSS does not know the file path).
@@ -112,14 +91,15 @@ declare class Input_ {
id?: string
/**
* The input source map passed from a compilation step before PostCSS
* (for example, from Sass compiler).
*
* ```js
* root.source.input.map.consumer().sources //=> ['a.sass']
* ```
* The flag to indicate whether or not the source code has Unicode BOM.
*/
map: PreviousMap
hasBOM: boolean
/**
* @param css Input CSS source.
* @param opts Process options.
*/
constructor(css: string, opts?: ProcessOptions)
/**
* The CSS source identifier. Contains `Input#file` if the user
@@ -135,63 +115,6 @@ declare class Input_ {
*/
get from(): string
/**
* @param css Input CSS source.
* @param opts Process options.
*/
constructor(css: string, opts?: ProcessOptions)
/**
* Returns `CssSyntaxError` with information about the error and its position.
*/
error(
message: string,
start:
| {
column: number
line: number
}
| {
offset: number
},
end:
| {
column: number
line: number
}
| {
offset: number
},
opts?: { plugin?: CssSyntaxError['plugin'] }
): CssSyntaxError
error(
message: string,
line: number,
column: number,
opts?: { plugin?: CssSyntaxError['plugin'] }
): CssSyntaxError
error(
message: string,
offset: number,
opts?: { plugin?: CssSyntaxError['plugin'] }
): CssSyntaxError
/**
* Converts source line and column to offset.
*
* @param line Source line.
* @param column Source column.
* @return Source offset.
*/
fromLineAndColumn(line: number, column: number): number
/**
* Converts source offset to line and column.
*
* @param offset Source offset.
*/
fromOffset(offset: number): { col: number; line: number } | null
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
@@ -216,12 +139,47 @@ declare class Input_ {
column: number,
endLine?: number,
endColumn?: number
): false | Input.FilePosition
): FilePosition | false
/** Converts this to a JSON-friendly object representation. */
toJSON(): object
/**
* Converts source offset to line and column.
*
* @param offset Source offset.
*/
fromOffset(offset: number): { line: number; col: number } | null
/**
* Returns `CssSyntaxError` with information about the error and its position.
*/
error(
message: string,
line: number,
column: number,
opts?: { plugin?: CssSyntaxError['plugin'] }
): CssSyntaxError
error(
message: string,
offset: number,
opts?: { plugin?: CssSyntaxError['plugin'] }
): CssSyntaxError
error(
message: string,
start:
| {
offset: number
}
| {
line: number
column: number
},
end:
| {
offset: number
}
| {
line: number
column: number
},
opts?: { plugin?: CssSyntaxError['plugin'] }
): CssSyntaxError
}
declare class Input extends Input_ {}
export = Input

217
node_modules/postcss/lib/input.js generated vendored
View File

@@ -1,39 +1,20 @@
'use strict'
let { nanoid } = require('nanoid/non-secure')
let { isAbsolute, resolve } = require('path')
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
let { fileURLToPath, pathToFileURL } = require('url')
let { resolve, isAbsolute } = require('path')
let { nanoid } = require('nanoid/non-secure')
let terminalHighlight = require('./terminal-highlight')
let CssSyntaxError = require('./css-syntax-error')
let PreviousMap = require('./previous-map')
let terminalHighlight = require('./terminal-highlight')
let lineToIndexCache = Symbol('lineToIndexCache')
let fromOffsetCache = Symbol('fromOffsetCache')
let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
let pathAvailable = Boolean(resolve && isAbsolute)
function getLineToIndex(input) {
if (input[lineToIndexCache]) return input[lineToIndexCache]
let lines = input.css.split('\n')
let lineToIndex = new Array(lines.length)
let prevIndex = 0
for (let i = 0, l = lines.length; i < l; i++) {
lineToIndex[i] = prevIndex
prevIndex += lines[i].length + 1
}
input[lineToIndexCache] = lineToIndex
return lineToIndex
}
class Input {
get from() {
return this.file || this.id
}
constructor(css, opts = {}) {
if (
css === null ||
@@ -52,9 +33,6 @@ class Input {
this.hasBOM = false
}
this.document = this.css
if (opts.document) this.document = opts.document.toString()
if (opts.from) {
if (
!pathAvailable ||
@@ -82,86 +60,23 @@ class Input {
if (this.map) this.map.file = this.from
}
error(message, line, column, opts = {}) {
let endColumn, endLine, endOffset, offset, result
if (line && typeof line === 'object') {
let start = line
let end = column
if (typeof start.offset === 'number') {
offset = start.offset
let pos = this.fromOffset(offset)
line = pos.line
column = pos.col
} else {
line = start.line
column = start.column
offset = this.fromLineAndColumn(line, column)
}
if (typeof end.offset === 'number') {
endOffset = end.offset
let pos = this.fromOffset(endOffset)
endLine = pos.line
endColumn = pos.col
} else {
endLine = end.line
endColumn = end.column
endOffset = this.fromLineAndColumn(end.line, end.column)
}
} else if (!column) {
offset = line
let pos = this.fromOffset(offset)
line = pos.line
column = pos.col
} else {
offset = this.fromLineAndColumn(line, column)
}
let origin = this.origin(line, column, endLine, endColumn)
if (origin) {
result = new CssSyntaxError(
message,
origin.endLine === undefined
? origin.line
: { column: origin.column, line: origin.line },
origin.endLine === undefined
? origin.column
: { column: origin.endColumn, line: origin.endLine },
origin.source,
origin.file,
opts.plugin
)
} else {
result = new CssSyntaxError(
message,
endLine === undefined ? line : { column, line },
endLine === undefined ? column : { column: endColumn, line: endLine },
this.css,
this.file,
opts.plugin
)
}
result.input = { column, endColumn, endLine, endOffset, line, offset, source: this.css }
if (this.file) {
if (pathToFileURL) {
result.input.url = pathToFileURL(this.file).toString()
}
result.input.file = this.file
}
return result
}
fromLineAndColumn(line, column) {
let lineToIndex = getLineToIndex(this)
let index = lineToIndex[line - 1]
return index + column - 1
}
fromOffset(offset) {
let lineToIndex = getLineToIndex(this)
let lastLine = lineToIndex[lineToIndex.length - 1]
let lastLine, lineToIndex
if (!this[fromOffsetCache]) {
let lines = this.css.split('\n')
lineToIndex = new Array(lines.length)
let prevIndex = 0
for (let i = 0, l = lines.length; i < l; i++) {
lineToIndex[i] = prevIndex
prevIndex += lines[i].length + 1
}
this[fromOffsetCache] = lineToIndex
} else {
lineToIndex = this[fromOffsetCache]
}
lastLine = lineToIndex[lineToIndex.length - 1]
let min = 0
if (offset >= lastLine) {
@@ -182,28 +97,85 @@ class Input {
}
}
return {
col: offset - lineToIndex[min] + 1,
line: min + 1
line: min + 1,
col: offset - lineToIndex[min] + 1
}
}
mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file
error(message, line, column, opts = {}) {
let result, endLine, endColumn
if (line && typeof line === 'object') {
let start = line
let end = column
if (typeof start.offset === 'number') {
let pos = this.fromOffset(start.offset)
line = pos.line
column = pos.col
} else {
line = start.line
column = start.column
}
if (typeof end.offset === 'number') {
let pos = this.fromOffset(end.offset)
endLine = pos.line
endColumn = pos.col
} else {
endLine = end.line
endColumn = end.column
}
} else if (!column) {
let pos = this.fromOffset(line)
line = pos.line
column = pos.col
}
return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
let origin = this.origin(line, column, endLine, endColumn)
if (origin) {
result = new CssSyntaxError(
message,
origin.endLine === undefined
? origin.line
: { line: origin.line, column: origin.column },
origin.endLine === undefined
? origin.column
: { line: origin.endLine, column: origin.endColumn },
origin.source,
origin.file,
opts.plugin
)
} else {
result = new CssSyntaxError(
message,
endLine === undefined ? line : { line, column },
endLine === undefined ? column : { line: endLine, column: endColumn },
this.css,
this.file,
opts.plugin
)
}
result.input = { line, column, endLine, endColumn, source: this.css }
if (this.file) {
if (pathToFileURL) {
result.input.url = pathToFileURL(this.file).toString()
}
result.input.file = this.file
}
return result
}
origin(line, column, endLine, endColumn) {
if (!this.map) return false
let consumer = this.map.consumer()
let from = consumer.originalPositionFor({ column, line })
let from = consumer.originalPositionFor({ line, column })
if (!from.source) return false
let to
if (typeof endLine === 'number') {
to = consumer.originalPositionFor({ column: endColumn, line: endLine })
to = consumer.originalPositionFor({ line: endLine, column: endColumn })
}
let fromUrl
@@ -218,11 +190,11 @@ class Input {
}
let result = {
column: from.column,
endColumn: to && to.column,
endLine: to && to.line,
url: fromUrl.toString(),
line: from.line,
url: fromUrl.toString()
column: from.column,
endLine: to && to.line,
endColumn: to && to.column
}
if (fromUrl.protocol === 'file:') {
@@ -240,6 +212,17 @@ class Input {
return result
}
mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file
}
return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
}
get from() {
return this.file || this.id
}
toJSON() {
let json = {}
for (let name of ['hasBOM', 'css', 'file', 'id']) {

View File

@@ -1,14 +1,8 @@
import Document from './document.js'
import Result, { Message, ResultOptions } from './result.js'
import { SourceMap } from './postcss.js'
import Processor from './processor.js'
import Result, { Message, ResultOptions } from './result.js'
import Root from './root.js'
import Warning from './warning.js'
declare namespace LazyResult {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { LazyResult_ as default }
}
import Root from './root.js'
/**
* A Promise proxy for the result of PostCSS transformations.
@@ -19,9 +13,22 @@ declare namespace LazyResult {
* const lazy = postcss([autoprefixer]).process(css)
* ```
*/
declare class LazyResult_<RootNode = Document | Root>
implements PromiseLike<Result<RootNode>>
{
export default class LazyResult implements PromiseLike<Result> {
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* ```js
* postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
* console.log(result.css)
* })
* ```
*/
then: Promise<Result>['then']
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
@@ -36,7 +43,7 @@ declare class LazyResult_<RootNode = Document | Root>
* })
* ```
*/
catch: Promise<Result<RootNode>>['catch']
catch: Promise<Result>['catch']
/**
* Processes input CSS through synchronous and asynchronous plugins
@@ -50,34 +57,31 @@ declare class LazyResult_<RootNode = Document | Root>
* })
* ```
*/
finally: Promise<Result<RootNode>>['finally']
finally: Promise<Result>['finally']
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* ```js
* postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
* console.log(result.css)
* })
* ```
* @param processor Processor used for this transformation.
* @param css CSS to parse and transform.
* @param opts Options from the `Processor#process` or `Root#toResult`.
*/
then: Promise<Result<RootNode>>['then']
constructor(processor: Processor, css: string, opts: ResultOptions)
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error.
*
* PostCSS runners should always use `LazyResult#then`.
* Returns the default string description of an object.
* Required to implement the Promise interface.
*/
get content(): string
get [Symbol.toStringTag](): string
/**
* Returns a `Processor` instance, which will be used
* for CSS transformations.
*/
get processor(): Processor
/**
* Options from the `Processor#process` call.
*/
get opts(): ResultOptions
/**
* Processes input CSS through synchronous plugins, converts `Root`
@@ -91,6 +95,18 @@ declare class LazyResult_<RootNode = Document | Root>
*/
get css(): string
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error.
*
* PostCSS runners should always use `LazyResult#then`.
*/
get content(): string
/**
* Processes input CSS through synchronous plugins
* and returns `Result#map`.
@@ -103,6 +119,17 @@ declare class LazyResult_<RootNode = Document | Root>
*/
get map(): SourceMap
/**
* Processes input CSS through synchronous plugins
* and returns `Result#root`.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* PostCSS runners should always use `LazyResult#then`.
*/
get root(): Root
/**
* Processes input CSS through synchronous plugins
* and returns `Result#messages`.
@@ -114,54 +141,13 @@ declare class LazyResult_<RootNode = Document | Root>
*/
get messages(): Message[]
/**
* Options from the `Processor#process` call.
*/
get opts(): ResultOptions
/**
* Returns a `Processor` instance, which will be used
* for CSS transformations.
*/
get processor(): Processor
/**
* Processes input CSS through synchronous plugins
* and returns `Result#root`.
* and calls `Result#warnings`.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* PostCSS runners should always use `LazyResult#then`.
* @return Warnings from plugins.
*/
get root(): RootNode
/**
* Returns the default string description of an object.
* Required to implement the Promise interface.
*/
get [Symbol.toStringTag](): string
/**
* @param processor Processor used for this transformation.
* @param css CSS to parse and transform.
* @param opts Options from the `Processor#process` or `Root#toResult`.
*/
constructor(processor: Processor, css: string, opts: ResultOptions)
/**
* Run plugin in async way and return `Result`.
*
* @return Result with output content.
*/
async(): Promise<Result<RootNode>>
/**
* Run plugin in sync way and return `Result`.
*
* @return Result with output content.
*/
sync(): Result<RootNode>
warnings(): Warning[]
/**
* Alias for the `LazyResult#css` property.
@@ -175,16 +161,16 @@ declare class LazyResult_<RootNode = Document | Root>
toString(): string
/**
* Processes input CSS through synchronous plugins
* and calls `Result#warnings`.
* Run plugin in sync way and return `Result`.
*
* @return Warnings from plugins.
* @return Result with output content.
*/
warnings(): Warning[]
sync(): Result
/**
* Run plugin in async way and return `Result`.
*
* @return Result with output content.
*/
async(): Promise<Result>
}
declare class LazyResult<
RootNode = Document | Root
> extends LazyResult_<RootNode> {}
export = LazyResult

View File

@@ -1,47 +1,47 @@
'use strict'
let { isClean, my } = require('./symbols')
let MapGenerator = require('./map-generator')
let stringify = require('./stringify')
let Container = require('./container')
let Document = require('./document')
let MapGenerator = require('./map-generator')
let parse = require('./parse')
let Result = require('./result')
let Root = require('./root')
let stringify = require('./stringify')
let { isClean, my } = require('./symbols')
let warnOnce = require('./warn-once')
let Result = require('./result')
let parse = require('./parse')
let Root = require('./root')
const TYPE_TO_CLASS_NAME = {
atrule: 'AtRule',
comment: 'Comment',
decl: 'Declaration',
document: 'Document',
root: 'Root',
rule: 'Rule'
atrule: 'AtRule',
rule: 'Rule',
decl: 'Declaration',
comment: 'Comment'
}
const PLUGIN_PROPS = {
AtRule: true,
AtRuleExit: true,
Comment: true,
CommentExit: true,
Declaration: true,
DeclarationExit: true,
Document: true,
DocumentExit: true,
Once: true,
OnceExit: true,
postcssPlugin: true,
prepare: true,
Once: true,
Document: true,
Root: true,
RootExit: true,
Declaration: true,
Rule: true,
RuleExit: true
AtRule: true,
Comment: true,
DeclarationExit: true,
RuleExit: true,
AtRuleExit: true,
CommentExit: true,
RootExit: true,
DocumentExit: true,
OnceExit: true
}
const NOT_VISITORS = {
Once: true,
postcssPlugin: true,
prepare: true
prepare: true,
Once: true
}
const CHILDREN = 0
@@ -87,12 +87,12 @@ function toStack(node) {
}
return {
eventIndex: 0,
events,
iterator: 0,
node,
events,
eventIndex: 0,
visitors: [],
visitorIndex: 0,
visitors: []
iterator: 0
}
}
@@ -105,38 +105,6 @@ function cleanMarks(node) {
let postcss = {}
class LazyResult {
get content() {
return this.stringify().content
}
get css() {
return this.stringify().css
}
get map() {
return this.stringify().map
}
get messages() {
return this.sync().messages
}
get opts() {
return this.result.opts
}
get processor() {
return this.result.processor
}
get root() {
return this.sync().root
}
get [Symbol.toStringTag]() {
return 'LazyResult'
}
constructor(processor, css, opts) {
this.stringified = false
this.processed = false
@@ -175,7 +143,7 @@ class LazyResult {
}
this.result = new Result(processor, root, opts)
this.helpers = { ...postcss, postcss, result: this.result }
this.helpers = { ...postcss, result: this.result, postcss }
this.plugins = this.processor.plugins.map(plugin => {
if (typeof plugin === 'object' && plugin.prepare) {
return { ...plugin, ...plugin.prepare(this.result) }
@@ -185,6 +153,67 @@ class LazyResult {
})
}
get [Symbol.toStringTag]() {
return 'LazyResult'
}
get processor() {
return this.result.processor
}
get opts() {
return this.result.opts
}
get css() {
return this.stringify().css
}
get content() {
return this.stringify().content
}
get map() {
return this.stringify().map
}
get root() {
return this.sync().root
}
get messages() {
return this.sync().messages
}
warnings() {
return this.sync().warnings()
}
toString() {
return this.css
}
then(onFulfilled, onRejected) {
if (process.env.NODE_ENV !== 'production') {
if (!('from' in this.opts)) {
warnOnce(
'Without `from` option PostCSS could generate wrong source map ' +
'and will not find Browserslist config. Set it to CSS file path ' +
'or to `undefined` to prevent this warning.'
)
}
}
return this.async().then(onFulfilled, onRejected)
}
catch(onRejected) {
return this.async().catch(onRejected)
}
finally(onFinally) {
return this.async().then(onFinally, onFinally)
}
async() {
if (this.error) return Promise.reject(this.error)
if (this.processed) return Promise.resolve(this.result)
@@ -194,12 +223,124 @@ class LazyResult {
return this.processing
}
catch(onRejected) {
return this.async().catch(onRejected)
sync() {
if (this.error) throw this.error
if (this.processed) return this.result
this.processed = true
if (this.processing) {
throw this.getAsyncError()
}
for (let plugin of this.plugins) {
let promise = this.runOnRoot(plugin)
if (isPromise(promise)) {
throw this.getAsyncError()
}
}
this.prepareVisitors()
if (this.hasListener) {
let root = this.result.root
while (!root[isClean]) {
root[isClean] = true
this.walkSync(root)
}
if (this.listeners.OnceExit) {
if (root.type === 'document') {
for (let subRoot of root.nodes) {
this.visitSync(this.listeners.OnceExit, subRoot)
}
} else {
this.visitSync(this.listeners.OnceExit, root)
}
}
}
return this.result
}
finally(onFinally) {
return this.async().then(onFinally, onFinally)
stringify() {
if (this.error) throw this.error
if (this.stringified) return this.result
this.stringified = true
this.sync()
let opts = this.result.opts
let str = stringify
if (opts.syntax) str = opts.syntax.stringify
if (opts.stringifier) str = opts.stringifier
if (str.stringify) str = str.stringify
let map = new MapGenerator(str, this.result.root, this.result.opts)
let data = map.generate()
this.result.css = data[0]
this.result.map = data[1]
return this.result
}
walkSync(node) {
node[isClean] = true
let events = getEvents(node)
for (let event of events) {
if (event === CHILDREN) {
if (node.nodes) {
node.each(child => {
if (!child[isClean]) this.walkSync(child)
})
}
} else {
let visitors = this.listeners[event]
if (visitors) {
if (this.visitSync(visitors, node.toProxy())) return
}
}
}
}
visitSync(visitors, node) {
for (let [plugin, visitor] of visitors) {
this.result.lastPlugin = plugin
let promise
try {
promise = visitor(node, this.helpers)
} catch (e) {
throw this.handleError(e, node.proxyOf)
}
if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
return true
}
if (isPromise(promise)) {
throw this.getAsyncError()
}
}
}
runOnRoot(plugin) {
this.result.lastPlugin = plugin
try {
if (typeof plugin === 'object' && plugin.Once) {
if (this.result.root.type === 'document') {
let roots = this.result.root.nodes.map(root =>
plugin.Once(root, this.helpers)
)
if (isPromise(roots[0])) {
return Promise.all(roots)
}
return roots
}
return plugin.Once(this.result.root, this.helpers)
} else if (typeof plugin === 'function') {
return plugin(this.result.root, this.result)
}
} catch (error) {
throw this.handleError(error)
}
}
getAsyncError() {
@@ -245,44 +386,6 @@ class LazyResult {
return error
}
prepareVisitors() {
this.listeners = {}
let add = (plugin, type, cb) => {
if (!this.listeners[type]) this.listeners[type] = []
this.listeners[type].push([plugin, cb])
}
for (let plugin of this.plugins) {
if (typeof plugin === 'object') {
for (let event in plugin) {
if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
throw new Error(
`Unknown event ${event} in ${plugin.postcssPlugin}. ` +
`Try to update PostCSS (${this.processor.version} now).`
)
}
if (!NOT_VISITORS[event]) {
if (typeof plugin[event] === 'object') {
for (let filter in plugin[event]) {
if (filter === '*') {
add(plugin, event, plugin[event][filter])
} else {
add(
plugin,
event + '-' + filter.toLowerCase(),
plugin[event][filter]
)
}
}
} else if (typeof plugin[event] === 'function') {
add(plugin, event, plugin[event])
}
}
}
}
}
this.hasListener = Object.keys(this.listeners).length > 0
}
async runAsync() {
this.plugin = 0
for (let i = 0; i < this.plugins.length; i++) {
@@ -340,122 +443,42 @@ class LazyResult {
return this.stringify()
}
runOnRoot(plugin) {
this.result.lastPlugin = plugin
try {
if (typeof plugin === 'object' && plugin.Once) {
if (this.result.root.type === 'document') {
let roots = this.result.root.nodes.map(root =>
plugin.Once(root, this.helpers)
)
if (isPromise(roots[0])) {
return Promise.all(roots)
}
return roots
}
return plugin.Once(this.result.root, this.helpers)
} else if (typeof plugin === 'function') {
return plugin(this.result.root, this.result)
}
} catch (error) {
throw this.handleError(error)
prepareVisitors() {
this.listeners = {}
let add = (plugin, type, cb) => {
if (!this.listeners[type]) this.listeners[type] = []
this.listeners[type].push([plugin, cb])
}
}
stringify() {
if (this.error) throw this.error
if (this.stringified) return this.result
this.stringified = true
this.sync()
let opts = this.result.opts
let str = stringify
if (opts.syntax) str = opts.syntax.stringify
if (opts.stringifier) str = opts.stringifier
if (str.stringify) str = str.stringify
let map = new MapGenerator(str, this.result.root, this.result.opts)
let data = map.generate()
this.result.css = data[0]
this.result.map = data[1]
return this.result
}
sync() {
if (this.error) throw this.error
if (this.processed) return this.result
this.processed = true
if (this.processing) {
throw this.getAsyncError()
}
for (let plugin of this.plugins) {
let promise = this.runOnRoot(plugin)
if (isPromise(promise)) {
throw this.getAsyncError()
}
}
this.prepareVisitors()
if (this.hasListener) {
let root = this.result.root
while (!root[isClean]) {
root[isClean] = true
this.walkSync(root)
}
if (this.listeners.OnceExit) {
if (root.type === 'document') {
for (let subRoot of root.nodes) {
this.visitSync(this.listeners.OnceExit, subRoot)
if (typeof plugin === 'object') {
for (let event in plugin) {
if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
throw new Error(
`Unknown event ${event} in ${plugin.postcssPlugin}. ` +
`Try to update PostCSS (${this.processor.version} now).`
)
}
if (!NOT_VISITORS[event]) {
if (typeof plugin[event] === 'object') {
for (let filter in plugin[event]) {
if (filter === '*') {
add(plugin, event, plugin[event][filter])
} else {
add(
plugin,
event + '-' + filter.toLowerCase(),
plugin[event][filter]
)
}
}
} else if (typeof plugin[event] === 'function') {
add(plugin, event, plugin[event])
}
}
} else {
this.visitSync(this.listeners.OnceExit, root)
}
}
}
return this.result
}
then(onFulfilled, onRejected) {
if (process.env.NODE_ENV !== 'production') {
if (!('from' in this.opts)) {
warnOnce(
'Without `from` option PostCSS could generate wrong source map ' +
'and will not find Browserslist config. Set it to CSS file path ' +
'or to `undefined` to prevent this warning.'
)
}
}
return this.async().then(onFulfilled, onRejected)
}
toString() {
return this.css
}
visitSync(visitors, node) {
for (let [plugin, visitor] of visitors) {
this.result.lastPlugin = plugin
let promise
try {
promise = visitor(node, this.helpers)
} catch (e) {
throw this.handleError(e, node.proxyOf)
}
if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
return true
}
if (isPromise(promise)) {
throw this.getAsyncError()
}
}
this.hasListener = Object.keys(this.listeners).length > 0
}
visitTick(stack) {
@@ -514,29 +537,6 @@ class LazyResult {
}
stack.pop()
}
walkSync(node) {
node[isClean] = true
let events = getEvents(node)
for (let event of events) {
if (event === CHILDREN) {
if (node.nodes) {
node.each(child => {
if (!child[isClean]) this.walkSync(child)
})
}
} else {
let visitors = this.listeners[event]
if (visitors) {
if (this.visitSync(visitors, node.toProxy())) return
}
}
}
}
warnings() {
return this.sync().warnings()
}
}
LazyResult.registerPostcss = dependant => {

103
node_modules/postcss/lib/list.d.ts generated vendored
View File

@@ -1,60 +1,51 @@
declare namespace list {
type List = {
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* ```js
* Once (root, { list }) {
* list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
* }
* ```
*
* @param str Comma-separated values.
* @return Split values.
*/
comma(str: string): string[]
export type List = {
/**
* Safely splits values.
*
* ```js
* Once (root, { list }) {
* list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)']
* }
* ```
*
* @param string separated values.
* @param separators array of separators.
* @param last boolean indicator.
* @return Split values.
*/
split(string: string, separators: string[], last: boolean): string[]
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* ```js
* Once (root, { list }) {
* list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
* }
* ```
*
* @param str Space-separated values.
* @return Split values.
*/
space(str: string): string[]
default: List
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* ```js
* Once (root, { list }) {
* list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
* }
* ```
*
* @param str Space-separated values.
* @return Split values.
*/
space(str: string): string[]
/**
* Safely splits values.
*
* ```js
* Once (root, { list }) {
* list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)']
* }
* ```
*
* @param string separated values.
* @param separators array of separators.
* @param last boolean indicator.
* @return Split values.
*/
split(
string: string,
separators: readonly string[],
last: boolean
): string[]
}
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* ```js
* Once (root, { list }) {
* list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
* }
* ```
*
* @param str Comma-separated values.
* @return Split values.
*/
comma(str: string): string[]
}
declare const list: list.List
declare const list: List
export = list
export default list

18
node_modules/postcss/lib/list.js generated vendored
View File

@@ -1,15 +1,6 @@
'use strict'
let list = {
comma(string) {
return list.split(string, [','], true)
},
space(string) {
let spaces = [' ', '\n', '\t']
return list.split(string, spaces)
},
split(string, separators, last) {
let array = []
let current = ''
@@ -51,6 +42,15 @@ let list = {
if (last || current !== '') array.push(current.trim())
return array
},
space(string) {
let spaces = [' ', '\n', '\t']
return list.split(string, spaces)
},
comma(string) {
return list.split(string, [','], true)
}
}

View File

@@ -1,7 +1,7 @@
'use strict'
let { dirname, relative, resolve, sep } = require('path')
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
let { dirname, resolve, relative, sep } = require('path')
let { pathToFileURL } = require('url')
let Input = require('./input')
@@ -16,12 +16,141 @@ class MapGenerator {
this.root = root
this.opts = opts
this.css = cssString
this.originalCSS = cssString
this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute
}
this.memoizedFileURLs = new Map()
this.memoizedPaths = new Map()
this.memoizedURLs = new Map()
isMap() {
if (typeof this.opts.map !== 'undefined') {
return !!this.opts.map
}
return this.previous().length > 0
}
previous() {
if (!this.previousMaps) {
this.previousMaps = []
if (this.root) {
this.root.walk(node => {
if (node.source && node.source.input.map) {
let map = node.source.input.map
if (!this.previousMaps.includes(map)) {
this.previousMaps.push(map)
}
}
})
} else {
let input = new Input(this.css, this.opts)
if (input.map) this.previousMaps.push(input.map)
}
}
return this.previousMaps
}
isInline() {
if (typeof this.mapOpts.inline !== 'undefined') {
return this.mapOpts.inline
}
let annotation = this.mapOpts.annotation
if (typeof annotation !== 'undefined' && annotation !== true) {
return false
}
if (this.previous().length) {
return this.previous().some(i => i.inline)
}
return true
}
isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== 'undefined') {
return this.mapOpts.sourcesContent
}
if (this.previous().length) {
return this.previous().some(i => i.withContent())
}
return true
}
clearAnnotation() {
if (this.mapOpts.annotation === false) return
if (this.root) {
let node
for (let i = this.root.nodes.length - 1; i >= 0; i--) {
node = this.root.nodes[i]
if (node.type !== 'comment') continue
if (node.text.indexOf('# sourceMappingURL=') === 0) {
this.root.removeChild(i)
}
}
} else if (this.css) {
this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '')
}
}
setSourcesContent() {
let already = {}
if (this.root) {
this.root.walk(node => {
if (node.source) {
let from = node.source.input.from
if (from && !already[from]) {
already[from] = true
let fromUrl = this.usesFileUrls
? this.toFileUrl(from)
: this.toUrl(this.path(from))
this.map.setSourceContent(fromUrl, node.source.input.css)
}
}
})
} else if (this.css) {
let from = this.opts.from
? this.toUrl(this.path(this.opts.from))
: '<no source>'
this.map.setSourceContent(from, this.css)
}
}
applyPrevMaps() {
for (let prev of this.previous()) {
let from = this.toUrl(this.path(prev.file))
let root = prev.root || dirname(prev.file)
let map
if (this.mapOpts.sourcesContent === false) {
map = new SourceMapConsumer(prev.text)
if (map.sourcesContent) {
map.sourcesContent = map.sourcesContent.map(() => null)
}
} else {
map = prev.consumer()
}
this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
}
}
isAnnotation() {
if (this.isInline()) {
return true
}
if (typeof this.mapOpts.annotation !== 'undefined') {
return this.mapOpts.annotation
}
if (this.previous().length) {
return this.previous().some(i => i.annotation)
}
return true
}
toBase64(str) {
if (Buffer) {
return Buffer.from(str).toString('base64')
} else {
return window.btoa(unescape(encodeURIComponent(str)))
}
}
addAnnotation() {
@@ -43,52 +172,13 @@ class MapGenerator {
this.css += eol + '/*# sourceMappingURL=' + content + ' */'
}
applyPrevMaps() {
for (let prev of this.previous()) {
let from = this.toUrl(this.path(prev.file))
let root = prev.root || dirname(prev.file)
let map
if (this.mapOpts.sourcesContent === false) {
map = new SourceMapConsumer(prev.text)
if (map.sourcesContent) {
map.sourcesContent = null
}
} else {
map = prev.consumer()
}
this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
}
}
clearAnnotation() {
if (this.mapOpts.annotation === false) return
if (this.root) {
let node
for (let i = this.root.nodes.length - 1; i >= 0; i--) {
node = this.root.nodes[i]
if (node.type !== 'comment') continue
if (node.text.startsWith('# sourceMappingURL=')) {
this.root.removeChild(i)
}
}
} else if (this.css) {
this.css = this.css.replace(/\n*\/\*#[\S\s]*?\*\/$/gm, '')
}
}
generate() {
this.clearAnnotation()
if (pathAvailable && sourceMapAvailable && this.isMap()) {
return this.generateMap()
outputFile() {
if (this.opts.to) {
return this.path(this.opts.to)
} else if (this.opts.from) {
return this.path(this.opts.from)
} else {
let result = ''
this.stringify(this.root, i => {
result += i
})
return [result]
return 'to.css'
}
}
@@ -98,20 +188,15 @@ class MapGenerator {
} else if (this.previous().length === 1) {
let prev = this.previous()[0].consumer()
prev.file = this.outputFile()
this.map = SourceMapGenerator.fromSourceMap(prev, {
ignoreInvalidMapping: true
})
this.map = SourceMapGenerator.fromSourceMap(prev)
} else {
this.map = new SourceMapGenerator({
file: this.outputFile(),
ignoreInvalidMapping: true
})
this.map = new SourceMapGenerator({ file: this.outputFile() })
this.map.addMapping({
generated: { column: 0, line: 1 },
original: { column: 0, line: 1 },
source: this.opts.from
? this.toUrl(this.path(this.opts.from))
: '<no source>'
: '<no source>',
generated: { line: 1, column: 0 },
original: { line: 1, column: 0 }
})
}
@@ -126,24 +211,63 @@ class MapGenerator {
}
}
path(file) {
if (file.indexOf('<') === 0) return file
if (/^\w+:\/\//.test(file)) return file
if (this.mapOpts.absolute) return file
let from = this.opts.to ? dirname(this.opts.to) : '.'
if (typeof this.mapOpts.annotation === 'string') {
from = dirname(resolve(from, this.mapOpts.annotation))
}
file = relative(from, file)
return file
}
toUrl(path) {
if (sep === '\\') {
path = path.replace(/\\/g, '/')
}
return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
}
toFileUrl(path) {
if (pathToFileURL) {
return pathToFileURL(path).toString()
} else {
throw new Error(
'`map.absolute` option is not available in this PostCSS build'
)
}
}
sourcePath(node) {
if (this.mapOpts.from) {
return this.toUrl(this.mapOpts.from)
} else if (this.usesFileUrls) {
return this.toFileUrl(node.source.input.from)
} else {
return this.toUrl(this.path(node.source.input.from))
}
}
generateString() {
this.css = ''
this.map = new SourceMapGenerator({
file: this.outputFile(),
ignoreInvalidMapping: true
})
this.map = new SourceMapGenerator({ file: this.outputFile() })
let line = 1
let column = 1
let noSource = '<no source>'
let mapping = {
generated: { column: 0, line: 0 },
original: { column: 0, line: 0 },
source: ''
source: '',
generated: { line: 0, column: 0 },
original: { line: 0, column: 0 }
}
let last, lines
let lines, last
this.stringify(this.root, (str, node, type) => {
this.css += str
@@ -197,172 +321,18 @@ class MapGenerator {
})
}
isAnnotation() {
if (this.isInline()) {
return true
}
if (typeof this.mapOpts.annotation !== 'undefined') {
return this.mapOpts.annotation
}
if (this.previous().length) {
return this.previous().some(i => i.annotation)
}
return true
}
isInline() {
if (typeof this.mapOpts.inline !== 'undefined') {
return this.mapOpts.inline
}
let annotation = this.mapOpts.annotation
if (typeof annotation !== 'undefined' && annotation !== true) {
return false
}
if (this.previous().length) {
return this.previous().some(i => i.inline)
}
return true
}
isMap() {
if (typeof this.opts.map !== 'undefined') {
return !!this.opts.map
}
return this.previous().length > 0
}
isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== 'undefined') {
return this.mapOpts.sourcesContent
}
if (this.previous().length) {
return this.previous().some(i => i.withContent())
}
return true
}
outputFile() {
if (this.opts.to) {
return this.path(this.opts.to)
} else if (this.opts.from) {
return this.path(this.opts.from)
generate() {
this.clearAnnotation()
if (pathAvailable && sourceMapAvailable && this.isMap()) {
return this.generateMap()
} else {
return 'to.css'
}
}
path(file) {
if (this.mapOpts.absolute) return file
if (file.charCodeAt(0) === 60 /* `<` */) return file
if (/^\w+:\/\//.test(file)) return file
let cached = this.memoizedPaths.get(file)
if (cached) return cached
let from = this.opts.to ? dirname(this.opts.to) : '.'
if (typeof this.mapOpts.annotation === 'string') {
from = dirname(resolve(from, this.mapOpts.annotation))
}
let path = relative(from, file)
this.memoizedPaths.set(file, path)
return path
}
previous() {
if (!this.previousMaps) {
this.previousMaps = []
if (this.root) {
this.root.walk(node => {
if (node.source && node.source.input.map) {
let map = node.source.input.map
if (!this.previousMaps.includes(map)) {
this.previousMaps.push(map)
}
}
})
} else {
let input = new Input(this.originalCSS, this.opts)
if (input.map) this.previousMaps.push(input.map)
}
}
return this.previousMaps
}
setSourcesContent() {
let already = {}
if (this.root) {
this.root.walk(node => {
if (node.source) {
let from = node.source.input.from
if (from && !already[from]) {
already[from] = true
let fromUrl = this.usesFileUrls
? this.toFileUrl(from)
: this.toUrl(this.path(from))
this.map.setSourceContent(fromUrl, node.source.input.css)
}
}
let result = ''
this.stringify(this.root, i => {
result += i
})
} else if (this.css) {
let from = this.opts.from
? this.toUrl(this.path(this.opts.from))
: '<no source>'
this.map.setSourceContent(from, this.css)
return [result]
}
}
sourcePath(node) {
if (this.mapOpts.from) {
return this.toUrl(this.mapOpts.from)
} else if (this.usesFileUrls) {
return this.toFileUrl(node.source.input.from)
} else {
return this.toUrl(this.path(node.source.input.from))
}
}
toBase64(str) {
if (Buffer) {
return Buffer.from(str).toString('base64')
} else {
return window.btoa(unescape(encodeURIComponent(str)))
}
}
toFileUrl(path) {
let cached = this.memoizedFileURLs.get(path)
if (cached) return cached
if (pathToFileURL) {
let fileURL = pathToFileURL(path).toString()
this.memoizedFileURLs.set(path, fileURL)
return fileURL
} else {
throw new Error(
'`map.absolute` option is not available in this PostCSS build'
)
}
}
toUrl(path) {
let cached = this.memoizedURLs.get(path)
if (cached) return cached
if (sep === '\\') {
path = path.replace(/\\/g, '/')
}
let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent)
this.memoizedURLs.set(path, url)
return url
}
}
module.exports = MapGenerator

View File

@@ -1,14 +1,9 @@
import LazyResult from './lazy-result.js'
import Result, { Message, ResultOptions } from './result.js'
import { SourceMap } from './postcss.js'
import Processor from './processor.js'
import Result, { Message, ResultOptions } from './result.js'
import Root from './root.js'
import Warning from './warning.js'
declare namespace NoWorkResult {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { NoWorkResult_ as default }
}
import Root from './root.js'
import LazyResult from './lazy-result.js'
/**
* A Promise proxy for the result of PostCSS transformations.
@@ -22,25 +17,21 @@ declare namespace NoWorkResult {
* let root = noWorkResult.root // now css is parsed because we accessed the root
* ```
*/
declare class NoWorkResult_ implements LazyResult<Root> {
catch: Promise<Result<Root>>['catch']
finally: Promise<Result<Root>>['finally']
then: Promise<Result<Root>>['then']
get content(): string
get css(): string
get map(): SourceMap
get messages(): Message[]
get opts(): ResultOptions
get processor(): Processor
get root(): Root
get [Symbol.toStringTag](): string
export default class NoWorkResult implements LazyResult {
then: Promise<Result>['then']
catch: Promise<Result>['catch']
finally: Promise<Result>['finally']
constructor(processor: Processor, css: string, opts: ResultOptions)
async(): Promise<Result<Root>>
sync(): Result<Root>
toString(): string
get [Symbol.toStringTag](): string
get processor(): Processor
get opts(): ResultOptions
get css(): string
get content(): string
get map(): SourceMap
get root(): Root
get messages(): Message[]
warnings(): Warning[]
toString(): string
sync(): Result
async(): Promise<Result>
}
declare class NoWorkResult extends NoWorkResult_ {}
export = NoWorkResult

View File

@@ -1,62 +1,12 @@
'use strict'
let MapGenerator = require('./map-generator')
let parse = require('./parse')
const Result = require('./result')
let stringify = require('./stringify')
let warnOnce = require('./warn-once')
let parse = require('./parse')
const Result = require('./result')
class NoWorkResult {
get content() {
return this.result.css
}
get css() {
return this.result.css
}
get map() {
return this.result.map
}
get messages() {
return []
}
get opts() {
return this.result.opts
}
get processor() {
return this.result.processor
}
get root() {
if (this._root) {
return this._root
}
let root
let parser = parse
try {
root = parser(this._css, this._opts)
} catch (error) {
this.error = error
}
if (this.error) {
throw this.error
} else {
this._root = root
return root
}
}
get [Symbol.toStringTag]() {
return 'NoWorkResult'
}
constructor(processor, css, opts) {
css = css.toString()
this.stringified = false
@@ -87,28 +37,65 @@ class NoWorkResult {
if (generatedMap) {
this.result.map = generatedMap
}
} else {
map.clearAnnotation()
this.result.css = map.css
}
}
async() {
if (this.error) return Promise.reject(this.error)
return Promise.resolve(this.result)
get [Symbol.toStringTag]() {
return 'NoWorkResult'
}
catch(onRejected) {
return this.async().catch(onRejected)
get processor() {
return this.result.processor
}
finally(onFinally) {
return this.async().then(onFinally, onFinally)
get opts() {
return this.result.opts
}
sync() {
if (this.error) throw this.error
return this.result
get css() {
return this.result.css
}
get content() {
return this.result.css
}
get map() {
return this.result.map
}
get root() {
if (this._root) {
return this._root
}
let root
let parser = parse
try {
root = parser(this._css, this._opts)
} catch (error) {
this.error = error
}
if (this.error) {
throw this.error
} else {
this._root = root
return root
}
}
get messages() {
return []
}
warnings() {
return []
}
toString() {
return this._css
}
then(onFulfilled, onRejected) {
@@ -125,12 +112,22 @@ class NoWorkResult {
return this.async().then(onFulfilled, onRejected)
}
toString() {
return this._css
catch(onRejected) {
return this.async().catch(onRejected)
}
warnings() {
return []
finally(onFinally) {
return this.async().then(onFinally, onFinally)
}
async() {
if (this.error) return Promise.reject(this.error)
return Promise.resolve(this.result)
}
sync() {
if (this.error) throw this.error
return this.result
}
}

648
node_modules/postcss/lib/node.d.ts generated vendored
View File

@@ -1,162 +1,166 @@
import AtRule = require('./at-rule.js')
import { AtRuleProps } from './at-rule.js'
import Comment, { CommentProps } from './comment.js'
import Container, { NewChild } from './container.js'
import CssSyntaxError from './css-syntax-error.js'
import Declaration, { DeclarationProps } from './declaration.js'
import Document from './document.js'
import Input from './input.js'
import Comment, { CommentProps } from './comment.js'
import { Stringifier, Syntax } from './postcss.js'
import Result from './result.js'
import Root from './root.js'
import AtRule, { AtRuleProps } from './at-rule.js'
import Rule, { RuleProps } from './rule.js'
import Warning, { WarningOptions } from './warning.js'
import CssSyntaxError from './css-syntax-error.js'
import Result from './result.js'
import Input from './input.js'
import Root from './root.js'
import Document from './document.js'
import Container from './container.js'
declare namespace Node {
export type ChildNode = AtRule.default | Comment | Declaration | Rule
export type ChildNode = AtRule | Rule | Declaration | Comment
export type AnyNode =
| AtRule.default
| Comment
| Declaration
| Document
| Root
| Rule
export type AnyNode = AtRule | Rule | Declaration | Comment | Root | Document
export type ChildProps =
| AtRuleProps
| CommentProps
| DeclarationProps
| RuleProps
export type ChildProps =
| AtRuleProps
| RuleProps
| DeclarationProps
| CommentProps
export interface Position {
/**
* Source line in file. In contrast to `offset` it starts from 1.
*/
column: number
/**
* Source column in file.
*/
line: number
/**
* Source offset in file. It starts from 0.
*/
offset: number
}
export interface Range {
/**
* End position, exclusive.
*/
end: Position
/**
* Start position, inclusive.
*/
start: Position
}
export interface Position {
/**
* Source offset in file. It starts from 0.
*/
offset: number
/**
* Source represents an interface for the {@link Node.source} property.
* Source line in file. In contrast to `offset` it starts from 1.
*/
export interface Source {
/**
* The inclusive ending position for the source
* code of a node.
*
* However, `end.offset` of a non `Root` node is the exclusive position.
* See https://github.com/postcss/postcss/pull/1879 for details.
*
* ```js
* const root = postcss.parse('a { color: black }')
* const a = root.first
* const color = a.first
*
* // The offset of `Root` node is the inclusive position
* css.source.end // { line: 1, column: 19, offset: 18 }
*
* // The offset of non `Root` node is the exclusive position
* a.source.end // { line: 1, column: 18, offset: 18 }
* color.source.end // { line: 1, column: 16, offset: 16 }
* ```
*/
end?: Position
/**
* The source file from where a node has originated.
*/
input: Input
/**
* The inclusive starting position for the source
* code of a node.
*/
start?: Position
}
column: number
/**
* Interface represents an interface for an object received
* as parameter by Node class constructor.
* Source column in file.
*/
export interface NodeProps {
source?: Source
}
line: number
}
export interface NodeErrorOptions {
/**
* An ending index inside a node's string that should be highlighted as
* source of error.
*/
endIndex?: number
/**
* An index inside a node's string that should be highlighted as source
* of error.
*/
index?: number
/**
* Plugin name that created this error. PostCSS will set it automatically.
*/
plugin?: string
/**
* A word inside a node's string, that should be highlighted as source
* of error.
*/
word?: string
}
export interface Range {
/**
* Start position, inclusive.
*/
start: Position
// eslint-disable-next-line @typescript-eslint/no-shadow
class Node extends Node_ {}
export { Node as default }
/**
* End position, exclusive.
*/
end: Position
}
export interface Source {
/**
* The file source of the node.
*/
input: Input
/**
* The inclusive starting position of the nodes source.
*/
start?: Position
/**
* The inclusive ending position of the node's source.
*/
end?: Position
}
export interface NodeProps {
source?: Source
}
interface NodeErrorOptions {
/**
* Plugin name that created this error. PostCSS will set it automatically.
*/
plugin?: string
/**
* A word inside a node's string, that should be highlighted as source
* of error.
*/
word?: string
/**
* An index inside a node's string that should be highlighted as source
* of error.
*/
index?: number
/**
* An ending index inside a node's string that should be highlighted as
* source of error.
*/
endIndex?: number
}
/**
* It represents an abstract class that handles common
* methods for other CSS abstract syntax tree nodes.
* All node classes inherit the following common methods.
*
* Any node that represents CSS selector or value should
* not extend the `Node` class.
* You should not extend this classes to create AST for selector or value
* parser.
*/
declare abstract class Node_ {
export default abstract class Node {
/**
* It represents parent of the current node.
* tring representing the nodes type. Possible values are `root`, `atrule`,
* `rule`, `decl`, or `comment`.
*
* ```js
* root.nodes[0].parent === root //=> true
* new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
* ```
*/
parent: Container | Document | undefined
type: string
/**
* It represents unnecessary whitespace and characters present
* in the css source code.
* The nodes parent node.
*
* ```js
* root.nodes[0].parent === root
* ```
*/
parent: Document | Container | undefined
/**
* The input source of the node.
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new nodes
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
* ```
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* })
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
* ```
*
* ```js
* if (atrule.name === 'add-link') {
* const rule = postcss.rule({ selector: 'a', source: atrule.source })
* atrule.parent.insertBefore(atrule, rule)
* }
* ```
*/
source?: Source
/**
* Information to generate byte-to-byte equal node string as it was
* in the origin input.
*
* The properties of the raws object are decided by parser,
* the default parser uses the following properties:
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
@@ -171,11 +175,13 @@ declare abstract class Node_ {
* * `left`: the space symbols between `/*` and the comments text.
* * `right`: the space symbols between the comments text
* and <code>*&#47;</code>.
* - `important`: the content of the important statement,
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS filters out the comments inside selectors, declaration values
* and at-rule parameters but it stores the origin content in raws.
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you dont change a declarations value,
* PostCSS will use the raw value with comments.
*
* ```js
* const root = postcss.parse('a {\n color:black\n}')
@@ -185,131 +191,101 @@ declare abstract class Node_ {
raws: any
/**
* It represents information related to origin of a node and is required
* for generating source maps.
*
* The nodes that are created manually using the public APIs
* provided by PostCSS will have `source` undefined and
* will be absent in the source map.
*
* For this reason, the plugin developer should consider
* duplicating nodes as the duplicate node will have the
* same source as the original node by default or assign
* source to a node created manually.
*
* ```js
* decl.source.input.from //=> '/home/ai/source.css'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
* ```
*
* ```js
* // Incorrect method, source not specified!
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* })
*
* // Correct method, source is inherited when duplicating.
* const prefixed = decl.clone({
* prop: '-moz-' + decl.prop
* })
* ```
*
* ```js
* if (atrule.name === 'add-link') {
* const rule = postcss.rule({
* selector: 'a',
* source: atrule.source
* })
*
* atrule.parent.insertBefore(atrule, rule)
* }
* ```
* @param defaults Value for node properties.
*/
source?: Node.Source
/**
* It represents type of a node in
* an abstract syntax tree.
*
* A type of node helps in identification of a node
* and perform operation based on it's type.
*
* ```js
* const declaration = new Declaration({
* prop: 'color',
* value: 'black'
* })
*
* declaration.type //=> 'decl'
* ```
*/
type: string
constructor(defaults?: object)
/**
* Insert new node after current node to current nodes parent.
* Returns a `CssSyntaxError` instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* Just alias for `node.parent.insertAfter(node, add)`.
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* ```js
* decl.after('color: black')
* if (!variables[name]) {
* throw decl.error(`Unknown variable ${name}`, { word: name })
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
* ```
*
* @param newNode New node.
* @return This node for methods chain.
* @param message Error description.
* @param opts Options.
*
* @return Error object to throw it.
*/
after(
newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
): this
error(message: string, options?: NodeErrorOptions): CssSyntaxError
/**
* It assigns properties to an existing node instance.
* This method is provided as a convenience wrapper for `Result#warn`.
*
* ```js
* Declaration: {
* bad: (decl, { result }) => {
* decl.warn(result, 'Deprecated property bad')
* }
* }
* ```
*
* @param result The `Result` instance that will receive the warning.
* @param text Warning message.
* @param opts Warning Options.
*
* @return Created warning object.
*/
warn(result: Result, text: string, opts?: WarningOptions): Warning
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* ```js
* if (decl.prop.match(/^-webkit-/)) {
* decl.remove()
* }
* ```
*
* @return Node to make calls chain.
*/
remove(): this
/**
* Returns a CSS string representing the node.
*
* ```js
* new Rule({ selector: 'a' }).toString() //=> "a {}"
* ```
*
* @param stringifier A syntax to use in string generation.
* @return CSS string of this node.
*/
toString(stringifier?: Stringifier | Syntax): string
/**
* Assigns properties to the current node.
*
* ```js
* decl.assign({ prop: 'word-wrap', value: 'break-word' })
* ```
*
* @param overrides New properties to override the node.
*
* @return `this` for method chaining.
* @return Current node to methods chain.
*/
assign(overrides: object): this
/**
* Insert new node before current node to current nodes parent.
* Returns an exact clone of the node.
*
* Just alias for `node.parent.insertBefore(node, add)`.
*
* ```js
* decl.before('content: ""')
* ```
*
* @param newNode New node.
* @return This node for methods chain.
*/
before(
newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
): this
/**
* Clear the code style properties for the node and its children.
*
* ```js
* node.raws.before //=> ' '
* node.cleanRaws()
* node.raws.before //=> undefined
* ```
*
* @param keepBetween Keep the `raws.between` symbols.
*/
cleanRaws(keepBetween?: boolean): void
/**
* It creates clone of an existing node, which includes all the properties
* and their values, that includes `raws` but not `type`.
* The resulting cloned node and its (cloned) children will retain
* code style properties.
*
* ```js
* decl.raws.before //=> "\n "
@@ -319,20 +295,10 @@ declare abstract class Node_ {
* ```
*
* @param overrides New properties to override in the clone.
*
* @return Duplicate of the node instance.
* @return Clone of the node.
*/
clone(overrides?: object): this
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param overrides New properties to override in the clone.
* @return New node.
*/
cloneAfter(overrides?: object): this
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
@@ -348,40 +314,31 @@ declare abstract class Node_ {
cloneBefore(overrides?: object): this
/**
* It creates an instance of the class `CssSyntaxError` and parameters passed
* to this method are assigned to the error instance.
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* The error instance will have description for the
* error, original position of the node in the
* source, showing line and column number.
*
* If any previous map is present, it would be used
* to get original position of the source.
*
* The Previous Map here is referred to the source map
* generated by previous compilation, example: Less,
* Stylus and Sass.
*
* This method returns the error instance instead of
* throwing it.
* @param overrides New properties to override in the clone.
* @return New node.
*/
cloneAfter(overrides?: object): this
/**
* Inserts node(s) before the current node and removes the current node.
*
* ```js
* if (!variables[name]) {
* throw decl.error(`Unknown variable ${name}`, { word: name })
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* AtRule: {
* mixin: atrule => {
* atrule.replaceWith(mixinRules[atrule.params])
* }
* }
* ```
*
* @param message Description for the error instance.
* @param options Options for the error instance.
*
* @return Error instance is returned.
* @param nodes Mode(s) to replace current one.
* @return Current node to methods chain.
*/
error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError
replaceWith(
...nodes: (ChildNode | ChildProps | ChildNode[] | ChildProps[])[]
): this
/**
* Returns the next child of the nodes parent.
@@ -398,23 +355,7 @@ declare abstract class Node_ {
*
* @return Next node.
*/
next(): Node.ChildNode | undefined
/**
* Get the position for a word or an index inside the node.
*
* @param opts Options.
* @return Position.
*/
positionBy(opts?: Pick<WarningOptions, 'index' | 'word'>): Node.Position
/**
* Convert string index to line/column.
*
* @param index The symbol number in the nodes string.
* @return Symbol position in file.
*/
positionInside(index: number): Node.Position
next(): ChildNode | undefined
/**
* Returns the previous child of the nodes parent.
@@ -429,21 +370,49 @@ declare abstract class Node_ {
*
* @return Previous node.
*/
prev(): Node.ChildNode | undefined
prev(): ChildNode | undefined
/**
* Get the range for a word or start and end index inside the node.
* The start index is inclusive; the end index is exclusive.
* Insert new node before current node to current nodes parent.
*
* @param opts Options.
* @return Range.
* Just alias for `node.parent.insertBefore(node, add)`.
*
* ```js
* decl.before('content: ""')
* ```
*
* @param newNode New node.
* @return This node for methods chain.
*/
rangeBy(
opts?: Pick<WarningOptions, 'end' | 'endIndex' | 'index' | 'start' | 'word'>
): Node.Range
before(newNode: Node | ChildProps | string | Node[]): this
/**
* Returns a `raws` value. If the node is missing
* Insert new node after current node to current nodes parent.
*
* Just alias for `node.parent.insertAfter(node, add)`.
*
* ```js
* decl.after('color: black')
* ```
*
* @param newNode New node.
* @return This node for methods chain.
*/
after(newNode: Node | ChildProps | string | Node[]): this
/**
* Finds the Root instance of the nodes tree.
*
* ```js
* root.nodes[0].nodes[0].root() === root
* ```
*
* @return Root parent.
*/
root(): Root
/**
* Returns a `Node#raws` value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
@@ -463,44 +432,17 @@ declare abstract class Node_ {
raw(prop: string, defaultType?: string): string
/**
* It removes the node from its parent and deletes its parent property.
* Clear the code style properties for the node and its children.
*
* ```js
* if (decl.prop.match(/^-webkit-/)) {
* decl.remove()
* }
* node.raws.before //=> ' '
* node.cleanRaws()
* node.raws.before //=> undefined
* ```
*
* @return `this` for method chaining.
* @param keepBetween Keep the `raws.between` symbols.
*/
remove(): this
/**
* Inserts node(s) before the current node and removes the current node.
*
* ```js
* AtRule: {
* mixin: atrule => {
* atrule.replaceWith(mixinRules[atrule.params])
* }
* }
* ```
*
* @param nodes Mode(s) to replace current one.
* @return Current node to methods chain.
*/
replaceWith(...nodes: NewChild[]): this
/**
* Finds the Root instance of the nodes tree.
*
* ```js
* root.nodes[0].nodes[0].root() === root
* ```
*
* @return Root parent.
*/
root(): Root
cleanRaws(keepBetween?: boolean): void
/**
* Fix circular links on `JSON.stringify()`.
@@ -510,47 +452,27 @@ declare abstract class Node_ {
toJSON(): object
/**
* It compiles the node to browser readable cascading style sheets string
* depending on it's type.
* Convert string index to line/column.
*
* ```js
* new Rule({ selector: 'a' }).toString() //=> "a {}"
* ```
*
* @param stringifier A syntax to use in string generation.
* @return CSS string of this node.
* @param index The symbol number in the nodes string.
* @return Symbol position in file.
*/
toString(stringifier?: Stringifier | Syntax): string
positionInside(index: number): Position
/**
* It is a wrapper for {@link Result#warn}, providing convenient
* way of generating warnings.
* Get the position for a word or an index inside the node.
*
* ```js
* Declaration: {
* bad: (decl, { result }) => {
* decl.warn(result, 'Deprecated property: bad')
* }
* }
* ```
*
* @param result The `Result` instance that will receive the warning.
* @param message Description for the warning.
* @param options Options for the warning.
*
* @return `Warning` instance is returned
* @param opts Options.
* @return Position.
*/
warn(result: Result, message: string, options?: WarningOptions): Warning
positionBy(opts?: Pick<WarningOptions, 'word' | 'index'>): Position
/**
* If this node isn't already dirty, marks it and its ancestors as such. This
* indicates to the LazyResult processor that the {@link Root} has been
* modified by the current plugin and may need to be processed again by other
* plugins.
* Get the range for a word or start and end index inside the node.
* The start index is inclusive; the end index is exclusive.
*
* @param opts Options.
* @return Range.
*/
protected markDirty(): void
rangeBy(opts?: Pick<WarningOptions, 'word' | 'index' | 'endIndex'>): Range
}
declare class Node extends Node_ {}
export = Node

476
node_modules/postcss/lib/node.js generated vendored
View File

@@ -1,9 +1,9 @@
'use strict'
let { isClean, my } = require('./symbols')
let CssSyntaxError = require('./css-syntax-error')
let Stringifier = require('./stringifier')
let stringify = require('./stringify')
let { isClean, my } = require('./symbols')
function cloneNode(obj, parent) {
let cloned = new obj.constructor()
@@ -32,38 +32,7 @@ function cloneNode(obj, parent) {
return cloned
}
function sourceOffset(inputCSS, position) {
// Not all custom syntaxes support `offset` in `source.start` and `source.end`
if (position && typeof position.offset !== 'undefined') {
return position.offset
}
let column = 1
let line = 1
let offset = 0
for (let i = 0; i < inputCSS.length; i++) {
if (line === position.line && column === position.column) {
offset = i
break
}
if (inputCSS[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return offset
}
class Node {
get proxyOf() {
return this
}
constructor(defaults = {}) {
this.raws = {}
this[isClean] = false
@@ -85,23 +54,42 @@ class Node {
}
}
addToError(error) {
error.postcssNode = this
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
error(message, opts = {}) {
if (this.source) {
let { start, end } = this.rangeBy(opts)
return this.source.input.error(
message,
{ line: start.line, column: start.column },
{ line: end.line, column: end.column },
opts
)
}
return error
return new CssSyntaxError(message)
}
after(add) {
this.parent.insertAfter(this, add)
warn(result, text, opts) {
let data = { node: this }
for (let i in opts) data[i] = opts[i]
return result.warn(text, data)
}
remove() {
if (this.parent) {
this.parent.removeChild(this)
}
this.parent = undefined
return this
}
toString(stringifier = stringify) {
if (stringifier.stringify) stringifier = stringifier.stringify
let result = ''
stringifier(this, i => {
result += i
})
return result
}
assign(overrides = {}) {
for (let name in overrides) {
this[name] = overrides[name]
@@ -109,17 +97,6 @@ class Node {
return this
}
before(add) {
this.parent.insertBefore(this, add)
return this
}
cleanRaws(keepBetween) {
delete this.raws.before
delete this.raws.after
if (!keepBetween) delete this.raws.between
}
clone(overrides = {}) {
let cloned = cloneNode(this)
for (let name in overrides) {
@@ -128,218 +105,16 @@ class Node {
return cloned
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertAfter(this, cloned)
return cloned
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertBefore(this, cloned)
return cloned
}
error(message, opts = {}) {
if (this.source) {
let { end, start } = this.rangeBy(opts)
return this.source.input.error(
message,
{ column: start.column, line: start.line },
{ column: end.column, line: end.line },
opts
)
}
return new CssSyntaxError(message)
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
},
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
/* c8 ignore next */
prop === 'text'
) {
node.markDirty()
}
return true
}
}
}
/* c8 ignore next 3 */
markClean() {
this[isClean] = true
}
markDirty() {
if (this[isClean]) {
this[isClean] = false
let next = this
while ((next = next.parent)) {
next[isClean] = false
}
}
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index + 1]
}
positionBy(opts = {}) {
let pos = this.source.start
if (opts.index) {
pos = this.positionInside(opts.index)
} else if (opts.word) {
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
)
let index = stringRepresentation.indexOf(opts.word)
if (index !== -1) pos = this.positionInside(index)
}
return pos
}
positionInside(index) {
let column = this.source.start.column
let line = this.source.start.line
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css
let offset = sourceOffset(inputString, this.source.start)
let end = offset + index
for (let i = offset; i < end; i++) {
if (inputString[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return { column, line, offset: end }
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index - 1]
}
rangeBy(opts = {}) {
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css
let start = {
column: this.source.start.column,
line: this.source.start.line,
offset: sourceOffset(inputString, this.source.start)
}
let end = this.source.end
? {
column: this.source.end.column + 1,
line: this.source.end.line,
offset:
typeof this.source.end.offset === 'number'
? // `source.end.offset` is exclusive, so we don't need to add 1
this.source.end.offset
: // Since line/column in this.source.end is inclusive,
// the `sourceOffset(... , this.source.end)` returns an inclusive offset.
// So, we add 1 to convert it to exclusive.
sourceOffset(inputString, this.source.end) + 1
}
: {
column: start.column + 1,
line: start.line,
offset: start.offset + 1
}
if (opts.word) {
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
)
let index = stringRepresentation.indexOf(opts.word)
if (index !== -1) {
start = this.positionInside(index)
end = this.positionInside(index + opts.word.length)
}
} else {
if (opts.start) {
start = {
column: opts.start.column,
line: opts.start.line,
offset: sourceOffset(inputString, opts.start)
}
} else if (opts.index) {
start = this.positionInside(opts.index)
}
if (opts.end) {
end = {
column: opts.end.column,
line: opts.end.line,
offset: sourceOffset(inputString, opts.end)
}
} else if (typeof opts.endIndex === 'number') {
end = this.positionInside(opts.endIndex)
} else if (opts.index) {
end = this.positionInside(opts.index + 1)
}
}
if (
end.line < start.line ||
(end.line === start.line && end.column <= start.column)
) {
end = {
column: start.column + 1,
line: start.line,
offset: start.offset + 1
}
}
return { end, start }
}
raw(prop, defaultType) {
let str = new Stringifier()
return str.raw(this, prop, defaultType)
}
remove() {
if (this.parent) {
this.parent.removeChild(this)
}
this.parent = undefined
return this
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertAfter(this, cloned)
return cloned
}
replaceWith(...nodes) {
@@ -365,6 +140,28 @@ class Node {
return this
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index + 1]
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index - 1]
}
before(add) {
this.parent.insertBefore(this, add)
return this
}
after(add) {
this.parent.insertAfter(this, add)
return this
}
root() {
let result = this
while (result.parent && result.parent.type !== 'document') {
@@ -373,6 +170,17 @@ class Node {
return result
}
raw(prop, defaultType) {
let str = new Stringifier()
return str.raw(this, prop, defaultType)
}
cleanRaws(keepBetween) {
delete this.raws.before
delete this.raws.after
if (!keepBetween) delete this.raws.between
}
toJSON(_, inputs) {
let fixed = {}
let emitInputs = inputs == null
@@ -398,7 +206,6 @@ class Node {
} else if (typeof value === 'object' && value.toJSON) {
fixed[name] = value.toJSON(null, inputs)
} else if (name === 'source') {
if (value == null) continue
let inputId = inputs.get(value.input)
if (inputId == null) {
inputId = inputsNextIndex
@@ -406,9 +213,9 @@ class Node {
inputsNextIndex++
}
fixed[name] = {
end: value.end,
inputId,
start: value.start
start: value.start,
end: value.end
}
} else {
fixed[name] = value
@@ -422,6 +229,118 @@ class Node {
return fixed
}
positionInside(index) {
let string = this.toString()
let column = this.source.start.column
let line = this.source.start.line
for (let i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return { line, column }
}
positionBy(opts) {
let pos = this.source.start
if (opts.index) {
pos = this.positionInside(opts.index)
} else if (opts.word) {
let index = this.toString().indexOf(opts.word)
if (index !== -1) pos = this.positionInside(index)
}
return pos
}
rangeBy(opts) {
let start = {
line: this.source.start.line,
column: this.source.start.column
}
let end = this.source.end
? {
line: this.source.end.line,
column: this.source.end.column + 1
}
: {
line: start.line,
column: start.column + 1
}
if (opts.word) {
let index = this.toString().indexOf(opts.word)
if (index !== -1) {
start = this.positionInside(index)
end = this.positionInside(index + opts.word.length)
}
} else {
if (opts.start) {
start = {
line: opts.start.line,
column: opts.start.column
}
} else if (opts.index) {
start = this.positionInside(opts.index)
}
if (opts.end) {
end = {
line: opts.end.line,
column: opts.end.column
}
} else if (opts.endIndex) {
end = this.positionInside(opts.endIndex)
} else if (opts.index) {
end = this.positionInside(opts.index + 1)
}
}
if (
end.line < start.line ||
(end.line === start.line && end.column <= start.column)
) {
end = { line: start.line, column: start.column + 1 }
}
return { start, end }
}
getProxyProcessor() {
return {
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
/* c8 ignore next */
prop === 'text'
) {
node.markDirty()
}
return true
},
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
}
}
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor())
@@ -429,19 +348,30 @@ class Node {
return this.proxyCache
}
toString(stringifier = stringify) {
if (stringifier.stringify) stringifier = stringifier.stringify
let result = ''
stringifier(this, i => {
result += i
})
return result
addToError(error) {
error.postcssNode = this
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
)
}
return error
}
warn(result, text, opts = {}) {
let data = { node: this }
for (let i in opts) data[i] = opts[i]
return result.warn(text, data)
markDirty() {
if (this[isClean]) {
this[isClean] = false
let next = this
while ((next = next.parent)) {
next[isClean] = false
}
}
}
get proxyOf() {
return this
}
}

View File

@@ -1,9 +1,5 @@
import { Parser } from './postcss.js'
interface Parse extends Parser {
default: Parse
}
declare const parse: Parser
declare const parse: Parse
export = parse
export default parse

2
node_modules/postcss/lib/parse.js generated vendored
View File

@@ -1,8 +1,8 @@
'use strict'
let Container = require('./container')
let Input = require('./input')
let Parser = require('./parser')
let Input = require('./input')
function parse(css, opts) {
let input = new Input(css, opts)

720
node_modules/postcss/lib/parser.js generated vendored
View File

@@ -1,11 +1,11 @@
'use strict'
let AtRule = require('./at-rule')
let Comment = require('./comment')
let Declaration = require('./declaration')
let tokenizer = require('./tokenize')
let Comment = require('./comment')
let AtRule = require('./at-rule')
let Root = require('./root')
let Rule = require('./rule')
let tokenizer = require('./tokenize')
const SAFE_COMMENT_NEIGHBOR = {
empty: true,
@@ -28,152 +28,58 @@ class Parser {
this.current = this.root
this.spaces = ''
this.semicolon = false
this.customProperty = false
this.createTokenizer()
this.root.source = { input, start: { column: 1, line: 1, offset: 0 } }
this.root.source = { input, start: { offset: 0, line: 1, column: 1 } }
}
atrule(token) {
let node = new AtRule()
node.name = token[1].slice(1)
if (node.name === '') {
this.unnamedAtrule(node, token)
}
this.init(node, token[2])
let type
let prev
let shift
let last = false
let open = false
let params = []
let brackets = []
createTokenizer() {
this.tokenizer = tokenizer(this.input)
}
parse() {
let token
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken()
type = token[0]
if (type === '(' || type === '[') {
brackets.push(type === '(' ? ')' : ']')
} else if (type === '{' && brackets.length > 0) {
brackets.push('}')
} else if (type === brackets[brackets.length - 1]) {
brackets.pop()
}
switch (token[0]) {
case 'space':
this.spaces += token[1]
break
if (brackets.length === 0) {
if (type === ';') {
node.source.end = this.getPosition(token[2])
node.source.end.offset++
this.semicolon = true
case ';':
this.freeSemicolon(token)
break
} else if (type === '{') {
open = true
break
} else if (type === '}') {
if (params.length > 0) {
shift = params.length - 1
prev = params[shift]
while (prev && prev[0] === 'space') {
prev = params[--shift]
}
if (prev) {
node.source.end = this.getPosition(prev[3] || prev[2])
node.source.end.offset++
}
}
case '}':
this.end(token)
break
} else {
params.push(token)
}
} else {
params.push(token)
}
if (this.tokenizer.endOfFile()) {
last = true
break
case 'comment':
this.comment(token)
break
case 'at-word':
this.atrule(token)
break
case '{':
this.emptyRule(token)
break
default:
this.other(token)
break
}
}
node.raws.between = this.spacesAndCommentsFromEnd(params)
if (params.length) {
node.raws.afterName = this.spacesAndCommentsFromStart(params)
this.raw(node, 'params', params)
if (last) {
token = params[params.length - 1]
node.source.end = this.getPosition(token[3] || token[2])
node.source.end.offset++
this.spaces = node.raws.between
node.raws.between = ''
}
} else {
node.raws.afterName = ''
node.params = ''
}
if (open) {
node.nodes = []
this.current = node
}
}
checkMissedSemicolon(tokens) {
let colon = this.colon(tokens)
if (colon === false) return
let founded = 0
let token
for (let j = colon - 1; j >= 0; j--) {
token = tokens[j]
if (token[0] !== 'space') {
founded += 1
if (founded === 2) break
}
}
// If the token is a word, e.g. `!important`, `red` or any other valid property's value.
// Then we need to return the colon after that word token. [3] is the "end" colon of that word.
// And because we need it after that one we do +1 to get the next one.
throw this.input.error(
'Missed semicolon',
token[0] === 'word' ? token[3] + 1 : token[2]
)
}
colon(tokens) {
let brackets = 0
let prev, token, type
for (let [i, element] of tokens.entries()) {
token = element
type = token[0]
if (type === '(') {
brackets += 1
}
if (type === ')') {
brackets -= 1
}
if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token)
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue
} else {
return i
}
}
prev = token
}
return false
this.endFile()
}
comment(token) {
let node = new Comment()
this.init(node, token[2])
node.source.end = this.getPosition(token[3] || token[2])
node.source.end.offset++
let text = token[1].slice(2, -2)
if (/^\s*$/.test(text)) {
@@ -188,123 +94,6 @@ class Parser {
}
}
createTokenizer() {
this.tokenizer = tokenizer(this.input)
}
decl(tokens, customProperty) {
let node = new Declaration()
this.init(node, tokens[0][2])
let last = tokens[tokens.length - 1]
if (last[0] === ';') {
this.semicolon = true
tokens.pop()
}
node.source.end = this.getPosition(
last[3] || last[2] || findLastWithPosition(tokens)
)
node.source.end.offset++
while (tokens[0][0] !== 'word') {
if (tokens.length === 1) this.unknownWord(tokens)
node.raws.before += tokens.shift()[1]
}
node.source.start = this.getPosition(tokens[0][2])
node.prop = ''
while (tokens.length) {
let type = tokens[0][0]
if (type === ':' || type === 'space' || type === 'comment') {
break
}
node.prop += tokens.shift()[1]
}
node.raws.between = ''
let token
while (tokens.length) {
token = tokens.shift()
if (token[0] === ':') {
node.raws.between += token[1]
break
} else {
if (token[0] === 'word' && /\w/.test(token[1])) {
this.unknownWord([token])
}
node.raws.between += token[1]
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0]
node.prop = node.prop.slice(1)
}
let firstSpaces = []
let next
while (tokens.length) {
next = tokens[0][0]
if (next !== 'space' && next !== 'comment') break
firstSpaces.push(tokens.shift())
}
this.precheckMissedSemicolon(tokens)
for (let i = tokens.length - 1; i >= 0; i--) {
token = tokens[i]
if (token[1].toLowerCase() === '!important') {
node.important = true
let string = this.stringFrom(tokens, i)
string = this.spacesFromEnd(tokens) + string
if (string !== ' !important') node.raws.important = string
break
} else if (token[1].toLowerCase() === 'important') {
let cache = tokens.slice(0)
let str = ''
for (let j = i; j > 0; j--) {
let type = cache[j][0]
if (str.trim().startsWith('!') && type !== 'space') {
break
}
str = cache.pop()[1] + str
}
if (str.trim().startsWith('!')) {
node.important = true
node.raws.important = str
tokens = cache
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break
}
}
let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment')
if (hasWord) {
node.raws.between += firstSpaces.map(i => i[1]).join('')
firstSpaces = []
}
this.raw(node, 'value', firstSpaces.concat(tokens), customProperty)
if (node.value.includes(':') && !customProperty) {
this.checkMissedSemicolon(tokens)
}
}
doubleColon(token) {
throw this.input.error(
'Double colon',
{ offset: token[2] },
{ offset: token[2] + token[1].length }
)
}
emptyRule(token) {
let node = new Rule()
this.init(node, token[2])
@@ -313,68 +102,6 @@ class Parser {
this.current = node
}
end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon
}
this.semicolon = false
this.current.raws.after = (this.current.raws.after || '') + this.spaces
this.spaces = ''
if (this.current.parent) {
this.current.source.end = this.getPosition(token[2])
this.current.source.end.offset++
this.current = this.current.parent
} else {
this.unexpectedClose(token)
}
}
endFile() {
if (this.current.parent) this.unclosedBlock()
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces
this.root.source.end = this.getPosition(this.tokenizer.position())
}
freeSemicolon(token) {
this.spaces += token[1]
if (this.current.nodes) {
let prev = this.current.nodes[this.current.nodes.length - 1]
if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces
this.spaces = ''
prev.source.end = this.getPosition(token[2])
prev.source.end.offset += prev.raws.ownSemicolon.length
}
}
}
// Helpers
getPosition(offset) {
let pos = this.input.fromOffset(offset)
return {
column: pos.col,
line: pos.line,
offset
}
}
init(node, offset) {
this.current.push(node)
node.source = {
input: this.input,
start: this.getPosition(offset)
}
node.raws.before = this.spaces
this.spaces = ''
if (node.type !== 'comment') this.semicolon = false
}
other(start) {
let end = false
let type = null
@@ -438,46 +165,260 @@ class Parser {
}
}
parse() {
let token
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken()
rule(tokens) {
tokens.pop()
switch (token[0]) {
case 'space':
this.spaces += token[1]
break
let node = new Rule()
this.init(node, tokens[0][2])
case ';':
this.freeSemicolon(token)
break
case '}':
this.end(token)
break
case 'comment':
this.comment(token)
break
case 'at-word':
this.atrule(token)
break
case '{':
this.emptyRule(token)
break
default:
this.other(token)
break
}
}
this.endFile()
node.raws.between = this.spacesAndCommentsFromEnd(tokens)
this.raw(node, 'selector', tokens)
this.current = node
}
precheckMissedSemicolon(/* tokens */) {
// Hook for Safe Parser
decl(tokens, customProperty) {
let node = new Declaration()
this.init(node, tokens[0][2])
let last = tokens[tokens.length - 1]
if (last[0] === ';') {
this.semicolon = true
tokens.pop()
}
node.source.end = this.getPosition(
last[3] || last[2] || findLastWithPosition(tokens)
)
while (tokens[0][0] !== 'word') {
if (tokens.length === 1) this.unknownWord(tokens)
node.raws.before += tokens.shift()[1]
}
node.source.start = this.getPosition(tokens[0][2])
node.prop = ''
while (tokens.length) {
let type = tokens[0][0]
if (type === ':' || type === 'space' || type === 'comment') {
break
}
node.prop += tokens.shift()[1]
}
node.raws.between = ''
let token
while (tokens.length) {
token = tokens.shift()
if (token[0] === ':') {
node.raws.between += token[1]
break
} else {
if (token[0] === 'word' && /\w/.test(token[1])) {
this.unknownWord([token])
}
node.raws.between += token[1]
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0]
node.prop = node.prop.slice(1)
}
let firstSpaces = []
let next
while (tokens.length) {
next = tokens[0][0]
if (next !== 'space' && next !== 'comment') break
firstSpaces.push(tokens.shift())
}
this.precheckMissedSemicolon(tokens)
for (let i = tokens.length - 1; i >= 0; i--) {
token = tokens[i]
if (token[1].toLowerCase() === '!important') {
node.important = true
let string = this.stringFrom(tokens, i)
string = this.spacesFromEnd(tokens) + string
if (string !== ' !important') node.raws.important = string
break
} else if (token[1].toLowerCase() === 'important') {
let cache = tokens.slice(0)
let str = ''
for (let j = i; j > 0; j--) {
let type = cache[j][0]
if (str.trim().indexOf('!') === 0 && type !== 'space') {
break
}
str = cache.pop()[1] + str
}
if (str.trim().indexOf('!') === 0) {
node.important = true
node.raws.important = str
tokens = cache
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break
}
}
let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment')
if (hasWord) {
node.raws.between += firstSpaces.map(i => i[1]).join('')
firstSpaces = []
}
this.raw(node, 'value', firstSpaces.concat(tokens), customProperty)
if (node.value.includes(':') && !customProperty) {
this.checkMissedSemicolon(tokens)
}
}
atrule(token) {
let node = new AtRule()
node.name = token[1].slice(1)
if (node.name === '') {
this.unnamedAtrule(node, token)
}
this.init(node, token[2])
let type
let prev
let shift
let last = false
let open = false
let params = []
let brackets = []
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken()
type = token[0]
if (type === '(' || type === '[') {
brackets.push(type === '(' ? ')' : ']')
} else if (type === '{' && brackets.length > 0) {
brackets.push('}')
} else if (type === brackets[brackets.length - 1]) {
brackets.pop()
}
if (brackets.length === 0) {
if (type === ';') {
node.source.end = this.getPosition(token[2])
this.semicolon = true
break
} else if (type === '{') {
open = true
break
} else if (type === '}') {
if (params.length > 0) {
shift = params.length - 1
prev = params[shift]
while (prev && prev[0] === 'space') {
prev = params[--shift]
}
if (prev) {
node.source.end = this.getPosition(prev[3] || prev[2])
}
}
this.end(token)
break
} else {
params.push(token)
}
} else {
params.push(token)
}
if (this.tokenizer.endOfFile()) {
last = true
break
}
}
node.raws.between = this.spacesAndCommentsFromEnd(params)
if (params.length) {
node.raws.afterName = this.spacesAndCommentsFromStart(params)
this.raw(node, 'params', params)
if (last) {
token = params[params.length - 1]
node.source.end = this.getPosition(token[3] || token[2])
this.spaces = node.raws.between
node.raws.between = ''
}
} else {
node.raws.afterName = ''
node.params = ''
}
if (open) {
node.nodes = []
this.current = node
}
}
end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon
}
this.semicolon = false
this.current.raws.after = (this.current.raws.after || '') + this.spaces
this.spaces = ''
if (this.current.parent) {
this.current.source.end = this.getPosition(token[2])
this.current = this.current.parent
} else {
this.unexpectedClose(token)
}
}
endFile() {
if (this.current.parent) this.unclosedBlock()
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces
}
freeSemicolon(token) {
this.spaces += token[1]
if (this.current.nodes) {
let prev = this.current.nodes[this.current.nodes.length - 1]
if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces
this.spaces = ''
}
}
}
// Helpers
getPosition(offset) {
let pos = this.input.fromOffset(offset)
return {
offset,
line: pos.line,
column: pos.col
}
}
init(node, offset) {
this.current.push(node)
node.source = {
start: this.getPosition(offset),
input: this.input
}
node.raws.before = this.spaces
this.spaces = ''
if (node.type !== 'comment') this.semicolon = false
}
raw(node, prop, tokens, customProperty) {
@@ -510,22 +451,11 @@ class Parser {
}
if (!clean) {
let raw = tokens.reduce((all, i) => all + i[1], '')
node.raws[prop] = { raw, value }
node.raws[prop] = { value, raw }
}
node[prop] = value
}
rule(tokens) {
tokens.pop()
let node = new Rule()
this.init(node, tokens[0][2])
node.raws.between = this.spacesAndCommentsFromEnd(tokens)
this.raw(node, 'selector', tokens)
this.current = node
}
spacesAndCommentsFromEnd(tokens) {
let lastTokenType
let spaces = ''
@@ -537,8 +467,6 @@ class Parser {
return spaces
}
// Errors
spacesAndCommentsFromStart(tokens) {
let next
let spaces = ''
@@ -570,11 +498,36 @@ class Parser {
return result
}
unclosedBlock() {
let pos = this.current.source.start
throw this.input.error('Unclosed block', pos.line, pos.column)
colon(tokens) {
let brackets = 0
let token, type, prev
for (let [i, element] of tokens.entries()) {
token = element
type = token[0]
if (type === '(') {
brackets += 1
}
if (type === ')') {
brackets -= 1
}
if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token)
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue
} else {
return i
}
}
prev = token
}
return false
}
// Errors
unclosedBracket(bracket) {
throw this.input.error(
'Unclosed bracket',
@@ -583,6 +536,14 @@ class Parser {
)
}
unknownWord(tokens) {
throw this.input.error(
'Unknown word',
{ offset: tokens[0][2] },
{ offset: tokens[0][2] + tokens[0][1].length }
)
}
unexpectedClose(token) {
throw this.input.error(
'Unexpected }',
@@ -591,11 +552,16 @@ class Parser {
)
}
unknownWord(tokens) {
unclosedBlock() {
let pos = this.current.source.start
throw this.input.error('Unclosed block', pos.line, pos.column)
}
doubleColon(token) {
throw this.input.error(
'Unknown word ' + tokens[0][1],
{ offset: tokens[0][2] },
{ offset: tokens[0][2] + tokens[0][1].length }
'Double colon',
{ offset: token[2] },
{ offset: token[2] + token[1].length }
)
}
@@ -606,6 +572,32 @@ class Parser {
{ offset: token[2] + token[1].length }
)
}
precheckMissedSemicolon(/* tokens */) {
// Hook for Safe Parser
}
checkMissedSemicolon(tokens) {
let colon = this.colon(tokens)
if (colon === false) return
let founded = 0
let token
for (let j = colon - 1; j >= 0; j--) {
token = tokens[j]
if (token[0] !== 'space') {
founded += 1
if (founded === 2) break
}
}
// If the token is a word, e.g. `!important`, `red` or any other valid property's value.
// Then we need to return the colon after that word token. [3] is the "end" colon of that word.
// And because we need it after that one we do +1 to get the next one.
throw this.input.error(
'Missed semicolon',
token[0] === 'word' ? token[3] + 1 : token[2]
)
}
}
module.exports = Parser

View File

@@ -1,69 +0,0 @@
export {
// Type-only exports
AcceptedPlugin,
AnyNode,
atRule,
AtRule,
AtRuleProps,
Builder,
ChildNode,
ChildProps,
comment,
Comment,
CommentProps,
Container,
ContainerProps,
CssSyntaxError,
decl,
Declaration,
DeclarationProps,
// postcss function / namespace
default,
document,
Document,
DocumentProps,
FilePosition,
fromJSON,
Helpers,
Input,
JSONHydrator,
// This is a class, but its not re-exported. Thats why its exported as type-only here.
type LazyResult,
list,
Message,
Node,
NodeErrorOptions,
NodeProps,
OldPlugin,
parse,
Parser,
// @ts-expect-error This value exists, but its untyped.
plugin,
Plugin,
PluginCreator,
Position,
Postcss,
ProcessOptions,
Processor,
Result,
root,
Root,
RootProps,
rule,
Rule,
RuleProps,
Source,
SourceMap,
SourceMapOptions,
Stringifier,
// Value exports from postcss.mjs
stringify,
Syntax,
TransformCallback,
Transformer,
Warning,
WarningOptions
} from './postcss.js'

591
node_modules/postcss/lib/postcss.d.ts generated vendored
View File

@@ -1,101 +1,87 @@
import { RawSourceMap, SourceMapGenerator } from 'source-map-js'
import { SourceMapGenerator, RawSourceMap } from 'source-map-js'
import AtRule, { AtRuleProps } from './at-rule.js'
import Comment, { CommentProps } from './comment.js'
import Container, { ContainerProps, NewChild } from './container.js'
import CssSyntaxError from './css-syntax-error.js'
import Declaration, { DeclarationProps } from './declaration.js'
import Document, { DocumentProps } from './document.js'
import Input, { FilePosition } from './input.js'
import LazyResult from './lazy-result.js'
import list from './list.js'
import Node, {
AnyNode,
Position,
Source,
ChildNode,
ChildProps,
NodeErrorOptions,
NodeProps,
Position,
Source
ChildProps,
AnyNode
} from './node.js'
import Processor from './processor.js'
import Declaration, { DeclarationProps } from './declaration.js'
import Container, { ContainerProps } from './container.js'
import Document, { DocumentProps } from './document.js'
import Warning, { WarningOptions } from './warning.js'
import Comment, { CommentProps } from './comment.js'
import AtRule, { AtRuleProps } from './at-rule.js'
import Input, { FilePosition } from './input.js'
import Result, { Message } from './result.js'
import Root, { RootProps } from './root.js'
import Rule, { RuleProps } from './rule.js'
import Warning, { WarningOptions } from './warning.js'
import CssSyntaxError from './css-syntax-error.js'
import list, { List } from './list.js'
import LazyResult from './lazy-result.js'
import Processor from './processor.js'
export {
NodeErrorOptions,
DeclarationProps,
CssSyntaxError,
ContainerProps,
WarningOptions,
DocumentProps,
FilePosition,
CommentProps,
AtRuleProps,
Declaration,
ChildProps,
LazyResult,
ChildNode,
NodeProps,
Processor,
RuleProps,
RootProps,
Container,
Position,
Document,
AnyNode,
Warning,
Message,
Comment,
Source,
AtRule,
Result,
Input,
Node,
list,
Rule,
Root
}
export type SourceMap = SourceMapGenerator & {
toJSON(): RawSourceMap
}
export type Helpers = { result: Result; postcss: Postcss } & Postcss
type DocumentProcessor = (
document: Document,
helper: postcss.Helpers
) => Promise<void> | void
type RootProcessor = (
root: Root,
helper: postcss.Helpers
helper: Helpers
) => Promise<void> | void
type RootProcessor = (root: Root, helper: Helpers) => Promise<void> | void
type DeclarationProcessor = (
decl: Declaration,
helper: postcss.Helpers
) => Promise<void> | void
type RuleProcessor = (
rule: Rule,
helper: postcss.Helpers
) => Promise<void> | void
type AtRuleProcessor = (
atRule: AtRule,
helper: postcss.Helpers
helper: Helpers
) => Promise<void> | void
type RuleProcessor = (rule: Rule, helper: Helpers) => Promise<void> | void
type AtRuleProcessor = (atRule: AtRule, helper: Helpers) => Promise<void> | void
type CommentProcessor = (
comment: Comment,
helper: postcss.Helpers
helper: Helpers
) => Promise<void> | void
interface Processors {
/**
* Will be called on all`AtRule` nodes.
*
* Will be called again on node or children changes.
*/
AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor
/**
* Will be called on all `AtRule` nodes, when all children will be processed.
*
* Will be called again on node or children changes.
*/
AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor
/**
* Will be called on all `Comment` nodes.
*
* Will be called again on node or children changes.
*/
Comment?: CommentProcessor
/**
* Will be called on all `Comment` nodes after listeners
* for `Comment` event.
*
* Will be called again on node or children changes.
*/
CommentExit?: CommentProcessor
/**
* Will be called on all `Declaration` nodes after listeners
* for `Declaration` event.
*
* Will be called again on node or children changes.
*/
Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor
/**
* Will be called on all `Declaration` nodes.
*
* Will be called again on node or children changes.
*/
DeclarationExit?:
| { [prop: string]: DeclarationProcessor }
| DeclarationProcessor
/**
* Will be called on `Document` node.
*
@@ -134,6 +120,23 @@ interface Processors {
*/
RootExit?: RootProcessor
/**
* Will be called on all `Declaration` nodes after listeners
* for `Declaration` event.
*
* Will be called again on node or children changes.
*/
Declaration?: DeclarationProcessor | { [prop: string]: DeclarationProcessor }
/**
* Will be called on all `Declaration` nodes.
*
* Will be called again on node or children changes.
*/
DeclarationExit?:
| DeclarationProcessor
| { [prop: string]: DeclarationProcessor }
/**
* Will be called on all `Rule` nodes.
*
@@ -147,218 +150,223 @@ interface Processors {
* Will be called again on node or children changes.
*/
RuleExit?: RuleProcessor
/**
* Will be called on all`AtRule` nodes.
*
* Will be called again on node or children changes.
*/
AtRule?: AtRuleProcessor | { [name: string]: AtRuleProcessor }
/**
* Will be called on all `AtRule` nodes, when all children will be processed.
*
* Will be called again on node or children changes.
*/
AtRuleExit?: AtRuleProcessor | { [name: string]: AtRuleProcessor }
/**
* Will be called on all `Comment` nodes.
*
* Will be called again on node or children changes.
*/
Comment?: CommentProcessor
/**
* Will be called on all `Comment` nodes after listeners
* for `Comment` event.
*
* Will be called again on node or children changes.
*/
CommentExit?: CommentProcessor
/**
* Will be called when all other listeners processed the document.
*
* This listener will not be called again.
*/
Exit?: RootProcessor
}
declare namespace postcss {
export {
AnyNode,
AtRule,
AtRuleProps,
ChildNode,
ChildProps,
Comment,
CommentProps,
Container,
ContainerProps,
CssSyntaxError,
Declaration,
DeclarationProps,
Document,
DocumentProps,
FilePosition,
Input,
LazyResult,
list,
Message,
NewChild,
Node,
NodeErrorOptions,
NodeProps,
Position,
Processor,
Result,
Root,
RootProps,
Rule,
RuleProps,
Source,
Warning,
WarningOptions
}
export interface Plugin extends Processors {
postcssPlugin: string
prepare?: (result: Result) => Processors
}
export type SourceMap = {
toJSON(): RawSourceMap
} & SourceMapGenerator
export interface PluginCreator<PluginOptions> {
(opts?: PluginOptions): Plugin | Processor
postcss: true
}
export type Helpers = { postcss: Postcss; result: Result } & Postcss
export interface Transformer extends TransformCallback {
postcssPlugin: string
postcssVersion: string
}
export interface Plugin extends Processors {
postcssPlugin: string
prepare?: (result: Result) => Processors
}
export interface TransformCallback {
(root: Root, result: Result): Promise<void> | void
}
export interface PluginCreator<PluginOptions> {
(opts?: PluginOptions): Plugin | Processor
postcss: true
}
export interface OldPlugin<T> extends Transformer {
(opts?: T): Transformer
postcss: Transformer
}
export interface Transformer extends TransformCallback {
postcssPlugin: string
postcssVersion: string
}
export type AcceptedPlugin =
| Plugin
| PluginCreator<any>
| OldPlugin<any>
| TransformCallback
| {
postcss: TransformCallback | Processor
}
| Processor
export interface TransformCallback {
(root: Root, result: Result): Promise<void> | void
}
export interface Parser<RootNode = Root | Document> {
(
css: string | { toString(): string },
opts?: Pick<ProcessOptions, 'map' | 'from'>
): RootNode
}
export interface OldPlugin<T> extends Transformer {
(opts?: T): Transformer
postcss: Transformer
}
export interface Builder {
(part: string, node?: AnyNode, type?: 'start' | 'end'): void
}
export type AcceptedPlugin =
| {
postcss: Processor | TransformCallback
}
| OldPlugin<any>
| Plugin
| PluginCreator<any>
| Processor
| TransformCallback
export interface Stringifier {
(node: AnyNode, builder: Builder): void
}
export interface Parser<RootNode = Document | Root> {
(
css: { toString(): string } | string,
opts?: Pick<ProcessOptions, 'document' | 'from' | 'map'>
): RootNode
}
export interface JSONHydrator {
(data: object[]): Node[]
(data: object): Node
}
export interface Builder {
(part: string, node?: AnyNode, type?: 'end' | 'start'): void
}
export interface Syntax {
/**
* Function to generate AST by string.
*/
parse?: Parser
export interface Stringifier {
(node: AnyNode, builder: Builder): void
}
/**
* Class to generate string by AST.
*/
stringify?: Stringifier
}
export interface JSONHydrator {
(data: object): Node
(data: object[]): Node[]
}
export interface SourceMapOptions {
/**
* Indicates that the source map should be embedded in the output CSS
* as a Base64-encoded comment. By default, it is `true`.
* But if all previous maps are external, not inline, PostCSS will not embed
* the map even if you do not set this option.
*
* If you have an inline source map, the result.map property will be empty,
* as the source map will be contained within the text of `result.css`.
*/
inline?: boolean
export interface Syntax<RootNode = Document | Root> {
/**
* Function to generate AST by string.
*/
parse?: Parser<RootNode>
/**
* Source map content from a previous processing step (e.g., Sass).
*
* PostCSS will try to read the previous source map
* automatically (based on comments within the source CSS), but you can use
* this option to identify it manually.
*
* If desired, you can omit the previous map with prev: `false`.
*/
prev?: string | boolean | object | ((file: string) => string)
/**
* Class to generate string by AST.
*/
stringify?: Stringifier
}
/**
* Indicates that PostCSS should set the origin content (e.g., Sass source)
* of the source map. By default, it is true. But if all previous maps do not
* contain sources content, PostCSS will also leave it out even if you
* do not set this option.
*/
sourcesContent?: boolean
export interface SourceMapOptions {
/**
* Use absolute path in generated source map.
*/
absolute?: boolean
/**
* Indicates that PostCSS should add annotation comments to the CSS.
* By default, PostCSS will always add a comment with a path
* to the source map. PostCSS will not add annotations to CSS files
* that do not contain any comments.
*
* By default, PostCSS presumes that you want to save the source map as
* `opts.to + '.map'` and will use this path in the annotation comment.
* A different path can be set by providing a string value for annotation.
*
* If you have set `inline: true`, annotation cannot be disabled.
*/
annotation?: string | boolean | ((file: string, root: Root) => string)
/**
* Indicates that PostCSS should add annotation comments to the CSS.
* By default, PostCSS will always add a comment with a path
* to the source map. PostCSS will not add annotations to CSS files
* that do not contain any comments.
*
* By default, PostCSS presumes that you want to save the source map as
* `opts.to + '.map'` and will use this path in the annotation comment.
* A different path can be set by providing a string value for annotation.
*
* If you have set `inline: true`, annotation cannot be disabled.
*/
annotation?: ((file: string, root: Root) => string) | boolean | string
/**
* Override `from` in maps sources.
*/
from?: string
/**
* Override `from` in maps sources.
*/
from?: string
/**
* Use absolute path in generated source map.
*/
absolute?: boolean
}
/**
* Indicates that the source map should be embedded in the output CSS
* as a Base64-encoded comment. By default, it is `true`.
* But if all previous maps are external, not inline, PostCSS will not embed
* the map even if you do not set this option.
*
* If you have an inline source map, the result.map property will be empty,
* as the source map will be contained within the text of `result.css`.
*/
inline?: boolean
export interface ProcessOptions {
/**
* The path of the CSS source file. You should always set `from`,
* because it is used in source map generation and syntax error messages.
*/
from?: string
/**
* Source map content from a previous processing step (e.g., Sass).
*
* PostCSS will try to read the previous source map
* automatically (based on comments within the source CSS), but you can use
* this option to identify it manually.
*
* If desired, you can omit the previous map with prev: `false`.
*/
prev?: ((file: string) => string) | boolean | object | string
/**
* The path where you'll put the output CSS file. You should always set `to`
* to generate correct source maps.
*/
to?: string
/**
* Indicates that PostCSS should set the origin content (e.g., Sass source)
* of the source map. By default, it is true. But if all previous maps do not
* contain sources content, PostCSS will also leave it out even if you
* do not set this option.
*/
sourcesContent?: boolean
}
/**
* Function to generate AST by string.
*/
parser?: Syntax | Parser
export interface ProcessOptions<RootNode = Document | Root> {
/**
* Input file if it is not simple CSS file, but HTML with <style> or JS with CSS-in-JS blocks.
*/
document?: string
/**
* Class to generate string by AST.
*/
stringifier?: Syntax | Stringifier
/**
* The path of the CSS source file. You should always set `from`,
* because it is used in source map generation and syntax error messages.
*/
from?: string | undefined
/**
* Object with parse and stringify.
*/
syntax?: Syntax
/**
* Source map options
*/
map?: boolean | SourceMapOptions
/**
* Source map options
*/
map?: SourceMapOptions | boolean
}
/**
* Function to generate AST by string.
*/
parser?: Parser<RootNode> | Syntax<RootNode>
/**
* Class to generate string by AST.
*/
stringifier?: Stringifier | Syntax<RootNode>
/**
* Object with parse and stringify.
*/
syntax?: Syntax<RootNode>
/**
* The path where you'll put the output CSS file. You should always set `to`
* to generate correct source maps.
*/
to?: string
}
export type Postcss = typeof postcss
export interface Postcss {
/**
* Create a new `Processor` instance that will apply `plugins`
* as CSS processors.
*
* ```js
* let postcss = require('postcss')
*
* postcss(plugins).process(css, { from, to }).then(result => {
* console.log(result.css)
* })
* ```
*
* @param plugins PostCSS plugins.
* @return Processor to process multiple CSS.
*/
(plugins?: AcceptedPlugin[]): Processor
(...plugins: AcceptedPlugin[]): Processor
/**
* Default function to convert a node tree into a CSS string.
*/
export let stringify: Stringifier
stringify: Stringifier
/**
* Parses source css and returns a new `Root` or `Document` node,
@@ -371,7 +379,7 @@ declare namespace postcss {
* root1.append(root2).toResult().css
* ```
*/
export let parse: Parser<Root>
parse: Parser<Root>
/**
* Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes.
@@ -382,7 +390,12 @@ declare namespace postcss {
* const root2 = postcss.fromJSON(json)
* ```
*/
export let fromJSON: JSONHydrator
fromJSON: JSONHydrator
/**
* Contains the `list` module.
*/
list: List
/**
* Creates a new `Comment` node.
@@ -390,7 +403,7 @@ declare namespace postcss {
* @param defaults Properties for the new node.
* @return New comment node
*/
export function comment(defaults?: CommentProps): Comment
comment(defaults?: CommentProps): Comment
/**
* Creates a new `AtRule` node.
@@ -398,7 +411,7 @@ declare namespace postcss {
* @param defaults Properties for the new node.
* @return New at-rule node.
*/
export function atRule(defaults?: AtRuleProps): AtRule
atRule(defaults?: AtRuleProps): AtRule
/**
* Creates a new `Declaration` node.
@@ -406,7 +419,7 @@ declare namespace postcss {
* @param defaults Properties for the new node.
* @return New declaration node.
*/
export function decl(defaults?: DeclarationProps): Declaration
decl(defaults?: DeclarationProps): Declaration
/**
* Creates a new `Rule` node.
@@ -414,7 +427,7 @@ declare namespace postcss {
* @param default Properties for the new node.
* @return New rule node.
*/
export function rule(defaults?: RuleProps): Rule
rule(defaults?: RuleProps): Rule
/**
* Creates a new `Root` node.
@@ -422,7 +435,7 @@ declare namespace postcss {
* @param defaults Properties for the new node.
* @return New root node.
*/
export function root(defaults?: RootProps): Root
root(defaults?: RootProps): Root
/**
* Creates a new `Document` node.
@@ -430,29 +443,31 @@ declare namespace postcss {
* @param defaults Properties for the new node.
* @return New document node.
*/
export function document(defaults?: DocumentProps): Document
document(defaults?: DocumentProps): Document
export { postcss as default }
CssSyntaxError: typeof CssSyntaxError
Declaration: typeof Declaration
Container: typeof Container
Comment: typeof Comment
Warning: typeof Warning
AtRule: typeof AtRule
Result: typeof Result
Input: typeof Input
Rule: typeof Rule
Root: typeof Root
Node: typeof Node
}
/**
* Create a new `Processor` instance that will apply `plugins`
* as CSS processors.
*
* ```js
* let postcss = require('postcss')
*
* postcss(plugins).process(css, { from, to }).then(result => {
* console.log(result.css)
* })
* ```
*
* @param plugins PostCSS plugins.
* @return Processor to process multiple CSS.
*/
declare function postcss(
plugins?: readonly postcss.AcceptedPlugin[]
): Processor
declare function postcss(...plugins: postcss.AcceptedPlugin[]): Processor
export const stringify: Stringifier
export const parse: Parser<Root>
export const fromJSON: JSONHydrator
export = postcss
export const comment: Postcss['comment']
export const atRule: Postcss['atRule']
export const decl: Postcss['decl']
export const rule: Postcss['rule']
export const root: Postcss['root']
declare const postcss: Postcss
export default postcss

24
node_modules/postcss/lib/postcss.js generated vendored
View File

@@ -1,23 +1,23 @@
'use strict'
let AtRule = require('./at-rule')
let Comment = require('./comment')
let Container = require('./container')
let CssSyntaxError = require('./css-syntax-error')
let Declaration = require('./declaration')
let Document = require('./document')
let fromJSON = require('./fromJSON')
let Input = require('./input')
let LazyResult = require('./lazy-result')
let list = require('./list')
let Node = require('./node')
let parse = require('./parse')
let Container = require('./container')
let Processor = require('./processor')
let Result = require('./result.js')
let Root = require('./root')
let Rule = require('./rule')
let stringify = require('./stringify')
let fromJSON = require('./fromJSON')
let Document = require('./document')
let Warning = require('./warning')
let Comment = require('./comment')
let AtRule = require('./at-rule')
let Result = require('./result.js')
let Input = require('./input')
let parse = require('./parse')
let list = require('./list')
let Rule = require('./rule')
let Root = require('./root')
let Node = require('./node')
function postcss(...plugins) {
if (plugins.length === 1 && Array.isArray(plugins[0])) {

View File

@@ -2,11 +2,6 @@ import { SourceMapConsumer } from 'source-map-js'
import { ProcessOptions } from './postcss.js'
declare namespace PreviousMap {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { PreviousMap_ as default }
}
/**
* Source map information from input CSS.
* For example, source map after Sass compiler.
@@ -19,38 +14,38 @@ declare namespace PreviousMap {
* root.input.map //=> PreviousMap
* ```
*/
declare class PreviousMap_ {
export default class PreviousMap {
/**
* Was source map inlined by data-uri to input CSS.
*/
inline: boolean
/**
* `sourceMappingURL` content.
*/
annotation?: string
/**
* Source map file content.
*/
text?: string
/**
* The directory with source map file, if source map is in separated file.
*/
root?: string
/**
* The CSS source identifier. Contains `Input#file` if the user
* set the `from` option, or `Input#id` if they did not.
*/
file?: string
/**
* Was source map inlined by data-uri to input CSS.
*/
inline: boolean
/**
* Path to source map file.
*/
mapFile?: string
/**
* The directory with source map file, if source map is in separated file.
*/
root?: string
/**
* Source map file content.
*/
text?: string
/**
* @param css Input CSS source.
* @param opts Process options.
@@ -75,7 +70,3 @@ declare class PreviousMap_ {
*/
withContent(): boolean
}
declare class PreviousMap extends PreviousMap_ {}
export = PreviousMap

View File

@@ -1,8 +1,8 @@
'use strict'
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
let { existsSync, readFileSync } = require('fs')
let { dirname, join } = require('path')
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
function fromBase64(str) {
if (Buffer) {
@@ -35,41 +35,24 @@ class PreviousMap {
return this.consumerCache
}
decodeInline(text) {
let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/
let baseUri = /^data:application\/json;base64,/
let charsetUri = /^data:application\/json;charset=utf-?8,/
let uri = /^data:application\/json,/
withContent() {
return !!(
this.consumer().sourcesContent &&
this.consumer().sourcesContent.length > 0
)
}
let uriMatch = text.match(charsetUri) || text.match(uri)
if (uriMatch) {
return decodeURIComponent(text.substr(uriMatch[0].length))
}
let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri)
if (baseUriMatch) {
return fromBase64(text.substr(baseUriMatch[0].length))
}
let encoding = text.match(/data:application\/json;([^,]+),/)[1]
throw new Error('Unsupported source map encoding ' + encoding)
startWith(string, start) {
if (!string) return false
return string.substr(0, start.length) === start
}
getAnnotationURL(sourceMapString) {
return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
}
isMap(map) {
if (typeof map !== 'object') return false
return (
typeof map.mappings === 'string' ||
typeof map._mappings === 'string' ||
Array.isArray(map.sections)
)
}
loadAnnotation(css) {
let comments = css.match(/\/\*\s*# sourceMappingURL=/g)
let comments = css.match(/\/\*\s*# sourceMappingURL=/gm)
if (!comments) return
// sourceMappingURLs from comments, strings, etc.
@@ -82,6 +65,24 @@ class PreviousMap {
}
}
decodeInline(text) {
let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/
let baseUri = /^data:application\/json;base64,/
let charsetUri = /^data:application\/json;charset=utf-?8,/
let uri = /^data:application\/json,/
if (charsetUri.test(text) || uri.test(text)) {
return decodeURIComponent(text.substr(RegExp.lastMatch.length))
}
if (baseCharsetUri.test(text) || baseUri.test(text)) {
return fromBase64(text.substr(RegExp.lastMatch.length))
}
let encoding = text.match(/data:application\/json;([^,]+),/)[1]
throw new Error('Unsupported source map encoding ' + encoding)
}
loadFile(path) {
this.root = dirname(path)
if (existsSync(path)) {
@@ -127,15 +128,12 @@ class PreviousMap {
}
}
startWith(string, start) {
if (!string) return false
return string.substr(0, start.length) === start
}
withContent() {
return !!(
this.consumer().sourcesContent &&
this.consumer().sourcesContent.length > 0
isMap(map) {
if (typeof map !== 'object') return false
return (
typeof map.mappings === 'string' ||
typeof map._mappings === 'string' ||
Array.isArray(map.sections)
)
}
}

View File

@@ -1,20 +1,14 @@
import Document from './document.js'
import LazyResult from './lazy-result.js'
import NoWorkResult from './no-work-result.js'
import {
AcceptedPlugin,
Plugin,
ProcessOptions,
TransformCallback,
Transformer
Transformer,
TransformCallback
} from './postcss.js'
import LazyResult from './lazy-result.js'
import Result from './result.js'
import Root from './root.js'
declare namespace Processor {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Processor_ as default }
}
import NoWorkResult from './no-work-result.js'
/**
* Contains plugins to process CSS. Create one `Processor` instance,
@@ -26,17 +20,7 @@ declare namespace Processor {
* processor.process(css2).then(result => console.log(result.css))
* ```
*/
declare class Processor_ {
/**
* Plugins added to this processor.
*
* ```js
* const processor = postcss([autoprefixer, postcssNested])
* processor.plugins.length //=> 2
* ```
*/
plugins: (Plugin | TransformCallback | Transformer)[]
export default class Processor {
/**
* Current PostCSS version.
*
@@ -49,36 +33,19 @@ declare class Processor_ {
version: string
/**
* @param plugins PostCSS plugins
*/
constructor(plugins?: readonly AcceptedPlugin[])
/**
* Parses source CSS and returns a `LazyResult` Promise proxy.
* Because some plugins can be asynchronous it doesnt make
* any transformations. Transformations will be applied
* in the `LazyResult` methods.
* Plugins added to this processor.
*
* ```js
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css)
* })
* const processor = postcss([autoprefixer, postcssNested])
* processor.plugins.length //=> 2
* ```
*
* @param css String with input CSS or any object with a `toString()` method,
* like a Buffer. Optionally, send a `Result` instance
* and the processor will take the `Root` from it.
* @param opts Options.
* @return Promise proxy.
*/
process(
css: { toString(): string } | LazyResult | Result | Root | string
): LazyResult | NoWorkResult
process<RootNode extends Document | Root = Root>(
css: { toString(): string } | LazyResult | Result | Root | string,
options: ProcessOptions<RootNode>
): LazyResult<RootNode>
plugins: (Plugin | Transformer | TransformCallback)[]
/**
* @param plugins PostCSS plugins
*/
constructor(plugins?: AcceptedPlugin[])
/**
* Adds a plugin to be used as a CSS processor.
@@ -87,7 +54,7 @@ declare class Processor_ {
* * A plugin in `Plugin` format.
* * A plugin creator function with `pluginCreator.postcss = true`.
* PostCSS will call this function without argument to get plugin.
* * A function. PostCSS will pass the function a {@link Root}
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current `Result` instance
* as the second.
* * Another `Processor` instance. PostCSS will copy plugins
@@ -108,8 +75,28 @@ declare class Processor_ {
* @return Current processor to make methods chain.
*/
use(plugin: AcceptedPlugin): this
/**
* Parses source CSS and returns a `LazyResult` Promise proxy.
* Because some plugins can be asynchronous it doesnt make
* any transformations. Transformations will be applied
* in the `LazyResult` methods.
*
* ```js
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css)
* })
* ```
*
* @param css String with input CSS or any object with a `toString()` method,
* like a Buffer. Optionally, senda `Result` instance
* and the processor will take the `Root` from it.
* @param opts Options.
* @return Promise proxy.
*/
process(
css: string | { toString(): string } | Result | LazyResult | Root,
options?: ProcessOptions
): LazyResult | NoWorkResult
}
declare class Processor extends Processor_ {}
export = Processor

View File

@@ -1,16 +1,34 @@
'use strict'
let Document = require('./document')
let LazyResult = require('./lazy-result')
let NoWorkResult = require('./no-work-result')
let LazyResult = require('./lazy-result')
let Document = require('./document')
let Root = require('./root')
class Processor {
constructor(plugins = []) {
this.version = '8.5.6'
this.version = '8.4.21'
this.plugins = this.normalize(plugins)
}
use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]))
return this
}
process(css, opts = {}) {
if (
this.plugins.length === 0 &&
typeof opts.parser === 'undefined' &&
typeof opts.stringifier === 'undefined' &&
typeof opts.syntax === 'undefined'
) {
return new NoWorkResult(this, css, opts)
} else {
return new LazyResult(this, css, opts)
}
}
normalize(plugins) {
let normalized = []
for (let i of plugins) {
@@ -40,24 +58,6 @@ class Processor {
}
return normalized
}
process(css, opts = {}) {
if (
!this.plugins.length &&
!opts.parser &&
!opts.stringifier &&
!opts.syntax
) {
return new NoWorkResult(this, css, opts)
} else {
return new LazyResult(this, css, opts)
}
}
use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]))
return this
}
}
module.exports = Processor

147
node_modules/postcss/lib/result.d.ts generated vendored
View File

@@ -1,46 +1,41 @@
import {
Document,
Node,
Plugin,
ProcessOptions,
Root,
Plugin,
SourceMap,
TransformCallback,
Root,
Document,
Node,
Warning,
WarningOptions
} from './postcss.js'
import Processor from './processor.js'
declare namespace Result {
export interface Message {
[others: string]: any
export interface Message {
/**
* Message type.
*/
type: string
/**
* Source PostCSS plugin name.
*/
plugin?: string
/**
* Source PostCSS plugin name.
*/
plugin?: string
/**
* Message type.
*/
type: string
}
[others: string]: any
}
export interface ResultOptions extends ProcessOptions {
/**
* The CSS node that was the source of the warning.
*/
node?: Node
export interface ResultOptions extends ProcessOptions {
/**
* The CSS node that was the source of the warning.
*/
node?: Node
/**
* Name of plugin that created this warning. `Result#warn` will fill it
* automatically with `Plugin#postcssPlugin` value.
*/
plugin?: string
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Result_ as default }
/**
* Name of plugin that created this warning. `Result#warn` will fill it
* automatically with `Plugin#postcssPlugin` value.
*/
plugin?: string
}
/**
@@ -59,36 +54,19 @@ declare namespace Result {
* const result2 = postcss.parse(css).toResult()
* ```
*/
declare class Result_<RootNode = Document | Root> {
export default class Result {
/**
* A CSS string representing of `Result#root`.
* The Processor instance used for this transformation.
*
* ```js
* postcss.parse('a{}').toResult().css //=> "a{}"
* for (const plugin of result.processor.plugins) {
* if (plugin.postcssPlugin === 'postcss-bad') {
* throw 'postcss-good is incompatible with postcss-bad'
* }
* })
* ```
*/
css: string
/**
* Last runned PostCSS plugin.
*/
lastPlugin: Plugin | TransformCallback
/**
* An instance of `SourceMapGenerator` class from the `source-map` library,
* representing changes to the `Result#root` instance.
*
* ```js
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
* ```
*
* ```js
* if (result.map) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString())
* }
* ```
*/
map: SourceMap
processor: Processor
/**
* Contains messages from plugins (e.g., warnings or custom messages).
@@ -108,7 +86,16 @@ declare class Result_<RootNode = Document | Root> {
* }
* ```
*/
messages: Result.Message[]
messages: Message[]
/**
* Root node after all transformations.
*
* ```js
* root.toResult().root === root
* ```
*/
root: Root | Document
/**
* Options from the `Processor#process` or `Root#toResult` call
@@ -118,29 +105,44 @@ declare class Result_<RootNode = Document | Root> {
* root.toResult(opts).opts === opts
* ```
*/
opts: Result.ResultOptions
opts: ResultOptions
/**
* The Processor instance used for this transformation.
* A CSS string representing of `Result#root`.
*
* ```js
* for (const plugin of result.processor.plugins) {
* if (plugin.postcssPlugin === 'postcss-bad') {
* throw 'postcss-good is incompatible with postcss-bad'
* }
* })
* postcss.parse('a{}').toResult().css //=> "a{}"
* ```
*/
processor: Processor
css: string
/**
* Root node after all transformations.
* An instance of `SourceMapGenerator` class from the `source-map` library,
* representing changes to the `Result#root` instance.
*
* ```js
* root.toResult().root === root
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
* ```
*
* ```js
* if (result.map) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString())
* }
* ```
*/
root: RootNode
map: SourceMap
/**
* Last runned PostCSS plugin.
*/
lastPlugin: Plugin | TransformCallback
/**
* @param processor Processor used for this transformation.
* @param root Root node after all transformations.
* @param opts Options from the `Processor#process` or `Root#toResult`.
*/
constructor(processor: Processor, root: Root | Document, opts: ResultOptions)
/**
* An alias for the `Result#css` property.
@@ -152,13 +154,6 @@ declare class Result_<RootNode = Document | Root> {
*/
get content(): string
/**
* @param processor Processor used for this transformation.
* @param root Root node after all transformations.
* @param opts Options from the `Processor#process` or `Root#toResult`.
*/
constructor(processor: Processor, root: RootNode, opts: Result.ResultOptions)
/**
* Returns for `Result#css` content.
*
@@ -199,7 +194,3 @@ declare class Result_<RootNode = Document | Root> {
*/
warnings(): Warning[]
}
declare class Result<RootNode = Document | Root> extends Result_<RootNode> {}
export = Result

10
node_modules/postcss/lib/result.js generated vendored
View File

@@ -3,16 +3,12 @@
let Warning = require('./warning')
class Result {
get content() {
return this.css
}
constructor(processor, root, opts) {
this.processor = processor
this.messages = []
this.root = root
this.opts = opts
this.css = ''
this.css = undefined
this.map = undefined
}
@@ -36,6 +32,10 @@ class Result {
warnings() {
return this.messages.filter(i => i.type === 'warning')
}
get content() {
return this.css
}
}
module.exports = Result

88
node_modules/postcss/lib/root.d.ts generated vendored
View File

@@ -3,45 +3,40 @@ import Document from './document.js'
import { ProcessOptions } from './postcss.js'
import Result from './result.js'
declare namespace Root {
export interface RootRaws extends Record<string, any> {
/**
* The space symbols after the last child to the end of file.
*/
after?: string
interface RootRaws extends Record<string, any> {
/**
* The space symbols after the last child to the end of file.
*/
after?: string
/**
* Non-CSS code after `Root`, when `Root` is inside `Document`.
*
* **Experimental:** some aspects of this node could change within minor
* or patch version releases.
*/
codeAfter?: string
/**
* Non-CSS code before `Root`, when `Root` is inside `Document`.
*
* **Experimental:** some aspects of this node could change within minor
* or patch version releases.
*/
codeBefore?: string
/**
* Non-CSS code before `Root`, when `Root` is inside `Document`.
*
* **Experimental:** some aspects of this node could change within minor
* or patch version releases.
*/
codeBefore?: string
/**
* Non-CSS code after `Root`, when `Root` is inside `Document`.
*
* **Experimental:** some aspects of this node could change within minor
* or patch version releases.
*/
codeAfter?: string
/**
* Is the last child has an (optional) semicolon.
*/
semicolon?: boolean
}
/**
* Is the last child has an (optional) semicolon.
*/
semicolon?: boolean
}
export interface RootProps extends ContainerProps {
/**
* Information used to generate byte-to-byte equal node string
* as it was in the origin input.
* */
raws?: RootRaws
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Root_ as default }
export interface RootProps extends ContainerProps {
/**
* Information used to generate byte-to-byte equal node string
* as it was in the origin input.
* */
raws?: RootRaws
}
/**
@@ -53,18 +48,10 @@ declare namespace Root {
* root.nodes.length //=> 2
* ```
*/
declare class Root_ extends Container {
nodes: NonNullable<Container['nodes']>
parent: Document | undefined
raws: Root.RootRaws
export default class Root extends Container {
type: 'root'
constructor(defaults?: Root.RootProps)
assign(overrides: object | Root.RootProps): this
clone(overrides?: Partial<Root.RootProps>): this
cloneAfter(overrides?: Partial<Root.RootProps>): this
cloneBefore(overrides?: Partial<Root.RootProps>): this
parent: Document | undefined
raws: RootRaws
/**
* Returns a `Result` instance representing the roots CSS.
@@ -76,12 +63,11 @@ declare class Root_ extends Container {
* const result = root1.toResult({ to: 'all.css', map: true })
* ```
*
* @param options Options.
* @param opts Options.
* @return Result with current roots CSS.
*/
toResult(options?: ProcessOptions): Result
constructor(defaults?: RootProps)
assign(overrides: object | RootProps): this
}
declare class Root extends Root_ {}
export = Root

20
node_modules/postcss/lib/root.js generated vendored
View File

@@ -11,6 +11,16 @@ class Root extends Container {
if (!this.nodes) this.nodes = []
}
removeChild(child, ignore) {
let index = this.index(child)
if (!ignore && index === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index].raws.before
}
return super.removeChild(child)
}
normalize(child, sample, type) {
let nodes = super.normalize(child)
@@ -31,16 +41,6 @@ class Root extends Container {
return nodes
}
removeChild(child, ignore) {
let index = this.index(child)
if (!ignore && index === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index].raws.before
}
return super.removeChild(child)
}
toResult(opts = {}) {
let lazy = new LazyResult(new Processor(), this, opts)
return lazy.stringify()

118
node_modules/postcss/lib/rule.d.ts generated vendored
View File

@@ -1,63 +1,48 @@
import Container, {
ContainerProps,
ContainerWithChildren
} from './container.js'
import Container, { ContainerProps } from './container.js'
declare namespace Rule {
export interface RuleRaws extends Record<string, unknown> {
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
interface RuleRaws extends Record<string, unknown> {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
/**
* The symbols between the selector and `{` for rules.
*/
between?: string
/**
* The symbols between the selector and `{` for rules.
*/
between?: string
/**
* Contains the text of the semicolon after this rule.
*/
ownSemicolon?: string
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
/**
* The rules selector with comments.
*/
selector?: {
raw: string
value: string
}
/**
* Contains `true` if there is semicolon after rule.
*/
ownSemicolon?: string
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
/**
* The rules selector with comments.
*/
selector?: {
value: string
raw: string
}
}
export type RuleProps = {
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: RuleRaws
} & (
| {
/** Selector or selectors of the rule. */
selector: string
selectors?: never
}
| {
selector?: never
/** Selectors of the rule represented as an array of strings. */
selectors: readonly string[]
}
) & ContainerProps
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Rule_ as default }
export interface RuleProps extends ContainerProps {
/** Selector or selectors of the rule. */
selector?: string
/** Selectors of the rule represented as an array of strings. */
selectors?: string[]
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: RuleRaws
}
/**
@@ -78,11 +63,11 @@ declare namespace Rule {
* rule.toString() //=> 'a{}'
* ```
*/
declare class Rule_ extends Container {
nodes: NonNullable<Container['nodes']>
parent: ContainerWithChildren | undefined
raws: Rule.RuleRaws
export default class Rule extends Container {
type: 'rule'
parent: Container | undefined
raws: RuleRaws
/**
* The rules full selector represented as a string.
*
@@ -92,9 +77,8 @@ declare class Rule_ extends Container {
* rule.selector //=> 'a, b'
* ```
*/
get selector(): string
selector: string
set selector(value: string)
/**
* An array containing the rules individual selectors.
* Groups of selectors are split at commas.
@@ -110,17 +94,11 @@ declare class Rule_ extends Container {
* rule.selector //=> 'a, strong'
* ```
*/
get selectors(): string[]
selectors: string[]
set selectors(values: string[])
constructor(defaults?: Rule.RuleProps)
assign(overrides: object | Rule.RuleProps): this
clone(overrides?: Partial<Rule.RuleProps>): this
cloneAfter(overrides?: Partial<Rule.RuleProps>): this
cloneBefore(overrides?: Partial<Rule.RuleProps>): this
constructor(defaults?: RuleProps)
assign(overrides: object | RuleProps): this
clone(overrides?: Partial<RuleProps>): this
cloneBefore(overrides?: Partial<RuleProps>): this
cloneAfter(overrides?: Partial<RuleProps>): this
}
declare class Rule extends Rule_ {}
export = Rule

12
node_modules/postcss/lib/rule.js generated vendored
View File

@@ -4,6 +4,12 @@ let Container = require('./container')
let list = require('./list')
class Rule extends Container {
constructor(defaults) {
super(defaults)
this.type = 'rule'
if (!this.nodes) this.nodes = []
}
get selectors() {
return list.comma(this.selector)
}
@@ -13,12 +19,6 @@ class Rule extends Container {
let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen')
this.selector = values.join(sep)
}
constructor(defaults) {
super(defaults)
this.type = 'rule'
if (!this.nodes) this.nodes = []
}
}
module.exports = Rule

View File

@@ -1,46 +1,37 @@
import {
AnyNode,
AtRule,
Builder,
Comment,
Container,
Declaration,
Document,
Root,
Rule
Comment,
Declaration,
Builder,
AnyNode,
Rule,
AtRule,
Container
} from './postcss.js'
declare namespace Stringifier {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Stringifier_ as default }
}
declare class Stringifier_ {
export default class Stringifier {
builder: Builder
constructor(builder: Builder)
atrule(node: AtRule, semicolon?: boolean): void
beforeAfter(node: AnyNode, detect: 'after' | 'before'): string
block(node: AnyNode, start: string): void
body(node: Container): void
stringify(node: AnyNode, semicolon?: boolean): void
document(node: Document): void
root(node: Root): void
comment(node: Comment): void
decl(node: Declaration, semicolon?: boolean): void
document(node: Document): void
raw(node: AnyNode, own: null | string, detect?: string): boolean | string
rawBeforeClose(root: Root): string | undefined
rawBeforeComment(root: Root, node: Comment): string | undefined
rawBeforeDecl(root: Root, node: Declaration): string | undefined
rawBeforeOpen(root: Root): string | undefined
rawBeforeRule(root: Root): string | undefined
rawColon(root: Root): string | undefined
rule(node: Rule): void
atrule(node: AtRule, semicolon?: boolean): void
body(node: Container): void
block(node: AnyNode, start: string): void
raw(node: AnyNode, own: string | null, detect?: string): string
rawSemicolon(root: Root): boolean | undefined
rawEmptyBody(root: Root): string | undefined
rawIndent(root: Root): string | undefined
rawSemicolon(root: Root): boolean | undefined
rawValue(node: AnyNode, prop: string): number | string
root(node: Root): void
rule(node: Rule): void
stringify(node: AnyNode, semicolon?: boolean): void
rawBeforeComment(root: Root, node: Comment): string | undefined
rawBeforeDecl(root: Root, node: Declaration): string | undefined
rawBeforeRule(root: Root): string | undefined
rawBeforeClose(root: Root): string | undefined
rawBeforeOpen(root: Root): string | undefined
rawColon(root: Root): string | undefined
beforeAfter(node: AnyNode, detect: 'before' | 'after'): string
rawValue(node: AnyNode, prop: string): string
}
declare class Stringifier extends Stringifier_ {}
export = Stringifier

View File

@@ -1,17 +1,17 @@
'use strict'
const DEFAULT_RAW = {
after: '\n',
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
beforeDecl: '\n',
beforeOpen: ' ',
beforeRule: '\n',
colon: ': ',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' ',
emptyBody: '',
indent: ' ',
semicolon: false
}
@@ -24,83 +24,27 @@ class Stringifier {
this.builder = builder
}
atrule(node, semicolon) {
let name = '@' + node.name
let params = node.params ? this.rawValue(node, 'params') : ''
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName
} else if (params) {
name += ' '
}
if (node.nodes) {
this.block(node, name + params)
} else {
let end = (node.raws.between || '') + (semicolon ? ';' : '')
this.builder(name + params + end, node)
stringify(node, semicolon) {
/* c8 ignore start */
if (!this[node.type]) {
throw new Error(
'Unknown AST node type ' +
node.type +
'. ' +
'Maybe you need to change PostCSS stringifier.'
)
}
/* c8 ignore stop */
this[node.type](node, semicolon)
}
beforeAfter(node, detect) {
let value
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl')
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment')
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule')
} else {
value = this.raw(node, null, 'beforeClose')
}
let buf = node.parent
let depth = 0
while (buf && buf.type !== 'root') {
depth += 1
buf = buf.parent
}
if (value.includes('\n')) {
let indent = this.raw(node, null, 'indent')
if (indent.length) {
for (let step = 0; step < depth; step++) value += indent
}
}
return value
document(node) {
this.body(node)
}
block(node, start) {
let between = this.raw(node, 'between', 'beforeOpen')
this.builder(start + between + '{', node, 'start')
let after
if (node.nodes && node.nodes.length) {
this.body(node)
after = this.raw(node, 'after')
} else {
after = this.raw(node, 'after', 'emptyBody')
}
if (after) this.builder(after)
this.builder('}', node, 'end')
}
body(node) {
let last = node.nodes.length - 1
while (last > 0) {
if (node.nodes[last].type !== 'comment') break
last -= 1
}
let semicolon = this.raw(node, 'semicolon')
for (let i = 0; i < node.nodes.length; i++) {
let child = node.nodes[i]
let before = this.raw(child, 'before')
if (before) this.builder(before)
this.stringify(child, last !== i || semicolon)
}
root(node) {
this.body(node)
if (node.raws.after) this.builder(node.raws.after)
}
comment(node) {
@@ -121,8 +65,61 @@ class Stringifier {
this.builder(string, node)
}
document(node) {
this.body(node)
rule(node) {
this.block(node, this.rawValue(node, 'selector'))
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end')
}
}
atrule(node, semicolon) {
let name = '@' + node.name
let params = node.params ? this.rawValue(node, 'params') : ''
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName
} else if (params) {
name += ' '
}
if (node.nodes) {
this.block(node, name + params)
} else {
let end = (node.raws.between || '') + (semicolon ? ';' : '')
this.builder(name + params + end, node)
}
}
body(node) {
let last = node.nodes.length - 1
while (last > 0) {
if (node.nodes[last].type !== 'comment') break
last -= 1
}
let semicolon = this.raw(node, 'semicolon')
for (let i = 0; i < node.nodes.length; i++) {
let child = node.nodes[i]
let before = this.raw(child, 'before')
if (before) this.builder(before)
this.stringify(child, last !== i || semicolon)
}
}
block(node, start) {
let between = this.raw(node, 'between', 'beforeOpen')
this.builder(start + between + '{', node, 'start')
let after
if (node.nodes && node.nodes.length) {
this.body(node)
after = this.raw(node, 'after')
} else {
after = this.raw(node, 'after', 'emptyBody')
}
if (after) this.builder(after)
this.builder('}', node, 'end')
}
raw(node, own, detect) {
@@ -179,20 +176,42 @@ class Stringifier {
return value
}
rawBeforeClose(root) {
rawSemicolon(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '')
}
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon
if (typeof value !== 'undefined') return false
}
})
return value
}
rawEmptyBody(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after
if (typeof value !== 'undefined') return false
}
})
return value
}
rawIndent(root) {
if (root.raws.indent) return root.raws.indent
let value
root.walk(i => {
let p = i.parent
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
let parts = i.raws.before.split('\n')
value = parts[parts.length - 1]
value = value.replace(/\S/g, '')
return false
}
}
})
if (value) value = value.replace(/\S/g, '')
return value
}
@@ -234,17 +253,6 @@ class Stringifier {
return value
}
rawBeforeOpen(root) {
let value
root.walk(i => {
if (i.type !== 'decl') {
value = i.raws.between
if (typeof value !== 'undefined') return false
}
})
return value
}
rawBeforeRule(root) {
let value
root.walk(i => {
@@ -262,6 +270,34 @@ class Stringifier {
return value
}
rawBeforeClose(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '')
}
return false
}
}
})
if (value) value = value.replace(/\S/g, '')
return value
}
rawBeforeOpen(root) {
let value
root.walk(i => {
if (i.type !== 'decl') {
value = i.raws.between
if (typeof value !== 'undefined') return false
}
})
return value
}
rawColon(root) {
let value
root.walkDecls(i => {
@@ -273,42 +309,32 @@ class Stringifier {
return value
}
rawEmptyBody(root) {
beforeAfter(node, detect) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after
if (typeof value !== 'undefined') return false
}
})
return value
}
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl')
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment')
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule')
} else {
value = this.raw(node, null, 'beforeClose')
}
rawIndent(root) {
if (root.raws.indent) return root.raws.indent
let value
root.walk(i => {
let p = i.parent
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
let parts = i.raws.before.split('\n')
value = parts[parts.length - 1]
value = value.replace(/\S/g, '')
return false
}
}
})
return value
}
let buf = node.parent
let depth = 0
while (buf && buf.type !== 'root') {
depth += 1
buf = buf.parent
}
rawSemicolon(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon
if (typeof value !== 'undefined') return false
if (value.includes('\n')) {
let indent = this.raw(node, null, 'indent')
if (indent.length) {
for (let step = 0; step < depth; step++) value += indent
}
})
}
return value
}
@@ -321,32 +347,6 @@ class Stringifier {
return value
}
root(node) {
this.body(node)
if (node.raws.after) this.builder(node.raws.after)
}
rule(node) {
this.block(node, this.rawValue(node, 'selector'))
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end')
}
}
stringify(node, semicolon) {
/* c8 ignore start */
if (!this[node.type]) {
throw new Error(
'Unknown AST node type ' +
node.type +
'. ' +
'Maybe you need to change PostCSS stringifier.'
)
}
/* c8 ignore stop */
this[node.type](node, semicolon)
}
}
module.exports = Stringifier

View File

@@ -1,9 +1,5 @@
import { Stringifier } from './postcss.js'
interface Stringify extends Stringifier {
default: Stringify
}
declare const stringify: Stringifier
declare const stringify: Stringify
export = stringify
export default stringify

View File

@@ -11,21 +11,21 @@ function registerInput(dependant) {
}
const HIGHLIGHT_THEME = {
';': pico.yellow,
':': pico.yellow,
'brackets': pico.cyan,
'at-word': pico.cyan,
'comment': pico.gray,
'string': pico.green,
'class': pico.yellow,
'hash': pico.magenta,
'call': pico.cyan,
'(': pico.cyan,
')': pico.cyan,
'[': pico.yellow,
']': pico.yellow,
'{': pico.yellow,
'}': pico.yellow,
'at-word': pico.cyan,
'brackets': pico.cyan,
'call': pico.cyan,
'class': pico.yellow,
'comment': pico.gray,
'hash': pico.magenta,
'string': pico.green
'[': pico.yellow,
']': pico.yellow,
':': pico.yellow,
';': pico.yellow
}
function getTokenType([type, value], processor) {

View File

@@ -22,15 +22,15 @@ const AT = '@'.charCodeAt(0)
const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g
const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g
const RE_BAD_BRACKET = /.[\r\n"'(/\\]/
const RE_BAD_BRACKET = /.[\n"'(/\\]/
const RE_HEX_ESCAPE = /[\da-f]/i
module.exports = function tokenizer(input, options = {}) {
let css = input.css.valueOf()
let ignore = options.ignoreErrors
let code, content, escape, next, quote
let currentToken, escaped, escapePos, n, prev
let code, next, quote, content, escape
let escaped, escapePos, prev, n, currentToken
let length = css.length
let pos = 0
@@ -259,8 +259,8 @@ module.exports = function tokenizer(input, options = {}) {
return {
back,
endOfFile,
nextToken,
endOfFile,
position
}
}

157
node_modules/postcss/lib/warning.d.ts generated vendored
View File

@@ -1,47 +1,42 @@
import { RangePosition } from './css-syntax-error.js'
import Node from './node.js'
declare namespace Warning {
export interface WarningOptions {
/**
* End position, exclusive, in CSS node string that caused the warning.
*/
end?: RangePosition
export interface WarningOptions {
/**
* CSS node that caused the warning.
*/
node?: Node
/**
* End index, exclusive, in CSS node string that caused the warning.
*/
endIndex?: number
/**
* Word in CSS source that caused the warning.
*/
word?: string
/**
* Start index, inclusive, in CSS node string that caused the warning.
*/
index?: number
/**
* Start index, inclusive, in CSS node string that caused the warning.
*/
index?: number
/**
* CSS node that caused the warning.
*/
node?: Node
/**
* End index, exclusive, in CSS node string that caused the warning.
*/
endIndex?: number
/**
* Name of the plugin that created this warning. `Result#warn` fills
* this property automatically.
*/
plugin?: string
/**
* Start position, inclusive, in CSS node string that caused the warning.
*/
start?: RangePosition
/**
* Start position, inclusive, in CSS node string that caused the warning.
*/
start?: RangePosition
/**
* End position, exclusive, in CSS node string that caused the warning.
*/
end?: RangePosition
/**
* Word in CSS source that caused the warning.
*/
word?: string
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { Warning_ as default }
/**
* Name of the plugin that created this warning. `Result#warn` fills
* this property automatically.
*/
plugin?: string
}
/**
@@ -53,51 +48,21 @@ declare namespace Warning {
* }
* ```
*/
declare class Warning_ {
export default class Warning {
/**
* Column for inclusive start position in the input file with this warnings source.
*
* ```js
* warning.column //=> 6
* ```
* Type to filter warnings from `Result#messages`.
* Always equal to `"warning"`.
*/
column: number
type: 'warning'
/**
* Column for exclusive end position in the input file with this warnings source.
* The warning message.
*
* ```js
* warning.endColumn //=> 4
* warning.text //=> 'Try to avoid !important'
* ```
*/
endColumn?: number
/**
* Line for exclusive end position in the input file with this warnings source.
*
* ```js
* warning.endLine //=> 6
* ```
*/
endLine?: number
/**
* Line for inclusive start position in the input file with this warnings source.
*
* ```js
* warning.line //=> 5
* ```
*/
line: number
/**
* Contains the CSS node that caused the warning.
*
* ```js
* warning.node.toString() //=> 'color: white !important'
* ```
*/
node: Node
text: string
/**
* The name of the plugin that created this warning.
@@ -110,25 +75,55 @@ declare class Warning_ {
plugin: string
/**
* The warning message.
* Contains the CSS node that caused the warning.
*
* ```js
* warning.text //=> 'Try to avoid !important'
* warning.node.toString() //=> 'color: white !important'
* ```
*/
text: string
node: Node
/**
* Type to filter warnings from `Result#messages`.
* Always equal to `"warning"`.
* Line for inclusive start position in the input file with this warnings source.
*
* ```js
* warning.line //=> 5
* ```
*/
type: 'warning'
line: number
/**
* Column for inclusive start position in the input file with this warnings source.
*
* ```js
* warning.column //=> 6
* ```
*/
column: number
/**
* Line for exclusive end position in the input file with this warnings source.
*
* ```js
* warning.endLine //=> 6
* ```
*/
endLine?: number
/**
* Column for exclusive end position in the input file with this warnings source.
*
* ```js
* warning.endColumn //=> 4
* ```
*/
endColumn?: number
/**
* @param text Warning message.
* @param opts Warning options.
*/
constructor(text: string, opts?: Warning.WarningOptions)
constructor(text: string, opts?: WarningOptions)
/**
* Returns a warning position and message.
@@ -141,7 +136,3 @@ declare class Warning_ {
*/
toString(): string
}
declare class Warning extends Warning_ {}
export = Warning

View File

@@ -19,8 +19,8 @@ class Warning {
toString() {
if (this.node) {
return this.node.error(this.text, {
index: this.index,
plugin: this.plugin,
index: this.index,
word: this.word
}).message
}