-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathmoduleGraph.ts
487 lines (437 loc) · 15.5 KB
/
moduleGraph.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
import { extname } from 'node:path'
import type { ModuleInfo, PartialResolvedId } from 'rollup'
import { isDirectCSSRequest } from '../plugins/css'
import {
normalizePath,
removeImportQuery,
removeTimestampQuery,
} from '../utils'
import { FS_PREFIX } from '../constants'
import { cleanUrl } from '../../shared/utils'
import type { TransformResult } from './transformRequest'
export class EnvironmentModuleNode {
environment: string
/**
* Public served url path, starts with /
*/
url: string
/**
* Resolved file system path + query
*/
id: string | null = null
file: string | null = null
type: 'js' | 'css'
info?: ModuleInfo
meta?: Record<string, any>
importers = new Set<EnvironmentModuleNode>()
importedModules = new Set<EnvironmentModuleNode>()
acceptedHmrDeps = new Set<EnvironmentModuleNode>()
acceptedHmrExports: Set<string> | null = null
importedBindings: Map<string, Set<string>> | null = null
isSelfAccepting?: boolean
transformResult: TransformResult | null = null
// ssrModule and ssrError are no longer needed. They are on the module runner module cache.
// Once `ssrLoadModule` is re-implemented on top of the new APIs, we can delete these.
ssrModule: Record<string, any> | null = null
ssrError: Error | null = null
lastHMRTimestamp = 0
/**
* `import.meta.hot.invalidate` is called by the client.
* If there's multiple clients, multiple `invalidate` request is received.
* This property is used to dedupe those request to avoid multiple updates happening.
* @internal
*/
lastHMRInvalidationReceived = false
lastInvalidationTimestamp = 0
/**
* If the module only needs to update its imports timestamp (e.g. within an HMR chain),
* it is considered soft-invalidated. In this state, its `transformResult` should exist,
* and the next `transformRequest` for this module will replace the timestamps.
*
* By default the value is `undefined` if it's not soft/hard-invalidated. If it gets
* soft-invalidated, this will contain the previous `transformResult` value. If it gets
* hard-invalidated, this will be set to `'HARD_INVALIDATED'`.
* @internal
*/
invalidationState: TransformResult | 'HARD_INVALIDATED' | undefined
/**
* The module urls that are statically imported in the code. This information is separated
* out from `importedModules` as only importers that statically import the module can be
* soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated.
* @internal
*/
staticImportedUrls?: Set<string>
/**
* @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
*/
constructor(url: string, environment: string, setIsSelfAccepting = true) {
this.environment = environment
this.url = url
this.type = isDirectCSSRequest(url) ? 'css' : 'js'
if (setIsSelfAccepting) {
this.isSelfAccepting = false
}
}
}
export type ResolvedUrl = [
url: string,
resolvedId: string,
meta: object | null | undefined,
]
export class EnvironmentModuleGraph {
environment: string
urlToModuleMap = new Map<string, EnvironmentModuleNode>()
idToModuleMap = new Map<string, EnvironmentModuleNode>()
etagToModuleMap = new Map<string, EnvironmentModuleNode>()
// a single file may corresponds to multiple modules with different queries
fileToModulesMap = new Map<string, Set<EnvironmentModuleNode>>()
/**
* @internal
*/
_unresolvedUrlToModuleMap = new Map<
string,
Promise<EnvironmentModuleNode> | EnvironmentModuleNode
>()
/**
* @internal
*/
_resolveId: (url: string) => Promise<PartialResolvedId | null>
/** @internal */
_hasResolveFailedErrorModules = new Set<EnvironmentModuleNode>()
constructor(
environment: string,
resolveId: (url: string) => Promise<PartialResolvedId | null>,
) {
this.environment = environment
this._resolveId = resolveId
}
async getModuleByUrl(
rawUrl: string,
): Promise<EnvironmentModuleNode | undefined> {
// Quick path, if we already have a module for this rawUrl (even without extension)
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl))
const mod = this._getUnresolvedUrlToModule(rawUrl)
if (mod) {
return mod
}
const [url] = await this._resolveUrl(rawUrl)
return this.urlToModuleMap.get(url)
}
getModuleById(id: string): EnvironmentModuleNode | undefined {
return this.idToModuleMap.get(removeTimestampQuery(id))
}
getModulesByFile(file: string): Set<EnvironmentModuleNode> | undefined {
return this.fileToModulesMap.get(file)
}
onFileChange(file: string): void {
const mods = this.getModulesByFile(file)
if (mods) {
const seen = new Set<EnvironmentModuleNode>()
mods.forEach((mod) => {
this.invalidateModule(mod, seen)
})
}
}
onFileDelete(file: string): void {
const mods = this.getModulesByFile(file)
if (mods) {
mods.forEach((mod) => {
mod.importedModules.forEach((importedMod) => {
importedMod.importers.delete(mod)
})
})
}
}
invalidateModule(
mod: EnvironmentModuleNode,
seen = new Set<EnvironmentModuleNode>(),
timestamp: number = Date.now(),
isHmr: boolean = false,
/** @internal */
softInvalidate = false,
): void {
const prevInvalidationState = mod.invalidationState
// Handle soft invalidation before the `seen` check, as consecutive soft/hard invalidations can
// cause the final soft invalidation state to be different.
// If soft invalidated, save the previous `transformResult` so that we can reuse and transform the
// import timestamps only in `transformRequest`. If there's no previous `transformResult`, hard invalidate it.
if (softInvalidate) {
mod.invalidationState ??= mod.transformResult ?? 'HARD_INVALIDATED'
}
// If hard invalidated, further soft invalidations have no effect until it's reset to `undefined`
else {
mod.invalidationState = 'HARD_INVALIDATED'
}
// Skip updating the module if it was already invalidated before and the invalidation state has not changed
if (seen.has(mod) && prevInvalidationState === mod.invalidationState) {
return
}
seen.add(mod)
if (isHmr) {
mod.lastHMRTimestamp = timestamp
mod.lastHMRInvalidationReceived = false
} else {
// Save the timestamp for this invalidation, so we can avoid caching the result of possible already started
// processing being done for this module
mod.lastInvalidationTimestamp = timestamp
}
// Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline
// Invalidating the transform result is enough to ensure this module is re-processed next time it is requested
const etag = mod.transformResult?.etag
if (etag) this.etagToModuleMap.delete(etag)
mod.transformResult = null
mod.ssrModule = null
mod.ssrError = null
mod.importers.forEach((importer) => {
if (!importer.acceptedHmrDeps.has(mod)) {
// If the importer statically imports the current module, we can soft-invalidate the importer
// to only update the import timestamps. If it's not statically imported, e.g. watched/glob file,
// we can only soft invalidate if the current module was also soft-invalidated. A soft-invalidation
// doesn't need to trigger a re-load and re-transform of the importer.
// But we exclude direct CSS files as those cannot be soft invalidated.
const shouldSoftInvalidateImporter =
(importer.staticImportedUrls?.has(mod.url) || softInvalidate) &&
importer.type !== 'css'
this.invalidateModule(
importer,
seen,
timestamp,
isHmr,
shouldSoftInvalidateImporter,
)
}
})
this._hasResolveFailedErrorModules.delete(mod)
}
invalidateAll(): void {
const timestamp = Date.now()
const seen = new Set<EnvironmentModuleNode>()
this.idToModuleMap.forEach((mod) => {
this.invalidateModule(mod, seen, timestamp)
})
}
/**
* Update the module graph based on a module's updated imports information
* If there are dependencies that no longer have any importers, they are
* returned as a Set.
*
* @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
* This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
*/
async updateModuleInfo(
mod: EnvironmentModuleNode,
importedModules: Set<string | EnvironmentModuleNode>,
importedBindings: Map<string, Set<string>> | null,
acceptedModules: Set<string | EnvironmentModuleNode>,
acceptedExports: Set<string> | null,
isSelfAccepting: boolean,
/** @internal */
staticImportedUrls?: Set<string>,
): Promise<Set<EnvironmentModuleNode> | undefined> {
mod.isSelfAccepting = isSelfAccepting
const prevImports = mod.importedModules
let noLongerImported: Set<EnvironmentModuleNode> | undefined
let resolvePromises = []
let resolveResults = new Array(importedModules.size)
let index = 0
// update import graph
for (const imported of importedModules) {
const nextIndex = index++
if (typeof imported === 'string') {
resolvePromises.push(
this.ensureEntryFromUrl(imported).then((dep) => {
dep.importers.add(mod)
resolveResults[nextIndex] = dep
}),
)
} else {
imported.importers.add(mod)
resolveResults[nextIndex] = imported
}
}
if (resolvePromises.length) {
await Promise.all(resolvePromises)
}
const nextImports = new Set(resolveResults)
mod.importedModules = nextImports
// remove the importer from deps that were imported but no longer are.
prevImports.forEach((dep) => {
if (!mod.importedModules.has(dep)) {
dep.importers.delete(mod)
if (!dep.importers.size) {
// dependency no longer imported
;(noLongerImported || (noLongerImported = new Set())).add(dep)
}
}
})
// update accepted hmr deps
resolvePromises = []
resolveResults = new Array(acceptedModules.size)
index = 0
for (const accepted of acceptedModules) {
const nextIndex = index++
if (typeof accepted === 'string') {
resolvePromises.push(
this.ensureEntryFromUrl(accepted).then((dep) => {
resolveResults[nextIndex] = dep
}),
)
} else {
resolveResults[nextIndex] = accepted
}
}
if (resolvePromises.length) {
await Promise.all(resolvePromises)
}
mod.acceptedHmrDeps = new Set(resolveResults)
mod.staticImportedUrls = staticImportedUrls
// update accepted hmr exports
mod.acceptedHmrExports = acceptedExports
mod.importedBindings = importedBindings
return noLongerImported
}
async ensureEntryFromUrl(
rawUrl: string,
setIsSelfAccepting = true,
): Promise<EnvironmentModuleNode> {
return this._ensureEntryFromUrl(rawUrl, setIsSelfAccepting)
}
/**
* @internal
*/
async _ensureEntryFromUrl(
rawUrl: string,
setIsSelfAccepting = true,
// Optimization, avoid resolving the same url twice if the caller already did it
resolved?: PartialResolvedId,
): Promise<EnvironmentModuleNode> {
// Quick path, if we already have a module for this rawUrl (even without extension)
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl))
let mod = this._getUnresolvedUrlToModule(rawUrl)
if (mod) {
return mod
}
const modPromise = (async () => {
const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, resolved)
mod = this.idToModuleMap.get(resolvedId)
if (!mod) {
mod = new EnvironmentModuleNode(
url,
this.environment,
setIsSelfAccepting,
)
if (meta) mod.meta = meta
this.urlToModuleMap.set(url, mod)
mod.id = resolvedId
this.idToModuleMap.set(resolvedId, mod)
const file = (mod.file = cleanUrl(resolvedId))
let fileMappedModules = this.fileToModulesMap.get(file)
if (!fileMappedModules) {
fileMappedModules = new Set()
this.fileToModulesMap.set(file, fileMappedModules)
}
fileMappedModules.add(mod)
}
// multiple urls can map to the same module and id, make sure we register
// the url to the existing module in that case
else if (!this.urlToModuleMap.has(url)) {
this.urlToModuleMap.set(url, mod)
}
this._setUnresolvedUrlToModule(rawUrl, mod)
return mod
})()
// Also register the clean url to the module, so that we can short-circuit
// resolving the same url twice
this._setUnresolvedUrlToModule(rawUrl, modPromise)
return modPromise
}
// some deps, like a css file referenced via @import, don't have its own
// url because they are inlined into the main css import. But they still
// need to be represented in the module graph so that they can trigger
// hmr in the importing css file.
createFileOnlyEntry(file: string): EnvironmentModuleNode {
file = normalizePath(file)
let fileMappedModules = this.fileToModulesMap.get(file)
if (!fileMappedModules) {
fileMappedModules = new Set()
this.fileToModulesMap.set(file, fileMappedModules)
}
const url = `${FS_PREFIX}${file}`
for (const m of fileMappedModules) {
if (m.url === url || m.id === file) {
return m
}
}
const mod = new EnvironmentModuleNode(url, this.environment)
mod.file = file
fileMappedModules.add(mod)
return mod
}
// for incoming urls, it is important to:
// 1. remove the HMR timestamp query (?t=xxxx) and the ?import query
// 2. resolve its extension so that urls with or without extension all map to
// the same module
async resolveUrl(url: string): Promise<ResolvedUrl> {
url = removeImportQuery(removeTimestampQuery(url))
const mod = await this._getUnresolvedUrlToModule(url)
if (mod?.id) {
return [mod.url, mod.id, mod.meta]
}
return this._resolveUrl(url)
}
updateModuleTransformResult(
mod: EnvironmentModuleNode,
result: TransformResult | null,
): void {
if (this.environment === 'client') {
const prevEtag = mod.transformResult?.etag
if (prevEtag) this.etagToModuleMap.delete(prevEtag)
if (result?.etag) this.etagToModuleMap.set(result.etag, mod)
}
mod.transformResult = result
}
getModuleByEtag(etag: string): EnvironmentModuleNode | undefined {
return this.etagToModuleMap.get(etag)
}
/**
* @internal
*/
_getUnresolvedUrlToModule(
url: string,
): Promise<EnvironmentModuleNode> | EnvironmentModuleNode | undefined {
return this._unresolvedUrlToModuleMap.get(url)
}
/**
* @internal
*/
_setUnresolvedUrlToModule(
url: string,
mod: Promise<EnvironmentModuleNode> | EnvironmentModuleNode,
): void {
this._unresolvedUrlToModuleMap.set(url, mod)
}
/**
* @internal
*/
async _resolveUrl(
url: string,
alreadyResolved?: PartialResolvedId,
): Promise<ResolvedUrl> {
const resolved = alreadyResolved ?? (await this._resolveId(url))
const resolvedId = resolved?.id || url
if (
url !== resolvedId &&
!url.includes('\0') &&
!url.startsWith(`virtual:`)
) {
const ext = extname(cleanUrl(resolvedId))
if (ext) {
const pathname = cleanUrl(url)
if (!pathname.endsWith(ext)) {
url = pathname + ext + url.slice(pathname.length)
}
}
}
return [url, resolvedId, resolved?.meta]
}
}