1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | var os = require('os'),
|
8 | path = require('path'),
|
9 | postcss = require('postcss');
|
10 |
|
11 | var fileProtocol = require('../file-protocol');
|
12 |
|
13 | var ORPHAN_CR_REGEX = /\r(?!\n)(.|\n)?/g;
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | function process(sourceFile, sourceContent, params) {
|
25 |
|
26 | var correctedContent = params.removeCR && (os.EOL !== '\r') ?
|
27 | sourceContent.replace(ORPHAN_CR_REGEX, ' $1') :
|
28 | sourceContent;
|
29 |
|
30 |
|
31 | return postcss([
|
32 | postcss.plugin('postcss-resolve-url', postcssPlugin)
|
33 | ])
|
34 | .process(correctedContent, {
|
35 | from: fileProtocol.prepend(sourceFile),
|
36 | map : params.outputSourceMap && {
|
37 | prev : !!params.absSourceMap && fileProtocol.prepend(params.absSourceMap),
|
38 | inline : false,
|
39 | annotation : false,
|
40 | sourcesContent: true
|
41 | }
|
42 | })
|
43 | .then(result => ({
|
44 | content: result.css,
|
45 | map : params.outputSourceMap ? fileProtocol.remove(result.map.toJSON()) : null
|
46 | }));
|
47 |
|
48 | |
49 |
|
50 |
|
51 | function postcssPlugin() {
|
52 | return function(styles) {
|
53 | styles.walkDecls(eachDeclaration);
|
54 | };
|
55 |
|
56 | |
57 |
|
58 |
|
59 |
|
60 | function eachDeclaration(declaration) {
|
61 | var isValid = declaration.value && (declaration.value.indexOf('url') >= 0);
|
62 | if (isValid) {
|
63 |
|
64 |
|
65 | var startPosApparent = declaration.source.start,
|
66 | startPosOriginal = params.sourceMapConsumer &&
|
67 | params.sourceMapConsumer.originalPositionFor(startPosApparent);
|
68 |
|
69 |
|
70 | var directory =
|
71 | startPosOriginal &&
|
72 | startPosOriginal.source &&
|
73 | fileProtocol.remove(path.dirname(startPosOriginal.source));
|
74 | if (directory) {
|
75 | declaration.value = params.transformDeclaration(declaration.value, directory);
|
76 | }
|
77 |
|
78 | else if (params.sourceMapConsumer) {
|
79 | throw new Error(
|
80 | 'source-map information is not available at url() declaration ' +
|
81 | (ORPHAN_CR_REGEX.test(sourceContent) ? '(found orphan CR, try removeCR option)' : '(no orphan CR found)')
|
82 | );
|
83 | }
|
84 | }
|
85 | }
|
86 | }
|
87 | }
|
88 |
|
89 | module.exports = process;
|