Skip to content

Commit 81f08f3

Browse files
committed
fix(cli): a font missing from this computer no longer stops a cloud render, and is named
1 parent 5259fd1 commit 81f08f3

4 files changed

Lines changed: 80 additions & 47 deletions

File tree

‎packages/cli/src/cloud/fontPreflight.test.ts‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { mkdtempSync, writeFileSync } from "node:fs";
22
import { tmpdir } from "node:os";
33
import { join } from "node:path";
44
import { describe, expect, it } from "vitest";
5-
import { describeUnresolvedFonts, embedSystemFonts } from "./fontPreflight.js";
5+
import { describeSwappedFonts, embedSystemFonts } from "./fontPreflight.js";
66

77
const PAGE = `<html><head><style>h1{font-family:"PingFang SC"}</style></head><body><h1>x</h1></body></html>`;
88

@@ -29,6 +29,7 @@ describe("embedSystemFonts", () => {
2929
});
3030
expect(left).toEqual([]);
3131
expect(calls.map((c) => c.allowSystemFontCapture)).toEqual([false, true]);
32+
expect(calls.map((c) => c.failClosedFontFetch)).toEqual([true, false]);
3233
expect(calls.map((c) => c.systemFontsByInnerName)).toEqual([undefined, true]);
3334
// The resolver only injects into a full document, so the probe for the capture pass must be one.
3435
expect(probes[1]).toContain("<head>");
@@ -37,13 +38,32 @@ describe("embedSystemFonts", () => {
3738
expect(entry.indexOf("data-hf-system-fonts")).toBeLessThan(entry.indexOf("</head>"));
3839
});
3940

40-
it("returns the fonts whose file is not on this machine and leaves the page alone", async () => {
41+
it("gives a font with no file on this machine an empty face and returns it, instead of stopping", async () => {
4142
const s = setup();
42-
const left = await embedSystemFonts(s, async () => {
43+
const left = await embedSystemFonts(s, async (html, options) => {
44+
if ((options as { allowSystemFontCapture: boolean }).allowSystemFontCapture) return html;
4345
throw missing(["PingFang SC"]);
4446
});
4547
expect(left).toEqual(["PingFang SC"]);
46-
expect(s.fileMap.get("index.html")!.toString()).toBe(PAGE);
48+
const entry = s.fileMap.get("index.html")!.toString();
49+
expect(entry).toContain('@font-face{font-family:"PingFang SC";src:local("hyperframes-font-not-installed');
50+
expect(entry).not.toContain("data:font");
51+
});
52+
53+
it("carries the fonts it finds even when another one is not on this machine", async () => {
54+
const page = `<html><head><style>a{font-family:"PingFang SC"}b{font-family:"Zapfino"}</style></head><body></body></html>`;
55+
const fileMap = new Map([["index.html", Buffer.from(page)]]);
56+
const dir = mkdtempSync(join(tmpdir(), "hf-font-pre-"));
57+
writeFileSync(join(dir, "index.html"), page);
58+
const left = await embedSystemFonts({ dir, entryPath: "index.html", fileMap }, async (html, options) => {
59+
if ((options as { allowSystemFontCapture: boolean }).allowSystemFontCapture)
60+
return `${html}<style>@font-face{font-family:"PingFang SC";src:url(data:font/woff2;base64,AAAA)}</style>`;
61+
throw missing(["PingFang SC", "Zapfino"]);
62+
});
63+
expect(left).toEqual(["Zapfino"]);
64+
const entry = fileMap.get("index.html")!.toString();
65+
expect(entry).toContain('font-family:"PingFang SC";src:url(data:font/woff2');
66+
expect(entry).toContain('font-family:"Zapfino";src:local(');
4767
});
4868

4969
it("changes nothing when every font resolves", async () => {
@@ -61,11 +81,11 @@ describe("embedSystemFonts", () => {
6181
});
6282
});
6383

64-
describe("describeUnresolvedFonts", () => {
65-
it("names the font and a look-alike when there is one", () => {
66-
expect(describeUnresolvedFonts(["PingFang SC", "Zapfino"])).toBe(
67-
"HyperFrames couldn't find a font file for PingFang SC on this computer, so the cloud can't have it: use Noto Sans SC, switch to a font in your project or render on this computer.\n" +
68-
"HyperFrames couldn't find a font file for Zapfino on this computer, so the cloud can't have it: switch to a font in your project or render on this computer.",
84+
describe("describeSwappedFonts", () => {
85+
it("names each font that is not on this computer and a look-alike when there is one", () => {
86+
expect(describeSwappedFonts(["PingFang SC", "Zapfino"])).toBe(
87+
"PingFang SC is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does; Noto Sans SC is a free look-alike you can use instead.\n" +
88+
"Zapfino is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does.",
6989
);
7090
});
7191
});

‎packages/cli/src/cloud/fontPreflight.ts‎

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,18 @@ async function unresolvedCloudFonts(
7171
}
7272
}
7373

74+
const faceFamily = (face: string) =>
75+
/font-family\s*:\s*(?:"([^"]+)"|'([^']+)'|([^;}"']+))/i.exec(face)?.slice(1).find(Boolean)?.trim();
76+
77+
/** A face whose source matches no font anywhere: the browser skips it and uses the next font in the stack, as it does
78+
* for a family that is not installed, and the cloud's resolver counts the family as declared. */
79+
const placeholderFace = (family: string) =>
80+
`@font-face{font-family:"${family}";src:local("hyperframes-font-not-installed ${family}")}`;
81+
7482
/**
7583
* Adds the system fonts the project uses to its entry page as inline @font-face rules, so the zip carries them.
76-
* Returns the families whose font file is not on this machine; those cannot render in the cloud.
84+
* A family with no font file on this machine gets an empty face, so the cloud renders it with the same fallback a
85+
* local render uses; those families are returned, for the caller to name.
7786
*/
7887
export async function embedSystemFonts(
7988
opts: { dir: string; entryFile?: string; entryPath: string; fileMap: Map<string, StagedFile> },
@@ -84,41 +93,43 @@ export async function embedSystemFonts(
8493
if (wanted.length === 0) return [];
8594
const css = wanted.map((f, i) => `.f${i}{font-family:"${f}"}`).join("");
8695
const probe = `<!doctype html><html><head><style>${css}</style></head><body></body></html>`;
87-
let out: string;
88-
try {
89-
out = await run(probe, {
90-
failClosedFontFetch: true,
91-
allowSystemFontCapture: true,
92-
systemFontsByInnerName: true,
93-
logger: QUIET,
94-
});
95-
} catch (err) {
96-
return namedFamilies(err) ?? wanted;
97-
}
98-
const faces = [...out.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)]
96+
const out = await run(probe, {
97+
failClosedFontFetch: false,
98+
allowSystemFontCapture: true,
99+
systemFontsByInnerName: true,
100+
logger: QUIET,
101+
});
102+
const captured = [...out.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)]
99103
.map((m) => m[1] ?? "")
100104
.filter((css) => css.includes("@font-face"))
101105
.join("\n");
106+
const found = new Set(
107+
[...captured.matchAll(/@font-face\s*{[^}]*}/gi)]
108+
.map((m) => faceFamily(m[0])?.toLowerCase())
109+
.filter((f): f is string => f !== undefined),
110+
);
111+
const missing = wanted.filter((family) => !found.has(family.toLowerCase()));
112+
const faces = [captured, ...missing.map(placeholderFace)].filter(Boolean).join("\n");
102113
const entry = opts.fileMap.get(opts.entryPath);
103-
if (!faces || !entry) return wanted;
114+
if (!entry) return missing;
104115
const html = readStaged(entry).toString("utf-8");
105116
const tag = `<style data-hf-system-fonts>${faces}</style>`;
106117
const at = html.search(/<\/head>/i);
107118
opts.fileMap.set(
108119
opts.entryPath,
109120
Buffer.from(at < 0 ? tag + html : html.slice(0, at) + tag + html.slice(at), "utf-8"),
110121
);
111-
return [];
122+
return missing;
112123
}
113124

114-
/** One line per font, with the swap when there is one. */
115-
export function describeUnresolvedFonts(families: readonly string[]): string {
125+
/** One line per font that is not on this computer: the cloud renders it with the same fallback a local render uses. */
126+
export function describeSwappedFonts(families: readonly string[]): string {
116127
return families
117128
.map((family) => {
118129
const swap = lookAlikeFor(family);
119-
return `HyperFrames couldn't find a font file for ${family} on this computer, so the cloud can't have it: ${
120-
swap ? `use ${swap}, ` : ""
121-
}switch to a font in your project or render on this computer.`;
130+
return `${family} is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does${
131+
swap ? `; ${swap} is a free look-alike you can use instead` : ""
132+
}.`;
122133
})
123134
.join("\n");
124135
}

‎packages/cli/src/commands/cloud/render.fonts.test.ts‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ vi.mock("../../cloud/fontPreflight.js", async (importOriginal) => ({
1111

1212
import render from "./render.js";
1313
import { errorBox } from "../../ui/format.js";
14-
import { CliRuntimeError, consumeCommandResult } from "../../utils/commandResult.js";
14+
import { consumeCommandResult } from "../../utils/commandResult.js";
1515

1616
vi.mock("../../ui/format.js", async (importOriginal) => ({
1717
...(await importOriginal<typeof import("../../ui/format.js")>()),
@@ -40,17 +40,14 @@ afterEach(() => {
4040
});
4141

4242
describe("cloud render font preflight", () => {
43-
it("stops before any upload and names the font that is not on this computer", async () => {
44-
await expect(runCommand(render, { rawArgs: [project, "--no-wait", "--json"] })).rejects.toThrow(
45-
CliRuntimeError,
46-
);
43+
it("does not stop for a font that is not on this computer: the dry run names it and carries on", async () => {
44+
const lines: string[] = [];
45+
const log = vi.spyOn(console, "log").mockImplementation((line) => void lines.push(String(line)));
46+
await runCommand(render, { rawArgs: [project, "--dry-run", "--json"] });
47+
log.mockRestore();
4748

4849
expect(fetchSpy).not.toHaveBeenCalled();
49-
expect(errorBox).toHaveBeenCalledWith(
50-
"Fonts not on this computer",
51-
expect.stringContaining(
52-
"HyperFrames couldn't find a font file for PingFang SC on this computer, so the cloud can't have it: use Noto Sans SC",
53-
),
54-
);
50+
expect(errorBox).not.toHaveBeenCalled();
51+
expect(JSON.parse(lines.join("")).archive.swapped_fonts).toEqual(["PingFang SC"]);
5552
});
5653
});

‎packages/cli/src/commands/cloud/render.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ import {
7373
pollUntilTerminal,
7474
} from "../../cloud/index.js";
7575
import { reportApiError } from "../../cloud/errors.js";
76-
import { describeUnresolvedFonts, embedSystemFonts } from "../../cloud/fontPreflight.js";
76+
import { describeSwappedFonts, embedSystemFonts } from "../../cloud/fontPreflight.js";
7777
import { parseEnumFlag, parseIntFlag, parseNumericFlag } from "../../cloud/parsing.js";
7878
import { uploadAssetViaDirectUpload, uploadZipViaDirectUpload } from "../../cloud/upload.js";
7979
import {
@@ -325,7 +325,10 @@ export default defineCommand({
325325
if (asJson) {
326326
console.log(
327327
JSON.stringify(
328-
withMeta({ render: { render_id: renderId, status: "queued" as const } }),
328+
withMeta({
329+
render: { render_id: renderId, status: "queued" as const },
330+
swapped_fonts: preparedArchive?.swappedFonts ?? [],
331+
}),
329332
null,
330333
2,
331334
),
@@ -370,6 +373,7 @@ export default defineCommand({
370373
render: detail,
371374
output_path: outputPath,
372375
bytes_written: downloadResult.bytes,
376+
swapped_fonts: preparedArchive?.swappedFonts ?? [],
373377
}),
374378
null,
375379
2,
@@ -649,6 +653,8 @@ interface PreparedLocalArchive {
649653
fileCount: number;
650654
largestFiles: ArchiveFileSummary[];
651655
offloaded: OffloadedMedia[];
656+
/** Fonts not on this computer: the cloud renders them in the fallback a local render uses. */
657+
swappedFonts: string[];
652658
}
653659

654660
function summarizeLargestFiles(fileMap: Map<string, StagedFile>): ArchiveFileSummary[] {
@@ -671,16 +677,13 @@ async function prepareLocalArchive(
671677
console.log(`${c.accent("◆")} Zipping ${c.accent(project.name)}`);
672678
}
673679
const { fileMap, entryPath } = stageProjectFiles(project, composition);
674-
const missingFonts = await embedSystemFonts({
680+
const swappedFonts = await embedSystemFonts({
675681
dir: project.dir,
676682
entryFile: composition,
677683
entryPath,
678684
fileMap,
679685
});
680-
if (missingFonts.length > 0) {
681-
errorBox("Fonts not on this computer", describeUnresolvedFonts(missingFonts));
682-
failCommand();
683-
}
686+
if (swappedFonts.length > 0 && !asJson) console.log(c.dim(describeSwappedFonts(swappedFonts)));
684687
const offloaded = await offloadMedia(project, fileMap, entryPath, asJson, upload, variablesText);
685688

686689
// Media left on disk barely compresses: past the limit, its size is the report and nothing is read.
@@ -703,6 +706,7 @@ async function prepareLocalArchive(
703706
fileCount: fileMap.size,
704707
largestFiles,
705708
offloaded,
709+
swappedFonts,
706710
};
707711
if (upload) assertArchiveFits(sizeBytes, largestFiles);
708712
if (!asJson && sizeBytes >= ARCHIVE_DIAGNOSTIC_THRESHOLD_BYTES) {
@@ -828,6 +832,7 @@ function reportDryRun(prepared: PreparedLocalArchive, asJson: boolean): void {
828832
exceeds_upload_limit: sizeBytes > DIRECT_UPLOAD_LIMIT_BYTES,
829833
largest_files: prepared.largestFiles,
830834
offloaded_media: prepared.offloaded,
835+
swapped_fonts: prepared.swappedFonts,
831836
},
832837
}),
833838
null,

0 commit comments

Comments
 (0)