-
-
Notifications
You must be signed in to change notification settings - Fork 6.1k
/
hmr.ts
488 lines (448 loc) · 12.5 KB
/
hmr.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import fs from 'fs'
import path from 'path'
import chalk from 'chalk'
import { createServer, ViteDevServer } from '..'
import { createDebugger, normalizePath } from '../utils'
import { ModuleNode } from './moduleGraph'
import { Update } from 'types/hmrPayload'
import { CLIENT_DIR } from '../constants'
import { RollupError } from 'rollup'
import match from 'minimatch'
import { Server } from 'http'
import { isCSSRequest } from '../plugins/css'
export const debugHmr = createDebugger('vite:hmr')
const normalizedClientDir = normalizePath(CLIENT_DIR)
export interface HmrOptions {
protocol?: string
host?: string
port?: number
clientPort?: number
path?: string
timeout?: number
overlay?: boolean
server?: Server
}
export interface HmrContext {
file: string
timestamp: number
modules: Array<ModuleNode>
read: () => string | Promise<string>
server: ViteDevServer
}
function getShortName(file: string, root: string) {
return file.startsWith(root + '/') ? path.posix.relative(root, file) : file
}
export async function handleHMRUpdate(
file: string,
server: ViteDevServer
): Promise<any> {
const { ws, config, moduleGraph } = server
const shortFile = getShortName(file, config.root)
const isConfig = file === config.configFile
const isConfigDependency = config.configFileDependencies.some(
(name) => file === path.resolve(name)
)
const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env')
if (isConfig || isConfigDependency || isEnv) {
// auto restart server
debugHmr(`[config change] ${chalk.dim(shortFile)}`)
config.logger.info(
chalk.green(
`${path.relative(process.cwd(), file)} changed, restarting server...`
),
{ clear: true, timestamp: true }
)
await restartServer(server)
return
}
debugHmr(`[file change] ${chalk.dim(shortFile)}`)
// (dev only) the client itself cannot be hot updated.
if (file.startsWith(normalizedClientDir)) {
ws.send({
type: 'full-reload',
path: '*'
})
return
}
const mods = moduleGraph.getModulesByFile(file)
// check if any plugin wants to perform custom HMR handling
const timestamp = Date.now()
const hmrContext: HmrContext = {
file,
timestamp,
modules: mods ? [...mods] : [],
read: () => readModifiedFile(file),
server
}
for (const plugin of config.plugins) {
if (plugin.handleHotUpdate) {
const filteredModules = await plugin.handleHotUpdate(hmrContext)
if (filteredModules) {
hmrContext.modules = filteredModules
}
}
}
if (!hmrContext.modules.length) {
// html file cannot be hot updated
if (file.endsWith('.html')) {
config.logger.info(chalk.green(`page reload `) + chalk.dim(shortFile), {
clear: true,
timestamp: true
})
ws.send({
type: 'full-reload',
path: config.server.middlewareMode
? '*'
: '/' + normalizePath(path.relative(config.root, file))
})
} else {
// loaded but not in the module graph, probably not js
debugHmr(`[no modules matched] ${chalk.dim(shortFile)}`)
}
return
}
updateModules(shortFile, hmrContext.modules, timestamp, server)
}
function updateModules(
file: string,
modules: ModuleNode[],
timestamp: number,
{ config, ws }: ViteDevServer
) {
const updates: Update[] = []
const invalidatedModules = new Set<ModuleNode>()
let needFullReload = false
for (const mod of modules) {
invalidate(mod, timestamp, invalidatedModules)
if (needFullReload) {
continue
}
const boundaries = new Set<{
boundary: ModuleNode
acceptedVia: ModuleNode
}>()
const hasDeadEnd = propagateUpdate(mod, boundaries)
if (hasDeadEnd) {
needFullReload = true
continue
}
updates.push(
...[...boundaries].map(({ boundary, acceptedVia }) => ({
type: `${boundary.type}-update` as Update['type'],
timestamp,
path: boundary.url,
acceptedPath: acceptedVia.url
}))
)
}
if (needFullReload) {
config.logger.info(chalk.green(`page reload `) + chalk.dim(file), {
clear: true,
timestamp: true
})
ws.send({
type: 'full-reload'
})
} else {
config.logger.info(
updates
.map(({ path }) => chalk.green(`hmr update `) + chalk.dim(path))
.join('\n'),
{ clear: true, timestamp: true }
)
ws.send({
type: 'update',
updates
})
}
}
export async function handleFileAddUnlink(
file: string,
server: ViteDevServer,
isUnlink = false
): Promise<void> {
const modules = [...(server.moduleGraph.getModulesByFile(file) ?? [])]
if (isUnlink && file in server._globImporters) {
delete server._globImporters[file]
} else {
for (const i in server._globImporters) {
const { module, importGlobs } = server._globImporters[i]
for (const { base, pattern } of importGlobs) {
if (match(file, pattern) || match(path.relative(base, file), pattern)) {
modules.push(module)
// We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()`
// calls get fresh glob import results with(out) the newly added(/removed) `file`.
server.moduleGraph.onFileChange(module.file!)
break
}
}
}
}
if (modules.length > 0) {
updateModules(
getShortName(file, server.config.root),
modules,
Date.now(),
server
)
}
}
function propagateUpdate(
node: ModuleNode,
boundaries: Set<{
boundary: ModuleNode
acceptedVia: ModuleNode
}>,
currentChain: ModuleNode[] = [node]
): boolean /* hasDeadEnd */ {
if (node.isSelfAccepting) {
boundaries.add({
boundary: node,
acceptedVia: node
})
// additionally check for CSS importers, since a PostCSS plugin like
// Tailwind JIT may register any file as a dependency to a CSS file.
for (const importer of node.importers) {
if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
propagateUpdate(importer, boundaries, currentChain.concat(importer))
}
}
return false
}
if (!node.importers.size) {
return true
}
// #3716, #3913
// For a non-CSS file, if all of its importers are CSS files (registered via
// PostCSS plugins) it should be considered a dead end and force full reload.
if (
!isCSSRequest(node.url) &&
[...node.importers].every((i) => isCSSRequest(i.url))
) {
return true
}
for (const importer of node.importers) {
const subChain = currentChain.concat(importer)
if (importer.acceptedHmrDeps.has(node)) {
boundaries.add({
boundary: importer,
acceptedVia: node
})
continue
}
if (currentChain.includes(importer)) {
// circular deps is considered dead end
return true
}
if (propagateUpdate(importer, boundaries, subChain)) {
return true
}
}
return false
}
function invalidate(mod: ModuleNode, timestamp: number, seen: Set<ModuleNode>) {
if (seen.has(mod)) {
return
}
seen.add(mod)
mod.lastHMRTimestamp = timestamp
mod.transformResult = null
mod.ssrModule = null
mod.ssrTransformResult = null
mod.importers.forEach((importer) => {
if (!importer.acceptedHmrDeps.has(mod)) {
invalidate(importer, timestamp, seen)
}
})
}
export function handlePrunedModules(
mods: Set<ModuleNode>,
{ ws }: ViteDevServer
): void {
// update the disposed modules' hmr timestamp
// since if it's re-imported, it should re-apply side effects
// and without the timestamp the browser will not re-import it!
const t = Date.now()
mods.forEach((mod) => {
mod.lastHMRTimestamp = t
debugHmr(`[dispose] ${chalk.dim(mod.file)}`)
})
ws.send({
type: 'prune',
paths: [...mods].map((m) => m.url)
})
}
const enum LexerState {
inCall,
inSingleQuoteString,
inDoubleQuoteString,
inTemplateString,
inArray
}
/**
* Lex import.meta.hot.accept() for accepted deps.
* Since hot.accept() can only accept string literals or array of string
* literals, we don't really need a heavy @babel/parse call on the entire source.
*
* @returns selfAccepts
*/
export function lexAcceptedHmrDeps(
code: string,
start: number,
urls: Set<{ url: string; start: number; end: number }>
): boolean {
let state: LexerState = LexerState.inCall
// the state can only be 2 levels deep so no need for a stack
let prevState: LexerState = LexerState.inCall
let currentDep: string = ''
function addDep(index: number) {
urls.add({
url: currentDep,
start: index - currentDep.length - 1,
end: index + 1
})
currentDep = ''
}
for (let i = start; i < code.length; i++) {
const char = code.charAt(i)
switch (state) {
case LexerState.inCall:
case LexerState.inArray:
if (char === `'`) {
prevState = state
state = LexerState.inSingleQuoteString
} else if (char === `"`) {
prevState = state
state = LexerState.inDoubleQuoteString
} else if (char === '`') {
prevState = state
state = LexerState.inTemplateString
} else if (/\s/.test(char)) {
continue
} else {
if (state === LexerState.inCall) {
if (char === `[`) {
state = LexerState.inArray
} else {
// reaching here means the first arg is neither a string literal
// nor an Array literal (direct callback) or there is no arg
// in both case this indicates a self-accepting module
return true // done
}
} else if (state === LexerState.inArray) {
if (char === `]`) {
return false // done
} else if (char === ',') {
continue
} else {
error(i)
}
}
}
break
case LexerState.inSingleQuoteString:
if (char === `'`) {
addDep(i)
if (prevState === LexerState.inCall) {
// accept('foo', ...)
return false
} else {
state = prevState
}
} else {
currentDep += char
}
break
case LexerState.inDoubleQuoteString:
if (char === `"`) {
addDep(i)
if (prevState === LexerState.inCall) {
// accept('foo', ...)
return false
} else {
state = prevState
}
} else {
currentDep += char
}
break
case LexerState.inTemplateString:
if (char === '`') {
addDep(i)
if (prevState === LexerState.inCall) {
// accept('foo', ...)
return false
} else {
state = prevState
}
} else if (char === '$' && code.charAt(i + 1) === '{') {
error(i)
} else {
currentDep += char
}
break
default:
throw new Error('unknown import.meta.hot lexer state')
}
}
return false
}
function error(pos: number) {
const err = new Error(
`import.meta.accept() can only accept string literals or an ` +
`Array of string literals.`
) as RollupError
err.pos = pos
throw err
}
// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
// change event and sometimes this can be too early and get an empty buffer.
// Poll until the file's modified time has changed before reading again.
async function readModifiedFile(file: string): Promise<string> {
const content = fs.readFileSync(file, 'utf-8')
if (!content) {
const mtime = fs.statSync(file).mtimeMs
await new Promise((r) => {
let n = 0
const poll = async () => {
n++
const newMtime = fs.statSync(file).mtimeMs
if (newMtime !== mtime || n > 10) {
r(0)
} else {
setTimeout(poll, 10)
}
}
setTimeout(poll, 10)
})
return fs.readFileSync(file, 'utf-8')
} else {
return content
}
}
async function restartServer(server: ViteDevServer) {
// @ts-ignore
global.__vite_start_time = Date.now()
const { port } = server.config.server
await server.close()
let newServer = null
try {
newServer = await createServer(server.config.inlineConfig)
} catch (err) {
server.config.logger.error(err.message, {
timestamp: true,
})
return
}
for (const key in newServer) {
if (key !== 'app') {
// @ts-ignore
server[key] = newServer[key]
}
}
if (!server.config.server.middlewareMode) {
await server.listen(port, true)
} else {
server.config.logger.info('server restarted.', { timestamp: true })
}
}