@timber-js/app 0.2.0-alpha.247 → 0.2.0-alpha.249

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 (38) 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.d.ts.map +1 -1
  17. package/dist/index.js +1262 -351
  18. package/dist/index.js.map +1 -1
  19. package/dist/plugins/build-manifest.d.ts +5 -0
  20. package/dist/plugins/build-manifest.d.ts.map +1 -1
  21. package/dist/plugins/fonts.d.ts.map +1 -1
  22. package/dist/plugins/route-css.d.ts +63 -0
  23. package/dist/plugins/route-css.d.ts.map +1 -0
  24. package/package.json +1 -1
  25. package/src/fonts/ast.ts +35 -2
  26. package/src/fonts/bundle.ts +71 -17
  27. package/src/fonts/fallbacks.ts +92 -28
  28. package/src/fonts/font-metrics.ts +236 -0
  29. package/src/fonts/local-fallback.ts +249 -0
  30. package/src/fonts/local.ts +14 -1
  31. package/src/fonts/pipeline.ts +6 -3
  32. package/src/fonts/sfnt.ts +185 -0
  33. package/src/fonts/transform.ts +4 -1
  34. package/src/fonts/types.ts +29 -0
  35. package/src/index.ts +2 -0
  36. package/src/plugins/build-manifest.ts +1 -1
  37. package/src/plugins/fonts.ts +28 -2
  38. package/src/plugins/route-css.ts +237 -0
package/dist/index.js CHANGED
@@ -4,26 +4,26 @@ import { n as scanRoutes } from "./_chunks/scanner-B6V2RqqF.js";
4
4
  import { c as writeRouteCodegen, i as readRouteOptions, l as buildDirToRouteMap, n as formatConventionWarnings, r as lintConventions, s as flushCodegenWrites, t as checkAppDirExists } from "./_chunks/convention-lint-BWbKAV4x.js";
5
5
  import { r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "./_chunks/walkers-BAZoAlfI.js";
6
6
  import { i as poisonPillSource, r as markerFor, t as EXPLICIT_MARKERS } from "./_chunks/poison-rules-Bmz-lCPi.js";
7
+ import { a as EMPTY_BUILD_MANIFEST, n as DEV_SPAN_REPLAY_EVENT, r as DEV_SPAN_SINK_KEY, t as DEV_SPAN_EVENT } from "./_chunks/dev-span-0aG7Q_Ph.js";
8
+ import { i as detectDirective } from "./_chunks/classify-Bbb_lKjH.js";
7
9
  import { t as writeFileAtomic } from "./_chunks/write-file-atomic-DW8m_Atv.js";
8
10
  import { i as withBasePath, n as normalizeBasePath, t as isRelativeBase } from "./_chunks/base-path-DDIx0FXe.js";
9
11
  import { n as rscPayloadPath, t as RSC_PAYLOAD_DIR } from "./_chunks/rsc-payload-path-EphpDB-J.js";
10
12
  import { a as REDIRECTS_FILE, n as detectFsIdentity, o as RESERVED_OUTPUT_PATHS, r as fsKey, t as EXACT_FS_IDENTITY } from "./_chunks/fs-identity-BmQ_Agg-.js";
11
- import { a as EMPTY_BUILD_MANIFEST, n as DEV_SPAN_REPLAY_EVENT, r as DEV_SPAN_SINK_KEY, t as DEV_SPAN_EVENT } from "./_chunks/dev-span-0aG7Q_Ph.js";
12
13
  import { t as fnv1aHash } from "./_chunks/fast-hash-DddxkU5Y.js";
13
- import { i as detectDirective } from "./_chunks/classify-Bbb_lKjH.js";
14
14
  import { a as contextAdapter, c as loadTimberConfigFile, d as resolveBuildDir, f as resolveClientJavascript, l as mergeFileConfig, m as createNoopTimer, o as createPluginContext, r as adapterConfig, u as resolveAppDir } from "./_chunks/plugin-context-BtaQcMuh.js";
15
15
  import { x as swallow } from "./_chunks/logger-D1sWX2I0.js";
16
16
  import { t as formatSize } from "./_chunks/format-DuPOoXUP.js";
17
17
  import { createLogger, esmExternalRequirePlugin, isRunnableDevEnvironment, parseAst } from "vite";
18
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep, win32 } from "node:path";
19
19
  import react from "@vitejs/plugin-react";
20
- import { existsSync, readFileSync } from "node:fs";
20
+ import { existsSync, readFileSync, statSync } from "node:fs";
21
21
  import nodeHTTP from "node:http";
22
22
  import { fileURLToPath, pathToFileURL } from "node:url";
23
23
  import { SourceMap, builtinModules, createRequire } from "node:module";
24
24
  import { createHash, randomUUID } from "node:crypto";
25
25
  import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
26
- import { gzipSync } from "node:zlib";
26
+ import { brotliDecompressSync, gzipSync, inflateSync } from "node:zlib";
27
27
  import { AsyncLocalStorage } from "node:async_hooks";
28
28
  // src/plugins/content.ts
29
29
  var CONFIG_FILE_NAMES = [
@@ -1575,35 +1575,45 @@ var SERIF_FAMILIES = /* @__PURE__ */ new Set([
1575
1575
  "cormorant",
1576
1576
  "cormorant garamond"
1577
1577
  ]);
1578
+ /** Guess a family's generic category from its name alone. */
1578
1579
  function getGenericFamily(family) {
1579
1580
  const lc = family.toLowerCase();
1580
1581
  if (lc.includes("mono") || lc.includes("code")) return "monospace";
1581
1582
  if (lc.includes("serif") && !lc.includes("sans") || SERIF_FAMILIES.has(lc)) return "serif";
1582
1583
  return "sans-serif";
1583
1584
  }
1584
- /**
1585
- * Generate the full CSS for a size-adjusted fallback font.
1586
- *
1587
- * This produces a complete @font-face block with override descriptors
1588
- * that FontFaceDescriptor doesn't natively support.
1589
- */
1590
- function generateFallbackCss(family) {
1591
- const metrics = FALLBACK_METRICS[family.toLowerCase()];
1592
- if (!metrics) return null;
1593
- return [
1585
+ /** The fallback family name for `family`. */
1586
+ function fallbackFamilyName(family) {
1587
+ return `${family} Fallback`;
1588
+ }
1589
+ /** Serialize a fallback face to an `@font-face` rule. */
1590
+ function generateFallbackFaceCss(face) {
1591
+ const lines = [
1594
1592
  "@font-face {",
1595
- ` font-family: '${`${family} Fallback`}';`,
1596
- ` src: local('${metrics.fallbackFont}');`,
1597
- ` size-adjust: ${metrics.sizeAdjust}%;`,
1598
- ` ascent-override: ${metrics.ascentOverride}%;`,
1599
- ` descent-override: ${metrics.descentOverride}%;`,
1600
- ` line-gap-override: ${metrics.lineGapOverride}%;`,
1601
- "}"
1602
- ].join("\n");
1593
+ ` font-family: '${face.family}';`,
1594
+ ` src: ${face.local.map((name) => `local('${name}')`).join(", ")};`
1595
+ ];
1596
+ if (face.weight) lines.push(` font-weight: ${face.weight};`);
1597
+ lines.push(` size-adjust: ${face.sizeAdjust}%;`, ` ascent-override: ${face.ascentOverride}%;`, ` descent-override: ${face.descentOverride}%;`, ` line-gap-override: ${face.lineGapOverride}%;`, "}");
1598
+ return lines.join("\n");
1603
1599
  }
1604
1600
  /**
1605
- * Check whether fallback metrics are available for a font family.
1601
+ * The fallback faces for a Google font, from the precomputed table. Empty
1602
+ * when the family isn't in the table.
1606
1603
  */
1604
+ function googleFallbackFaces(family) {
1605
+ const metrics = FALLBACK_METRICS[family.toLowerCase()];
1606
+ if (!metrics) return [];
1607
+ return [{
1608
+ family: fallbackFamilyName(family),
1609
+ local: [metrics.fallbackFont],
1610
+ sizeAdjust: metrics.sizeAdjust,
1611
+ ascentOverride: metrics.ascentOverride,
1612
+ descentOverride: metrics.descentOverride,
1613
+ lineGapOverride: metrics.lineGapOverride
1614
+ }];
1615
+ }
1616
+ /** Check whether the Google fallback table has metrics for a family. */
1607
1617
  function hasFallbackMetrics(family) {
1608
1618
  return family.toLowerCase() in FALLBACK_METRICS;
1609
1619
  }
@@ -1613,16 +1623,625 @@ function hasFallbackMetrics(family) {
1613
1623
  *
1614
1624
  * Example: `'Inter', 'Inter Fallback', system-ui, sans-serif`
1615
1625
  */
1616
- function buildFontStack(family) {
1617
- const generic = getGenericFamily(family);
1618
- const hasMetrics = hasFallbackMetrics(family);
1626
+ function buildFontStack(family, options = {}) {
1627
+ const generic = options.generic ?? getGenericFamily(family);
1628
+ const hasFallbackFace = options.hasFallbackFace ?? hasFallbackMetrics(family);
1619
1629
  const parts = [`'${family}'`];
1620
- if (hasMetrics) parts.push(`'${family} Fallback'`);
1621
- if (generic === "monospace") parts.push("ui-monospace");
1622
- else if (generic === "sans-serif") parts.push("system-ui");
1623
- parts.push(generic);
1630
+ if (hasFallbackFace) parts.push(`'${fallbackFamilyName(family)}'`);
1631
+ if (options.fallback) parts.push(...options.fallback);
1632
+ else {
1633
+ if (generic === "monospace") parts.push("ui-monospace");
1634
+ else if (generic === "sans-serif") parts.push("system-ui");
1635
+ parts.push(generic);
1636
+ }
1624
1637
  return parts.join(", ");
1625
1638
  }
1639
+ // src/fonts/sfnt.ts
1640
+ /**
1641
+ * Minimal font-container reader: TrueType/OpenType (sfnt), WOFF and WOFF2.
1642
+ *
1643
+ * Returns the raw bytes of the requested tables so `font-metrics.ts` can
1644
+ * read the handful of fields the fallback generator needs. This is
1645
+ * deliberately not a font parser — it only undoes the container:
1646
+ *
1647
+ * - sfnt (`\0\1\0\0`, `true`, `OTTO`): tables are stored as-is.
1648
+ * - WOFF (`wOFF`): each table is zlib-compressed independently.
1649
+ * - WOFF2 (`wOF2`): all tables are concatenated into one Brotli stream.
1650
+ * WOFF2 may *transform* `glyf`, `loca` and `hmtx`; a transformed table is
1651
+ * not in sfnt layout, so it is reported as missing rather than misread.
1652
+ * `head`, `hhea`, `OS/2`, `post` and `cmap` are never transformed.
1653
+ *
1654
+ * Both decompressors come from `node:zlib`, so no dependency is needed.
1655
+ * Font collections (`ttcf`) are not supported — they are not web fonts.
1656
+ *
1657
+ * Every read is bounds-checked: a truncated or non-font file yields `null`,
1658
+ * never a throw, because the caller's fallback is simply "no metrics".
1659
+ *
1660
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
1661
+ */
1662
+ var SFNT_TRUETYPE = 65536;
1663
+ var SFNT_TRUE = 1953658213;
1664
+ var SFNT_OTTO = 1330926671;
1665
+ var WOFF = 2001684038;
1666
+ var WOFF2 = 2001684018;
1667
+ /** WOFF2 §5.1 known-table index (flags & 0x3f). */
1668
+ var WOFF2_KNOWN_TAGS = [
1669
+ "cmap",
1670
+ "head",
1671
+ "hhea",
1672
+ "hmtx",
1673
+ "maxp",
1674
+ "name",
1675
+ "OS/2",
1676
+ "post",
1677
+ "cvt ",
1678
+ "fpgm",
1679
+ "glyf",
1680
+ "loca",
1681
+ "prep",
1682
+ "CFF ",
1683
+ "VORG",
1684
+ "EBDT",
1685
+ "EBLC",
1686
+ "gasp",
1687
+ "hdmx",
1688
+ "kern",
1689
+ "LTSH",
1690
+ "PCLT",
1691
+ "VDMX",
1692
+ "vhea",
1693
+ "vmtx",
1694
+ "BASE",
1695
+ "GDEF",
1696
+ "GPOS",
1697
+ "GSUB",
1698
+ "EBSC",
1699
+ "JSTF",
1700
+ "MATH",
1701
+ "CBDT",
1702
+ "CBLC",
1703
+ "COLR",
1704
+ "CPAL",
1705
+ "SVG ",
1706
+ "sbix",
1707
+ "acnt",
1708
+ "avar",
1709
+ "bdat",
1710
+ "bloc",
1711
+ "bsln",
1712
+ "cvar",
1713
+ "fdsc",
1714
+ "feat",
1715
+ "fmtx",
1716
+ "fvar",
1717
+ "gvar",
1718
+ "hsty",
1719
+ "just",
1720
+ "lcar",
1721
+ "mort",
1722
+ "morx",
1723
+ "opbd",
1724
+ "prop",
1725
+ "trak",
1726
+ "Zapf",
1727
+ "Silf",
1728
+ "Glat",
1729
+ "Gloc",
1730
+ "Feat",
1731
+ "Sill"
1732
+ ];
1733
+ function tagAt(view, offset) {
1734
+ return String.fromCharCode(view.getUint8(offset), view.getUint8(offset + 1), view.getUint8(offset + 2), view.getUint8(offset + 3));
1735
+ }
1736
+ function slice(bytes, offset, length) {
1737
+ if (offset < 0 || length < 0 || offset + length > bytes.byteLength) return null;
1738
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, length);
1739
+ }
1740
+ /**
1741
+ * Read the requested tables out of a font file. Returns `null` when the
1742
+ * bytes are not a supported font container or are truncated.
1743
+ */
1744
+ function readSfntTables(data, wanted) {
1745
+ try {
1746
+ if (data.byteLength < 12) return null;
1747
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1748
+ const signature = view.getUint32(0);
1749
+ const want = new Set(wanted);
1750
+ switch (signature) {
1751
+ case SFNT_TRUETYPE:
1752
+ case SFNT_TRUE:
1753
+ case SFNT_OTTO: return readSfnt(data, view, want);
1754
+ case WOFF: return readWoff(data, view, want);
1755
+ case WOFF2: return readWoff2(data, view, want);
1756
+ default: return null;
1757
+ }
1758
+ } catch {
1759
+ return null;
1760
+ }
1761
+ }
1762
+ function readSfnt(data, view, want) {
1763
+ const numTables = view.getUint16(4);
1764
+ const tables = /* @__PURE__ */ new Map();
1765
+ for (let i = 0; i < numTables; i++) {
1766
+ const rec = 12 + i * 16;
1767
+ const tag = tagAt(view, rec);
1768
+ if (!want.has(tag)) continue;
1769
+ const table = slice(data, view.getUint32(rec + 8), view.getUint32(rec + 12));
1770
+ if (!table) return null;
1771
+ tables.set(tag, table);
1772
+ }
1773
+ return tables;
1774
+ }
1775
+ function readWoff(data, view, want) {
1776
+ const numTables = view.getUint16(12);
1777
+ const tables = /* @__PURE__ */ new Map();
1778
+ for (let i = 0; i < numTables; i++) {
1779
+ const rec = 44 + i * 20;
1780
+ const tag = tagAt(view, rec);
1781
+ if (!want.has(tag)) continue;
1782
+ const offset = view.getUint32(rec + 4);
1783
+ const compLength = view.getUint32(rec + 8);
1784
+ const origLength = view.getUint32(rec + 12);
1785
+ const stored = slice(data, offset, compLength);
1786
+ if (!stored) return null;
1787
+ if (compLength === origLength) {
1788
+ tables.set(tag, stored);
1789
+ continue;
1790
+ }
1791
+ const raw = inflateSync(new Uint8Array(stored.buffer, stored.byteOffset, compLength));
1792
+ tables.set(tag, new DataView(raw.buffer, raw.byteOffset, raw.byteLength));
1793
+ }
1794
+ return tables;
1795
+ }
1796
+ /** WOFF2 UIntBase128: big-endian base-128, at most 5 bytes. */
1797
+ function readBase128(view, cursor) {
1798
+ let value = 0;
1799
+ for (let i = 0; i < 5; i++) {
1800
+ const byte = view.getUint8(cursor.pos++);
1801
+ if (i === 0 && byte === 128) throw new RangeError("bad UIntBase128");
1802
+ value = value * 128 + (byte & 127);
1803
+ if ((byte & 128) === 0) return value;
1804
+ }
1805
+ throw new RangeError("UIntBase128 too long");
1806
+ }
1807
+ function readWoff2(data, view, want) {
1808
+ if (view.getUint32(4) === 1953784678) return null;
1809
+ const numTables = view.getUint16(12);
1810
+ const totalCompressedSize = view.getUint32(20);
1811
+ const cursor = { pos: 48 };
1812
+ const entries = [];
1813
+ let streamOffset = 0;
1814
+ for (let i = 0; i < numTables; i++) {
1815
+ const flags = view.getUint8(cursor.pos++);
1816
+ const knownIndex = flags & 63;
1817
+ let tag;
1818
+ if (knownIndex === 63) {
1819
+ tag = tagAt(view, cursor.pos);
1820
+ cursor.pos += 4;
1821
+ } else {
1822
+ tag = WOFF2_KNOWN_TAGS[knownIndex];
1823
+ if (!tag) return null;
1824
+ }
1825
+ const transformVersion = flags >> 6 & 3;
1826
+ const origLength = readBase128(view, cursor);
1827
+ const transformed = tag === "glyf" || tag === "loca" ? transformVersion !== 3 : transformVersion !== 0;
1828
+ const length = transformed ? readBase128(view, cursor) : origLength;
1829
+ entries.push({
1830
+ tag,
1831
+ offset: streamOffset,
1832
+ length,
1833
+ transformed
1834
+ });
1835
+ streamOffset += length;
1836
+ }
1837
+ const compressed = slice(data, cursor.pos, totalCompressedSize);
1838
+ if (!compressed) return null;
1839
+ const stream = brotliDecompressSync(new Uint8Array(compressed.buffer, compressed.byteOffset, totalCompressedSize));
1840
+ const tables = /* @__PURE__ */ new Map();
1841
+ for (const entry of entries) {
1842
+ if (!want.has(entry.tag) || entry.transformed) continue;
1843
+ const table = slice(stream, entry.offset, entry.length);
1844
+ if (!table) return null;
1845
+ tables.set(entry.tag, table);
1846
+ }
1847
+ return tables;
1848
+ }
1849
+ // src/fonts/font-metrics.ts
1850
+ /**
1851
+ * Read the vertical and horizontal metrics a size-adjusted fallback needs
1852
+ * from a font file (TTF / OTF / WOFF / WOFF2).
1853
+ *
1854
+ * Fields read:
1855
+ *
1856
+ * - `head.unitsPerEm`
1857
+ * - ascent / descent / lineGap — from `hhea`, or from `OS/2` sTypo* when
1858
+ * `fsSelection` bit 7 (USE_TYPO_METRICS) is set, which is what browsers
1859
+ * do with such fonts
1860
+ * - `OS/2.xAvgCharWidth`, and the advance widths of a letter-frequency
1861
+ * weighted Latin sample (`cmap` → glyph id → `hmtx`), the same sample
1862
+ * Next.js's `adjustFontFallback` and capsize use
1863
+ * - whether the font is monospace: `post.isFixedPitch`, `OS/2` PANOSE
1864
+ * proportion = monospaced, or every sampled glyph sharing one advance
1865
+ * - whether it is serif or sans, from PANOSE / IBM font class, when the
1866
+ * font declares it
1867
+ *
1868
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
1869
+ */
1870
+ /**
1871
+ * Letter-frequency weighted Latin sample, with spaces for word length.
1872
+ * Identical to Next.js's `calcAverageWidth` (packages/font/src/local/
1873
+ * get-fallback-metrics-from-font-file.ts) so the reference widths of the
1874
+ * fallback bases are comparable.
1875
+ */
1876
+ var AVG_WIDTH_SAMPLE = "aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ";
1877
+ /** Characters whose advances must all match for a font to count as monospace. */
1878
+ var MONO_PROBE = "abcdefghijklmnopqrstuvwxyz0123456789 ";
1879
+ var TABLES = [
1880
+ "head",
1881
+ "hhea",
1882
+ "OS/2",
1883
+ "post",
1884
+ "cmap",
1885
+ "hmtx"
1886
+ ];
1887
+ /** Parse metrics from font bytes. `null` when the file can't be read. */
1888
+ function readFontMetrics(data) {
1889
+ const tables = readSfntTables(data, TABLES);
1890
+ if (!tables) return null;
1891
+ const head = tables.get("head");
1892
+ const hhea = tables.get("hhea");
1893
+ if (!head || !hhea || head.byteLength < 54 || hhea.byteLength < 36) return null;
1894
+ try {
1895
+ const unitsPerEm = head.getUint16(18);
1896
+ if (unitsPerEm === 0) return null;
1897
+ let ascent = hhea.getInt16(4);
1898
+ let descent = hhea.getInt16(6);
1899
+ let lineGap = hhea.getInt16(8);
1900
+ const numberOfHMetrics = hhea.getUint16(34);
1901
+ const os2 = tables.get("OS/2");
1902
+ let xAvgCharWidth;
1903
+ let declaredCategory;
1904
+ let panoseMono = false;
1905
+ if (os2 && os2.byteLength >= 78) {
1906
+ const avg = os2.getInt16(2);
1907
+ if (avg > 0) xAvgCharWidth = avg;
1908
+ if (os2.getUint16(62) & 128) {
1909
+ ascent = os2.getInt16(68);
1910
+ descent = os2.getInt16(70);
1911
+ lineGap = os2.getInt16(72);
1912
+ }
1913
+ const panose = (i) => os2.getUint8(32 + i);
1914
+ if (panose(0) === 2) {
1915
+ const serifStyle = panose(1);
1916
+ if (serifStyle >= 2 && serifStyle <= 10) declaredCategory = "serif";
1917
+ else if (serifStyle >= 11 && serifStyle <= 13) declaredCategory = "sans-serif";
1918
+ panoseMono = panose(3) === 9;
1919
+ }
1920
+ if (!declaredCategory) {
1921
+ const ibmClass = os2.getInt16(30) >> 8;
1922
+ if (ibmClass >= 1 && ibmClass <= 5 || ibmClass === 7) declaredCategory = "serif";
1923
+ else if (ibmClass === 8) declaredCategory = "sans-serif";
1924
+ }
1925
+ }
1926
+ const post = tables.get("post");
1927
+ const isFixedPitch = post !== void 0 && post.byteLength >= 16 && post.getUint32(12) !== 0;
1928
+ const advanceOf = buildAdvanceLookup(tables.get("cmap"), tables.get("hmtx"), numberOfHMetrics);
1929
+ const sampleAvgWidth = advanceOf ? averageAdvance(AVG_WIDTH_SAMPLE, advanceOf) : void 0;
1930
+ const sameAdvance = advanceOf ? allSameAdvance(MONO_PROBE, advanceOf) : false;
1931
+ return {
1932
+ unitsPerEm,
1933
+ ascent,
1934
+ descent: Math.abs(descent),
1935
+ lineGap,
1936
+ xAvgCharWidth,
1937
+ sampleAvgWidth,
1938
+ monospace: isFixedPitch || panoseMono || sameAdvance,
1939
+ declaredCategory
1940
+ };
1941
+ } catch {
1942
+ return null;
1943
+ }
1944
+ }
1945
+ function averageAdvance(sample, advanceOf) {
1946
+ let total = 0;
1947
+ for (const ch of sample) {
1948
+ const advance = advanceOf(ch.codePointAt(0));
1949
+ if (advance === void 0) return void 0;
1950
+ total += advance;
1951
+ }
1952
+ return total / sample.length;
1953
+ }
1954
+ function allSameAdvance(sample, advanceOf) {
1955
+ let first;
1956
+ for (const ch of sample) {
1957
+ const advance = advanceOf(ch.codePointAt(0));
1958
+ if (advance === void 0) return false;
1959
+ if (first === void 0) first = advance;
1960
+ else if (advance !== first) return false;
1961
+ }
1962
+ return true;
1963
+ }
1964
+ /** Code point → advance width, via `cmap` and `hmtx`. */
1965
+ function buildAdvanceLookup(cmap, hmtx, numberOfHMetrics) {
1966
+ if (!cmap || !hmtx || numberOfHMetrics === 0) return null;
1967
+ if (hmtx.byteLength < numberOfHMetrics * 4) return null;
1968
+ const glyphOf = buildGlyphLookup(cmap);
1969
+ if (!glyphOf) return null;
1970
+ return (codePoint) => {
1971
+ const gid = glyphOf(codePoint);
1972
+ if (!gid) return void 0;
1973
+ const index = Math.min(gid, numberOfHMetrics - 1);
1974
+ return hmtx.getUint16(index * 4);
1975
+ };
1976
+ }
1977
+ /**
1978
+ * Pick a Unicode `cmap` subtable (format 4 or 12) and return a lookup.
1979
+ * Preference: (3,10) / (0,4+) full repertoire, then (3,1) / (0,x) BMP.
1980
+ */
1981
+ function buildGlyphLookup(cmap) {
1982
+ const numSubtables = cmap.getUint16(2);
1983
+ let best = null;
1984
+ for (let i = 0; i < numSubtables; i++) {
1985
+ const rec = 4 + i * 8;
1986
+ const platform = cmap.getUint16(rec);
1987
+ const encoding = cmap.getUint16(rec + 2);
1988
+ const offset = cmap.getUint32(rec + 4);
1989
+ if (offset + 4 > cmap.byteLength) continue;
1990
+ const format = cmap.getUint16(offset);
1991
+ if (format !== 4 && format !== 12) continue;
1992
+ if (!(platform === 0 || platform === 3 && (encoding === 1 || encoding === 10))) continue;
1993
+ const rank = format === 12 ? 2 : 1;
1994
+ if (!best || rank > best.rank) best = {
1995
+ offset,
1996
+ rank
1997
+ };
1998
+ }
1999
+ if (!best) return null;
2000
+ const offset = best.offset;
2001
+ return cmap.getUint16(offset) === 12 ? cmapFormat12(cmap, offset) : cmapFormat4(cmap, offset);
2002
+ }
2003
+ function cmapFormat4(cmap, offset) {
2004
+ const segCount = cmap.getUint16(offset + 6) / 2;
2005
+ const endCodes = offset + 14;
2006
+ const startCodes = endCodes + segCount * 2 + 2;
2007
+ const idDeltas = startCodes + segCount * 2;
2008
+ const idRangeOffsets = idDeltas + segCount * 2;
2009
+ return (cp) => {
2010
+ if (cp > 65535) return 0;
2011
+ for (let s = 0; s < segCount; s++) {
2012
+ if (cp > cmap.getUint16(endCodes + s * 2)) continue;
2013
+ const start = cmap.getUint16(startCodes + s * 2);
2014
+ if (cp < start) return 0;
2015
+ const delta = cmap.getInt16(idDeltas + s * 2);
2016
+ const rangeOffsetPos = idRangeOffsets + s * 2;
2017
+ const rangeOffset = cmap.getUint16(rangeOffsetPos);
2018
+ if (rangeOffset === 0) return cp + delta & 65535;
2019
+ const glyphPos = rangeOffsetPos + rangeOffset + (cp - start) * 2;
2020
+ if (glyphPos + 2 > cmap.byteLength) return 0;
2021
+ const glyph = cmap.getUint16(glyphPos);
2022
+ return glyph === 0 ? 0 : glyph + delta & 65535;
2023
+ }
2024
+ return 0;
2025
+ };
2026
+ }
2027
+ function cmapFormat12(cmap, offset) {
2028
+ const numGroups = cmap.getUint32(offset + 12);
2029
+ return (cp) => {
2030
+ for (let g = 0; g < numGroups; g++) {
2031
+ const rec = offset + 16 + g * 12;
2032
+ const start = cmap.getUint32(rec);
2033
+ const end = cmap.getUint32(rec + 4);
2034
+ if (cp >= start && cp <= end) return cmap.getUint32(rec + 8) + (cp - start);
2035
+ }
2036
+ return 0;
2037
+ };
2038
+ }
2039
+ // src/fonts/local-fallback.ts
2040
+ /**
2041
+ * Size-adjusted fallbacks for local fonts, computed from the font files.
2042
+ *
2043
+ * Google fonts ship with a precomputed metrics table (`fallbacks.ts`); a
2044
+ * local font can be anything, so its metrics are read from the font file
2045
+ * itself (`font-metrics.ts`) when the transform registers it — at build
2046
+ * time in production, on first transform in dev.
2047
+ *
2048
+ * From those metrics this module decides:
2049
+ *
2050
+ * 1. The generic family. Fixed-pitch fonts are `monospace`; otherwise the
2051
+ * font's own PANOSE / IBM class, otherwise the family-name heuristic.
2052
+ * `adjustFontFallback: 'Arial' | 'Times New Roman' | 'monospace'`
2053
+ * overrides it.
2054
+ * 2. The fallback base: Arial (sans), Times New Roman (serif), or a list
2055
+ * of ~0.600em monospace system fonts (mono). Each base lists
2056
+ * metric-compatible Linux equivalents as later `local()` sources.
2057
+ * 3. The overrides, computed the way Next.js's `adjustFontFallback` does:
2058
+ * `size-adjust` = font average width / base average width, then each
2059
+ * vertical metric divided by `unitsPerEm × size-adjust` (the overrides
2060
+ * apply to the *adjusted* size).
2061
+ *
2062
+ * A bold (700) face is emitted when the font has its own 700 source, using
2063
+ * the base's bold system font and the bold file's metrics. Without it the
2064
+ * browser would synthesize bold from the regular fallback, which changes
2065
+ * glyph widths and re-wraps text on swap.
2066
+ *
2067
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
2068
+ */
2069
+ /**
2070
+ * Reference metrics, measured with `readFontMetrics` on the macOS system
2071
+ * fonts. Arial's and Times New Roman's sample widths match Next.js's
2072
+ * constants (934.51 and 854.40 per 2048). Every listed monospace font is
2073
+ * 1229–1233/2048 wide (Courier New, Liberation Mono, Cousine, Droid Sans
2074
+ * Mono and Roboto Mono are 1229; Menlo and DejaVu Sans Mono 1233), so one
2075
+ * reference serves the list.
2076
+ */
2077
+ var BASES = {
2078
+ "sans-serif": {
2079
+ regular: {
2080
+ local: [
2081
+ "Arial",
2082
+ "ArialMT",
2083
+ "Liberation Sans",
2084
+ "Arimo"
2085
+ ],
2086
+ unitsPerEm: 2048,
2087
+ sampleAvgWidth: 934.5116279069767,
2088
+ xAvgCharWidth: 904
2089
+ },
2090
+ bold: {
2091
+ local: [
2092
+ "Arial Bold",
2093
+ "Arial-BoldMT",
2094
+ "Liberation Sans Bold",
2095
+ "Arimo Bold"
2096
+ ],
2097
+ unitsPerEm: 2048,
2098
+ sampleAvgWidth: 1011.046511627907,
2099
+ xAvgCharWidth: 980
2100
+ }
2101
+ },
2102
+ "serif": {
2103
+ regular: {
2104
+ local: [
2105
+ "Times New Roman",
2106
+ "TimesNewRomanPSMT",
2107
+ "Liberation Serif",
2108
+ "Tinos"
2109
+ ],
2110
+ unitsPerEm: 2048,
2111
+ sampleAvgWidth: 854.3953488372093,
2112
+ xAvgCharWidth: 821
2113
+ },
2114
+ bold: {
2115
+ local: [
2116
+ "Times New Roman Bold",
2117
+ "TimesNewRomanPS-BoldMT",
2118
+ "Liberation Serif Bold",
2119
+ "Tinos Bold"
2120
+ ],
2121
+ unitsPerEm: 2048,
2122
+ sampleAvgWidth: 907.5581395348837,
2123
+ xAvgCharWidth: 874
2124
+ }
2125
+ },
2126
+ "monospace": {
2127
+ regular: {
2128
+ local: [
2129
+ "Menlo",
2130
+ "DejaVu Sans Mono",
2131
+ "Liberation Mono",
2132
+ "Cousine",
2133
+ "Droid Sans Mono",
2134
+ "Roboto Mono",
2135
+ "Courier New"
2136
+ ],
2137
+ unitsPerEm: 2048,
2138
+ sampleAvgWidth: 1229,
2139
+ xAvgCharWidth: 1229
2140
+ },
2141
+ bold: {
2142
+ local: [
2143
+ "Menlo Bold",
2144
+ "Menlo-Bold",
2145
+ "DejaVu Sans Mono Bold",
2146
+ "Liberation Mono Bold",
2147
+ "Cousine Bold",
2148
+ "Roboto Mono Bold",
2149
+ "Courier New Bold",
2150
+ "CourierNewPS-BoldMT"
2151
+ ],
2152
+ unitsPerEm: 2048,
2153
+ sampleAvgWidth: 1229,
2154
+ xAvgCharWidth: 1229
2155
+ }
2156
+ }
2157
+ };
2158
+ var ADJUST_CATEGORY = {
2159
+ "Arial": "sans-serif",
2160
+ "Times New Roman": "serif",
2161
+ "monospace": "monospace"
2162
+ };
2163
+ /** Metrics by absolute path, invalidated by mtime/size (dev edits). */
2164
+ var metricsCache = /* @__PURE__ */ new Map();
2165
+ /** Read a font file's metrics, or `null` when it is missing or unreadable. */
2166
+ function readFontFileMetrics(path) {
2167
+ let stat;
2168
+ try {
2169
+ stat = statSync(path);
2170
+ } catch {
2171
+ return null;
2172
+ }
2173
+ const cached = metricsCache.get(path);
2174
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.metrics;
2175
+ let metrics;
2176
+ try {
2177
+ metrics = readFontMetrics(readFileSync(path));
2178
+ } catch {
2179
+ metrics = null;
2180
+ }
2181
+ metricsCache.set(path, {
2182
+ mtimeMs: stat.mtimeMs,
2183
+ size: stat.size,
2184
+ metrics
2185
+ });
2186
+ return metrics;
2187
+ }
2188
+ var isBold = (weight) => weight === "700" || weight === "bold";
2189
+ var isRegular = (weight) => weight === void 0 || weight === "400" || weight === "normal";
2190
+ var isUpright$1 = (style) => style === void 0 || style === "normal";
2191
+ /** The source fallback metrics come from: 400 normal, else the first. */
2192
+ function pickRegularSource(sources) {
2193
+ return sources.find((s) => isRegular(s.weight) && isUpright$1(s.style)) ?? sources[0];
2194
+ }
2195
+ function pickBoldSource(sources) {
2196
+ return sources.find((s) => isBold(s.weight) && isUpright$1(s.style)) ?? sources.find((s) => isBold(s.weight));
2197
+ }
2198
+ /** Round to the 2-decimal percentage a CSS descriptor carries. */
2199
+ function percent(ratio) {
2200
+ return Math.round(Math.abs(ratio) * 1e4) / 100;
2201
+ }
2202
+ /** Compute one fallback face from a font's metrics against a base face. */
2203
+ function computeFallbackFace(family, metrics, base, weight) {
2204
+ let sizeAdjust = 1;
2205
+ if (metrics.sampleAvgWidth) sizeAdjust = metrics.sampleAvgWidth / metrics.unitsPerEm / (base.sampleAvgWidth / base.unitsPerEm);
2206
+ else if (metrics.xAvgCharWidth) sizeAdjust = metrics.xAvgCharWidth / metrics.unitsPerEm / (base.xAvgCharWidth / base.unitsPerEm);
2207
+ const scale = metrics.unitsPerEm * sizeAdjust;
2208
+ return {
2209
+ family: fallbackFamilyName(family),
2210
+ local: base.local,
2211
+ ...weight ? { weight } : {},
2212
+ sizeAdjust: percent(sizeAdjust),
2213
+ ascentOverride: percent(metrics.ascent / scale),
2214
+ descentOverride: percent(metrics.descent / scale),
2215
+ lineGapOverride: percent(metrics.lineGap / scale)
2216
+ };
2217
+ }
2218
+ /**
2219
+ * Work out a local font's generic family and fallback faces.
2220
+ *
2221
+ * `sources` must already be resolved to absolute paths. Missing or
2222
+ * unreadable files produce no faces (the stack then skips the fallback
2223
+ * family) and the name heuristic for the generic family.
2224
+ */
2225
+ function resolveLocalFallback(family, sources, adjust = true) {
2226
+ const regularSrc = pickRegularSource(sources);
2227
+ const metrics = regularSrc ? readFontFileMetrics(regularSrc.path) : null;
2228
+ const generic = typeof adjust === "string" ? ADJUST_CATEGORY[adjust] : metrics?.monospace ? "monospace" : metrics?.declaredCategory ?? getGenericFamily(family);
2229
+ if (adjust === false || !metrics) return {
2230
+ generic,
2231
+ faces: []
2232
+ };
2233
+ const base = BASES[generic];
2234
+ const faces = [computeFallbackFace(family, metrics, base.regular)];
2235
+ const boldSrc = pickBoldSource(sources);
2236
+ if (boldSrc && boldSrc !== regularSrc) {
2237
+ const boldMetrics = readFontFileMetrics(boldSrc.path) ?? metrics;
2238
+ faces.push(computeFallbackFace(family, boldMetrics, base.bold, "700"));
2239
+ }
2240
+ return {
2241
+ generic,
2242
+ faces
2243
+ };
2244
+ }
1626
2245
  // src/fonts/ast-walk.ts
1627
2246
  /** Convert a 0-based byte offset into a 1-based line and 0-based column. */
1628
2247
  function offsetToLineColumn(source, offset) {
@@ -1892,6 +2511,9 @@ function extractGoogleConfig(objNode) {
1892
2511
  }
1893
2512
  return config;
1894
2513
  }
2514
+ function isAdjustFontFallback(value) {
2515
+ return typeof value === "boolean" || value === "Arial" || value === "Times New Roman" || value === "monospace";
2516
+ }
1895
2517
  /** Shared implementation for LocalFontConfig extraction from an object node. */
1896
2518
  function extractLocalConfig(objNode) {
1897
2519
  const props = objectProperties(objNode);
@@ -1901,6 +2523,25 @@ function extractLocalConfig(objNode) {
1901
2523
  const variable = variableNode ? extractString(variableNode) : void 0;
1902
2524
  const familyNode = props.get("family");
1903
2525
  const family = familyNode ? extractString(familyNode) : void 0;
2526
+ const options = {};
2527
+ const preloadNode = props.get("preload");
2528
+ if (preloadNode) {
2529
+ const b = extractBoolean(preloadNode);
2530
+ if (b === void 0) return null;
2531
+ options.preload = b;
2532
+ }
2533
+ const adjustNode = props.get("adjustFontFallback");
2534
+ if (adjustNode) {
2535
+ const value = extractBoolean(adjustNode) ?? extractString(adjustNode);
2536
+ if (!isAdjustFontFallback(value)) return null;
2537
+ options.adjustFontFallback = value;
2538
+ }
2539
+ const fallbackNode = props.get("fallback");
2540
+ if (fallbackNode) {
2541
+ const list = extractStringArray(fallbackNode);
2542
+ if (!list) return null;
2543
+ options.fallback = list;
2544
+ }
1904
2545
  const srcNode = props.get("src");
1905
2546
  if (!srcNode) return null;
1906
2547
  const srcString = extractString(srcNode);
@@ -1908,7 +2549,8 @@ function extractLocalConfig(objNode) {
1908
2549
  src: srcString,
1909
2550
  display,
1910
2551
  variable,
1911
- family
2552
+ family,
2553
+ ...options
1912
2554
  };
1913
2555
  if (srcNode.type === "ArrayExpression") {
1914
2556
  const arr = srcNode;
@@ -1923,7 +2565,8 @@ function extractLocalConfig(objNode) {
1923
2565
  src: entries,
1924
2566
  display,
1925
2567
  variable,
1926
- family
2568
+ family,
2569
+ ...options
1927
2570
  };
1928
2571
  }
1929
2572
  return null;
@@ -2223,7 +2866,12 @@ function processLocalFont(config, importerPath) {
2223
2866
  const family = config.family ?? generateFamilyName(sources);
2224
2867
  const display = config.display ?? "swap";
2225
2868
  const className = localFontClassName(family);
2226
- const fontStack = buildFontStack(family);
2869
+ const { generic, faces } = resolveLocalFallback(family, resolvedSources, config.adjustFontFallback);
2870
+ const fontStack = buildFontStack(family, {
2871
+ generic,
2872
+ hasFallbackFace: faces.length > 0,
2873
+ fallback: config.fallback
2874
+ });
2227
2875
  const weights = [...new Set(resolvedSources.map((s) => s.weight ?? "400"))];
2228
2876
  const styles = [...new Set(resolvedSources.map((s) => s.style ?? "normal"))];
2229
2877
  return {
@@ -2238,7 +2886,9 @@ function processLocalFont(config, importerPath) {
2238
2886
  localSources: resolvedSources,
2239
2887
  importer: importerPath,
2240
2888
  className,
2241
- fontFamily: fontStack
2889
+ fontFamily: fontStack,
2890
+ fallbackFaces: faces,
2891
+ preload: config.preload ?? true
2242
2892
  };
2243
2893
  }
2244
2894
  var RESOLVED_GOOGLE = "\0@timber/fonts/google";
@@ -2620,8 +3270,8 @@ function renderEntryCss(entry, urlPrefix) {
2620
3270
  const faceCss = generateFontFaces(entry.faces);
2621
3271
  if (faceCss) cssParts.push(faceCss);
2622
3272
  }
2623
- const fallbackCss = generateFallbackCss(entry.family);
2624
- if (fallbackCss) cssParts.push(fallbackCss);
3273
+ const fallbackFaces = entry.provider === "local" ? entry.fallbackFaces ?? [] : googleFallbackFaces(entry.family);
3274
+ for (const face of fallbackFaces) cssParts.push(generateFallbackFaceCss(face));
2625
3275
  if (entry.variable) cssParts.push(generateVariableClass(entry.className, entry.variable, entry.fontFamily));
2626
3276
  else cssParts.push(generateFontFamilyClass(entry.className, entry.fontFamily));
2627
3277
  return cssParts.join("\n\n");
@@ -4342,12 +4992,13 @@ function runFontsTransform(code, id, pipeline, emitError) {
4342
4992
  variable: config.variable,
4343
4993
  className,
4344
4994
  fontFamily: fontStack,
4345
- importer: id
4995
+ importer: id,
4996
+ preload: config.preload ?? true
4346
4997
  }
4347
4998
  });
4348
4999
  } else {
4349
5000
  const config = extractLocalFontConfigFromNode(site.configNode);
4350
- if (!config) emitError(`Could not statically analyze local font config at line ${site.line}, column ${site.column}. Ensure src is a string or array of { path, weight?, style? } objects.`);
5001
+ if (!config) emitError(`Could not statically analyze local font config at line ${site.line}, column ${site.column}. Ensure src is a string or array of { path, weight?, style? } objects, preload is a boolean, adjustFontFallback is a boolean or 'Arial' | 'Times New Roman' | 'monospace', and fallback is an array of strings.`);
4351
5002
  pending.push({
4352
5003
  site,
4353
5004
  extracted: processLocalFont(config, id)
@@ -4487,134 +5138,395 @@ function emitFontAssets(pipeline, emitFile, warn) {
4487
5138
  }
4488
5139
  }
4489
5140
  /**
4490
- * Populate `buildManifest.fonts` with `ManifestFontEntry[]` keyed by the
4491
- * absolute importer path. This matches the runtime route manifest's
4492
- * `filePath` values (which are absolute) and is consistent with how
4493
- * `buildManifest.css` keys work after TIM-1014.
5141
+ * Map each font importer to the route files (layouts and pages) that
5142
+ * import it, directly or through any chain of modules.
5143
+ *
5144
+ * A font is usually defined in a shared module (`app/fonts.ts`) and applied
5145
+ * in a layout that imports it. The manifest is read per matched route
5146
+ * segment (`collectRouteFonts`), so an entry keyed only by the defining
5147
+ * module would never be found. Walking *up* the importer graph from each
5148
+ * font module is cheap — there are a handful of font modules, and the walk
5149
+ * stops at modules already visited.
5150
+ *
5151
+ * `getImporters` is Rollup's `getModuleInfo(id)?.importers` from the RSC
5152
+ * build, where layouts and pages are real modules. A route file reached
5153
+ * through another route file (a page importing a layout's module) still
5154
+ * counts: the font is in that page's graph.
5155
+ */
5156
+ function mapFontImportersToRoutes(importers, routeFiles, getImporters) {
5157
+ const routeSet = new Set(routeFiles);
5158
+ const result = /* @__PURE__ */ new Map();
5159
+ for (const importer of importers) {
5160
+ const routes = [];
5161
+ const visited = /* @__PURE__ */ new Set([importer]);
5162
+ const queue = [importer];
5163
+ while (queue.length > 0) {
5164
+ const id = queue.shift();
5165
+ if (routeSet.has(id)) routes.push(id);
5166
+ for (const parent of getImporters(id) ?? []) {
5167
+ if (visited.has(parent)) continue;
5168
+ visited.add(parent);
5169
+ queue.push(parent);
5170
+ }
5171
+ }
5172
+ result.set(importer, routes);
5173
+ }
5174
+ return result;
5175
+ }
5176
+ /** Only upright faces are preloaded — italics are rarely above the fold. */
5177
+ var isUpright = (style) => style === void 0 || style === "normal";
5178
+ /**
5179
+ * Populate `buildManifest.fonts` with the font binaries to preload, keyed
5180
+ * by absolute path. The keys are the font's importer plus every route file
5181
+ * that reaches it (`routesByImporter`, from `mapFontImportersToRoutes`), so
5182
+ * `collectRouteFonts` finds a font defined outside the layout that applies
5183
+ * it. Keys are absolute, matching the route manifest's `filePath` values
5184
+ * (and `buildManifest.css`, TIM-1014).
4494
5185
  *
4495
- * All font binaries use content-hashed filenames for immutable caching.
4496
- * Hrefs are prefixed with Vite's resolved `base` so they match the URLs
4497
- * the platform serves the emitted binaries under.
5186
+ * Fonts with `preload: false` and non-upright faces are left out. All
5187
+ * hrefs are content-hashed and prefixed with Vite's resolved `base`.
4498
5188
  */
4499
- function writeFontManifest(pipeline, buildManifest, base = "/") {
5189
+ function writeFontManifest(pipeline, buildManifest, base = "/", routesByImporter) {
4500
5190
  const urlPrefix = fontUrlPrefix(base);
4501
- const fontsByImporter = /* @__PURE__ */ new Map();
5191
+ const fontsByKey = /* @__PURE__ */ new Map();
4502
5192
  for (const entry of pipeline.entries()) {
4503
- const manifestEntries = fontsByImporter.get(entry.importer) ?? [];
5193
+ if (entry.preload === false) continue;
5194
+ const preloads = [];
4504
5195
  if (entry.provider === "local" && entry.localSources) for (const src of entry.localSources) {
5196
+ if (!isUpright(src.style)) continue;
4505
5197
  const filename = src.hashedBasename ?? fontOutputBasename(src.path);
4506
- const format = inferFontFormat(src.path);
4507
- manifestEntries.push({
5198
+ preloads.push({
4508
5199
  href: `${urlPrefix}/${filename}`,
4509
- format,
5200
+ format: inferFontFormat(src.path),
4510
5201
  crossOrigin: "anonymous"
4511
5202
  });
4512
5203
  }
4513
- else if (entry.cachedFiles) for (const cf of entry.cachedFiles) manifestEntries.push({
4514
- href: `${urlPrefix}/${cf.hashedFilename}`,
4515
- format: "woff2",
4516
- crossOrigin: "anonymous"
4517
- });
4518
- fontsByImporter.set(entry.importer, manifestEntries);
5204
+ else if (entry.cachedFiles) for (const cf of entry.cachedFiles) {
5205
+ if (!isUpright(cf.face.style)) continue;
5206
+ preloads.push({
5207
+ href: `${urlPrefix}/${cf.hashedFilename}`,
5208
+ format: "woff2",
5209
+ crossOrigin: "anonymous"
5210
+ });
5211
+ }
5212
+ if (preloads.length === 0) continue;
5213
+ const keys = /* @__PURE__ */ new Set([entry.importer, ...routesByImporter?.get(entry.importer) ?? []]);
5214
+ for (const key of keys) {
5215
+ const byHref = fontsByKey.get(key) ?? /* @__PURE__ */ new Map();
5216
+ for (const preload of preloads) byHref.set(preload.href, preload);
5217
+ fontsByKey.set(key, byHref);
5218
+ }
4519
5219
  }
4520
- for (const [importer, entries] of fontsByImporter) buildManifest.fonts[importer] = entries;
5220
+ for (const [key, byHref] of fontsByKey) buildManifest.fonts[key] = [...byHref.values()];
4521
5221
  }
4522
- // src/plugins/fonts.ts
5222
+ // src/plugins/build-manifest.ts
4523
5223
  /**
4524
- * timber-fonts — Vite sub-plugin shell for build-time font processing.
5224
+ * timber-build-manifest — Vite sub-plugin for build asset manifest generation.
4525
5225
  *
4526
- * This file is intentionally thin: it wires the Vite plugin hooks to the
4527
- * pipeline + per-concern modules under `../fonts/`. All real logic lives
4528
- * in:
5226
+ * Provides `virtual:timber-build-manifest` which exports a BuildManifest
5227
+ * mapping route segment file paths to their CSS, JS, and modulepreload
5228
+ * output chunks.
4529
5229
  *
4530
- * - `../fonts/pipeline.ts` — `FontPipeline` (state, mutators)
4531
- * - `../fonts/transform.ts` — transform-hook logic, parsing helpers
4532
- * - `../fonts/dev-middleware.ts` — dev font binary server
4533
- * - `../fonts/virtual-modules.ts` — virtual module ID constants + source
5230
+ * - Dev mode: exports an empty manifest (Vite HMR handles CSS/JS).
5231
+ * - Build mode: virtual module reads from globalThis.__TIMBER_BUILD_MANIFEST__
5232
+ * at runtime. The actual manifest data is injected by the adapter via a
5233
+ * _timber-manifest-init.js module that runs before the RSC handler.
4534
5234
  *
4535
- * The public exports below are the stable API that the test suite and
4536
- * other parts of the framework import. Anything new should be added to
4537
- * one of the per-concern modules and re-exported here only if external
4538
- * consumers need it.
5235
+ * The generateBundle hook (client env only) extracts CSS/JS/modulepreload
5236
+ * data from the Rollup bundle and populates ctx.buildManifest.
4539
5237
  *
4540
- * Design doc: 24-fonts.md
5238
+ * Design docs: 18-build-system.md §"Build Manifest", 02-rendering-pipeline.md §"Early Hints"
4541
5239
  */
5240
+ var VIRTUAL_MODULE_ID = "virtual:timber-build-manifest";
5241
+ var RESOLVED_VIRTUAL_ID = `\0${VIRTUAL_MODULE_ID}`;
4542
5242
  /**
4543
- * Create the timber-fonts Vite plugin.
5243
+ * Build a BuildManifest from a Rollup output bundle.
5244
+ *
5245
+ * Unlike parseViteManifest (which reads Vite's manifest.json), this
5246
+ * works directly with the Rollup bundle output. This is necessary because
5247
+ * the RSC plugin doesn't produce a standard Vite manifest.json.
5248
+ *
5249
+ * Walks each chunk in the bundle and collects:
5250
+ * - `css`: CSS files imported by each chunk (via viteMetadata.importedCss)
5251
+ * - `js`: The output filename for each chunk with a facadeModuleId
5252
+ * - `modulepreload`: Transitive JS imports for each entry chunk
5253
+ *
5254
+ * Keys are input file paths relative to root.
4544
5255
  */
4545
- function timberFonts(ctx) {
4546
- const pipeline = new FontPipeline({ hashOnRegister: !ctx.dev });
4547
- /** Whether the client environment emitted a binary this build. */
4548
- let emittedToClient = false;
5256
+ function buildManifestFromBundle(bundle, base, root) {
5257
+ const css = {};
5258
+ const js = {};
5259
+ const modulepreload = {};
5260
+ const chunksByFileName = /* @__PURE__ */ new Map();
5261
+ for (const item of Object.values(bundle)) if (item.type === "chunk") chunksByFileName.set(item.fileName, item);
5262
+ for (const item of Object.values(bundle)) {
5263
+ if (item.type !== "chunk") continue;
5264
+ const chunk = item;
5265
+ if (!chunk.facadeModuleId) continue;
5266
+ let inputPath = chunk.facadeModuleId;
5267
+ if (inputPath.startsWith(root)) inputPath = inputPath.slice(root.length + 1);
5268
+ js[inputPath] = base + chunk.fileName;
5269
+ const viteMetadata = chunk.viteMetadata;
5270
+ if (viteMetadata?.importedCss && viteMetadata.importedCss.size > 0) css[inputPath] = Array.from(viteMetadata.importedCss).map((cssFile) => base + cssFile);
5271
+ const deps = collectTransitiveBundleDeps(chunk, chunksByFileName, base);
5272
+ if (deps.length > 0) modulepreload[inputPath] = deps;
5273
+ }
4549
5274
  return {
4550
- name: "timber-fonts",
4551
- api: {
4552
- contributeManifest: (manifest) => writeFontManifest(pipeline, manifest, ctx.base),
4553
- immutableDirs: () => emittedToClient ? [FONT_OUTPUT_DIR] : []
4554
- },
4555
- /**
4556
- * Push Vite's resolved `base` into the pipeline so every font URL it
4557
- * emits (@font-face src, manifest hrefs, dev middleware matching)
4558
- * carries the prefix. Emitted file locations are unaffected — only URLs.
4559
- *
4560
- * `config.base` is read here rather than `ctx.base`: this plugin is
4561
- * `enforce: 'pre'`, so its configResolved runs before timber-root-sync
4562
- * populates `ctx.base`. Every *later* hook reads `ctx.base` — the single
4563
- * copy (TIM-1261).
4564
- */
4565
- configResolved(config) {
4566
- pipeline.setBase(config.base);
4567
- const originalWarnOnce = config.logger.warnOnce.bind(config.logger);
4568
- config.logger.warnOnce = (msg, options) => {
4569
- if (msg.includes("_timber/fonts/") && msg.includes("didn't resolve at build time")) return;
4570
- originalWarnOnce(msg, options);
4571
- };
4572
- },
4573
- /**
4574
- * `enforce: 'pre'` is load-bearing for the font CSS pipeline (TIM-828).
4575
- *
4576
- * The transform hook injects a side-effect
4577
- * `import 'virtual:timber-font-css/<hash>.css'` into every file that
4578
- * registers a font. @vitejs/plugin-rsc's `rsc:rsc-css-export-transform`
4579
- * later inspects each server component's source for CSS imports and
4580
- * wraps the default export in `import.meta.viteRsc.loadCss(...)` so
4581
- * the matched virtual CSS module ends up `preinit`'d as
4582
- * `<link rel="stylesheet" data-rsc-css-href=...>`.
4583
- *
4584
- * If timber-fonts ran in normal order it would inject the CSS import
4585
- * *after* plugin-rsc had already scanned the source, and the font CSS
4586
- * would be silently dropped from the rendered HTML. Running in the
4587
- * `pre` slot guarantees our injected import is visible to plugin-rsc's
4588
- * later CSS-export scan.
4589
- */
4590
- enforce: "pre",
4591
- /**
4592
- * Resolve `@timber/fonts/google`, `@timber/fonts/local`, and the
4593
- * per-importer `virtual:timber-font-css/<hash>.css` modules injected
4594
- * by the transform hook.
4595
- *
4596
- * Strips the `\0` prefix added by the RSC plugin's re-imports and the
4597
- * absolute root prefix added by SSR build entries before comparing
4598
- * against the public IDs. The `.css` suffix on font-css ids is
4599
- * preserved so Vite's CSS pipeline (`isCSSRequest`) recognises the
4600
- * resolved id as CSS.
4601
- */
4602
- resolveId(id) {
4603
- let cleanId = id.startsWith("\0") ? id.slice(1) : id;
4604
- const qIdx = cleanId.indexOf("?");
4605
- const query = qIdx !== -1 ? cleanId.slice(qIdx) : "";
4606
- if (qIdx !== -1) cleanId = cleanId.slice(0, qIdx);
4607
- if (cleanId.startsWith(ctx.root)) {
4608
- const stripped = cleanId.slice(ctx.root.length);
4609
- if (stripped.startsWith("/") || stripped.startsWith("\\")) cleanId = stripped.slice(1);
4610
- else cleanId = stripped;
4611
- }
4612
- if (cleanId === "@timber/fonts/google") return RESOLVED_GOOGLE;
4613
- if (cleanId === "@timber/fonts/local") return RESOLVED_LOCAL;
4614
- if (pipeline.cssIdMap.matches(cleanId)) return "\0" + cleanId + query;
4615
- return null;
4616
- },
4617
- /**
5275
+ css,
5276
+ js,
5277
+ modulepreload,
5278
+ fonts: {},
5279
+ metadataRouteHashes: {}
5280
+ };
5281
+ }
5282
+ /**
5283
+ * Recursively collect transitive JS dependency URLs from a bundle chunk.
5284
+ */
5285
+ function collectTransitiveBundleDeps(chunk, chunksByFileName, base) {
5286
+ const seen = /* @__PURE__ */ new Set();
5287
+ const result = [];
5288
+ function walk(imports) {
5289
+ for (const importFileName of imports) {
5290
+ if (seen.has(importFileName)) continue;
5291
+ seen.add(importFileName);
5292
+ result.push(base + importFileName);
5293
+ const dep = chunksByFileName.get(importFileName);
5294
+ if (dep) walk(dep.imports);
5295
+ }
5296
+ }
5297
+ walk(chunk.imports);
5298
+ return result;
5299
+ }
5300
+ /**
5301
+ * Walk the route tree and compute short content hashes for metadata route
5302
+ * files, used to cache-bust the auto-linked opengraph-image URL in <head>.
5303
+ * A dynamic handler (.ts/.tsx) is hashed by its source: its output can depend
5304
+ * on runtime data too, but the source is the best build-time signal there is.
5305
+ * An unreadable file gets no hash, and the link falls back to the per-startup
5306
+ * nonce.
5307
+ */
5308
+ function computeMetadataRouteHashes(node) {
5309
+ const hashes = {};
5310
+ for (const file of Object.values(node.metadataRoutes ?? {})) try {
5311
+ const content = readFileSync(file.filePath);
5312
+ hashes[file.filePath] = createHash("sha256").update(content).digest("hex").slice(0, 8);
5313
+ } catch {}
5314
+ for (const child of node.children) Object.assign(hashes, computeMetadataRouteHashes(child));
5315
+ for (const slot of Object.values(node.slots)) Object.assign(hashes, computeMetadataRouteHashes(slot));
5316
+ return hashes;
5317
+ }
5318
+ var CLIENT_REF_KEY_RE = /registerClientReference\([^,]+,\s*"([0-9a-f]{12})"/g;
5319
+ /**
5320
+ * Collect all route file paths (layout, page) from the route tree.
5321
+ */
5322
+ function collectRouteFilePaths(node) {
5323
+ const paths = [];
5324
+ if (node.layout) paths.push(node.layout.filePath);
5325
+ if (node.page) paths.push(node.page.filePath);
5326
+ for (const child of node.children) paths.push(...collectRouteFilePaths(child));
5327
+ for (const slot of Object.values(node.slots)) paths.push(...collectRouteFilePaths(slot));
5328
+ return paths;
5329
+ }
5330
+ /**
5331
+ * Scan RSC bundle chunks to find which modules contain registerClientReference
5332
+ * calls, and extract the reference hash keys from each.
5333
+ */
5334
+ function buildClientRefIndex(bundle) {
5335
+ const index = /* @__PURE__ */ new Map();
5336
+ for (const item of Object.values(bundle)) {
5337
+ if (item.type !== "chunk" || !item.modules) continue;
5338
+ for (const [moduleId, mod] of Object.entries(item.modules)) {
5339
+ if (!mod.code) continue;
5340
+ const keys = [];
5341
+ for (const match of mod.code.matchAll(CLIENT_REF_KEY_RE)) keys.push(match[1]);
5342
+ if (keys.length > 0) index.set(moduleId, keys);
5343
+ }
5344
+ }
5345
+ return index;
5346
+ }
5347
+ /**
5348
+ * Walk a module's transitive imports to collect all client reference
5349
+ * keys reachable from it.
5350
+ */
5351
+ function walkModuleImports(moduleId, clientRefIndex, visited, result, getModuleInfo) {
5352
+ if (visited.has(moduleId)) return;
5353
+ visited.add(moduleId);
5354
+ const refKeys = clientRefIndex.get(moduleId);
5355
+ if (refKeys) for (const key of refKeys) result.add(key);
5356
+ const info = getModuleInfo(moduleId);
5357
+ if (!info) return;
5358
+ for (const importedId of info.importedIds) walkModuleImports(importedId, clientRefIndex, visited, result, getModuleInfo);
5359
+ }
5360
+ /**
5361
+ * Create the timber-build-manifest Vite plugin.
5362
+ *
5363
+ * Hooks: configResolved, resolveId, load, generateBundle (client and RSC envs)
5364
+ */
5365
+ function timberBuildManifest(ctx) {
5366
+ let isDev = false;
5367
+ return {
5368
+ name: "timber-build-manifest",
5369
+ configResolved(config) {
5370
+ isDev = config.command === "serve";
5371
+ if (!isDev && !ctx.deploymentId) ctx.deploymentId = randomUUID().replace(/-/g, "").slice(0, 16);
5372
+ },
5373
+ resolveId(id) {
5374
+ const cleanId = id.startsWith("\0") ? id.slice(1) : id;
5375
+ if (cleanId === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_ID;
5376
+ if (cleanId.endsWith(`/${VIRTUAL_MODULE_ID}`)) return RESOLVED_VIRTUAL_ID;
5377
+ return null;
5378
+ },
5379
+ load(id) {
5380
+ if (id !== RESOLVED_VIRTUAL_ID) return null;
5381
+ const empty = JSON.stringify(EMPTY_BUILD_MANIFEST);
5382
+ if (isDev) return [
5383
+ "// Auto-generated build manifest — do not edit.",
5384
+ "// Dev mode: empty manifest (Vite HMR handles CSS/JS).",
5385
+ "",
5386
+ `const manifest = ${empty};`,
5387
+ "",
5388
+ "export default manifest;"
5389
+ ].join("\n");
5390
+ return [
5391
+ "// Auto-generated build manifest — do not edit.",
5392
+ "// Production: reads manifest from globalThis (set by _timber-manifest-init.js).",
5393
+ "// The object below is only the fallback for when that global is unset —",
5394
+ "// the real manifest is in that init module.",
5395
+ "",
5396
+ `const manifest = globalThis.__TIMBER_BUILD_MANIFEST__ ?? ${empty};`,
5397
+ "",
5398
+ "export default manifest;"
5399
+ ].join("\n");
5400
+ },
5401
+ generateBundle(_options, bundle) {
5402
+ if (isDev) return;
5403
+ const envName = this.environment?.name;
5404
+ if (envName === "rsc" && ctx.routeTree) {
5405
+ const clientRefIndex = buildClientRefIndex(bundle);
5406
+ if (clientRefIndex.size > 0) {
5407
+ const routeFiles = collectRouteFilePaths(ctx.routeTree.root);
5408
+ const routeClientRefKeys = /* @__PURE__ */ new Map();
5409
+ const getInfo = (id) => this.getModuleInfo?.(id) ?? null;
5410
+ for (const filePath of routeFiles) {
5411
+ const refKeys = /* @__PURE__ */ new Set();
5412
+ walkModuleImports(filePath, clientRefIndex, /* @__PURE__ */ new Set(), refKeys, getInfo);
5413
+ if (refKeys.size > 0) routeClientRefKeys.set(filePath, refKeys);
5414
+ }
5415
+ if (routeClientRefKeys.size > 0) ctx.routeClientRefKeys = routeClientRefKeys;
5416
+ }
5417
+ }
5418
+ if (envName === "client") {
5419
+ ctx.buildManifest = buildManifestFromBundle(bundle, ctx.base, ctx.root);
5420
+ if (ctx.routeTree) ctx.buildManifest.metadataRouteHashes = computeMetadataRouteHashes(ctx.routeTree.root);
5421
+ if (ctx.clientJavascript.disabled) {
5422
+ for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk") delete bundle[fileName];
5423
+ }
5424
+ }
5425
+ }
5426
+ };
5427
+ }
5428
+ // src/plugins/fonts.ts
5429
+ /**
5430
+ * timber-fonts — Vite sub-plugin shell for build-time font processing.
5431
+ *
5432
+ * This file is intentionally thin: it wires the Vite plugin hooks to the
5433
+ * pipeline + per-concern modules under `../fonts/`. All real logic lives
5434
+ * in:
5435
+ *
5436
+ * - `../fonts/pipeline.ts` — `FontPipeline` (state, mutators)
5437
+ * - `../fonts/transform.ts` — transform-hook logic, parsing helpers
5438
+ * - `../fonts/dev-middleware.ts` — dev font binary server
5439
+ * - `../fonts/virtual-modules.ts` — virtual module ID constants + source
5440
+ *
5441
+ * The public exports below are the stable API that the test suite and
5442
+ * other parts of the framework import. Anything new should be added to
5443
+ * one of the per-concern modules and re-exported here only if external
5444
+ * consumers need it.
5445
+ *
5446
+ * Design doc: 24-fonts.md
5447
+ */
5448
+ /**
5449
+ * Create the timber-fonts Vite plugin.
5450
+ */
5451
+ function timberFonts(ctx) {
5452
+ const pipeline = new FontPipeline({ hashOnRegister: !ctx.dev });
5453
+ /** Whether the client environment emitted a binary this build. */
5454
+ let emittedToClient = false;
5455
+ /**
5456
+ * Font importer → the layouts/pages that reach it, from the RSC build's
5457
+ * module graph. Lets the manifest key a font defined in `app/fonts.ts`
5458
+ * under the layout that imports it.
5459
+ */
5460
+ let routesByImporter;
5461
+ return {
5462
+ name: "timber-fonts",
5463
+ api: {
5464
+ contributeManifest: (manifest) => writeFontManifest(pipeline, manifest, ctx.base, routesByImporter),
5465
+ immutableDirs: () => emittedToClient ? [FONT_OUTPUT_DIR] : []
5466
+ },
5467
+ /**
5468
+ * Push Vite's resolved `base` into the pipeline so every font URL it
5469
+ * emits (@font-face src, manifest hrefs, dev middleware matching)
5470
+ * carries the prefix. Emitted file locations are unaffected — only URLs.
5471
+ *
5472
+ * `config.base` is read here rather than `ctx.base`: this plugin is
5473
+ * `enforce: 'pre'`, so its configResolved runs before timber-root-sync
5474
+ * populates `ctx.base`. Every *later* hook reads `ctx.base` — the single
5475
+ * copy (TIM-1261).
5476
+ */
5477
+ configResolved(config) {
5478
+ pipeline.setBase(config.base);
5479
+ const originalWarnOnce = config.logger.warnOnce.bind(config.logger);
5480
+ config.logger.warnOnce = (msg, options) => {
5481
+ if (msg.includes("_timber/fonts/") && msg.includes("didn't resolve at build time")) return;
5482
+ originalWarnOnce(msg, options);
5483
+ };
5484
+ },
5485
+ /**
5486
+ * `enforce: 'pre'` is load-bearing for the font CSS pipeline (TIM-828).
5487
+ *
5488
+ * The transform hook injects a side-effect
5489
+ * `import 'virtual:timber-font-css/<hash>.css'` into every file that
5490
+ * registers a font. @vitejs/plugin-rsc's `rsc:rsc-css-export-transform`
5491
+ * later inspects each server component's source for CSS imports and
5492
+ * wraps the default export in `import.meta.viteRsc.loadCss(...)` so
5493
+ * the matched virtual CSS module ends up `preinit`'d as
5494
+ * `<link rel="stylesheet" data-rsc-css-href=...>`.
5495
+ *
5496
+ * If timber-fonts ran in normal order it would inject the CSS import
5497
+ * *after* plugin-rsc had already scanned the source, and the font CSS
5498
+ * would be silently dropped from the rendered HTML. Running in the
5499
+ * `pre` slot guarantees our injected import is visible to plugin-rsc's
5500
+ * later CSS-export scan.
5501
+ */
5502
+ enforce: "pre",
5503
+ /**
5504
+ * Resolve `@timber/fonts/google`, `@timber/fonts/local`, and the
5505
+ * per-importer `virtual:timber-font-css/<hash>.css` modules injected
5506
+ * by the transform hook.
5507
+ *
5508
+ * Strips the `\0` prefix added by the RSC plugin's re-imports and the
5509
+ * absolute root prefix added by SSR build entries before comparing
5510
+ * against the public IDs. The `.css` suffix on font-css ids is
5511
+ * preserved so Vite's CSS pipeline (`isCSSRequest`) recognises the
5512
+ * resolved id as CSS.
5513
+ */
5514
+ resolveId(id) {
5515
+ let cleanId = id.startsWith("\0") ? id.slice(1) : id;
5516
+ const qIdx = cleanId.indexOf("?");
5517
+ const query = qIdx !== -1 ? cleanId.slice(qIdx) : "";
5518
+ if (qIdx !== -1) cleanId = cleanId.slice(0, qIdx);
5519
+ if (cleanId.startsWith(ctx.root)) {
5520
+ const stripped = cleanId.slice(ctx.root.length);
5521
+ if (stripped.startsWith("/") || stripped.startsWith("\\")) cleanId = stripped.slice(1);
5522
+ else cleanId = stripped;
5523
+ }
5524
+ if (cleanId === "@timber/fonts/google") return RESOLVED_GOOGLE;
5525
+ if (cleanId === "@timber/fonts/local") return RESOLVED_LOCAL;
5526
+ if (pipeline.cssIdMap.matches(cleanId)) return "\0" + cleanId + query;
5527
+ return null;
5528
+ },
5529
+ /**
4618
5530
  * Return generated source for font virtual modules.
4619
5531
  *
4620
5532
  * The per-importer `virtual:timber-font-css/<hash>.css` modules
@@ -4745,6 +5657,210 @@ function timberFonts(ctx) {
4745
5657
  return this.emitFile(asset);
4746
5658
  }, (msg) => this.warn(msg));
4747
5659
  if (this.environment?.name === "client") emittedToClient = emitted > 0;
5660
+ if (this.environment?.name === "rsc" && ctx.routeTree) {
5661
+ const importers = /* @__PURE__ */ new Set();
5662
+ for (const font of pipeline.fonts()) importers.add(font.importer);
5663
+ routesByImporter = mapFontImportersToRoutes(importers, collectRouteFilePaths(ctx.routeTree.root), (id) => this.getModuleInfo(id)?.importers);
5664
+ }
5665
+ }
5666
+ };
5667
+ }
5668
+ // src/plugins/route-css.ts
5669
+ /**
5670
+ * timber-route-css — link font CSS that a route file reaches only through
5671
+ * a plain (non-component) module.
5672
+ *
5673
+ * @vitejs/plugin-rsc renders a server component's stylesheets by wrapping
5674
+ * the component in `import.meta.viteRsc.loadCss()`, which collects every
5675
+ * CSS file the module reaches, directly or through other modules. But it
5676
+ * only applies that wrap to a module that imports CSS **itself**
5677
+ * (`rsc:rsc-css-export-transform`). A font is usually defined in a plain
5678
+ * module, and the font's CSS import is injected there:
5679
+ *
5680
+ * ```ts
5681
+ * // app/fonts.ts — the font's @font-face CSS is imported here
5682
+ * export const body = localFont({ src: './TX-02.woff2' });
5683
+ *
5684
+ * // app/layout.tsx — imports no CSS of its own, so nothing is wrapped
5685
+ * import { body } from './fonts';
5686
+ * ```
5687
+ *
5688
+ * The page rendered with the font's class and no `@font-face`.
5689
+ *
5690
+ * This plugin gives such a route file a static import of an empty
5691
+ * stylesheet, so plugin-rsc wraps it exactly as it wraps a layout that
5692
+ * imports `globals.css`, and `loadCss()` collects the font CSS. The anchor
5693
+ * is imported with `?inline`: plugin-rsc's wrap check counts it as a CSS
5694
+ * import, while its collector skips `?inline` ids (no `<link>` in dev) and
5695
+ * the build compiles it to a JS string (no asset).
5696
+ *
5697
+ * **Only route files that reach a font module are touched.** The wrap is
5698
+ * not free: in dev it renders an async `Resources` component beside the
5699
+ * route component, which shifts shell timing (a delayed `deny()` can land
5700
+ * before the shell commits). Wrapping every route file changed dev status
5701
+ * codes in apps with no fonts at all. Route files that import CSS are
5702
+ * wrapped by plugin-rsc already; this adds only the font case.
5703
+ *
5704
+ * A route file is transformed before its imports, so the font pipeline
5705
+ * can't answer "does this reach a font?" yet. The plugin scans source
5706
+ * instead: it follows the route file's static imports through local,
5707
+ * server-side modules (not node_modules, not `'use client'` — a client
5708
+ * module's CSS rides its client reference) and stops at the first module
5709
+ * that imports a font loader. Scans are cached per file by mtime.
5710
+ *
5711
+ * Not touched: `'use client'` route files (a statement before the directive
5712
+ * would cancel it), MDX (frontmatter must stay on line 1), and route.ts /
5713
+ * middleware.ts / access.ts / metadata routes (not components).
5714
+ *
5715
+ * Known limit (dev): adding the first font call to a module a route file
5716
+ * already imports takes effect when the route file is next transformed
5717
+ * (edit or restart), because the route file's own source did not change.
5718
+ *
5719
+ * Design doc: 24-fonts.md §"Step 3: @font-face Generation"
5720
+ */
5721
+ var ANCHOR_ID = "virtual:timber-route-css.css";
5722
+ var RESOLVED_ANCHOR_ID = "\0" + ANCHOR_ID;
5723
+ /** The import the transform adds. See the module comment for `?inline`. */
5724
+ var ROUTE_CSS_ANCHOR_IMPORT = `import '${ANCHOR_ID}?inline';\n`;
5725
+ var SCRIPT_RE$1 = /\.[cm]?[jt]sx?$/;
5726
+ /** Module specifiers that make a module a font module (same as the fonts transform). */
5727
+ var FONT_SPECIFIER_PREFIXES = [
5728
+ "@timber/fonts/",
5729
+ "@timber-js/app/fonts/",
5730
+ "next/font/"
5731
+ ];
5732
+ var isFontSpecifier = (spec) => FONT_SPECIFIER_PREFIXES.some((p) => spec.startsWith(p));
5733
+ /** True when an import/export node carries TS's `type` modifier (not in ESTree). */
5734
+ function isTypeOnly(node, key) {
5735
+ return key in node && Reflect.get(node, key) === "type";
5736
+ }
5737
+ /** Static value import/re-export specifiers of a module. */
5738
+ function staticSpecifiers(code, filename) {
5739
+ const ext = filename.slice(filename.lastIndexOf(".") + 1);
5740
+ const lang = ext.includes("ts") ? ext.endsWith("x") ? "tsx" : "ts" : ext.endsWith("x") ? "jsx" : "js";
5741
+ let program;
5742
+ try {
5743
+ program = parseAst(code, { lang });
5744
+ } catch {
5745
+ return [];
5746
+ }
5747
+ const specs = [];
5748
+ for (const node of program.body) if (node.type === "ImportDeclaration") {
5749
+ if (!isTypeOnly(node, "importKind") && typeof node.source.value === "string") specs.push(node.source.value);
5750
+ } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
5751
+ if (!isTypeOnly(node, "exportKind") && typeof node.source?.value === "string") specs.push(node.source.value);
5752
+ }
5753
+ return specs;
5754
+ }
5755
+ /** Every route file that exports a server component plugin-rsc may wrap. */
5756
+ function collectComponentRouteFiles(node, into = /* @__PURE__ */ new Set()) {
5757
+ for (const file of [
5758
+ node.page,
5759
+ node.layout,
5760
+ node.default,
5761
+ node.denied,
5762
+ node.error
5763
+ ]) if (file) into.add(file.filePath);
5764
+ for (const file of Object.values(node.statusFiles ?? {})) into.add(file.filePath);
5765
+ for (const child of node.children) collectComponentRouteFiles(child, into);
5766
+ for (const slot of Object.values(node.slots)) collectComponentRouteFiles(slot, into);
5767
+ return into;
5768
+ }
5769
+ function timberRouteCss(ctx) {
5770
+ const scans = /* @__PURE__ */ new Map();
5771
+ const scan = (id, code) => {
5772
+ let stat;
5773
+ try {
5774
+ stat = statSync(id);
5775
+ } catch {
5776
+ return null;
5777
+ }
5778
+ const cached = scans.get(id);
5779
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached;
5780
+ const source = code ?? readFileSync(id, "utf8");
5781
+ const specifiers = staticSpecifiers(source, id);
5782
+ const result = {
5783
+ mtimeMs: stat.mtimeMs,
5784
+ size: stat.size,
5785
+ definesFont: specifiers.some(isFontSpecifier),
5786
+ directive: detectDirective(source, id) !== null,
5787
+ specifiers
5788
+ };
5789
+ scans.set(id, result);
5790
+ return result;
5791
+ };
5792
+ let tree = null;
5793
+ let routeFiles = /* @__PURE__ */ new Set();
5794
+ const isRouteFile = (id) => {
5795
+ if (ctx.routeTree !== tree) {
5796
+ tree = ctx.routeTree;
5797
+ routeFiles = tree ? collectComponentRouteFiles(tree.root) : /* @__PURE__ */ new Set();
5798
+ }
5799
+ return routeFiles.has(id);
5800
+ };
5801
+ return {
5802
+ name: "timber-route-css",
5803
+ enforce: "pre",
5804
+ resolveId: {
5805
+ filter: { id: /virtual:timber-route-css\.css/ },
5806
+ handler(id) {
5807
+ const bare = id.startsWith("\0") ? id.slice(1) : id;
5808
+ if (!bare.startsWith(ANCHOR_ID)) return null;
5809
+ return RESOLVED_ANCHOR_ID + bare.slice(28);
5810
+ }
5811
+ },
5812
+ load: {
5813
+ filter: { id: /virtual:timber-route-css\.css/ },
5814
+ handler(id) {
5815
+ return id.startsWith(RESOLVED_ANCHOR_ID) ? "" : null;
5816
+ }
5817
+ },
5818
+ transform: {
5819
+ filter: { id: {
5820
+ include: SCRIPT_RE$1,
5821
+ exclude: /(?:^\0|[?&]|\/node_modules\/)/
5822
+ } },
5823
+ async handler(code, id) {
5824
+ if (this.environment.name !== "rsc") return null;
5825
+ if (!isRouteFile(id) || detectDirective(code, id) !== null) return null;
5826
+ const self = scan(id, code);
5827
+ if (!self || self.definesFont) return null;
5828
+ let reachesFont = false;
5829
+ const visited = /* @__PURE__ */ new Set([id]);
5830
+ const queue = [{
5831
+ importer: id,
5832
+ specifiers: self.specifiers
5833
+ }];
5834
+ for (let item = queue.shift(); item && !reachesFont; item = queue.shift()) {
5835
+ const { importer, specifiers } = item;
5836
+ for (const spec of specifiers) {
5837
+ if (isFontSpecifier(spec)) continue;
5838
+ const resolved = await this.resolve(spec, importer);
5839
+ if (!resolved || resolved.external) continue;
5840
+ const next = resolved.id;
5841
+ if (visited.has(next) || next.startsWith("\0") || next.includes("/node_modules/")) continue;
5842
+ visited.add(next);
5843
+ if (!SCRIPT_RE$1.test(next)) continue;
5844
+ const info = scan(next);
5845
+ if (!info || info.directive) continue;
5846
+ if (info.definesFont) {
5847
+ reachesFont = true;
5848
+ break;
5849
+ }
5850
+ queue.push({
5851
+ importer: next,
5852
+ specifiers: info.specifiers
5853
+ });
5854
+ }
5855
+ }
5856
+ if (!reachesFont) return null;
5857
+ const s = new MagicString(code);
5858
+ s.prepend(ROUTE_CSS_ANCHOR_IMPORT);
5859
+ return {
5860
+ code: s.toString(),
5861
+ map: s.generateMap({ hires: "boundary" })
5862
+ };
5863
+ }
4748
5864
  }
4749
5865
  };
4750
5866
  }
@@ -5250,212 +6366,6 @@ function timberStaticBuild(ctx) {
5250
6366
  }
5251
6367
  };
5252
6368
  }
5253
- // src/plugins/build-manifest.ts
5254
- /**
5255
- * timber-build-manifest — Vite sub-plugin for build asset manifest generation.
5256
- *
5257
- * Provides `virtual:timber-build-manifest` which exports a BuildManifest
5258
- * mapping route segment file paths to their CSS, JS, and modulepreload
5259
- * output chunks.
5260
- *
5261
- * - Dev mode: exports an empty manifest (Vite HMR handles CSS/JS).
5262
- * - Build mode: virtual module reads from globalThis.__TIMBER_BUILD_MANIFEST__
5263
- * at runtime. The actual manifest data is injected by the adapter via a
5264
- * _timber-manifest-init.js module that runs before the RSC handler.
5265
- *
5266
- * The generateBundle hook (client env only) extracts CSS/JS/modulepreload
5267
- * data from the Rollup bundle and populates ctx.buildManifest.
5268
- *
5269
- * Design docs: 18-build-system.md §"Build Manifest", 02-rendering-pipeline.md §"Early Hints"
5270
- */
5271
- var VIRTUAL_MODULE_ID = "virtual:timber-build-manifest";
5272
- var RESOLVED_VIRTUAL_ID = `\0${VIRTUAL_MODULE_ID}`;
5273
- /**
5274
- * Build a BuildManifest from a Rollup output bundle.
5275
- *
5276
- * Unlike parseViteManifest (which reads Vite's manifest.json), this
5277
- * works directly with the Rollup bundle output. This is necessary because
5278
- * the RSC plugin doesn't produce a standard Vite manifest.json.
5279
- *
5280
- * Walks each chunk in the bundle and collects:
5281
- * - `css`: CSS files imported by each chunk (via viteMetadata.importedCss)
5282
- * - `js`: The output filename for each chunk with a facadeModuleId
5283
- * - `modulepreload`: Transitive JS imports for each entry chunk
5284
- *
5285
- * Keys are input file paths relative to root.
5286
- */
5287
- function buildManifestFromBundle(bundle, base, root) {
5288
- const css = {};
5289
- const js = {};
5290
- const modulepreload = {};
5291
- const chunksByFileName = /* @__PURE__ */ new Map();
5292
- for (const item of Object.values(bundle)) if (item.type === "chunk") chunksByFileName.set(item.fileName, item);
5293
- for (const item of Object.values(bundle)) {
5294
- if (item.type !== "chunk") continue;
5295
- const chunk = item;
5296
- if (!chunk.facadeModuleId) continue;
5297
- let inputPath = chunk.facadeModuleId;
5298
- if (inputPath.startsWith(root)) inputPath = inputPath.slice(root.length + 1);
5299
- js[inputPath] = base + chunk.fileName;
5300
- const viteMetadata = chunk.viteMetadata;
5301
- if (viteMetadata?.importedCss && viteMetadata.importedCss.size > 0) css[inputPath] = Array.from(viteMetadata.importedCss).map((cssFile) => base + cssFile);
5302
- const deps = collectTransitiveBundleDeps(chunk, chunksByFileName, base);
5303
- if (deps.length > 0) modulepreload[inputPath] = deps;
5304
- }
5305
- return {
5306
- css,
5307
- js,
5308
- modulepreload,
5309
- fonts: {},
5310
- metadataRouteHashes: {}
5311
- };
5312
- }
5313
- /**
5314
- * Recursively collect transitive JS dependency URLs from a bundle chunk.
5315
- */
5316
- function collectTransitiveBundleDeps(chunk, chunksByFileName, base) {
5317
- const seen = /* @__PURE__ */ new Set();
5318
- const result = [];
5319
- function walk(imports) {
5320
- for (const importFileName of imports) {
5321
- if (seen.has(importFileName)) continue;
5322
- seen.add(importFileName);
5323
- result.push(base + importFileName);
5324
- const dep = chunksByFileName.get(importFileName);
5325
- if (dep) walk(dep.imports);
5326
- }
5327
- }
5328
- walk(chunk.imports);
5329
- return result;
5330
- }
5331
- /**
5332
- * Walk the route tree and compute short content hashes for metadata route
5333
- * files, used to cache-bust the auto-linked opengraph-image URL in <head>.
5334
- * A dynamic handler (.ts/.tsx) is hashed by its source: its output can depend
5335
- * on runtime data too, but the source is the best build-time signal there is.
5336
- * An unreadable file gets no hash, and the link falls back to the per-startup
5337
- * nonce.
5338
- */
5339
- function computeMetadataRouteHashes(node) {
5340
- const hashes = {};
5341
- for (const file of Object.values(node.metadataRoutes ?? {})) try {
5342
- const content = readFileSync(file.filePath);
5343
- hashes[file.filePath] = createHash("sha256").update(content).digest("hex").slice(0, 8);
5344
- } catch {}
5345
- for (const child of node.children) Object.assign(hashes, computeMetadataRouteHashes(child));
5346
- for (const slot of Object.values(node.slots)) Object.assign(hashes, computeMetadataRouteHashes(slot));
5347
- return hashes;
5348
- }
5349
- var CLIENT_REF_KEY_RE = /registerClientReference\([^,]+,\s*"([0-9a-f]{12})"/g;
5350
- /**
5351
- * Collect all route file paths (layout, page) from the route tree.
5352
- */
5353
- function collectRouteFilePaths(node) {
5354
- const paths = [];
5355
- if (node.layout) paths.push(node.layout.filePath);
5356
- if (node.page) paths.push(node.page.filePath);
5357
- for (const child of node.children) paths.push(...collectRouteFilePaths(child));
5358
- for (const slot of Object.values(node.slots)) paths.push(...collectRouteFilePaths(slot));
5359
- return paths;
5360
- }
5361
- /**
5362
- * Scan RSC bundle chunks to find which modules contain registerClientReference
5363
- * calls, and extract the reference hash keys from each.
5364
- */
5365
- function buildClientRefIndex(bundle) {
5366
- const index = /* @__PURE__ */ new Map();
5367
- for (const item of Object.values(bundle)) {
5368
- if (item.type !== "chunk" || !item.modules) continue;
5369
- for (const [moduleId, mod] of Object.entries(item.modules)) {
5370
- if (!mod.code) continue;
5371
- const keys = [];
5372
- for (const match of mod.code.matchAll(CLIENT_REF_KEY_RE)) keys.push(match[1]);
5373
- if (keys.length > 0) index.set(moduleId, keys);
5374
- }
5375
- }
5376
- return index;
5377
- }
5378
- /**
5379
- * Walk a module's transitive imports to collect all client reference
5380
- * keys reachable from it.
5381
- */
5382
- function walkModuleImports(moduleId, clientRefIndex, visited, result, getModuleInfo) {
5383
- if (visited.has(moduleId)) return;
5384
- visited.add(moduleId);
5385
- const refKeys = clientRefIndex.get(moduleId);
5386
- if (refKeys) for (const key of refKeys) result.add(key);
5387
- const info = getModuleInfo(moduleId);
5388
- if (!info) return;
5389
- for (const importedId of info.importedIds) walkModuleImports(importedId, clientRefIndex, visited, result, getModuleInfo);
5390
- }
5391
- /**
5392
- * Create the timber-build-manifest Vite plugin.
5393
- *
5394
- * Hooks: configResolved, resolveId, load, generateBundle (client and RSC envs)
5395
- */
5396
- function timberBuildManifest(ctx) {
5397
- let isDev = false;
5398
- return {
5399
- name: "timber-build-manifest",
5400
- configResolved(config) {
5401
- isDev = config.command === "serve";
5402
- if (!isDev && !ctx.deploymentId) ctx.deploymentId = randomUUID().replace(/-/g, "").slice(0, 16);
5403
- },
5404
- resolveId(id) {
5405
- const cleanId = id.startsWith("\0") ? id.slice(1) : id;
5406
- if (cleanId === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_ID;
5407
- if (cleanId.endsWith(`/${VIRTUAL_MODULE_ID}`)) return RESOLVED_VIRTUAL_ID;
5408
- return null;
5409
- },
5410
- load(id) {
5411
- if (id !== RESOLVED_VIRTUAL_ID) return null;
5412
- const empty = JSON.stringify(EMPTY_BUILD_MANIFEST);
5413
- if (isDev) return [
5414
- "// Auto-generated build manifest — do not edit.",
5415
- "// Dev mode: empty manifest (Vite HMR handles CSS/JS).",
5416
- "",
5417
- `const manifest = ${empty};`,
5418
- "",
5419
- "export default manifest;"
5420
- ].join("\n");
5421
- return [
5422
- "// Auto-generated build manifest — do not edit.",
5423
- "// Production: reads manifest from globalThis (set by _timber-manifest-init.js).",
5424
- "// The object below is only the fallback for when that global is unset —",
5425
- "// the real manifest is in that init module.",
5426
- "",
5427
- `const manifest = globalThis.__TIMBER_BUILD_MANIFEST__ ?? ${empty};`,
5428
- "",
5429
- "export default manifest;"
5430
- ].join("\n");
5431
- },
5432
- generateBundle(_options, bundle) {
5433
- if (isDev) return;
5434
- const envName = this.environment?.name;
5435
- if (envName === "rsc" && ctx.routeTree) {
5436
- const clientRefIndex = buildClientRefIndex(bundle);
5437
- if (clientRefIndex.size > 0) {
5438
- const routeFiles = collectRouteFilePaths(ctx.routeTree.root);
5439
- const routeClientRefKeys = /* @__PURE__ */ new Map();
5440
- const getInfo = (id) => this.getModuleInfo?.(id) ?? null;
5441
- for (const filePath of routeFiles) {
5442
- const refKeys = /* @__PURE__ */ new Set();
5443
- walkModuleImports(filePath, clientRefIndex, /* @__PURE__ */ new Set(), refKeys, getInfo);
5444
- if (refKeys.size > 0) routeClientRefKeys.set(filePath, refKeys);
5445
- }
5446
- if (routeClientRefKeys.size > 0) ctx.routeClientRefKeys = routeClientRefKeys;
5447
- }
5448
- }
5449
- if (envName === "client") {
5450
- ctx.buildManifest = buildManifestFromBundle(bundle, ctx.base, ctx.root);
5451
- if (ctx.routeTree) ctx.buildManifest.metadataRouteHashes = computeMetadataRouteHashes(ctx.routeTree.root);
5452
- if (ctx.clientJavascript.disabled) {
5453
- for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk") delete bundle[fileName];
5454
- }
5455
- }
5456
- }
5457
- };
5458
- }
5459
6369
  // src/dev-tools/span-sink.ts
5460
6370
  /**
5461
6371
  * Span sink — streams finished dev spans to the browser over HMR, for the
@@ -10418,6 +11328,7 @@ function timber(config) {
10418
11328
  timberEntries(ctx),
10419
11329
  timberBuildManifest(ctx),
10420
11330
  fonts,
11331
+ timberRouteCss(ctx),
10421
11332
  timberMdx(ctx),
10422
11333
  timberOptimizePackageImports(ctx),
10423
11334
  timberClientInServerPackageDeps(),