-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathtransform.ts
271 lines (254 loc) · 9.33 KB
/
transform.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
import path from 'node:path'
import fsp from 'node:fs/promises'
import type { Connect } from 'dep-types/connect'
import colors from 'picocolors'
import type { ExistingRawSourceMap } from 'rollup'
import type { ViteDevServer } from '..'
import {
cleanUrl,
createDebugger,
fsPathFromId,
injectQuery,
isImportRequest,
isJSRequest,
normalizePath,
prettifyUrl,
removeImportQuery,
removeTimestampQuery,
unwrapId,
} from '../../utils'
import { send } from '../send'
import { ERR_LOAD_URL, transformRequest } from '../transformRequest'
import { applySourcemapIgnoreList } from '../sourcemap'
import { isHTMLProxy } from '../../plugins/html'
import {
DEP_VERSION_RE,
FS_PREFIX,
NULL_BYTE_PLACEHOLDER,
} from '../../constants'
import {
isCSSRequest,
isDirectCSSRequest,
isDirectRequest,
} from '../../plugins/css'
import {
ERR_OPTIMIZE_DEPS_PROCESSING_ERROR,
ERR_OUTDATED_OPTIMIZED_DEP,
} from '../../plugins/optimizedDeps'
import { ERR_CLOSED_SERVER } from '../pluginContainer'
import { getDepsOptimizer } from '../../optimizer'
import { urlRE } from '../../plugins/asset'
const debugCache = createDebugger('vite:cache')
const knownIgnoreList = new Set(['/', '/favicon.ico'])
export function transformMiddleware(
server: ViteDevServer,
): Connect.NextHandleFunction {
const {
config: { root, logger },
moduleGraph,
} = server
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return async function viteTransformMiddleware(req, res, next) {
if (req.method !== 'GET' || knownIgnoreList.has(req.url!)) {
return next()
}
let url: string
try {
url = decodeURI(removeTimestampQuery(req.url!)).replace(
NULL_BYTE_PLACEHOLDER,
'\0',
)
} catch (e) {
return next(e)
}
const withoutQuery = cleanUrl(url)
try {
const isSourceMap = withoutQuery.endsWith('.map')
// since we generate source map references, handle those requests here
if (isSourceMap) {
const depsOptimizer = getDepsOptimizer(server.config, false) // non-ssr
if (depsOptimizer?.isOptimizedDepUrl(url)) {
// If the browser is requesting a source map for an optimized dep, it
// means that the dependency has already been pre-bundled and loaded
const sourcemapPath = url.startsWith(FS_PREFIX)
? fsPathFromId(url)
: normalizePath(path.resolve(root, url.slice(1)))
try {
const map = JSON.parse(
await fsp.readFile(sourcemapPath, 'utf-8'),
) as ExistingRawSourceMap
applySourcemapIgnoreList(
map,
sourcemapPath,
server.config.server.sourcemapIgnoreList,
logger,
)
return send(req, res, JSON.stringify(map), 'json', {
headers: server.config.server.headers,
})
} catch (e) {
// Outdated source map request for optimized deps, this isn't an error
// but part of the normal flow when re-optimizing after missing deps
// Send back an empty source map so the browser doesn't issue warnings
const dummySourceMap = {
version: 3,
file: sourcemapPath.replace(/\.map$/, ''),
sources: [],
sourcesContent: [],
names: [],
mappings: ';;;;;;;;;',
}
return send(req, res, JSON.stringify(dummySourceMap), 'json', {
cacheControl: 'no-cache',
headers: server.config.server.headers,
})
}
} else {
const originalUrl = url.replace(/\.map($|\?)/, '$1')
const map = (await moduleGraph.getModuleByUrl(originalUrl, false))
?.transformResult?.map
if (map) {
return send(req, res, JSON.stringify(map), 'json', {
headers: server.config.server.headers,
})
} else {
return next()
}
}
}
// check if public dir is inside root dir
const publicDir = normalizePath(server.config.publicDir)
const rootDir = normalizePath(server.config.root)
if (publicDir.startsWith(rootDir)) {
const publicPath = `${publicDir.slice(rootDir.length)}/`
// warn explicit public paths
if (url.startsWith(publicPath)) {
let warning: string
if (isImportRequest(url)) {
const rawUrl = removeImportQuery(url)
if (urlRE.test(url)) {
warning =
`Assets in the public directory are served at the root path.\n` +
`Instead of ${colors.cyan(rawUrl)}, use ${colors.cyan(
rawUrl.replace(publicPath, '/'),
)}.`
} else {
warning =
'Assets in public directory cannot be imported from JavaScript.\n' +
`If you intend to import that asset, put the file in the src directory, and use ${colors.cyan(
rawUrl.replace(publicPath, '/src/'),
)} instead of ${colors.cyan(rawUrl)}.\n` +
`If you intend to use the URL of that asset, use ${colors.cyan(
injectQuery(rawUrl.replace(publicPath, '/'), 'url'),
)}.`
}
} else {
warning =
`files in the public directory are served at the root path.\n` +
`Instead of ${colors.cyan(url)}, use ${colors.cyan(
url.replace(publicPath, '/'),
)}.`
}
logger.warn(colors.yellow(warning))
}
}
if (
isJSRequest(url) ||
isImportRequest(url) ||
isCSSRequest(url) ||
isHTMLProxy(url)
) {
// strip ?import
url = removeImportQuery(url)
// Strip valid id prefix. This is prepended to resolved Ids that are
// not valid browser import specifiers by the importAnalysis plugin.
url = unwrapId(url)
// for CSS, we need to differentiate between normal CSS requests and
// imports
if (
isCSSRequest(url) &&
!isDirectRequest(url) &&
req.headers.accept?.includes('text/css')
) {
url = injectQuery(url, 'direct')
}
// check if we can return 304 early
const ifNoneMatch = req.headers['if-none-match']
if (
ifNoneMatch &&
(await moduleGraph.getModuleByUrl(url, false))?.transformResult
?.etag === ifNoneMatch
) {
debugCache?.(`[304] ${prettifyUrl(url, root)}`)
res.statusCode = 304
return res.end()
}
// resolve, load and transform using the plugin container
const result = await transformRequest(url, server, {
html: req.headers.accept?.includes('text/html'),
})
if (result) {
const depsOptimizer = getDepsOptimizer(server.config, false) // non-ssr
const type = isDirectCSSRequest(url) ? 'css' : 'js'
const isDep =
DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url)
return send(req, res, result.code, type, {
etag: result.etag,
// allow browser to cache npm deps!
cacheControl: isDep ? 'max-age=31536000,immutable' : 'no-cache',
headers: server.config.server.headers,
map: result.map,
})
}
}
} catch (e) {
if (e?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
// Skip if response has already been sent
if (!res.writableEnded) {
res.statusCode = 504 // status code request timeout
res.statusMessage = 'Optimize Deps Processing Error'
res.end()
}
// This timeout is unexpected
logger.error(e.message)
return
}
if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
// Skip if response has already been sent
if (!res.writableEnded) {
res.statusCode = 504 // status code request timeout
res.statusMessage = 'Outdated Optimize Dep'
res.end()
}
// We don't need to log an error in this case, the request
// is outdated because new dependencies were discovered and
// the new pre-bundle dependencies have changed.
// A full-page reload has been issued, and these old requests
// can't be properly fulfilled. This isn't an unexpected
// error but a normal part of the missing deps discovery flow
return
}
if (e?.code === ERR_CLOSED_SERVER) {
// Skip if response has already been sent
if (!res.writableEnded) {
res.statusCode = 504 // status code request timeout
res.statusMessage = 'Outdated Request'
res.end()
}
// We don't need to log an error in this case, the request
// is outdated because new dependencies were discovered and
// the new pre-bundle dependencies have changed.
// A full-page reload has been issued, and these old requests
// can't be properly fulfilled. This isn't an unexpected
// error but a normal part of the missing deps discovery flow
return
}
if (e?.code === ERR_LOAD_URL) {
// Let other middleware handle if we can't load the url via transformRequest
return next()
}
return next(e)
}
next()
}
}