-
Notifications
You must be signed in to change notification settings - Fork 91
/
stylesPlugin.ts
235 lines (199 loc) · 7.04 KB
/
stylesPlugin.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
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
import { utimes } from 'fs/promises'
import * as path from 'upath'
import _debug from 'debug'
import { normalizePath as normalizeVitePath } from 'vite'
import { cacheDir, writeStyles, resolveVuetifyBase, normalizePath } from '@vuetify/loader-shared'
import type { Plugin, ViteDevServer } from 'vite'
import type { Options } from '@vuetify/loader-shared'
import type { PluginContext } from 'rollup'
const debug = _debug('vuetify:styles')
function isSubdir (root: string, test: string) {
const relative = path.relative(root, test)
return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
}
const styleImportRegexp = /(@use |meta\.load-css\()['"](vuetify(?:\/lib)?(?:\/styles(?:\/main(?:\.sass)?)?)?)['"]/
export function stylesPlugin (options: Options): Plugin {
const vuetifyBase = resolveVuetifyBase()
const files = new Set<string>()
let server: ViteDevServer
let context: PluginContext
let resolve: (v: boolean) => void
let promise: Promise<boolean> | null
let needsTouch = false
const blockingModules = new Set<string>()
let pendingModules: string[]
async function getPendingModules () {
if (!server) {
await new Promise(resolve => setTimeout(resolve, 0))
const modules = Array.from(context.getModuleIds())
.filter(id => {
return !blockingModules.has(id) && // Ignore the current file
!/\w\.(s[ac]|c)ss/.test(id) // Ignore stylesheets
})
.map(id => context.getModuleInfo(id)!)
.filter(module => module.code == null) // Ignore already loaded modules
pendingModules = modules.map(module => module.id)
if (!pendingModules.length) return 0
const promises = modules.map(module => context.load(module))
await Promise.race(promises)
return promises.length
} else {
const modules = Array.from(server.moduleGraph.urlToModuleMap.entries())
.filter(([k, v]) => (
v.transformResult == null && // Ignore already loaded modules
!k.startsWith('/@id/') &&
!/\w\.(s[ac]|c)ss/.test(k) && // Ignore stylesheets
!blockingModules.has(v.id!) && // Ignore the current file
!/\/node_modules\/\.vite\/deps\/(?!vuetify[._])/.test(k) // Ignore dependencies
))
pendingModules = modules.map(([, v]) => v.id!)
if (!pendingModules.length) return 0
const promises = modules.map(([k, v]) => server.transformRequest(k).then(() => v))
await Promise.race(promises)
return promises.length
}
}
let timeout: NodeJS.Timeout
async function awaitBlocking () {
let pending
do {
clearTimeout(timeout)
timeout = setTimeout(() => {
console.error('vuetify:styles fallback timeout hit', {
blockingModules: Array.from(blockingModules.values()),
pendingModules,
pendingRequests: server?._pendingRequests.keys()
})
resolve(false)
}, options.stylesTimeout)
pending = await Promise.any<boolean | number | null>([
promise,
getPendingModules()
])
debug(pending, 'pending modules', pendingModules)
} while (pending)
resolve(false)
}
async function awaitResolve (id?: string) {
if (id) {
blockingModules.add(id)
}
if (!promise) {
promise = new Promise((_resolve) => resolve = _resolve)
awaitBlocking()
await promise
clearTimeout(timeout)
blockingModules.clear()
debug('writing styles')
await writeStyles(files)
if (server && needsTouch) {
const cacheFile = normalizeVitePath(cacheDir('styles.scss'))
server.moduleGraph.getModulesByFile(cacheFile)?.forEach(module => {
module.importers.forEach(module => {
if (module.file) {
const now = new Date()
debug(`touching ${module.file}`)
utimes(module.file, now, now)
}
})
})
needsTouch = false
}
promise = null
}
return promise
}
let configFile: string
const tempFiles = new Map<string, string>()
return {
name: 'vuetify:styles',
enforce: 'pre',
configureServer (_server) {
server = _server
},
buildStart () {
if (!server) {
context = this
}
},
configResolved (config) {
if (typeof options.styles === 'object') {
if (path.isAbsolute(options.styles.configFile)) {
configFile = options.styles.configFile
} else {
configFile = path.join(config.root || process.cwd(), options.styles.configFile)
}
}
},
async resolveId (source, importer, { custom }) {
if (
source === 'vuetify/styles' || (
importer &&
source.endsWith('.css') &&
isSubdir(vuetifyBase, path.isAbsolute(source) ? source : importer)
)
) {
if (options.styles === 'none') {
return '\0__void__'
} else if (options.styles === 'sass') {
const target = source.replace(/\.css$/, '.sass')
return this.resolve(target, importer, { skipSelf: true, custom })
} else if (options.styles === 'expose') {
awaitResolve()
const resolution = await this.resolve(
source.replace(/\.css$/, '.sass'),
importer,
{ skipSelf: true, custom }
)
if (resolution) {
if (!files.has(resolution.id)) {
needsTouch = true
files.add(resolution.id)
}
return '\0__void__'
}
} else if (typeof options.styles === 'object') {
const resolution = await this.resolve(source, importer, { skipSelf: true, custom })
if (!resolution) return null
const target = resolution.id.replace(/\.css$/, '.sass')
const file = path.relative(path.join(vuetifyBase, 'lib'), target)
const contents = `@use "${normalizePath(configFile)}"\n@use "${normalizePath(target)}"`
tempFiles.set(file, contents)
return `\0plugin-vuetify:${file}`
}
} else if (source.startsWith('/plugin-vuetify:')) {
return '\0' + source.slice(1)
} else if (source.startsWith('/@id/__x00__plugin-vuetify:')) {
return '\0' + source.slice(12)
}
return null
},
async transform (code, id) {
if (
options.styles === 'expose' &&
['.scss', '.sass'].some(v => id.endsWith(v)) &&
styleImportRegexp.test(code)
) {
debug(`awaiting ${id}`)
await awaitResolve(id)
debug(`returning ${id}`)
return {
code: code.replace(styleImportRegexp, '$1".cache/vuetify/styles.scss"'),
map: null,
}
}
},
load (id) {
// When Vite is configured with `optimizeDeps.exclude: ['vuetify']`, the
// received id contains a version hash (e.g. \0__void__?v=893fa859).
if (/^\0__void__(\?.*)?$/.test(id)) {
return ''
}
if (id.startsWith('\0plugin-vuetify')) {
const file = /^\0plugin-vuetify:(.*?)(\?.*)?$/.exec(id)![1]
return tempFiles.get(file)
}
return null
},
}
}