diff --git a/src/runtime/utils.ts b/src/runtime/utils.ts index 426b1a7f..b69d2e4b 100644 --- a/src/runtime/utils.ts +++ b/src/runtime/utils.ts @@ -1 +1,13 @@ +export const INTERNAL_PREFIX = "/_frsh"; +export const STATIC_PREFIX = `/static`; + export const IS_BROWSER = typeof document !== "undefined"; + +/** + * Return a path "hashed" with the BUILD_ID. of a static file + * Such path will be served by the server with a Cache-Control of 1 year. + * @param path a path to a file in the static folder asset. e.g. /style.css + */ +export function asset(path: string) { + return `${INTERNAL_PREFIX}${STATIC_PREFIX}/${__FRSH_BUILD_ID}${path}`; +} diff --git a/src/server/bundle.ts b/src/server/bundle.ts index 1e235fa7..ef337336 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -1,3 +1,4 @@ +import { BUILD_ID } from "./constants.ts"; import { denoPlugin, esbuild, toFileUrl } from "./deps.ts"; import { Island } from "./types.ts"; @@ -40,6 +41,7 @@ export class Bundler { await ensureEsbuildInialized(); const bundle = await esbuild.build({ bundle: true, + define: { __FRSH_BUILD_ID: `"${BUILD_ID}"` }, entryPoints, format: "esm", metafile: true, diff --git a/src/server/constants.ts b/src/server/constants.ts index f8cf3506..c8946bba 100644 --- a/src/server/constants.ts +++ b/src/server/constants.ts @@ -1,4 +1,5 @@ -export const INTERNAL_PREFIX = "/_frsh"; +import { INTERNAL_PREFIX } from "../runtime/utils.ts"; + export const REFRESH_JS_URL = `${INTERNAL_PREFIX}/refresh.js`; export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`; export const BUILD_ID = Deno.env.get("DENO_DEPLOYMENT_ID") || @@ -10,8 +11,13 @@ export function bundleAssetUrl(path: string) { return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`; } +globalThis.__FRSH_BUILD_ID = BUILD_ID; + declare global { interface Crypto { randomUUID(): string; } + + // deno-lint-ignore no-var + var __FRSH_BUILD_ID: string; } diff --git a/src/server/context.ts b/src/server/context.ts index 09a170d7..d776ed52 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -10,13 +10,7 @@ import { } from "./deps.ts"; import { Manifest } from "./mod.ts"; import { Bundler } from "./bundle.ts"; -import { - ALIVE_URL, - BUILD_ID, - INTERNAL_PREFIX, - JS_PREFIX, - REFRESH_JS_URL, -} from "./constants.ts"; +import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts"; import DefaultErrorHandler from "./default_error_page.tsx"; import { AppModule, @@ -36,6 +30,7 @@ import { import { render as internalRender } from "./render.tsx"; import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts"; import { h } from "../runtime/deps.ts"; +import { asset, INTERNAL_PREFIX } from "../runtime/utils.ts"; interface StaticFile { /** The URL to the static file on disk. */ @@ -319,6 +314,9 @@ export class ServerContext { } // Add the static file routes. + // each files has 2 static routes: + // - one serving the file at its location without a "cache bursting" mechanism + // - one containing the BUILD_ID in the path that can be cached for ( const { localUrl, path, size, contentType, etag } of this.#staticFiles ) { @@ -329,6 +327,15 @@ export class ServerContext { contentType, etag, ); + + const hashedRoute = sanitizePathToRegex(asset(path)); + routes[`GET@${hashedRoute}`] = this.#staticFileHandler( + localUrl, + size, + contentType, + etag, + true, + ); } const genRender = ( @@ -442,18 +449,25 @@ export class ServerContext { size: number, contentType: string, etag: string, + isCacheable?: boolean, ): router.MatchHandler { return async (req: Request) => { if (req.headers.get("if-none-match") === etag) { return new Response(null, { status: 304 }); } else { const resp = await fetch(localUrl); + const headers = new Headers({ + "content-type": contentType, + "content-length": String(size), + "etag": etag, + }); + + if (isCacheable) { + headers.set("Cache-Control", "public, max-age=31536000, immutable"); + } + return new Response(resp.body, { - headers: { - "content-type": contentType, - "content-length": String(size), - "etag": etag, - }, + headers, }); } }; diff --git a/src/server/render.tsx b/src/server/render.tsx index f21f9f8d..89b4bf7b 100644 --- a/src/server/render.tsx +++ b/src/server/render.tsx @@ -5,7 +5,6 @@ import { ComponentType, h, options, - VNode, } from "../runtime/deps.ts"; import { AppModule, @@ -18,7 +17,7 @@ import { import { HEAD_CONTEXT } from "../runtime/head.ts"; import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts"; import { ContentSecurityPolicy } from "../runtime/csp.ts"; -import { bundleAssetUrl } from "./constants.ts"; +import { BUILD_ID, bundleAssetUrl } from "./constants.ts"; export interface RenderOptions { page: Page | UnknownPage | ErrorPage; diff --git a/tests/fixture/islands/Test.tsx b/tests/fixture/islands/Test.tsx index 32cc5c05..9baedbe4 100644 --- a/tests/fixture/islands/Test.tsx +++ b/tests/fixture/islands/Test.tsx @@ -1,7 +1,12 @@ /** @jsx h */ -import { h } from "../client_deps.ts"; +import { asset, h } from "../client_deps.ts"; export default function Test(props: { message: string }) { - return

{props.message}

; + return ( +
+

{props.message}

+ +
+ ); } diff --git a/tests/fixture/routes/static.tsx b/tests/fixture/routes/static.tsx index 96dbf70c..5e763480 100644 --- a/tests/fixture/routes/static.tsx +++ b/tests/fixture/routes/static.tsx @@ -1,7 +1,12 @@ /** @jsx h */ -import { h } from "../client_deps.ts"; +import { asset, h } from "../client_deps.ts"; export default function StaticPage() { - return

This is a static page.

; + return ( +
+

This is a static page.

+ +
+ ); } diff --git a/tests/fixture/static/image.png b/tests/fixture/static/image.png new file mode 100644 index 00000000..c2d41252 Binary files /dev/null and b/tests/fixture/static/image.png differ diff --git a/tests/main_test.ts b/tests/main_test.ts index 2c93f165..82c390ec 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -137,6 +137,7 @@ Deno.test("/static page prerender", async () => { assert(!body.includes(`main.js`)); assert(!body.includes(`island-test.js`)); assertStringIncludes(body, "

This is a static page.

"); + assertStringIncludes(body, `src="/_frsh/static`); assert(!body.includes("__FRSH_ISLAND_PROPS")); }); @@ -181,7 +182,7 @@ Deno.test("/foo/:path*", async () => { assert(body.includes("bar/baz")); }); -Deno.test("static file", async () => { +Deno.test("static file - by file path", async () => { const resp = await router(new Request("https://fresh.deno.dev/foo.txt")); assertEquals(resp.status, 200); const body = await resp.text(); @@ -198,6 +199,35 @@ Deno.test("static file", async () => { assertEquals(resp2.status, 304); }); +Deno.test("static file - by 'hashed' path", async () => { + // Check that the file path have the BUILD_ID + const resp = await router(new Request("https://fresh.deno.dev/")); + const body = await resp.text(); + const imgFilePath = body.match(/img src="(.*?)"/)?.[1]; + assert(imgFilePath); + assert(imgFilePath.includes(globalThis.__FRSH_BUILD_ID)); + + // check the static file is served corectly under its cacheable route + const resp2 = await router( + new Request(`https://fresh.deno.dev${imgFilePath}`), + ); + const _ = await resp2.text(); + assertEquals(resp2.status, 200); + assertEquals( + resp2.headers.get("cache-control"), + "public, max-age=31536000, immutable", + ); + + const resp3 = await router( + new Request(`https://fresh.deno.dev${imgFilePath}`, { + headers: { + "if-none-match": resp2.headers.get("etag")!, + }, + }), + ); + assertEquals(resp3.status, 304); +}); + Deno.test("/params/:path*", async () => { const resp = await router( new Request("https://fresh.deno.dev/params/bar/baz"),