@timber-js/app 0.2.0-alpha.246 → 0.2.0-alpha.248

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 (63) hide show
  1. package/dist/fonts/ast.d.ts.map +1 -1
  2. package/dist/fonts/bundle.d.ts +26 -8
  3. package/dist/fonts/bundle.d.ts.map +1 -1
  4. package/dist/fonts/fallbacks.d.ts +46 -8
  5. package/dist/fonts/fallbacks.d.ts.map +1 -1
  6. package/dist/fonts/font-metrics.d.ts +54 -0
  7. package/dist/fonts/font-metrics.d.ts.map +1 -0
  8. package/dist/fonts/local-fallback.d.ts +64 -0
  9. package/dist/fonts/local-fallback.d.ts.map +1 -0
  10. package/dist/fonts/local.d.ts.map +1 -1
  11. package/dist/fonts/sfnt.d.ts +30 -0
  12. package/dist/fonts/sfnt.d.ts.map +1 -0
  13. package/dist/fonts/transform.d.ts.map +1 -1
  14. package/dist/fonts/types.d.ts +29 -0
  15. package/dist/fonts/types.d.ts.map +1 -1
  16. package/dist/index.js +1063 -352
  17. package/dist/index.js.map +1 -1
  18. package/dist/native/rsc/manifest.json +1 -0
  19. package/dist/native/rsc/server/internal.js +2 -2
  20. package/dist/native/rsc/server/metadata-render.js +3 -1
  21. package/dist/native/rsc/server/metadata-render.js.map +1 -1
  22. package/dist/native/rsc/server/metadata-urls.js +70 -0
  23. package/dist/native/rsc/server/metadata-urls.js.map +1 -0
  24. package/dist/native/rsc/server/metadata.js +1 -64
  25. package/dist/native/rsc/server/metadata.js.map +1 -1
  26. package/dist/native/ssr/manifest.json +1 -0
  27. package/dist/native/ssr/server/internal.js +2 -2
  28. package/dist/native/ssr/server/metadata-render.js +3 -1
  29. package/dist/native/ssr/server/metadata-render.js.map +1 -1
  30. package/dist/native/ssr/server/metadata-urls.js +70 -0
  31. package/dist/native/ssr/server/metadata-urls.js.map +1 -0
  32. package/dist/native/ssr/server/metadata.js +1 -64
  33. package/dist/native/ssr/server/metadata.js.map +1 -1
  34. package/dist/plugins/build-manifest.d.ts +5 -0
  35. package/dist/plugins/build-manifest.d.ts.map +1 -1
  36. package/dist/plugins/fonts.d.ts.map +1 -1
  37. package/dist/server/internal.d.ts +1 -1
  38. package/dist/server/internal.d.ts.map +1 -1
  39. package/dist/server/internal.js +84 -77
  40. package/dist/server/internal.js.map +1 -1
  41. package/dist/server/metadata-render.d.ts +4 -1
  42. package/dist/server/metadata-render.d.ts.map +1 -1
  43. package/dist/server/metadata-urls.d.ts +24 -0
  44. package/dist/server/metadata-urls.d.ts.map +1 -0
  45. package/dist/server/metadata.d.ts +0 -7
  46. package/dist/server/metadata.d.ts.map +1 -1
  47. package/package.json +1 -1
  48. package/src/fonts/ast.ts +35 -2
  49. package/src/fonts/bundle.ts +71 -17
  50. package/src/fonts/fallbacks.ts +92 -28
  51. package/src/fonts/font-metrics.ts +236 -0
  52. package/src/fonts/local-fallback.ts +249 -0
  53. package/src/fonts/local.ts +14 -1
  54. package/src/fonts/pipeline.ts +6 -3
  55. package/src/fonts/sfnt.ts +185 -0
  56. package/src/fonts/transform.ts +4 -1
  57. package/src/fonts/types.ts +29 -0
  58. package/src/plugins/build-manifest.ts +1 -1
  59. package/src/plugins/fonts.ts +28 -2
  60. package/src/server/internal.ts +1 -6
  61. package/src/server/metadata-render.ts +6 -1
  62. package/src/server/metadata-urls.ts +109 -0
  63. package/src/server/metadata.ts +0 -108
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Size-adjusted fallbacks for local fonts, computed from the font files.
3
+ *
4
+ * Google fonts ship with a precomputed metrics table (`fallbacks.ts`); a
5
+ * local font can be anything, so its metrics are read from the font file
6
+ * itself (`font-metrics.ts`) when the transform registers it — at build
7
+ * time in production, on first transform in dev.
8
+ *
9
+ * From those metrics this module decides:
10
+ *
11
+ * 1. The generic family. Fixed-pitch fonts are `monospace`; otherwise the
12
+ * font's own PANOSE / IBM class, otherwise the family-name heuristic.
13
+ * `adjustFontFallback: 'Arial' | 'Times New Roman' | 'monospace'`
14
+ * overrides it.
15
+ * 2. The fallback base: Arial (sans), Times New Roman (serif), or a list
16
+ * of ~0.600em monospace system fonts (mono). Each base lists
17
+ * metric-compatible Linux equivalents as later `local()` sources.
18
+ * 3. The overrides, computed the way Next.js's `adjustFontFallback` does:
19
+ * `size-adjust` = font average width / base average width, then each
20
+ * vertical metric divided by `unitsPerEm × size-adjust` (the overrides
21
+ * apply to the *adjusted* size).
22
+ *
23
+ * A bold (700) face is emitted when the font has its own 700 source, using
24
+ * the base's bold system font and the bold file's metrics. Without it the
25
+ * browser would synthesize bold from the regular fallback, which changes
26
+ * glyph widths and re-wraps text on swap.
27
+ *
28
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
29
+ */
30
+
31
+ import { readFileSync, statSync } from 'node:fs';
32
+ import type { LocalFontSrc } from './types.ts';
33
+ import { readFontMetrics, type FontCategory, type FontMetrics } from './font-metrics.ts';
34
+ import { fallbackFamilyName, getGenericFamily, type FallbackFace } from './fallbacks.ts';
35
+
36
+ /** `next/font/local`'s `adjustFontFallback` option. */
37
+ export type AdjustFontFallback = boolean | 'Arial' | 'Times New Roman' | 'monospace';
38
+
39
+ /** A system font's reference metrics, measured from the font file. */
40
+ interface BaseFace {
41
+ local: string[];
42
+ unitsPerEm: number;
43
+ /** Mean advance of `AVG_WIDTH_SAMPLE` (font-metrics.ts). */
44
+ sampleAvgWidth: number;
45
+ /** `OS/2.xAvgCharWidth`, for fonts whose sample can't be measured. */
46
+ xAvgCharWidth: number;
47
+ }
48
+
49
+ /**
50
+ * Reference metrics, measured with `readFontMetrics` on the macOS system
51
+ * fonts. Arial's and Times New Roman's sample widths match Next.js's
52
+ * constants (934.51 and 854.40 per 2048). Every listed monospace font is
53
+ * 1229–1233/2048 wide (Courier New, Liberation Mono, Cousine, Droid Sans
54
+ * Mono and Roboto Mono are 1229; Menlo and DejaVu Sans Mono 1233), so one
55
+ * reference serves the list.
56
+ */
57
+ const BASES: Record<FontCategory, { regular: BaseFace; bold: BaseFace }> = {
58
+ 'sans-serif': {
59
+ regular: {
60
+ local: ['Arial', 'ArialMT', 'Liberation Sans', 'Arimo'],
61
+ unitsPerEm: 2048,
62
+ sampleAvgWidth: 934.5116279069767,
63
+ xAvgCharWidth: 904,
64
+ },
65
+ bold: {
66
+ local: ['Arial Bold', 'Arial-BoldMT', 'Liberation Sans Bold', 'Arimo Bold'],
67
+ unitsPerEm: 2048,
68
+ sampleAvgWidth: 1011.046511627907,
69
+ xAvgCharWidth: 980,
70
+ },
71
+ },
72
+ 'serif': {
73
+ regular: {
74
+ local: ['Times New Roman', 'TimesNewRomanPSMT', 'Liberation Serif', 'Tinos'],
75
+ unitsPerEm: 2048,
76
+ sampleAvgWidth: 854.3953488372093,
77
+ xAvgCharWidth: 821,
78
+ },
79
+ bold: {
80
+ local: [
81
+ 'Times New Roman Bold',
82
+ 'TimesNewRomanPS-BoldMT',
83
+ 'Liberation Serif Bold',
84
+ 'Tinos Bold',
85
+ ],
86
+ unitsPerEm: 2048,
87
+ sampleAvgWidth: 907.5581395348837,
88
+ xAvgCharWidth: 874,
89
+ },
90
+ },
91
+ 'monospace': {
92
+ regular: {
93
+ local: [
94
+ 'Menlo',
95
+ 'DejaVu Sans Mono',
96
+ 'Liberation Mono',
97
+ 'Cousine',
98
+ 'Droid Sans Mono',
99
+ 'Roboto Mono',
100
+ 'Courier New',
101
+ ],
102
+ unitsPerEm: 2048,
103
+ sampleAvgWidth: 1229,
104
+ xAvgCharWidth: 1229,
105
+ },
106
+ bold: {
107
+ local: [
108
+ 'Menlo Bold',
109
+ 'Menlo-Bold',
110
+ 'DejaVu Sans Mono Bold',
111
+ 'Liberation Mono Bold',
112
+ 'Cousine Bold',
113
+ 'Roboto Mono Bold',
114
+ 'Courier New Bold',
115
+ 'CourierNewPS-BoldMT',
116
+ ],
117
+ unitsPerEm: 2048,
118
+ sampleAvgWidth: 1229,
119
+ xAvgCharWidth: 1229,
120
+ },
121
+ },
122
+ };
123
+
124
+ const ADJUST_CATEGORY: Record<Exclude<AdjustFontFallback, boolean>, FontCategory> = {
125
+ 'Arial': 'sans-serif',
126
+ 'Times New Roman': 'serif',
127
+ 'monospace': 'monospace',
128
+ };
129
+
130
+ /** What a local font's stack and fallback CSS are built from. */
131
+ export interface LocalFallback {
132
+ generic: FontCategory;
133
+ faces: FallbackFace[];
134
+ }
135
+
136
+ /** Metrics by absolute path, invalidated by mtime/size (dev edits). */
137
+ const metricsCache = new Map<
138
+ string,
139
+ { mtimeMs: number; size: number; metrics: FontMetrics | null }
140
+ >();
141
+
142
+ /** Read a font file's metrics, or `null` when it is missing or unreadable. */
143
+ export function readFontFileMetrics(path: string): FontMetrics | null {
144
+ let stat;
145
+ try {
146
+ stat = statSync(path);
147
+ } catch {
148
+ return null;
149
+ }
150
+ const cached = metricsCache.get(path);
151
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
152
+ return cached.metrics;
153
+ }
154
+ let metrics: FontMetrics | null;
155
+ try {
156
+ metrics = readFontMetrics(readFileSync(path));
157
+ } catch {
158
+ metrics = null;
159
+ }
160
+ metricsCache.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, metrics });
161
+ return metrics;
162
+ }
163
+
164
+ const isBold = (weight: string | undefined) => weight === '700' || weight === 'bold';
165
+ const isRegular = (weight: string | undefined) =>
166
+ weight === undefined || weight === '400' || weight === 'normal';
167
+ const isUpright = (style: string | undefined) => style === undefined || style === 'normal';
168
+
169
+ /** The source fallback metrics come from: 400 normal, else the first. */
170
+ export function pickRegularSource(sources: LocalFontSrc[]): LocalFontSrc | undefined {
171
+ return sources.find((s) => isRegular(s.weight) && isUpright(s.style)) ?? sources[0];
172
+ }
173
+
174
+ function pickBoldSource(sources: LocalFontSrc[]): LocalFontSrc | undefined {
175
+ return (
176
+ sources.find((s) => isBold(s.weight) && isUpright(s.style)) ??
177
+ sources.find((s) => isBold(s.weight))
178
+ );
179
+ }
180
+
181
+ /** Round to the 2-decimal percentage a CSS descriptor carries. */
182
+ function percent(ratio: number): number {
183
+ return Math.round(Math.abs(ratio) * 10000) / 100;
184
+ }
185
+
186
+ /** Compute one fallback face from a font's metrics against a base face. */
187
+ export function computeFallbackFace(
188
+ family: string,
189
+ metrics: FontMetrics,
190
+ base: BaseFace,
191
+ weight?: string
192
+ ): FallbackFace {
193
+ // Compare like with like: the weighted sample when the font has every
194
+ // sampled glyph, else OS/2's average, else leave the size alone.
195
+ let sizeAdjust = 1;
196
+ if (metrics.sampleAvgWidth) {
197
+ sizeAdjust =
198
+ metrics.sampleAvgWidth / metrics.unitsPerEm / (base.sampleAvgWidth / base.unitsPerEm);
199
+ } else if (metrics.xAvgCharWidth) {
200
+ sizeAdjust =
201
+ metrics.xAvgCharWidth / metrics.unitsPerEm / (base.xAvgCharWidth / base.unitsPerEm);
202
+ }
203
+ const scale = metrics.unitsPerEm * sizeAdjust;
204
+ return {
205
+ family: fallbackFamilyName(family),
206
+ local: base.local,
207
+ ...(weight ? { weight } : {}),
208
+ sizeAdjust: percent(sizeAdjust),
209
+ ascentOverride: percent(metrics.ascent / scale),
210
+ descentOverride: percent(metrics.descent / scale),
211
+ lineGapOverride: percent(metrics.lineGap / scale),
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Work out a local font's generic family and fallback faces.
217
+ *
218
+ * `sources` must already be resolved to absolute paths. Missing or
219
+ * unreadable files produce no faces (the stack then skips the fallback
220
+ * family) and the name heuristic for the generic family.
221
+ */
222
+ export function resolveLocalFallback(
223
+ family: string,
224
+ sources: LocalFontSrc[],
225
+ adjust: AdjustFontFallback = true
226
+ ): LocalFallback {
227
+ const regularSrc = pickRegularSource(sources);
228
+ const metrics = regularSrc ? readFontFileMetrics(regularSrc.path) : null;
229
+
230
+ const generic: FontCategory =
231
+ typeof adjust === 'string'
232
+ ? ADJUST_CATEGORY[adjust]
233
+ : metrics?.monospace
234
+ ? 'monospace'
235
+ : (metrics?.declaredCategory ?? getGenericFamily(family));
236
+
237
+ if (adjust === false || !metrics) return { generic, faces: [] };
238
+
239
+ const base = BASES[generic];
240
+ const faces = [computeFallbackFace(family, metrics, base.regular)];
241
+
242
+ const boldSrc = pickBoldSource(sources);
243
+ if (boldSrc && boldSrc !== regularSrc) {
244
+ const boldMetrics = readFontFileMetrics(boldSrc.path) ?? metrics;
245
+ faces.push(computeFallbackFace(family, boldMetrics, base.bold, '700'));
246
+ }
247
+
248
+ return { generic, faces };
249
+ }
@@ -16,6 +16,7 @@
16
16
  import { resolve, dirname, extname } from 'node:path';
17
17
  import type { LocalFontConfig, LocalFontSrc, FontFaceDescriptor, ExtractedFont } from './types.ts';
18
18
  import { buildFontStack } from './fallbacks.ts';
19
+ import { resolveLocalFallback } from './local-fallback.ts';
19
20
  import { extractLocalFontConfigAst } from './ast.ts';
20
21
  import { fontOutputBasename, fontUrlPrefix } from './paths.ts';
21
22
 
@@ -144,7 +145,17 @@ export function processLocalFont(config: LocalFontConfig, importerPath: string):
144
145
  const family = config.family ?? generateFamilyName(sources);
145
146
  const display = config.display ?? 'swap';
146
147
  const className = localFontClassName(family);
147
- const fontStack = buildFontStack(family);
148
+ // Reads the font file's metrics (cached by mtime) — see local-fallback.ts.
149
+ const { generic, faces } = resolveLocalFallback(
150
+ family,
151
+ resolvedSources,
152
+ config.adjustFontFallback
153
+ );
154
+ const fontStack = buildFontStack(family, {
155
+ generic,
156
+ hasFallbackFace: faces.length > 0,
157
+ fallback: config.fallback,
158
+ });
148
159
 
149
160
  const weights = [...new Set(resolvedSources.map((s) => s.weight ?? '400'))];
150
161
  const styles = [...new Set(resolvedSources.map((s) => s.style ?? 'normal'))];
@@ -162,6 +173,8 @@ export function processLocalFont(config: LocalFontConfig, importerPath: string):
162
173
  importer: importerPath,
163
174
  className,
164
175
  fontFamily: fontStack,
176
+ fallbackFaces: faces,
177
+ preload: config.preload ?? true,
165
178
  };
166
179
  }
167
180
 
@@ -32,7 +32,7 @@ import type { ExtractedFont, FontEntry, FontFaceDescriptor } from './types.ts';
32
32
  import type { CachedFont } from './google.ts';
33
33
  import { contentHash } from './google.ts';
34
34
  import { generateVariableClass, generateFontFamilyClass, generateFontFaces } from './css.ts';
35
- import { generateFallbackCss } from './fallbacks.ts';
35
+ import { generateFallbackFaceCss, googleFallbackFaces } from './fallbacks.ts';
36
36
  import { generateLocalFontFaces } from './local.ts';
37
37
  import { hashedFontBasename, fontUrlPrefix } from './paths.ts';
38
38
  import { VirtualFontCssIdMap } from './virtual-modules.ts';
@@ -335,8 +335,11 @@ function renderEntryCss(entry: FontEntry, urlPrefix: string): string {
335
335
  if (faceCss) cssParts.push(faceCss);
336
336
  }
337
337
 
338
- const fallbackCss = generateFallbackCss(entry.family);
339
- if (fallbackCss) cssParts.push(fallbackCss);
338
+ // Local fonts carry faces measured from their files; Google fonts use
339
+ // the precomputed table, keyed by family.
340
+ const fallbackFaces =
341
+ entry.provider === 'local' ? (entry.fallbackFaces ?? []) : googleFallbackFaces(entry.family);
342
+ for (const face of fallbackFaces) cssParts.push(generateFallbackFaceCss(face));
340
343
 
341
344
  if (entry.variable) {
342
345
  cssParts.push(generateVariableClass(entry.className, entry.variable, entry.fontFamily));
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Minimal font-container reader: TrueType/OpenType (sfnt), WOFF and WOFF2.
3
+ *
4
+ * Returns the raw bytes of the requested tables so `font-metrics.ts` can
5
+ * read the handful of fields the fallback generator needs. This is
6
+ * deliberately not a font parser — it only undoes the container:
7
+ *
8
+ * - sfnt (`\0\1\0\0`, `true`, `OTTO`): tables are stored as-is.
9
+ * - WOFF (`wOFF`): each table is zlib-compressed independently.
10
+ * - WOFF2 (`wOF2`): all tables are concatenated into one Brotli stream.
11
+ * WOFF2 may *transform* `glyf`, `loca` and `hmtx`; a transformed table is
12
+ * not in sfnt layout, so it is reported as missing rather than misread.
13
+ * `head`, `hhea`, `OS/2`, `post` and `cmap` are never transformed.
14
+ *
15
+ * Both decompressors come from `node:zlib`, so no dependency is needed.
16
+ * Font collections (`ttcf`) are not supported — they are not web fonts.
17
+ *
18
+ * Every read is bounds-checked: a truncated or non-font file yields `null`,
19
+ * never a throw, because the caller's fallback is simply "no metrics".
20
+ *
21
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
22
+ */
23
+
24
+ import { brotliDecompressSync, inflateSync } from 'node:zlib';
25
+
26
+ /** Table tag → that table's uncompressed bytes. */
27
+ export type SfntTables = Map<string, DataView>;
28
+
29
+ const SFNT_TRUETYPE = 0x00010000;
30
+ const SFNT_TRUE = 0x74727565; // 'true'
31
+ const SFNT_OTTO = 0x4f54544f; // 'OTTO'
32
+ const WOFF = 0x774f4646; // 'wOFF'
33
+ const WOFF2 = 0x774f4632; // 'wOF2'
34
+
35
+ /** WOFF2 §5.1 known-table index (flags & 0x3f). */
36
+ const WOFF2_KNOWN_TAGS = [
37
+ 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf',
38
+ 'loca', 'prep', 'CFF ', 'VORG', 'EBDT', 'EBLC', 'gasp', 'hdmx', 'kern', 'LTSH', 'PCLT',
39
+ 'VDMX', 'vhea', 'vmtx', 'BASE', 'GDEF', 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH', 'CBDT',
40
+ 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar',
41
+ 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar', 'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd',
42
+ 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill',
43
+ ]; // prettier-ignore
44
+
45
+ function tagAt(view: DataView, offset: number): string {
46
+ return String.fromCharCode(
47
+ view.getUint8(offset),
48
+ view.getUint8(offset + 1),
49
+ view.getUint8(offset + 2),
50
+ view.getUint8(offset + 3)
51
+ );
52
+ }
53
+
54
+ function slice(bytes: Uint8Array, offset: number, length: number): DataView | null {
55
+ if (offset < 0 || length < 0 || offset + length > bytes.byteLength) return null;
56
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, length);
57
+ }
58
+
59
+ /**
60
+ * Read the requested tables out of a font file. Returns `null` when the
61
+ * bytes are not a supported font container or are truncated.
62
+ */
63
+ export function readSfntTables(data: Uint8Array, wanted: readonly string[]): SfntTables | null {
64
+ try {
65
+ if (data.byteLength < 12) return null;
66
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
67
+ const signature = view.getUint32(0);
68
+ const want = new Set(wanted);
69
+ switch (signature) {
70
+ case SFNT_TRUETYPE:
71
+ case SFNT_TRUE:
72
+ case SFNT_OTTO:
73
+ return readSfnt(data, view, want);
74
+ case WOFF:
75
+ return readWoff(data, view, want);
76
+ case WOFF2:
77
+ return readWoff2(data, view, want);
78
+ default:
79
+ return null;
80
+ }
81
+ } catch {
82
+ // RangeError from a DataView read past a lying length field, or a
83
+ // zlib error from corrupt compressed data. Both mean "not readable".
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function readSfnt(data: Uint8Array, view: DataView, want: Set<string>): SfntTables | null {
89
+ const numTables = view.getUint16(4);
90
+ const tables: SfntTables = new Map();
91
+ for (let i = 0; i < numTables; i++) {
92
+ const rec = 12 + i * 16;
93
+ const tag = tagAt(view, rec);
94
+ if (!want.has(tag)) continue;
95
+ const table = slice(data, view.getUint32(rec + 8), view.getUint32(rec + 12));
96
+ if (!table) return null;
97
+ tables.set(tag, table);
98
+ }
99
+ return tables;
100
+ }
101
+
102
+ function readWoff(data: Uint8Array, view: DataView, want: Set<string>): SfntTables | null {
103
+ const numTables = view.getUint16(12);
104
+ const tables: SfntTables = new Map();
105
+ for (let i = 0; i < numTables; i++) {
106
+ const rec = 44 + i * 20;
107
+ const tag = tagAt(view, rec);
108
+ if (!want.has(tag)) continue;
109
+ const offset = view.getUint32(rec + 4);
110
+ const compLength = view.getUint32(rec + 8);
111
+ const origLength = view.getUint32(rec + 12);
112
+ const stored = slice(data, offset, compLength);
113
+ if (!stored) return null;
114
+ if (compLength === origLength) {
115
+ tables.set(tag, stored);
116
+ continue;
117
+ }
118
+ const raw = inflateSync(new Uint8Array(stored.buffer, stored.byteOffset, compLength));
119
+ tables.set(tag, new DataView(raw.buffer, raw.byteOffset, raw.byteLength));
120
+ }
121
+ return tables;
122
+ }
123
+
124
+ /** WOFF2 UIntBase128: big-endian base-128, at most 5 bytes. */
125
+ function readBase128(view: DataView, cursor: { pos: number }): number {
126
+ let value = 0;
127
+ for (let i = 0; i < 5; i++) {
128
+ const byte = view.getUint8(cursor.pos++);
129
+ // A leading 0x80 byte is a non-canonical encoding — reject it.
130
+ if (i === 0 && byte === 0x80) throw new RangeError('bad UIntBase128');
131
+ value = value * 128 + (byte & 0x7f);
132
+ if ((byte & 0x80) === 0) return value;
133
+ }
134
+ throw new RangeError('UIntBase128 too long');
135
+ }
136
+
137
+ function readWoff2(data: Uint8Array, view: DataView, want: Set<string>): SfntTables | null {
138
+ const flavor = view.getUint32(4);
139
+ if (flavor === 0x74746366 /* 'ttcf' */) return null;
140
+ const numTables = view.getUint16(12);
141
+ const totalCompressedSize = view.getUint32(20);
142
+
143
+ // Table directory (§5): flags, optional tag, origLength, optional
144
+ // transformLength. Tables appear in the decompressed stream in directory
145
+ // order, back to back with no padding.
146
+ const cursor = { pos: 48 };
147
+ const entries: { tag: string; offset: number; length: number; transformed: boolean }[] = [];
148
+ let streamOffset = 0;
149
+ for (let i = 0; i < numTables; i++) {
150
+ const flags = view.getUint8(cursor.pos++);
151
+ const knownIndex = flags & 0x3f;
152
+ let tag: string;
153
+ if (knownIndex === 0x3f) {
154
+ tag = tagAt(view, cursor.pos);
155
+ cursor.pos += 4;
156
+ } else {
157
+ tag = WOFF2_KNOWN_TAGS[knownIndex];
158
+ if (!tag) return null;
159
+ }
160
+ const transformVersion = (flags >> 6) & 0x03;
161
+ const origLength = readBase128(view, cursor);
162
+ // glyf/loca: version 0 *is* the transform, 3 is null. Everything else:
163
+ // version 0 is null, anything else is a transform.
164
+ const transformed =
165
+ tag === 'glyf' || tag === 'loca' ? transformVersion !== 3 : transformVersion !== 0;
166
+ const length = transformed ? readBase128(view, cursor) : origLength;
167
+ entries.push({ tag, offset: streamOffset, length, transformed });
168
+ streamOffset += length;
169
+ }
170
+
171
+ const compressed = slice(data, cursor.pos, totalCompressedSize);
172
+ if (!compressed) return null;
173
+ const stream = brotliDecompressSync(
174
+ new Uint8Array(compressed.buffer, compressed.byteOffset, totalCompressedSize)
175
+ );
176
+
177
+ const tables: SfntTables = new Map();
178
+ for (const entry of entries) {
179
+ if (!want.has(entry.tag) || entry.transformed) continue;
180
+ const table = slice(stream, entry.offset, entry.length);
181
+ if (!table) return null;
182
+ tables.set(entry.tag, table);
183
+ }
184
+ return tables;
185
+ }
@@ -250,6 +250,7 @@ export function runFontsTransform(
250
250
  className,
251
251
  fontFamily: fontStack,
252
252
  importer: id,
253
+ preload: config!.preload ?? true,
253
254
  },
254
255
  });
255
256
  } else {
@@ -259,7 +260,9 @@ export function runFontsTransform(
259
260
  emitError(
260
261
  `Could not statically analyze local font config ` +
261
262
  `at line ${site.line}, column ${site.column}. ` +
262
- `Ensure src is a string or array of { path, weight?, style? } objects.`
263
+ `Ensure src is a string or array of { path, weight?, style? } objects, ` +
264
+ `preload is a boolean, adjustFontFallback is a boolean or ` +
265
+ `'Arial' | 'Times New Roman' | 'monospace', and fallback is an array of strings.`
263
266
  );
264
267
  }
265
268
 
@@ -10,6 +10,8 @@
10
10
  // `CachedFont` lives in `google.ts`. Importing it here is type-only so
11
11
  // there is no runtime dependency cycle — TypeScript erases the import.
12
12
  import type { CachedFont } from './google.ts';
13
+ import type { FallbackFace } from './fallbacks.ts';
14
+ import type { AdjustFontFallback } from './local-fallback.ts';
13
15
 
14
16
  /** Configuration passed to a Google font function (e.g. `Inter({ ... })`). */
15
17
  export interface GoogleFontConfig {
@@ -37,6 +39,25 @@ export interface LocalFontConfig {
37
39
  variable?: string;
38
40
  /** Override the font family name. Defaults to a generated name. */
39
41
  family?: string;
42
+ /**
43
+ * Preload the font's upright (`font-style: normal`) files on every route
44
+ * whose layout or page imports it, directly or through another module.
45
+ * Defaults to `true`.
46
+ */
47
+ preload?: boolean;
48
+ /**
49
+ * Size-adjusted fallback, as in `next/font/local`. `true` (the default)
50
+ * measures the font file and picks the base from its metrics; `false`
51
+ * emits no `'<Family> Fallback'` face; a font name forces that base (and
52
+ * its generic family): `'Arial'` → sans-serif, `'Times New Roman'` →
53
+ * serif, `'monospace'` → a list of ~0.600em monospace system fonts.
54
+ */
55
+ adjustFontFallback?: AdjustFontFallback;
56
+ /**
57
+ * Font families after `'<Family> Fallback'` in the stack, replacing the
58
+ * default generic tail (e.g. `['ui-monospace', 'monospace']`).
59
+ */
60
+ fallback?: string[];
40
61
  }
41
62
 
42
63
  /**
@@ -88,6 +109,14 @@ export interface ExtractedFont {
88
109
  className: string;
89
110
  /** Full font stack including fallback. */
90
111
  fontFamily: string;
112
+ /**
113
+ * Size-adjusted fallback faces measured from a local font's files.
114
+ * Google fonts leave this unset — their faces come from the precomputed
115
+ * table in `fallbacks.ts`, keyed by family.
116
+ */
117
+ fallbackFaces?: FallbackFace[];
118
+ /** Whether the font's files are preloaded. Defaults to `true`. */
119
+ preload?: boolean;
91
120
  }
92
121
 
93
122
  /**
@@ -252,7 +252,7 @@ const CLIENT_REF_KEY_RE = /registerClientReference\([^,]+,\s*"([0-9a-f]{12})"/g;
252
252
  /**
253
253
  * Collect all route file paths (layout, page) from the route tree.
254
254
  */
255
- function collectRouteFilePaths(node: SegmentNode<RouteFile>): string[] {
255
+ export function collectRouteFilePaths(node: SegmentNode<RouteFile>): string[] {
256
256
  const paths: string[] = [];
257
257
  if (node.layout) paths.push(node.layout.filePath);
258
258
  if (node.page) paths.push(node.page.filePath);
@@ -31,7 +31,13 @@ import { FONT_OUTPUT_DIR, fontUrlPrefix } from '../fonts/paths.ts';
31
31
  import { FontPipeline } from '../fonts/pipeline.ts';
32
32
  import { runFontsTransform } from '../fonts/transform.ts';
33
33
  import { installFontDevMiddleware } from '../fonts/dev-middleware.ts';
34
- import { emitFontAssets, writeFontManifest, groupCachedFontsByFamily } from '../fonts/bundle.ts';
34
+ import {
35
+ emitFontAssets,
36
+ writeFontManifest,
37
+ groupCachedFontsByFamily,
38
+ mapFontImportersToRoutes,
39
+ } from '../fonts/bundle.ts';
40
+ import { collectRouteFilePaths } from './build-manifest.ts';
35
41
  import {
36
42
  RESOLVED_GOOGLE,
37
43
  RESOLVED_LOCAL,
@@ -81,12 +87,19 @@ export function timberFonts(ctx: PluginContext): Plugin & { api: FontsBuildStep
81
87
  const pipeline = new FontPipeline({ hashOnRegister: !ctx.dev });
82
88
  /** Whether the client environment emitted a binary this build. */
83
89
  let emittedToClient = false;
90
+ /**
91
+ * Font importer → the layouts/pages that reach it, from the RSC build's
92
+ * module graph. Lets the manifest key a font defined in `app/fonts.ts`
93
+ * under the layout that imports it.
94
+ */
95
+ let routesByImporter: Map<string, string[]> | undefined;
84
96
 
85
97
  return {
86
98
  name: 'timber-fonts',
87
99
 
88
100
  api: {
89
- contributeManifest: (manifest) => writeFontManifest(pipeline, manifest, ctx.base),
101
+ contributeManifest: (manifest) =>
102
+ writeFontManifest(pipeline, manifest, ctx.base, routesByImporter),
90
103
  immutableDirs: () => (emittedToClient ? [FONT_OUTPUT_DIR] : []),
91
104
  },
92
105
 
@@ -331,6 +344,19 @@ export function timberFonts(ctx: PluginContext): Plugin & { api: FontsBuildStep
331
344
  (msg) => this.warn(msg)
332
345
  );
333
346
  if (this.environment?.name === 'client') emittedToClient = emitted > 0;
347
+
348
+ // Server components (layouts, pages, and the modules they import) are
349
+ // real modules only in the RSC graph, so the route association is
350
+ // read there.
351
+ if (this.environment?.name === 'rsc' && ctx.routeTree) {
352
+ const importers = new Set<string>();
353
+ for (const font of pipeline.fonts()) importers.add(font.importer);
354
+ routesByImporter = mapFontImportersToRoutes(
355
+ importers,
356
+ collectRouteFilePaths(ctx.routeTree.root),
357
+ (id) => this.getModuleInfo(id)?.importers
358
+ );
359
+ }
334
360
  },
335
361
  };
336
362
  }
@@ -82,12 +82,7 @@ export { parseBodySize, enforceBodyLimits, DEFAULT_LIMITS } from './body-limits.
82
82
  export type { BodyLimitsConfig, BodyLimitResult, BodyKind } from './body-limits.ts';
83
83
 
84
84
  // ── Metadata ─────────────────────────────────────────────────────────────
85
- export {
86
- resolveMetadata,
87
- resolveTitle,
88
- resolveMetadataUrls,
89
- renderMetadataToElements,
90
- } from './metadata.ts';
85
+ export { resolveMetadata, resolveTitle, renderMetadataToElements } from './metadata.ts';
91
86
  export type { SegmentMetadataEntry, ResolveMetadataOptions } from './metadata.ts';
92
87
 
93
88
  // ── Metadata Routes ──────────────────────────────────────────────────────
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { Metadata } from './types.ts';
10
10
  import type { HeadElement } from './metadata.ts';
11
+ import { resolveMetadataUrls } from './metadata-urls.ts';
11
12
  import { renderOpenGraph, renderTwitter } from './metadata-social.ts';
12
13
  import {
13
14
  renderIcons,
@@ -28,8 +29,12 @@ import {
28
29
  *
29
30
  * The framework's MetadataResolver component consumes these descriptors
30
31
  * and renders them into the <head>.
32
+ *
33
+ * Relative URLs resolve against `metadataBase` here, so every caller emits
34
+ * absolute URLs (design/16-metadata.md §"metadataBase — URL Resolution").
31
35
  */
32
- export function renderMetadataToElements(metadata: Metadata): HeadElement[] {
36
+ export function renderMetadataToElements(declared: Metadata): HeadElement[] {
37
+ const metadata = resolveMetadataUrls(declared);
33
38
  const elements: HeadElement[] = [];
34
39
 
35
40
  // Title