@ -1,22 +1,10 @@
import compression from '@polka/compression'
import fs from 'node:f s'
import { readFile } from 'node:fs/promise s'
import path from 'node:path'
import polka , { type IOptions } from 'polka'
import sirv from 'sirv'
import { resolveConfig } from '../config'
function trimChar ( str : string , char : string ) {
while ( str . charAt ( 0 ) === char ) {
str = str . substring ( 1 )
}
while ( str . charAt ( str . length - 1 ) === char ) {
str = str . substring ( 0 , str . length - 1 )
}
return str
}
export interface ServeOptions {
base? : string
root? : string
@ -26,14 +14,20 @@ export interface ServeOptions {
export async function serve ( options : ServeOptions = { } ) {
const port = options . port ? ? 4173
const config = await resolveConfig ( options . root , 'serve' , 'production' )
const base = trimChar ( options ? . base ? ? config ? . site ? . base ? ? '' , '/' )
const base = ( options ? . base ? ? config ? . site ? . base ? ? '' ) . replace (
/^\/+|\/+$/g ,
''
)
const notAnAsset = ( pathname : string ) = >
! pathname . includes ( ` / ${ config . assetsDir } / ` )
const notFound = fs . readFileSync ( path . resolve ( config . outDir , './404.html' ) )
const notFound = await readFile (
path . resolve ( config . outDir , './404.html' ) ,
'utf8'
)
const onNoMatch : IOptions [ 'onNoMatch' ] = ( req , res ) = > {
res . statusCode = 404
if ( notAnAsset ( req . path ) ) res . write ( notFound . toString ( ) )
if ( notAnAsset ( req . path ) ) res . write ( notFound )
res . end ( )
}
@ -59,11 +53,11 @@ export async function serve(options: ServeOptions = {}) {
` Built site served at http://localhost: ${ port } / ${ base } / `
)
} )
} else {
}
return polka ( { onNoMatch } )
. use ( compress , serve )
. listen ( port , ( ) = > {
config . logger . info ( ` Built site served at http://localhost: ${ port } / ` )
} )
}
}