| 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286 |
86x
3x
84x
58x
3x
3x
3x
3x
2x
1x
84x
82x
73x
72x
2x
70x
2x
68x
2x
66x
2x
64x
62x
2x
60x
2x
47x
46x
46x
46x
45x
45x
47x
47x
47x
47x
46x
1x
47x
46x
46x
46x
46x
52x
45x
33x
7x
17x
7x
46x
46x
46x
1x
45x
638x
45x
45x
45x
45x
195x
195x
193x
193x
609x
609x
252x
357x
357x
334x
23x
6x
252x
252x
101x
193x
193x
193x
45x
195x
2x
193x
193x
7x
186x
252x
299x
45x
45x
45x
76x
53x
31x
45x
24x
8x
254x
198x
88x
135x
117x
33x
16x
| // @flow
import { type ExtractorsObj, type Options } from './../flow/index.js'
import fs from 'fs'
import path from 'path'
import glob from 'glob'
import defaultOptions from './constants/defaultOptions'
import postcss from 'postcss'
import selectorParser from 'postcss-selector-parser'
import {
CONFIG_FILENAME,
ERROR_CONFIG_FILE_LOADING,
ERROR_MISSING_CONTENT,
ERROR_MISSING_CSS,
ERROR_EXTRACTER_FAILED,
ERROR_OPTIONS_TYPE,
ERROR_OUTPUT_TYPE,
ERROR_EXTRACTERS_TYPE,
ERROR_WHITELIST_TYPE,
ERROR_STDOUT_TYPE,
ERROR_INFO_TYPE,
ERROR_REJECTED_TYPE,
ERROR_WHITELIST_PATTERNS_TYPE,
IGNORE_ANNOTATION
} from './constants/constants'
import CSS_WHITELIST from './constants/cssWhitelist'
import SELECTOR_STANDARD_TYPES from './constants/selectorTypes'
import DefaultExtractor from './Extractors/DefaultExtractor'
import LegacyExtractor from './Extractors/LegacyExtractor'
class Purgecss {
options: Options
constructor(options: Options | string) {
if (typeof options === 'string' || typeof options === 'undefined')
options = this.loadConfigFile(options)
this.checkOptions(options)
this.options = Object.assign(defaultOptions, options)
}
/**
* Load the configuration file from the path
* @param {string} configFile Path of the config file
*/
loadConfigFile(configFile: string) {
const pathConfig = typeof configFile === 'undefined' ? CONFIG_FILENAME : configFile
let options
try {
const t = path.resolve(process.cwd(), pathConfig)
options = require(t)
} catch (e) {
throw new Error(ERROR_CONFIG_FILE_LOADING + e.message)
}
return options
}
/**
* Verify that the purgecss options provided are valid
* @param {object} options Purgecss options
*/
checkOptions(options: Options) {
if (typeof options !== 'object') throw new TypeError(ERROR_OPTIONS_TYPE)
if (!options.content || !options.content.length) throw new Error(ERROR_MISSING_CONTENT)
if (!options.css || !options.css.length) throw new Error(ERROR_MISSING_CSS)
if (options.output && typeof options.output !== 'string')
throw new TypeError(ERROR_OUTPUT_TYPE)
if (options.extractors && !Array.isArray(options.extractors))
throw new TypeError(ERROR_EXTRACTERS_TYPE)
if (options.whitelist && !Array.isArray(options.whitelist))
throw new TypeError(ERROR_WHITELIST_TYPE)
if (options.stdout && typeof options.stdout !== 'boolean')
throw new TypeError(ERROR_STDOUT_TYPE)
if (options.info && typeof options.info !== 'boolean') throw new TypeError(ERROR_INFO_TYPE)
if (options.rejected && typeof options.rejected !== 'boolean')
throw new TypeError(ERROR_REJECTED_TYPE)
if (options.whitelistPatterns && !Array.isArray(options.whitelistPatterns))
throw new TypeError(ERROR_WHITELIST_PATTERNS_TYPE)
}
/**
* Main function that purge the css file
*/
purge() {
// Get selectors from content files
let cssClasses = this.extractFileSelector(this.options.content, this.options.extractors)
// Get css selectors and remove unused ones
let files = []
for (let file of this.options.css) {
const cssContent = this.options.stdin ? file : fs.readFileSync(file, 'utf8')
files.push({
file,
css: this.getSelectorsCss(cssContent, cssClasses)
})
}
return files
}
/**
* Extract the selectors present in the files using a purgecss extractor
* @param {array} files Array of files path or glob pattern
* @param {array} extractors Array of extractors
*/
extractFileSelector(files: Array<string>, extractors?: Array<ExtractorsObj>): Set<string> {
let selectors = new Set()
for (let globfile of files) {
let filesnames = []
if (fs.existsSync(globfile)) {
filesnames.push(globfile)
} else {
filesnames = glob.sync(globfile)
}
for (let file of filesnames) {
const content = fs.readFileSync(file, 'utf8')
const extractor = this.getFileExtractor(file, extractors)
selectors = new Set(...selectors, this.extractSelectors(content, extractor))
}
}
return selectors
}
/**
* Get the extractor corresponding to the extension file
* @param {string} filename Name of the file
* @param {array} extractors Array of extractors definition objects
*/
getFileExtractor(filename: string, extractors: Array<ExtractorsObj> = []) {
if (!extractors.length) {
if (this.options.legacy === true) return LegacyExtractor
return DefaultExtractor
}
const extractorObj: any = extractors.find(extractor =>
extractor.extensions.find(ext => filename.endsWith(ext))
)
return extractorObj.extractor
}
/**
* Use the extract function of the extractor to get the list of selectors
* @param {string} content Content (e.g: html file)
* @param {object} extractor Purgecss extractor use to extract the selector
*/
extractSelectors(content: string, extractor: Object): Set<string> {
let selectors = new Set()
const arraySelector = extractor.extract(content)
if (arraySelector === null) {
throw new Error(ERROR_EXTRACTER_FAILED)
}
arraySelector.forEach(selector => {
selectors.add(selector)
})
// Remove empty string
selectors.delete('')
return selectors
}
/**
* Use postcss to walk through the css ast and remove unused css
* @param {string} css css to remove selectors from
* @param {*} selectors selectors used in content files
*/
getSelectorsCss(css: string, selectors: Set<string>) {
const root = postcss.parse(css)
root.walkRules(node => {
const annotation = node.prev()
if (this.isIgnoreAnnotation(annotation)) return
node.selector = selectorParser(selectorsParsed => {
selectorsParsed.walk(selector => {
let selectorsInRule = []
if (selector.type === 'selector') {
for (let nodeSelector of selector.nodes) {
const { type, value } = nodeSelector
if (
SELECTOR_STANDARD_TYPES.includes(type) &&
typeof value !== 'undefined'
) {
selectorsInRule.push(value)
} else if (
type === 'attribute' &&
typeof nodeSelector.raws.unquoted !== 'undefined'
) {
selectorsInRule.push(nodeSelector.raws.unquoted)
}
}
let keepSelector = this.shouldKeepSelector(selectors, selectorsInRule)
if (!keepSelector) {
selector.remove()
}
}
})
}).processSync(node.selector)
const parent = node.parent
// // Remove empty rules
if (!node.selector) node.remove()
if (this.isRuleEmpty(parent)) parent.remove()
})
return root.toString()
}
/**
* Check if the node is a css comment to ignore the selector rule
* @param {object} node Node of postcss abstract syntax tree
*/
isIgnoreAnnotation(node: Object) {
if (node && node.type === 'comment') {
return node.text.includes(IGNORE_ANNOTATION)
}
return false
}
/**
* Check if the node correspond to an empty css rule
* @param {object} node Node of postcss abstract syntax tree
*/
isRuleEmpty(node: Object) {
if (
(node.type === 'decl' && !node.value) ||
((node.type === 'rule' && !node.selector) || (node.nodes && !node.nodes.length)) ||
(node.type === 'atrule' &&
((!node.nodes && !node.params) || (!node.params && !node.nodes.length)))
) {
return true
}
return false
}
/**
* Determine if the selector should be kept, based on the selectors found in the files
* @param {Set} selectorsInContent Set of css selectors found in the content files
* @param {Array} selectorsInRule Array of selectors
*/
shouldKeepSelector(selectorsInContent: Set<string>, selectorsInRule: Array<string>) {
for (let selector of selectorsInRule) {
// legacy
if (this.options.legacy) {
const sels = selector.split(/[^a-z]/g)
let keepSelector = false
for (let sel of sels) {
if (!sel) continue
if (!selectorsInContent.has(sel)) break
keepSelector = true
}
if (keepSelector) return true
if (
selectorsInContent.has(selector) ||
CSS_WHITELIST.includes(selector) ||
this.isSelectorWhitelisted(selector)
)
return true
} else {
// non legacy extractors
// pseudo class
if (selector.startsWith(':')) continue
if (
!(
selectorsInContent.has(selector) ||
CSS_WHITELIST.includes(selector) ||
this.isSelectorWhitelisted(selector)
)
) {
return false
}
}
}
return this.options.legacy ? false : true
}
/**
* Check if the selector is whitelisted by the options whitelist or whitelistPatterns
* @param {string} selector css selector
*/
isSelectorWhitelisted(selector: string): boolean {
return !!(
CSS_WHITELIST.includes(selector) ||
(this.options.whitelist && this.options.whitelist.some(v => v === selector)) ||
(this.options.whitelistPatterns &&
this.options.whitelistPatterns.some(v => v.test(selector)))
)
}
}
export default Purgecss
|