From 75afa6dacaf7e06a504a556b6f4ca8c7b1b265c9 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Sat, 25 Sep 2021 13:37:46 +0200 Subject: [PATCH] feat: add static file support (#58) This commit adds support for serving static files. Static can be placed into the `/static` directory (as a sibling of the `/pages` directory). --- example/deps.ts | 1 + example/main.ts | 2 +- example/static/favicon.ico | Bin 0 -> 18102 bytes src/cli/init.ts | 3 +- src/server/context.ts | 101 +++++++++++++++++++++++++++++++++++-- src/server/deps.ts | 8 ++- src/server/mod.ts | 30 +++-------- tests/fixture/main.ts | 2 +- tests/main_test.ts | 5 +- 9 files changed, 117 insertions(+), 35 deletions(-) create mode 100644 example/static/favicon.ico diff --git a/example/deps.ts b/example/deps.ts index d561d51f..43d6b91e 100644 --- a/example/deps.ts +++ b/example/deps.ts @@ -1,5 +1,6 @@ /// /// +/// /// /// diff --git a/example/main.ts b/example/main.ts index 8d2b7ce2..df7d2f2d 100644 --- a/example/main.ts +++ b/example/main.ts @@ -1,4 +1,4 @@ import { start } from "../server.ts"; import routes from "./routes.gen.ts"; -start(routes); +await start(routes); diff --git a/example/static/favicon.ico b/example/static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..5f48a9e4e3953c8fdff28a4d6ac6ac702e84f037 GIT binary patch literal 18102 zcmdU$35-@n5`fg>tFEf9>VB`g zy1M@;s)|}fojOI5_lo}2DvJIQMNv&n{d1ooQ8YtveFP^YLQ#*GEQ$nQ1oRb}e@j{| zY1=^u9kjh&yLM|DaMWc%YpIwmX|E)ssZXCiX4kG==IyuNHiHHYq7E8pec*YqB*&-a zfddB`A7;*+XMgJvSmwi?6Jq1-o1O9FTeaU z#sB^H-<#I0Tf?J$W!paV&_m7Xr=MbHaFdL zQ;a&-`?j( z2Xn#+Cn$-_moHy#=^l9C0f!qpbg1%@!%H8SgAYE~+;PVpj*h}Fzx-l`4DH~A&kwH~zrzkY%v^KLHRg{${)oxhvuBS%ha-TeN7A!iDG* z$J#z(#0a-O{Q2j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k_kP Gc>f1$%Wo_I literal 0 HcmV?d00001 diff --git a/src/cli/init.ts b/src/cli/init.ts index 0d260917..c60b2ab6 100644 --- a/src/cli/init.ts +++ b/src/cli/init.ts @@ -141,13 +141,14 @@ export const handler = (_req: Request): Response => { const serverUrl = new URL("../../server.ts", import.meta.url); const MAIN_TS = `/// /// +/// /// /// import { start } from "${serverUrl}"; import routes from "./routes.gen.ts"; -start(routes); +await start(routes); `; await Deno.writeTextFile( join(directory, "main.ts"), diff --git a/src/server/context.ts b/src/server/context.ts index 297749e1..6dcc372d 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -1,4 +1,11 @@ -import { extname, mediaTypeLookup, router } from "./deps.ts"; +import { + extname, + fromFileUrl, + mediaTypeLookup, + router, + toFileUrl, + walk, +} from "./deps.ts"; import { Routes } from "./mod.ts"; import { Bundler } from "./bundle.ts"; import { INTERNAL_PREFIX } from "./constants.ts"; @@ -15,11 +22,17 @@ import { render as internalRender } from "./render.tsx"; export class ServerContext { #pages: Page[]; + #staticFiles: [URL, string][]; #bundler: Bundler; #renderer: Renderer; - constructor(pages: Page[], renderer: Renderer) { + constructor( + pages: Page[], + staticFiles: [URL, string][], + renderer: Renderer, + ) { this.#pages = pages; + this.#staticFiles = staticFiles; this.#renderer = renderer; this.#bundler = new Bundler(pages); } @@ -27,7 +40,7 @@ export class ServerContext { /** * Process the routes into individual components and pages. */ - static fromRoutes(routes: Routes): ServerContext { + static async fromRoutes(routes: Routes): Promise { // Get the routes' base URL. const baseUrl = new URL("./", routes.baseUrl).href; @@ -74,16 +87,55 @@ export class ServerContext { } sortRoutes(pages); - return new ServerContext(pages, renderer); + const staticFiles: [URL, string][] = []; + try { + const staticFolder = new URL("./static", routes.baseUrl); + // TODO(lucacasonato): remove the extranious Deno.readDir when + // https://github.com/denoland/deno_std/issues/1310 is fixed. + for await (const _ of Deno.readDir(fromFileUrl(staticFolder))) { + // do nothing + } + const entires = walk(fromFileUrl(staticFolder), { + includeFiles: true, + includeDirs: false, + followSymlinks: false, + }); + for await (const entry of entires) { + const path = toFileUrl(entry.path); + const subpath = path.href.substring(staticFolder.href.length); + staticFiles.push([path, subpath]); + } + } catch (err) { + if (err instanceof Deno.errors.NotFound) { + // Do nothing. + } else { + throw err; + } + } + return new ServerContext(pages, staticFiles, renderer); + } + + /** + * This functions returns a request handler that handles all routes required + * by fresh, including static files. + */ + handler(): router.RequestHandler { + return router.router(this.#routes()); } /** * This function returns all routes required by fresh as an extended * path-to-regex, to handler mapping. */ - routes(): router.Routes { + #routes(): router.Routes { const routes: router.Routes = {}; + // Add the static file routes. + for (const [fullPath, path] of this.#staticFiles) { + const route = sanitizePathToRegex(path); + routes[`GET@${route}`] = this.#staticFileHandler(fullPath); + } + for (const page of this.#pages) { const bundlePath = `/${page.name}.js`; const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : []; @@ -135,6 +187,22 @@ export class ServerContext { return routes; } + #staticFileHandler(fullPath: URL): router.MatchHandler { + return async (_req: Request) => { + try { + const data = await Deno.readFile(fullPath); + const contentType = mediaTypeLookup(extname(fullPath.href)) ?? + "application/octet-stream"; + return new Response(data, { headers: { "content-type": contentType } }); + } catch (err) { + if (err instanceof Deno.errors.NotFound) { + return new Response("404 Not Found", { status: 404 }); + } + throw err; + } + }; + } + /** * Returns a router that contains all fresh routes. Should be mounted at * constants.INTERNAL_PREFIX @@ -219,3 +287,26 @@ function pathToRoute(path: string): string { .join("/"); return route; } + +// Normalize a path for use in a URL. Returns null if the path is unparsable. +export function normalizeURLPath(path: string): string | null { + try { + const pathUrl = new URL("file:///"); + pathUrl.pathname = path; + return pathUrl.pathname; + } catch { + return null; + } +} + +function sanitizePathToRegex(path: string): string { + return path + .replaceAll("\*", "\\*") + .replaceAll("\+", "\\+") + .replaceAll("\?", "\\?") + .replaceAll("\{", "\\{") + .replaceAll("\}", "\\}") + .replaceAll("\(", "\\(") + .replaceAll("\)", "\\)") + .replaceAll("\:", "\\:"); +} diff --git a/src/server/deps.ts b/src/server/deps.ts index 5ec2ad83..f94110bc 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -2,7 +2,13 @@ export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.14"; // -- std -- -export { extname } from "https://deno.land/std@0.108.0/path/mod.ts"; +export { + extname, + fromFileUrl, + toFileUrl, +} from "https://deno.land/std@0.108.0/path/mod.ts"; +export { walk } from "https://deno.land/std@0.108.0/fs/walk.ts"; +export { listenAndServe } from "https://deno.land/std@0.108.0/http/server.ts"; // -- router -- export * as router from "https://crux.land/router@0.0.4"; diff --git a/src/server/mod.ts b/src/server/mod.ts index d7994fc2..e473f420 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -1,5 +1,5 @@ import { ServerContext } from "./context.ts"; -import { router } from "./deps.ts"; +import { listenAndServe } from "./deps.ts"; import { PageModule, RendererModule } from "./types.ts"; export type { Handler, HandlerContext, Handlers } from "./types.ts"; export { RenderContext } from "./render.tsx"; @@ -10,28 +10,10 @@ export interface Routes { baseUrl: string; } -export { router, ServerContext }; +export { ServerContext }; -export function start(routes: Routes) { - const ctx = ServerContext.fromRoutes(routes); - const app = router.router(ctx.routes()); - serve(app); -} - -async function serve(handler: (req: Request) => Response | Promise) { - async function handleConn(conn: Deno.Conn) { - const httpConn = Deno.serveHttp(conn); - for await (const e of httpConn) { - e.respondWith(handler(e.request)) - .catch((e) => console.error("Failed handing a request:", e)); - } - } - - const listener = Deno.listen({ port: 8000 }); - const addr = listener.addr as Deno.NetAddr; - console.log(`Listening on http://${addr.hostname}:${addr.port}`); - for await (const conn of listener) { - handleConn(conn) - .catch((e) => console.error("Failed serving a connection:", e)); - } +export async function start(routes: Routes) { + const ctx = await ServerContext.fromRoutes(routes); + console.log("Server listening on http://localhost:8000"); + await listenAndServe(":8000", ctx.handler()); } diff --git a/tests/fixture/main.ts b/tests/fixture/main.ts index f332138d..8ac8fc54 100644 --- a/tests/fixture/main.ts +++ b/tests/fixture/main.ts @@ -1,4 +1,4 @@ import { start } from "../../server.ts"; import routes from "./routes.gen.ts"; -start(routes); +await start(routes); diff --git a/tests/main_test.ts b/tests/main_test.ts index 454dcc0a..4915c469 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -1,8 +1,9 @@ -import { router as r, ServerContext } from "../server.ts"; +import { ServerContext } from "../server.ts"; import { assert, assertEquals, assertStringIncludes } from "./deps.ts"; import routes from "./fixture/routes.gen.ts"; -const router = r.router(ServerContext.fromRoutes(routes).routes()); +const ctx = await ServerContext.fromRoutes(routes); +const router = ctx.handler(); Deno.test("/ page prerender", async () => { const resp = await router(new Request("https://fresh.deno.dev/"));