feat: automatically apply asset caching to img src and srcset (#184)

This commit is contained in:
Sylvain Cau
2022-05-19 19:19:59 +02:00
committed by GitHub
parent c1a9d53b18
commit e8b1e229b3
11 changed files with 254 additions and 50 deletions
+48 -1
View File
@@ -1 +1,48 @@
> TODO(lucacasonato): this page still needs to be written
> TODO(lucacasonato): this page still needs to be completed
Fresh automatically serves static assets placed in a `static/` directory in the
project root. These assets are served at the root of the webserver, with a
higher priority than routes. This means that if a given request matches a file
in the `static/` folder, it is always served, even if there is a route that
would also match the request.
Static asset responses automatically get a `content-type` header assigned based
on the file extension of the file on disk. Assets are also automatically
streamed from disk to the client to improve performance and efficiency for both
user and server.
Fresh also adds an `etag` header to assets automatically, and handles the
`If-None-Match` header for incoming requests.
### Caching
By default, no caching headers are added to assets. This can be disadvantageous
in many scenarios, so fresh makes it easy to serve assets with long cache
lifetimes too.
The first approach to do this is manual. The client runtime exports an `asset`
function that takes an absolute path to the static asset, and returns a "locked"
version of this path that contains a build ID for cache busting. When the asset
is requested at this "locked" path, it will be served with a cache lifetime of
one year.
```jsx
import { asset, h } from "../deps.ts";
export default function Page() {
return (
<p>
<a href={asset("/brochure.pdf")}>View brochure</a>
</p>
);
}
```
Fresh also does this automatically for `src` and `srcset` attributes in `<img>`
and `<source>` HTML tags. These will automatically use "locked" paths if fresh
deems it safe to do so. You can always opt out of this behaviour per tag, by
adding the `data-fresh-disable-lock` attribute.
```jsx
<img src="/user.png" />;
```
+8 -1
View File
@@ -1,4 +1,5 @@
import { ComponentType, h, render } from "./deps.ts";
import { ComponentType, h, options, render } from "./deps.ts";
import { assetHashingHook } from "./utils.ts";
function createRootFragment(
parent: Element,
@@ -61,3 +62,9 @@ export function revive(islands: Record<string, ComponentType>) {
}
walk(document.body);
}
const originalHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode);
if (originalHook) originalHook(vnode);
};
+40
View File
@@ -1,3 +1,5 @@
import { VNode } from "./deps.ts";
export const INTERNAL_PREFIX = "/_frsh";
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
@@ -28,3 +30,41 @@ export function asset(path: string) {
return path;
}
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSet(srcset: string): string {
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
const parts = srcset.split(",");
const constructed = [];
for (const part of parts) {
const trimmed = part.trimStart();
const leadingWhitespace = part.length - trimmed.length;
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
constructed.push(leading + asset(url) + trailing);
}
return constructed.join(",");
}
export function assetHashingHook(
vnode: VNode<{
src?: string;
srcset?: string;
["data-fresh-disable-lock"]?: boolean;
}>,
) {
if (vnode.type === "img" || vnode.type === "source") {
const { props } = vnode;
if (props["data-fresh-disable-lock"]) return;
if (typeof props.src === "string") {
props.src = asset(props.src);
}
if (typeof props.srcset === "string") {
props.srcset = assetSrcSet(props.srcset);
}
}
}
+42 -1
View File
@@ -1,5 +1,5 @@
import { assertEquals } from "../../tests/deps.ts";
import { asset } from "./utils.ts";
import { asset, assetSrcSet } from "./utils.ts";
globalThis.__FRSH_BUILD_ID = "ID123";
@@ -17,3 +17,44 @@ Deno.test("asset", () => {
"https://example.com/logo.png",
);
});
Deno.test("assetSrcSet", () => {
assertEquals(assetSrcSet("/img.png"), "/img.png?__frsh_c=ID123");
assertEquals(
assetSrcSet("/img.png, /img.png 2x"),
"/img.png?__frsh_c=ID123, /img.png?__frsh_c=ID123 2x",
);
assertEquals(assetSrcSet("/img.png 1x"), "/img.png?__frsh_c=ID123 1x");
assertEquals(
assetSrcSet("/img.png 1x, /img.png 2x"),
"/img.png?__frsh_c=ID123 1x, /img.png?__frsh_c=ID123 2x",
);
assertEquals(
assetSrcSet("/img.png 1.5x, /img.png 3x"),
"/img.png?__frsh_c=ID123 1.5x, /img.png?__frsh_c=ID123 3x",
);
//test with queries
assertEquals(
assetSrcSet("/img.png?w=140, /img.png?w=200 2x"),
"/img.png?w=140&__frsh_c=ID123, /img.png?w=200&__frsh_c=ID123 2x",
);
// test with extra spaces
assertEquals(
assetSrcSet("/img-s.png 300w, /img-l.png 600w , /img-xl.png 900w"),
"/img-s.png?__frsh_c=ID123 300w, /img-l.png?__frsh_c=ID123 600w , /img-xl.png?__frsh_c=ID123 900w",
);
// test with ( syntax
assertEquals(
assetSrcSet("/img.png ( 140,0w)"),
"/img.png ( 140,0w)",
);
// test with invalid parts
assertEquals(
assetSrcSet("/img.png,, /img-s.png 300w"),
"/img.png,, /img-s.png 300w",
);
});
+2
View File
@@ -18,6 +18,7 @@ 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 { assetHashingHook } from "../runtime/utils.ts";
export interface RenderOptions<Data> {
page: Page<Data> | UnknownPage | ErrorPage;
@@ -296,6 +297,7 @@ let ISLAND_PROPS: unknown[] = [];
const originalHook = options.vnode;
let ignoreNext = false;
options.vnode = (vnode) => {
assetHashingHook(vnode);
const originalType = vnode.type as ComponentType<unknown>;
if (typeof vnode.type === "function") {
const island = ISLANDS.find((island) => island.component === originalType);
+36 -34
View File
@@ -9,23 +9,24 @@ import * as $3 from "./routes/_app.tsx";
import * as $4 from "./routes/_middleware.ts";
import * as $5 from "./routes/_render.ts";
import * as $6 from "./routes/api/get_only.ts";
import * as $7 from "./routes/books/[id].tsx";
import * as $8 from "./routes/connInfo.ts";
import * as $9 from "./routes/failure.ts";
import * as $10 from "./routes/index.tsx";
import * as $11 from "./routes/intercept.tsx";
import * as $12 from "./routes/intercept_args.tsx";
import * as $13 from "./routes/layeredMdw/_middleware.ts";
import * as $14 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts";
import * as $15 from "./routes/layeredMdw/layer2/_middleware.ts";
import * as $16 from "./routes/layeredMdw/layer2/abc.ts";
import * as $17 from "./routes/layeredMdw/layer2/layer3/[id].ts";
import * as $18 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
import * as $19 from "./routes/middleware_root.ts";
import * as $20 from "./routes/params.tsx";
import * as $21 from "./routes/props/[id].tsx";
import * as $22 from "./routes/static.tsx";
import * as $23 from "./routes/wildcard.tsx";
import * as $7 from "./routes/assetsCaching/index.tsx";
import * as $8 from "./routes/books/[id].tsx";
import * as $9 from "./routes/connInfo.ts";
import * as $10 from "./routes/failure.ts";
import * as $11 from "./routes/index.tsx";
import * as $12 from "./routes/intercept.tsx";
import * as $13 from "./routes/intercept_args.tsx";
import * as $14 from "./routes/layeredMdw/_middleware.ts";
import * as $15 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts";
import * as $16 from "./routes/layeredMdw/layer2/_middleware.ts";
import * as $17 from "./routes/layeredMdw/layer2/abc.ts";
import * as $18 from "./routes/layeredMdw/layer2/layer3/[id].ts";
import * as $19 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
import * as $20 from "./routes/middleware_root.ts";
import * as $21 from "./routes/params.tsx";
import * as $22 from "./routes/props/[id].tsx";
import * as $23 from "./routes/static.tsx";
import * as $24 from "./routes/wildcard.tsx";
import * as $$0 from "./islands/Test.tsx";
const manifest = {
@@ -37,23 +38,24 @@ const manifest = {
"./routes/_middleware.ts": $4,
"./routes/_render.ts": $5,
"./routes/api/get_only.ts": $6,
"./routes/books/[id].tsx": $7,
"./routes/connInfo.ts": $8,
"./routes/failure.ts": $9,
"./routes/index.tsx": $10,
"./routes/intercept.tsx": $11,
"./routes/intercept_args.tsx": $12,
"./routes/layeredMdw/_middleware.ts": $13,
"./routes/layeredMdw/layer2-no-mw/without_mw.ts": $14,
"./routes/layeredMdw/layer2/_middleware.ts": $15,
"./routes/layeredMdw/layer2/abc.ts": $16,
"./routes/layeredMdw/layer2/layer3/[id].ts": $17,
"./routes/layeredMdw/layer2/layer3/_middleware.ts": $18,
"./routes/middleware_root.ts": $19,
"./routes/params.tsx": $20,
"./routes/props/[id].tsx": $21,
"./routes/static.tsx": $22,
"./routes/wildcard.tsx": $23,
"./routes/assetsCaching/index.tsx": $7,
"./routes/books/[id].tsx": $8,
"./routes/connInfo.ts": $9,
"./routes/failure.ts": $10,
"./routes/index.tsx": $11,
"./routes/intercept.tsx": $12,
"./routes/intercept_args.tsx": $13,
"./routes/layeredMdw/_middleware.ts": $14,
"./routes/layeredMdw/layer2-no-mw/without_mw.ts": $15,
"./routes/layeredMdw/layer2/_middleware.ts": $16,
"./routes/layeredMdw/layer2/abc.ts": $17,
"./routes/layeredMdw/layer2/layer3/[id].ts": $18,
"./routes/layeredMdw/layer2/layer3/_middleware.ts": $19,
"./routes/middleware_root.ts": $20,
"./routes/params.tsx": $21,
"./routes/props/[id].tsx": $22,
"./routes/static.tsx": $23,
"./routes/wildcard.tsx": $24,
},
islands: {
"./islands/Test.tsx": $$0,
+7 -2
View File
@@ -1,12 +1,17 @@
/** @jsx h */
import { asset, h } from "../client_deps.ts";
import { h } from "../client_deps.ts";
export default function Test(props: { message: string }) {
return (
<div>
<p>{props.message}</p>
<img src={asset("/image.png")} />
<img
id="img-in-island"
src="/image.png"
srcset="/image.png 1x"
height={130}
/>
</div>
);
}
@@ -0,0 +1,30 @@
/** @jsx h */
import { asset, h } from "../../client_deps.ts";
import Test from "../../islands/Test.tsx";
export default function Home() {
return (
<div>
<div style={{ marginTop: 20 }}>img-with-hashing</div>
<img id="img-with-hashing" src="/image.png" height={130} />
<div style={{ marginTop: 20 }}>img-without-hashing</div>
<img
id="img-without-hashing"
src="/image.png"
data-fresh-disable-lock
height={130}
/>
<Test message="In island" />
<div style={{ marginTop: 20 }}>img-external</div>
<img
id="img-missing"
src="https://fresh.deno.dev/favicon.ico"
height={130}
/>
</div>
);
}
+36 -2
View File
@@ -219,9 +219,11 @@ Deno.test("static file - by file path", async () => {
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 resp = await router(
new Request("https://fresh.deno.dev/assetsCaching"),
);
const body = await resp.text();
const imgFilePath = body.match(/img src="(.*?)"/)?.[1];
const imgFilePath = body.match(/img id="img-with-hashing" src="(.*?)"/)?.[1];
assert(imgFilePath);
assert(imgFilePath.includes(`?__frsh_c=${globalThis.__FRSH_BUILD_ID}`));
@@ -244,6 +246,38 @@ Deno.test("static file - by 'hashed' path", async () => {
}),
);
assertEquals(resp3.status, 304);
// ensure asset hook is not applied on file explicitly excluded with attribute
const imgFilePathWithNoCache = body.match(
/img id="img-without-hashing" src="(.*?)"/,
)?.[1];
assert(imgFilePathWithNoCache);
assert(
!imgFilePathWithNoCache.includes(globalThis.__FRSH_BUILD_ID),
"img-without-hashing",
);
// ensure asset hook is applied on img within an island
const imgInIsland = body.match(/img id="img-in-island" src="(.*?)"/)?.[1];
assert(imgInIsland);
assert(imgInIsland.includes(globalThis.__FRSH_BUILD_ID), "img-in-island");
// verify that the asset hook is applied to the srcset
const imgInIslandSrcSet = body.match(/srcset="(.*?)"/)?.[1];
assert(imgInIslandSrcSet);
console.log(imgInIslandSrcSet);
assert(
imgInIslandSrcSet.includes(globalThis.__FRSH_BUILD_ID),
"img-in-island-srcset",
);
// verify that the asset hook is not applied to img outside reference out of the static folder
const imgMissing = body.match(/img id="img-missing" src="(.*?)"/)?.[1];
assert(imgMissing);
assert(
!imgMissing.includes(globalThis.__FRSH_BUILD_ID),
"Applying hash on unknown asset",
);
});
Deno.test("/params/:path*", async () => {
+1 -1
View File
@@ -83,7 +83,7 @@ function Logo() {
return (
<a href="/" class={tw`flex mr-3 items-center`}>
<img
src={asset("/logo.svg")}
src="/logo.svg"
alt="Fresh logo"
width={40}
height={40}
+4 -8
View File
@@ -88,20 +88,16 @@ function Intro() {
>
<picture>
<source
srcset={`${asset("/illustration/2x.avif")} 2x, ${
asset("/illustration/1x.avif")
}`}
srcset="/illustration/2x.avif 2x, /illustration/1x.avif"
type="image/avif"
/>
<source
srcset={`${asset("/illustration/2x.webp")} 2x, ${
asset("/illustration/1x.webp")
}`}
srcset="/illustration/2x.webp2x, /illustration/1x.webp"
type="image/webp"
/>
<img
src={asset("/illustration/1x.jpeg")}
srcset={`${asset("/illustration/2x.jpeg")} 2x`}
src="/illustration/1x.jpg"
srcset="/illustration/2x.jpg 2x"
class={tw`w-64 mx-auto`}
width={800}
height={678}