Open in a new tab

Read a .ttf or .otf picked by the user with the hardened parser: flavour, family, units per em, glyph count, and for a typed character its glyph index, advance width and outline as an inline SVG path; a non-font shows the typed error.

Uses @awacloud/fonts (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only. No font file is committed here: bring your own, or use Liberation Sans (SIL Open Font License 1.1) from @awacloud/oconv-fonts.

When to use it

Accepting font uploads — a design tool, a document generator, a font manager in the browser — where the file comes from a user and the parser must refuse malformed input with a clear message instead of crashing or mis-rendering; and any time you need glyph metrics or outlines without a canvas.

Copy-paste steps

  1. npm install @awacloud/fonts (it depends on @awacloud/fw).
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ and node_modules/@awacloud/fonts/src/ at /vendor/fonts/ (any static server).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link. Keep the legal notice under </main>: copy ../../LICENSES/AGPL-3.0-only.txt along, or point its link at your copy.
  4. Keep inspect() as the single entry for untrusted bytes: it returns { ok: false, error } for the typed ParseError and lets anything else propagate.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/fonts's fw_require (the binary reader/writer and the compression closure WOFF needs) and modules; rt.resolve('fonts') and rt.resolve('fontErrors').
  • Parsing untrusted input: fonts.read(bytes) validates every table and the cross-table references (the README's security section: cmap range bombs, composite width and depth, count caps, consistent tables) and throws a ParseError with a fonts/… code on anything malformed.
  • The Font object: flavor (truetype, cff, …), names (family, subfamily, fullName, postScriptName, …), unitsPerEm, numGlyphs, glyphIndexForCodePoint(cp, { strict: true }) (-1 when absent, instead of the ambiguous .notdef 0) and getGlyphByIndex(gid).
  • A glyph: advanceWidth, bbox and path.toSvgPath() in font design units with y up; the page flips it with transform="scale(1 -1)" and sets the viewBox from the bounding box.
  • Not shown: WOFF/WOFF2 decoding (the parser does it when the bytes are WOFF), variable-font instancing, the OpenType layout tables, the coverage bundles and the extras; subsetting is in fonts/subset-for-pdf.

Code

main.js

javascriptAGPL-3.0-only80 lines

// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/fonts';

const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules]);
const FONTS = rt.resolve('fonts');
const { ParseError } = rt.resolve('fontErrors');

/**
 * Parse untrusted font bytes. The parsers bound every table (cmap ranges,
 * composite depth, counts, cross-table consistency) and throw a typed
 * `ParseError`, never a bare `Error`, so a bad upload is a readable line.
 * @param {Uint8Array} bytes
 * @returns {{ ok: true, font: any, flavor: string, family: string, subfamily: string,
 *   unitsPerEm: number, numGlyphs: number } | { ok: false, error: string }}
 */
export function inspect(bytes) {
    try {
        const font = FONTS.read(bytes);
        const { flavor, names: { family, subfamily }, unitsPerEm, numGlyphs } = font;
        return { ok: true, font, flavor, family, subfamily, unitsPerEm, numGlyphs };
    } catch (err) {
        if (err instanceof ParseError) return { ok: false, error: `${err.code}: ${err.message}` };
        throw err;
    }
}

/**
 * The glyph of one character: its index, advance width and outline as an SVG
 * path, all in font design units (y up), or `null` when the font has none.
 * @param {any} font a `fonts.read` result
 * @param {string} char
 */
export function glyphOf(font, char) {
    const gid = font.glyphIndexForCodePoint(/** @type {number} */ (char.codePointAt(0)), { strict: true });
    if (gid < 0) return null;
    const { advanceWidth, bbox, path } = font.getGlyphByIndex(gid);
    return { gid, advanceWidth, bbox, svgPath: path ? path.toSvgPath() : '' };
}

const input = /** @type {HTMLInputElement} */ (document.getElementById('file'));
const charInput = /** @type {HTMLInputElement} */ (document.getElementById('char'));
const summary = /** @type {HTMLElement} */ (document.getElementById('summary'));
const glyphInfo = /** @type {HTMLElement} */ (document.getElementById('glyph-info'));
const svg = /** @type {SVGElement} */ (document.getElementById('glyph'));
const outline = /** @type {SVGElement} */ (document.getElementById('outline'));
let font = /** @type {any} */ (null);

function showGlyph() {
    const [char] = [...charInput.value];
    const glyph = font && char ? glyphOf(font, char) : null;
    if (!glyph) {
        glyphInfo.textContent = font && char ? `no glyph for "${char}"` : '';
        outline.removeAttribute('d');
        return;
    }
    const box = glyph.bbox ?? { xMin: 0, yMin: 0, xMax: glyph.advanceWidth, yMax: font.unitsPerEm };
    glyphInfo.textContent = `"${char}": glyph ${glyph.gid}, advance width ${glyph.advanceWidth} units`;
    outline.setAttribute('d', glyph.svgPath);
    // y up → flipped by the path transform
    svg.setAttribute('viewBox', `${box.xMin} ${-box.yMax} ${box.xMax - box.xMin || 1} ${box.yMax - box.yMin || 1}`);
}

input.addEventListener('change', async () => {
    const [file] = input.files ?? [];
    if (!file) return;
    const result = inspect(new Uint8Array(await file.arrayBuffer()));
    font = result.ok ? result.font : null;
    const rows = !result.ok ? [['Error', result.error]] : [
        ['Flavour', result.flavor], ['Family', result.family], ['Style', result.subfamily],
        ['Units per em', String(result.unitsPerEm)], ['Glyphs', String(result.numGlyphs)]];
    summary.replaceChildren(...rows.flatMap(([k, v]) => {
        const dt = document.createElement('dt'); dt.textContent = k;
        const dd = document.createElement('dd'); dd.textContent = v;
        return [dt, dd];
    }));
    showGlyph();
});
charInput.addEventListener('input', showGlyph);

index.html

htmlAGPL-3.0-only46 lines

<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fonts · Inspect a font file and draw one glyph</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
    "@awacloud/fonts": "/vendor/fonts/main.js", "@awacloud/fonts/": "/vendor/fonts/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Inspect a font file and draw one glyph</h1>
    <p>
      <label for="file">Font file (.ttf, .otf)</label>
      <input id="file" type="file" accept=".ttf,.otf,font/ttf,font/otf">
    </p>
    <dl id="summary" aria-live="polite"></dl>
    <p>
      <label for="char">Character</label>
      <input id="char" type="text" value="A" maxlength="2" size="2">
      <span id="glyph-info" aria-live="polite"></span>
    </p>
    <svg id="glyph" width="160" height="160" role="img" aria-label="Glyph outline">
      <path id="outline" transform="scale(1 -1)" fill="currentColor"></path></svg>
    <p>The file is parsed in memory and never uploaded.</p>
  </main>
  <!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
  <footer id="legal" aria-label="Legal notices">
    <p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
      version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
      <a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
    <p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
    <ul>
      <li>@awacloud/fw · Apache-2.0</li>
      <li>@awacloud/fonts · AGPL-3.0-only</li>
    </ul>
  </footer>
  <!-- aln:end -->
</body>
</html>