@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
@@ -15,6 +15,9 @@ import type { HeadElement } from './metadata.ts';
15
15
  *
16
16
  * The framework's MetadataResolver component consumes these descriptors
17
17
  * and renders them into the <head>.
18
+ *
19
+ * Relative URLs resolve against `metadataBase` here, so every caller emits
20
+ * absolute URLs (design/16-metadata.md §"metadataBase — URL Resolution").
18
21
  */
19
- export declare function renderMetadataToElements(metadata: Metadata): HeadElement[];
22
+ export declare function renderMetadataToElements(declared: Metadata): HeadElement[];
20
23
  //# sourceMappingURL=metadata-render.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"metadata-render.d.ts","sourceRoot":"","sources":["../../src/server/metadata-render.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAajD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,QAAQ,GAAG,WAAW,EAAE,CAwJ1E"}
1
+ {"version":3,"file":"metadata-render.d.ts","sourceRoot":"","sources":["../../src/server/metadata-render.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAcjD;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,QAAQ,GAAG,WAAW,EAAE,CAyJ1E"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * metadataBase — resolve relative URLs in metadata against the base URL.
3
+ *
4
+ * Runs inside renderMetadataToElements, so every path that turns metadata
5
+ * into head tags (MetadataHead, the deny page) emits absolute URLs. It must
6
+ * not run before findDeclaredImageOwners: that reads which segment supplied
7
+ * the merged images by object identity, and resolving copies the images.
8
+ *
9
+ * Auto-linked metadata route hrefs (metadata-route-links.ts) never pass
10
+ * through here — they are HeadElements, not Metadata — so nothing is
11
+ * resolved twice.
12
+ *
13
+ * See design/16-metadata.md §"metadataBase — URL Resolution".
14
+ */
15
+ import type { Metadata } from './types.ts';
16
+ /**
17
+ * Resolve relative URLs in metadata fields against metadataBase.
18
+ *
19
+ * Returns a new metadata object with URLs resolved. Absolute and
20
+ * protocol-relative URLs are not modified. If metadataBase is not set,
21
+ * returns the metadata unchanged.
22
+ */
23
+ export declare function resolveMetadataUrls(metadata: Metadata): Metadata;
24
+ //# sourceMappingURL=metadata-urls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata-urls.d.ts","sourceRoot":"","sources":["../../src/server/metadata-urls.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA0B3C;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CA4DhE"}
@@ -65,11 +65,4 @@ export declare function resolveTitle(title: Metadata['title'], template: string
65
65
  * See design/16-metadata.md §"Merge Algorithm"
66
66
  */
67
67
  export declare function resolveMetadata(entries: SegmentMetadataEntry[], options?: ResolveMetadataOptions): Metadata;
68
- /**
69
- * Resolve relative URLs in metadata fields against metadataBase.
70
- *
71
- * Returns a new metadata object with URLs resolved. Absolute URLs are not modified.
72
- * If metadataBase is not set, returns the metadata unchanged.
73
- */
74
- export declare function resolveMetadataUrls(metadata: Metadata): Metadata;
75
68
  //# sourceMappingURL=metadata.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../src/server/metadata.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAI3C,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC,YAAY,CAW/E;AAID,4DAA4D;AAC5D,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,QAAQ,EAAE,QAAQ,CAAC;IACnB,yDAAyD;IACzD,MAAM,EAAE,OAAO,CAAC;CACjB;AAED,mCAAmC;AACnC,MAAM,WAAW,sBAAsB;IACrC;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,0CAA0C;AAC1C,MAAM,WAAW,WAAW;IAC1B,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAID;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,EACxB,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,MAAM,GAAG,SAAS,CAmBpB;AAID;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,oBAAoB,EAAE,EAC/B,OAAO,GAAE,sBAA2B,GACnC,QAAQ,CAwDV;AAmBD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAmFhE"}
1
+ {"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../src/server/metadata.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAI3C,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC,YAAY,CAW/E;AAID,4DAA4D;AAC5D,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,QAAQ,EAAE,QAAQ,CAAC;IACnB,yDAAyD;IACzD,MAAM,EAAE,OAAO,CAAC;CACjB;AAED,mCAAmC;AACnC,MAAM,WAAW,sBAAsB;IACrC;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,0CAA0C;AAC1C,MAAM,WAAW,WAAW;IAC1B,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAID;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,EACxB,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,MAAM,GAAG,SAAS,CAmBpB;AAID;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,oBAAoB,EAAE,EAC/B,OAAO,GAAE,sBAA2B,GACnC,QAAQ,CAwDV"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.246",
3
+ "version": "0.2.0-alpha.248",
4
4
  "description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
package/src/fonts/ast.ts CHANGED
@@ -299,6 +299,17 @@ function extractGoogleConfig(objNode: ObjectExpressionNode): GoogleFontConfig {
299
299
  return config;
300
300
  }
301
301
 
302
+ function isAdjustFontFallback(
303
+ value: boolean | string | undefined
304
+ ): value is NonNullable<LocalFontConfig['adjustFontFallback']> {
305
+ return (
306
+ typeof value === 'boolean' ||
307
+ value === 'Arial' ||
308
+ value === 'Times New Roman' ||
309
+ value === 'monospace'
310
+ );
311
+ }
312
+
302
313
  /** Shared implementation for LocalFontConfig extraction from an object node. */
303
314
  function extractLocalConfig(objNode: ObjectExpressionNode): LocalFontConfig | null {
304
315
  const props = objectProperties(objNode);
@@ -314,12 +325,34 @@ function extractLocalConfig(objNode: ObjectExpressionNode): LocalFontConfig | nu
314
325
  const familyNode = props.get('family');
315
326
  const family = familyNode ? extractString(familyNode) : undefined;
316
327
 
328
+ // Optional options: present-but-not-static is a hard failure (the caller
329
+ // reports it), never a silent default.
330
+ const options: Pick<LocalFontConfig, 'preload' | 'adjustFontFallback' | 'fallback'> = {};
331
+ const preloadNode = props.get('preload');
332
+ if (preloadNode) {
333
+ const b = extractBoolean(preloadNode);
334
+ if (b === undefined) return null;
335
+ options.preload = b;
336
+ }
337
+ const adjustNode = props.get('adjustFontFallback');
338
+ if (adjustNode) {
339
+ const value = extractBoolean(adjustNode) ?? extractString(adjustNode);
340
+ if (!isAdjustFontFallback(value)) return null;
341
+ options.adjustFontFallback = value;
342
+ }
343
+ const fallbackNode = props.get('fallback');
344
+ if (fallbackNode) {
345
+ const list = extractStringArray(fallbackNode);
346
+ if (!list) return null;
347
+ options.fallback = list;
348
+ }
349
+
317
350
  const srcNode = props.get('src');
318
351
  if (!srcNode) return null;
319
352
 
320
353
  const srcString = extractString(srcNode);
321
354
  if (srcString !== undefined) {
322
- return { src: srcString, display, variable, family };
355
+ return { src: srcString, display, variable, family, ...options };
323
356
  }
324
357
 
325
358
  if (srcNode.type === 'ArrayExpression') {
@@ -331,7 +364,7 @@ function extractLocalConfig(objNode: ObjectExpressionNode): LocalFontConfig | nu
331
364
  entries.push(entry);
332
365
  }
333
366
  if (entries.length === 0) return null;
334
- return { src: entries, display, variable, family };
367
+ return { src: entries, display, variable, family, ...options };
335
368
  }
336
369
 
337
370
  return null;
@@ -89,50 +89,104 @@ export function emitFontAssets(
89
89
  }
90
90
 
91
91
  /**
92
- * Populate `buildManifest.fonts` with `ManifestFontEntry[]` keyed by the
93
- * absolute importer path. This matches the runtime route manifest's
94
- * `filePath` values (which are absolute) and is consistent with how
95
- * `buildManifest.css` keys work after TIM-1014.
92
+ * Map each font importer to the route files (layouts and pages) that
93
+ * import it, directly or through any chain of modules.
96
94
  *
97
- * All font binaries use content-hashed filenames for immutable caching.
98
- * Hrefs are prefixed with Vite's resolved `base` so they match the URLs
99
- * the platform serves the emitted binaries under.
95
+ * A font is usually defined in a shared module (`app/fonts.ts`) and applied
96
+ * in a layout that imports it. The manifest is read per matched route
97
+ * segment (`collectRouteFonts`), so an entry keyed only by the defining
98
+ * module would never be found. Walking *up* the importer graph from each
99
+ * font module is cheap — there are a handful of font modules, and the walk
100
+ * stops at modules already visited.
101
+ *
102
+ * `getImporters` is Rollup's `getModuleInfo(id)?.importers` from the RSC
103
+ * build, where layouts and pages are real modules. A route file reached
104
+ * through another route file (a page importing a layout's module) still
105
+ * counts: the font is in that page's graph.
106
+ */
107
+ export function mapFontImportersToRoutes(
108
+ importers: Iterable<string>,
109
+ routeFiles: Iterable<string>,
110
+ getImporters: (id: string) => readonly string[] | null | undefined
111
+ ): Map<string, string[]> {
112
+ const routeSet = new Set(routeFiles);
113
+ const result = new Map<string, string[]>();
114
+ for (const importer of importers) {
115
+ const routes: string[] = [];
116
+ const visited = new Set<string>([importer]);
117
+ const queue = [importer];
118
+ while (queue.length > 0) {
119
+ const id = queue.shift()!;
120
+ if (routeSet.has(id)) routes.push(id);
121
+ for (const parent of getImporters(id) ?? []) {
122
+ if (visited.has(parent)) continue;
123
+ visited.add(parent);
124
+ queue.push(parent);
125
+ }
126
+ }
127
+ result.set(importer, routes);
128
+ }
129
+ return result;
130
+ }
131
+
132
+ /** Only upright faces are preloaded — italics are rarely above the fold. */
133
+ const isUpright = (style: string | undefined) => style === undefined || style === 'normal';
134
+
135
+ /**
136
+ * Populate `buildManifest.fonts` with the font binaries to preload, keyed
137
+ * by absolute path. The keys are the font's importer plus every route file
138
+ * that reaches it (`routesByImporter`, from `mapFontImportersToRoutes`), so
139
+ * `collectRouteFonts` finds a font defined outside the layout that applies
140
+ * it. Keys are absolute, matching the route manifest's `filePath` values
141
+ * (and `buildManifest.css`, TIM-1014).
142
+ *
143
+ * Fonts with `preload: false` and non-upright faces are left out. All
144
+ * hrefs are content-hashed and prefixed with Vite's resolved `base`.
100
145
  */
101
146
  export function writeFontManifest(
102
147
  pipeline: FontPipeline,
103
148
  buildManifest: BuildManifest,
104
- base = '/'
149
+ base = '/',
150
+ routesByImporter?: ReadonlyMap<string, readonly string[]>
105
151
  ): void {
106
152
  const urlPrefix = fontUrlPrefix(base);
107
- const fontsByImporter = new Map<string, ManifestFontEntry[]>();
153
+ const fontsByKey = new Map<string, Map<string, ManifestFontEntry>>();
108
154
 
109
155
  for (const entry of pipeline.entries()) {
110
- const manifestEntries = fontsByImporter.get(entry.importer) ?? [];
156
+ if (entry.preload === false) continue;
157
+ const preloads: ManifestFontEntry[] = [];
111
158
 
112
159
  if (entry.provider === 'local' && entry.localSources) {
113
160
  for (const src of entry.localSources) {
161
+ if (!isUpright(src.style)) continue;
114
162
  const filename = src.hashedBasename ?? fontOutputBasename(src.path);
115
- const format = inferFontFormat(src.path);
116
- manifestEntries.push({
163
+ preloads.push({
117
164
  href: `${urlPrefix}/${filename}`,
118
- format,
165
+ format: inferFontFormat(src.path),
119
166
  crossOrigin: 'anonymous',
120
167
  });
121
168
  }
122
169
  } else if (entry.cachedFiles) {
123
170
  for (const cf of entry.cachedFiles) {
124
- manifestEntries.push({
171
+ if (!isUpright(cf.face.style)) continue;
172
+ preloads.push({
125
173
  href: `${urlPrefix}/${cf.hashedFilename}`,
126
174
  format: 'woff2',
127
175
  crossOrigin: 'anonymous',
128
176
  });
129
177
  }
130
178
  }
179
+ if (preloads.length === 0) continue;
131
180
 
132
- fontsByImporter.set(entry.importer, manifestEntries);
181
+ const keys = new Set([entry.importer, ...(routesByImporter?.get(entry.importer) ?? [])]);
182
+ for (const key of keys) {
183
+ const byHref = fontsByKey.get(key) ?? new Map<string, ManifestFontEntry>();
184
+ for (const preload of preloads) byHref.set(preload.href, preload);
185
+ fontsByKey.set(key, byHref);
186
+ }
133
187
  }
134
188
 
135
- for (const [importer, entries] of fontsByImporter) {
136
- buildManifest.fonts[importer] = entries;
189
+ for (const [key, byHref] of fontsByKey) {
190
+ buildManifest.fonts[key] = [...byHref.values()];
137
191
  }
138
192
  }
@@ -5,9 +5,15 @@
5
5
  * `size-adjust`, `ascent-override`, `descent-override`, and
6
6
  * `line-gap-override` to match custom font metrics and eliminate CLS.
7
7
  *
8
+ * Google fonts use the precomputed `FALLBACK_METRICS` table below. Local
9
+ * fonts compute their faces from the font file (`local-fallback.ts`); both
10
+ * paths produce `FallbackFace` values serialized by `generateFallbackFaceCss`.
11
+ *
8
12
  * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
9
13
  */
10
14
 
15
+ import type { FontCategory } from './font-metrics.ts';
16
+
11
17
  /**
12
18
  * Font metrics for size-adjusted fallback calculation.
13
19
  *
@@ -158,7 +164,8 @@ const SERIF_FAMILIES = new Set([
158
164
  'cormorant garamond',
159
165
  ]);
160
166
 
161
- export function getGenericFamily(family: string): string {
167
+ /** Guess a family's generic category from its name alone. */
168
+ export function getGenericFamily(family: string): FontCategory {
162
169
  const lc = family.toLowerCase();
163
170
  if (lc.includes('mono') || lc.includes('code')) return 'monospace';
164
171
  if ((lc.includes('serif') && !lc.includes('sans')) || SERIF_FAMILIES.has(lc)) {
@@ -167,59 +174,116 @@ export function getGenericFamily(family: string): string {
167
174
  return 'sans-serif';
168
175
  }
169
176
 
177
+ // ─── Fallback faces ──────────────────────────────────────────────────────
178
+
170
179
  /**
171
- * Generate the full CSS for a size-adjusted fallback font.
172
- *
173
- * This produces a complete @font-face block with override descriptors
174
- * that FontFaceDescriptor doesn't natively support.
180
+ * One size-adjusted fallback `@font-face`. Percentages are final CSS values
181
+ * (e.g. `107.64` → `size-adjust: 107.64%`).
175
182
  */
176
- export function generateFallbackCss(family: string): string | null {
177
- const metrics = FALLBACK_METRICS[family.toLowerCase()];
178
- if (!metrics) return null;
183
+ export interface FallbackFace {
184
+ /** `'<Family> Fallback'`. */
185
+ family: string;
186
+ /** System fonts tried in order, as `local()` sources. */
187
+ local: string[];
188
+ /** `font-weight` descriptor. Omitted for the regular face (defaults to normal). */
189
+ weight?: string;
190
+ sizeAdjust: number;
191
+ ascentOverride: number;
192
+ descentOverride: number;
193
+ lineGapOverride: number;
194
+ }
179
195
 
180
- const fallbackFamily = `${family} Fallback`;
196
+ /** The fallback family name for `family`. */
197
+ export function fallbackFamilyName(family: string): string {
198
+ return `${family} Fallback`;
199
+ }
181
200
 
201
+ /** Serialize a fallback face to an `@font-face` rule. */
202
+ export function generateFallbackFaceCss(face: FallbackFace): string {
182
203
  const lines = [
183
204
  '@font-face {',
184
- ` font-family: '${fallbackFamily}';`,
185
- ` src: local('${metrics.fallbackFont}');`,
186
- ` size-adjust: ${metrics.sizeAdjust}%;`,
187
- ` ascent-override: ${metrics.ascentOverride}%;`,
188
- ` descent-override: ${metrics.descentOverride}%;`,
189
- ` line-gap-override: ${metrics.lineGapOverride}%;`,
190
- '}',
205
+ ` font-family: '${face.family}';`,
206
+ ` src: ${face.local.map((name) => `local('${name}')`).join(', ')};`,
191
207
  ];
192
-
208
+ if (face.weight) lines.push(` font-weight: ${face.weight};`);
209
+ lines.push(
210
+ ` size-adjust: ${face.sizeAdjust}%;`,
211
+ ` ascent-override: ${face.ascentOverride}%;`,
212
+ ` descent-override: ${face.descentOverride}%;`,
213
+ ` line-gap-override: ${face.lineGapOverride}%;`,
214
+ '}'
215
+ );
193
216
  return lines.join('\n');
194
217
  }
195
218
 
196
219
  /**
197
- * Check whether fallback metrics are available for a font family.
220
+ * The fallback faces for a Google font, from the precomputed table. Empty
221
+ * when the family isn't in the table.
198
222
  */
223
+ export function googleFallbackFaces(family: string): FallbackFace[] {
224
+ const metrics = FALLBACK_METRICS[family.toLowerCase()];
225
+ if (!metrics) return [];
226
+ return [
227
+ {
228
+ family: fallbackFamilyName(family),
229
+ local: [metrics.fallbackFont],
230
+ sizeAdjust: metrics.sizeAdjust,
231
+ ascentOverride: metrics.ascentOverride,
232
+ descentOverride: metrics.descentOverride,
233
+ lineGapOverride: metrics.lineGapOverride,
234
+ },
235
+ ];
236
+ }
237
+
238
+ /** Check whether the Google fallback table has metrics for a family. */
199
239
  export function hasFallbackMetrics(family: string): boolean {
200
240
  return family.toLowerCase() in FALLBACK_METRICS;
201
241
  }
202
242
 
243
+ /**
244
+ * Generate the fallback `@font-face` CSS for a Google font, or `null` when
245
+ * the family isn't in the table.
246
+ */
247
+ export function generateFallbackCss(family: string): string | null {
248
+ const faces = googleFallbackFaces(family);
249
+ return faces.length > 0 ? faces.map(generateFallbackFaceCss).join('\n\n') : null;
250
+ }
251
+
252
+ // ─── Font stack ──────────────────────────────────────────────────────────
253
+
254
+ export interface FontStackOptions {
255
+ /** Generic family. Defaults to the name heuristic (`getGenericFamily`). */
256
+ generic?: FontCategory;
257
+ /** Whether a `'<Family> Fallback'` face exists. Defaults to the Google table. */
258
+ hasFallbackFace?: boolean;
259
+ /**
260
+ * Replaces the default generic tail (`system-ui, sans-serif`, etc.) —
261
+ * the `fallback` option of `next/font`. Entries are emitted verbatim.
262
+ */
263
+ fallback?: string[];
264
+ }
265
+
203
266
  /**
204
267
  * Build the full font stack string for a font, including its
205
268
  * size-adjusted fallback and a generic family.
206
269
  *
207
270
  * Example: `'Inter', 'Inter Fallback', system-ui, sans-serif`
208
271
  */
209
- export function buildFontStack(family: string): string {
210
- const generic = getGenericFamily(family);
211
- const hasMetrics = hasFallbackMetrics(family);
272
+ export function buildFontStack(family: string, options: FontStackOptions = {}): string {
273
+ const generic = options.generic ?? getGenericFamily(family);
274
+ const hasFallbackFace = options.hasFallbackFace ?? hasFallbackMetrics(family);
212
275
 
213
276
  const parts = [`'${family}'`];
214
- if (hasMetrics) parts.push(`'${family} Fallback'`);
277
+ if (hasFallbackFace) parts.push(`'${fallbackFamilyName(family)}'`);
215
278
 
216
- // Add system-ui for sans-serif fonts, ui-monospace for mono
217
- if (generic === 'monospace') {
218
- parts.push('ui-monospace');
219
- } else if (generic === 'sans-serif') {
220
- parts.push('system-ui');
279
+ if (options.fallback) {
280
+ parts.push(...options.fallback);
281
+ } else {
282
+ // system-ui for sans-serif fonts, ui-monospace for mono
283
+ if (generic === 'monospace') parts.push('ui-monospace');
284
+ else if (generic === 'sans-serif') parts.push('system-ui');
285
+ parts.push(generic);
221
286
  }
222
- parts.push(generic);
223
287
 
224
288
  return parts.join(', ');
225
289
  }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Read the vertical and horizontal metrics a size-adjusted fallback needs
3
+ * from a font file (TTF / OTF / WOFF / WOFF2).
4
+ *
5
+ * Fields read:
6
+ *
7
+ * - `head.unitsPerEm`
8
+ * - ascent / descent / lineGap — from `hhea`, or from `OS/2` sTypo* when
9
+ * `fsSelection` bit 7 (USE_TYPO_METRICS) is set, which is what browsers
10
+ * do with such fonts
11
+ * - `OS/2.xAvgCharWidth`, and the advance widths of a letter-frequency
12
+ * weighted Latin sample (`cmap` → glyph id → `hmtx`), the same sample
13
+ * Next.js's `adjustFontFallback` and capsize use
14
+ * - whether the font is monospace: `post.isFixedPitch`, `OS/2` PANOSE
15
+ * proportion = monospaced, or every sampled glyph sharing one advance
16
+ * - whether it is serif or sans, from PANOSE / IBM font class, when the
17
+ * font declares it
18
+ *
19
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
20
+ */
21
+
22
+ import { readSfntTables } from './sfnt.ts';
23
+
24
+ /** The generic CSS family a font belongs to. */
25
+ export type FontCategory = 'sans-serif' | 'serif' | 'monospace';
26
+
27
+ export interface FontMetrics {
28
+ unitsPerEm: number;
29
+ /** Positive, in font units. */
30
+ ascent: number;
31
+ /** Positive (distance below the baseline), in font units. */
32
+ descent: number;
33
+ lineGap: number;
34
+ /** `OS/2.xAvgCharWidth`, or `undefined` when the table is absent / zero. */
35
+ xAvgCharWidth?: number;
36
+ /**
37
+ * Mean advance of `AVG_WIDTH_SAMPLE` in font units, or `undefined` when
38
+ * the font lacks a sampled character or its `hmtx` is unreadable.
39
+ */
40
+ sampleAvgWidth?: number;
41
+ /** True for fixed-pitch fonts. */
42
+ monospace: boolean;
43
+ /**
44
+ * `serif` / `sans-serif` when the font's PANOSE or IBM class says so;
45
+ * `undefined` when it does not (caller falls back to a name heuristic).
46
+ */
47
+ declaredCategory?: 'serif' | 'sans-serif';
48
+ }
49
+
50
+ /**
51
+ * Letter-frequency weighted Latin sample, with spaces for word length.
52
+ * Identical to Next.js's `calcAverageWidth` (packages/font/src/local/
53
+ * get-fallback-metrics-from-font-file.ts) so the reference widths of the
54
+ * fallback bases are comparable.
55
+ */
56
+ export const AVG_WIDTH_SAMPLE = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ';
57
+
58
+ /** Characters whose advances must all match for a font to count as monospace. */
59
+ const MONO_PROBE = 'abcdefghijklmnopqrstuvwxyz0123456789 ';
60
+
61
+ const TABLES = ['head', 'hhea', 'OS/2', 'post', 'cmap', 'hmtx'] as const;
62
+
63
+ /** Parse metrics from font bytes. `null` when the file can't be read. */
64
+ export function readFontMetrics(data: Uint8Array): FontMetrics | null {
65
+ const tables = readSfntTables(data, TABLES);
66
+ if (!tables) return null;
67
+ const head = tables.get('head');
68
+ const hhea = tables.get('hhea');
69
+ if (!head || !hhea || head.byteLength < 54 || hhea.byteLength < 36) return null;
70
+
71
+ try {
72
+ const unitsPerEm = head.getUint16(18);
73
+ if (unitsPerEm === 0) return null;
74
+
75
+ let ascent = hhea.getInt16(4);
76
+ let descent = hhea.getInt16(6);
77
+ let lineGap = hhea.getInt16(8);
78
+ const numberOfHMetrics = hhea.getUint16(34);
79
+
80
+ const os2 = tables.get('OS/2');
81
+ let xAvgCharWidth: number | undefined;
82
+ let declaredCategory: FontMetrics['declaredCategory'];
83
+ let panoseMono = false;
84
+ if (os2 && os2.byteLength >= 78) {
85
+ const avg = os2.getInt16(2);
86
+ if (avg > 0) xAvgCharWidth = avg;
87
+ const fsSelection = os2.getUint16(62);
88
+ if (fsSelection & (1 << 7)) {
89
+ ascent = os2.getInt16(68);
90
+ descent = os2.getInt16(70);
91
+ lineGap = os2.getInt16(72);
92
+ }
93
+ const panose = (i: number) => os2.getUint8(32 + i);
94
+ // PANOSE family kind 2 = Latin Text; only then do the digits below
95
+ // mean serif style (byte 1) and proportion (byte 3).
96
+ if (panose(0) === 2) {
97
+ const serifStyle = panose(1);
98
+ if (serifStyle >= 2 && serifStyle <= 10) declaredCategory = 'serif';
99
+ else if (serifStyle >= 11 && serifStyle <= 13) declaredCategory = 'sans-serif';
100
+ panoseMono = panose(3) === 9;
101
+ }
102
+ if (!declaredCategory) {
103
+ // IBM font class (high byte of sFamilyClass): 1–5 and 7 are serif
104
+ // classes, 8 is sans serif.
105
+ const ibmClass = os2.getInt16(30) >> 8;
106
+ if ((ibmClass >= 1 && ibmClass <= 5) || ibmClass === 7) declaredCategory = 'serif';
107
+ else if (ibmClass === 8) declaredCategory = 'sans-serif';
108
+ }
109
+ }
110
+
111
+ const post = tables.get('post');
112
+ const isFixedPitch = post !== undefined && post.byteLength >= 16 && post.getUint32(12) !== 0;
113
+
114
+ const advanceOf = buildAdvanceLookup(tables.get('cmap'), tables.get('hmtx'), numberOfHMetrics);
115
+ const sampleAvgWidth = advanceOf ? averageAdvance(AVG_WIDTH_SAMPLE, advanceOf) : undefined;
116
+ const sameAdvance = advanceOf ? allSameAdvance(MONO_PROBE, advanceOf) : false;
117
+
118
+ return {
119
+ unitsPerEm,
120
+ ascent,
121
+ descent: Math.abs(descent),
122
+ lineGap,
123
+ xAvgCharWidth,
124
+ sampleAvgWidth,
125
+ monospace: isFixedPitch || panoseMono || sameAdvance,
126
+ declaredCategory,
127
+ };
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ type AdvanceLookup = (codePoint: number) => number | undefined;
134
+
135
+ function averageAdvance(sample: string, advanceOf: AdvanceLookup): number | undefined {
136
+ let total = 0;
137
+ for (const ch of sample) {
138
+ const advance = advanceOf(ch.codePointAt(0)!);
139
+ if (advance === undefined) return undefined;
140
+ total += advance;
141
+ }
142
+ return total / sample.length;
143
+ }
144
+
145
+ function allSameAdvance(sample: string, advanceOf: AdvanceLookup): boolean {
146
+ let first: number | undefined;
147
+ for (const ch of sample) {
148
+ const advance = advanceOf(ch.codePointAt(0)!);
149
+ if (advance === undefined) return false;
150
+ if (first === undefined) first = advance;
151
+ else if (advance !== first) return false;
152
+ }
153
+ return true;
154
+ }
155
+
156
+ /** Code point → advance width, via `cmap` and `hmtx`. */
157
+ function buildAdvanceLookup(
158
+ cmap: DataView | undefined,
159
+ hmtx: DataView | undefined,
160
+ numberOfHMetrics: number
161
+ ): AdvanceLookup | null {
162
+ if (!cmap || !hmtx || numberOfHMetrics === 0) return null;
163
+ if (hmtx.byteLength < numberOfHMetrics * 4) return null;
164
+ const glyphOf = buildGlyphLookup(cmap);
165
+ if (!glyphOf) return null;
166
+ return (codePoint) => {
167
+ const gid = glyphOf(codePoint);
168
+ if (!gid) return undefined; // 0 is .notdef — the character is missing
169
+ // Glyphs past numberOfHMetrics share the last advance (monospace tail).
170
+ const index = Math.min(gid, numberOfHMetrics - 1);
171
+ return hmtx.getUint16(index * 4);
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Pick a Unicode `cmap` subtable (format 4 or 12) and return a lookup.
177
+ * Preference: (3,10) / (0,4+) full repertoire, then (3,1) / (0,x) BMP.
178
+ */
179
+ function buildGlyphLookup(cmap: DataView): ((codePoint: number) => number) | null {
180
+ const numSubtables = cmap.getUint16(2);
181
+ let best: { offset: number; rank: number } | null = null;
182
+ for (let i = 0; i < numSubtables; i++) {
183
+ const rec = 4 + i * 8;
184
+ const platform = cmap.getUint16(rec);
185
+ const encoding = cmap.getUint16(rec + 2);
186
+ const offset = cmap.getUint32(rec + 4);
187
+ if (offset + 4 > cmap.byteLength) continue;
188
+ const format = cmap.getUint16(offset);
189
+ if (format !== 4 && format !== 12) continue;
190
+ const unicode = platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10));
191
+ if (!unicode) continue;
192
+ const rank = format === 12 ? 2 : 1;
193
+ if (!best || rank > best.rank) best = { offset, rank };
194
+ }
195
+ if (!best) return null;
196
+ const offset = best.offset;
197
+ return cmap.getUint16(offset) === 12 ? cmapFormat12(cmap, offset) : cmapFormat4(cmap, offset);
198
+ }
199
+
200
+ function cmapFormat4(cmap: DataView, offset: number): (codePoint: number) => number {
201
+ const segCount = cmap.getUint16(offset + 6) / 2;
202
+ const endCodes = offset + 14;
203
+ const startCodes = endCodes + segCount * 2 + 2;
204
+ const idDeltas = startCodes + segCount * 2;
205
+ const idRangeOffsets = idDeltas + segCount * 2;
206
+ return (cp) => {
207
+ if (cp > 0xffff) return 0;
208
+ for (let s = 0; s < segCount; s++) {
209
+ if (cp > cmap.getUint16(endCodes + s * 2)) continue;
210
+ const start = cmap.getUint16(startCodes + s * 2);
211
+ if (cp < start) return 0;
212
+ const delta = cmap.getInt16(idDeltas + s * 2);
213
+ const rangeOffsetPos = idRangeOffsets + s * 2;
214
+ const rangeOffset = cmap.getUint16(rangeOffsetPos);
215
+ if (rangeOffset === 0) return (cp + delta) & 0xffff;
216
+ const glyphPos = rangeOffsetPos + rangeOffset + (cp - start) * 2;
217
+ if (glyphPos + 2 > cmap.byteLength) return 0;
218
+ const glyph = cmap.getUint16(glyphPos);
219
+ return glyph === 0 ? 0 : (glyph + delta) & 0xffff;
220
+ }
221
+ return 0;
222
+ };
223
+ }
224
+
225
+ function cmapFormat12(cmap: DataView, offset: number): (codePoint: number) => number {
226
+ const numGroups = cmap.getUint32(offset + 12);
227
+ return (cp) => {
228
+ for (let g = 0; g < numGroups; g++) {
229
+ const rec = offset + 16 + g * 12;
230
+ const start = cmap.getUint32(rec);
231
+ const end = cmap.getUint32(rec + 4);
232
+ if (cp >= start && cp <= end) return cmap.getUint32(rec + 8) + (cp - start);
233
+ }
234
+ return 0;
235
+ };
236
+ }