Skip to content

Commit

Permalink
chore: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
magne4000 committed Oct 16, 2024
1 parent 662d027 commit 4913908
Show file tree
Hide file tree
Showing 11 changed files with 51 additions and 268 deletions.
41 changes: 5 additions & 36 deletions packages/vike-node/src/runtime/adapters/connectToWeb.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export { connectToWeb, connectToWebFallback }
export { connectToWeb }

import type { IncomingMessage } from 'node:http'
import { Readable } from 'node:stream'
import { DUMMY_BASE_URL } from '../constants.js'
import type { ConnectMiddleware, ConnectMiddlewareBoolean, WebHandler } from '../types.js'
import { flattenHeaders } from '../utils/header-utils.js'
import { createServerResponse } from './createServerResponse.js'
import { DUMMY_BASE_URL } from '../constants.js'

const statusCodesWithoutBody = [
100, // Continue
Expand All @@ -20,41 +20,10 @@ const statusCodesWithoutBody = [
/**
* Converts a Connect-style middleware to a web-compatible request handler.
*
* @param {ConnectMiddleware} handler - The Connect-style middleware function to be converted.
* @param {ConnectMiddleware | ConnectMiddlewareBoolean} handler - The Connect-style middleware function to be converted.
* @returns {WebHandler} A function that handles web requests and returns a Response or undefined.
*/
function connectToWeb(handler: ConnectMiddleware): WebHandler {
return async (request: Request): Promise<Response | undefined> => {
const req = createIncomingMessage(request)
const { res, onReadable } = createServerResponse(req)

return new Promise<Response | undefined>((resolve, reject) => {
onReadable(({ readable, headers, statusCode }) => {
const responseBody = statusCodesWithoutBody.includes(statusCode)
? null
: (Readable.toWeb(readable) as ReadableStream)
resolve(
new Response(responseBody, {
status: statusCode,
headers: flattenHeaders(headers)
})
)
})

const next = (error?: unknown) => {
if (error) {
reject(error instanceof Error ? error : new Error(String(error)))
} else {
resolve(undefined)
}
}

Promise.resolve(handler(req, res, next)).catch(next)
})
}
}

function connectToWebFallback(handler: ConnectMiddlewareBoolean): WebHandler {
function connectToWeb(handler: ConnectMiddleware | ConnectMiddlewareBoolean): WebHandler {
return async (request: Request): Promise<Response | undefined> => {
const req = createIncomingMessage(request)
const { res, onReadable } = createServerResponse(req)
Expand Down Expand Up @@ -83,7 +52,7 @@ function connectToWebFallback(handler: ConnectMiddlewareBoolean): WebHandler {
try {
const handled = await handler(req, res, next)

if (!handled) {
if (handled === false) {
res.destroy()
resolve(undefined)
}
Expand Down
3 changes: 1 addition & 2 deletions packages/vike-node/src/runtime/frameworks/connect.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
export { vike }

import type { IncomingMessage, ServerResponse } from 'http'
import { createHandler } from '../handler-node-only.js'
import type { NextFunction, VikeOptions } from '../types.js'
import { globalStore } from '../globalStore.js'
import type { NextFunction, VikeOptions } from '../types.js'

/**
* Creates middleware for Express-like frameworks to handle Vike requests.
Expand Down
121 changes: 0 additions & 121 deletions packages/vike-node/src/runtime/handler-node-only.ts

This file was deleted.

44 changes: 0 additions & 44 deletions packages/vike-node/src/runtime/handler-web-and-node.ts

This file was deleted.

12 changes: 0 additions & 12 deletions packages/vike-node/src/runtime/handler-web-only.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/vike-node/src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type VikeOptions = {
export type ConnectMiddleware<
PlatformRequest extends IncomingMessage = IncomingMessage,
PlatformResponse extends ServerResponse = ServerResponse
> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void
> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>
export type ConnectMiddlewareBoolean<
PlatformRequest extends IncomingMessage = IncomingMessage,
PlatformResponse extends ServerResponse = ServerResponse
Expand Down
25 changes: 2 additions & 23 deletions packages/vike-node/src/runtime/utils/header-utils.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,8 @@
export { flattenHeaders, groupHeaders, parseHeaders }
export { flattenHeaders, parseHeaders }

import type { OutgoingHttpHeaders } from 'http'
import type { OutgoingHttpHeaders } from 'node:http'
import { HeadersProvided } from '../types.js'

function groupHeaders(headers: [string, string][]): [string, string | string[]][] {
const grouped: { [key: string]: string | string[] } = {}

headers.forEach(([key, value]) => {
if (grouped[key]) {
// If the key already exists, append the new value
if (Array.isArray(grouped[key])) {
;(grouped[key] as string[]).push(value)
} else {
grouped[key] = [grouped[key] as string, value]
}
} else {
// If the key doesn't exist, add it to the object
grouped[key] = value
}
})

// Convert the object back to an array
return Object.entries(grouped)
}

function flattenHeaders(headers: OutgoingHttpHeaders): [string, string][] {
const flatHeaders: [string, string][] = []

Expand Down
29 changes: 29 additions & 0 deletions packages/vike-node/src/runtime/utils/resolve-static-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { dirname, isAbsolute, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { isVercel } from '../../utils/isVercel.js'
import type { VikeOptions } from '../types.js'

export function resolveStaticConfig(static_: VikeOptions['static']): false | { root: string; cache: boolean } {
// Disable static file serving for Vercel
// Vercel will serve static files on its own
// See vercel.json > outputDirectory
if (isVercel()) return false
if (static_ === false) return false

const argv1 = process.argv[1]
const entrypointDirAbs = argv1
? dirname(isAbsolute(argv1) ? argv1 : join(process.cwd(), argv1))
: dirname(fileURLToPath(import.meta.url))
const defaultStaticDir = join(entrypointDirAbs, '..', 'client')

if (static_ === true || static_ === undefined) {
return { root: defaultStaticDir, cache: true }
}
if (typeof static_ === 'string') {
return { root: static_, cache: true }
}
return {
root: static_.root ?? defaultStaticDir,
cache: static_.cache ?? true
}
}
18 changes: 0 additions & 18 deletions packages/vike-node/src/runtime/utils/writeHttpResponse.ts

This file was deleted.

20 changes: 10 additions & 10 deletions packages/vike-node/src/runtime/vike-handler.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { parseHeaders } from './utils/header-utils.js'
import { renderPage as _renderPage } from 'vike/server'
import type { ConnectMiddleware, VikeHttpResponse, VikeOptions } from './types.js'
import { type Get, pipe, type UniversalHandler, type UniversalMiddleware } from '@universal-middleware/core'
import type { IncomingMessage, ServerResponse } from 'http'
import compressMiddlewareFactory from '@universal-middleware/compress'
import { globalStore } from './globalStore.js'
import { type Get, type UniversalHandler, type UniversalMiddleware, pipe } from '@universal-middleware/core'
import { renderPage as _renderPage } from 'vike/server'
import { assert } from '../utils/assert.js'
import type { IncomingMessage, ServerResponse } from 'http'
import { connectToWebFallback } from './adapters/connectToWeb.js'
import { isVercel } from '../utils/isVercel.js'
import { connectToWeb } from './adapters/connectToWeb.js'
import { globalStore } from './globalStore.js'
import type { ConnectMiddleware, VikeHttpResponse, VikeOptions } from './types.js'
import { parseHeaders } from './utils/header-utils.js'

export { renderPage, renderPageWeb }

Expand Down Expand Up @@ -80,7 +80,7 @@ export const renderPageHandler = ((options?) => async (request, context, runtime

if (nodeReq) {
globalStore.setupHMRProxy(nodeReq)
const { resolveStaticConfig } = await import('./handler-node-only.js')
const { resolveStaticConfig } = await import('./utils/resolve-static-config.js')
staticConfig = resolveStaticConfig(options?.static)
}

Expand All @@ -91,7 +91,7 @@ export const renderPageHandler = ((options?) => async (request, context, runtime
if (handled) return handled
} else if (nodeReq) {
if (staticConfig) {
const handled = await connectToWebFallback(serveStaticFiles)(request)
const handled = await connectToWeb(serveStaticFiles)(request)
if (handled) return handled
}
}
Expand Down Expand Up @@ -133,7 +133,7 @@ export const renderPageHandler = ((options?) => async (request, context, runtime
export const renderPageUniversal = ((options?) =>
pipe(renderPageCompress(options), renderPageHandler(options))) satisfies Get<[options: VikeOptions], UniversalHandler>

const web = connectToWebFallback(handleViteDevServer)
const web = connectToWeb(handleViteDevServer)

function handleViteDevServer(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
return new Promise<boolean>((resolve) => {
Expand Down
Loading

0 comments on commit 4913908

Please sign in to comment.