Skip to content

Commit 04d56d0

Browse files
fix(producer): renders use the font named in a var() fallback (#4619)
* fix(producer): renders use the font named in a var() fallback When a font-family starts with var(--x, A, B) and --x is not defined, the render now reads A, B the way the browser does. A system font at the head of that fallback gets Inter placed in front of it, the same rule a direct system-font stack already follows. The rewrite stays inside the var() fallback, so a defined --x still wins. A defined property whose value is itself a var() is followed too. The distributed plan check reads the same answer. Fonts named only in such a fallback are best-effort: they are embedded when they resolve, and one that does not resolve is logged instead of failing a distributed render. Fonts named directly, or through a defined property, still fail closed as before. CSS-wide keywords such as inherit are no longer treated as font names to fetch. Compiled the way a distributed render compiles them, 28 registry items now embed a font they name this way, and none newly fails. * refactor(producer): fold var() fallback resolution into one branch * fix(producer): fonts behind a var() chain or empty fallback add no new render failures A family reached through a chain of defined var()s is optional like a fallback-only one: fetched fail-closed, skipped only when no source serves it. An empty var() fallback makes the declaration invalid, so the browser inherits and the plan check no longer rejects the families after it. * test(producer): a family named after a leading var() stays required * fix(producer): a transient error on an optional font warns and renders the fallback * chore(catalog): record the font requests var() fallbacks now make * fix(producer): required fonts fetch before optional ones can spend the time budget
1 parent 4094c7b commit 04d56d0

10 files changed

Lines changed: 719 additions & 78 deletions

‎packages/producer/src/services/deterministicFonts-failClosed.test.ts‎

Lines changed: 301 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,16 @@
1414
* The tests inject `fetchImpl` so no real network call happens.
1515
*/
1616

17-
import { beforeEach, describe, expect, it } from "bun:test";
17+
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
18+
import { defaultLogger } from "../logger.js";
1819
import {
1920
_clearGoogleFontCssCacheForTests,
2021
FONT_FETCH_FAILED,
2122
FONT_FETCH_UNAVAILABLE,
2223
FontFetchError,
2324
FontFetchUnavailableError,
2425
injectDeterministicFontFaces,
26+
normalizeSystemFontPrimaryFamilies,
2527
} from "./deterministicFonts.js";
2628

2729
// The Google Fonts CSS cache is process-lifetime and keyed by URL; several
@@ -343,3 +345,301 @@ describe("FontFetchError", () => {
343345
expect(err).toBeInstanceOf(Error);
344346
});
345347
});
348+
349+
describe("fail-closed fonts named only in an undefined var() fallback", () => {
350+
const styled = (css: string) =>
351+
`<!doctype html><html><head><style>${css}</style></head><body><p>hello</p></body></html>`;
352+
353+
it("injects what resolves from a Tailwind v4 stack and skips the rest", async () => {
354+
const html = normalizeSystemFontPrimaryFamilies(
355+
styled(
356+
`body { font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"); }`,
357+
),
358+
);
359+
const result = await injectDeterministicFontFaces(html, {
360+
failClosedFontFetch: true,
361+
allowSystemFontCapture: false,
362+
fetchImpl: makeHttp400Fetch(),
363+
});
364+
expect(result).toContain(`font-family: "Inter";`);
365+
});
366+
367+
it("still throws for an unresolved family in a direct list", async () => {
368+
const caught = await rejectedError(
369+
injectDeterministicFontFaces(styled(`body { font-family: "Acme Brand Sans", sans-serif; }`), {
370+
failClosedFontFetch: true,
371+
allowSystemFontCapture: false,
372+
fetchImpl: makeHttp400Fetch(),
373+
}),
374+
);
375+
expect(caught).toBeInstanceOf(FontFetchError);
376+
expect((caught as FontFetchError).familyName).toContain("Acme Brand Sans");
377+
});
378+
379+
it("tries a fallback-only family and tolerates it not being found", async () => {
380+
const html = styled(`body { font-family: var(--brand, "Acme Brand Sans", sans-serif); }`);
381+
let requests = 0;
382+
const notFound = makeHttp400Fetch();
383+
const fetchImpl = (async (...args: Parameters<typeof fetch>) => {
384+
requests += 1;
385+
return notFound(...args);
386+
}) as unknown as typeof fetch;
387+
const result = await injectDeterministicFontFaces(html, {
388+
failClosedFontFetch: true,
389+
allowSystemFontCapture: false,
390+
fetchImpl,
391+
});
392+
expect(result).toBe(html);
393+
expect(requests).toBeGreaterThan(0);
394+
});
395+
396+
it.each([
397+
[`:root { --a: var(--b); --b: "Acme Brand Sans"; } body { font-family: var(--a), serif; }`],
398+
[`:root { --b: "Acme Brand Sans"; } body { font-family: var(--unset, var(--b)), serif; }`],
399+
])("tolerates a family behind a chain of var()s not being found: %s", async (css) => {
400+
const html = styled(css);
401+
const result = await injectDeterministicFontFaces(html, {
402+
failClosedFontFetch: true,
403+
allowSystemFontCapture: false,
404+
fetchImpl: makeHttp400Fetch(),
405+
});
406+
expect(result).toBe(html);
407+
});
408+
409+
it("keeps a family named after a leading var() required", async () => {
410+
const caught = await rejectedError(
411+
injectDeterministicFontFaces(
412+
styled(`body { font-family: var(--unset, Inter), "Acme Brand Sans", serif; }`),
413+
{ failClosedFontFetch: true, allowSystemFontCapture: false, fetchImpl: makeHttp400Fetch() },
414+
),
415+
);
416+
expect((caught as FontFetchError).familyName).toContain("Acme Brand Sans");
417+
});
418+
419+
it("keeps a family required behind one defined var()", async () => {
420+
const caught = await rejectedError(
421+
injectDeterministicFontFaces(
422+
styled(`:root { --a: "Acme Brand Sans"; } body { font-family: var(--a), serif; }`),
423+
{ failClosedFontFetch: true, allowSystemFontCapture: false, fetchImpl: makeHttp400Fetch() },
424+
),
425+
);
426+
expect(caught).toBeInstanceOf(FontFetchError);
427+
});
428+
429+
describe("a transient failure on a fallback-only family", () => {
430+
const FALLBACK_ONLY = styled(
431+
`body { font-family: var(--brand, "Acme Brand Sans", sans-serif); }`,
432+
);
433+
let warnings: string[] = [];
434+
let warnSpy: ReturnType<typeof spyOn>;
435+
beforeEach(() => {
436+
warnings = [];
437+
warnSpy = spyOn(defaultLogger, "warn").mockImplementation((message: string) => {
438+
warnings.push(message);
439+
});
440+
});
441+
afterEach(() => warnSpy.mockRestore());
442+
443+
const counting = (inner: typeof fetch) => {
444+
const counter = { requests: 0 };
445+
const fetchImpl = (async (...args: Parameters<typeof fetch>) => {
446+
counter.requests += 1;
447+
return inner(...args);
448+
}) as unknown as typeof fetch;
449+
return { counter, fetchImpl };
450+
};
451+
const hangingFetch = (async (_input: unknown, init?: RequestInit) =>
452+
new Promise<Response>((_resolve, reject) => {
453+
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
454+
})) as unknown as typeof fetch;
455+
const optionalWarnings = () => warnings.filter((w) => w.includes("Optional font"));
456+
457+
it.each([
458+
["HTTP 503", makeHttp503Fetch],
459+
["a network failure", makeFailingFetch],
460+
])("retries once on %s, then renders the fallback and warns", async (_label, makeFetch) => {
461+
const { counter, fetchImpl } = counting(makeFetch());
462+
const result = await injectDeterministicFontFaces(FALLBACK_ONLY, {
463+
failClosedFontFetch: true,
464+
allowSystemFontCapture: false,
465+
fetchImpl,
466+
fontFetchRetryPolicy: { baseDelayMs: 0, maxAttempts: 3 },
467+
});
468+
expect(result).toBe(FALLBACK_ONLY);
469+
expect(counter.requests).toBe(2);
470+
expect(optionalWarnings()).toHaveLength(1);
471+
expect(optionalWarnings()[0]).toContain(`"Acme Brand Sans"`);
472+
});
473+
474+
it("fetches a required family before hanging optional ones spend the budget", async () => {
475+
const requested: string[] = [];
476+
const notFound = makeHttp400Fetch();
477+
const fetchImpl = (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
478+
requested.push(String(input));
479+
return String(input).includes("Required")
480+
? notFound(input, init)
481+
: hangingFetch(input, init);
482+
}) as unknown as typeof fetch;
483+
const caught = await rejectedError(
484+
injectDeterministicFontFaces(
485+
styled(
486+
`.a { font-family: var(--a, "Optional One"), serif; } .b { font-family: var(--b, "Optional Two"), serif; } .c { font-family: "Required Face", serif; }`,
487+
),
488+
{
489+
failClosedFontFetch: true,
490+
allowSystemFontCapture: false,
491+
fetchImpl,
492+
fontFetchRetryPolicy: { baseDelayMs: 0, attemptTimeoutMs: 100, maxElapsedMs: 300 },
493+
},
494+
),
495+
);
496+
expect((caught as FontFetchError).code).toBe(FONT_FETCH_FAILED);
497+
expect(requested.some((url) => url.includes("Required"))).toBe(true);
498+
});
499+
500+
it("keeps the bundled Inter faces and warns when its top-up fetch fails", async () => {
501+
const html = styled(`body { font-family: var(--brand, Inter, sans-serif); }`);
502+
const result = await injectDeterministicFontFaces(html, {
503+
failClosedFontFetch: true,
504+
allowSystemFontCapture: false,
505+
fetchImpl: makeHttp503Fetch(),
506+
fontFetchRetryPolicy: { baseDelayMs: 0 },
507+
});
508+
expect(result).toContain(`font-family: "Inter";`);
509+
expect(optionalWarnings()).toHaveLength(1);
510+
expect(optionalWarnings()[0]).toContain(`"Inter"`);
511+
});
512+
513+
it("gives up on a hanging fetch within the per-attempt bound and warns", async () => {
514+
const { counter, fetchImpl } = counting(hangingFetch);
515+
const started = Date.now();
516+
const result = await injectDeterministicFontFaces(FALLBACK_ONLY, {
517+
failClosedFontFetch: true,
518+
allowSystemFontCapture: false,
519+
fetchImpl,
520+
fontFetchRetryPolicy: { baseDelayMs: 0, attemptTimeoutMs: 50, maxAttempts: 3 },
521+
});
522+
expect(result).toBe(FALLBACK_ONLY);
523+
expect(counter.requests).toBe(2);
524+
expect(Date.now() - started).toBeLessThan(1_000);
525+
expect(optionalWarnings()[0]).toContain(`"Acme Brand Sans"`);
526+
});
527+
528+
it("injects the face when the retry succeeds, without a warning", async () => {
529+
const served = makeGoogleFontFetch([]);
530+
const unavailable = makeHttp503Fetch();
531+
let calls = 0;
532+
const fetchImpl = (async (...args: Parameters<typeof fetch>) =>
533+
(calls += 1) === 1 ? unavailable(...args) : served(...args)) as unknown as typeof fetch;
534+
const result = await injectDeterministicFontFaces(FALLBACK_ONLY, {
535+
failClosedFontFetch: true,
536+
allowSystemFontCapture: false,
537+
fetchImpl,
538+
fontFetchRetryPolicy: { baseDelayMs: 0 },
539+
});
540+
expect(result).toContain("data-hyperframes-deterministic-fonts");
541+
expect(result).toContain(`font-family: "Acme Brand Sans"`);
542+
expect(optionalWarnings()).toHaveLength(0);
543+
});
544+
545+
it("still aborts when the caller cancels", async () => {
546+
const controller = new AbortController();
547+
const reason = new Error("caller cancelled");
548+
setTimeout(() => controller.abort(reason), 20);
549+
const caught = await rejectedError(
550+
injectDeterministicFontFaces(FALLBACK_ONLY, {
551+
failClosedFontFetch: true,
552+
allowSystemFontCapture: false,
553+
fetchImpl: hangingFetch,
554+
abortSignal: controller.signal,
555+
fontFetchRetryPolicy: { baseDelayMs: 0, attemptTimeoutMs: 5_000 },
556+
}),
557+
);
558+
expect(caught).toBe(reason);
559+
expect(optionalWarnings()).toHaveLength(0);
560+
});
561+
562+
it("keeps a required family fail-closed after all its attempts", async () => {
563+
const { counter, fetchImpl } = counting(makeHttp503Fetch());
564+
const caught = await rejectedError(
565+
injectDeterministicFontFaces(
566+
styled(`body { font-family: "Acme Brand Sans", sans-serif; }`),
567+
{
568+
failClosedFontFetch: true,
569+
allowSystemFontCapture: false,
570+
fetchImpl,
571+
fontFetchRetryPolicy: { baseDelayMs: 0, maxAttempts: 3 },
572+
},
573+
),
574+
);
575+
expect(caught).toBeInstanceOf(FontFetchUnavailableError);
576+
expect(counter.requests).toBe(3);
577+
expect(optionalWarnings()).toHaveLength(0);
578+
});
579+
580+
it("does not hand a required family the optional retry count for the same request", async () => {
581+
const { counter, fetchImpl } = counting(makeHttp503Fetch());
582+
const fontFetchRetryPolicy = { baseDelayMs: 0, maxAttempts: 3 };
583+
const [optionalResult, requiredError] = await Promise.all([
584+
injectDeterministicFontFaces(FALLBACK_ONLY, {
585+
failClosedFontFetch: true,
586+
allowSystemFontCapture: false,
587+
fetchImpl,
588+
fontFetchRetryPolicy,
589+
}),
590+
rejectedError(
591+
injectDeterministicFontFaces(
592+
styled(
593+
`body { font-family: var(--brand, "Acme Brand Sans", sans-serif); } p { font-family: "Acme Brand Sans"; }`,
594+
),
595+
{
596+
failClosedFontFetch: true,
597+
allowSystemFontCapture: false,
598+
fetchImpl,
599+
fontFetchRetryPolicy,
600+
},
601+
),
602+
),
603+
]);
604+
expect(optionalResult).toBe(FALLBACK_ONLY);
605+
expect(requiredError).toBeInstanceOf(FontFetchUnavailableError);
606+
expect(counter.requests).toBe(5);
607+
});
608+
609+
it("keeps a family fail-closed when it is also named directly", async () => {
610+
const caught = await rejectedError(
611+
injectDeterministicFontFaces(
612+
styled(
613+
`.a { font-family: var(--brand, "Acme Brand Sans", sans-serif); } .b { font-family: "Acme Brand Sans", serif; }`,
614+
),
615+
{
616+
failClosedFontFetch: true,
617+
allowSystemFontCapture: false,
618+
fetchImpl: makeHttp503Fetch(),
619+
fontFetchRetryPolicy: { baseDelayMs: 0 },
620+
},
621+
),
622+
);
623+
expect(caught).toBeInstanceOf(FontFetchUnavailableError);
624+
});
625+
});
626+
627+
it.each([
628+
[
629+
`.a { font-family: var(--brand, "Acme Brand Sans", sans-serif); } .b { font-family: "Acme Brand Sans", serif; }`,
630+
],
631+
[
632+
`.b { font-family: "Acme Brand Sans", serif; } .a { font-family: var(--brand, "Acme Brand Sans", sans-serif); }`,
633+
],
634+
])("keeps a family required when it is also named directly: %s", async (css) => {
635+
const caught = await rejectedError(
636+
injectDeterministicFontFaces(styled(css), {
637+
failClosedFontFetch: true,
638+
allowSystemFontCapture: false,
639+
fetchImpl: makeHttp400Fetch(),
640+
}),
641+
);
642+
expect(caught).toBeInstanceOf(FontFetchError);
643+
expect((caught as FontFetchError).familyName).toContain("Acme Brand Sans");
644+
});
645+
});

0 commit comments

Comments
 (0)