-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
workspace.ts
450 lines (387 loc) · 14.2 KB
/
workspace.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import { promises as fs } from 'node:fs'
import fg from 'fast-glob'
import mm from 'micromatch'
import { dirname, isAbsolute, join, relative, resolve, toNamespacedPath } from 'pathe'
import type { TransformResult, ViteDevServer, InlineConfig as ViteInlineConfig } from 'vite'
import { ViteNodeRunner } from 'vite-node/client'
import { ViteNodeServer } from 'vite-node/server'
import c from 'picocolors'
import { createBrowserServer } from '../integrations/browser/server'
import type { ProvidedContext, ResolvedConfig, UserConfig, UserWorkspaceConfig, Vitest } from '../types'
import { deepMerge } from '../utils'
import type { Typechecker } from '../typecheck/typechecker'
import type { BrowserProvider } from '../types/browser'
import { getBrowserProvider } from '../integrations/browser'
import { createDefer } from '../public/utils'
import { isBrowserEnabled, resolveConfig } from './config'
import { WorkspaceVitestPlugin } from './plugins/workspace'
import { createViteServer } from './vite'
import type { GlobalSetupFile } from './globalSetup'
import { loadGlobalSetupFiles } from './globalSetup'
import { divider } from './reporters/renderers/utils'
interface InitializeProjectOptions extends UserWorkspaceConfig {
workspaceConfigPath: string
extends?: string
}
export async function initializeProject(workspacePath: string | number, ctx: Vitest, options: InitializeProjectOptions) {
const project = new WorkspaceProject(workspacePath, ctx, options)
const configFile = options.extends
? resolve(dirname(options.workspaceConfigPath), options.extends)
: (typeof workspacePath === 'number' || workspacePath.endsWith('/'))
? false
: workspacePath
const root = options.root || (
typeof workspacePath === 'number'
? undefined
: workspacePath.endsWith('/') ? workspacePath : dirname(workspacePath)
)
return new Promise<() => Promise<WorkspaceProject>>((resolve, reject) => {
const resolution = createDefer<WorkspaceProject>()
let configResolved = false
const config: ViteInlineConfig = {
...options,
root,
logLevel: 'error',
configFile,
// this will make "mode": "test" | "benchmark" inside defineConfig
mode: options.test?.mode || options.mode || ctx.config.mode,
plugins: [
{
name: 'vitest:workspace:resolve',
configResolved() {
configResolved = true
resolve(() => resolution)
},
},
...options.plugins || [],
WorkspaceVitestPlugin(project, { ...options, root, workspacePath }),
],
}
createViteServer(config)
.then(() => resolution.resolve(project))
.catch((err) => {
if (configResolved)
resolution.reject(err)
else
reject(err)
})
return project
})
}
export class WorkspaceProject {
configOverride: Partial<ResolvedConfig> | undefined
config!: ResolvedConfig
server!: ViteDevServer
vitenode!: ViteNodeServer
runner!: ViteNodeRunner
browser?: ViteDevServer
typechecker?: Typechecker
closingPromise: Promise<unknown> | undefined
browserProvider: BrowserProvider | undefined
browserState: {
files: string[]
resolve: () => void
reject: (v: unknown) => void
} | undefined
testFilesList: string[] | null = null
private _globalSetups: GlobalSetupFile[] | undefined
private _provided: ProvidedContext = {} as any
constructor(
public path: string | number,
public ctx: Vitest,
public options?: InitializeProjectOptions,
) { }
getName(): string {
return this.config.name || ''
}
isCore() {
return this.ctx.getCoreWorkspaceProject() === this
}
provide = (key: string, value: unknown) => {
try {
structuredClone(value)
}
catch (err) {
throw new Error(`Cannot provide "${key}" because it's not serializable.`, {
cause: err,
})
}
(this._provided as any)[key] = value
}
getProvidedContext(): ProvidedContext {
if (this.isCore())
return this._provided
// globalSetup can run even if core workspace is not part of the test run
// so we need to inherit its provided context
return {
...this.ctx.getCoreWorkspaceProject().getProvidedContext(),
...this._provided,
}
}
async initializeGlobalSetup() {
if (this._globalSetups)
return
this._globalSetups = await loadGlobalSetupFiles(this.runner, this.config.globalSetup)
try {
for (const globalSetupFile of this._globalSetups) {
const teardown = await globalSetupFile.setup?.({ provide: this.provide, config: this.config })
if (teardown == null || !!globalSetupFile.teardown)
continue
if (typeof teardown !== 'function')
throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`)
globalSetupFile.teardown = teardown
}
}
catch (e) {
this.logger.error(`\n${c.red(divider(c.bold(c.inverse(' Error during global setup '))))}`)
await this.logger.printError(e)
process.exit(1)
}
}
async teardownGlobalSetup() {
if (!this._globalSetups)
return
for (const globalSetupFile of [...this._globalSetups].reverse()) {
try {
await globalSetupFile.teardown?.()
}
catch (error) {
this.logger.error(`error during global teardown of ${globalSetupFile.file}`, error)
await this.logger.printError(error)
process.exitCode = 1
}
}
}
get logger() {
return this.ctx.logger
}
// it's possible that file path was imported with different queries (?raw, ?url, etc)
getModulesByFilepath(file: string) {
const set = this.server.moduleGraph.getModulesByFile(file)
|| this.browser?.moduleGraph.getModulesByFile(file)
return set || new Set()
}
getModuleById(id: string) {
return this.server.moduleGraph.getModuleById(id)
|| this.browser?.moduleGraph.getModuleById(id)
}
getSourceMapModuleById(id: string): TransformResult['map'] | undefined {
const mod = this.server.moduleGraph.getModuleById(id)
return mod?.ssrTransformResult?.map || mod?.transformResult?.map
}
getBrowserSourceMapModuleById(id: string): TransformResult['map'] | undefined {
return this.browser?.moduleGraph.getModuleById(id)?.transformResult?.map
}
get reporters() {
return this.ctx.reporters
}
async globTestFiles(filters: string[] = []) {
const dir = this.config.dir || this.config.root
const { include, exclude, includeSource } = this.config
const typecheck = this.config.typecheck
const [testFiles, typecheckTestFiles] = await Promise.all([
typecheck.enabled && typecheck.only ? [] : this.globAllTestFiles(include, exclude, includeSource, dir),
typecheck.enabled ? this.globFiles(typecheck.include, typecheck.exclude, dir) : [],
])
return this.filterFiles([...testFiles, ...typecheckTestFiles], filters, dir)
}
async globAllTestFiles(include: string[], exclude: string[], includeSource: string[] | undefined, cwd: string) {
if (this.testFilesList)
return this.testFilesList
const testFiles = await this.globFiles(include, exclude, cwd)
if (includeSource?.length) {
const files = await this.globFiles(includeSource, exclude, cwd)
await Promise.all(files.map(async (file) => {
try {
const code = await fs.readFile(file, 'utf-8')
if (this.isInSourceTestFile(code))
testFiles.push(file)
}
catch {
return null
}
}))
}
this.testFilesList = testFiles
return testFiles
}
isTestFile(id: string) {
return this.testFilesList && this.testFilesList.includes(id)
}
async globFiles(include: string[], exclude: string[], cwd: string) {
const globOptions: fg.Options = {
dot: true,
cwd,
ignore: exclude,
}
const files = await fg(include, globOptions)
return files.map(file => resolve(cwd, file))
}
async isTargetFile(id: string, source?: string): Promise<boolean> {
const relativeId = relative(this.config.dir || this.config.root, id)
if (mm.isMatch(relativeId, this.config.exclude))
return false
if (mm.isMatch(relativeId, this.config.include))
return true
if (this.config.includeSource?.length && mm.isMatch(relativeId, this.config.includeSource)) {
source = source || await fs.readFile(id, 'utf-8')
return this.isInSourceTestFile(source)
}
return false
}
isInSourceTestFile(code: string) {
return code.includes('import.meta.vitest')
}
filterFiles(testFiles: string[], filters: string[], dir: string) {
if (filters.length && process.platform === 'win32')
filters = filters.map(f => toNamespacedPath(f))
if (filters.length) {
return testFiles.filter((t) => {
const testFile = relative(dir, t).toLocaleLowerCase()
return filters.some((f) => {
const relativePath = f.endsWith('/') ? join(relative(dir, f), '/') : relative(dir, f)
// if filter is a full file path, we should include it if it's in the same folder
if (isAbsolute(f)) {
// the file is inside the filter path, so we should always include it,
// we don't include ../file because this condition is always true if
// the file doens't exist which cause false positives
if (relativePath === '..' || relativePath === '../' || relativePath.startsWith('../..'))
return true
}
return testFile.includes(f.toLocaleLowerCase()) || testFile.includes(relativePath.toLocaleLowerCase())
})
})
}
return testFiles
}
async initBrowserServer(configFile: string | undefined) {
if (!this.isBrowserEnabled())
return
await this.browser?.close()
this.browser = await createBrowserServer(this, configFile)
}
static createBasicProject(ctx: Vitest) {
const project = new WorkspaceProject(ctx.config.name || ctx.config.root, ctx)
project.vitenode = ctx.vitenode
project.server = ctx.server
project.runner = ctx.runner
project.config = ctx.config
return project
}
static async createCoreProject(ctx: Vitest) {
const project = WorkspaceProject.createBasicProject(ctx)
await project.initBrowserServer(ctx.server.config.configFile)
return project
}
async setServer(options: UserConfig, server: ViteDevServer) {
this.config = resolveConfig(
this.ctx.mode,
{
...options,
coverage: this.ctx.config.coverage,
},
server.config,
)
this.server = server
this.vitenode = new ViteNodeServer(server, this.config.server)
const node = this.vitenode
this.runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
fetchModule(id: string) {
return node.fetchModule(id)
},
resolveId(id: string, importer?: string) {
return node.resolveId(id, importer)
},
})
await this.initBrowserServer(this.server.config.configFile)
}
isBrowserEnabled() {
return isBrowserEnabled(this.config)
}
getSerializableConfig() {
const optimizer = this.config.deps?.optimizer
const poolOptions = this.config.poolOptions
// Resolve from server.config to avoid comparing against default value
const isolate = this.server?.config?.test?.isolate
return deepMerge({
...this.config,
poolOptions: {
forks: {
singleFork: poolOptions?.forks?.singleFork ?? this.ctx.config.poolOptions?.forks?.singleFork ?? false,
isolate: poolOptions?.forks?.isolate ?? isolate ?? this.ctx.config.poolOptions?.forks?.isolate ?? true,
},
threads: {
singleThread: poolOptions?.threads?.singleThread ?? this.ctx.config.poolOptions?.threads?.singleThread ?? false,
isolate: poolOptions?.threads?.isolate ?? isolate ?? this.ctx.config.poolOptions?.threads?.isolate ?? true,
},
vmThreads: {
singleThread: poolOptions?.vmThreads?.singleThread ?? this.ctx.config.poolOptions?.vmThreads?.singleThread ?? false,
},
},
reporters: [],
deps: {
...this.config.deps,
optimizer: {
web: {
enabled: optimizer?.web?.enabled ?? true,
},
ssr: {
enabled: optimizer?.ssr?.enabled ?? true,
},
},
},
snapshotOptions: {
...this.ctx.config.snapshotOptions,
expand: this.config.snapshotOptions.expand ?? this.ctx.config.snapshotOptions.expand,
resolveSnapshotPath: undefined,
},
onConsoleLog: undefined!,
onStackTrace: undefined!,
sequence: {
...this.ctx.config.sequence,
sequencer: undefined!,
},
benchmark: {
...this.config.benchmark,
reporters: [],
},
inspect: this.ctx.config.inspect,
inspectBrk: this.ctx.config.inspectBrk,
inspector: this.ctx.config.inspector,
alias: [],
includeTaskLocation: this.config.includeTaskLocation ?? this.ctx.config.includeTaskLocation,
env: {
...this.server?.config.env,
...this.config.env,
},
}, this.ctx.configOverride || {} as any) as ResolvedConfig
}
close() {
if (!this.closingPromise) {
this.closingPromise = Promise.all([
this.server.close(),
this.typechecker?.stop(),
this.browser?.close(),
].filter(Boolean)).then(() => this._provided = {} as any)
}
return this.closingPromise
}
async initBrowserProvider() {
if (!this.isBrowserEnabled())
return
if (this.browserProvider)
return
const Provider = await getBrowserProvider(this.config.browser, this)
this.browserProvider = new Provider()
const browser = this.config.browser.name
const supportedBrowsers = this.browserProvider.getSupportedBrowsers()
if (!browser)
throw new Error(`[${this.getName()}] Browser name is required. Please, set \`test.browser.name\` option manually.`)
if (supportedBrowsers.length && !supportedBrowsers.includes(browser))
throw new Error(`[${this.getName()}] Browser "${browser}" is not supported by the browser provider "${this.browserProvider.name}". Supported browsers: ${supportedBrowsers.join(', ')}.`)
const providerOptions = this.config.browser.providerOptions
await this.browserProvider.initialize(this, { browser, options: providerOptions })
}
}