import{Path}from"../utils/path";importlogfrom"utils/log";import{makeFileResponse}from"./utils";import{readFile}from"../file";import{createServer}from"./createServer";importDirectoryfrom"../file/filetype/directory";import{homePage}from"../pages/home";import{getPageSettings}from"./utils";/** * Serve the files in a directory. * @param {*} absolutePathToDirectory primary directory we should source files from. * @param {*} fallbackDirPath path to directory we should fall back to serving. */constdirectoryServer=({
absolutePathToDirectory,
fallbackDirPath,
url,
port,
siteName,
websocketPath,}: {absolutePathToDirectory: Path;fallbackDirPath: string;url: string;port: number;siteName: string;websocketPath: string;})=>{letpageSettings=getPageSettings({
url,
port,
siteName,
absolutePathToDirectory,
fallbackDirPath,});constdir=readFile(absolutePathToDirectory,pageSettings)asunknownasDirectory;letfallbackDir: Directory;try{if(fallbackDirPath){fallbackDir=readFile(fallbackDirPath,pageSettings)asunknownasDirectory;}}catch(e: any){log.debug("Error finding fallback dir:",e.message);}if(!dir.isDirectory()){thrownewError(`Received path '${absolutePathToDirectory}' is not a directory`);}pageSettings=getPageSettings({
url,
port,
siteName,absolutePathToDirectory: dir.path,
fallbackDirPath,});createServer({
url,
port,
websocketPath,onRequest: ({ path }: {path: Path})=>{letpathToUse=Path.create(path);// If we request the root, serve up the home pageif(["","/","/index","/index.html"].includes(pathToUse.toString())){returnmakeFileResponse(homePage(pageSettings),{
...pageSettings,
websocketPath,});}if(path.name==="index.html"){// if the path is a directory, serve the parent like an html filepathToUse=Path.create(path.parent.toString()+".html");}// we look for a directory with .html,// then fall back to types.htmlletfile=dir.findFile(pathToUse,pageSettings);if(!file){// if we can't find the file, attempt to find it in a fallback directory.file=fallbackDir?.findFile(pathToUse,pageSettings);}if(!file){returnnewResponse("Not found",{status: 404});}returnmakeFileResponse(file,{ ...pageSettings, websocketPath });},onSocketConnected: (ws)=>{log.hotReload("hot reload socket connected");},});};export{directoryServer};