Merge perf/ssr-highlight into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 3c4c931, fe7313d · Browse files · 23 files·+1545 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
23 files+1545 added−78 removed
- tests:+466 added−5 removed
- other:+1079 added−73 removed
Provenance
- Commit
5881ff2- Tree
4123dbf- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
3c4c931- Parent 2
fe7313d
23 files changed+1545 added−78 removed
modified:apps/web/src/features/code/blob-view.tsx+5 added-3 removed
1234567867891011121314171 unmodified linesExpand all/** * One file of a project at a revision, in Code mode (its Why mode is * `why/why-view.tsx`, the same page). The file header stays under the * context bar: the path once, the file in words, Code | Why, Raw, * Permalink (`y`) and Copy. The code takes the pane's whole width and * scrolls sideways inside itself, never wrapping: the server sends it as * numbered, anchored plain text (`NumberedLines`), which the browser's * highlighted drawing (`code`, from `client-code.tsx`) replaces in place. * scrolls sideways inside itself, never wrapping: the server sends it * highlighted where it highlights its language and size (`ServerCode`, * ADR 0027), else as numbered, anchored plain text (`NumberedLines`), and * the browser's drawing (`code`, from `client-code.tsx`) replaces it in * place. * * A Markdown file is rendered (its source on `?plain=1`), an image is shown * from raw, and a binary file or one past the read cap says its size and * links its bytes. The inspector holds "This file".171 unmodified linesExpand allmodified:apps/web/src/features/code/client-code.tsx+109 added-28 removed
1 /**2- * A file and a commit's diff, drawn in the browser only. `@pierre/diffs`3- * and Shiki's grammars are megabytes, and the drawing needs the DOM, so the4- * server renders `fallback` (numbered lines, or the plain-text diff)5- * and the browser loads the drawing after hydration. `import.meta.env.SSR`6- * is `true` in the Worker's build, so the dynamic imports below are dead7- * code there and the Worker bundles none of it (`bytes:check`), as8- * `features/finish/client-diff.tsx` does.2+ * A file and a commit's diff, drawn in the browser over what the server3+ * sent. The server renders `fallback`: the code it highlighted4+ * (`ServerCode`), or numbered lines or the plain-text diff for code it5+ * does not highlight. After hydration the browser loads the drawing,6+ * starts the worker pool and highlights the code there first7+ * (`prepareFile`, `prepareDiffs`); only then does the drawing take the8+ * fallback's place, in one render, drawing the highlighted code at once.9+ * So code the server highlighted never visibly changes, and plain code10+ * changes once, to highlighted.11+ *12+ * The fallback stays where it is until then (no `ClientOnly`, whose13+ * switch would mount a second copy of it without the server's drawing).14+ * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic15+ * imports below are dead code there and the Worker bundles none of the16+ * drawings (`bytes:check`), as `features/finish/client-diff.tsx` does.17 */10-import { ClientOnly } from "@tanstack/react-router";11-import { lazy, Suspense } from "react";12-import type { ReactNode } from "react";18+import { Effect, Fiber } from "effect";19+import { Suspense, useEffect, useRef, useState } from "react";20+import type { ComponentType, ReactNode } from "react";21 22 // Type-only imports are erased, so the server bundles nothing of these.23 import type { FileCodeProps } from "./code-view.tsx";24 import type { DiffCodeProps } from "./diff-view.tsx";25 26+/** The file's drawing, once its module is loaded and the file highlighted in the pool; none on the server. */18-const FileLater = import.meta.env.SSR27+const fileDrawing = import.meta.env.SSR28 ? undefined20- : lazy(() => import("./code-view.tsx"));29+ : (file: FileCodeProps) =>30+ Effect.gen(function* () {31+ const { FileCode, prepareFile } = yield* Effect.tryPromise(32+ () => import("./code-view.tsx")33+ );34 35+ yield* prepareFile(file);36+37+ return FileCode;38+ });39+40+/** The diff's drawing, once its module is loaded and its first files highlighted; none on the server. */22-const DiffLater = import.meta.env.SSR41+const diffDrawing = import.meta.env.SSR42 ? undefined24- : lazy(() => import("./diff-view.tsx"));43+ : (files: Pick<DiffCodeProps, "drawn" | "files">) =>44+ Effect.gen(function* () {45+ const { DiffCode, prepareDiffs } = yield* Effect.tryPromise(46+ () => import("./diff-view.tsx")47+ );48 49+ yield* prepareDiffs(files);50+51+ return DiffCode;52+ });53+54+/** A drawing, held in state: a component is a function, which state would call. */55+interface Ready<P> {56+ readonly Draw: ComponentType<P>;57+}58+59+/**60+ * Runs `ready` (load the drawing, prepare what it draws) and hands its61+ * drawing to `done`; the returned function stops it, so a page left in62+ * the meantime is not drawn. A drawing that cannot load leaves the63+ * fallback in place.64+ */65+const start = <P, E>(66+ ready: Effect.Effect<ComponentType<P>, E>,67+ done: (ready: Ready<P>) => void68+) => {69+ const fiber = Effect.runFork(70+ ready.pipe(71+ Effect.andThen((Draw) =>72+ Effect.sync(() => {73+ done({ Draw });74+ })75+ ),76+ Effect.ignore77+ )78+ );79+80+ return () => {81+ Effect.runFork(Fiber.interrupt(fiber));82+ };83+};84+85 export const ClientFile = ({86 fallback,87 ...props29-}: FileCodeProps & { readonly fallback: ReactNode }) =>30- FileLater === undefined ? (88+}: FileCodeProps & { readonly fallback: ReactNode }) => {89+ const { path, sha, text } = props;90+ const [ready, setReady] = useState<Ready<FileCodeProps>>();91+92+ useEffect(93+ () =>94+ fileDrawing === undefined95+ ? undefined96+ : start(fileDrawing({ path, sha, text }), setReady),97+ [path, sha, text]98+ );99+100+ return ready === undefined ? (101 fallback102 ) : (33- <ClientOnly fallback={fallback}>34- <Suspense fallback={fallback}>35- <FileLater {...props} />36- </Suspense>103+ <Suspense fallback={fallback}>104+ <ready.Draw {...props} />105+ </Suspense>37- </ClientOnly>106 );107+};108 109 export const ClientDiffs = ({110 fallback,111 ...props43-}: DiffCodeProps & { readonly fallback: ReactNode }) =>44- DiffLater === undefined ? (112+}: DiffCodeProps & { readonly fallback: ReactNode }) => {113+ // The files as they first came: the drawing, once ready, follows any114+ // change itself, so preparing is done once.115+ const first = useRef({ drawn: props.drawn, files: props.files });116+ const [ready, setReady] = useState<Ready<DiffCodeProps>>();117+118+ useEffect(119+ () =>120+ diffDrawing === undefined121+ ? undefined122+ : start(diffDrawing(first.current), setReady),123+ []124+ );125+126+ return ready === undefined ? (127 fallback128 ) : (47- <ClientOnly fallback={fallback}>48- <Suspense fallback={fallback}>49- <DiffLater {...props} />50- </Suspense>129+ <Suspense fallback={fallback}>130+ <ready.Draw {...props} />131+ </Suspense>51- </ClientOnly>132 );133+};modified:apps/web/src/features/code/code-view.tsx+16 added-8 removed
13 unmodified lines14 * loads this module (`client-code.tsx`); the Worker never bundles it.15 */16 import { File } from "@pierre/diffs/react";17 import type { FileOptions, SelectedLineRange } from "@pierre/diffs/react";18-import { Option } from "effect";18+import { Effect, Option } from "effect";19 import { useEffect, useMemo, useRef, useState } from "react";20 21 import { lineHash, parseLineHash } from "./line-hash.ts";22 import type { LineRange } from "./line-hash.ts";23-import { diffsOptions, registerCodeTheme } from "./pierre.ts";24-import { CodePool } from "./pool.tsx";23+import { diffsOptions, fileOptions, registerCodeTheme } from "./pierre.ts";24+import { CodePool, poolReady } from "./pool.tsx";25+import { warmFile } from "./warm.ts";26 27 registerCodeTheme();28 29 export interface FileCodeProps {61 unmodified lines91 );92 93 const options = useMemo(94 (): FileOptions<undefined, undefined> => ({94- ...diffsOptions,95- enableLineSelection: true,96- lineHoverHighlight: "number",95+ ...fileOptions,96 onLineSelected: (range: SelectedLineRange | null) => {97 const lines =98 range === null99 ? null15 unmodified lines115 diffsOptions.onPostRender(node);116 pending.current.node = node;117 reveal(pending.current);118 },120- disableFileHeader: true,121- overflow: "scroll",119 }),120 []121 );122 5 unmodified lines128 </CodePool>129 );130 };131 132+/**133+ * Ready to draw `file` highlighted at once: the pool up, and the file134+ * highlighted in it, keyed as `FileCode` draws it. Settles either way; a135+ * file the pool could not highlight is drawn as it would have been.136+ */137+export const prepareFile = (file: FileCodeProps) =>138+ Effect.tryPromise(() => poolReady()).pipe(139+ Effect.andThen(Effect.tryPromise(() => warmFile(file))),140+ Effect.ignore141+ );142+143 // `React.lazy` takes a module's default export.144 export default FileCode;modified:apps/web/src/features/code/diff-view.tsx+34 added-11 removed
24 unmodified lines25 import { CodeView } from "@pierre/diffs/react";26 import type { CodeViewHandle, CodeViewReactOptions } from "@pierre/diffs/react";27 import type { ChangedFile } from "@repo/protocol/domain/code";28 import { useLocation, useRouter } from "@tanstack/react-router";29-import { Option, Predicate } from "effect";29+import { Effect, Option, Predicate } from "effect";30 import { Check, ChevronDown, OctagonX } from "lucide-react";31 import { useEffect, useMemo, useRef, useState } from "react";32 import type { ReactNode } from "react";33 34 import { drawnFiles, emptyDiffOf } from "./diff-model.ts";35 import type { DrawnFile } from "./diff-model.ts";36 import { PANE_SCROLLER } from "./diff-pane.tsx";37 import { diffLinesHash, parseDiffHash } from "./line-hash.ts";38-import { diffsOptions, registerCodeTheme } from "./pierre.ts";39-import { CodePool } from "./pool.tsx";38+import { diffOptionsFor, diffsOptions, registerCodeTheme } from "./pierre.ts";39+import { CodePool, poolReady, workerPool } from "./pool.tsx";40+import { SERVER_FILES } from "./prerender.ts";41 42 registerCodeTheme();43 44 /** A row a page draws under one line of one file's diff, on one side. */195 unmodified lines240 }, [byPath, hash]);241 242 const options = useMemo(243 (): CodeViewReactOptions<DiffAnnotation, undefined> => ({243- ...diffsOptions,244- diffIndicators: split ? "bars" : "classic",245- diffStyle: split ? "split" : "unified",246- enableLineSelection: true,247- hunkSeparators: "line-info",244+ ...diffOptionsFor(split),245 layout: { gap: 0, paddingBottom: 16, paddingTop: 0 },249- lineDiffType: "word-line",250- lineHoverHighlight: "both",251- overflow: "scroll",246 stickyHeaders: true,247 unsafeCSS: `${diffsOptions.unsafeCSS}\n${HEADER_CSS}`,248 }),249 [split]100 unmodified lines350 </CodePool>351 );352 };353 354+/**355+ * Ready to draw the first files of a diff highlighted at once: the pool356+ * up, and the files a reader sees first (those the server may have sent357+ * highlighted) highlighted in it, keyed as `DiffCode` draws them. The rest358+ * are highlighted as they scroll into view. Settles either way.359+ */360+export const prepareDiffs = ({361+ drawn,362+ files,363+}: Pick<DiffCodeProps, "drawn" | "files">) =>364+ Effect.tryPromise(() => poolReady()).pipe(365+ Effect.andThen(366+ Effect.forEach(367+ (drawn ?? drawnFiles(files))368+ .filter((file) => !file.folded)369+ .flatMap((file) => Option.toArray(file.diff))370+ .slice(0, SERVER_FILES),371+ (diff) =>372+ "Worker" in globalThis373+ ? Effect.tryPromise(() =>374+ workerPool().primeDiffHighlightCache(diff)375+ )376+ : Effect.void,377+ { concurrency: "unbounded", discard: true }378+ )379+ ),380+ Effect.ignore381+ );382+383 // `React.lazy` takes a module's default export.384 export default DiffCode;modified:apps/web/src/features/code/paths.ts+17 added
117 unmodified lines118 119 /** Whether `path` is Markdown, rendered on its page. */120 export const isMarkdown = (path: string) => MARKDOWN.test(path);121 122+/**123+ * Whether a file's page shows it as code: text it has, and not an image124+ * or Markdown shown as itself (`?plain=1` shows their source). The server125+ * highlights a file ahead only then.126+ */127+export const showsCode = (128+ file: {129+ readonly binary: boolean;130+ readonly path: string;131+ readonly text?: string | undefined;132+ },133+ plain: boolean134+) =>135+ !file.binary &&136+ file.text !== undefined &&137+ (plain || !(isImage(file.path) || isMarkdown(file.path)));138+139 /** The id of a changed file's diff on its commit's page. */140 export const diffAnchor = (path: string) => `diff-${encodeURIComponent(path)}`;modified:apps/web/src/features/code/pierre.ts+48 added-5 removed
16 unmodified lines17 * The limits are Pierre's own defaults, written out so a reader sees them:18 * past them a file (or a line, or a changed line's pair) is drawn as plain19 * text, so a minified bundle or a lockfile cannot stall the page.20 *21- * No React and no DOM here: the module loads in Node for its test, and in22- * the browser only through the views that draw. A drawing hands its code23- * boxes over once drawn, so code too wide for its pane is a stop for Tab.21+ * The server draws a file or a diff with these same options22+ * (`prerender-server.ts`), so the browser's drawing takes the place of the23+ * server's with nothing on the screen changing.24+ *25+ * No React and no DOM here: the module loads in Node for its test, in the26+ * Worker for the server's drawing, and in the browser only through the27+ * views that draw. A drawing hands its code boxes over once drawn, so code28+ * too wide for its pane is a stop for Tab.29 */30 import {31+ createCSSVariablesTheme,32 DEFAULT_TOKENIZE_MAX_LENGTH,33+ formatCSSVariablePrefix,27- registerCustomCSSVariableTheme,34+ registerCustomTheme,35 } from "@pierre/diffs";36 37 /** The token theme's registered name. */38 export const CODE_THEME = "repo-tokens";47 unmodified lines86 tokenizeMaxLineLength: 1000,87 unsafeCSS: FOCUS_CSS,88 } as const;89 90+/** A file's drawing: no header of its own (the page's sits above it), its lines selectable, scrolling sideways. */91+export const fileOptions = {92+ ...diffsOptions,93+ disableFileHeader: true,94+ enableLineSelection: true,95+ lineHoverHighlight: "number",96+ overflow: "scroll",97+} as const;98+99+/** A diff's drawing, unified or split: signs or side bars, changed words marked, unchanged runs folded into bars. */100+export const diffOptionsFor = (split: boolean) =>101+ ({102+ ...diffsOptions,103+ diffIndicators: split ? "bars" : "classic",104+ diffStyle: split ? "split" : "unified",105+ enableLineSelection: true,106+ hunkSeparators: "line-info",107+ lineDiffType: "word-line",108+ lineHoverHighlight: "both",109+ overflow: "scroll",110+ }) as const;111+112 /** The file tree's look: compact rows, plain icons (`styles.css` greys them). */113 export const treesOptions = { density: "compact", icons: "minimal" } as const;114 115 /**13 unmodified lines129 "token-string": "var(--foreground)",130 "token-string-expression": "var(--foreground)",131 };132 133+/**134+ * The token theme itself, made as Pierre's `registerCustomCSSVariableTheme`135+ * makes it. The browser registers it by name; the server attaches it to136+ * its highlighter directly, since Pierre refuses to resolve a theme by name137+ * in a Worker's global scope.138+ */139+export const codeTheme = () =>140+ createCSSVariablesTheme({141+ fontStyle: false,142+ name: CODE_THEME,143+ variableDefaults,144+ variablePrefix: formatCSSVariablePrefix("global"),145+ });146+147 /** Whether this page has registered the theme yet; Pierre refuses a name twice. */148 const registered = { done: false };149 150 /** Registers the token theme, once; each drawing calls it before it draws. */151 export const registerCodeTheme = () => {152 if (!registered.done) {153 registered.done = true;111- registerCustomCSSVariableTheme(CODE_THEME, variableDefaults);154+ registerCustomTheme(CODE_THEME, () => Promise.resolve(codeTheme()));155 }156 };modified:apps/web/src/features/code/plain-diff.tsx+31 added-6 removed
4 unmodified lines5 * drawing's own parser) and takes Pierre's measures: a 44 px file header,6 * 13 px code on 20 px lines, line numbers in a gutter of at least three7 * figures with two before and one after, a sign in the first of two8 * leading columns, unchanged runs as 32 px "N unmodified lines" bars. So9- * the highlighting arrives in place and nothing moves.9+ * the highlighting arrives in place and nothing moves. The first files the10+ * server highlights (`prerenderedPaths`, ADR 0027) are its drawing instead11+ * of plain lines, under the same header.12 *13 * Each file is a disclosure whose summary is its header: folded, only the14 * header shows (an added or deleted file past 80 lines starts folded).15 * Additions and deletions take the diff's own tints, never the landed or9 unmodified lines25 26 import { drawnFiles, splitRows, unifiedRows } from "./diff-model.ts";27 import type { DrawnFile, PlainRow, SplitRow } from "./diff-model.ts";28 import { diffAnchor } from "./paths.ts";29+import { diffDrawing } from "./prerender.ts";30+import { ServerCode } from "./server-code.tsx";31 32 /** One numbered line: its text, and which side it is on. */33 type Line = Extract<PlainRow, { readonly number: number }>;34 155 unmodified lines190 {file.binary ? "A binary file" : "Its text is not shown"}, {file.status}.191 </p>192 );193 190-/** A file's lines, unified or split; why it has none when it has none. */194+/**195+ * A file's lines, unified or split; why it has none when it has none. A196+ * file the server highlighted (unified, `prerenderedPaths`) is its drawing,197+ * and the plain lines only where the document did not bring it.198+ */199 const FileBody = ({200 file,201+ prerendered,202 split,203 }: {204 readonly file: DrawnFile;205+ readonly prerendered: boolean;206 readonly split: boolean;207 }) => {208 const diff = Option.getOrUndefined(file.diff);209 210 if (diff === undefined) {211 return <Unshown file={file.file} />;212 }213 204- return split ? (205- <SplitBody rows={splitRows(diff)} />214+ if (split) {215+ return <SplitBody rows={splitRows(diff)} />;216+ }217+218+ const plain = <UnifiedBody rows={unifiedRows(diff)} />;219+220+ return prerendered ? (221+ <div className="min-w-0" data-code="prerendered">222+ <ServerCode drawing={() => diffDrawing(file)} plain={plain} />223+ </div>224 ) : (207- <UnifiedBody rows={unifiedRows(diff)} />225+ plain226 );227 };228 229 /** Each kind of change as the drawing's header marks it, in the diff's tints. */58 unmodified lines288 /** A header's fold was pressed. */289 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;290 /** `files` already parsed (`drawnFiles`), so a page parses each once. */291 readonly drawn?: readonly DrawnFile[] | undefined;292+ /** The paths the server sends highlighted (`prerenderedPaths`); none when absent. */293+ readonly prerendered?: ReadonlySet<string> | undefined;294 }295 296 /**297 * The diff of `files`, plain, in the order a tree lists them. Server4 unmodified lines302 drawn: parsed,303 files,304 folded,305 onFold,306+ prerendered,307 split = false,308 }: PlainDiffProps) => {309 const drawnList = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);310 25 unmodified lines336 data-diffs-header=""337 >338 <FileHeaderLine file={drawn} />339 </summary>319- <FileBody file={drawn} split={split} />340+ <FileBody341+ file={drawn}342+ prerendered={prerendered?.has(file.path) === true}343+ split={split}344+ />345 </details>346 </section>347 );348 })}3 unmodified linesmodified:apps/web/src/features/code/pool.tsx+14 added-1 removed
62 unmodified lines63 return known;64 }65 66 // A pool already up is marked settled the way React reads a promise it67- // has seen, so `use` does not hold the drawing back for a turn.67+ // has seen, so `use` does not hold the drawing back for a turn; one68+ // still starting is marked so once it is up, whoever awaited it first.69 const made = pool.isInitialized()70 ? Object.assign(Promise.resolve(), { status: "fulfilled" })71 : Effect.runPromise(72 Effect.ignore(Effect.tryPromise(() => pool.initialize()))73 );74 75+ Effect.runFork(76+ Effect.promise(() => made).pipe(77+ Effect.map(() => Object.assign(made, { status: "fulfilled" }))78+ )79+ );80 readiness.set(pool, made);81 82 return made;83 };84 85 /**86+ * Settles once the tab's pool is up (at once where there are no workers):87+ * a drawing awaited on this then mounts with nothing left to wait for.88+ */89+export const poolReady = () =>90+ "Worker" in globalThis ? readyOf(workerPool()) : Promise.resolve();91+92+/**93 * The pool, for the drawings under it; none outside a browser. Until the94 * pool is up the drawings wait in their `Suspense`, whose fallback is the95 * server's plain text.96 */13 unmodified linesadded:apps/web/src/features/code/prerender-server.ts+159 added
1+/**2+ * Code highlighted on the server: a file, or one file of a diff, drawn by3+ * `@pierre/diffs/ssr` with the browser's own options (`pierre.ts`) into4+ * the HTML of the drawing's shadow root, which the page sends as a5+ * declarative shadow root. The browser's drawing later takes its place6+ * with the same highlighting, so the reader sees the code once.7+ *8+ * Shiki runs on its JavaScript engine (a Worker compiles no WebAssembly),9+ * and only with the grammars named here: the Worker's build resolves10+ * `shiki` to core alone (`vite.config.ts`), so no other grammar is11+ * bundled. Pierre will not resolve a grammar or a theme by name in a12+ * Worker's global scope, so each is loaded here and attached to its13+ * highlighter directly, once per isolate.14+ *15+ * Loaded on the server only, by `prerender.ts`, on a page's first16+ * highlighted code: the Worker's entry carries none of it.17+ */18+import {19+ attachResolvedLanguages,20+ attachResolvedThemes,21+ getSharedHighlighter,22+} from "@pierre/diffs";23+import type {24+ FileContents,25+ FileDiffMetadata,26+ LanguageRegistration,27+} from "@pierre/diffs";28+import { preloadDiffHTML, preloadFile } from "@pierre/diffs/ssr";29+import { Effect, Option } from "effect";30+import { normalizeTheme } from "shiki/core";31+32+import type { DrawnFile } from "./diff-model.ts";33+import {34+ codeTheme,35+ diffOptionsFor,36+ diffsOptions,37+ fileOptions,38+} from "./pierre.ts";39+import { serverLanguageOf } from "./prerender.ts";40+import type { ServerLanguage } from "./prerender.ts";41+42+type Grammar = () => Promise<{ readonly default: LanguageRegistration[] }>;43+44+/** Each server language's grammar, loaded on first use; `yml` and `zsh` are aliases Pierre names. */45+const GRAMMARS: Record<ServerLanguage, Grammar> = {46+ css: () => import("shiki/langs/css.mjs"),47+ html: () => import("shiki/langs/html.mjs"),48+ javascript: () => import("shiki/langs/javascript.mjs"),49+ json: () => import("shiki/langs/json.mjs"),50+ jsx: () => import("shiki/langs/jsx.mjs"),51+ markdown: () => import("shiki/langs/markdown.mjs"),52+ toml: () => import("shiki/langs/toml.mjs"),53+ tsx: () => import("shiki/langs/tsx.mjs"),54+ typescript: () => import("shiki/langs/typescript.mjs"),55+ yaml: () => import("shiki/langs/yaml.mjs"),56+ yml: () => import("shiki/langs/yaml.mjs"),57+ zsh: () => import("shiki/langs/shellscript.mjs"),58+};59+60+/** The shared highlighter, with the token theme and `language`'s grammar attached. */61+const highlighterFor = (language: ServerLanguage) =>62+ Effect.gen(function* () {63+ const highlighter = yield* Effect.tryPromise(() =>64+ getSharedHighlighter({65+ langs: [],66+ preferredHighlighter: "shiki-js",67+ themes: [],68+ })69+ );70+71+ const grammar = yield* Effect.tryPromise(GRAMMARS[language]);72+73+ // Each is attached once; Pierre skips one already attached. The theme74+ // is normalized as Pierre normalizes a registered one.75+ yield* Effect.try(() => {76+ attachResolvedThemes(normalizeTheme(codeTheme()), highlighter);77+ attachResolvedLanguages(78+ { data: grammar.default, name: language },79+ highlighter80+ );81+ });82+ });83+84+/**85+ * A drawing in `language`; if it fails, the same drawing as plain text, so86+ * the page still sends Pierre's markup; none if that fails too.87+ */88+const draw = <E1, E2>(89+ language: Option.Option<ServerLanguage>,90+ highlighted: Effect.Effect<string, E1>,91+ plain: Effect.Effect<string, E2>92+): Effect.Effect<string | undefined> =>93+ Option.match(language, {94+ onNone: () => plain,95+ onSome: (name) =>96+ highlighterFor(name).pipe(97+ Effect.andThen(highlighted),98+ Effect.catchCause(() => plain)99+ ),100+ }).pipe(Effect.orElseSucceed((): string | undefined => undefined));101+102+/** A file drawn as `FileCode` draws it. */103+const fileHtml = (file: FileContents) =>104+ Effect.tryPromise(() => preloadFile({ file, options: fileOptions })).pipe(105+ Effect.map(({ prerenderedHTML }) => prerenderedHTML)106+ );107+108+/** One file, as `FileCode` draws it. */109+export const prerenderFile = (file: {110+ readonly path: string;111+ readonly sha: string;112+ readonly text: string;113+}) => {114+ const contents = { cacheKey: file.sha, contents: file.text, name: file.path };115+116+ return draw(117+ serverLanguageOf(file.path),118+ fileHtml(contents),119+ fileHtml({ ...contents, lang: "text" })120+ );121+};122+123+/**124+ * A diff's body drawn without Pierre's header (the page's own sits above125+ * it) sits as it does in the browser's drawing: Pierre drops the code's126+ * top gap only after a header, so the lines would otherwise start 8 px127+ * lower, and it takes a scrollbar's width from the bottom gap only once128+ * its script has measured one, so the next file would start 6 px higher.129+ */130+const UNDER_HEADER_CSS =131+ "[data-code] { padding-top: 0; padding-bottom: var(--diffs-gap-block, var(--diffs-gap-fallback)); }";132+133+/** A diff's body drawn unified, as `DiffCode` draws it, without a header. */134+const diffHtml = (fileDiff: FileDiffMetadata) =>135+ Effect.tryPromise(() =>136+ preloadDiffHTML({137+ fileDiff,138+ options: {139+ ...diffOptionsFor(false),140+ disableFileHeader: true,141+ unsafeCSS: `${diffsOptions.unsafeCSS}\n${UNDER_HEADER_CSS}`,142+ },143+ })144+ );145+146+/**147+ * One file of a diff's body, unified, as `DiffCode` draws it, under the148+ * page's own header: none for a file with no lines.149+ */150+export const prerenderDiff = (file: DrawnFile) =>151+ Option.match(file.diff, {152+ onNone: () => Effect.sync((): string | undefined => undefined),153+ onSome: (diff) =>154+ draw(155+ serverLanguageOf(file.file.path),156+ diffHtml(diff),157+ diffHtml({ ...diff, lang: "text" })158+ ),159+ });added:apps/web/src/features/code/prerender.ts+271 added
1+/**2+ * Which code the server sends highlighted, and where its drawing waits3+ * between the page's loader and its render.4+ *5+ * The server highlights a fixed set of languages (`SERVER_LANGUAGES`, the6+ * grammars the Worker bundles) and only within its own limit, far below7+ * the browser's: a page highlights at most `SERVER_LINES` lines of text8+ * (a diff counts both sides, as Pierre highlights both whole files), and9+ * no line longer than the drawing's own line limit, so a minified file is10+ * never tokenized on the server. Anything else is sent as plain text, as11+ * before, and the browser highlights it.12+ *13+ * Both sides decide alike from the page's own data, so the browser knows14+ * which code arrived highlighted without being told.15+ *16+ * The drawing is made once per (blob, path) or (both blobs, path), so it17+ * is kept here, keyed by those ids, which never change what they name: the18+ * loader starts it and waits for it, and the render reads it at once. A19+ * few are kept, within a byte budget, so a file read again is not drawn20+ * again. Nothing here runs in the browser but the decision.21+ */22+import { getFiletypeFromFileName } from "@pierre/diffs";23+import type { ChangedFile } from "@repo/protocol/domain/code";24+import { Effect, Option } from "effect";25+26+import { drawnFiles } from "./diff-model.ts";27+import type { DrawnFile } from "./diff-model.ts";28+import { diffsOptions } from "./pierre.ts";29+30+/** The languages the Worker bundles a grammar for, by the names Pierre gives a file's type. */31+export const SERVER_LANGUAGES = [32+ "css",33+ "html",34+ "javascript",35+ "json",36+ "jsx",37+ "markdown",38+ "toml",39+ "tsx",40+ "typescript",41+ "yaml",42+ "yml",43+ "zsh",44+] as const;45+46+export type ServerLanguage = (typeof SERVER_LANGUAGES)[number];47+48+/**49+ * The most lines the server highlights for one page. Measured in the dev50+ * world's workerd (ADR 0027), warm: 2,400 lines of TypeScript took about51+ * 315 ms, 600 about 85 ms and 400 about 57 ms, so a page spends at most52+ * some 60 ms highlighting, and a longer file is sent plain.53+ */54+export const SERVER_LINES = 400;55+56+/** The most files of a diff the server highlights: those a reader sees first. */57+export const SERVER_FILES = 8;58+59+const isServerLanguage = (name: string): name is ServerLanguage =>60+ SERVER_LANGUAGES.some((language) => language === name);61+62+/** The language the server highlights `path` in, if it highlights it at all. */63+export const serverLanguageOf = (64+ path: string65+): Option.Option<ServerLanguage> => {66+ const name = getFiletypeFromFileName(path);67+68+ return isServerLanguage(name) ? Option.some(name) : Option.none();69+};70+71+/** `text`'s lines, or none when one is longer than the drawing tokenizes. */72+const linesWithin = (text: string): Option.Option<number> => {73+ const lines = text.split("\n");74+75+ return lines.every(76+ (line) => line.length <= diffsOptions.tokenizeMaxLineLength77+ )78+ ? Option.some(lines.length)79+ : Option.none();80+};81+82+/** Whether the server sends this file highlighted. */83+export const prerendersFile = (file: {84+ readonly path: string;85+ readonly text: string;86+}) =>87+ Option.isSome(serverLanguageOf(file.path)) &&88+ file.text.length <= diffsOptions.tokenizeMaxLength &&89+ Option.exists(linesWithin(file.text), (lines) => lines <= SERVER_LINES);90+91+/** A diff's lines on both sides, or none when a side has a line too long. */92+const diffLines = (drawn: DrawnFile): Option.Option<number> => {93+ const sides = [drawn.file.oldText, drawn.file.newText].flatMap((text) =>94+ text === undefined ? [] : [linesWithin(text)]95+ );96+97+ return Option.all(sides).pipe(98+ Option.map((counts) => counts.reduce((sum, count) => sum + count, 0))99+ );100+};101+102+/**103+ * The paths of a diff the server sends highlighted, unified: among the104+ * first `SERVER_FILES` files that start open and have lines, those in a105+ * server language, within `SERVER_LINES` together.106+ */107+export const prerenderedPaths = (108+ drawn: readonly DrawnFile[]109+): ReadonlySet<string> => {110+ const paths = new Set<string>();111+ let spent = 0;112+113+ const open = drawn114+ .filter((file) => !file.folded && Option.isSome(file.diff))115+ .slice(0, SERVER_FILES);116+117+ for (const file of open) {118+ const lines = diffLines(file);119+120+ if (121+ Option.isSome(serverLanguageOf(file.file.path)) &&122+ Option.isSome(lines) &&123+ spent + lines.value <= SERVER_LINES124+ ) {125+ spent += lines.value;126+ paths.add(file.file.path);127+ }128+ }129+130+ return paths;131+};132+133+/** A drawing as React's `use` reads it: settled ones say so, so a render never waits on them. */134+type Drawing = Promise<string | undefined> & {135+ status?: "fulfilled";136+ value?: string | undefined;137+};138+139+/** How many drawings are kept, and how many characters of HTML at most. */140+const KEPT = { count: 24, size: 8_000_000 } as const;141+142+/** The drawings made, the oldest first; each id names what it draws for good. */143+const kept = new Map<string, { readonly drawing: Drawing; size: number }>();144+145+const sizeOf = () =>146+ [...kept.values()].reduce((sum, entry) => sum + entry.size, 0);147+148+/** Drops the oldest drawings past the count or the size. */149+const trim = () => {150+ for (const id of kept.keys()) {151+ if (kept.size <= KEPT.count && sizeOf() <= KEPT.size) {152+ return;153+ }154+155+ kept.delete(id);156+ }157+};158+159+/** The drawing `id` names: the one kept, or one `make` starts now. */160+const keptDrawing = <E>(161+ id: string,162+ make: Effect.Effect<string | undefined, E>163+): Drawing => {164+ const known = kept.get(id);165+166+ if (known !== undefined) {167+ kept.delete(id);168+ kept.set(id, known);169+170+ return known.drawing;171+ }172+173+ // A drawing that fails is none: the page sends the plain text instead.174+ const drawing: Drawing = Effect.runPromise(175+ make.pipe(Effect.orElseSucceed((): string | undefined => undefined))176+ );177+178+ const entry = { drawing, size: 0 };179+180+ kept.set(id, entry);181+ // Settled, it says so (`use` then reads it without waiting) and counts182+ // its size. Subscribed first, so whoever awaits it next finds it marked.183+ Effect.runFork(184+ Effect.promise(() => drawing).pipe(185+ Effect.andThen((html) =>186+ Effect.sync(() => {187+ drawing.status = "fulfilled";188+ drawing.value = html;189+ entry.size = html?.length ?? 0;190+ trim();191+ })192+ )193+ )194+ );195+ trim();196+197+ return drawing;198+};199+200+/**201+ * The server's drawing module, on its first use. The browser's build has202+ * none (`import.meta.env.SSR` is false there, so the import is dead code),203+ * and draws nothing here.204+ */205+const server = () =>206+ import.meta.env.SSR207+ ? Effect.tryPromise(() => import("./prerender-server.ts"))208+ : Effect.die("Only the server draws code ahead");209+210+/** The id a file's drawing is kept by: its blob and its path (which names its language). */211+export const fileDrawingId = (file: {212+ readonly path: string;213+ readonly sha: string;214+}) => `file:${file.sha}:${file.path}`;215+216+/** The id a diff's drawing is kept by: both its blobs and its path. */217+export const diffDrawingId = (drawn: DrawnFile) =>218+ `${drawn.file.before ?? "none"}:${drawn.file.after ?? "none"}:${drawn.file.path}`;219+220+/** A file highlighted by the server, as the HTML of its shadow root; none if it could not be. */221+export const fileDrawing = (file: {222+ readonly path: string;223+ readonly sha: string;224+ readonly text: string;225+}) =>226+ keptDrawing(227+ fileDrawingId(file),228+ server().pipe(Effect.andThen(({ prerenderFile }) => prerenderFile(file)))229+ );230+231+/** A diff's file highlighted by the server, unified, as the HTML of its shadow root. */232+export const diffDrawing = (drawn: DrawnFile) =>233+ keptDrawing(234+ diffDrawingId(drawn),235+ server().pipe(Effect.andThen(({ prerenderDiff }) => prerenderDiff(drawn)))236+ );237+238+/**239+ * A page's file highlighted ahead of its render, which then finds it240+ * drawn and waits for nothing; nothing to do for a file sent plain.241+ */242+export const drawFileAhead = ({243+ path,244+ sha,245+ text,246+}: {247+ readonly path: string;248+ readonly sha: string;249+ readonly text?: string | undefined;250+}) =>251+ Effect.runPromise(252+ text === undefined || !prerendersFile({ path, text })253+ ? Effect.void254+ : Effect.promise(() => fileDrawing({ path, sha, text })).pipe(255+ Effect.asVoid256+ )257+ );258+259+/** A diff's first files highlighted ahead of its render, as `drawFileAhead`. */260+export const drawDiffAhead = (files: readonly ChangedFile[]) => {261+ const drawn = drawnFiles(files);262+ const paths = prerenderedPaths(drawn);263+264+ return Effect.runPromise(265+ Effect.forEach(266+ drawn.filter((file) => paths.has(file.file.path)),267+ (file) => Effect.promise(() => diffDrawing(file)),268+ { concurrency: "unbounded", discard: true }269+ )270+ );271+};added:apps/web/src/features/code/server-code.tsx+103 added
1+/**2+ * Code the server highlighted: Pierre's own host element, `diffs-container`,3+ * whose shadow root the server sends as a declarative shadow root (a4+ * `<template shadowrootmode="open">`), so the browser paints the5+ * highlighted code with the document, before any script.6+ *7+ * The parser turns the template into the element's shadow root, so the8+ * browser's render holds the same element with nothing in it: React9+ * adopts it as it is, shadow root and all, until the page's drawing takes10+ * its place. A page drawn in the browser alone (one reached by a link,11+ * not loaded) has no drawing there, and shows `plain` instead, before it12+ * paints.13+ */14+import { createElement, use, useCallback, useState } from "react";15+import type { ReactNode } from "react";16+17+import { NumberedLines } from "./numbered-lines.tsx";18+import { fileDrawing, prerendersFile } from "./prerender.ts";19+20+/** Pierre's host element; its stylesheet and script come with the drawing. */21+const HOST = "diffs-container";22+23+/** The drawing's HTML, in its shadow root; an empty host when there is none. */24+const Prerendered = ({ html }: { readonly html: string | undefined }) =>25+ createElement(26+ HOST,27+ { "data-prerendered": "" },28+ html === undefined29+ ? null30+ : createElement("template", {31+ // oxlint-disable-next-line react/no-danger -- a declarative shadow root is HTML the parser must read; Pierre's own SSR sends it so (`templateRender`), and the HTML is Pierre's rendering of escaped code text32+ dangerouslySetInnerHTML: { __html: html },33+ shadowrootmode: "open",34+ })35+ );36+37+/** The server's drawing, kept as the document holds it; `plain` when it holds none. */38+const Adopted = ({ plain }: { readonly plain: ReactNode }) => {39+ const [kept, setKept] = useState(true);40+41+ // Read as the host mounts, before the page paints. The drawing's code,42+ // not just a shadow root: once Pierre's element is defined (a page drawn43+ // before), a new host gets an empty one at once.44+ const adopt = useCallback((host: HTMLElement | null) => {45+ if (46+ host !== null &&47+ (host.shadowRoot?.querySelector("pre") ?? null) === null48+ ) {49+ setKept(false);50+ }51+ }, []);52+53+ return kept54+ ? createElement(HOST, {55+ "data-prerendered": "",56+ ref: adopt,57+ suppressHydrationWarning: true,58+ })59+ : plain;60+};61+62+export const ServerCode = ({63+ drawing,64+ plain,65+}: {66+ /** The server's drawing (`prerender.ts`), settled before the page renders. */67+ readonly drawing: () => Promise<string | undefined>;68+ /** What the browser shows when the document did not bring the drawing. */69+ readonly plain: ReactNode;70+}) =>71+ import.meta.env.SSR ? (72+ <Prerendered html={use(drawing())} />73+ ) : (74+ <Adopted plain={plain} />75+ );76+77+/**78+ * A file as the server sends it, until the browser's drawing replaces it:79+ * highlighted where the server highlights it (`prerendersFile`), else80+ * numbered, anchored plain text.81+ */82+export const FileFallback = ({83+ path,84+ sha,85+ text,86+}: {87+ readonly path: string;88+ readonly sha: string;89+ readonly text: string;90+}) => {91+ const plain = <NumberedLines text={text} />;92+93+ return prerendersFile({ path, text }) ? (94+ <div className="min-w-0" data-code="prerendered">95+ <ServerCode96+ drawing={() => fileDrawing({ path, sha, text })}97+ plain={plain}98+ />99+ </div>100+ ) : (101+ plain102+ );103+};modified:apps/web/src/routes/$project/blob/$rev/$.tsx+36 added-6 removed
12 unmodified lines13 } from "../../../../features/code/address.ts";14 import { BlobView } from "../../../../features/code/blob-view.tsx";15 import { ClientFile } from "../../../../features/code/client-code.tsx";16 import { CodeNotFound } from "../../../../features/code/not-found.tsx";17-import { NumberedLines } from "../../../../features/code/numbered-lines.tsx";17+import { showsCode } from "../../../../features/code/paths.ts";18+import { FileFallback } from "../../../../features/code/server-code.tsx";19 import { pageHead } from "../../../../features/shared/head.ts";20 import { notFoundFor } from "../../../../features/shared/refusals.ts";21 import { branchPage } from "../../../../server/cache-headers.ts";22 import { serverClient } from "../../../../server/client.ts";1 unmodified line24 import { FilesButton } from "../../tree/-files-button.tsx";25 import { softLanding } from "../../tree/-soft-landing.ts";26 27 // A file at a revision, read on the server with the commit that last27-// changed it: its text arrives as numbered, anchored lines, and the28-// browser then draws it highlighted, the `#L10-L20` selection kept in the29-// address. `?plain=1` shows a Markdown file's source. A path missing at a28+// changed it: its text arrives highlighted when the server highlights its29+// language and size (`features/code/prerender.ts`), else as numbered,30+// anchored lines, and the browser's drawing then takes its place, the31+// `#L10-L20` selection kept in the address. `?plain=1` shows a Markdown file's source. A path missing at a32 // revision that exists lands on the nearest folder above it; any other33 // address naming nothing is a 404 showing the platform's refusal.34 35 const BlobPageData = Schema.Struct({69 unmodified lines105 <BlobView106 code={107 file.text === undefined ? undefined : (108 <ClientFile107- fallback={<NumberedLines text={file.text} />}109+ fallback={110+ <FileFallback path={file.path} sha={file.sha} text={file.text} />111+ }112 key={file.sha}113 path={file.path}114 sha={file.sha}115 text={file.text}17 unmodified lines133 // so a rendered file's address carries no `plain`.134 validateSearch: ({ plain }: { readonly plain?: unknown }) => ({135 plain: plain === 1 || plain === "1" ? (1 as const) : undefined,136 }),133- loader: ({ params, preload }) => {137+ loader: ({ location, params, preload }) => {138 const page = blobPage({ data: params });139 140+ // A document's file is highlighted on the server before the page141+ // renders, so the render waits for nothing and sends it highlighted.142+ // Imported here, not at the top: a loader stays in the chunks every143+ // page preloads, and the browser's build drops this branch whole.144+ if (import.meta.env.SSR) {145+ const plain =146+ new URLSearchParams(location.searchStr).get("plain") === "1";147+148+ // A failed read rejects as it would have (the router's not-found).149+ return Effect.runPromise(150+ Effect.gen(function* () {151+ const data = yield* Effect.promise(() => page);152+153+ if (showsCode(data.file, plain)) {154+ const { drawFileAhead } = yield* Effect.promise(155+ () => import("../../../../features/code/prerender.ts")156+ );157+158+ yield* Effect.promise(() => drawFileAhead(data.file));159+ }160+161+ return data;162+ })163+ );164+ }165+166 // A hover's preload warms the file's highlighting too, so the click167 // draws it at once; a failed read or warm-up changes nothing here.168 if (preload && !import.meta.env.SSR) {169 Effect.runFork(21 unmodified linesmodified:apps/web/src/routes/$project/commit/$sha.tsx+42 added-3 removed
11 unmodified lines12 import { PANE_SCROLLER } from "../../../features/code/diff-pane.tsx";13 import { SPLIT_QUERY, useMedia } from "../../../features/code/media.ts";14 import { CodeNotFound } from "../../../features/code/not-found.tsx";15 import { PlainDiff } from "../../../features/code/plain-diff.tsx";16+import { prerenderedPaths } from "../../../features/code/prerender.ts";17 import { pageHead } from "../../../features/shared/head.ts";18 import { notFoundFor } from "../../../features/shared/refusals.ts";19 import { branchPage } from "../../../server/cache-headers.ts";20 import { serverClient } from "../../../server/client.ts";2 unmodified lines23 import { FilesButton } from "../tree/-files-button.tsx";24 25 // One commit and what it changed, read on the server, with the territory26 // of the ask it answered (the diff's stats split by it): the page arrives26-// with the landing and the diff as plain text, and the browser draws the27-// diff over it, the changed files as a tree in the rail. A commit never27+// with the landing and the diff, its first files highlighted where the28+// server highlights them (`features/code/prerender.ts`) and the rest as29+// plain text, and the browser's drawing then takes its place, the changed30+// files as a tree in the rail. A commit never31 // changes, but its page carries its landing, which the project records32 // after main has moved, and times reckoned from the read: a browser keeps33 // it briefly, as a page at `main`. Within a visit the router keeps what it34 // read, so a change of layout never reads the diff again.67 unmodified lines102 // Each file parsed once for the page: the head's stats, the plain text103 // and the folds all read this.104 const drawn = useMemo(() => drawnFiles(diff.files), [diff.files]);105 106+ // The files the server sends highlighted: the same on both sides, since107+ // both decide from the diff alone.108+ const prerendered = useMemo(() => prerenderedPaths(drawn), [drawn]);109+110 const defaults = useMemo(111 () =>112 new Set(113 drawn.filter(({ folded }) => folded).map(({ file }) => file.path)51 unmodified lines165 drawn={drawn}166 files={diff.files}167 folded={folded}168 onFold={onFold}169+ prerendered={prerendered}170 split={split}171 />172 </div>173 }24 unmodified lines198 // so a unified diff's address carries no `style`.199 validateSearch: (search: { readonly style?: unknown }) => ({200 style: search.style === "split" ? ("split" as const) : undefined,201 }),194- loader: ({ params }) => commitPage({ data: params }),202+ loader: ({ params }) => {203+ const page = commitPage({ data: params });204+205+ // A document's first files are highlighted on the server before the206+ // page renders, so the render waits for nothing and sends them so.207+ // Imported here, not at the top: a loader stays in the chunks every208+ // page preloads, and the browser's build drops this branch whole.209+ // A failed read rejects as it would have (the router's not-found).210+ return import.meta.env.SSR211+ ? Effect.runPromise(212+ Effect.gen(function* () {213+ const data = yield* Effect.promise(() => page);214+215+ const decoded = yield* Schema.decodeEffect(CommitPageData)(216+ data217+ ).pipe(Effect.option);218+219+ if (Option.isSome(decoded) && !decoded.value.diff.truncated) {220+ const { drawDiffAhead } = yield* Effect.promise(221+ () => import("../../../features/code/prerender.ts")222+ );223+224+ yield* Effect.promise(() =>225+ drawDiffAhead(decoded.value.diff.files)226+ );227+ }228+229+ return data;230+ })231+ )232+ : page;233+ },234 // The diff never changes: a layout change (`?style=split`) rewrites the235 // address, and must not read it again.236 staleTime: Number.POSITIVE_INFINITY,237 headers: () => branchPage,5 unmodified linesadded:apps/web/src/server/pierre-themes.ts+57 added
1+/**2+ * `@pierre/theming/themes` as the web Worker bundles it (`vite.config.ts`3+ * resolves it here for the Worker): no theme collection. The package's4+ * collections map every Pierre and Shiki theme to a dynamic import, about5+ * 1.7 MB the Worker's build would carry; the server draws in the token6+ * theme alone, which `features/code/prerender-server.ts` attaches itself.7+ * So the collections here hold nothing, and `createTheme` normalizes a8+ * theme as the package's does.9+ */10+import { Effect } from "effect";11+import { normalizeTheme } from "shiki/core";12+import type {13+ ThemeRegistrationAny,14+ ThemeRegistrationResolved,15+} from "shiki/core";16+17+/** A theme as a collection holds it: its name, and its loader. */18+interface Descriptor {19+ readonly name: string;20+ readonly load: () => Promise<ThemeRegistrationResolved>;21+}22+23+/** A collection with no themes in it. */24+const empty = {25+ getTheme: (_name: string): Descriptor | undefined => undefined,26+ getThemes: (): readonly Descriptor[] => [],27+};28+29+export const pierreThemes = empty;30+31+export const shikiThemes = empty;32+33+export const themes = empty;34+35+/** A module's theme, whether it is the module or its default export. */36+const unwrap = (37+ loaded: ThemeRegistrationAny | { default: ThemeRegistrationAny }38+) => ("default" in loaded ? loaded.default : loaded);39+40+/** A named theme whose loader hands it over normalized, as Shiki draws with it. */41+export const createTheme = ({42+ load,43+ name,44+}: {45+ readonly name: string;46+ readonly load: () => Promise<47+ ThemeRegistrationAny | { default: ThemeRegistrationAny }48+ >;49+}): Descriptor => ({50+ load: () =>51+ Effect.runPromise(52+ Effect.promise(load).pipe(53+ Effect.map((loaded) => normalizeTheme(unwrap(loaded)))54+ )55+ ),56+ name,57+});added:apps/web/src/server/shiki.ts+59 added
1+/**2+ * `shiki` as the web Worker bundles it (`vite.config.ts` resolves the3+ * Worker's `shiki` here): Shiki's core and its JavaScript regex engine,4+ * with no bundled grammar or theme and no WebAssembly.5+ *6+ * The package's own entry maps every grammar and theme to a dynamic7+ * import, about 10 MB the Worker's build would carry, and its Oniguruma8+ * engine compiles WebAssembly, which a Worker may not. `@pierre/diffs`9+ * imports both from `shiki`; it reaches neither on the server, where the10+ * few grammars the server highlights in are loaded and attached by11+ * `features/code/prerender-server.ts`. So here the bundled maps are empty,12+ * and asking for Oniguruma fails.13+ */14+import {15+ createBundledHighlighter,16+ createSingletonShorthands,17+ guessEmbeddedLanguages,18+} from "shiki/core";19+import type {20+ DynamicImportLanguageRegistration,21+ DynamicImportThemeRegistration,22+ RegexEngine,23+} from "shiki/core";24+import { createJavaScriptRegexEngine } from "shiki/engine/javascript";25+26+export * from "shiki/core";27+28+export { createJavaScriptRegexEngine } from "shiki/engine/javascript";29+30+/** No grammar is bundled by name; each is attached where it is used. */31+export const bundledLanguages: Record<32+ string,33+ DynamicImportLanguageRegistration34+> = {};35+36+/** No theme is bundled by name; the token theme is attached where it is used. */37+export const bundledThemes: Record<string, DynamicImportThemeRegistration> = {};38+39+/** Oniguruma compiles WebAssembly, which a Worker may not: never on the server. */40+export const createOnigurumaEngine = (): Promise<RegexEngine> =>41+ Promise.reject(42+ new Error("The Worker highlights with the JavaScript engine only")43+ );44+45+export const createHighlighter = createBundledHighlighter<string, string>({46+ engine: () => createJavaScriptRegexEngine(),47+ langs: bundledLanguages,48+ themes: bundledThemes,49+});50+51+export const {52+ codeToHast,53+ codeToHtml,54+ codeToTokens,55+ codeToTokensBase,56+ codeToTokensWithThemes,57+ getLastGrammarState,58+ getSingletonHighlighter,59+} = createSingletonShorthands(createHighlighter, { guessEmbeddedLanguages });modified:apps/web/test/code-client.test.tsx+3 added-2 removed
3 unmodified lines4 * `@pierre/diffs` (`<diffs-container>`), a commit's diff by its `CodeView`5 * (which draws nothing until it mounts, so its server markup is its6 * marked host alone; `code.test.tsx` holds the plain text it replaces), and7 * the repo's file tree by `@pierre/trees` (`<file-tree-container>`). The8- * pages import these only behind `ClientOnly` and a lazy import, so the9- * Worker never bundles them.8+ * pages import these only through a dynamic import the Worker's build9+ * drops, so the Worker never bundles them (the server's own highlighting10+ * is `code-prerender.test.tsx`'s).11 *12 * The tree moves the page through the router: choosing a file calls the13 * page's own `onOpen`, never `location.assign`, so the document stays.14 */139 unmodified linesadded:apps/web/test/code-prerender.test.tsx+369 added
1+/**2+ * Code the server sends highlighted (ADR 0027): a blob page's file and a3+ * commit page's first files, drawn by `@pierre/diffs/ssr` into a4+ * declarative shadow root, in a fixed set of languages and within the5+ * server's own limit; anything else is sent as plain text, as before.6+ *7+ * Each page is rendered as its route renders it on the server: the loader8+ * draws the code ahead (`drawFileAhead`, `drawDiffAhead`), then the page9+ * renders with the browser's drawing (`ClientFile`, `ClientDiffs`) holding10+ * the server's fallback, which is all a server render shows.11+ */12+import { describe, expect, it } from "@effect/vitest";13+import { ChangedFile, CommitDiff, FileView } from "@repo/protocol/domain/code";14+import { ProjectName } from "@repo/protocol/ids";15+import { DateTime, Effect, Schema } from "effect";16+import { renderToStaticMarkup } from "react-dom/server";17+18+import { BlobView } from "../src/features/code/blob-view.tsx";19+import { ClientDiffs, ClientFile } from "../src/features/code/client-code.tsx";20+import { CommitView } from "../src/features/code/commit-view.tsx";21+import { drawnFiles } from "../src/features/code/diff-model.ts";22+import { PlainDiff } from "../src/features/code/plain-diff.tsx";23+import { prerenderFile } from "../src/features/code/prerender-server.ts";24+import {25+ drawDiffAhead,26+ drawFileAhead,27+ prerenderedPaths,28+ prerendersFile,29+ SERVER_FILES,30+ SERVER_LINES,31+} from "../src/features/code/prerender.ts";32+import { FileFallback } from "../src/features/code/server-code.tsx";33+34+const datekit = ProjectName.make("datekit");35+36+const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");37+38+const AT = "a".repeat(40);39+40+const decodeFile = Schema.decodeSync(FileView);41+42+const decodeFiles = Schema.decodeSync(Schema.Array(ChangedFile));43+44+/** A highlighted token, as Pierre draws one in the token theme. */45+const TOKEN = /--diffs-token-light:var\(--diffs-token-[a-z-]+/gu;46+47+/** How many highlighted tokens `markup` holds. */48+const tokensIn = (markup: string) => [...markup.matchAll(TOKEN)].length;49+50+/** How many server drawings `markup` holds. */51+const shadowRootsIn = (markup: string) =>52+ [...markup.matchAll(/<template shadowrootmode="open">/gu)].length;53+54+const TYPESCRIPT = [55+ 'import { fromIso } from "./iso.ts";',56+ "",57+ "/** A date from an ISO week string. */",58+ "export const parse = (text: string): Date => fromIso(text);",59+ "",60+].join("\n");61+62+/** `count` lines of TypeScript. */63+const linesOf = (count: number) =>64+ Array.from(65+ { length: count },66+ (_, index) => `export const n${index} = ${index};`67+ ).join("\n");68+69+let blobs = 0;70+71+/** A file at `path`, with a blob id of its own, so no drawing is shared. */72+const fileAt = (path: string, text: string) => {73+ blobs += 1;74+75+ return decodeFile({76+ at: AT,77+ binary: false,78+ path,79+ sha: blobs.toString(16).padStart(40, "0"),80+ size: text.length,81+ text,82+ truncated: false,83+ });84+};85+86+/** The blob page's markup for `file`, as the server renders it once its loader has drawn the file. */87+const blobPage = (file: FileView) =>88+ Effect.gen(function* () {89+ yield* Effect.promise(() => drawFileAhead(file));90+91+ const text = file.text ?? "";92+93+ return renderToStaticMarkup(94+ <BlobView95+ code={96+ <ClientFile97+ fallback={98+ <FileFallback path={file.path} sha={file.sha} text={text} />99+ }100+ path={file.path}101+ sha={file.sha}102+ text={text}103+ />104+ }105+ file={file}106+ now={now}107+ project={datekit}108+ rev="main"109+ />110+ );111+ });112+113+const signature = {114+ at: "2026-10-06T15:00:00.000Z",115+ email: "lin@example.com",116+ name: "Lin",117+};118+119+/** A commit changing `files`, imported (no landing). */120+const commitOf = (files: readonly (typeof ChangedFile.Encoded)[]) =>121+ Schema.decodeSync(CommitDiff)({122+ commit: {123+ author: signature,124+ body: "",125+ committer: signature,126+ parents: ["2".repeat(40)],127+ sha: "1".repeat(40),128+ subject: "Parse ISO weeks",129+ trailers: [],130+ tree: "4".repeat(40),131+ },132+ files,133+ truncated: false,134+ });135+136+/** The commit page's markup, as the server renders it once its loader has drawn the first files. */137+const commitPage = (diff: CommitDiff) =>138+ Effect.gen(function* () {139+ const drawn = drawnFiles(diff.files);140+141+ yield* Effect.promise(() => drawDiffAhead(diff.files));142+143+ return renderToStaticMarkup(144+ <CommitView145+ diff={diff}146+ drawing={147+ <ClientDiffs148+ fallback={149+ <PlainDiff150+ drawn={drawn}151+ files={diff.files}152+ prerendered={prerenderedPaths(drawn)}153+ />154+ }155+ files={diff.files}156+ split={false}157+ />158+ }159+ drawn={drawn}160+ now={now}161+ project={datekit}162+ />163+ );164+ });165+166+/** The markup of one file's section of a diff. */167+const sectionOf = (markup: string, path: string) =>168+ new RegExp(169+ `<section aria-label="${path.replaceAll(".", "\\.")}"[\\s\\S]*?</section>`,170+ "u"171+ ).exec(markup)?.[0] ?? "";172+173+/** An added file at `path`, `lines` long, with a blob id of its own. */174+const added = (path: string, lines: number) => {175+ blobs += 1;176+177+ return {178+ after: blobs.toString(16).padStart(40, "0"),179+ binary: false,180+ newText: linesOf(lines),181+ path,182+ status: "added" as const,183+ };184+};185+186+describe("a blob page's code, as the server sends it", () => {187+ it.effect(188+ "holds a TypeScript file highlighted, in a declarative shadow root",189+ () =>190+ Effect.gen(function* () {191+ const markup = yield* blobPage(fileAt("src/parse.ts", TYPESCRIPT));192+193+ expect(shadowRootsIn(markup)).toBe(1);194+ expect(markup).toContain('data-code="prerendered"');195+ expect(markup).toContain("<diffs-container");196+ expect(tokensIn(markup)).toBeGreaterThan(5);197+ expect(markup).not.toContain('data-code="plain"');198+ })199+ );200+201+ it.effect(202+ "holds a file in a language the server does not highlight as numbered plain text",203+ () =>204+ Effect.gen(function* () {205+ const markup = yield* blobPage(206+ fileAt("src/parse.rs", "fn parse() -> u32 {\n 1\n}\n")207+ );208+209+ expect(shadowRootsIn(markup)).toBe(0);210+ expect(tokensIn(markup)).toBe(0);211+ expect(markup).toContain('data-code="plain"');212+ expect(markup).toContain('id="L1"');213+ })214+ );215+216+ it.effect(217+ "holds a file past the server's limit as plain text: too many lines, or a line too long",218+ () =>219+ Effect.gen(function* () {220+ const long = yield* blobPage(221+ fileAt("src/long.ts", linesOf(SERVER_LINES + 1))222+ );223+224+ const wide = yield* blobPage(225+ fileAt("src/wide.ts", `export const wide = "${"x".repeat(1000)}";\n`)226+ );227+228+ const within = yield* blobPage(229+ fileAt("src/within.ts", linesOf(SERVER_LINES))230+ );231+232+ expect([long, wide, within].map(shadowRootsIn)).toStrictEqual([233+ 0, 0, 1,234+ ]);235+ expect(long).toContain('data-code="plain"');236+ expect(wide).toContain('data-code="plain"');237+ })238+ );239+});240+241+describe("a commit page's diff, as the server sends it", () => {242+ it.effect(243+ "holds a TypeScript file's changes highlighted, and an unknown language's as plain lines",244+ () =>245+ Effect.gen(function* () {246+ const markup = yield* commitPage(247+ commitOf([248+ {249+ after: "a".repeat(40),250+ before: "b".repeat(40),251+ binary: false,252+ newText: TYPESCRIPT.replace(253+ "fromIso(text)",254+ "fromIso(text.trim())"255+ ),256+ oldText: TYPESCRIPT,257+ path: "src/parse.ts",258+ status: "modified",259+ },260+ {261+ after: "c".repeat(40),262+ binary: false,263+ newText: "fn week() -> u32 {\n 1\n}\n",264+ path: "src/week.rs",265+ status: "added",266+ },267+ ])268+ );269+270+ const typescript = sectionOf(markup, "src/parse.ts");271+ const rust = sectionOf(markup, "src/week.rs");272+273+ expect(shadowRootsIn(typescript)).toBe(1);274+ expect(tokensIn(typescript)).toBeGreaterThan(5);275+ expect(shadowRootsIn(rust)).toBe(0);276+ expect(rust).toContain('data-line-type="addition"');277+ expect(rust).toContain("fn week() -> u32 {");278+ })279+ );280+});281+282+describe("which code the server highlights", () => {283+ it("highlights its languages by Pierre's names for them, and no other", () => {284+ const highlighted = [285+ "a.ts",286+ "a.tsx",287+ "a.js",288+ "a.mjs",289+ "a.cjs",290+ "a.jsx",291+ "a.json",292+ "a.md",293+ "a.yaml",294+ "a.yml",295+ "a.toml",296+ "a.sh",297+ "a.css",298+ "a.html",299+ ];300+301+ expect(302+ highlighted.filter((path) => !prerendersFile({ path, text: "x" }))303+ ).toStrictEqual([]);304+ expect(305+ ["a.rs", "a.py", "Makefile", "a.go", "a.txt"].filter((path) =>306+ prerendersFile({ path, text: "x" })307+ )308+ ).toStrictEqual([]);309+ });310+311+ it.effect("has a grammar for each of its languages, aliases included", () =>312+ Effect.gen(function* () {313+ const samples = {314+ "a.css": "a { color: red; }",315+ "a.html": '<p class="x">hi</p>',316+ "a.js": "const a = 1;",317+ "a.json": '{ "a": 1 }',318+ "a.jsx": "const a = <p>hi</p>;",319+ "a.md": "See [the docs](https://example.com).",320+ "a.sh": 'echo "hi"',321+ "a.toml": 'a = "b"',322+ "a.ts": "const a: number = 1;",323+ "a.tsx": "const a = <p>{1}</p>;",324+ "a.yaml": "a: b",325+ "a.yml": "a: b",326+ };327+328+ const drawn = yield* Effect.forEach(329+ Object.entries(samples),330+ ([path, text]) =>331+ prerenderFile({ path, sha: `grammar:${path}`, text }).pipe(332+ Effect.map((html) => [path, tokensIn(html ?? "") > 0] as const)333+ )334+ );335+336+ expect(drawn.filter(([, highlighted]) => !highlighted)).toStrictEqual([]);337+ })338+ );339+340+ it("highlights a diff's first open files within its lines, never a folded one", () => {341+ // `a` is folded (an added file past 80 lines starts so); `b` and `c`342+ // fit together; `d` would pass the limit; `e` still fits after it.343+ const drawn = drawnFiles(344+ decodeFiles([345+ added("a.ts", 90),346+ added("b.ts", 60),347+ added("c.ts", 60),348+ added("d.ts", SERVER_LINES),349+ added("e.ts", 10),350+ ])351+ );352+353+ expect([...prerenderedPaths(drawn)]).toStrictEqual([354+ "b.ts",355+ "c.ts",356+ "e.ts",357+ ]);358+359+ const many = drawnFiles(360+ decodeFiles(361+ Array.from({ length: SERVER_FILES + 2 }, (_, index) =>362+ added(`f${index}.ts`, 1)363+ )364+ )365+ );366+367+ expect(prerenderedPaths(many).size).toBe(SERVER_FILES);368+ });369+});modified:apps/web/test/production-bundle.test.ts+93 added-2 removed
8 unmodified lines9 * `PLATFORM`; and nothing in it comes from the dev world: no `src/dev/`10 * module, no memory adapter, no seed, no dev sign-in and no test kit.11 *12 * Its root route, whose chunks every page preloads, carries no Markdown13- * renderer and stays under a size ceiling, and the hashed assets it serves14- * are kept by browsers for good (`public/_headers`).13+ * renderer, no grammar and nothing of the server's highlighting, and stays14+ * under a size ceiling, and the hashed assets it serves are kept by15+ * browsers for good (`public/_headers`). The Worker bundles the grammars16+ * it highlights in and no others, none on its entry, and no theme17+ * collection or WebAssembly (ADR 0027).18 *19 * Modules are read from the build's source maps (each map's `sources`),20 * strings from every other file it wrote. The Cloudflare plugin rewrites21 * `.wrangler/deploy/config.json` at each build to point at its output; the44 unmodified lines66 * in 31 before).67 */68 const ROOT_PRELOADS_GZIP = 244_000;69 70+/** A Shiki grammar module, by its name. */71+const GRAMMAR = /node_modules\/@shikijs\/langs\/dist\/(?<name>[\w-]+)\.mjs$/u;72+73+/**74+ * The grammars the Worker highlights in (`features/code/prerender-server.ts`,75+ * ADR 0027), by Shiki's module names: HTML brings JavaScript and CSS with it.76+ */77+const SERVER_GRAMMARS = [78+ "css",79+ "html",80+ "javascript",81+ "json",82+ "jsx",83+ "markdown",84+ "shellscript",85+ "toml",86+ "tsx",87+ "typescript",88+ "yaml",89+];90+91+/** Whether a file's modules hold the server's highlighting. */92+const drawing = (held: readonly string[]) =>93+ held.some((module) => module.endsWith("features/code/prerender-server.ts"));94+95 /** Files whose bytes are not text: fonts and images. */96 const BINARY = /\.(?:ico|png|woff2)$/u;97 98 const decodeSourceMap = Schema.decodeUnknownEffect(304 unmodified lines403 }).toStrictEqual({ markdown: [], missing: [], underCeiling: true });404 })405 );406 407+ it.effect(408+ "preloads on every page no grammar and nothing of the server's highlighting",409+ () =>410+ Effect.gen(function* () {411+ const output = yield* Built;412+413+ expect(414+ rootPreloads(output).flatMap((chunk) =>415+ (output.holding.get(`client${chunk}`) ?? []).filter(416+ (module) => GRAMMAR.test(module) || module.includes("prerender")417+ )418+ )419+ ).toStrictEqual([]);420+421+ // The server's highlighting is the Worker's alone.422+ expect({423+ browser: [...output.holding].flatMap(([at, held]) =>424+ at.startsWith("client/") && drawing(held) ? [at] : []425+ ),426+ worker: [...output.holding].some(427+ ([at, held]) => at.startsWith("server/") && drawing(held)428+ ),429+ }).toStrictEqual({ browser: [], worker: true });430+ })431+ );432+433+ it.effect(434+ "bundles into the Worker its few grammars alone, off its entry, and no theme collection or WebAssembly",435+ () =>436+ Effect.gen(function* () {437+ const output = yield* Built;438+439+ const server = [...output.holding].filter(([at]) =>440+ at.startsWith("server/")441+ );442+443+ const grammars = new Set(444+ server.flatMap(([, held]) =>445+ held.flatMap((module) => {446+ const name = GRAMMAR.exec(module)?.groups?.name;447+448+ return name === undefined ? [] : [name];449+ })450+ )451+ );452+453+ expect([...grammars].toSorted()).toStrictEqual(SERVER_GRAMMARS);454+ expect(455+ server.flatMap(([at, held]) =>456+ held.filter(457+ (module) =>458+ module.includes("node_modules/@shikijs/themes/") ||459+ module.includes("node_modules/@pierre/theme/") ||460+ module.includes("node_modules/@shikijs/engine-oniguruma/") ||461+ (at === "server/index.js" &&462+ (GRAMMAR.test(module) ||463+ module.includes("features/code/prerender-server.ts")))464+ )465+ )466+ ).toStrictEqual([]);467+ })468+ );469+470 it.effect("tells browsers to keep the hashed assets for good", () =>471 Effect.gen(function* () {472 const output = yield* Built;473 7 unmodified linesmodified:apps/web/vite.config.ts+37 added
1+import { fileURLToPath } from "node:url";2+3 import { cloudflare } from "@cloudflare/vite-plugin";4 import tailwindcss from "@tailwindcss/vite";5 import { tanstackStart } from "@tanstack/react-start/plugin/vite";6 import viteReact from "@vitejs/plugin-react";28 unmodified lines35 },36 name: "web-app-manifest",37 });38 39+/** Shiki's WebAssembly, as the Worker's build resolves it: nothing. */40+const NO_WASM = "\0worker-no-shiki-wasm";41+42+/** What the Worker's build resolves in place of a package entry, by the entry. */43+const WORKER_IN_PLACE = new Map([44+ ["@pierre/theming/themes", "src/server/pierre-themes.ts"],45+ ["shiki", "src/server/shiki.ts"],46+]);47+48+/**49+ * The Worker's Shiki: core and the JavaScript engine alone50+ * (`src/server/shiki.ts`), with no theme collection51+ * (`src/server/pierre-themes.ts`), so the server's highlighting bundles52+ * only the grammars it names: never Shiki's map of every grammar (about53+ * 10 MB) and theme, Pierre's themes, or Shiki's WebAssembly, which a54+ * Worker cannot compile. The browser's build keeps the whole packages;55+ * their grammars and themes are chunks fetched only when used.56+ */57+const workerShiki = (): Plugin => ({58+ applyToEnvironment: (environment) => environment.name === "ssr",59+ enforce: "pre",60+ load: (id) => (id === NO_WASM ? "export default undefined;" : undefined),61+ name: "worker-shiki",62+ resolveId: (id) => {63+ const inPlace = WORKER_IN_PLACE.get(id);64+65+ if (inPlace !== undefined) {66+ return fileURLToPath(new URL(inPlace, import.meta.url));67+ }68+69+ return id === "shiki/wasm" ? NO_WASM : undefined;70+ },71+});72+73 // The Cloudflare framework guide's order: the Worker runs TanStack Start's74 // SSR environment, and Start comes before React. `vite build` picks the75 // stage from `CLOUDFLARE_ENV` (infra/deploy.ts sets it).76 export default defineConfig(({ mode }) => {20 unmodified lines97 tailwindcss(),98 tanstackStart(),99 viteReact(),100 webAppManifest(),101+ workerShiki(),102 ],103 // shadcn's components import through `@/` (components.json), which104 // tsconfig.json's `paths` maps to `src/`.105 resolve: { tsconfigPaths: true },8 unmodified linesmodified:docs/adr/0019-the-web-reads-repos-through-public-contracts.md+2 added
2 unmodified lines3 ---4 5 # The web reads a project's code through public contracts the platform serves6 7+> **Superseded in part (2026-10-10).** Code is no longer drawn in the browser only. ADR 0027 records that the web Worker highlights a blob page's file and a commit page's first files on the server, in a fixed set of languages and within its own limit, and that the browser's drawing takes their place once it can draw the same code at once. The tree is still drawn in the browser only. The record below is kept as it was decided.8+9 The web's code browser (tree, file, raw bytes, log, commit, refs, and why each line is there) reads only through public, read-only contracts on `/rpc`. The platform Worker serves them over its existing `RepoHost` on the public Artifacts namespace. The logic lives in one host-free module, `@repo/project/code`, which the platform's handlers and the web's offline dev world both call. No payload names a repo. Each names a project, and the module reads that project's canonical repo only, never a fork or a layer. A revision is `main` (the project's landed SHA, from its record and never from a ref), a full commit SHA in the canonical repo, or a tag name matched exactly against the port's tag list, never joined into a ref path. Every answer names the commit it resolved, so any page becomes a permalink.10 11 ## Considered Options12 16 unmodified linesadded:docs/adr/0027-code-is-highlighted-on-the-server-in-a-fixed-set-of-languages.md+31 added
1+---2+status: accepted3+---4+5+# Code is highlighted on the server in a fixed set of languages6+7+This amends ADR 0019, which drew code in the browser only. A blob page's file and a commit page's first files now arrive highlighted in the document: the web Worker draws them with `@pierre/diffs/ssr`, using the browser's own options (`apps/web/src/features/code/pierre.ts`), and sends each drawing as a declarative shadow root on Pierre's `diffs-container`. The browser paints it with the document, before any script. The browser's own drawing (`File`, or the commit's `CodeView`) still takes over, with line selection, the address's `#L` and the worker pool, but only once it is ready to draw the same code highlighted at once: its module loaded, the pool up, and the code highlighted in the pool first (`prepareFile`, `prepareDiffs`). It then replaces the server's drawing in one render (`apps/web/src/features/code/client-code.tsx`), with every line in the same place. Code the server does not highlight still arrives as plain text and changes once, to highlighted.8+9+The server highlights only within its own limits (`apps/web/src/features/code/prerender.ts`):10+11+- **Languages.** TypeScript, TSX, JavaScript (with `.mjs` and `.cjs`), JSX, JSON, Markdown, YAML, TOML, shell, CSS and HTML, by the names Pierre gives a file's type. Any other language is sent as numbered plain text, as before, and the browser highlights it.12+- **Lines.** At most 400 lines a page. A diff counts both sides, since Pierre highlights both whole files. A commit page considers at most its first 8 files that start open (an added or deleted file past 80 lines starts folded), the ones a reader sees first. `CodeView` highlights the rest as they scroll into view.13+- **The drawing's own limits.** A file past `tokenizeMaxLength`, or with any line past `tokenizeMaxLineLength` (1,000, the same as `maxLineDiffLength`), is sent plain, so a minified file is never tokenized on the server.14+15+Both sides decide from the page's own data, so the browser knows which code arrived highlighted without being told. The Worker runs Shiki's JavaScript regex engine, since a Worker may not compile WebAssembly. Its build resolves `shiki` to core alone (`apps/web/src/server/shiki.ts`) and `@pierre/theming/themes` to an empty collection (`apps/web/src/server/pierre-themes.ts`), through a plugin in `apps/web/vite.config.ts`. So it bundles the eleven grammars it names, as chunks off its entry, and no other grammar, theme or WebAssembly. Pierre will not resolve a grammar or a theme by name in a Worker's global scope (`isWorkerContext`), and `registerCustomLanguage` only registers a loader for that resolution. The server therefore loads each grammar and the token theme itself and attaches them to Pierre's shared highlighter (`apps/web/src/features/code/prerender-server.ts`).16+17+## Considered Options18+19+- **Keep drawing in the browser only** (ADR 0019 as it stood). The plain text already matched Pierre's measures, so nothing moved. But the code changed colour after hydration, and that swap was the largest paint on code pages.20+- **Highlight on the platform and keep the HTML in R2.** Each drawing would be made once for good. But it would need a new public read for the HTML, and every Worker reading it would take a hop on every code page.21+- **Every grammar on the server.** About 10.7 MB of grammars, far past the web's byte budget.22+- **Ship the HTML in the loader's data.** The browser could then adopt it on any page, but the document would carry every drawing twice: once as markup and once as a string in the router's state. Instead the loader draws the code ahead, the drawing is kept by its blob ids until the render reads it, and the browser needs nothing but the markup.23+24+## Consequences25+26+- **Bytes.** The web Worker's JavaScript grows from 1,528,378 to 2,773,744 bytes (budget 4,075,000), about 940 KB of it grammars. Its entry stays at 308,418 (budget 801,000): the grammars and `@pierre/diffs/ssr` load by dynamic import on a page's first highlighted code. `apps/web/test/production-bundle.test.ts` holds the Worker to exactly these grammars, none on its entry, and no theme collection or Oniguruma. It also holds the chunks every page preloads to no grammar and nothing of this module.27+- **CPU.** Measured in the dev world's workerd, highlighting TypeScript takes about 0.14 ms a line warm: 2,400 lines about 315 ms, 600 about 85 ms, 400 about 57 ms, 100 about 18 ms. A fresh isolate's first 400-line file took 180 ms, which includes making the highlighter and compiling the grammar. 2,400 lines would cost hundreds of milliseconds, so the server's limit is 400 lines, well below the browser's.28+- **Document size.** A highlighted line costs about 700 to 1,600 bytes of markup, depending on how many tokens it holds: a 400-line TypeScript file is about 640 KB. Each drawing also carries Pierre's stylesheet and icons (about 48 KB). Both compress well: an 11-line file's page is 100 KB raw and 16 KB gzipped.29+- **Cache.** The drawings are kept in the isolate (`prerender.ts`): at most 24, and 8,000,000 characters of HTML, keyed by blob ids and path, which never change what they name. A file read again is not drawn again. A loader that finds its drawing evicted before the render makes it again, and the render streams it.30+- **The page.** A page reached by a link, not loaded, has no server drawing. It shows the plain text, which the browser's drawing then replaces. A split diff (`?style=split` on a wide screen) is plain until drawn, as before, since the server draws unified only.31+- **Without script.** A highlighted file has no `#L` anchors: Pierre's lines live in a shadow root, which a fragment cannot reach. Plain text keeps its anchors.modified:packages/config/test/web-wiring.test.ts+1 added-1 removed
249 unmodified lines250 it("holds each Worker it measures to limits of its own", () => {251 expect(budgets).toStrictEqual({252 "apps/platform": { entry: 1_900_000, javascript: 1_900_000 },253 "apps/sandbox": { entry: 656_000, javascript: 656_000 },254- "apps/web": { entry: 801_000, javascript: 4_075_000 },254+ "apps/web": { entry: 356_000, javascript: 3_191_000 },255 });256 expect(Object.keys(budgets).toSorted()).toStrictEqual(257 workers.map(({ dir }) => dir).toSorted()258 );23 unmodified linesmodified:scripts/startup-budget.ts+8 added-2 removed
42 unmodified lines43 * browser as an app, no limit was raised: the platform's entry measured44 * 1,693,131 (1,900,000, 12%), the sandbox's 570,831 (656,000, 15%), the45 * web's JavaScript 4,074,781 (4,075,000: no room left, until the server46 * build is minified) and the web's entry 696,419, which fell, so its limit47- * is tightened to 801,000 (15%).47+ * is tightened to 801,000 (15%). Minifying the web's server build took48+ * its JavaScript to 1,528,378 and its entry to 308,418. Highlighting code49+ * on the server (ADR 0027) then added its grammars and `@pierre/diffs/ssr`50+ * as chunks off the entry, with no limit raised. Once Workers Cache's51+ * entry had landed beside them, the web's JavaScript measured 2,774,68952+ * and its entry 309,341, so its limits are tightened to 3,191,000 and53+ * 356,000 (15%).54 */55 import { BunRuntime, BunServices } from "@effect/platform-bun";56 import { Console, Data, Effect, FileSystem, Path, pipe } from "effect";57 import { ChildProcess, ChildProcessSpawner } from "effect/process";7 unmodified lines65 /** Each Worker's limits, by its folder. */66 export const budgets = {67 "apps/platform": { entry: 1_900_000, javascript: 1_900_000 },68 "apps/sandbox": { entry: 656_000, javascript: 656_000 },63- "apps/web": { entry: 801_000, javascript: 4_075_000 },69+ "apps/web": { entry: 356_000, javascript: 3_191_000 },70 } as const satisfies Record<string, Budget>;71 72 /**73 * Each Worker, the file its `main` bundles to, and the build a dry run needs131 unmodified lines