/
contextLoader.ts
243 lines (201 loc) · 6.44 KB
/
contextLoader.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
236
237
238
239
240
241
242
243
import { readdir } from 'fs/promises'
import path from 'path'
import fs from 'fs'
import type { UnocssPluginContext, UserConfig } from '@unocss/core'
import { notNull } from '@unocss/core'
import { sourceObjectFields, sourcePluginFactory } from 'unconfig/presets'
import presetUno from '@unocss/preset-uno'
import { resolveOptions as resolveNuxtOptions } from '../../nuxt/src/options'
import { createNanoEvents } from '../../core/src/utils/events'
import { createContext } from './integration'
import { isSubdir } from './utils'
import { log } from './log'
export class ContextLoader {
public cwd: string
public ready: Promise<void>
public defaultContext: UnocssPluginContext<UserConfig<any>>
public contextsMap = new Map<string, UnocssPluginContext<UserConfig<any>> | null>()
private fileContextCache = new Map<string, UnocssPluginContext<UserConfig<any>> | null>()
private configExistsCache = new Map<string, boolean>()
public events = createNanoEvents<{
reload: () => void
contextLoaded: (context: UnocssPluginContext<UserConfig<any>>) => void
contextReload: (context: UnocssPluginContext<UserConfig<any>>) => void
contextUnload: (context: UnocssPluginContext<UserConfig<any>>) => void
}>()
constructor(cwd: string) {
this.cwd = cwd
this.defaultContext = createContext({
presets: [
presetUno(),
],
})
this.ready = this.reload()
.then(async () => {
await this.defaultContext.ready
})
}
get contexts() {
return Array.from(new Set(this.contextsMap.values())).filter(notNull)
}
async reload() {
this.ready = this._reload()
await this.ready
this.events.emit('reload')
}
private async _reload() {
for (const dir of this.contextsMap.keys())
this.unloadContext(dir)
this.fileContextCache.clear()
this.configExistsCache.clear()
await this.loadContextInDirectory(this.cwd)
}
async unloadContext(configDir: string) {
const context = this.contextsMap.get(configDir)
if (!context)
return
this.contextsMap.delete(configDir)
for (const [path, ctx] of this.fileContextCache) {
if (ctx === context)
this.fileContextCache.delete(path)
}
this.events.emit('contextUnload', context)
}
async configExists(dir: string) {
if (!this.configExistsCache.has(dir)) {
const files = await readdir(dir)
this.configExistsCache.set(dir, files.some(f => /^(vite|svelte|astro|iles|nuxt|unocss|uno)\.config/.test(f)))
}
return this.configExistsCache.has(dir)!
}
async loadContextInDirectory(dir: string) {
const cached = this.contextsMap.get(dir)
if (cached !== undefined)
return cached
const load = async () => {
log.appendLine(`[info] Resolving config for ${dir}`)
const context = createContext(
dir,
undefined,
[
sourcePluginFactory({
files: [
'vite.config',
'svelte.config',
'astro.config',
'iles.config',
],
targetModule: 'unocss/vite',
parameters: [{ command: 'serve', mode: 'development' }],
}),
sourceObjectFields({
files: 'nuxt.config',
fields: 'unocss',
}),
],
(result) => {
if (result.sources.some(s => s.includes('nuxt.config')))
resolveNuxtOptions(result.config)
},
)
context.updateRoot(dir)
let sources = []
try {
sources = (await context.ready).sources
}
catch (e) {
log.appendLine(`[error] ${String(e)}`)
log.appendLine(`[error] Error occurred while loading config. Config directory: ${dir}`)
return null
}
if (!sources.length)
return null
const baseDir = path.dirname(sources[0])
if (baseDir !== dir) {
// exists on upper level, skip
this.contextsMap.set(dir, null)
return null
}
context.onReload(() => {
for (const [path, ctx] of this.fileContextCache) {
if (ctx === context || !ctx)
this.fileContextCache.delete(path)
}
this.configExistsCache.clear()
this.events.emit('contextReload', context)
})
for (const [path, ctx] of this.fileContextCache) {
if (!ctx)
this.fileContextCache.delete(path)
}
this.events.emit('contextLoaded', context)
log.appendLine(`[info] New configuration loaded from\n ${sources.map(s => ` - ${s}`).join('\n')}`)
return context
}
const context = await load()
if (!this.contextsMap.has(dir))
this.contextsMap.set(dir, context)
return context
}
async resolveContext(code: string, file: string) {
if (file.match(/[\/](node_modules|dist|\.temp|\.cache)[\/]/g))
return
const cached = this.fileContextCache.get(file)
if (cached !== undefined)
return cached
// try finding an existing context that includes the file
for (const [configDir, context] of this.contextsMap) {
if (!context)
continue
if (!isSubdir(configDir, file))
continue
if (!context.filter(code, file))
continue
this.fileContextCache.set(file, context)
return context
}
// try finding a config from disk
if (fs.existsSync(file)) {
let dir = path.dirname(file)
while (isSubdir(this.cwd, dir)) {
if (!await this.configExists(dir))
continue
const context = await this.loadContextInDirectory(dir)
if (context?.filter(code, file)) {
this.fileContextCache.set(file, context)
return context
}
const newDir = path.dirname(dir)
if (newDir === dir)
break
dir = newDir
}
}
this.fileContextCache.set(file, null)
return null
}
async resolveClosestContext(code: string, file: string) {
const cached = this.fileContextCache.get(file)
if (cached)
return cached
for (const [configDir, context] of this.contextsMap) {
if (!context)
continue
if (!isSubdir(configDir, file))
continue
if (!context.filter(code, file))
continue
this.fileContextCache.set(file, context)
return context
}
for (const [configDir, context] of this.contextsMap) {
if (!context)
continue
if (isSubdir(configDir, file)) {
this.fileContextCache.set(file, context)
return context
}
}
return this.defaultContext
}
}