(root: postcss.Root)
| 124 | } |
| 125 | |
| 126 | export function postCssAstToCssAst(root: postcss.Root): AstNode[] { |
| 127 | let inputMap = new DefaultMap<postcss.Input, Source>((input) => ({ |
| 128 | file: input.file ?? input.id ?? null, |
| 129 | code: input.css, |
| 130 | })) |
| 131 | |
| 132 | function toSource(node: postcss.ChildNode): SourceLocation | undefined { |
| 133 | let source = node.source |
| 134 | if (!source) return |
| 135 | |
| 136 | let input = source.input |
| 137 | if (!input) return |
| 138 | if (source.start === undefined) return |
| 139 | if (source.end === undefined) return |
| 140 | |
| 141 | return [inputMap.get(input), source.start.offset, source.end.offset] |
| 142 | } |
| 143 | |
| 144 | function transform( |
| 145 | node: postcss.ChildNode, |
| 146 | parent: Extract<AstNode, { nodes: AstNode[] }>['nodes'], |
| 147 | ) { |
| 148 | // Declaration |
| 149 | if (node.type === 'decl') { |
| 150 | let astNode = decl(node.prop, node.value, node.important) |
| 151 | astNode.src = toSource(node) |
| 152 | parent.push(astNode) |
| 153 | } |
| 154 | |
| 155 | // Rule |
| 156 | else if (node.type === 'rule') { |
| 157 | let astNode = rule(node.selector) |
| 158 | astNode.src = toSource(node) |
| 159 | node.each((child) => transform(child, astNode.nodes)) |
| 160 | parent.push(astNode) |
| 161 | } |
| 162 | |
| 163 | // AtRule |
| 164 | else if (node.type === 'atrule') { |
| 165 | let astNode = atRule(`@${node.name}`, node.params) |
| 166 | astNode.src = toSource(node) |
| 167 | node.each((child) => transform(child, astNode.nodes)) |
| 168 | parent.push(astNode) |
| 169 | } |
| 170 | |
| 171 | // Comment |
| 172 | else if (node.type === 'comment') { |
| 173 | if (node.text.charCodeAt(0) !== EXCLAMATION_MARK) return |
| 174 | let astNode = comment(node.text) |
| 175 | astNode.src = toSource(node) |
| 176 | parent.push(astNode) |
| 177 | } |
| 178 | |
| 179 | // Unknown |
| 180 | else { |
| 181 | node satisfies never |
| 182 | } |
| 183 | } |
no test coverage detected