@hamur/fonts 0.0.0-stage → 0.0.2

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.
Files changed (79) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/index.js +2472 -0
  4. package/dist/src/providers/index.js +386 -0
  5. package/dist/src/server/index.js +22 -0
  6. package/dist/types/src/build/cache.d.ts +17 -0
  7. package/dist/types/src/build/data.d.ts +19 -0
  8. package/dist/types/src/build/fallbacks.d.ts +49 -0
  9. package/dist/types/src/build/files.d.ts +7 -0
  10. package/dist/types/src/build/global.d.ts +3 -0
  11. package/dist/types/src/build/preload.d.ts +25 -0
  12. package/dist/types/src/build/providers.d.ts +5 -0
  13. package/dist/types/src/build/public-url.d.ts +2 -0
  14. package/dist/types/src/build/scan.d.ts +6 -0
  15. package/dist/types/src/build/subset.d.ts +7 -0
  16. package/dist/types/src/index.d.ts +18 -0
  17. package/dist/types/src/inject.d.ts +21 -0
  18. package/dist/types/src/module.d.ts +3 -0
  19. package/dist/types/src/options.d.ts +46 -0
  20. package/dist/types/src/providers/adobe.d.ts +2 -0
  21. package/dist/types/src/providers/bunny.d.ts +4 -0
  22. package/dist/types/src/providers/css.d.ts +27 -0
  23. package/dist/types/src/providers/fontshare.d.ts +4 -0
  24. package/dist/types/src/providers/fontsource.d.ts +18 -0
  25. package/dist/types/src/providers/google.d.ts +4 -0
  26. package/dist/types/src/providers/googleicons.d.ts +2 -0
  27. package/dist/types/src/providers/index.d.ts +3 -0
  28. package/dist/types/src/providers/local.d.ts +17 -0
  29. package/dist/types/src/providers/npm.d.ts +5 -0
  30. package/dist/types/src/resolve.d.ts +32 -0
  31. package/dist/types/src/runtime/global.d.ts +3 -0
  32. package/dist/types/src/scan.d.ts +29 -0
  33. package/dist/types/src/server/data.d.ts +11 -0
  34. package/dist/types/src/server/door.d.ts +2 -0
  35. package/dist/types/src/server/index.d.ts +9 -0
  36. package/dist/types/src/server/preload.d.ts +2 -0
  37. package/dist/types/src/subset/cmap.d.ts +2 -0
  38. package/dist/types/src/subset/glyf.d.ts +15 -0
  39. package/dist/types/src/subset/sfnt.d.ts +21 -0
  40. package/dist/types/src/subset/woff2.d.ts +7 -0
  41. package/dist/types/src/types.d.ts +71 -0
  42. package/package.json +41 -4
  43. package/src/build/cache.ts +50 -0
  44. package/src/build/data.ts +145 -0
  45. package/src/build/fallbacks.ts +384 -0
  46. package/src/build/files.ts +102 -0
  47. package/src/build/global.ts +14 -0
  48. package/src/build/preload.ts +104 -0
  49. package/src/build/providers.ts +19 -0
  50. package/src/build/public-url.ts +21 -0
  51. package/src/build/scan.ts +172 -0
  52. package/src/build/subset.ts +74 -0
  53. package/src/env.d.ts +13 -0
  54. package/src/index.ts +25 -0
  55. package/src/inject.ts +59 -0
  56. package/src/module.ts +29 -0
  57. package/src/options.ts +375 -0
  58. package/src/providers/adobe.ts +18 -0
  59. package/src/providers/bunny.ts +35 -0
  60. package/src/providers/css.ts +154 -0
  61. package/src/providers/fontshare.ts +37 -0
  62. package/src/providers/fontsource.ts +53 -0
  63. package/src/providers/google.ts +31 -0
  64. package/src/providers/googleicons.ts +20 -0
  65. package/src/providers/index.ts +17 -0
  66. package/src/providers/local.ts +141 -0
  67. package/src/providers/npm.ts +96 -0
  68. package/src/resolve.ts +134 -0
  69. package/src/runtime/global.ts +5 -0
  70. package/src/scan.ts +275 -0
  71. package/src/server/data.ts +20 -0
  72. package/src/server/door.ts +13 -0
  73. package/src/server/index.ts +9 -0
  74. package/src/server/preload.ts +50 -0
  75. package/src/subset/cmap.ts +79 -0
  76. package/src/subset/glyf.ts +93 -0
  77. package/src/subset/sfnt.ts +196 -0
  78. package/src/subset/woff2.ts +68 -0
  79. package/src/types.ts +71 -0
@@ -0,0 +1,196 @@
1
+ import { readCmap, readTables, type Table } from "../build/fallbacks.ts"
2
+ import { writeCmap } from "./cmap.ts"
3
+ import { glyphClosure, glyphOffsets, subsetGlyf } from "./glyf.ts"
4
+
5
+ export type SubsetResult =
6
+ { outlines: "cff" } | { outlines: "gvar" } | { outlines: "glyf"; tables: Map<string, Uint8Array> }
7
+
8
+ // Tables that name no glyph id; every other table not rebuilt here (GPOS, GSUB, GDEF, hdmx, vmtx, …) is dropped.
9
+ const KEPT = new Set(["name", "OS/2", "cvt ", "fpgm", "prep", "gasp"])
10
+
11
+ // FreeType's Latin autohinter (Chrome's slight hinting) sets its blue zones from these characters in the cmap, so without them the kept glyphs hint differently: afblue.dat AF_BLUE_STRINGSET_LATN and the latn standard characters.
12
+ export const AUTOHINT_LATIN = ["THEZOCQS", "HEZLOCUS", "fijkdbh", "xzroesc", "pqgjy", "oO0"].join("")
13
+
14
+ const view = (bytes: Uint8Array): DataView => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
15
+ const pad4 = (length: number): number => (length + 3) & ~3
16
+ const bytesOf = (table: Table): Uint8Array =>
17
+ new Uint8Array(table.data.buffer, table.data.byteOffset, table.data.byteLength)
18
+
19
+ /** The sum of a table's bytes as big-endian 32-bit words, the last word padded with zeros. */
20
+ export function checksum(bytes: Uint8Array): number {
21
+ const data = view(bytes)
22
+ const whole = bytes.byteLength & ~3
23
+ let sum = 0
24
+ for (let at = 0; at < whole; at += 4) sum = (sum + data.getUint32(at)) >>> 0
25
+ if (whole < bytes.byteLength) {
26
+ const last = new Uint8Array(4)
27
+ last.set(bytes.subarray(whole))
28
+ sum = (sum + view(last).getUint32(0)) >>> 0
29
+ }
30
+ return sum
31
+ }
32
+
33
+ /** A TrueType file of `tables`, each 4-byte aligned, with its directory checksums and `head.checkSumAdjustment`. */
34
+ export function writeSfnt(tables: Map<string, Uint8Array>): Uint8Array {
35
+ const tags = [...tables.keys()].sort()
36
+ const count = tags.length
37
+ const power = 2 ** Math.floor(Math.log2(count))
38
+ let size = 12 + 16 * count
39
+ const offsets = tags.map((tag) => {
40
+ const at = size
41
+ size += pad4(tables.get(tag)!.byteLength)
42
+ return at
43
+ })
44
+ const out = new Uint8Array(size)
45
+ const data = view(out)
46
+ data.setUint32(0, 0x00010000)
47
+ data.setUint16(4, count)
48
+ data.setUint16(6, 16 * power)
49
+ data.setUint16(8, Math.log2(power))
50
+ data.setUint16(10, 16 * count - 16 * power)
51
+ tags.forEach((tag, i) => {
52
+ const table = tables.get(tag)!.slice()
53
+ if (tag === "head") view(table).setUint32(8, 0)
54
+ const record = 12 + 16 * i
55
+ for (let k = 0; k < 4; k++) out[record + k] = tag.charCodeAt(k)
56
+ data.setUint32(record + 4, checksum(table))
57
+ data.setUint32(record + 8, offsets[i]!)
58
+ data.setUint32(record + 12, table.byteLength)
59
+ out.set(table, offsets[i]!)
60
+ })
61
+ const head = tags.indexOf("head")
62
+ if (head >= 0) data.setUint32(offsets[head]! + 8, (0xb1b0afba - checksum(out)) >>> 0)
63
+ return out
64
+ }
65
+
66
+ /** The format 0 subtables of a version 0 `kern` table with the pairs of kept glyphs, renumbered; `undefined` when none is left. */
67
+ export function subsetKern(kern: Uint8Array, id: ReadonlyMap<number, number>): Uint8Array | undefined {
68
+ const data = view(kern)
69
+ if (kern.byteLength < 4 || data.getUint16(0) !== 0) return undefined
70
+ const subtables: Uint8Array[] = []
71
+ let at = 4
72
+ for (let i = 0; i < data.getUint16(2) && at + 14 <= kern.byteLength; i++) {
73
+ const coverage = data.getUint16(at + 4)
74
+ // A format 0 subtable's length field wraps above 65535 bytes in real fonts; its pair count does not.
75
+ const length = coverage >> 8 === 0 ? 14 + 6 * data.getUint16(at + 6) : data.getUint16(at + 2)
76
+ if (coverage >> 8 === 0) {
77
+ const pairs: Array<[number, number, number]> = []
78
+ for (let p = 0; p < data.getUint16(at + 6); p++) {
79
+ const pair = at + 14 + 6 * p
80
+ const left = id.get(data.getUint16(pair))
81
+ const right = id.get(data.getUint16(pair + 2))
82
+ if (left !== undefined && right !== undefined) pairs.push([left, right, data.getInt16(pair + 4)])
83
+ }
84
+ if (pairs.length > 0) {
85
+ pairs.sort((a, b) => a[0] - b[0] || a[1] - b[1])
86
+ const out = new Uint8Array(14 + 6 * pairs.length)
87
+ const write = view(out)
88
+ const power = 2 ** Math.floor(Math.log2(pairs.length))
89
+ write.setUint16(2, out.byteLength)
90
+ write.setUint16(4, coverage)
91
+ write.setUint16(6, pairs.length)
92
+ write.setUint16(8, 6 * power)
93
+ write.setUint16(10, Math.log2(power))
94
+ write.setUint16(12, 6 * pairs.length - 6 * power)
95
+ pairs.forEach(([left, right, value], p) => {
96
+ write.setUint16(14 + 6 * p, left)
97
+ write.setUint16(16 + 6 * p, right)
98
+ write.setInt16(18 + 6 * p, value)
99
+ })
100
+ subtables.push(out)
101
+ }
102
+ }
103
+ at += length
104
+ }
105
+ if (subtables.length === 0) return undefined
106
+ const out = new Uint8Array(4 + subtables.reduce((sum, table) => sum + table.byteLength, 0))
107
+ view(out).setUint16(2, subtables.length)
108
+ let offset = 4
109
+ for (const table of subtables) {
110
+ out.set(table, offset)
111
+ offset += table.byteLength
112
+ }
113
+ return out
114
+ }
115
+
116
+ /**
117
+ * The tables of a TrueType font (TTF, WOFF, or WOFF2 with null-transformed `glyf`, `loca` and `hmtx`)
118
+ * cut to glyph 0, the glyphs `text` maps to (with `AUTOHINT_LATIN` when `text` holds a Latin letter) and their composite parts, renumbered. A CFF font and a font with `gvar`
119
+ * are not cut. Throws when the file cannot be read.
120
+ */
121
+ export function subsetFont(bytes: Uint8Array, text: string): SubsetResult {
122
+ const source = readTables(bytes)
123
+ if (source.has("CFF ") || source.has("CFF2")) return { outlines: "cff" }
124
+ if (source.has("gvar")) return { outlines: "gvar" }
125
+ const table = (tag: string): Uint8Array => {
126
+ const found = source.get(tag)
127
+ if (!found) throw new Error(`no ${tag}`)
128
+ if (found.transformed) throw new Error(`a transformed ${tag} is not read`)
129
+ return bytesOf(found)
130
+ }
131
+ const head = table("head").slice()
132
+ const hhea = table("hhea").slice()
133
+ const maxp = table("maxp").slice()
134
+ const hmtx = view(table("hmtx"))
135
+ const glyf = table("glyf")
136
+ const numGlyphs = view(maxp).getUint16(4)
137
+ const offsets = glyphOffsets(table("loca"), view(head).getInt16(50), numGlyphs, glyf.byteLength)
138
+
139
+ const glyphOf = readCmap(source.get("cmap"))
140
+ const wanted = /\p{Script=Latin}/u.test(text) ? text + AUTOHINT_LATIN : text
141
+ const mapped = [...new Set(Array.from(wanted, (char) => char.codePointAt(0)!))]
142
+ .sort((a, b) => a - b)
143
+ .map((codePoint) => [codePoint, glyphOf(codePoint)] as const)
144
+ .filter(([, glyph]) => glyph > 0 && glyph < numGlyphs)
145
+ const kept = glyphClosure(
146
+ glyf,
147
+ offsets,
148
+ mapped.map(([, glyph]) => glyph),
149
+ )
150
+ const id = new Map(kept.map((glyph, index) => [glyph, index]))
151
+ const outlines = subsetGlyf(glyf, offsets, kept)
152
+
153
+ const longMetrics = view(hhea).getUint16(34)
154
+ if (longMetrics === 0) throw new Error("hhea.numberOfHMetrics is 0")
155
+ const advance = (glyph: number): number => hmtx.getUint16(4 * Math.min(glyph, longMetrics - 1))
156
+ const bearing = (glyph: number): number =>
157
+ glyph < longMetrics ? hmtx.getInt16(4 * glyph + 2) : hmtx.getInt16(4 * longMetrics + 2 * (glyph - longMetrics))
158
+ let metrics = kept.length
159
+ while (metrics > 1 && advance(kept[metrics - 1]!) === advance(kept[metrics - 2]!)) metrics--
160
+ const newHmtx = new Uint8Array(4 * metrics + 2 * (kept.length - metrics))
161
+ const hmtxOut = view(newHmtx)
162
+ kept.forEach((glyph, index) => {
163
+ if (index < metrics) {
164
+ hmtxOut.setUint16(4 * index, advance(glyph))
165
+ hmtxOut.setInt16(4 * index + 2, bearing(glyph))
166
+ } else {
167
+ hmtxOut.setInt16(4 * metrics + 2 * (index - metrics), bearing(glyph))
168
+ }
169
+ })
170
+
171
+ view(head).setUint32(8, 0)
172
+ view(head).setInt16(50, outlines.indexToLocFormat)
173
+ view(hhea).setUint16(34, metrics)
174
+ view(maxp).setUint16(4, kept.length)
175
+
176
+ const tables = new Map<string, Uint8Array>()
177
+ for (const [tag, found] of source) if (KEPT.has(tag) && !found.transformed) tables.set(tag, bytesOf(found))
178
+ tables.set("head", head)
179
+ tables.set("hhea", hhea)
180
+ tables.set("maxp", maxp)
181
+ tables.set("hmtx", newHmtx)
182
+ tables.set("glyf", outlines.glyf)
183
+ tables.set("loca", outlines.loca)
184
+ tables.set("cmap", writeCmap(mapped.map(([codePoint, glyph]) => [codePoint, id.get(glyph)!] as const)))
185
+ const post = source.get("post")
186
+ if (post && post.data.byteLength >= 32 && !post.transformed) {
187
+ const names = new Uint8Array(32)
188
+ names.set(bytesOf(post).subarray(4, 32), 4)
189
+ view(names).setUint32(0, 0x00030000)
190
+ tables.set("post", names)
191
+ }
192
+ const kern = source.get("kern")
193
+ const pairs = kern && !kern.transformed ? subsetKern(bytesOf(kern), id) : undefined
194
+ if (pairs) tables.set("kern", pairs)
195
+ return { outlines: "glyf", tables }
196
+ }
@@ -0,0 +1,68 @@
1
+ import { brotliCompressSync, constants } from "node:zlib"
2
+ import { WOFF2_TAGS } from "../build/fallbacks.ts"
3
+
4
+ const pad4 = (length: number): number => (length + 3) & ~3
5
+
6
+ /** UIntBase128: big-endian groups of 7 bits, the high bit set on every byte but the last, no leading zero byte. */
7
+ export function base128(value: number): number[] {
8
+ const bytes: number[] = []
9
+ do {
10
+ bytes.unshift(value & 0x7f)
11
+ value = Math.floor(value / 128)
12
+ } while (value > 0)
13
+ return bytes.map((byte, i) => (i < bytes.length - 1 ? byte | 0x80 : byte))
14
+ }
15
+
16
+ /**
17
+ * WOFF2 of a TrueType font's tables: every table under its null transform (version 3 for `glyf` and `loca`, 0 for the
18
+ * others, so no `transformLength`), the table data concatenated in directory order and compressed with Brotli in font mode.
19
+ */
20
+ export function writeWoff2(tables: Map<string, Uint8Array>): Uint8Array {
21
+ const tags = [...tables.keys()].sort()
22
+ const directory: number[] = []
23
+ const data: Uint8Array[] = []
24
+ let sfntSize = 12 + 16 * tags.length
25
+ for (const tag of tags) {
26
+ let table = tables.get(tag)!
27
+ if (tag === "head") {
28
+ table = table.slice()
29
+ const head = new DataView(table.buffer)
30
+ // The WOFF2 spec asks for bit 11 of head.flags, "font data is lossless converted", in every WOFF2 file.
31
+ head.setUint16(16, head.getUint16(16) | 0x0800)
32
+ }
33
+ const known = WOFF2_TAGS.indexOf(tag)
34
+ const version = tag === "glyf" || tag === "loca" ? 3 : 0
35
+ directory.push((known === -1 ? 63 : known) | (version << 6))
36
+ if (known === -1) for (let k = 0; k < 4; k++) directory.push(tag.charCodeAt(k))
37
+ directory.push(...base128(table.byteLength))
38
+ data.push(table)
39
+ sfntSize += pad4(table.byteLength)
40
+ }
41
+ const stream = new Uint8Array(data.reduce((sum, table) => sum + table.byteLength, 0))
42
+ let at = 0
43
+ for (const table of data) {
44
+ stream.set(table, at)
45
+ at += table.byteLength
46
+ }
47
+ const compressed = brotliCompressSync(stream, {
48
+ params: {
49
+ [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_FONT,
50
+ [constants.BROTLI_PARAM_QUALITY]: 11,
51
+ [constants.BROTLI_PARAM_SIZE_HINT]: stream.byteLength,
52
+ },
53
+ })
54
+ const headerSize = 48 + directory.length
55
+ const length = pad4(headerSize + compressed.byteLength)
56
+ const out = new Uint8Array(length)
57
+ const header = new DataView(out.buffer)
58
+ out.set([0x77, 0x4f, 0x46, 0x32], 0)
59
+ header.setUint32(4, 0x00010000)
60
+ header.setUint32(8, length)
61
+ header.setUint16(12, tags.length)
62
+ header.setUint32(16, sfntSize)
63
+ header.setUint32(20, compressed.byteLength)
64
+ header.setUint16(24, 1)
65
+ out.set(directory, 48)
66
+ out.set(compressed, headerSize)
67
+ return out
68
+ }
package/src/types.ts ADDED
@@ -0,0 +1,71 @@
1
+ export type FontFormat = "woff2" | "woff" | "ttf" | "otf"
2
+ export type FontStyle = "normal" | "italic" | "oblique"
3
+ export type FontDisplay = "auto" | "block" | "swap" | "fallback" | "optional"
4
+ export type FontWeight = number | `${number}` | `${number} ${number}`
5
+
6
+ export interface FontDefaults {
7
+ weights: FontWeight[]
8
+ styles: FontStyle[]
9
+ subsets: string[]
10
+ display: FontDisplay
11
+ formats: FontFormat[]
12
+ preload: boolean
13
+ }
14
+
15
+ export interface FontFamilyOptions extends Partial<FontDefaults> {
16
+ name: string
17
+ provider?: string
18
+ src?: string | string[]
19
+ unicodeRange?: string
20
+ stretch?: string
21
+ featureSettings?: string
22
+ variationSettings?: string
23
+ glyphs?: string
24
+ global?: boolean
25
+ }
26
+
27
+ export interface FontsOptions {
28
+ enabled?: boolean
29
+ priority?: string[]
30
+ providers?: Record<string, false | string | { options?: Record<string, unknown> }>
31
+ defaults?: Partial<FontDefaults>
32
+ families?: FontFamilyOptions[]
33
+ processCSSVariables?: boolean | "font-prefixed-only"
34
+ fallbacks?: false | Record<string, string[]>
35
+ localSources?: boolean
36
+ cache?: boolean
37
+ throwOnError?: boolean
38
+ }
39
+
40
+ export interface ResolveFontOptions {
41
+ weights: string[]
42
+ styles: FontStyle[]
43
+ subsets: string[]
44
+ formats: FontFormat[]
45
+ glyphs?: string
46
+ options?: Record<string, unknown>
47
+ fetch: typeof fetch
48
+ }
49
+
50
+ export interface FontFaceData {
51
+ src: Array<{ url: string; format?: FontFormat } | { name: string }>
52
+ weight?: string
53
+ style?: string
54
+ stretch?: string
55
+ unicodeRange?: string
56
+ display?: string
57
+ featureSettings?: string
58
+ variationSettings?: string
59
+ subset?: string
60
+ }
61
+
62
+ export interface FontResolution {
63
+ fonts: FontFaceData[]
64
+ fallbacks?: string[]
65
+ }
66
+
67
+ export interface FontProvider {
68
+ name: string
69
+ /** The faces of `family` for `options`, or `undefined` when this provider does not have it. A thrown error is a failure of the provider, not of the family. */
70
+ resolveFont(family: string, options: ResolveFontOptions): Promise<FontResolution | undefined>
71
+ }