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 00000000..5f48a9e4 Binary files /dev/null and b/example/static/favicon.ico differ 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/"));