Skip to content

Commit

Permalink
feat: use polka 1.x
Browse files Browse the repository at this point in the history
Switches to polka 1.x which orders middleware the same way as express,
allowing us to have fallback middleware (0.x doesn't allow multiple
fallbacks).
  • Loading branch information
43081j committed Jul 29, 2024
1 parent a573156 commit 6bc3a37
Show file tree
Hide file tree
Showing 44 changed files with 303 additions and 872 deletions.
1 change: 0 additions & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
},
"devDependencies": {
"@shikijs/vitepress-twoslash": "^1.11.0",
"@types/express": "^4.17.21",
"feed": "^4.2.2",
"vitepress": "1.3.1",
"vue": "^3.4.33"
Expand Down
65 changes: 29 additions & 36 deletions packages/vite/LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,13 +237,6 @@ Repository: git+https://github.com/ampproject/remapping.git
---------------------------------------

## @arr/every
License: MIT
By: Luke Edwards
Repository: lukeed/arr

---------------------------------------

## @jridgewell/gen-mapping
License: MIT
By: Justin Ridgewell
Expand Down Expand Up @@ -1879,35 +1872,6 @@ Repository: https://github.com/rich-harris/magic-string
---------------------------------------

## matchit
License: MIT
By: Luke Edwards
Repository: lukeed/matchit

> The MIT License (MIT)
>
> Copyright (c) Luke Edwards <[email protected]> (lukeed.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------

## merge2
License: MIT
Repository: [email protected]:teambition/merge2.git
Expand Down Expand Up @@ -2680,6 +2644,35 @@ Repository: git://github.com/paulmillr/readdirp.git
---------------------------------------

## regexparam
License: MIT
By: Luke Edwards
Repository: lukeed/regexparam

> The MIT License (MIT)
>
> Copyright (c) Luke Edwards <[email protected]> (lukeed.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------

## requires-port
License: MIT
By: Arnout Kazemier
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
"artichokie": "^0.2.1",
"cac": "^6.7.14",
"chokidar": "^3.6.0",
"polka": "^0.5.2",
"polka": "^1.0.0-next.25",
"convert-source-map": "^2.0.0",
"cors": "^2.8.5",
"cross-spawn": "^7.0.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { cleanUrl, withTrailingSlash } from '../../../shared/utils'
export function baseMiddleware(
rawBase: string,
middlewareMode: boolean,
): Polka.RequestHandler {
): Polka.Middleware {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteBaseMiddleware(req, res, next) {
const url = req.url!
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/htmlFallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function htmlFallbackMiddleware(
root: string,
spaFallback: boolean,
fsUtils: FsUtils = commonFsUtils,
): Polka.RequestHandler {
): Polka.Middleware {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteHtmlFallbackMiddleware(req, res, next) {
if (
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/indexHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ const devHtmlHook: IndexHtmlTransformHook = async (
export function indexHtmlMiddleware(
root: string,
server: ViteDevServer | PreviewServer,
): Polka.RequestHandler {
): Polka.Middleware {
const isDev = isDevServer(server)
const fsUtils = getFsUtils(server.config)

Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/notFound.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Polka } from 'dep-types/polka'

export function notFoundMiddleware(): Polka.RequestHandler {
export function notFoundMiddleware(): Polka.Middleware {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function vite404Middleware(_, res) {
res.statusCode = 404
Expand Down
5 changes: 3 additions & 2 deletions packages/vite/src/node/server/middlewares/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function proxyMiddleware(
httpServer: HttpServer | null,
options: NonNullable<CommonServerOptions['proxy']>,
config: ResolvedConfig,
): Polka.RequestHandler {
): Polka.Middleware {
// lazy require only when proxy is used
const proxies: Record<string, [HttpProxy.Server, ProxyOptions]> = {}

Expand Down Expand Up @@ -196,7 +196,8 @@ export function proxyMiddleware(
} else if (bypassResult === false) {
debug?.(`bypass: ${req.url} -> 404`)
res.statusCode = 404
return res.end()
res.end()
return
}
}

Expand Down
12 changes: 4 additions & 8 deletions packages/vite/src/node/server/middlewares/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const sirvOptions = ({
export function servePublicMiddleware(
server: ViteDevServer,
publicFiles?: Set<string>,
): Polka.RequestHandler {
): Polka.Middleware {
const dir = server.config.publicDir
const serve = sirv(
dir,
Expand Down Expand Up @@ -94,9 +94,7 @@ export function servePublicMiddleware(
}
}

export function serveStaticMiddleware(
server: ViteDevServer,
): Polka.RequestHandler {
export function serveStaticMiddleware(server: ViteDevServer): Polka.Middleware {
const dir = server.config.root
const serve = sirv(
dir,
Expand Down Expand Up @@ -163,9 +161,7 @@ export function serveStaticMiddleware(
}
}

export function serveRawFsMiddleware(
server: ViteDevServer,
): Polka.RequestHandler {
export function serveRawFsMiddleware(server: ViteDevServer): Polka.Middleware {
const serveFromRoot = sirv(
'/',
sirvOptions({ getHeaders: () => server.config.server.headers }),
Expand Down Expand Up @@ -233,7 +229,7 @@ function ensureServingAccess(
url: string,
server: ViteDevServer,
res: ServerResponse,
next: Polka.Next,
next: Polka.NextHandler,
): boolean {
if (isFileServingAllowed(url, server)) {
return true
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createDebugger, prettifyUrl, timeFrom } from '../../utils'

const logTime = createDebugger('vite:time')

export function timeMiddleware(root: string): Polka.RequestHandler {
export function timeMiddleware(root: string): Polka.Middleware {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteTimeMiddleware(req, res, next) {
const start = performance.now()
Expand Down
24 changes: 14 additions & 10 deletions packages/vite/src/node/server/middlewares/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const knownIgnoreList = new Set(['/', '/favicon.ico'])
*/
export function cachedTransformMiddleware(
server: ViteDevServer,
): Polka.RequestHandler {
): Polka.Middleware {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteCachedTransformMiddleware(req, res, next) {
// check if we can return 304 early
Expand All @@ -60,7 +60,8 @@ export function cachedTransformMiddleware(
if (!maybeMixedEtag) {
debugCache?.(`[304] ${prettifyUrl(req.url!, server.config.root)}`)
res.statusCode = 304
return res.end()
res.end()
return
}
}
}
Expand All @@ -69,9 +70,7 @@ export function cachedTransformMiddleware(
}
}

export function transformMiddleware(
server: ViteDevServer,
): Polka.RequestHandler {
export function transformMiddleware(server: ViteDevServer): Polka.Middleware {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`

// check if public dir is inside root dir
Expand Down Expand Up @@ -119,9 +118,10 @@ export function transformMiddleware(
server.config.logger,
)

return send(req, res, JSON.stringify(map), 'json', {
send(req, res, JSON.stringify(map), 'json', {
headers: server.config.server.headers,
})
return
} 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
Expand All @@ -134,20 +134,22 @@ export function transformMiddleware(
names: [],
mappings: ';;;;;;;;;',
}
return send(req, res, JSON.stringify(dummySourceMap), 'json', {
send(req, res, JSON.stringify(dummySourceMap), 'json', {
cacheControl: 'no-cache',
headers: server.config.server.headers,
})
return
}
} else {
const originalUrl = url.replace(/\.map($|\?)/, '$1')
const map = (
await server.moduleGraph.getModuleByUrl(originalUrl, false)
)?.transformResult?.map
if (map) {
return send(req, res, JSON.stringify(map), 'json', {
send(req, res, JSON.stringify(map), 'json', {
headers: server.config.server.headers,
})
return
} else {
return next()
}
Expand Down Expand Up @@ -190,7 +192,8 @@ export function transformMiddleware(
) {
debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`)
res.statusCode = 304
return res.end()
res.end()
return
}
}

Expand All @@ -203,13 +206,14 @@ export function transformMiddleware(
const type = isDirectCSSRequest(url) ? 'css' : 'js'
const isDep =
DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url)
return send(req, res, result.code, type, {
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,
})
return
}
}
} catch (e) {
Expand Down
Loading

0 comments on commit 6bc3a37

Please sign in to comment.