harmonink 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,119 @@
1
- # Temporary Holding Version
1
+ # harmonink
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tiny font metric normalizer. Reads a font binary, measures it from the glyph
4
+ outlines, and returns the `size-adjust`, `line-height`, `letter-spacing` and
5
+ `font-weight` that make it render at a consistent, readable x-height.
6
+
7
+ `font-size: 16px` measures the em box. Nobody reads the em box. Two fonts set at
8
+ 16px can differ by a third in the height that actually determines readability,
9
+ because x-height ratios across Google Fonts run from 0.31 to 0.66.
10
+
11
+ ```js
12
+ import { measure, normalize, toCSS } from 'harmonink';
13
+
14
+ const m = measure(readFileSync('EBGaramond.woff2'));
15
+ const rules = normalize(m);
16
+ // { sizeAdjust: 128.4, lineHeight: 28, letterSpacing: -0.0078, fontWeight: 300, … }
17
+ ```
18
+
19
+ ```
20
+ npm i harmonink # pnpm add / yarn add / bun add all work; Deno: npm:harmonink
21
+
22
+ npx harmonink ./fonts/*.woff2 -o src/styles/fonts.css
23
+ npx harmonink ./fonts/Lora.woff2 --json
24
+ npx harmonink ./fonts/*.woff2 --grid 24
25
+ ```
26
+
27
+ Emitted CSS needs no runtime:
28
+
29
+ ```css
30
+ @font-face { font-family: "EB Garamond"; src: url(…); size-adjust: 123.46% }
31
+ .text-normalized { font-family: "EB Garamond"; font-size: 1em;
32
+ line-height: 1.6875; font-weight: 300 }
33
+ ```
34
+
35
+ Relative units, so the class composes wherever it lands. `size-adjust` and
36
+ `letter-spacing` are left out when they come out as the identity, since writing them
37
+ claims a correction that did not happen and would override an inherited value. Pass
38
+ `selector` to rename the class. Given more than one font, the CLI names each class
39
+ after its family (`.eb-garamond`) so the blocks do not overwrite each other.
40
+
41
+ ## API
42
+
43
+ - `measure(buffer, { weight })` → objective metrics. TrueType outlines in `.ttf`,
44
+ `.otf`, `.woff`, `.woff2`. A variable font is measured at `weight` (400 unless
45
+ set), clamped to its `wght` axis; `weightMeasured` reports the weight used.
46
+ - `measureLive(family)` → the same shape from canvas, in the browser. No parsing,
47
+ no brotli. Rasterises the glyph rather than reading `actualBoundingBox*`, which
48
+ Chromium quantises to 1/64 em on Linux and Safari to 1/64 px; advances still come
49
+ from `measureText().width`, which is exact to five decimal places. Flagged
50
+ `approximate: true`.
51
+ - `normalize(metrics, opts)` → CSS rules. Pass `category` to override the
52
+ measured one, or `lineMode: 'hold'` to pin line height to a grid.
53
+ - `classify(metrics)` → the measured category.
54
+ - `weightFor(rules, baseWeight, steps)` → the weight correction applied to a weight
55
+ you chose, not just to 400. Snaps to 100s, or to `steps` when you know which
56
+ weights the family ships.
57
+ - `toCSS(rules, { src })` → a stylesheet fragment.
58
+
59
+ Subpath exports keep the browser bundle small: `harmonink/live` and
60
+ `harmonink/normalize` carry no dependency on the woff2 parser or `node:zlib`.
61
+
62
+ Metrics and rules are separate exports on purpose. The measurements are objective
63
+ and stable; the ruleset is opinionated and will move.
64
+
65
+ ## What the ruleset does
66
+
67
+ Size is corrected **two-way**, with `size-adjust` clamped to 90% at the bottom —
68
+ `font-size` stays 16px and the correction lives in the `@font-face` descriptor.
69
+ The x-height target is 0.54 with a ±0.04 deadband, so a face already between 0.50
70
+ and 0.58 is left as drawn.
71
+
72
+ Tracking is asymmetric on purpose. Letters are **loosened** when they are cramped
73
+ at the stem band, and **tightened** only when there is real air between the ink
74
+ and the character box — never because a face has thin strokes. Clamped ±0.025em
75
+ and never past the point where terminals crowd. Values under 0.003em are dropped
76
+ entirely — they move a full line by under 1% while still overriding whatever the
77
+ consumer inherited.
78
+
79
+ Two categories are detected rather than declared. A face counts as **handwriting**
80
+ when its letterforms scatter — the spread of flat-topped letters plus the spread
81
+ of flat feet — and gets **cap-anchored** when its lowercase are capital forms, or
82
+ its capitals are unusually small for its category.
83
+
84
+ ## Line height
85
+
86
+ `follow`, the default, treats leading as a measurement — a face scaled up gets a
87
+ taller line box. `hold` pins every face to `gridBox` (24px unless set) and lets
88
+ only the ink floor break it. The returned `gridBroken` flag says which faces it
89
+ broke for.
90
+
91
+ ```js
92
+ normalize(m, { lineMode: 'hold', gridBox: 24 });
93
+ ```
94
+
95
+ ## What it does not do
96
+
97
+ harmonink measures type and corrects it. It does not decide whether a face is
98
+ *appropriate* — for body text or anything else. That judgement depends on what
99
+ you are making and is not a property of the font file.
100
+
101
+ ## Limits
102
+
103
+ - CFF/OTF (PostScript) outlines are not supported. Throws with a clear message.
104
+ - Variable fonts are moved along the `wght` axis only. Every other axis (optical
105
+ size, width, slant) stays at its default. The `wght` axis range is reported so
106
+ weights resolve exactly rather than snapping to 100s.
107
+ - Requires Latin lowercase. Throws if `x` has no outline.
108
+ - A damaged or cut-short file throws `corrupt font file — ` and what was wrong
109
+ with it. Files built to attack a parser are not defended against.
110
+ - Hand-drawn faces with regular letterforms (Comic Neue, Itim) measure as sans.
111
+ Category is a geometric judgement, not an editorial one — pass `category`
112
+ explicitly where that matters.
113
+ - Family names from a subset whose default instance is not Regular can carry a
114
+ style word — "Figtree Light". Unambiguous mangling is cleaned; a bare trailing
115
+ style word is not, because "Shadows Into Light" is a real family. `familyRaw`
116
+ holds the untouched string.
117
+ - `measureLive` and `measure` disagree on a handful of faces whose glyphs overhang
118
+ their advances — Pacifico among them — enough to flip a category. The five are
119
+ listed in `test/live-verify.mjs`.
package/bin/cli.js ADDED
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { basename } from 'node:path';
4
+ import { measure } from '../src/measure.js';
5
+ import { normalize } from '../src/normalize.js';
6
+ import { toCSS } from '../src/css.js';
7
+
8
+ const argv = process.argv.slice(2);
9
+ const flags = {};
10
+ const files = [];
11
+ for (let i = 0; i < argv.length; i++) {
12
+ const a = argv[i];
13
+ if (a === '-o' || a === '--out') flags.out = argv[++i];
14
+ else if (a === '--json') flags.json = true;
15
+ else if (a === '--category') flags.category = argv[++i];
16
+ else if (a === '--base') flags.base = Number(argv[++i]);
17
+ else if (a === '--grid') flags.grid = Number(argv[++i]);
18
+ else if (a === '-h' || a === '--help') flags.help = true;
19
+ else files.push(a);
20
+ }
21
+
22
+ if (flags.help || !files.length) {
23
+ console.log(`harmonink — normalize a font's rendered size, leading and tracking
24
+
25
+ npx harmonink <font...> [-o out.css] emit CSS for one or more fonts
26
+ npx harmonink <font...> --json emit measurements and rules as JSON
27
+
28
+ Options
29
+ --category <sans-serif|serif|monospace|handwriting> override auto-detection
30
+ --base <px> nominal size (default 16)
31
+ --grid <px> hold line height to a fixed box
32
+
33
+ Accepts .ttf, .otf (TrueType outlines), .woff and .woff2.`);
34
+ process.exit(files.length ? 0 : 1);
35
+ }
36
+
37
+ const out = [];
38
+ let failed = 0;
39
+ for (const f of files) {
40
+ const opts = { category: flags.category, baseSize: flags.base,
41
+ lineMode: flags.grid ? 'hold' : undefined, gridBox: flags.grid };
42
+ let m, rules;
43
+ try { m = measure(readFileSync(f)); rules = normalize(m, opts); }
44
+ catch (e) { console.error(`${basename(f)}: ${e.message}`); failed++; continue; }
45
+ if (flags.json) {
46
+ out.push({ file: f, metrics: m, rules });
47
+ } else {
48
+ // shortcut: a family starting with a digit gives an invalid class name, prefix it if one turns up
49
+ const slug = (m.family ?? basename(f)).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
50
+ out.push(toCSS(rules, { src: `./${basename(f)}`, selector: files.length > 1 ? `.${slug}` : undefined }));
51
+ }
52
+ }
53
+
54
+ if (flags.json) console.log(JSON.stringify(out, null, 2));
55
+ else if (out.length) {
56
+ const css = out.join('\n');
57
+ if (flags.out) { writeFileSync(flags.out, css); console.error(`wrote ${flags.out}`); }
58
+ else process.stdout.write(css);
59
+ }
60
+ process.exit(failed ? 1 : 0);
package/package.json CHANGED
@@ -1,6 +1,140 @@
1
1
  {
2
2
  "name": "harmonink",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Tiny font metric normalizer — makes any font render at a consistent, readable x-height",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./measure": "./src/measure.js",
10
+ "./normalize": "./src/normalize.js",
11
+ "./live": "./src/live.js",
12
+ "./css": "./src/css.js"
13
+ },
14
+ "bin": {
15
+ "harmonink": "./bin/cli.js"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "bin",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "scripts": {
26
+ "test": "node test/run.js",
27
+ "census": "node test/census.mjs",
28
+ "lint": "biome lint --error-on-warnings ."
29
+ },
30
+ "keywords": [
31
+ "font",
32
+ "typography",
33
+ "x-height",
34
+ "metrics",
35
+ "readability",
36
+ "size-adjust",
37
+ "woff2"
38
+ ],
39
+ "license": "MIT",
40
+ "homepage": "https://harmonink.dev",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/rylanwill/harmonink.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/rylanwill/harmonink/issues"
47
+ },
48
+ "sideEffects": false,
49
+ "devDependencies": {
50
+ "@biomejs/biome": "^2.6.7",
51
+ "@fontsource-variable/bitter": "^5.3.0",
52
+ "@fontsource-variable/cormorant-garamond": "^5.3.0",
53
+ "@fontsource-variable/inter": "^5.3.0",
54
+ "@fontsource-variable/merriweather": "^5.3.0",
55
+ "@fontsource-variable/montserrat": "^5.3.0",
56
+ "@fontsource-variable/nunito": "^5.3.0",
57
+ "@fontsource-variable/rubik": "^5.3.0",
58
+ "@fontsource-variable/source-code-pro": "^5.3.1",
59
+ "@fontsource/amatic-sc": "^5.3.0",
60
+ "@fontsource/anonymous-pro": "^5.3.0",
61
+ "@fontsource/architects-daughter": "^5.3.0",
62
+ "@fontsource/atkinson-hyperlegible": "^5.3.0",
63
+ "@fontsource/azeret-mono": "^5.3.0",
64
+ "@fontsource/bitter": "^5.3.0",
65
+ "@fontsource/cardo": "^5.3.0",
66
+ "@fontsource/caveat": "^5.3.0",
67
+ "@fontsource/cookie": "^5.3.0",
68
+ "@fontsource/cormorant-garamond": "^5.3.0",
69
+ "@fontsource/courgette": "^5.3.0",
70
+ "@fontsource/courier-prime": "^5.3.0",
71
+ "@fontsource/cousine": "^5.3.0",
72
+ "@fontsource/crimson-text": "^5.3.0",
73
+ "@fontsource/cutive-mono": "^5.3.0",
74
+ "@fontsource/dancing-script": "^5.3.0",
75
+ "@fontsource/dm-mono": "^5.3.0",
76
+ "@fontsource/dm-sans": "^5.3.0",
77
+ "@fontsource/domine": "^5.3.0",
78
+ "@fontsource/eb-garamond": "^5.3.0",
79
+ "@fontsource/figtree": "^5.3.0",
80
+ "@fontsource/fira-mono": "^5.3.0",
81
+ "@fontsource/frank-ruhl-libre": "^5.3.0",
82
+ "@fontsource/geist-mono": "^5.3.0",
83
+ "@fontsource/gloria-hallelujah": "^5.3.0",
84
+ "@fontsource/great-vibes": "^5.3.0",
85
+ "@fontsource/handlee": "^5.3.0",
86
+ "@fontsource/homemade-apple": "^5.3.0",
87
+ "@fontsource/ibm-plex-mono": "^5.3.0",
88
+ "@fontsource/inconsolata": "^5.3.0",
89
+ "@fontsource/indie-flower": "^5.3.0",
90
+ "@fontsource/inter": "^5.3.0",
91
+ "@fontsource/jetbrains-mono": "^5.3.0",
92
+ "@fontsource/kalam": "^5.3.0",
93
+ "@fontsource/lato": "^5.3.0",
94
+ "@fontsource/libre-baskerville": "^5.3.0",
95
+ "@fontsource/literata": "^5.3.0",
96
+ "@fontsource/lora": "^5.3.0",
97
+ "@fontsource/manrope": "^5.3.0",
98
+ "@fontsource/marck-script": "^5.3.0",
99
+ "@fontsource/martian-mono": "^5.3.0",
100
+ "@fontsource/merriweather": "^5.3.0",
101
+ "@fontsource/montserrat": "^5.3.0",
102
+ "@fontsource/mulish": "^5.3.0",
103
+ "@fontsource/newsreader": "^5.3.0",
104
+ "@fontsource/noto-sans": "^5.3.0",
105
+ "@fontsource/noto-serif": "^5.3.0",
106
+ "@fontsource/nunito": "^5.3.0",
107
+ "@fontsource/nunito-sans": "^5.3.0",
108
+ "@fontsource/open-sans": "^5.3.0",
109
+ "@fontsource/oswald": "^5.3.0",
110
+ "@fontsource/overpass-mono": "^5.3.0",
111
+ "@fontsource/pacifico": "^5.3.0",
112
+ "@fontsource/patrick-hand": "^5.3.0",
113
+ "@fontsource/permanent-marker": "^5.3.0",
114
+ "@fontsource/playfair-display": "^5.3.0",
115
+ "@fontsource/plus-jakarta-sans": "^5.3.0",
116
+ "@fontsource/poppins": "^5.3.0",
117
+ "@fontsource/pt-serif": "^5.3.0",
118
+ "@fontsource/raleway": "^5.3.0",
119
+ "@fontsource/red-hat-mono": "^5.3.0",
120
+ "@fontsource/roboto": "^5.3.0",
121
+ "@fontsource/roboto-condensed": "^5.3.0",
122
+ "@fontsource/roboto-mono": "^5.3.0",
123
+ "@fontsource/roboto-slab": "^5.3.0",
124
+ "@fontsource/rubik": "^5.3.0",
125
+ "@fontsource/sacramento": "^5.3.0",
126
+ "@fontsource/satisfy": "^5.3.0",
127
+ "@fontsource/shadows-into-light": "^5.3.0",
128
+ "@fontsource/share-tech-mono": "^5.3.0",
129
+ "@fontsource/source-code-pro": "^5.3.0",
130
+ "@fontsource/source-serif-4": "^5.3.0",
131
+ "@fontsource/space-mono": "^5.3.0",
132
+ "@fontsource/spectral": "^5.3.0",
133
+ "@fontsource/ubuntu": "^5.3.0",
134
+ "@fontsource/ubuntu-mono": "^5.3.0",
135
+ "@fontsource/victor-mono": "^5.3.0",
136
+ "@fontsource/vollkorn": "^5.3.0",
137
+ "@fontsource/work-sans": "^5.3.0",
138
+ "@fontsource/yellowtail": "^5.3.0"
139
+ }
140
+ }
package/src/css.js ADDED
@@ -0,0 +1,39 @@
1
+ // Emitted in relative units so the class composes: font-size inherits, and the line
2
+ // height is the ratio that yields the measured px at the inherited size.
3
+ export function toCSS(rules, opts = {}) {
4
+ const family = opts.family || rules.family;
5
+ const src = opts.src;
6
+ const sel = opts.selector || '.text-normalized';
7
+ const q = JSON.stringify(family);
8
+
9
+ const leading = trim(rules.lineHeight / rules.fontSize);
10
+ const adjusted = rules.sizeAdjust !== 100;
11
+ const tracked = rules.letterSpacing !== 0;
12
+
13
+ const face = src ? [
14
+ `@font-face {`,
15
+ ` font-family: ${q};`,
16
+ ` src: url("${src}");`,
17
+ ` font-display: swap;`,
18
+ // a 100% adjust is the identity — emitting it says "corrected" where nothing was
19
+ ...(adjusted ? [` size-adjust: ${rules.sizeAdjust}%;`] : []),
20
+ `}`,
21
+ ].join('\n') : null;
22
+
23
+ const cls = [
24
+ `${sel} {`,
25
+ ` font-family: ${q};`,
26
+ ` font-size: 1em;`,
27
+ ` line-height: ${leading};`,
28
+ // like size-adjust, a zero here is the identity — writing it claims a correction
29
+ // that did not happen, and it would override an inherited value
30
+ ...(tracked ? [` letter-spacing: ${rules.letterSpacing}em;`] : []),
31
+ ` font-weight: ${rules.fontWeight};`,
32
+ `}`,
33
+ ].join('\n');
34
+
35
+ const head = `/* harmonink — ${family} · x-height normalized to ${rules.renderedSize}px · ${rules.category} */`;
36
+ return [head, face, cls].filter(Boolean).join('\n\n') + '\n';
37
+ }
38
+
39
+ const trim = n => Number(n.toFixed(4));
package/src/glyf.js ADDED
@@ -0,0 +1,211 @@
1
+ import { Reader, corrupt } from './sfnt.js';
2
+
3
+ function sign(f, v) { return (f & 1) ? v : -v; }
4
+ function f2dot14(r) { return r.i16() / 16384; }
5
+
6
+ export function resolveComposites(glyphs) {
7
+ const build = (g, d) => {
8
+ const gl = glyphs[g];
9
+ if (!gl || !gl.composite || !gl.comps || d > 5) return gl ? gl.contours : [];
10
+ if (gl.__resolved) return gl.contours;
11
+ const out = [];
12
+ for (const c of gl.comps) {
13
+ const sub = build(c.gi, d + 1);
14
+ for (const contour of sub)
15
+ out.push(contour.map(p => ({
16
+ x: c.a * p.x + c.c * p.y + c.dx,
17
+ y: c.b * p.x + c.d * p.y + c.dy,
18
+ on: p.on,
19
+ })));
20
+ }
21
+ gl.contours = out;
22
+ gl.__resolved = true;
23
+ return out;
24
+ };
25
+ for (let g = 0; g < glyphs.length; g++) if (glyphs[g] && glyphs[g].composite) build(g, 0);
26
+ return glyphs;
27
+ }
28
+
29
+ function readComponents(r) {
30
+ const comps = [];
31
+ let more = true, haveInstr = false;
32
+ while (more) {
33
+ const f = r.u16(), gi = r.u16();
34
+ more = (f & 0x0020) !== 0;
35
+ if (f & 0x0100) haveInstr = true;
36
+ let dx, dy;
37
+ if (f & 0x0001) { dx = r.i16(); dy = r.i16(); }
38
+ else { const a1 = r.u8(), a2 = r.u8(); dx = a1 > 127 ? a1 - 256 : a1; dy = a2 > 127 ? a2 - 256 : a2; }
39
+ if (!(f & 0x0002)) { dx = 0; dy = 0; }
40
+ let a = 1, b = 0, c2 = 0, d = 1;
41
+ if (f & 0x0008) { a = d = f2dot14(r); }
42
+ else if (f & 0x0040) { a = f2dot14(r); d = f2dot14(r); }
43
+ else if (f & 0x0080) { a = f2dot14(r); b = f2dot14(r); c2 = f2dot14(r); d = f2dot14(r); }
44
+ comps.push({ gi, dx, dy, a, b, c: c2, d });
45
+ }
46
+ return { comps, haveInstr };
47
+ }
48
+
49
+ function decodeTriplets(flagStream, r, nPoints) {
50
+ const pts = new Array(nPoints);
51
+ let x = 0, y = 0;
52
+ for (let i = 0; i < nPoints; i++) {
53
+ const raw = flagStream[i];
54
+ const on = !(raw >> 7);
55
+ const f = raw & 0x7f;
56
+ let dx, dy;
57
+ if (f < 10) {
58
+ dx = 0;
59
+ dy = sign(f, ((f & 14) << 7) + r.u8());
60
+ } else if (f < 20) {
61
+ dx = sign(f, (((f - 10) & 14) << 7) + r.u8());
62
+ dy = 0;
63
+ } else if (f < 84) {
64
+ const b0 = f - 20, b1 = r.u8();
65
+ dx = sign(f, 1 + (b0 & 0x30) + (b1 >> 4));
66
+ dy = sign(f >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f));
67
+ } else if (f < 120) {
68
+ const b0 = f - 84, b1 = r.u8(), b2 = r.u8();
69
+ dx = sign(f, 1 + (((b0 / 12) | 0) << 8) + b1);
70
+ dy = sign(f >> 1, 1 + ((((b0 % 12) >> 2)) << 8) + b2);
71
+ } else if (f < 124) {
72
+ const b0 = r.u8(), b1 = r.u8(), b2 = r.u8();
73
+ dx = sign(f, (b0 << 4) + (b1 >> 4));
74
+ dy = sign(f >> 1, ((b1 & 0x0f) << 8) + b2);
75
+ } else {
76
+ const b0 = r.u8(), b1 = r.u8(), b2 = r.u8(), b3 = r.u8();
77
+ dx = sign(f, (b0 << 8) + b1);
78
+ dy = sign(f >> 1, (b2 << 8) + b3);
79
+ }
80
+ x += dx; y += dy;
81
+ pts[i] = { x, y, on };
82
+ }
83
+ return pts;
84
+ }
85
+
86
+ export function decodeWoff2Glyf(glyfTable) {
87
+ const r = new Reader(glyfTable, 0);
88
+ r.u16(); // reserved
89
+ const optionFlags = r.u16();
90
+ const numGlyphs = r.u16();
91
+ r.u16(); // indexFormat
92
+ const nContourSize = r.u32();
93
+ const nPointsSize = r.u32();
94
+ const flagSize = r.u32();
95
+ const glyphSize = r.u32();
96
+ const compositeSize= r.u32();
97
+ const bboxSize = r.u32();
98
+ const instrSize = r.u32();
99
+ // length is implied, not stored — the header is a fixed 36 bytes
100
+ const overlapSize = (optionFlags & 1) ? ((numGlyphs + 7) >> 3) : 0;
101
+
102
+ let o = r.p;
103
+ const cut = n => { const s = glyfTable.subarray(o, o + n); o += n; return s; };
104
+ const nContour = cut(nContourSize);
105
+ const nPoints = cut(nPointsSize);
106
+ const flags = cut(flagSize);
107
+ const glyphs = cut(glyphSize);
108
+ const composite = cut(compositeSize);
109
+ const bboxes = cut(bboxSize);
110
+ cut(instrSize);
111
+ if (overlapSize) cut(overlapSize);
112
+
113
+ const bmpLen = ((numGlyphs + 31) >> 5) << 2;
114
+ const bmp = bboxes.subarray(0, bmpLen);
115
+ const bboxR = new Reader(bboxes, bmpLen);
116
+
117
+ const ncR = new Reader(nContour, 0);
118
+ const npR = new Reader(nPoints, 0);
119
+ const glR = new Reader(glyphs, 0);
120
+ const cpR = new Reader(composite, 0);
121
+ let flagPos = 0;
122
+
123
+ const out = new Array(numGlyphs);
124
+ for (let g = 0; g < numGlyphs; g++) {
125
+ const nc = ncR.i16();
126
+ const hasBbox = (bmp[g >> 3] & (0x80 >> (g & 7))) !== 0;
127
+ if (nc === 0) {
128
+ if (hasBbox) { bboxR.i16(); bboxR.i16(); bboxR.i16(); bboxR.i16(); }
129
+ out[g] = { empty: true, contours: [], composite: false };
130
+ continue;
131
+ }
132
+ if (nc < 0) {
133
+ const { comps, haveInstr } = readComponents(cpR);
134
+ if (haveInstr) glR.u255();
135
+ const bb = hasBbox
136
+ ? { xMin: bboxR.i16(), yMin: bboxR.i16(), xMax: bboxR.i16(), yMax: bboxR.i16() }
137
+ : null;
138
+ out[g] = { composite: true, contours: [], bbox: bb, comps };
139
+ continue;
140
+ }
141
+ const counts = new Array(nc);
142
+ let total = 0;
143
+ for (let i = 0; i < nc; i++) { counts[i] = npR.u255(); total += counts[i]; }
144
+ const fslice = flags.subarray(flagPos, flagPos + total);
145
+ if (fslice.length < total) throw corrupt('a table ends before its data');
146
+ flagPos += total;
147
+ const pts = decodeTriplets(fslice, glR, total);
148
+ glR.u255(); // instructionLength
149
+ const contours = [];
150
+ let i = 0;
151
+ for (const c of counts) { contours.push(pts.slice(i, i + c)); i += c; }
152
+ const bb = hasBbox
153
+ ? { xMin: bboxR.i16(), yMin: bboxR.i16(), xMax: bboxR.i16(), yMax: bboxR.i16() }
154
+ : null;
155
+ out[g] = { composite: false, contours, bbox: bb };
156
+ }
157
+ return out;
158
+ }
159
+
160
+ export function parseSfntGlyf(glyf, loca, indexToLocFormat, numGlyphs) {
161
+ const lr = new Reader(loca, 0);
162
+ const offs = new Array(numGlyphs + 1);
163
+ for (let i = 0; i <= numGlyphs; i++) offs[i] = indexToLocFormat ? lr.u32() : lr.u16() * 2;
164
+ const out = new Array(numGlyphs);
165
+ for (let g = 0; g < numGlyphs; g++) {
166
+ if (offs[g] === offs[g + 1]) { out[g] = { empty: true, contours: [], composite: false }; continue; }
167
+ const r = new Reader(glyf, offs[g]);
168
+ const nc = r.i16();
169
+ const bbox = { xMin: r.i16(), yMin: r.i16(), xMax: r.i16(), yMax: r.i16() };
170
+ if (nc < 0) {
171
+ const { comps } = readComponents(r);
172
+ out[g] = { composite: true, contours: [], bbox, comps };
173
+ continue;
174
+ }
175
+ // nothing follows the header of a glyph with no contours, so there is no instruction length to read
176
+ if (nc === 0) { out[g] = { composite: false, contours: [], bbox }; continue; }
177
+ const ends = new Array(nc);
178
+ for (let i = 0; i < nc; i++) ends[i] = r.u16();
179
+ const total = ends[nc - 1] + 1;
180
+ const instrLen = r.u16(); r.p += instrLen; // read first: += would use the stale p
181
+ const flags = new Array(total);
182
+ for (let i = 0; i < total;) {
183
+ const f = r.u8(); flags[i++] = f;
184
+ if (f & 8) { let rep = r.u8(); while (rep-- > 0 && i < total) flags[i++] = f; }
185
+ }
186
+ const xs = new Array(total); let x = 0;
187
+ for (let i = 0; i < total; i++) {
188
+ const f = flags[i];
189
+ if (f & 2) { const d = r.u8(); x += (f & 16) ? d : -d; }
190
+ else if (!(f & 16)) x += r.i16();
191
+ xs[i] = x;
192
+ }
193
+ const ys = new Array(total); let y = 0;
194
+ for (let i = 0; i < total; i++) {
195
+ const f = flags[i];
196
+ if (f & 4) { const d = r.u8(); y += (f & 32) ? d : -d; }
197
+ else if (!(f & 32)) y += r.i16();
198
+ ys[i] = y;
199
+ }
200
+ const contours = []; let s = 0;
201
+ for (const e of ends) {
202
+ // ends that go backwards would build the same points again for every contour, without limit
203
+ if (e + 1 < s) throw corrupt("a glyph's contours are out of order");
204
+ const c = [];
205
+ for (let i = s; i <= e; i++) c.push({ x: xs[i], y: ys[i], on: !!(flags[i] & 1) });
206
+ contours.push(c); s = e + 1;
207
+ }
208
+ out[g] = { composite: false, contours, bbox };
209
+ }
210
+ return out;
211
+ }