/
parse-styles.js
243 lines (207 loc) · 5.76 KB
/
parse-styles.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"use strict"
const path = require("path")
const dataURL = require("./data-url")
const parseStatements = require("./parse-statements")
const processContent = require("./process-content")
const resolveId = require("./resolve-id")
const formatImportPrelude = require("./format-import-prelude")
async function parseStyles(
result,
styles,
options,
state,
conditions,
from,
postcss,
) {
const statements = parseStatements(result, styles, conditions, from)
for (const stmt of statements) {
if (stmt.type !== "import" || !isProcessableURL(stmt.uri)) {
continue
}
if (options.filter && !options.filter(stmt.uri)) {
// rejected by filter
continue
}
await resolveImportId(result, stmt, options, state, postcss)
}
let charset
const imports = []
const bundle = []
function handleCharset(stmt) {
if (!charset) charset = stmt
// charsets aren't case-sensitive, so convert to lower case to compare
else if (
stmt.node.params.toLowerCase() !== charset.node.params.toLowerCase()
) {
throw stmt.node.error(
`Incompatible @charset statements:
${stmt.node.params} specified in ${stmt.node.source.input.file}
${charset.node.params} specified in ${charset.node.source.input.file}`,
)
}
}
// squash statements and their children
statements.forEach(stmt => {
if (stmt.type === "charset") handleCharset(stmt)
else if (stmt.type === "import") {
if (stmt.children) {
stmt.children.forEach((child, index) => {
if (child.type === "import") imports.push(child)
else if (child.type === "charset") handleCharset(child)
else bundle.push(child)
// For better output
if (index === 0) child.parent = stmt
})
} else imports.push(stmt)
} else if (stmt.type === "nodes") {
bundle.push(stmt)
}
})
return charset ? [charset, ...imports.concat(bundle)] : imports.concat(bundle)
}
async function resolveImportId(result, stmt, options, state, postcss) {
if (dataURL.isValid(stmt.uri)) {
// eslint-disable-next-line require-atomic-updates
stmt.children = await loadImportContent(
result,
stmt,
stmt.uri,
options,
state,
postcss,
)
return
} else if (dataURL.isValid(stmt.from.slice(-1))) {
// Data urls can't be used as a base url to resolve imports.
throw stmt.node.error(
`Unable to import '${stmt.uri}' from a stylesheet that is embedded in a data url`,
)
}
const atRule = stmt.node
let sourceFile
if (atRule.source?.input?.file) {
sourceFile = atRule.source.input.file
}
const base = sourceFile
? path.dirname(atRule.source.input.file)
: options.root
const paths = [await options.resolve(stmt.uri, base, options, atRule)].flat()
// Ensure that each path is absolute:
const resolved = await Promise.all(
paths.map(file => {
return !path.isAbsolute(file)
? resolveId(file, base, options, atRule)
: file
}),
)
// Add dependency messages:
resolved.forEach(file => {
result.messages.push({
type: "dependency",
plugin: "postcss-import",
file,
parent: sourceFile,
})
})
const importedContent = await Promise.all(
resolved.map(file => {
return loadImportContent(result, stmt, file, options, state, postcss)
}),
)
// Merge loaded statements
// eslint-disable-next-line require-atomic-updates
stmt.children = importedContent.flat().filter(x => !!x)
}
async function loadImportContent(
result,
stmt,
filename,
options,
state,
postcss,
) {
const atRule = stmt.node
const { conditions, from } = stmt
const stmtDuplicateCheckKey = conditions
.map(condition =>
formatImportPrelude(condition.layer, condition.media, condition.supports),
)
.join(":")
if (options.skipDuplicates) {
// skip files already imported at the same scope
if (state.importedFiles[filename]?.[stmtDuplicateCheckKey]) {
return
}
// save imported files to skip them next time
if (!state.importedFiles[filename]) {
state.importedFiles[filename] = {}
}
state.importedFiles[filename][stmtDuplicateCheckKey] = true
}
if (from.includes(filename)) {
return
}
const content = await options.load(filename, options)
if (content.trim() === "" && options.warnOnEmpty) {
result.warn(`${filename} is empty`, { node: atRule })
return
}
// skip previous imported files not containing @import rules
if (
options.skipDuplicates &&
state.hashFiles[content]?.[stmtDuplicateCheckKey]
) {
return
}
const importedResult = await processContent(
result,
content,
filename,
options,
postcss,
)
const styles = importedResult.root
result.messages = result.messages.concat(importedResult.messages)
if (options.skipDuplicates) {
const hasImport = styles.some(child => {
return child.type === "atrule" && child.name === "import"
})
if (!hasImport) {
// save hash files to skip them next time
if (!state.hashFiles[content]) {
state.hashFiles[content] = {}
}
state.hashFiles[content][stmtDuplicateCheckKey] = true
}
}
// recursion: import @import from imported file
return parseStyles(
result,
styles,
options,
state,
conditions,
[...from, filename],
postcss,
)
}
function isProcessableURL(uri) {
// skip protocol base uri (protocol://url) or protocol-relative
if (/^(?:[a-z]+:)?\/\//i.test(uri)) {
return false
}
// check for fragment or query
try {
// needs a base to parse properly
const url = new URL(uri, "https://example.com")
if (url.hash) {
return false
}
if (url.search) {
return false
}
} catch {} // Ignore
return true
}
module.exports = parseStyles