Skip to content

Commit 9dd8d0f

Browse files
committed
fix(web): canonicalize preload identity across registration & adoption
1 parent a5d3af3 commit 9dd8d0f

7 files changed

Lines changed: 137 additions & 24 deletions

File tree

‎packages/web/frames/src/frame-client.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2061,11 +2061,15 @@ function parseFragment(html) {
20612061
// Mirrors head.ts without importing it into the standalone frame client.
20622062
const PRELOAD_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
20632063

2064-
// Mirrors head.ts's qualifierValue: `crossorigin` is three states, not a
2065-
// string range, so `""`, a bare attribute and `anonymous` are one request.
2066-
// Frame `attrs` are already strings, but the document may carry any spelling.
2064+
// Mirrors head.ts's qualifierValue — keep them in step. `as` folds ASCII
2065+
// case; an empty source set or size reads as absent (registration never
2066+
// emits one); `crossorigin` is three states, not a string range, so `""`, a
2067+
// bare attribute and `anonymous` are one request. Frame `attrs` are already
2068+
// canonical strings, but the document may carry any spelling.
20672069
function qualifierValue(name, value) {
20682070
if (value == null) return null;
2071+
if (name === "imagesrcset" || name === "imagesizes") return value === "" ? null : value;
2072+
if (name === "as") return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
20692073
if (name !== "crossorigin") return value;
20702074
return value.length === 15 && value.toLowerCase() === "use-credentials"
20712075
? "use-credentials"

‎packages/web/src/head.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,21 +99,42 @@ export function classifyHeadTag(desc) {
9999
// invalid value — is Anonymous. `crossorigin=""` and `crossorigin="anonymous"`
100100
// are one request and must be one identity, or the same font ships twice
101101
// and the client mounts a second link instead of adopting the server's.
102+
// - `as` is an enumerated attribute, ASCII case-insensitive: registration
103+
// lowercases it before emitting, so identity and adoption must fold the
104+
// same way or a client `as="IMAGE"` never adopts the server's `as="image"`.
105+
// - the responsive pair is filtered at registration: `""` and any
106+
// non-string value never reach the markup, so they must read as absent
107+
// here too, or a client `imagesrcset: ""` mounts a second link beside a
108+
// server link that (correctly) carries none.
109+
// The standalone frame client mirrors this function; keep them in step.
102110
export function qualifierValue(name, value) {
103111
if (value == null || value === false) return null;
112+
if (name === "imagesrcset" || name === "imagesizes")
113+
return typeof value === "string" && value !== "" ? value : null;
104114
const v = value === true ? "" : String(value);
115+
if (name === "as") return asciiLowerCase(v);
105116
if (name !== "crossorigin") return v;
106117
return v.length === 15 && v.toLowerCase() === "use-credentials" ? v.toLowerCase() : "anonymous";
107118
}
108119

120+
// HTML compares rel/as ASCII case-insensitively; toLowerCase would fold a
121+
// non-ASCII character onto an ASCII one the parser never matches.
122+
export function asciiLowerCase(value) {
123+
return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
124+
}
125+
109126
// Identity for a resource-class tag (evaluated props). Qualifier values are
110127
// length-prefixed: plain `:q=value` concatenation let a value containing the
111128
// delimiters forge another qualifier (`type: "a:media=b"` collided with
112129
// `type: "a", media: "b"`), which silently dropped the second resource. The
113130
// responsive attributes made that reachable — a source set is a long free-form
114-
// string that routinely carries `:` and `=`.
131+
// string that routinely carries `:` and `=`. The URL is length-prefixed for the
132+
// same reason: it is free-form too, and `/loader:type=6:module` with no `type`
133+
// otherwise reads as `/loader` with `type: "module"`. `tag` and `rel` come
134+
// from closed sets and cannot carry the delimiters.
115135
export function resourceIdentity(tag, props) {
116-
let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
136+
const url = String(props.href || props.src || "");
137+
let id = "res:" + tag + ":" + (props.rel || "") + ":" + url.length + ":" + url;
117138
for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
118139
const q = RESOURCE_QUALIFIERS[i];
119140
const value = qualifierValue(q, props[q]);

‎packages/web/src/server.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
evalHeadProps,
5050
evalHeadValue,
5151
resourceIdentity,
52+
asciiLowerCase,
5253
replaceableIdentity,
5354
resolveHead,
5455
STYLESHEET_FETCH_META
@@ -341,7 +342,9 @@ function joinAssetPath(base, file) {
341342
// commas TRAILING that run separate it from the next candidate. Commas INSIDE a
342343
// URL (`/w,400/hero.avif`, the shape image CDNs emit) are part of it, so they no
343344
// longer read as two relative candidates.
344-
function eachCandidateUrl(srcset, visit) {
345+
// `visit(url, descriptors)` sees each candidate's URL and the descriptor text
346+
// between it and the closing comma, so a descriptor check never scans a URL.
347+
function eachCandidate(srcset, visit) {
345348
let i = 0;
346349
const n = srcset.length;
347350
while (i < n) {
@@ -351,12 +354,15 @@ function eachCandidateUrl(srcset, visit) {
351354
if (i === start) return false;
352355
const raw = srcset.slice(start, i);
353356
const url = raw.replace(/,+$/, "");
354-
if (url && visit(url)) return true;
357+
let descriptors = "";
355358
// A URL that did not end in commas is followed by its descriptor; the
356359
// comma that closes this candidate comes after it.
357360
if (url === raw) {
361+
const from = i;
358362
while (i < n && srcset[i] !== ",") i++;
363+
descriptors = srcset.slice(from, i);
359364
}
365+
if (url && visit(url, descriptors)) return true;
360366
}
361367
return false;
362368
}
@@ -366,14 +372,17 @@ function eachCandidateUrl(srcset, visit) {
366372
// places on any route below the root — which is true whether or not `_base` is
367373
// set, hence no base guard here.
368374
function hasRelativeCandidate(srcset) {
369-
return eachCandidateUrl(srcset, url => !/^(?:[a-zA-Z][a-zA-Z0-9+.-]*:|\/)/.test(url));
375+
return eachCandidate(srcset, url => !/^(?:[a-zA-Z][a-zA-Z0-9+.-]*:|\/)/.test(url));
370376
}
371377

372378
// Whether any candidate carries a width descriptor (`400w`), which the spec
373-
// makes `imagesizes` mandatory for. Descriptors sit between a candidate's URL
374-
// and the comma that closes it, so a separator always precedes them.
379+
// makes `imagesizes` mandatory for. Only descriptor text is examined: a URL is
380+
// free-form and `https://cdn.example/image,400w 1x` is one density candidate,
381+
// not a width descriptor.
375382
function hasWidthDescriptor(srcset) {
376-
return /[\s,]\d+(?:\.\d+)?w(?=[\s,]|$)/.test(srcset);
383+
return eachCandidate(srcset, (_, descriptors) =>
384+
/(?:^|\s)\d+(?:\.\d+)?w(?=\s|$)/.test(descriptors)
385+
);
377386
}
378387

379388
function resolveAssets(moduleUrl, manifest) {
@@ -1243,12 +1252,6 @@ export function styleNonce(nonce) {
12431252
return destinationNonce(nonce, "style");
12441253
}
12451254

1246-
// HTML compares rel/as ASCII case-insensitively; toLowerCase would fold a
1247-
// non-ASCII character onto an ASCII one the parser never matches.
1248-
function asciiLowerCase(value) {
1249-
return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
1250-
}
1251-
12521255
// Attribute names are ASCII case-insensitive, so a caller-supplied `Nonce`
12531256
// counts as one too.
12541257
function hasNonceProp(props) {

‎packages/web/test/preload-links-adopt-client.spec.tsx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,12 @@ describe("preload link adoption on the client", () => {
112112
expect(preloads()).toHaveLength(1);
113113
expect(preloads()[0]).toBe(server);
114114
});
115+
116+
test("adopts across destination case and filtered responsive values", () => {
117+
const server = serverEmitted({ href: "/j.avif", as: "image" });
118+
mount({ href: "/j.avif", as: "IMAGE", imagesrcset: "", imagesizes: "" });
119+
120+
expect(preloads()).toHaveLength(1);
121+
expect(preloads()[0]).toBe(server);
122+
});
115123
});

‎packages/web/test/preload-links-frame-client.spec.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,32 @@ describe("frame preload links", () => {
150150
expect(document.head.querySelector('link[crossorigin="anonymous"]')).toBe(server);
151151
});
152152

153+
it("adopts across destination case and filtered responsive values", () => {
154+
const server = document.createElement("link");
155+
server.rel = "preload";
156+
server.setAttribute("href", "/j.avif");
157+
server.setAttribute("as", "IMAGE");
158+
server.setAttribute("imagesrcset", "");
159+
server.setAttribute("imagesizes", "");
160+
document.head.appendChild(server);
161+
162+
const boundary = document.createElement("div");
163+
document.body.appendChild(boundary);
164+
createFrame(boundary).apply({
165+
version: 1,
166+
r: {
167+
"seg::assets": {
168+
type: "assets",
169+
key: "",
170+
preloads: [{ href: "/j.avif", attrs: { as: "image" } }]
171+
}
172+
}
173+
});
174+
175+
expect(document.head.querySelectorAll('link[href="/j.avif"]')).toHaveLength(1);
176+
expect(document.head.querySelector('link[href="/j.avif"]')).toBe(server);
177+
});
178+
153179
it("retains every late root asset record until a frame registers", () => {
154180
const host = createFrameHost();
155181
host.apply({

‎packages/web/test/runtime/preload-links.spec.js‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,12 +267,21 @@ describe("typed preload links", () => {
267267
expect(html).not.toContain("imagesizes");
268268
});
269269

270-
it("does not fork an image identity on an empty source set", () => {
270+
it("canonicalizes destinations and filtered responsive qualifiers", () => {
271271
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
272272
const html = r.renderToString(() => {
273273
const ctx = sharedConfig.context;
274274
ctx.registerAsset("preload", { href: "/x.avif", as: "image" });
275-
ctx.registerAsset("preload", { href: "/x.avif", as: "image", imagesrcset: "" });
275+
r.useHead({
276+
tag: "link",
277+
props: {
278+
rel: "preload",
279+
href: "/x.avif",
280+
as: "IMAGE",
281+
imagesrcset: "",
282+
imagesizes: ""
283+
}
284+
});
276285
return r.ssr`<html><head></head><body></body></html>`;
277286
});
278287
warn.mockRestore();
@@ -488,6 +497,10 @@ describe("typed preload links", () => {
488497
imagesizes: "50vw"
489498
});
490499
ctx.registerAsset("preload", { as: "image", imagesrcset: "/c-1x.avif, /c-2x.avif 2x" });
500+
ctx.registerAsset("preload", {
501+
as: "image",
502+
imagesrcset: "https://cdn.example/image,400w 1x"
503+
});
491504
return r.ssr`<html><head></head><body></body></html>`;
492505
});
493506
const warnings = warn.mock.calls.map(call => String(call[0]));
@@ -714,4 +727,20 @@ describe("typed preload links", () => {
714727

715728
expect(html.match(/rel="preload"/g)).toHaveLength(2);
716729
});
730+
731+
it("keeps URLs from forging qualifier fields", () => {
732+
const html = r.renderToString(() => {
733+
r.useHead({
734+
tag: "link",
735+
props: { rel: "stylesheet", href: "/loader:type=8:text/css" }
736+
});
737+
r.useHead({
738+
tag: "link",
739+
props: { rel: "stylesheet", href: "/loader", type: "text/css" }
740+
});
741+
return r.ssr`<html><head></head><body></body></html>`;
742+
});
743+
744+
expect(html.match(/rel="stylesheet"/g)).toHaveLength(2);
745+
});
717746
});

‎scripts/size/.size-limit.js‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,15 @@ module.exports = [
319319
// Patch-channel removal (2026-09-02): 10.86 -> 10.73 KB, measured at
320320
// 10.70. The channel is deleted from next — regions own value delivery,
321321
// the unified-For design owns structure — reclaiming the core-retained emission seams.
322-
limit: "10.73 KB",
322+
// Preload identity canonicalization, rebased onto next (2026-09-02):
323+
// 10.73 -> 10.74 KB, measured at 10.731 against next's 10.700 with only
324+
// dist/web.js swapped. Not retained code: the tree-shaken bundle is
325+
// byte-identical and web.js contributes the same 7106 minified bytes on
326+
// both sides. head.ts gains two top-level helpers this bundle never
327+
// reaches (asciiLowerCase, qualifierValue), which shifts esbuild's
328+
// identifier allocation over the same-length output — brotli layout
329+
// drift, 31 B. Ratcheted to the next 0.01 kB per this file's rule.
330+
limit: "10.74 KB",
323331
modifyEsbuildConfig
324332
},
325333
{
@@ -374,15 +382,16 @@ module.exports = [
374382
// 17.673. Hydration seeds the applied-class snapshot without mutating
375383
// the claimed DOM so the first live in-place change still diffs.
376384
//
377-
// Patch-channel removal (2026-09-02): 17.72 -> 17.61 KB, measured at
378-
// 17.58. The channel is deleted from next — regions own value delivery,
379-
// the unified-For design owns structure — reclaiming the insert $ll seam and core emission bytes.
380385
// Responsive image preloads (2026-09-01): 17.56 -> 17.59 KB, measured at
381386
// 17.570 (+29 B). The one document scenario that pays: it retains
382387
// `lazy`, so the whole asset-registration path is reachable and it picks
383388
// up the source-set branch in mountHeadResource. csr-app moved the other
384389
// way on brotli layout (see its note); the identity commit before this
385390
// one was byte-neutral in every document bundle.
391+
//
392+
// Patch-channel removal (2026-09-02): 17.72 -> 17.61 KB, measured at
393+
// 17.58. The channel is deleted from next — regions own value delivery,
394+
// the unified-For design owns structure — reclaiming the insert $ll seam and core emission bytes.
386395
limit: "17.61 KB",
387396
modifyEsbuildConfig
388397
},
@@ -531,8 +540,21 @@ module.exports = [
531540
// 11.360 (+40 B on top of the identity commit). Frame consumers locate
532541
// and create a source-set link with no href — adoption matches on a null
533542
// href — and the wire entry drops the key when there is none.
543+
//
544+
// Canonical qualifier matching (2026-09-01): 11.37 -> 11.38 KB, measured
545+
// at 11.374 (+14 B). The frame client's mirrored `qualifierValue` folds
546+
// `as` and reads an empty source set or size as absent, so a document
547+
// link spelled `as="IMAGE"` or carrying `imagesrcset=""` adopts instead
548+
// of duplicating — the same rules head.ts applies.
549+
//
550+
// Rebased onto next after the patch-channel removal (2026-09-02):
551+
// 11.30 -> 11.40 KB, measured at 11.372 against next's 11.266 — +106 B
552+
// for the whole branch (identity canonicalization, the source-set form,
553+
// and the mirrored qualifier folding above). The per-commit notes were
554+
// measured on the pre-removal base, so their absolutes no longer line
555+
// up with this file's floor, but their deltas do.
534556
path: "../../packages/web/frames/dist/client.js",
535-
limit: "11.30 KB",
557+
limit: "11.40 KB",
536558
modifyEsbuildConfig: framesEsbuildConfig
537559
}
538560
];

0 commit comments

Comments
 (0)