@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
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Minimal font-container reader: TrueType/OpenType (sfnt), WOFF and WOFF2.
3
+ *
4
+ * Returns the raw bytes of the requested tables so `font-metrics.ts` can
5
+ * read the handful of fields the fallback generator needs. This is
6
+ * deliberately not a font parser — it only undoes the container:
7
+ *
8
+ * - sfnt (`\0\1\0\0`, `true`, `OTTO`): tables are stored as-is.
9
+ * - WOFF (`wOFF`): each table is zlib-compressed independently.
10
+ * - WOFF2 (`wOF2`): all tables are concatenated into one Brotli stream.
11
+ * WOFF2 may *transform* `glyf`, `loca` and `hmtx`; a transformed table is
12
+ * not in sfnt layout, so it is reported as missing rather than misread.
13
+ * `head`, `hhea`, `OS/2`, `post` and `cmap` are never transformed.
14
+ *
15
+ * Both decompressors come from `node:zlib`, so no dependency is needed.
16
+ * Font collections (`ttcf`) are not supported — they are not web fonts.
17
+ *
18
+ * Every read is bounds-checked: a truncated or non-font file yields `null`,
19
+ * never a throw, because the caller's fallback is simply "no metrics".
20
+ *
21
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
22
+ */
23
+
24
+ import { brotliDecompressSync, inflateSync } from 'node:zlib';
25
+
26
+ /** Table tag → that table's uncompressed bytes. */
27
+ export type SfntTables = Map<string, DataView>;
28
+
29
+ const SFNT_TRUETYPE = 0x00010000;
30
+ const SFNT_TRUE = 0x74727565; // 'true'
31
+ const SFNT_OTTO = 0x4f54544f; // 'OTTO'
32
+ const WOFF = 0x774f4646; // 'wOFF'
33
+ const WOFF2 = 0x774f4632; // 'wOF2'
34
+
35
+ /** WOFF2 §5.1 known-table index (flags & 0x3f). */
36
+ const WOFF2_KNOWN_TAGS = [
37
+ 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf',
38
+ 'loca', 'prep', 'CFF ', 'VORG', 'EBDT', 'EBLC', 'gasp', 'hdmx', 'kern', 'LTSH', 'PCLT',
39
+ 'VDMX', 'vhea', 'vmtx', 'BASE', 'GDEF', 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH', 'CBDT',
40
+ 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar',
41
+ 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar', 'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd',
42
+ 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill',
43
+ ]; // prettier-ignore
44
+
45
+ function tagAt(view: DataView, offset: number): string {
46
+ return String.fromCharCode(
47
+ view.getUint8(offset),
48
+ view.getUint8(offset + 1),
49
+ view.getUint8(offset + 2),
50
+ view.getUint8(offset + 3)
51
+ );
52
+ }
53
+
54
+ function slice(bytes: Uint8Array, offset: number, length: number): DataView | null {
55
+ if (offset < 0 || length < 0 || offset + length > bytes.byteLength) return null;
56
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, length);
57
+ }
58
+
59
+ /**
60
+ * Read the requested tables out of a font file. Returns `null` when the
61
+ * bytes are not a supported font container or are truncated.
62
+ */
63
+ export function readSfntTables(data: Uint8Array, wanted: readonly string[]): SfntTables | null {
64
+ try {
65
+ if (data.byteLength < 12) return null;
66
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
67
+ const signature = view.getUint32(0);
68
+ const want = new Set(wanted);
69
+ switch (signature) {
70
+ case SFNT_TRUETYPE:
71
+ case SFNT_TRUE:
72
+ case SFNT_OTTO:
73
+ return readSfnt(data, view, want);
74
+ case WOFF:
75
+ return readWoff(data, view, want);
76
+ case WOFF2:
77
+ return readWoff2(data, view, want);
78
+ default:
79
+ return null;
80
+ }
81
+ } catch {
82
+ // RangeError from a DataView read past a lying length field, or a
83
+ // zlib error from corrupt compressed data. Both mean "not readable".
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function readSfnt(data: Uint8Array, view: DataView, want: Set<string>): SfntTables | null {
89
+ const numTables = view.getUint16(4);
90
+ const tables: SfntTables = new Map();
91
+ for (let i = 0; i < numTables; i++) {
92
+ const rec = 12 + i * 16;
93
+ const tag = tagAt(view, rec);
94
+ if (!want.has(tag)) continue;
95
+ const table = slice(data, view.getUint32(rec + 8), view.getUint32(rec + 12));
96
+ if (!table) return null;
97
+ tables.set(tag, table);
98
+ }
99
+ return tables;
100
+ }
101
+
102
+ function readWoff(data: Uint8Array, view: DataView, want: Set<string>): SfntTables | null {
103
+ const numTables = view.getUint16(12);
104
+ const tables: SfntTables = new Map();
105
+ for (let i = 0; i < numTables; i++) {
106
+ const rec = 44 + i * 20;
107
+ const tag = tagAt(view, rec);
108
+ if (!want.has(tag)) continue;
109
+ const offset = view.getUint32(rec + 4);
110
+ const compLength = view.getUint32(rec + 8);
111
+ const origLength = view.getUint32(rec + 12);
112
+ const stored = slice(data, offset, compLength);
113
+ if (!stored) return null;
114
+ if (compLength === origLength) {
115
+ tables.set(tag, stored);
116
+ continue;
117
+ }
118
+ const raw = inflateSync(new Uint8Array(stored.buffer, stored.byteOffset, compLength));
119
+ tables.set(tag, new DataView(raw.buffer, raw.byteOffset, raw.byteLength));
120
+ }
121
+ return tables;
122
+ }
123
+
124
+ /** WOFF2 UIntBase128: big-endian base-128, at most 5 bytes. */
125
+ function readBase128(view: DataView, cursor: { pos: number }): number {
126
+ let value = 0;
127
+ for (let i = 0; i < 5; i++) {
128
+ const byte = view.getUint8(cursor.pos++);
129
+ // A leading 0x80 byte is a non-canonical encoding — reject it.
130
+ if (i === 0 && byte === 0x80) throw new RangeError('bad UIntBase128');
131
+ value = value * 128 + (byte & 0x7f);
132
+ if ((byte & 0x80) === 0) return value;
133
+ }
134
+ throw new RangeError('UIntBase128 too long');
135
+ }
136
+
137
+ function readWoff2(data: Uint8Array, view: DataView, want: Set<string>): SfntTables | null {
138
+ const flavor = view.getUint32(4);
139
+ if (flavor === 0x74746366 /* 'ttcf' */) return null;
140
+ const numTables = view.getUint16(12);
141
+ const totalCompressedSize = view.getUint32(20);
142
+
143
+ // Table directory (§5): flags, optional tag, origLength, optional
144
+ // transformLength. Tables appear in the decompressed stream in directory
145
+ // order, back to back with no padding.
146
+ const cursor = { pos: 48 };
147
+ const entries: { tag: string; offset: number; length: number; transformed: boolean }[] = [];
148
+ let streamOffset = 0;
149
+ for (let i = 0; i < numTables; i++) {
150
+ const flags = view.getUint8(cursor.pos++);
151
+ const knownIndex = flags & 0x3f;
152
+ let tag: string;
153
+ if (knownIndex === 0x3f) {
154
+ tag = tagAt(view, cursor.pos);
155
+ cursor.pos += 4;
156
+ } else {
157
+ tag = WOFF2_KNOWN_TAGS[knownIndex];
158
+ if (!tag) return null;
159
+ }
160
+ const transformVersion = (flags >> 6) & 0x03;
161
+ const origLength = readBase128(view, cursor);
162
+ // glyf/loca: version 0 *is* the transform, 3 is null. Everything else:
163
+ // version 0 is null, anything else is a transform.
164
+ const transformed =
165
+ tag === 'glyf' || tag === 'loca' ? transformVersion !== 3 : transformVersion !== 0;
166
+ const length = transformed ? readBase128(view, cursor) : origLength;
167
+ entries.push({ tag, offset: streamOffset, length, transformed });
168
+ streamOffset += length;
169
+ }
170
+
171
+ const compressed = slice(data, cursor.pos, totalCompressedSize);
172
+ if (!compressed) return null;
173
+ const stream = brotliDecompressSync(
174
+ new Uint8Array(compressed.buffer, compressed.byteOffset, totalCompressedSize)
175
+ );
176
+
177
+ const tables: SfntTables = new Map();
178
+ for (const entry of entries) {
179
+ if (!want.has(entry.tag) || entry.transformed) continue;
180
+ const table = slice(stream, entry.offset, entry.length);
181
+ if (!table) return null;
182
+ tables.set(entry.tag, table);
183
+ }
184
+ return tables;
185
+ }
@@ -250,6 +250,7 @@ export function runFontsTransform(
250
250
  className,
251
251
  fontFamily: fontStack,
252
252
  importer: id,
253
+ preload: config!.preload ?? true,
253
254
  },
254
255
  });
255
256
  } else {
@@ -259,7 +260,9 @@ export function runFontsTransform(
259
260
  emitError(
260
261
  `Could not statically analyze local font config ` +
261
262
  `at line ${site.line}, column ${site.column}. ` +
262
- `Ensure src is a string or array of { path, weight?, style? } objects.`
263
+ `Ensure src is a string or array of { path, weight?, style? } objects, ` +
264
+ `preload is a boolean, adjustFontFallback is a boolean or ` +
265
+ `'Arial' | 'Times New Roman' | 'monospace', and fallback is an array of strings.`
263
266
  );
264
267
  }
265
268
 
@@ -10,6 +10,8 @@
10
10
  // `CachedFont` lives in `google.ts`. Importing it here is type-only so
11
11
  // there is no runtime dependency cycle — TypeScript erases the import.
12
12
  import type { CachedFont } from './google.ts';
13
+ import type { FallbackFace } from './fallbacks.ts';
14
+ import type { AdjustFontFallback } from './local-fallback.ts';
13
15
 
14
16
  /** Configuration passed to a Google font function (e.g. `Inter({ ... })`). */
15
17
  export interface GoogleFontConfig {
@@ -37,6 +39,25 @@ export interface LocalFontConfig {
37
39
  variable?: string;
38
40
  /** Override the font family name. Defaults to a generated name. */
39
41
  family?: string;
42
+ /**
43
+ * Preload the font's upright (`font-style: normal`) files on every route
44
+ * whose layout or page imports it, directly or through another module.
45
+ * Defaults to `true`.
46
+ */
47
+ preload?: boolean;
48
+ /**
49
+ * Size-adjusted fallback, as in `next/font/local`. `true` (the default)
50
+ * measures the font file and picks the base from its metrics; `false`
51
+ * emits no `'<Family> Fallback'` face; a font name forces that base (and
52
+ * its generic family): `'Arial'` → sans-serif, `'Times New Roman'` →
53
+ * serif, `'monospace'` → a list of ~0.600em monospace system fonts.
54
+ */
55
+ adjustFontFallback?: AdjustFontFallback;
56
+ /**
57
+ * Font families after `'<Family> Fallback'` in the stack, replacing the
58
+ * default generic tail (e.g. `['ui-monospace', 'monospace']`).
59
+ */
60
+ fallback?: string[];
40
61
  }
41
62
 
42
63
  /**
@@ -88,6 +109,14 @@ export interface ExtractedFont {
88
109
  className: string;
89
110
  /** Full font stack including fallback. */
90
111
  fontFamily: string;
112
+ /**
113
+ * Size-adjusted fallback faces measured from a local font's files.
114
+ * Google fonts leave this unset — their faces come from the precomputed
115
+ * table in `fallbacks.ts`, keyed by family.
116
+ */
117
+ fallbackFaces?: FallbackFace[];
118
+ /** Whether the font's files are preloaded. Defaults to `true`. */
119
+ preload?: boolean;
91
120
  }
92
121
 
93
122
  /**
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ import { timberMdx } from './plugins/mdx.ts';
22
22
  import { timberRouting } from './plugins/routing.ts';
23
23
  import { timberShims } from './plugins/shims.ts';
24
24
  import { timberFonts } from './plugins/fonts.ts';
25
+ import { timberRouteCss } from './plugins/route-css.ts';
25
26
  import { timberStaticBuild } from './plugins/static-build.ts';
26
27
  import { timberBuildManifest } from './plugins/build-manifest.ts';
27
28
  import { timberDevLogs, originalConsole, wrapLoggerWithOriginalConsole } from './dev-tools/logs.ts';
@@ -589,6 +590,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
589
590
  timberEntries(ctx),
590
591
  timberBuildManifest(ctx),
591
592
  fonts,
593
+ timberRouteCss(ctx), // Route files collect transitive CSS (font CSS from app/fonts.ts)
592
594
  timberMdx(ctx),
593
595
  timberOptimizePackageImports(ctx), // Listed barrels → the modules that define the imported names
594
596
  timberClientInServerPackageDeps(), // Dev: a package's inner 'use client' file → its bare path, so the browser pre-bundles it
@@ -252,7 +252,7 @@ const CLIENT_REF_KEY_RE = /registerClientReference\([^,]+,\s*"([0-9a-f]{12})"/g;
252
252
  /**
253
253
  * Collect all route file paths (layout, page) from the route tree.
254
254
  */
255
- function collectRouteFilePaths(node: SegmentNode<RouteFile>): string[] {
255
+ export function collectRouteFilePaths(node: SegmentNode<RouteFile>): string[] {
256
256
  const paths: string[] = [];
257
257
  if (node.layout) paths.push(node.layout.filePath);
258
258
  if (node.page) paths.push(node.page.filePath);
@@ -31,7 +31,13 @@ import { FONT_OUTPUT_DIR, fontUrlPrefix } from '../fonts/paths.ts';
31
31
  import { FontPipeline } from '../fonts/pipeline.ts';
32
32
  import { runFontsTransform } from '../fonts/transform.ts';
33
33
  import { installFontDevMiddleware } from '../fonts/dev-middleware.ts';
34
- import { emitFontAssets, writeFontManifest, groupCachedFontsByFamily } from '../fonts/bundle.ts';
34
+ import {
35
+ emitFontAssets,
36
+ writeFontManifest,
37
+ groupCachedFontsByFamily,
38
+ mapFontImportersToRoutes,
39
+ } from '../fonts/bundle.ts';
40
+ import { collectRouteFilePaths } from './build-manifest.ts';
35
41
  import {
36
42
  RESOLVED_GOOGLE,
37
43
  RESOLVED_LOCAL,
@@ -81,12 +87,19 @@ export function timberFonts(ctx: PluginContext): Plugin & { api: FontsBuildStep
81
87
  const pipeline = new FontPipeline({ hashOnRegister: !ctx.dev });
82
88
  /** Whether the client environment emitted a binary this build. */
83
89
  let emittedToClient = false;
90
+ /**
91
+ * Font importer → the layouts/pages that reach it, from the RSC build's
92
+ * module graph. Lets the manifest key a font defined in `app/fonts.ts`
93
+ * under the layout that imports it.
94
+ */
95
+ let routesByImporter: Map<string, string[]> | undefined;
84
96
 
85
97
  return {
86
98
  name: 'timber-fonts',
87
99
 
88
100
  api: {
89
- contributeManifest: (manifest) => writeFontManifest(pipeline, manifest, ctx.base),
101
+ contributeManifest: (manifest) =>
102
+ writeFontManifest(pipeline, manifest, ctx.base, routesByImporter),
90
103
  immutableDirs: () => (emittedToClient ? [FONT_OUTPUT_DIR] : []),
91
104
  },
92
105
 
@@ -331,6 +344,19 @@ export function timberFonts(ctx: PluginContext): Plugin & { api: FontsBuildStep
331
344
  (msg) => this.warn(msg)
332
345
  );
333
346
  if (this.environment?.name === 'client') emittedToClient = emitted > 0;
347
+
348
+ // Server components (layouts, pages, and the modules they import) are
349
+ // real modules only in the RSC graph, so the route association is
350
+ // read there.
351
+ if (this.environment?.name === 'rsc' && ctx.routeTree) {
352
+ const importers = new Set<string>();
353
+ for (const font of pipeline.fonts()) importers.add(font.importer);
354
+ routesByImporter = mapFontImportersToRoutes(
355
+ importers,
356
+ collectRouteFilePaths(ctx.routeTree.root),
357
+ (id) => this.getModuleInfo(id)?.importers
358
+ );
359
+ }
334
360
  },
335
361
  };
336
362
  }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * timber-route-css — link font CSS that a route file reaches only through
3
+ * a plain (non-component) module.
4
+ *
5
+ * @vitejs/plugin-rsc renders a server component's stylesheets by wrapping
6
+ * the component in `import.meta.viteRsc.loadCss()`, which collects every
7
+ * CSS file the module reaches, directly or through other modules. But it
8
+ * only applies that wrap to a module that imports CSS **itself**
9
+ * (`rsc:rsc-css-export-transform`). A font is usually defined in a plain
10
+ * module, and the font's CSS import is injected there:
11
+ *
12
+ * ```ts
13
+ * // app/fonts.ts — the font's @font-face CSS is imported here
14
+ * export const body = localFont({ src: './TX-02.woff2' });
15
+ *
16
+ * // app/layout.tsx — imports no CSS of its own, so nothing is wrapped
17
+ * import { body } from './fonts';
18
+ * ```
19
+ *
20
+ * The page rendered with the font's class and no `@font-face`.
21
+ *
22
+ * This plugin gives such a route file a static import of an empty
23
+ * stylesheet, so plugin-rsc wraps it exactly as it wraps a layout that
24
+ * imports `globals.css`, and `loadCss()` collects the font CSS. The anchor
25
+ * is imported with `?inline`: plugin-rsc's wrap check counts it as a CSS
26
+ * import, while its collector skips `?inline` ids (no `<link>` in dev) and
27
+ * the build compiles it to a JS string (no asset).
28
+ *
29
+ * **Only route files that reach a font module are touched.** The wrap is
30
+ * not free: in dev it renders an async `Resources` component beside the
31
+ * route component, which shifts shell timing (a delayed `deny()` can land
32
+ * before the shell commits). Wrapping every route file changed dev status
33
+ * codes in apps with no fonts at all. Route files that import CSS are
34
+ * wrapped by plugin-rsc already; this adds only the font case.
35
+ *
36
+ * A route file is transformed before its imports, so the font pipeline
37
+ * can't answer "does this reach a font?" yet. The plugin scans source
38
+ * instead: it follows the route file's static imports through local,
39
+ * server-side modules (not node_modules, not `'use client'` — a client
40
+ * module's CSS rides its client reference) and stops at the first module
41
+ * that imports a font loader. Scans are cached per file by mtime.
42
+ *
43
+ * Not touched: `'use client'` route files (a statement before the directive
44
+ * would cancel it), MDX (frontmatter must stay on line 1), and route.ts /
45
+ * middleware.ts / access.ts / metadata routes (not components).
46
+ *
47
+ * Known limit (dev): adding the first font call to a module a route file
48
+ * already imports takes effect when the route file is next transformed
49
+ * (edit or restart), because the route file's own source did not change.
50
+ *
51
+ * Design doc: 24-fonts.md §"Step 3: @font-face Generation"
52
+ */
53
+
54
+ import { readFileSync, statSync } from 'node:fs';
55
+ import MagicString from 'magic-string';
56
+ import { parseAst, type Plugin } from 'vite';
57
+ import type { PluginContext } from '../plugin-context.ts';
58
+ import { detectDirective } from '../analyze/classify.ts';
59
+ import type { RouteTree, SegmentNode } from '../routing/types.ts';
60
+
61
+ const ANCHOR_ID = 'virtual:timber-route-css.css';
62
+ const RESOLVED_ANCHOR_ID = '\0' + ANCHOR_ID;
63
+ /** The import the transform adds. See the module comment for `?inline`. */
64
+ export const ROUTE_CSS_ANCHOR_IMPORT = `import '${ANCHOR_ID}?inline';\n`;
65
+
66
+ const SCRIPT_RE = /\.[cm]?[jt]sx?$/;
67
+ /** Module specifiers that make a module a font module (same as the fonts transform). */
68
+ const FONT_SPECIFIER_PREFIXES = ['@timber/fonts/', '@timber-js/app/fonts/', 'next/font/'];
69
+
70
+ const isFontSpecifier = (spec: string) => FONT_SPECIFIER_PREFIXES.some((p) => spec.startsWith(p));
71
+
72
+ /** What a module's source says, for the reachability walk. */
73
+ interface ModuleScan {
74
+ mtimeMs: number;
75
+ size: number;
76
+ /** Imports a font loader (so the fonts transform injects its CSS here). */
77
+ definesFont: boolean;
78
+ /** A 'use client' / 'use server' module — not walked into. */
79
+ directive: boolean;
80
+ /** Static, value (non-type) import and re-export specifiers. */
81
+ specifiers: string[];
82
+ }
83
+
84
+ /** True when an import/export node carries TS's `type` modifier (not in ESTree). */
85
+ function isTypeOnly(node: object, key: 'importKind' | 'exportKind'): boolean {
86
+ return key in node && Reflect.get(node, key) === 'type';
87
+ }
88
+
89
+ /** Static value import/re-export specifiers of a module. */
90
+ export function staticSpecifiers(code: string, filename: string): string[] {
91
+ const ext = filename.slice(filename.lastIndexOf('.') + 1);
92
+ const lang = ext.includes('ts')
93
+ ? ext.endsWith('x')
94
+ ? 'tsx'
95
+ : 'ts'
96
+ : ext.endsWith('x')
97
+ ? 'jsx'
98
+ : 'js';
99
+ let program: ReturnType<typeof parseAst>;
100
+ try {
101
+ program = parseAst(code, { lang });
102
+ } catch {
103
+ return [];
104
+ }
105
+ const specs: string[] = [];
106
+ for (const node of program.body) {
107
+ if (node.type === 'ImportDeclaration') {
108
+ if (!isTypeOnly(node, 'importKind') && typeof node.source.value === 'string') {
109
+ specs.push(node.source.value);
110
+ }
111
+ } else if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {
112
+ if (!isTypeOnly(node, 'exportKind') && typeof node.source?.value === 'string') {
113
+ specs.push(node.source.value);
114
+ }
115
+ }
116
+ }
117
+ return specs;
118
+ }
119
+
120
+ /** Every route file that exports a server component plugin-rsc may wrap. */
121
+ export function collectComponentRouteFiles(
122
+ node: SegmentNode,
123
+ into = new Set<string>()
124
+ ): Set<string> {
125
+ for (const file of [node.page, node.layout, node.default, node.denied, node.error]) {
126
+ if (file) into.add(file.filePath);
127
+ }
128
+ for (const file of Object.values(node.statusFiles ?? {})) into.add(file.filePath);
129
+ for (const child of node.children) collectComponentRouteFiles(child, into);
130
+ for (const slot of Object.values(node.slots)) collectComponentRouteFiles(slot, into);
131
+ return into;
132
+ }
133
+
134
+ export function timberRouteCss(ctx: PluginContext): Plugin {
135
+ const scans = new Map<string, ModuleScan>();
136
+ const scan = (id: string, code?: string): ModuleScan | null => {
137
+ let stat;
138
+ try {
139
+ stat = statSync(id);
140
+ } catch {
141
+ return null;
142
+ }
143
+ const cached = scans.get(id);
144
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached;
145
+ const source = code ?? readFileSync(id, 'utf8');
146
+ const specifiers = staticSpecifiers(source, id);
147
+ const result: ModuleScan = {
148
+ mtimeMs: stat.mtimeMs,
149
+ size: stat.size,
150
+ definesFont: specifiers.some(isFontSpecifier),
151
+ // Anywhere in the directive prologue (`'use strict'; 'use client'`).
152
+ directive: detectDirective(source, id) !== null,
153
+ specifiers,
154
+ };
155
+ scans.set(id, result);
156
+ return result;
157
+ };
158
+
159
+ // Recomputed when the routing plugin rescans (a new tree object).
160
+ let tree: RouteTree | null = null;
161
+ let routeFiles = new Set<string>();
162
+ const isRouteFile = (id: string): boolean => {
163
+ if (ctx.routeTree !== tree) {
164
+ tree = ctx.routeTree;
165
+ routeFiles = tree ? collectComponentRouteFiles(tree.root) : new Set();
166
+ }
167
+ return routeFiles.has(id);
168
+ };
169
+
170
+ return {
171
+ name: 'timber-route-css',
172
+ // Before plugin-rsc's CSS export transform reads the module's imports.
173
+ enforce: 'pre',
174
+
175
+ resolveId: {
176
+ filter: { id: /virtual:timber-route-css\.css/ },
177
+ handler(id) {
178
+ const bare = id.startsWith('\0') ? id.slice(1) : id;
179
+ if (!bare.startsWith(ANCHOR_ID)) return null;
180
+ return RESOLVED_ANCHOR_ID + bare.slice(ANCHOR_ID.length);
181
+ },
182
+ },
183
+
184
+ load: {
185
+ filter: { id: /virtual:timber-route-css\.css/ },
186
+ handler(id) {
187
+ return id.startsWith(RESOLVED_ANCHOR_ID) ? '' : null;
188
+ },
189
+ },
190
+
191
+ transform: {
192
+ filter: { id: { include: SCRIPT_RE, exclude: /(?:^\0|[?&]|\/node_modules\/)/ } },
193
+ async handler(code, id) {
194
+ if (this.environment.name !== 'rsc') return null;
195
+ if (!isRouteFile(id) || detectDirective(code, id) !== null) return null;
196
+ const self = scan(id, code);
197
+ // A route file that calls a font loader itself already imports the
198
+ // font CSS, and plugin-rsc wraps it — nothing to add.
199
+ if (!self || self.definesFont) return null;
200
+
201
+ // Breadth-first over local server modules, stopping at the first
202
+ // font module.
203
+ let reachesFont = false;
204
+ const visited = new Set([id]);
205
+ const queue: Array<{ importer: string; specifiers: string[] }> = [
206
+ { importer: id, specifiers: self.specifiers },
207
+ ];
208
+ for (let item = queue.shift(); item && !reachesFont; item = queue.shift()) {
209
+ const { importer, specifiers } = item;
210
+ for (const spec of specifiers) {
211
+ if (isFontSpecifier(spec)) continue;
212
+ const resolved = await this.resolve(spec, importer);
213
+ if (!resolved || resolved.external) continue;
214
+ const next = resolved.id;
215
+ if (visited.has(next) || next.startsWith('\0') || next.includes('/node_modules/')) {
216
+ continue;
217
+ }
218
+ visited.add(next);
219
+ if (!SCRIPT_RE.test(next)) continue;
220
+ const info = scan(next);
221
+ if (!info || info.directive) continue;
222
+ if (info.definesFont) {
223
+ reachesFont = true;
224
+ break;
225
+ }
226
+ queue.push({ importer: next, specifiers: info.specifiers });
227
+ }
228
+ }
229
+ if (!reachesFont) return null;
230
+
231
+ const s = new MagicString(code);
232
+ s.prepend(ROUTE_CSS_ANCHOR_IMPORT);
233
+ return { code: s.toString(), map: s.generateMap({ hires: 'boundary' }) };
234
+ },
235
+ },
236
+ };
237
+ }