Skip to content

Commit a16222d

Browse files
jrusso1020akzarma
andauthored
fix(fonts): supplement alias faces from the canonical family (#3230)
A family resolving through FONT_ALIAS_MAP could emit @font-face rules drawn from two unrelated typefaces under one font-family name, split by weight and style. The supplementation fetch was passed the authored name, so for a cross-typeface alias (helvetica -> inter) it asked Google for the very typeface the alias exists to replace. Diagnosed, reported and fixed by Akshay Kumar Sharma (@akzarma) in #3083 / #3085. This PR carries that work because the fix requires re-recorded regression baselines, which are LFS objects we cannot push to a fork's LFS store. Baselines re-recorded for style-15-prod and style-3-prod, each verified text-only before acceptance. All 9 regression shards pass. Closes #3083. Co-authored-by: Akshay Kumar Sharma <[email protected]>
1 parent e0ba41c commit a16222d

4 files changed

Lines changed: 426 additions & 17 deletions

File tree

Lines changed: 306 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
1+
/**
2+
* Regression test for cross-typeface alias supplementation.
3+
*
4+
* A family in FONT_ALIAS_MAP resolves to a canonical bundled typeface — e.g.
5+
* `Noto Sans` → Inter. `buildFontFaceCss` emits the canonical's embedded faces
6+
* under the authored family name, then queries Google Fonts to fill the weights
7+
* and styles the bundle lacks.
8+
*
9+
* The bug: that supplementary query used the *authored* name, so a
10+
* cross-typeface alias regained faces from the very typeface the alias exists to
11+
* replace. No canonical bundle ships an italic face, so every italic Google
12+
* served for the authored name was injected — `Noto Sans` came out as Inter
13+
* upright plus real Noto Sans italic, two typefaces under one `font-family`.
14+
*
15+
* These tests inject `fetchImpl` (no network) and a temp `HYPERFRAMES_FONT_CACHE_DIR`
16+
* so they are hermetic.
17+
*/
18+
19+
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
20+
import { mkdtempSync, rmSync } from "node:fs";
21+
import { tmpdir } from "node:os";
22+
import { join } from "node:path";
23+
import { EMBEDDED_FONT_DATA } from "./fontData.generated.js";
24+
25+
let cacheDir: string;
26+
let prevCacheEnv: string | undefined;
27+
28+
beforeAll(() => {
29+
prevCacheEnv = process.env.HYPERFRAMES_FONT_CACHE_DIR;
30+
cacheDir = mkdtempSync(join(tmpdir(), "hf-font-alias-"));
31+
process.env.HYPERFRAMES_FONT_CACHE_DIR = cacheDir;
32+
});
33+
34+
afterAll(() => {
35+
if (prevCacheEnv === undefined) delete process.env.HYPERFRAMES_FONT_CACHE_DIR;
36+
else process.env.HYPERFRAMES_FONT_CACHE_DIR = prevCacheEnv;
37+
rmSync(cacheDir, { recursive: true, force: true });
38+
});
39+
40+
// One woff2 per typeface Google could serve, with identifiable bodies so every
41+
// injected `src` can be traced back to the family that was queried.
42+
const SERVED_FACES: Record<string, { url: string; bytes: string }> = {
43+
Inter: {
44+
url: "https://fonts.gstatic.com/s/inter/v1/inter-supplement.woff2",
45+
bytes: "INTER_FETCHED_BYTES",
46+
},
47+
"Noto Sans": {
48+
url: "https://fonts.gstatic.com/s/notosans/v1/notosans-supplement.woff2",
49+
bytes: "NOTO_SANS_FETCHED_BYTES",
50+
},
51+
Montserrat: {
52+
url: "https://fonts.gstatic.com/s/montserrat/v1/montserrat-supplement.woff2",
53+
bytes: "MONTSERRAT_FETCHED_BYTES",
54+
},
55+
};
56+
57+
const b64 = (s: string) => Buffer.from(s).toString("base64");
58+
59+
// 300 normal + 400 italic: no CANONICAL_FONTS bundle ships either, so both are
60+
// classified "missing from the bundle" and injected.
61+
function cssFor(family: string): string {
62+
const url = SERVED_FACES[family]?.url;
63+
if (!url) return "";
64+
return `@font-face {
65+
font-family: '${family}';
66+
font-style: normal;
67+
font-weight: 300;
68+
src: url(${url}) format('woff2');
69+
}
70+
@font-face {
71+
font-family: '${family}';
72+
font-style: italic;
73+
font-weight: 400;
74+
src: url(${url}) format('woff2');
75+
}`;
76+
}
77+
78+
function makeGoogleFetch(queriedFamilies: string[]): typeof fetch {
79+
return (async (input: unknown) => {
80+
const url = String(input);
81+
if (url.startsWith("https://fonts.googleapis.com/")) {
82+
const family = new URL(url).searchParams.get("family")?.split(":", 1)[0] ?? "";
83+
queriedFamilies.push(family);
84+
return new Response(cssFor(family), { status: 200 });
85+
}
86+
const served = Object.values(SERVED_FACES).find((face) => face.url === url);
87+
if (served) return new Response(served.bytes, { status: 200 });
88+
return new Response("", { status: 404 });
89+
}) as unknown as typeof fetch;
90+
}
91+
92+
function htmlRequesting(family: string): string {
93+
return `<!doctype html><html><head><style>
94+
h1 { font-family: "${family}"; }
95+
</style></head><body><h1>Upright</h1></body></html>`;
96+
}
97+
98+
function injectedSrcs(html: string): string[] {
99+
return [...html.matchAll(/src:\s*url\("([^"]+)"\)/g)].map((match) => match[1] ?? "");
100+
}
101+
102+
function bundledUris(packageName: string): Set<string> {
103+
return new Set(
104+
[...EMBEDDED_FONT_DATA]
105+
.filter(([key]) => key.startsWith(`${packageName}:`))
106+
.map(([, uri]) => uri),
107+
);
108+
}
109+
110+
describe("aliased font-family supplementation", () => {
111+
it("supplements a cross-typeface alias from the canonical family", async () => {
112+
const { injectDeterministicFontFaces } = await import("./deterministicFonts.js");
113+
const queriedFamilies: string[] = [];
114+
const result = await injectDeterministicFontFaces(htmlRequesting("Noto Sans"), {
115+
allowSystemFontCapture: false,
116+
fetchImpl: makeGoogleFetch(queriedFamilies),
117+
});
118+
119+
// "Noto Sans" aliases to Inter, so the supplementary query asks for Inter.
120+
expect(queriedFamilies).toEqual(["Inter"]);
121+
122+
// The authored spelling still names the family, so authored CSS keeps matching.
123+
expect(result).toContain('font-family: "Noto Sans"');
124+
125+
// Every injected face is Inter — either the embedded bundle or the Inter
126+
// fetch. None carry the real Noto Sans the alias exists to replace.
127+
const canonicalUris = bundledUris("@fontsource/inter");
128+
canonicalUris.add(`data:font/woff2;base64,${b64(SERVED_FACES.Inter!.bytes)}`);
129+
const srcs = injectedSrcs(result);
130+
expect(srcs.length).toBeGreaterThan(0);
131+
for (const src of srcs) expect(canonicalUris.has(src)).toBe(true);
132+
expect(result).not.toContain(b64(SERVED_FACES["Noto Sans"]!.bytes));
133+
});
134+
135+
it("collapses a variable font's shared source into one weight-range rule", async () => {
136+
const { injectDeterministicFontFaces } = await import("./deterministicFonts.js");
137+
// Google serves Inter as a variable font: one woff2 for every static weight.
138+
const sharedUrl = "https://fonts.gstatic.com/s/inter/v1/inter-variable.woff2";
139+
const css = [100, 200, 300, 500]
140+
.map(
141+
(weight) => `@font-face {
142+
font-family: 'Inter';
143+
font-style: normal;
144+
font-weight: ${weight};
145+
src: url(${sharedUrl}) format('woff2');
146+
}`,
147+
)
148+
.join("\n");
149+
const fetchImpl = (async (input: unknown) => {
150+
const url = String(input);
151+
if (url.startsWith("https://fonts.googleapis.com/"))
152+
return new Response(css, { status: 200 });
153+
if (url === sharedUrl) return new Response("INTER_VARIABLE_BYTES", { status: 200 });
154+
return new Response("", { status: 404 });
155+
}) as unknown as typeof fetch;
156+
157+
const result = await injectDeterministicFontFaces(htmlRequesting("Noto Sans"), {
158+
allowSystemFontCapture: false,
159+
fetchImpl,
160+
});
161+
162+
// One rule spanning the run, not four rules carrying the same blob.
163+
const variableUri = `data:font/woff2;base64,${b64("INTER_VARIABLE_BYTES")}`;
164+
// 100-300 collapse into one rule; 500 stays separate because the bundle
165+
// serves 400 and a 100-500 range would shadow that embedded face.
166+
const occurrences = result.split(variableUri).length - 1;
167+
expect(occurrences).toBe(2);
168+
expect(result).toContain("font-weight: 100 300;");
169+
expect(result).toContain("font-weight: 500;");
170+
});
171+
172+
it("collapses shared sources when Google interleaves subsets without text=", async () => {
173+
const { injectDeterministicFontFaces } = await import("./deterministicFonts.js");
174+
// Without `text=` Google orders the response weight-major, subset-minor,
175+
// so the faces sharing one variable source are never adjacent.
176+
const latinUrl = "https://fonts.gstatic.com/s/inter/v1/inter-latin-variable.woff2";
177+
const latinExtUrl = "https://fonts.gstatic.com/s/inter/v1/inter-latinext-variable.woff2";
178+
const LATIN = "U+0000-00FF";
179+
const LATIN_EXT = "U+0100-024F";
180+
const subsets = [
181+
{ url: latinUrl, range: LATIN },
182+
{ url: latinExtUrl, range: LATIN_EXT },
183+
];
184+
const css = [100, 200, 300, 500]
185+
.flatMap((weight) =>
186+
subsets.map(
187+
(subset) => `@font-face {
188+
font-family: 'Inter';
189+
font-style: normal;
190+
font-weight: ${weight};
191+
src: url(${subset.url}) format('woff2');
192+
unicode-range: ${subset.range};
193+
}`,
194+
),
195+
)
196+
.join("\n");
197+
198+
const fetchImpl = (async (input: unknown) => {
199+
const url = String(input);
200+
if (url.startsWith("https://fonts.googleapis.com/")) {
201+
// The request must not carry `text=`, or Google would return one
202+
// subset and the interleaving under test would not occur.
203+
expect(new URL(url).searchParams.get("text")).toBeNull();
204+
return new Response(css, { status: 200 });
205+
}
206+
if (url === latinUrl) return new Response("LATIN_VARIABLE_BYTES", { status: 200 });
207+
if (url === latinExtUrl) return new Response("LATINEXT_VARIABLE_BYTES", { status: 200 });
208+
return new Response("", { status: 404 });
209+
}) as unknown as typeof fetch;
210+
211+
// Enough unique characters that extractGoogleFontsText exceeds its budget
212+
// and returns undefined, which is what drops `text=` in production.
213+
const manyUniqueChars = Array.from({ length: 400 }, (_, index) =>
214+
String.fromCodePoint(0x4e00 + index),
215+
).join("");
216+
const html = `<!doctype html><html><head><style>
217+
h1 { font-family: "Noto Sans"; }
218+
</style></head><body><h1>${manyUniqueChars}</h1></body></html>`;
219+
220+
const result = await injectDeterministicFontFaces(html, {
221+
allowSystemFontCapture: false,
222+
fetchImpl,
223+
});
224+
225+
// Per subset: 100-300 collapse into one rule, 500 stays separate because
226+
// the bundle covers 400. Two rules per subset, not one per weight.
227+
for (const bytes of ["LATIN_VARIABLE_BYTES", "LATINEXT_VARIABLE_BYTES"]) {
228+
const uri = `data:font/woff2;base64,${b64(bytes)}`;
229+
expect(result.split(uri).length - 1).toBe(2);
230+
}
231+
expect(result.split("font-weight: 100 300;").length - 1).toBe(2);
232+
expect(result.split("font-weight: 500;").length - 1).toBe(2);
233+
});
234+
235+
it("keeps overlapping subsets in response order when collapsing", async () => {
236+
const { injectDeterministicFontFaces } = await import("./deterministicFonts.js");
237+
// Real Google output has codepoints in more than one subset (U+0304 and
238+
// friends). Overlapping `unicode-range` rules resolve last-defined-first,
239+
// so collapsing must not move a subset ahead of one declared after it.
240+
const firstUrl = "https://fonts.gstatic.com/s/inter/v1/inter-first.woff2";
241+
const secondUrl = "https://fonts.gstatic.com/s/inter/v1/inter-second.woff2";
242+
const OVERLAPPING = "U+0000-00FF, U+0304";
243+
const css = [100, 200, 500]
244+
.flatMap((weight) =>
245+
[
246+
{ url: firstUrl, range: "U+0000-00FF" },
247+
{ url: secondUrl, range: OVERLAPPING },
248+
].map(
249+
(subset) => `@font-face {
250+
font-family: 'Inter';
251+
font-style: normal;
252+
font-weight: ${weight};
253+
src: url(${subset.url}) format('woff2');
254+
unicode-range: ${subset.range};
255+
}`,
256+
),
257+
)
258+
.join("\n");
259+
260+
const fetchImpl = (async (input: unknown) => {
261+
const url = String(input);
262+
if (url.startsWith("https://fonts.googleapis.com/"))
263+
return new Response(css, { status: 200 });
264+
if (url === firstUrl) return new Response("FIRST_BYTES", { status: 200 });
265+
if (url === secondUrl) return new Response("SECOND_BYTES", { status: 200 });
266+
return new Response("", { status: 404 });
267+
}) as unknown as typeof fetch;
268+
269+
const result = await injectDeterministicFontFaces(htmlRequesting("Noto Sans"), {
270+
allowSystemFontCapture: false,
271+
fetchImpl,
272+
});
273+
274+
// 100-200 and 500 are separate runs per source because the bundle covers
275+
// 400, so each source is emitted twice. The interleaving must survive
276+
// collapsing: source-major grouping would emit FIRST, FIRST, SECOND, SECOND
277+
// and hand the shared codepoints to the wrong subset.
278+
const order = [...result.matchAll(/base64,([A-Za-z0-9+/=]+)/g)]
279+
.map((match) => match[1] ?? "")
280+
.filter((data) => data === b64("FIRST_BYTES") || data === b64("SECOND_BYTES"))
281+
.map((data) => (data === b64("FIRST_BYTES") ? "FIRST" : "SECOND"));
282+
expect(order).toEqual(["FIRST", "SECOND", "FIRST", "SECOND"]);
283+
});
284+
285+
it("has a canonical display name for every alias target", async () => {
286+
const { FONT_ALIAS_MAP, resolveAliasDisplayName } =
287+
await import("@hyperframes/core/fonts/aliases");
288+
// The supplementary fetch is skipped outright when this lookup fails, so
289+
// every alias must resolve or its family silently loses Google's weights.
290+
for (const alias of Object.keys(FONT_ALIAS_MAP)) {
291+
expect(resolveAliasDisplayName(alias)).toBeString();
292+
}
293+
});
294+
295+
it("still supplements a self-referencing alias from its own family", async () => {
296+
const { injectDeterministicFontFaces } = await import("./deterministicFonts.js");
297+
const queriedFamilies: string[] = [];
298+
const result = await injectDeterministicFontFaces(htmlRequesting("Montserrat"), {
299+
allowSystemFontCapture: false,
300+
fetchImpl: makeGoogleFetch(queriedFamilies),
301+
});
302+
303+
expect(queriedFamilies).toEqual(["Montserrat"]);
304+
expect(result).toContain(b64(SERVED_FACES.Montserrat!.bytes));
305+
});
306+
});

0 commit comments

Comments
 (0)