|
| 1 | +// Carries the system fonts a project uses inside its zip, as the cloud has no copy of them. |
| 2 | +import { bundleWithLocalizedFonts } from "../utils/bundleWithLocalizedFonts.js"; |
| 3 | +import { loadProducer } from "../utils/producer.js"; |
| 4 | +import { readStaged, type StagedFile } from "../utils/publishProject.js"; |
| 5 | + |
| 6 | +// Free look-alikes for system fonts the cloud lacks. |
| 7 | +const LOOK_ALIKES: Record<string, string> = { |
| 8 | + "pingfang sc": "Noto Sans SC", |
| 9 | + "pingfang tc": "Noto Sans TC", |
| 10 | + "pingfang hk": "Noto Sans HK", |
| 11 | + "hiragino sans": "Noto Sans JP", |
| 12 | + "hiragino kaku gothic pro": "Noto Sans JP", |
| 13 | + "yu gothic": "Noto Sans JP", |
| 14 | + "apple sd gothic neo": "Noto Sans KR", |
| 15 | + "malgun gothic": "Noto Sans KR", |
| 16 | + "microsoft yahei": "Noto Sans SC", |
| 17 | + "microsoft jhenghei": "Noto Sans TC", |
| 18 | + "sf pro": "Inter", |
| 19 | + "sf pro display": "Inter", |
| 20 | + "sf pro text": "Inter", |
| 21 | + "helvetica neue": "Inter", |
| 22 | + helvetica: "Inter", |
| 23 | + arial: "Inter", |
| 24 | + "segoe ui": "Inter", |
| 25 | + georgia: "Lora", |
| 26 | + "times new roman": "Tinos", |
| 27 | + menlo: "JetBrains Mono", |
| 28 | + consolas: "JetBrains Mono", |
| 29 | +}; |
| 30 | + |
| 31 | +function lookAlikeFor(family: string): string | undefined { |
| 32 | + return LOOK_ALIKES[family.trim().toLowerCase()]; |
| 33 | +} |
| 34 | + |
| 35 | +type Injector = (html: string, options: object) => Promise<string>; |
| 36 | + |
| 37 | +const QUIET = { warn() {}, info() {} }; |
| 38 | + |
| 39 | +async function injectorOr(inject?: Injector): Promise<Injector> { |
| 40 | + return ( |
| 41 | + inject ?? |
| 42 | + ((await loadProducer()) as { injectDeterministicFontFaces: Injector }) |
| 43 | + .injectDeterministicFontFaces |
| 44 | + ); |
| 45 | +} |
| 46 | + |
| 47 | +/** The families the resolver names in a fail-closed error, or null when it failed another way. */ |
| 48 | +function namedFamilies(err: unknown): string[] | null { |
| 49 | + const e = err as { code?: unknown; unresolvedFamilies?: unknown }; |
| 50 | + if (e.code !== "FONT_FETCH_FAILED" || !Array.isArray(e.unresolvedFamilies)) return null; |
| 51 | + return e.unresolvedFamilies.filter((f): f is string => typeof f === "string"); |
| 52 | +} |
| 53 | + |
| 54 | +/** The families the cloud cannot resolve; empty when all resolve or it cannot tell. */ |
| 55 | +async function unresolvedCloudFonts( |
| 56 | + dir: string, |
| 57 | + entryFile: string | undefined, |
| 58 | + run: Injector, |
| 59 | +): Promise<string[]> { |
| 60 | + try { |
| 61 | + await bundleWithLocalizedFonts( |
| 62 | + dir, |
| 63 | + (html) => |
| 64 | + run(html, { failClosedFontFetch: true, allowSystemFontCapture: false, logger: QUIET }), |
| 65 | + { entryFile }, |
| 66 | + ); |
| 67 | + return []; |
| 68 | + } catch (err) { |
| 69 | + // Only a named font counts; a network failure is the server's call. |
| 70 | + return namedFamilies(err) ?? []; |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * 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. |
| 77 | + */ |
| 78 | +export async function embedSystemFonts( |
| 79 | + opts: { dir: string; entryFile?: string; entryPath: string; fileMap: Map<string, StagedFile> }, |
| 80 | + inject?: Injector, |
| 81 | +): Promise<string[]> { |
| 82 | + const run = await injectorOr(inject); |
| 83 | + const wanted = await unresolvedCloudFonts(opts.dir, opts.entryFile, run); |
| 84 | + if (wanted.length === 0) return []; |
| 85 | + const css = wanted.map((f, i) => `.f${i}{font-family:"${f}"}`).join(""); |
| 86 | + 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)] |
| 99 | + .map((m) => m[1] ?? "") |
| 100 | + .filter((css) => css.includes("@font-face")) |
| 101 | + .join("\n"); |
| 102 | + const entry = opts.fileMap.get(opts.entryPath); |
| 103 | + if (!faces || !entry) return wanted; |
| 104 | + const html = readStaged(entry).toString("utf-8"); |
| 105 | + const tag = `<style data-hf-system-fonts>${faces}</style>`; |
| 106 | + const at = html.search(/<\/head>/i); |
| 107 | + opts.fileMap.set( |
| 108 | + opts.entryPath, |
| 109 | + Buffer.from(at < 0 ? tag + html : html.slice(0, at) + tag + html.slice(at), "utf-8"), |
| 110 | + ); |
| 111 | + return []; |
| 112 | +} |
| 113 | + |
| 114 | +/** One line per font, with the swap when there is one. */ |
| 115 | +export function describeUnresolvedFonts(families: readonly string[]): string { |
| 116 | + return families |
| 117 | + .map((family) => { |
| 118 | + 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.`; |
| 122 | + }) |
| 123 | + .join("\n"); |
| 124 | +} |
0 commit comments