-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
203 lines (173 loc) · 4.78 KB
/
index.ts
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
import { SkipFunction, VariableCompressParameters, BuildHistory } from './types'
export * from './types'
import fs from 'fs'
import path from 'path'
const postcssPlugin = 'postcss-variable-compress'
const buildHistoryFileName = 'postcssVariableCompress.json'
let renamedVariables = new Set<string>()
let pureSkips = new Set<string>()
let functionBasedSkips: SkipFunction[] = []
let cssVariablesMap = new Map<string, string>()
function scriptCheck(val: string): boolean {
return functionBasedSkips.some((skipFunc) => skipFunc(val))
}
function shouldRun(val: string): boolean {
return !renamedVariables.has(val) && !scriptCheck(val)
}
function getReplacementVariable() {
}
function increase(): void {
let counter = cssVariablesMap.size
let temp = counter.toString(36)
while (pureSkips.has(temp)) {
counter++
temp = counter.toString(36)
}
}
function replacer(match: string): string {
if (!shouldRun(match)) return match
let exist = cssVariablesMap.get(match)
if (!exist) {
exist = '--' + cssVariablesMap.size.toString(36)
increase()
cssVariablesMap.set(match, exist)
renamedVariables.add(exist)
}
return exist
}
function map(declaration: import('postcss').Declaration): void {
const prop = declaration.prop
if (prop && declaration.variable && shouldRun(prop)) {
const old = prop
let exist = cssVariablesMap.get(old)
if (!exist) {
exist = '--' + cssVariablesMap.size.toString(36)
increase()
cssVariablesMap.set(old, exist)
renamedVariables.add(exist)
}
declaration.prop = exist
}
let value = declaration.value
if (
value &&
value.includes('var(') &&
value.includes('--') &&
value.length <= 1000
) {
value = value.replace(/--[\w-_]{1,1000}/g, replacer)
declaration.value = value
}
// @ts-ignore
declaration.processed = true
}
function loadBuildHistory(historyPath: string): void {
try {
let stats = fs.statSync(historyPath)
if (stats.isDirectory()) {
historyPath = path.join(historyPath, buildHistoryFileName)
}
try {
stats = fs.statSync(historyPath)
cssVariablesMap.clear()
const fileData = fs.readFileSync(historyPath, 'utf8')
const buildHistory: BuildHistory = JSON.parse(fileData)
buildHistory.variables
.filter((item) => Boolean(Array.isArray(item) && item.length === 2))
.forEach(([a, b]) => {
cssVariablesMap.set(a, b)
})
} catch (error) {
fs.writeFileSync(
historyPath,
JSON.stringify(
{
variables: []
},
null,
2
),
'utf8'
)
}
} catch (error) {
console.error('Failed to load build history:', error)
}
}
async function saveBuildHistory(historyPath: string): Promise<void> {
try {
const stats = await fs.promises.stat(historyPath)
if (stats.isDirectory()) {
historyPath = path.join(historyPath, buildHistoryFileName)
}
const buildHistory: BuildHistory = {
variables: [...cssVariablesMap.entries()]
}
const jsonData = JSON.stringify(buildHistory, null, 2)
await fs.promises.writeFile(historyPath, jsonData, 'utf8')
} catch (error) {
console.error('Failed to save build history:', error)
}
}
/**
* This is necessary as if the
*/
let lastHistory: string | boolean | undefined
let runs = 0
/**
*
* @param preserveVariables Provides facility to preserver the variables from being changed
* @param history When true is provided changes are kept same in the build
* @param history When a path is provided Keeps the list of variables same accross build at the cost of storing variables in a file
* @returns
*/
function variableCompress(
preserveVariables?: VariableCompressParameters[],
history?: string | boolean
): any {
let firstRun = runs === 0
if (
!(history === true || typeof history === 'string') ||
(!firstRun && lastHistory !== history)
) {
renamedVariables = new Set()
pureSkips = new Set()
functionBasedSkips = []
cssVariablesMap.clear()
}
runs++
if (typeof history === 'string') {
loadBuildHistory(history)
}
preserveVariables?.forEach((param) => {
if (typeof param === 'string') {
let name = param
let cssName = param
if (param.slice(0, 2) === '--') {
name = param.slice(2)
} else {
cssName = '--' + param
}
pureSkips.add(name)
cssVariablesMap.set(cssName, cssName)
} else {
functionBasedSkips.push(param)
}
})
increase()
return {
postcssPlugin,
Declaration: {
'*': map
},
async OnceExit() {
if (typeof history === 'string') {
await saveBuildHistory(history)
}
return true
}
}
}
module.exports = variableCompress
module.exports.postcss = true
export default variableCompress