Add ETag conditional handling for static files

Co-authored-by: Theo Browne <[email protected]>
This commit is contained in:
Cursor AgentandTheo Browne committed 2026-02-10 03:09:07 +00:00
1 parent 01b32b2d35
commit f6210af9d0
3 files changed
+85

No files matched your search

+35
View File
@@ -241,6 +241,10 @@ async function main() {
if ((assetResponse.headers.get("vary") ?? "").toLowerCase() !== "range") {
throw new Error("Smoke test failed: expected vary=range on built asset response.");
}
const assetEtag = assetResponse.headers.get("etag");
if (!assetEtag || assetEtag.length === 0) {
throw new Error("Smoke test failed: expected ETag on built asset response.");
}
const assetContentLength = Number(assetResponse.headers.get("content-length") ?? "0");
if (!Number.isFinite(assetContentLength) || assetContentLength <= 0) {
throw new Error(
@@ -249,6 +253,26 @@ async function main() {
)}.`,
);
}
const conditionalAsset = await fetch(assetUrl, {
headers: {
"If-None-Match": assetEtag,
},
});
if (conditionalAsset.status !== 304) {
throw new Error(
`Smoke test failed: expected conditional asset status 304, received ${conditionalAsset.status}.`,
);
}
if (conditionalAsset.headers.get("etag") !== assetEtag) {
throw new Error(
`Smoke test failed: expected conditional asset ETag ${assetEtag}, got ${String(
conditionalAsset.headers.get("etag"),
)}.`,
);
}
if ((conditionalAsset.headers.get("cache-control") ?? "").toLowerCase() !== assetCacheControl) {
throw new Error("Smoke test failed: expected cache-control preserved on conditional asset response.");
}
const rangeEnd = Math.min(15, assetContentLength - 1);
const rangedAsset = await fetch(assetUrl, {
headers: {
@@ -282,6 +306,17 @@ async function main() {
if ((rangedAsset.headers.get("vary") ?? "").toLowerCase() !== "range") {
throw new Error("Smoke test failed: expected vary=range on ranged asset response.");
}
const conditionalRangedAsset = await fetch(assetUrl, {
headers: {
Range: `bytes=0-${rangeEnd}`,
"If-None-Match": assetEtag,
},
});
if (conditionalRangedAsset.status !== 206) {
throw new Error(
`Smoke test failed: expected conditional ranged asset status 206, received ${conditionalRangedAsset.status}.`,
);
}
const unsatisfiableRange = await fetch(assetUrl, {
headers: {
Range: `bytes=${assetContentLength}-${assetContentLength + 10}`,
+20
View File
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
import {
formatStartupError,
ifNoneMatchSatisfied,
parseByteRangeHeader,
parseCliOptions,
readCliVersion,
@@ -936,6 +937,25 @@ describe("parseByteRangeHeader", () => {
});
});
describe("ifNoneMatchSatisfied", () => {
it("returns false when header is missing or empty", () => {
expect(ifNoneMatchSatisfied(undefined, "\"abc\"")).toBe(false);
expect(ifNoneMatchSatisfied(" ", "\"abc\"")).toBe(false);
});
it("matches wildcard headers", () => {
expect(ifNoneMatchSatisfied("*", "\"abc\"")).toBe(true);
});
it("matches exact etags from comma-separated lists", () => {
expect(ifNoneMatchSatisfied("\"foo\", \"bar\", \"abc\"", "\"abc\"")).toBe(true);
});
it("does not match non-identical etags", () => {
expect(ifNoneMatchSatisfied("\"foo\", \"bar\"", "\"abc\"")).toBe(false);
});
});
describe("resolveStaticAssetReadTarget", () => {
it("falls back to index for unknown routes", () => {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3-static-route-"));
+30
View File
@@ -512,6 +512,26 @@ function cacheControlFor(filePath: string): string {
return "public, max-age=31536000, immutable";
}
function staticEtagFor(stats: fs.Stats): string {
return `"${stats.size.toString(16)}-${Math.trunc(stats.mtimeMs).toString(16)}"`;
}
export function ifNoneMatchSatisfied(ifNoneMatchHeader: string | undefined, etag: string): boolean {
if (!ifNoneMatchHeader) {
return false;
}
const candidates = ifNoneMatchHeader
.split(",")
.map((token) => token.trim())
.filter((token) => token.length > 0);
if (candidates.length === 0) {
return false;
}
return candidates.includes("*") || candidates.includes(etag);
}
export function parseByteRangeHeader(
rangeHeaderValue: string | undefined,
fileSize: number,
@@ -766,8 +786,11 @@ function startStaticWebServer(distRoot: string, port: number) {
return;
}
const etag = staticEtagFor(stats);
response.statusCode = resolvedRange ? 206 : 200;
response.setHeader("Content-Type", contentTypeFor(targetPath));
response.setHeader("ETag", etag);
response.setHeader(
"Content-Length",
String(resolvedRange ? resolvedRange.end - resolvedRange.start + 1 : stats.size),
@@ -781,6 +804,13 @@ function startStaticWebServer(distRoot: string, port: number) {
cacheControl: cacheControlFor(targetPath),
});
if (!resolvedRange && ifNoneMatchSatisfied(request.headers["if-none-match"], etag)) {
response.statusCode = 304;
response.removeHeader("Content-Length");
response.end();
return;
}
if (requestMethod === "HEAD") {
response.end();
return;