1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | var path = require('path'),
|
8 | convert = require('convert-source-map'),
|
9 | rework = require('rework'),
|
10 | visit = require('rework-visit');
|
11 |
|
12 | var fileProtocol = require('../file-protocol');
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | function process(sourceFile, sourceContent, params) {
|
24 |
|
25 |
|
26 |
|
27 | var contentWithMap = sourceContent + (
|
28 | params.absSourceMap ?
|
29 | convert.fromObject(fileProtocol.prepend(params.absSourceMap)).toComment({multiline: true}) :
|
30 | ''
|
31 | );
|
32 |
|
33 |
|
34 | var reworked = rework(contentWithMap, {source: fileProtocol.prepend(sourceFile)})
|
35 | .use(reworkPlugin)
|
36 | .toString({
|
37 | sourcemap : params.outputSourceMap,
|
38 | sourcemapAsObject: params.outputSourceMap
|
39 | });
|
40 |
|
41 |
|
42 | if (params.outputSourceMap) {
|
43 | return {
|
44 | content: reworked.code,
|
45 | map : fileProtocol.remove(reworked.map)
|
46 | };
|
47 | }
|
48 |
|
49 | else {
|
50 | return {
|
51 | content: reworked,
|
52 | map : null
|
53 | };
|
54 | }
|
55 |
|
56 | |
57 |
|
58 |
|
59 |
|
60 |
|
61 | function reworkPlugin(stylesheet) {
|
62 |
|
63 |
|
64 |
|
65 | visit(stylesheet, function visitor(declarations) {
|
66 | if (declarations) {
|
67 | declarations.forEach(eachDeclaration);
|
68 | }
|
69 | });
|
70 |
|
71 | |
72 |
|
73 |
|
74 |
|
75 | function eachDeclaration(declaration) {
|
76 | var isValid = declaration.value && (declaration.value.indexOf('url') >= 0);
|
77 | if (isValid) {
|
78 |
|
79 |
|
80 | var startPosApparent = declaration.position.start,
|
81 | startPosOriginal = params.sourceMapConsumer &&
|
82 | params.sourceMapConsumer.originalPositionFor(startPosApparent);
|
83 |
|
84 |
|
85 | var directory =
|
86 | startPosOriginal &&
|
87 | startPosOriginal.source &&
|
88 | fileProtocol.remove(path.dirname(startPosOriginal.source));
|
89 | if (directory) {
|
90 | declaration.value = params.transformDeclaration(declaration.value, directory);
|
91 | }
|
92 |
|
93 | else if (params.sourceMapConsumer) {
|
94 | throw new Error('source-map information is not available at url() declaration');
|
95 | }
|
96 | }
|
97 | }
|
98 | }
|
99 | }
|
100 |
|
101 | module.exports = process;
|