@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.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/src/index.js +2472 -0
- package/dist/src/providers/index.js +386 -0
- package/dist/src/server/index.js +22 -0
- package/dist/types/src/build/cache.d.ts +17 -0
- package/dist/types/src/build/data.d.ts +19 -0
- package/dist/types/src/build/fallbacks.d.ts +49 -0
- package/dist/types/src/build/files.d.ts +7 -0
- package/dist/types/src/build/global.d.ts +3 -0
- package/dist/types/src/build/preload.d.ts +25 -0
- package/dist/types/src/build/providers.d.ts +5 -0
- package/dist/types/src/build/public-url.d.ts +2 -0
- package/dist/types/src/build/scan.d.ts +6 -0
- package/dist/types/src/build/subset.d.ts +7 -0
- package/dist/types/src/index.d.ts +18 -0
- package/dist/types/src/inject.d.ts +21 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +46 -0
- package/dist/types/src/providers/adobe.d.ts +2 -0
- package/dist/types/src/providers/bunny.d.ts +4 -0
- package/dist/types/src/providers/css.d.ts +27 -0
- package/dist/types/src/providers/fontshare.d.ts +4 -0
- package/dist/types/src/providers/fontsource.d.ts +18 -0
- package/dist/types/src/providers/google.d.ts +4 -0
- package/dist/types/src/providers/googleicons.d.ts +2 -0
- package/dist/types/src/providers/index.d.ts +3 -0
- package/dist/types/src/providers/local.d.ts +17 -0
- package/dist/types/src/providers/npm.d.ts +5 -0
- package/dist/types/src/resolve.d.ts +32 -0
- package/dist/types/src/runtime/global.d.ts +3 -0
- package/dist/types/src/scan.d.ts +29 -0
- package/dist/types/src/server/data.d.ts +11 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/index.d.ts +9 -0
- package/dist/types/src/server/preload.d.ts +2 -0
- package/dist/types/src/subset/cmap.d.ts +2 -0
- package/dist/types/src/subset/glyf.d.ts +15 -0
- package/dist/types/src/subset/sfnt.d.ts +21 -0
- package/dist/types/src/subset/woff2.d.ts +7 -0
- package/dist/types/src/types.d.ts +71 -0
- package/package.json +41 -4
- package/src/build/cache.ts +50 -0
- package/src/build/data.ts +145 -0
- package/src/build/fallbacks.ts +384 -0
- package/src/build/files.ts +102 -0
- package/src/build/global.ts +14 -0
- package/src/build/preload.ts +104 -0
- package/src/build/providers.ts +19 -0
- package/src/build/public-url.ts +21 -0
- package/src/build/scan.ts +172 -0
- package/src/build/subset.ts +74 -0
- package/src/env.d.ts +13 -0
- package/src/index.ts +25 -0
- package/src/inject.ts +59 -0
- package/src/module.ts +29 -0
- package/src/options.ts +375 -0
- package/src/providers/adobe.ts +18 -0
- package/src/providers/bunny.ts +35 -0
- package/src/providers/css.ts +154 -0
- package/src/providers/fontshare.ts +37 -0
- package/src/providers/fontsource.ts +53 -0
- package/src/providers/google.ts +31 -0
- package/src/providers/googleicons.ts +20 -0
- package/src/providers/index.ts +17 -0
- package/src/providers/local.ts +141 -0
- package/src/providers/npm.ts +96 -0
- package/src/resolve.ts +134 -0
- package/src/runtime/global.ts +5 -0
- package/src/scan.ts +275 -0
- package/src/server/data.ts +20 -0
- package/src/server/door.ts +13 -0
- package/src/server/index.ts +9 -0
- package/src/server/preload.ts +50 -0
- package/src/subset/cmap.ts +79 -0
- package/src/subset/glyf.ts +93 -0
- package/src/subset/sfnt.ts +196 -0
- package/src/subset/woff2.ts +68 -0
- package/src/types.ts +71 -0
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import { brotliDecompressSync, inflateSync } from "node:zlib"
|
|
2
|
+
import type { FontFaceData } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
export interface FontMetrics {
|
|
5
|
+
unitsPerEm: number
|
|
6
|
+
ascender: number
|
|
7
|
+
descender: number
|
|
8
|
+
lineGap: number
|
|
9
|
+
/** The advance of `a`–`z` and the space, weighted by English frequency, in font units. */
|
|
10
|
+
meanWidth: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface SystemMetrics {
|
|
14
|
+
unitsPerEm: number
|
|
15
|
+
meanWidth: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Ratios: `1.074` is written `107.4%`. */
|
|
19
|
+
export interface FallbackOverrides {
|
|
20
|
+
sizeAdjust: number
|
|
21
|
+
ascent: number
|
|
22
|
+
descent: number
|
|
23
|
+
lineGap: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The a–z and space weights of the latin table of @capsizecss/unpack 4.0.1 (src/weightings.ts), English text frequency.
|
|
27
|
+
export const LETTER_FREQUENCY: Readonly<Record<string, number>> = {
|
|
28
|
+
" ": 0.154,
|
|
29
|
+
a: 0.0668,
|
|
30
|
+
b: 0.0114,
|
|
31
|
+
c: 0.0232,
|
|
32
|
+
d: 0.0298,
|
|
33
|
+
e: 0.0922,
|
|
34
|
+
f: 0.017,
|
|
35
|
+
g: 0.0155,
|
|
36
|
+
h: 0.0351,
|
|
37
|
+
i: 0.0588,
|
|
38
|
+
j: 0.0009,
|
|
39
|
+
k: 0.0046,
|
|
40
|
+
l: 0.0304,
|
|
41
|
+
m: 0.0181,
|
|
42
|
+
n: 0.0578,
|
|
43
|
+
o: 0.0571,
|
|
44
|
+
p: 0.0163,
|
|
45
|
+
q: 0.0008,
|
|
46
|
+
r: 0.0526,
|
|
47
|
+
s: 0.0469,
|
|
48
|
+
t: 0.0672,
|
|
49
|
+
u: 0.0207,
|
|
50
|
+
v: 0.0076,
|
|
51
|
+
w: 0.011,
|
|
52
|
+
x: 0.0025,
|
|
53
|
+
y: 0.0123,
|
|
54
|
+
z: 0.0011,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// LETTER_FREQUENCY over hmtx of metric-compatible open fonts (Liberation Sans for Arial and Helvetica, Liberation Serif, Liberation Mono, Gelasio, Selawik, Roboto), each within 0.03 % of @capsizecss/metrics 4.5.0 xWidthAvg under capsize's own weights; 2026-11-23.
|
|
58
|
+
export const SYSTEM_METRICS: Readonly<Record<string, SystemMetrics>> = {
|
|
59
|
+
Arial: { unitsPerEm: 2048, meanWidth: 899.0846 },
|
|
60
|
+
Helvetica: { unitsPerEm: 2048, meanWidth: 899.0846 },
|
|
61
|
+
"Times New Roman": { unitsPerEm: 2048, meanWidth: 814.8911 },
|
|
62
|
+
Georgia: { unitsPerEm: 2048, meanWidth: 896.64 },
|
|
63
|
+
"Courier New": { unitsPerEm: 2048, meanWidth: 1229 },
|
|
64
|
+
"Segoe UI": { unitsPerEm: 2048, meanWidth: 901.7859 },
|
|
65
|
+
Roboto: { unitsPerEm: 2048, meanWidth: 902.8188 },
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface Table {
|
|
69
|
+
data: DataView
|
|
70
|
+
/** WOFF2 transform version 1 of `hmtx`. */
|
|
71
|
+
transformed: boolean
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const view = (bytes: Uint8Array): DataView => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
75
|
+
const tagAt = (data: DataView, at: number): string =>
|
|
76
|
+
String.fromCharCode(data.getUint8(at), data.getUint8(at + 1), data.getUint8(at + 2), data.getUint8(at + 3))
|
|
77
|
+
|
|
78
|
+
function slice(bytes: Uint8Array, offset: number, length: number): Uint8Array {
|
|
79
|
+
if (offset + length > bytes.byteLength) throw new Error("a table runs past the end of the file")
|
|
80
|
+
return bytes.subarray(offset, offset + length)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function sfntTables(bytes: Uint8Array): Map<string, Table> {
|
|
84
|
+
const data = view(bytes)
|
|
85
|
+
const tables = new Map<string, Table>()
|
|
86
|
+
const count = data.getUint16(4)
|
|
87
|
+
for (let i = 0; i < count; i++) {
|
|
88
|
+
const at = 12 + 16 * i
|
|
89
|
+
tables.set(tagAt(data, at), {
|
|
90
|
+
data: view(slice(bytes, data.getUint32(at + 8), data.getUint32(at + 12))),
|
|
91
|
+
transformed: false,
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
return tables
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function woffTables(bytes: Uint8Array): Map<string, Table> {
|
|
98
|
+
const data = view(bytes)
|
|
99
|
+
const tables = new Map<string, Table>()
|
|
100
|
+
const count = data.getUint16(12)
|
|
101
|
+
for (let i = 0; i < count; i++) {
|
|
102
|
+
const at = 44 + 20 * i
|
|
103
|
+
const stored = slice(bytes, data.getUint32(at + 4), data.getUint32(at + 8))
|
|
104
|
+
const length = data.getUint32(at + 12)
|
|
105
|
+
const table = stored.byteLength < length ? new Uint8Array(inflateSync(stored)) : stored
|
|
106
|
+
tables.set(tagAt(data, at), { data: view(table), transformed: false })
|
|
107
|
+
}
|
|
108
|
+
return tables
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const WOFF2_TAGS = [
|
|
112
|
+
"cmap",
|
|
113
|
+
"head",
|
|
114
|
+
"hhea",
|
|
115
|
+
"hmtx",
|
|
116
|
+
"maxp",
|
|
117
|
+
"name",
|
|
118
|
+
"OS/2",
|
|
119
|
+
"post",
|
|
120
|
+
"cvt ",
|
|
121
|
+
"fpgm",
|
|
122
|
+
"glyf",
|
|
123
|
+
"loca",
|
|
124
|
+
"prep",
|
|
125
|
+
"CFF ",
|
|
126
|
+
"VORG",
|
|
127
|
+
"EBDT",
|
|
128
|
+
"EBLC",
|
|
129
|
+
"gasp",
|
|
130
|
+
"hdmx",
|
|
131
|
+
"kern",
|
|
132
|
+
"LTSH",
|
|
133
|
+
"PCLT",
|
|
134
|
+
"VDMX",
|
|
135
|
+
"vhea",
|
|
136
|
+
"vmtx",
|
|
137
|
+
"BASE",
|
|
138
|
+
"GDEF",
|
|
139
|
+
"GPOS",
|
|
140
|
+
"GSUB",
|
|
141
|
+
"EBSC",
|
|
142
|
+
"JSTF",
|
|
143
|
+
"MATH",
|
|
144
|
+
"CBDT",
|
|
145
|
+
"CBLC",
|
|
146
|
+
"COLR",
|
|
147
|
+
"CPAL",
|
|
148
|
+
"SVG ",
|
|
149
|
+
"sbix",
|
|
150
|
+
"acnt",
|
|
151
|
+
"avar",
|
|
152
|
+
"bdat",
|
|
153
|
+
"bloc",
|
|
154
|
+
"bsln",
|
|
155
|
+
"cvar",
|
|
156
|
+
"fdsc",
|
|
157
|
+
"feat",
|
|
158
|
+
"fmtx",
|
|
159
|
+
"fvar",
|
|
160
|
+
"gvar",
|
|
161
|
+
"hsty",
|
|
162
|
+
"just",
|
|
163
|
+
"lcar",
|
|
164
|
+
"mort",
|
|
165
|
+
"morx",
|
|
166
|
+
"opbd",
|
|
167
|
+
"prop",
|
|
168
|
+
"trak",
|
|
169
|
+
"Zapf",
|
|
170
|
+
"Silf",
|
|
171
|
+
"Glat",
|
|
172
|
+
"Gloc",
|
|
173
|
+
"Feat",
|
|
174
|
+
"Sill",
|
|
175
|
+
]
|
|
176
|
+
|
|
177
|
+
function base128(data: DataView, at: { offset: number }): number {
|
|
178
|
+
let value = 0
|
|
179
|
+
for (let i = 0; i < 5; i++) {
|
|
180
|
+
const byte = data.getUint8(at.offset++)
|
|
181
|
+
if (i === 0 && byte === 0x80) throw new Error("a UIntBase128 has a leading zero")
|
|
182
|
+
if (value & 0xfe000000) throw new Error("a UIntBase128 overflows")
|
|
183
|
+
value = (value << 7) | (byte & 0x7f)
|
|
184
|
+
if ((byte & 0x80) === 0) return value >>> 0
|
|
185
|
+
}
|
|
186
|
+
throw new Error("a UIntBase128 is longer than 5 bytes")
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function woff2Tables(bytes: Uint8Array): Map<string, Table> {
|
|
190
|
+
const data = view(bytes)
|
|
191
|
+
if (tagAt(data, 4) === "ttcf") throw new Error("a WOFF2 collection is not read")
|
|
192
|
+
const count = data.getUint16(12)
|
|
193
|
+
const compressed = data.getUint32(20)
|
|
194
|
+
const at = { offset: 48 }
|
|
195
|
+
const entries: Array<{ tag: string; length: number; transformed: boolean }> = []
|
|
196
|
+
for (let i = 0; i < count; i++) {
|
|
197
|
+
const flags = data.getUint8(at.offset++)
|
|
198
|
+
const known = flags & 0x3f
|
|
199
|
+
let tag: string
|
|
200
|
+
if (known === 63) {
|
|
201
|
+
tag = tagAt(data, at.offset)
|
|
202
|
+
at.offset += 4
|
|
203
|
+
} else {
|
|
204
|
+
tag = WOFF2_TAGS[known]!
|
|
205
|
+
}
|
|
206
|
+
const version = flags >> 6
|
|
207
|
+
const original = base128(data, at)
|
|
208
|
+
const transformed = tag === "glyf" || tag === "loca" ? version !== 3 : version !== 0
|
|
209
|
+
entries.push({ tag, length: transformed ? base128(data, at) : original, transformed })
|
|
210
|
+
}
|
|
211
|
+
const stream = new Uint8Array(brotliDecompressSync(slice(bytes, at.offset, compressed)))
|
|
212
|
+
const tables = new Map<string, Table>()
|
|
213
|
+
let offset = 0
|
|
214
|
+
for (const entry of entries) {
|
|
215
|
+
tables.set(entry.tag, { data: view(slice(stream, offset, entry.length)), transformed: entry.transformed })
|
|
216
|
+
offset += entry.length
|
|
217
|
+
}
|
|
218
|
+
return tables
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function readTables(bytes: Uint8Array): Map<string, Table> {
|
|
222
|
+
if (bytes.byteLength < 12) throw new Error("the file is not a font")
|
|
223
|
+
const signature = tagAt(view(bytes), 0)
|
|
224
|
+
if (signature === "wOFF") return woffTables(bytes)
|
|
225
|
+
if (signature === "wOF2") return woff2Tables(bytes)
|
|
226
|
+
if (signature === "\0\x01\0\0" || signature === "OTTO" || signature === "true") return sfntTables(bytes)
|
|
227
|
+
throw new Error("the file is not a font")
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
type GlyphOf = (codePoint: number) => number
|
|
231
|
+
|
|
232
|
+
function format4(data: DataView, base: number): GlyphOf {
|
|
233
|
+
const segments = data.getUint16(base + 6) / 2
|
|
234
|
+
const ends = base + 14
|
|
235
|
+
const starts = ends + 2 * segments + 2
|
|
236
|
+
const deltas = starts + 2 * segments
|
|
237
|
+
const ranges = deltas + 2 * segments
|
|
238
|
+
return (codePoint) => {
|
|
239
|
+
for (let i = 0; i < segments; i++) {
|
|
240
|
+
if (data.getUint16(ends + 2 * i) < codePoint) continue
|
|
241
|
+
const start = data.getUint16(starts + 2 * i)
|
|
242
|
+
if (start > codePoint) return 0
|
|
243
|
+
const delta = data.getInt16(deltas + 2 * i)
|
|
244
|
+
const range = data.getUint16(ranges + 2 * i)
|
|
245
|
+
if (range === 0) return (codePoint + delta) & 0xffff
|
|
246
|
+
const glyph = data.getUint16(ranges + 2 * i + range + 2 * (codePoint - start))
|
|
247
|
+
return glyph === 0 ? 0 : (glyph + delta) & 0xffff
|
|
248
|
+
}
|
|
249
|
+
return 0
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function format12(data: DataView, base: number): GlyphOf {
|
|
254
|
+
const groups = data.getUint32(base + 12)
|
|
255
|
+
return (codePoint) => {
|
|
256
|
+
for (let i = 0; i < groups; i++) {
|
|
257
|
+
const at = base + 16 + 12 * i
|
|
258
|
+
const start = data.getUint32(at)
|
|
259
|
+
if (codePoint >= start && codePoint <= data.getUint32(at + 4)) return data.getUint32(at + 8) + codePoint - start
|
|
260
|
+
}
|
|
261
|
+
return 0
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function readCmap(cmap: Table | undefined): GlyphOf {
|
|
266
|
+
if (!cmap) throw new Error("no cmap")
|
|
267
|
+
const { data } = cmap
|
|
268
|
+
let found4: number | undefined
|
|
269
|
+
let found12: number | undefined
|
|
270
|
+
for (let i = 0; i < data.getUint16(2); i++) {
|
|
271
|
+
const platform = data.getUint16(4 + 8 * i)
|
|
272
|
+
const encoding = data.getUint16(6 + 8 * i)
|
|
273
|
+
const offset = data.getUint32(8 + 8 * i)
|
|
274
|
+
if (platform !== 0 && !(platform === 3 && (encoding === 1 || encoding === 10))) continue
|
|
275
|
+
const format = data.getUint16(offset)
|
|
276
|
+
if (format === 4) found4 ??= offset
|
|
277
|
+
else if (format === 12) found12 ??= offset
|
|
278
|
+
}
|
|
279
|
+
if (found12 !== undefined) return format12(data, found12)
|
|
280
|
+
if (found4 !== undefined) return format4(data, found4)
|
|
281
|
+
throw new Error("no cmap of format 4 or 12")
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function need(tables: Map<string, Table>, tag: string): DataView {
|
|
285
|
+
const table = tables.get(tag)
|
|
286
|
+
if (!table) throw new Error(`no ${tag}`)
|
|
287
|
+
return table.data
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The metrics a fallback face needs, from a TTF, OTF, WOFF or WOFF2 file. Throws when the file, its cmap, `head`,
|
|
292
|
+
* `hhea` or `hmtx` cannot be read; `undefined` when the cmap maps none of `a`–`z` and the space.
|
|
293
|
+
*/
|
|
294
|
+
export function readFontMetrics(bytes: Uint8Array): FontMetrics | undefined {
|
|
295
|
+
const tables = readTables(bytes)
|
|
296
|
+
const glyphOf = readCmap(tables.get("cmap"))
|
|
297
|
+
const head = need(tables, "head")
|
|
298
|
+
const hhea = need(tables, "hhea")
|
|
299
|
+
const hmtx = tables.get("hmtx")
|
|
300
|
+
if (!hmtx) throw new Error("no hmtx")
|
|
301
|
+
const metrics = hhea.getUint16(34)
|
|
302
|
+
if (metrics === 0) throw new Error("hhea.numberOfHMetrics is 0")
|
|
303
|
+
const advance = (glyph: number): number => {
|
|
304
|
+
const index = Math.min(glyph, metrics - 1)
|
|
305
|
+
return hmtx.transformed ? hmtx.data.getUint16(1 + 2 * index) : hmtx.data.getUint16(4 * index)
|
|
306
|
+
}
|
|
307
|
+
let weighted = 0
|
|
308
|
+
let total = 0
|
|
309
|
+
for (const [char, weight] of Object.entries(LETTER_FREQUENCY)) {
|
|
310
|
+
const glyph = glyphOf(char.charCodeAt(0))
|
|
311
|
+
if (glyph === 0) continue
|
|
312
|
+
weighted += advance(glyph) * weight
|
|
313
|
+
total += weight
|
|
314
|
+
}
|
|
315
|
+
if (total === 0) return undefined
|
|
316
|
+
return {
|
|
317
|
+
unitsPerEm: head.getUint16(18),
|
|
318
|
+
ascender: hhea.getInt16(4),
|
|
319
|
+
descender: hhea.getInt16(6),
|
|
320
|
+
lineGap: hhea.getInt16(8),
|
|
321
|
+
meanWidth: weighted / total,
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The `size-adjust` and metric overrides that make the system font take the width of `font`. */
|
|
326
|
+
export function fallbackOverrides(font: FontMetrics, system: SystemMetrics): FallbackOverrides {
|
|
327
|
+
const sizeAdjust = font.meanWidth / font.unitsPerEm / (system.meanWidth / system.unitsPerEm)
|
|
328
|
+
const scale = font.unitsPerEm * sizeAdjust
|
|
329
|
+
return {
|
|
330
|
+
sizeAdjust,
|
|
331
|
+
ascent: font.ascender / scale,
|
|
332
|
+
descent: Math.abs(font.descender) / scale,
|
|
333
|
+
lineGap: font.lineGap / scale,
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export const fallbackFamily = (family: string, system: string): string => `${family} Fallback: ${system}`
|
|
338
|
+
|
|
339
|
+
const weightDistance = (weight: string | undefined): number => {
|
|
340
|
+
const parts = (weight ?? "400").trim().split(/\s+/).map(Number)
|
|
341
|
+
const low = parts[0]!
|
|
342
|
+
const high = parts[1] ?? low
|
|
343
|
+
return low > 400 ? low - 400 : high < 400 ? 400 - high : 0
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The files to read metrics from, best first: the upright face nearest weight 400, of the `latin` subset when there is one. */
|
|
347
|
+
export function metricSources(faces: FontFaceData[]): string[] {
|
|
348
|
+
const ranked = faces
|
|
349
|
+
.map((face, index) => ({ face, index }))
|
|
350
|
+
.sort(
|
|
351
|
+
(a, b) =>
|
|
352
|
+
Number((a.face.style ?? "normal") !== "normal") - Number((b.face.style ?? "normal") !== "normal") ||
|
|
353
|
+
weightDistance(a.face.weight) - weightDistance(b.face.weight) ||
|
|
354
|
+
Number(a.face.subset !== undefined && a.face.subset !== "latin") -
|
|
355
|
+
Number(b.face.subset !== undefined && b.face.subset !== "latin") ||
|
|
356
|
+
a.index - b.index,
|
|
357
|
+
)
|
|
358
|
+
return ranked.flatMap(({ face }) => face.src.flatMap((entry) => ("url" in entry ? [entry.url] : [])))
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export interface MetricsScope {
|
|
362
|
+
/** The bytes of a face's `src` URL, or `undefined` when it is not a file the build can read (a remote URL kept after a failed download). */
|
|
363
|
+
read(url: string): Promise<Uint8Array | undefined>
|
|
364
|
+
report(message: string): void
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** The metrics of a family's first readable file; a file whose tables cannot be read is reported once and gives none. */
|
|
368
|
+
export async function familyMetrics(
|
|
369
|
+
family: string,
|
|
370
|
+
faces: FontFaceData[],
|
|
371
|
+
scope: MetricsScope,
|
|
372
|
+
): Promise<FontMetrics | undefined> {
|
|
373
|
+
for (const url of metricSources(faces)) {
|
|
374
|
+
const bytes = await scope.read(url)
|
|
375
|
+
if (!bytes) continue
|
|
376
|
+
try {
|
|
377
|
+
return readFontMetrics(bytes)
|
|
378
|
+
} catch {
|
|
379
|
+
scope.report(`[fonts] no fallback metrics for ${JSON.stringify(family)}: its file has no readable cmap`)
|
|
380
|
+
return undefined
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return undefined
|
|
384
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { extname, join } from "node:path"
|
|
3
|
+
import { sha256, writeAtomic } from "./cache.ts"
|
|
4
|
+
import type { FontFaceData, FontFormat } from "../types.ts"
|
|
5
|
+
|
|
6
|
+
export interface FontFiles {
|
|
7
|
+
/** The faces with every remote `src` URL replaced by the absolute path of its downloaded file; a failed download keeps the URL. */
|
|
8
|
+
localize(family: string, faces: FontFaceData[], glyphs?: string): Promise<FontFaceData[]>
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const slugPart = (text: string): string =>
|
|
12
|
+
text
|
|
13
|
+
.toLowerCase()
|
|
14
|
+
.replace(/[^a-z0-9.]+/g, "-")
|
|
15
|
+
.replace(/^-+|-+$/g, "")
|
|
16
|
+
const glyphsSlug = (glyphs: string | undefined): string | undefined => {
|
|
17
|
+
const set = [...new Set(Array.from(glyphs ?? ""))].sort().join("")
|
|
18
|
+
return set ? `g${new Bun.CryptoHasher("sha256").update(set).digest("hex").slice(0, 8)}` : undefined
|
|
19
|
+
}
|
|
20
|
+
const REMOTE = /^https?:\/\//i
|
|
21
|
+
|
|
22
|
+
function extension(url: string, format: FontFormat | undefined): string {
|
|
23
|
+
const ext = extname(new URL(url).pathname).slice(1).toLowerCase()
|
|
24
|
+
return /^(?:woff2|woff|ttf|otf)$/.test(ext) ? ext : (format ?? "woff2")
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Each remote font URL is downloaded once to `<dir>/<family>-<weight>-<style>-<subset>.<ext>`; with `cache`, a file whose `.json` names the same URL and SHA-256 is kept between builds. */
|
|
28
|
+
export function createFontFiles(dir: string, report: (message: string) => void, cache = true): FontFiles {
|
|
29
|
+
const downloads = new Map<string, Promise<string | undefined>>()
|
|
30
|
+
const owners = new Map<string, string>()
|
|
31
|
+
|
|
32
|
+
const cached = async (target: string, url: string): Promise<boolean> => {
|
|
33
|
+
try {
|
|
34
|
+
const entry = JSON.parse(await readFile(`${target}.json`, "utf8")) as { url?: unknown; sha256?: unknown }
|
|
35
|
+
return entry.url === url && entry.sha256 === sha256(await readFile(target))
|
|
36
|
+
} catch {
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const download = async (url: string, name: string): Promise<string | undefined> => {
|
|
42
|
+
const target = join(dir, name)
|
|
43
|
+
try {
|
|
44
|
+
if (cache && (await cached(target, url))) return target
|
|
45
|
+
const response = await globalThis.fetch(url)
|
|
46
|
+
if (!response.ok) {
|
|
47
|
+
report(`[fonts] could not download ${url}: ${response.status}`)
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
const bytes = new Uint8Array(await response.arrayBuffer())
|
|
51
|
+
await writeAtomic(target, bytes)
|
|
52
|
+
await writeAtomic(`${target}.json`, JSON.stringify({ url, sha256: sha256(bytes) }))
|
|
53
|
+
return target
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof Error && error.message.startsWith("[fonts] ")) throw error
|
|
56
|
+
report(`[fonts] could not download ${url}: ${error instanceof Error ? error.message : String(error)}`)
|
|
57
|
+
return undefined
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const fileName = (
|
|
62
|
+
family: string,
|
|
63
|
+
face: FontFaceData,
|
|
64
|
+
url: string,
|
|
65
|
+
format: FontFormat | undefined,
|
|
66
|
+
glyphs: string | undefined,
|
|
67
|
+
): string => {
|
|
68
|
+
const base = [family, face.weight ?? "400", face.style ?? "normal", face.subset, glyphsSlug(glyphs)]
|
|
69
|
+
.filter((part) => part !== undefined && part !== "")
|
|
70
|
+
.map((part) => slugPart(part!))
|
|
71
|
+
.join("-")
|
|
72
|
+
const ext = extension(url, format)
|
|
73
|
+
let name = `${base}.${ext}`
|
|
74
|
+
const owner = owners.get(name)
|
|
75
|
+
if (owner !== undefined && owner !== url)
|
|
76
|
+
name = `${base}-${new Bun.CryptoHasher("sha256").update(url).digest("hex").slice(0, 8)}.${ext}`
|
|
77
|
+
owners.set(name, url)
|
|
78
|
+
return name
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
async localize(family, faces, glyphs) {
|
|
83
|
+
return Promise.all(
|
|
84
|
+
faces.map(async (face) => ({
|
|
85
|
+
...face,
|
|
86
|
+
src: await Promise.all(
|
|
87
|
+
face.src.map(async (entry) => {
|
|
88
|
+
if (!("url" in entry) || !REMOTE.test(entry.url)) return entry
|
|
89
|
+
let pending = downloads.get(entry.url)
|
|
90
|
+
if (!pending) {
|
|
91
|
+
pending = download(entry.url, fileName(family, face, entry.url, entry.format, glyphs))
|
|
92
|
+
downloads.set(entry.url, pending)
|
|
93
|
+
}
|
|
94
|
+
const path = await pending
|
|
95
|
+
return path ? { ...entry, url: path } : entry
|
|
96
|
+
}),
|
|
97
|
+
),
|
|
98
|
+
})),
|
|
99
|
+
)
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { addAppPlugin, addTemplate, createResolver } from "hamur/kit"
|
|
2
|
+
import { quote } from "../inject.ts"
|
|
3
|
+
import type { ResolvedFontsOptions } from "../options.ts"
|
|
4
|
+
|
|
5
|
+
/** `fonts/global.css` names each `global` family once, so the `fonts:css` transform writes its faces; an app plugin imports it, which makes it global CSS. */
|
|
6
|
+
export function setupGlobal(options: ResolvedFontsOptions): void {
|
|
7
|
+
const names = options.families.filter((family) => family.global).map((family) => family.name)
|
|
8
|
+
if (names.length === 0) return
|
|
9
|
+
addTemplate({
|
|
10
|
+
filename: "fonts/global.css",
|
|
11
|
+
getContents: () => `${names.map((name) => `.hamur-fonts-global { font-family: ${quote(name)} }`).join("\n")}\n`,
|
|
12
|
+
})
|
|
13
|
+
addAppPlugin({ src: createResolver(import.meta.url).resolve("../runtime/global.ts"), mode: "all" })
|
|
14
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { addServer, addTemplate, createResolver, type HamurContext } from "hamur/kit"
|
|
4
|
+
import type { ResolvedFontsOptions } from "../options.ts"
|
|
5
|
+
import type { FontFaceData } from "../types.ts"
|
|
6
|
+
|
|
7
|
+
/** The file names of the faces a document should preload, collected while the CSS is transformed. */
|
|
8
|
+
export interface PreloadNames {
|
|
9
|
+
add(faces: FontFaceData[], subsets: string[]): void
|
|
10
|
+
has(file: string): boolean
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const HASH = /-[0-9a-zA-Z]{8}(\.[^.]+)$/
|
|
14
|
+
export const FONT_FACE = /@font-face\s*\{[^}]*\}/gi
|
|
15
|
+
export const URL_OF = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)/gi
|
|
16
|
+
export const ORIGIN = "http://hamur.invalid"
|
|
17
|
+
|
|
18
|
+
export const fileName = (url: string): string => {
|
|
19
|
+
const name = url.split(/[?#]/)[0]!.split(/[\\/]/).pop()!
|
|
20
|
+
try {
|
|
21
|
+
return decodeURIComponent(name)
|
|
22
|
+
} catch {
|
|
23
|
+
return name
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Of one family's faces, those of the `latin` subset, else of the first of `subsets`; a face with no subset always. */
|
|
28
|
+
export function preloadedFaces(faces: FontFaceData[], subsets: string[]): FontFaceData[] {
|
|
29
|
+
const wanted = faces.some((face) => face.subset === "latin") ? "latin" : subsets[0]
|
|
30
|
+
return faces.filter((face) => face.subset === undefined || face.subset === wanted)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function createPreloadNames(): PreloadNames {
|
|
34
|
+
const names = new Set<string>()
|
|
35
|
+
return {
|
|
36
|
+
add(faces, subsets) {
|
|
37
|
+
for (const face of preloadedFaces(faces, subsets)) {
|
|
38
|
+
const first = face.src.find((entry): entry is { url: string } => "url" in entry)
|
|
39
|
+
if (first) names.add(fileName(first.url))
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
has: (file) => names.has(file) || names.has(file.replace(HASH, "$1")),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function cssURLs(manifest: unknown, into = new Set<string>()): Set<string> {
|
|
47
|
+
if (typeof manifest === "string") {
|
|
48
|
+
if (manifest.endsWith(".css")) into.add(manifest)
|
|
49
|
+
} else if (Array.isArray(manifest)) {
|
|
50
|
+
for (const item of manifest) cssURLs(item, into)
|
|
51
|
+
} else if (typeof manifest === "object" && manifest !== null) {
|
|
52
|
+
for (const [key, value] of Object.entries(manifest))
|
|
53
|
+
if (key !== "inline" && key !== "integrity") cssURLs(value, into)
|
|
54
|
+
}
|
|
55
|
+
return into
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The text of each stylesheet of the client manifest, by its URL; an inlined one is read from the manifest, the others from the output directory. */
|
|
59
|
+
export async function manifestSheets(hamur: HamurContext): Promise<Array<{ url: string; text: string }>> {
|
|
60
|
+
const { manifest, options } = hamur
|
|
61
|
+
const dir = join(options.outputDir, "public", options.app.buildAssetsDir.replace(/^\/+|\/+$/g, ""))
|
|
62
|
+
const sheets: Array<{ url: string; text: string }> = []
|
|
63
|
+
for (const url of cssURLs(manifest)) {
|
|
64
|
+
const text = manifest.inline?.[url] ?? (await readFile(join(dir, fileName(url)), "utf8").catch(() => undefined))
|
|
65
|
+
if (text !== undefined) sheets.push({ url, text })
|
|
66
|
+
}
|
|
67
|
+
return sheets
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The font files each stylesheet of the manifest uses and `names` lists, by the stylesheet's URL; a `data:` URL is never listed. */
|
|
71
|
+
export async function preloadTable(hamur: HamurContext, names: PreloadNames): Promise<Record<string, string[]>> {
|
|
72
|
+
const table: Record<string, string[]> = {}
|
|
73
|
+
for (const { url: sheet, text } of await manifestSheets(hamur)) {
|
|
74
|
+
const base = new URL(sheet, `${ORIGIN}/`)
|
|
75
|
+
const fonts = new Set<string>()
|
|
76
|
+
for (const rule of text.match(FONT_FACE) ?? []) {
|
|
77
|
+
for (const match of rule.matchAll(URL_OF)) {
|
|
78
|
+
const href = match[1] ?? match[2] ?? match[3] ?? ""
|
|
79
|
+
if (!href || /^data:/i.test(href)) continue
|
|
80
|
+
let resolved: URL
|
|
81
|
+
try {
|
|
82
|
+
resolved = new URL(href, base)
|
|
83
|
+
} catch {
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
if (names.has(fileName(resolved.pathname)))
|
|
87
|
+
fonts.add(resolved.origin === ORIGIN ? resolved.pathname + resolved.search : resolved.href)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (fonts.size) table[sheet] = [...fonts]
|
|
91
|
+
}
|
|
92
|
+
return table
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The template `fonts/preloads` and the door whose server plugin writes the preload links; `hamur dev` has an empty table. */
|
|
96
|
+
export function setupPreload(options: ResolvedFontsOptions, hamur: HamurContext, names: PreloadNames): void {
|
|
97
|
+
if (!options.defaults.preload && !options.families.some((family) => family.preload)) return
|
|
98
|
+
addTemplate({
|
|
99
|
+
filename: "fonts/preloads",
|
|
100
|
+
getContents: async () =>
|
|
101
|
+
`export default ${JSON.stringify(hamur.options.dev ? {} : await preloadTable(hamur, names))};\n`,
|
|
102
|
+
})
|
|
103
|
+
addServer(createResolver(import.meta.url).resolve("../server/door.ts"))
|
|
104
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { HamurContext } from "hamur/kit"
|
|
2
|
+
import { checkPriority, type ResolvedFontsOptions } from "../options.ts"
|
|
3
|
+
import type { FontProvider } from "../types.ts"
|
|
4
|
+
|
|
5
|
+
/** The files of `fonts.providers` replace built-ins, then `fonts:providers` runs once in `modules:done`; `providers` is what the resolver reads, so it is changed in place. */
|
|
6
|
+
export function setupProviders(
|
|
7
|
+
options: ResolvedFontsOptions,
|
|
8
|
+
hamur: HamurContext,
|
|
9
|
+
providers: Record<string, FontProvider>,
|
|
10
|
+
): void {
|
|
11
|
+
hamur.hooks.hook("modules:done", async () => {
|
|
12
|
+
const all: Record<string, FontProvider> = { ...providers, ...options.custom }
|
|
13
|
+
await hamur.hooks.callHook("fonts:providers", all)
|
|
14
|
+
for (const name of Object.keys(providers)) delete providers[name]
|
|
15
|
+
Object.assign(providers, all)
|
|
16
|
+
options.custom = {}
|
|
17
|
+
checkPriority(options.priority, Object.keys(providers))
|
|
18
|
+
})
|
|
19
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
let kept: Promise<boolean> | undefined
|
|
2
|
+
|
|
3
|
+
const PROBE = "@font-face{font-family:probe;src:url(/hamur-probe.woff2)}"
|
|
4
|
+
|
|
5
|
+
async function probe(): Promise<boolean> {
|
|
6
|
+
try {
|
|
7
|
+
const result = await Bun.build({ entrypoints: ["./probe.css"], files: { "./probe.css": PROBE }, throw: false })
|
|
8
|
+
if (!result.success) return false
|
|
9
|
+
const css = (
|
|
10
|
+
await Promise.all(result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => output.text()))
|
|
11
|
+
).join("")
|
|
12
|
+
return /url\(\s*["']?\/hamur-probe\.woff2["']?\s*\)/.test(css)
|
|
13
|
+
} catch {
|
|
14
|
+
return false
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Whether Bun's CSS bundler writes a root-absolute `url(/x.woff2)` as it is, asked once per process; Bun may resolve it as a file or fail on it. */
|
|
19
|
+
export function publicUrlsKept(): Promise<boolean> {
|
|
20
|
+
return (kept ??= probe())
|
|
21
|
+
}
|