( server: ViteDevServer, )
| 199 | } |
| 200 | |
| 201 | export function serveRawFsMiddleware( |
| 202 | server: ViteDevServer, |
| 203 | ): Connect.NextHandleFunction { |
| 204 | const serveFromRoot = sirv( |
| 205 | '/', |
| 206 | sirvOptions({ |
| 207 | config: server.config, |
| 208 | getHeaders: () => server.config.server.headers, |
| 209 | }), |
| 210 | ) |
| 211 | |
| 212 | // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` |
| 213 | return function viteServeRawFsMiddleware(req, res, next) { |
| 214 | // In some cases (e.g. linked monorepos) files outside of root will |
| 215 | // reference assets that are also out of served root. In such cases |
| 216 | // the paths are rewritten to `/@fs/` prefixed paths and must be served by |
| 217 | // searching based from fs root. |
| 218 | if (req.url!.startsWith(FS_PREFIX)) { |
| 219 | const url = new URL(req.url!, 'http://example.com') |
| 220 | const pathname = decodeURIIfPossible(url.pathname) |
| 221 | if (pathname === undefined) { |
| 222 | return next() |
| 223 | } |
| 224 | |
| 225 | let newPathname = pathname.slice(FS_PREFIX.length) |
| 226 | if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, '') |
| 227 | url.pathname = encodeURI(newPathname) |
| 228 | req.url = url.href.slice(url.origin.length) |
| 229 | |
| 230 | try { |
| 231 | serveFromRoot(req, res, next) |
| 232 | } catch (e) { |
| 233 | if (e && 'code' in e && e.code === ERR_DENIED_FILE) { |
| 234 | respondWithAccessDenied(e.path, server, res) |
| 235 | return |
| 236 | } |
| 237 | throw e |
| 238 | } |
| 239 | } else { |
| 240 | next() |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Check if the url is allowed to be served, via the `server.fs` config. |
no test coverage detected