( postcss: postcss.Postcss, ast: AstNode[], source?: postcss.Source, )
| 7 | const EXCLAMATION_MARK = 0x21 |
| 8 | |
| 9 | export function cssAstToPostCssAst( |
| 10 | postcss: postcss.Postcss, |
| 11 | ast: AstNode[], |
| 12 | source?: postcss.Source, |
| 13 | ): postcss.Root { |
| 14 | let inputMap = new DefaultMap<Source, postcss.Input>((src) => { |
| 15 | return new postcss.Input(src.code, { |
| 16 | map: source?.input.map, |
| 17 | from: src.file ?? undefined, |
| 18 | }) |
| 19 | }) |
| 20 | |
| 21 | let lineTables = new DefaultMap<Source, LineTable>((src) => createLineTable(src.code)) |
| 22 | |
| 23 | let root = postcss.root() |
| 24 | root.source = source |
| 25 | |
| 26 | function toSource(loc: SourceLocation | undefined): postcss.Source | undefined { |
| 27 | // Use the fallback if this node has no location info in the AST |
| 28 | if (!loc) return |
| 29 | if (!loc[0]) return |
| 30 | |
| 31 | let table = lineTables.get(loc[0]) |
| 32 | let start = table.find(loc[1]) |
| 33 | let end = table.find(loc[2]) |
| 34 | |
| 35 | return { |
| 36 | input: inputMap.get(loc[0]), |
| 37 | start: { |
| 38 | line: start.line, |
| 39 | column: start.column + 1, |
| 40 | offset: loc[1], |
| 41 | }, |
| 42 | end: { |
| 43 | line: end.line, |
| 44 | column: end.column + 1, |
| 45 | offset: loc[2], |
| 46 | }, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | function updateSource(astNode: postcss.ChildNode, loc: SourceLocation | undefined) { |
| 51 | let source = toSource(loc) |
| 52 | |
| 53 | // The `source` property on PostCSS nodes must be defined if present because |
| 54 | // `toJSON()` reads each property and tries to read from source.input if it |
| 55 | // sees a `source` property. This means for a missing or otherwise absent |
| 56 | // source it must be *missing* from the object rather than just `undefined` |
| 57 | if (source) { |
| 58 | astNode.source = source |
| 59 | } else { |
| 60 | delete astNode.source |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | function transform(node: AstNode, parent: postcss.Container) { |
| 65 | // Declaration |
| 66 | if (node.kind === 'declaration') { |
no test coverage detected