/
registerMissing.ts
273 lines (236 loc) · 8.14 KB
/
registerMissing.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
import colors from 'picocolors'
import {
createOptimizeDepsRun,
getOptimizedDepPath,
getHash,
depsFromOptimizedDepInfo,
newDepOptimizationProcessing
} from '.'
import type {
DepOptimizationMetadata,
DepOptimizationProcessing,
OptimizedDepInfo
} from '.'
import type { ViteDevServer } from '..'
import { resolveSSRExternal } from '../ssr/ssrExternal'
/**
* The amount to wait for requests to register newly found dependencies before triggering
* a re-bundle + page reload
*/
const debounceMs = 100
export function createMissingImporterRegisterFn(
server: ViteDevServer,
initialProcessingPromise: Promise<void>
): (id: string, resolved: string, ssr?: boolean) => OptimizedDepInfo {
const { logger } = server.config
let metadata = server._optimizeDepsMetadata!
let handle: NodeJS.Timeout | undefined
let newDepsDiscovered = false
let depOptimizationProcessing = newDepOptimizationProcessing()
let depOptimizationProcessingQueue: DepOptimizationProcessing[] = []
const resolveEnqueuedProcessingPromises = () => {
// Resolve all the processings (including the ones which were delayed)
for (const processing of depOptimizationProcessingQueue) {
processing.resolve()
}
depOptimizationProcessingQueue = []
}
let enqueuedRerun: (() => void) | undefined
let currentlyProcessing = true
initialProcessingPromise.then(() => {
currentlyProcessing = false
enqueuedRerun?.()
})
async function rerun(ssr: boolean | undefined) {
// debounce time to wait for new missing deps finished, issue a new
// optimization of deps (both old and newly found) once the previous
// optimizeDeps processing is finished
// a succesful completion of the optimizeDeps rerun will end up
// creating new bundled version of all current and discovered deps
// in the cache dir and a new metadata info object assigned
// to server._optimizeDepsMetadata. A fullReload is only issued if
// the previous bundled dependencies have changed.
// if the rerun fails, server._optimizeDepsMetadata remains untouched,
// current discovered deps are cleaned, and a fullReload is issued
// Ensure that rerun is called sequentially
enqueuedRerun = undefined
currentlyProcessing = true
logger.info(
colors.yellow(
`new dependencies found: ${Object.keys(metadata.discovered).join(
', '
)}, updating...`
),
{
timestamp: true
}
)
// All deps, previous known and newly discovered are rebundled,
// respect insertion order to keep the metadata file stable
const newDeps: Record<string, OptimizedDepInfo> = {}
// Clone optimized info objects, fileHash, browserHash may be changed for them
for (const dep of Object.keys(metadata.optimized)) {
newDeps[dep] = { ...metadata.optimized[dep] }
}
// Don't clone discovered info objects, they are read after awaited
for (const dep of Object.keys(metadata.discovered)) {
newDeps[dep] = metadata.discovered[dep]
}
newDepsDiscovered = false
// Add the current depOptimizationProcessing to the queue, these
// promises are going to be resolved once a rerun is committed
depOptimizationProcessingQueue.push(depOptimizationProcessing)
// Create a new promise for the next rerun, discovered missing
// dependencies will be asigned this promise from this point
depOptimizationProcessing = newDepOptimizationProcessing()
let newData: DepOptimizationMetadata | null = null
try {
const optimizeDeps = await createOptimizeDepsRun(
server.config,
true,
false,
metadata,
newDeps,
ssr
)
const processingResult = await optimizeDeps.run()
const commitProcessing = () => {
processingResult.commit()
newData = optimizeDeps.metadata
// update ssr externals
if (ssr) {
server._ssrExternals = resolveSSRExternal(
server.config,
Object.keys(newData.optimized)
)
}
// While optimizeDeps is running, new missing deps may be discovered,
// in which case they will keep being added to metadata.discovered
for (const o of Object.keys(metadata.discovered)) {
if (!newData.optimized[o]) {
newData.discovered[o] = metadata.discovered[o]
}
}
metadata = server._optimizeDepsMetadata = newData
resolveEnqueuedProcessingPromises()
}
if (!processingResult.alteredFiles) {
commitProcessing()
logger.info(colors.green(`✨ new dependencies pre-bundled...`), {
timestamp: true
})
} else {
if (newDepsDiscovered) {
// There are newly discovered deps, and another rerun is about to be
// excecuted. Avoid the current full reload discarding this rerun result
// We don't resolve the processing promise, as they will be resolved
// once a rerun is committed
processingResult.cancel()
logger.info(
colors.green(
`✨ delaying reload as new dependencies have been found...`
),
{
timestamp: true
}
)
} else {
commitProcessing()
logger.info(
colors.green(`✨ dependencies updated, reloading page...`),
{
timestamp: true
}
)
fullReload()
}
}
} catch (e) {
logger.error(
colors.red(`error while updating dependencies:\n${e.stack}`),
{ timestamp: true, error: e }
)
resolveEnqueuedProcessingPromises()
// Reset missing deps, let the server rediscover the dependencies
metadata.discovered = {}
fullReload()
}
currentlyProcessing = false
// @ts-ignore
enqueuedRerun?.()
}
function fullReload() {
// Cached transform results have stale imports (resolved to
// old locations) so they need to be invalidated before the page is
// reloaded.
server.moduleGraph.invalidateAll()
server.ws.send({
type: 'full-reload',
path: '*'
})
}
const discoveredTimestamp = Date.now()
function getDiscoveredBrowserHash(
hash: string,
deps: Record<string, string>,
missing: Record<string, string>
) {
return getHash(
hash +
JSON.stringify(deps) +
JSON.stringify(missing) +
discoveredTimestamp
)
}
return function registerMissingImport(
id: string,
resolved: string,
ssr?: boolean
): OptimizedDepInfo {
const optimized = metadata.optimized[id]
if (optimized) {
return optimized
}
const chunk = metadata.chunks[id]
if (chunk) {
return chunk
}
let missing = metadata.discovered[id]
if (missing) {
// We are already discover this dependency
// It will be processed in the next rerun call
return missing
}
newDepsDiscovered = true
missing = metadata.discovered[id] = {
file: getOptimizedDepPath(id, server.config),
src: resolved,
// Assing a browserHash to this missing dependency that is unique to
// the current state of known + missing deps. If its optimizeDeps run
// doesn't alter the bundled files of previous known dependendencies,
// we don't need a full reload and this browserHash will be kept
browserHash: getDiscoveredBrowserHash(
metadata.hash,
depsFromOptimizedDepInfo(metadata.optimized),
depsFromOptimizedDepInfo(metadata.discovered)
),
// loading of this pre-bundled dep needs to await for its processing
// promise to be resolved
processing: depOptimizationProcessing.promise
}
// Debounced rerun, let other missing dependencies be discovered before
// the running next optimizeDeps
enqueuedRerun = undefined
if (handle) clearTimeout(handle)
handle = setTimeout(() => {
handle = undefined
enqueuedRerun = () => rerun(ssr)
if (!currentlyProcessing) {
enqueuedRerun()
}
}, debounceMs)
// Return the path for the optimized bundle, this path is known before
// esbuild is run to generate the pre-bundle
return missing
}
}