import { Buffer } from "buffer"; import parseASCII from "parse-bmfont-ascii"; import parseXML from "parse-bmfont-xml"; import readBinary from "parse-bmfont-binary"; import { BmCharacter, BmKerning, BmFont, BmCommonProps } from "./types.js"; import png from "@jimp/js-png"; import { createJimp } from "@jimp/core"; import path from "path"; import xmlPackage from "simple-xml-to-json"; const { convertXML } = xmlPackage; export const isWebWorker = typeof self !== "undefined" && self.document === undefined; const CharacterJimp = createJimp({ formats: [png] }); const HEADER = Buffer.from([66, 77, 70, 3]); function isBinary(buf: Buffer | string) { if (typeof buf === "string") { return buf.substring(0, 3) === "BMF"; } const startOfHeader = buf.slice(0, 4); return ( buf.length > 4 && startOfHeader[0] === HEADER[0] && startOfHeader[1] === HEADER[1] && startOfHeader[2] === HEADER[2] ); } export interface LoadedFont { chars: BmCharacter[]; kernings: BmKerning[]; common: BmCommonProps; // eslint-disable-next-line @typescript-eslint/no-explicit-any info: Record; pages: string[]; } function parseFont(file: string, data: Buffer | string): LoadedFont { if (isBinary(data)) { if (typeof data === "string") { data = Buffer.from(data, "binary"); } return readBinary(data); } data = data.toString().trim(); if (/.json$/.test(file) || data.charAt(0) === "{") { return JSON.parse(data); } if (/.xml$/.test(file) || data.charAt(0) === "<") { if (!isWebWorker) { return parseXML(data); } const json = convertXML(data); const font = json.font.children.reduce( // eslint-disable-next-line @typescript-eslint/no-explicit-any (acc: Record, i: any) => ({ ...acc, ...i }), {} ); const pages: LoadedFont["pages"] = []; const chars: LoadedFont["chars"] = []; const kernings: LoadedFont["kernings"] = []; for (let i = 0; i < font.pages.children.length; i++) { const p = font.pages.children[i].page; const id = parseInt(p.id, 10); pages[id] = parseNumbersInObject(p.file); } for (let i = 0; i < font.chars.children.length; i++) { chars.push(parseNumbersInObject(font.chars.children[i].char)); } for (let i = 0; i < font.kernings.children.length; i++) { kernings.push(parseNumbersInObject(font.kernings.children[i].kerning)); } return { info: font.info, common: font.common, pages, chars, kernings, } satisfies LoadedFont; } return parseASCII(data); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function parseNumbersInObject>(obj: T) { for (const key in obj) { try { // eslint-disable-next-line @typescript-eslint/no-explicit-any (obj as any)[key] = parseInt(obj[key], 10); } catch { // do nothing } if (typeof obj[key] === "object") { parseNumbersInObject(obj[key]); } } return obj; } /** * * @param bufferOrUrl A URL to a file or a buffer * @returns */ export async function loadBitmapFontData( bufferOrUrl: string | Buffer ): Promise { if (typeof bufferOrUrl === "string") { // Some Node.js-like runtimes (e.g. Raycast) don't provide fetch if (typeof globalThis.fetch !== "function") { throw new Error( `loadFont: can't load ${JSON.stringify(bufferOrUrl)} because this runtime has no global fetch. Pass a path to the .fnt file instead (it and its pages are read from disk), or install a fetch polyfill.`, ); } let res: Response; try { res = await fetch(bufferOrUrl); } catch (error) { throw new Error( `loadFont: couldn't fetch ${JSON.stringify(bufferOrUrl)}: ${(error as Error).message}`, { cause: error }, ); } // Otherwise the error page is parsed as a font if (!res.ok) { throw new Error( `loadFont: couldn't load ${JSON.stringify(bufferOrUrl)}: HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ""}`, ); } const text = await res.text(); return parseFont(bufferOrUrl, text); } else { return parseFont("", bufferOrUrl); } } type RawFont = Awaited>; export type ResolveBmFont = Omit & Pick; // Two or more characters so Windows drive letters (C:\) aren't treated as schemes const URL_SCHEME = /^[a-z][a-z\d+.-]+:/i; const ABSOLUTE_URL = /^[a-z][a-z\d+.-]+:\/\//i; /** * Resolve a page file name from the font relative to the font file. * The name comes from the font data, so it must not escape the font's directory. */ export function resolvePagePath(file: string, page: string) { const outside = new Error( `Font page is outside of the font directory: ${page}`, ); // Resolve pages of remote fonts the same way fetch will, so encoded dots // (%2e%2e) and backslashes can't be used to walk out of the directory. if (ABSOLUTE_URL.test(file)) { const dir = new URL(".", file); const url = new URL(page, file); // Encoded slashes are left alone by URL but some servers decode them if ( url.protocol !== dir.protocol || url.host !== dir.host || !url.pathname.startsWith(dir.pathname) || /%2f|%5c/i.test(url.pathname.slice(dir.pathname.length)) ) { throw outside; } return url.href; } // Checked against the page alone so the result doesn't depend on the cwd // (the browser path polyfill resolves relative paths against "/"). Relative // fonts in the browser are fetched, so treat "\\" and "%2e" like fetch does. const relative = path.join( ".", page.replace(/\\/g, "/").replace(/%2e/gi, "."), ); if (relative === ".." || relative.startsWith(`..${path.sep}`)) { throw outside; } const pagePath = path.join(path.dirname(file), page); // With no directory in front of it a page like "http://host/x.png" would // survive the join and be fetched by Jimp.read if (URL_SCHEME.test(pagePath)) { throw outside; } return pagePath; } export async function processBitmapFont(file: string, font: LoadedFont) { const chars: Record = {}; const kernings: Record = {}; for (let i = 0; i < font.chars.length; i++) { const char = font.chars[i]!; chars[String.fromCodePoint(char.id)] = char; } for (let i = 0; i < font.kernings.length; i++) { const firstString = String.fromCodePoint(font.kernings[i]!.first); kernings[firstString] = kernings[firstString]! || {}; kernings[firstString]![String.fromCodePoint(font.kernings[i]!.second)] = font.kernings[i]!.amount; } return { ...font, chars, kernings, pages: await Promise.all( font.pages.map((page) => readPage(resolvePagePath(file, page))) ), }; } const PNG_ONLY = "Jimp fonts need PNG pages. In BMFont, set the texture format to png when exporting."; /** Read a font page, explaining why pages in other formats can't be decoded */ async function readPage(pagePath: string) { try { return await CharacterJimp.read(pagePath); } catch (error) { const { message } = error as Error; if ( !message.startsWith("Could not find MIME") && !message.endsWith("does not support decoding") ) { throw error; } // BMFont exports TGA pages by default, which look like icons to Jimp const extension = path .extname(pagePath.replace(/[?#].*$/, "")) .slice(1) .toUpperCase(); const kind = extension && extension !== "PNG" ? `is a ${extension} image` : "isn't a PNG image"; throw new Error( `loadFont: font page ${JSON.stringify(pagePath)} ${kind}; ${PNG_ONLY}`, { cause: error }, ); } }