Skip to content
Myr

prerender.ts

This file

Path

apps/web/src/features/code/prerender.ts

222 lines · 5.5 KiB · TypeScript

Last changed by

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

History of this file

Take it

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

line 1why, one step back
1/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 2–3why, one step back
2 * The server and the browser decide alike from the page's own data, so the
3 * browser knows which code arrived highlighted without being told.

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 4–29why, one step back
4 */
5import { getFiletypeFromFileName } from "@pierre/diffs";6import type { ChangedFile } from "@repo/protocol/domain/code";7import { Effect, Option } from "effect";89import { drawnFiles } from "./diff-model.ts";10import type { DrawnFile } from "./diff-model.ts";11import { diffsOptions } from "./pierre.ts";1213export const SERVER_LANGUAGES = [14 "css",15 "html",16 "javascript",17 "json",18 "jsx",19 "markdown",20 "toml",21 "tsx",22 "typescript",23 "yaml",24 "yml",25 "zsh",26] as const;2728export type ServerLanguage = (typeof SERVER_LANGUAGES)[number];29

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

line 30why, one step back
30/** Measured warm in workerd: 400 lines of TypeScript took about 57 ms. */

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 31–99why, one step back
31export const SERVER_LINES = 400;
3233export const SERVER_FILES = 8;3435const isServerLanguage = (name: string): name is ServerLanguage =>36 SERVER_LANGUAGES.some((language) => language === name);3738export const serverLanguageOf = (39 path: string40): Option.Option<ServerLanguage> => {41 const name = getFiletypeFromFileName(path);4243 return isServerLanguage(name) ? Option.some(name) : Option.none();44};4546const linesWithin = (text: string): Option.Option<number> => {47 const lines = text.split("\n");4849 return lines.every(50 (line) => line.length <= diffsOptions.tokenizeMaxLineLength51 )52 ? Option.some(lines.length)53 : Option.none();54};5556export const prerendersFile = (file: {57 readonly path: string;58 readonly text: string;59}) =>60 Option.isSome(serverLanguageOf(file.path)) &&61 file.text.length <= diffsOptions.tokenizeMaxLength &&62 Option.exists(linesWithin(file.text), (lines) => lines <= SERVER_LINES);6364const diffLines = (drawn: DrawnFile): Option.Option<number> => {65 const sides = [drawn.file.oldText, drawn.file.newText].flatMap((text) =>66 text === undefined ? [] : [linesWithin(text)]67 );6869 return Option.all(sides).pipe(70 Option.map((counts) => counts.reduce((sum, count) => sum + count, 0))71 );72};7374export const prerenderedPaths = (75 drawn: readonly DrawnFile[]76): ReadonlySet<string> => {77 const paths = new Set<string>();78 let spent = 0;7980 const open = drawn81 .filter((file) => !file.folded && Option.isSome(file.diff))82 .slice(0, SERVER_FILES);8384 for (const file of open) {85 const lines = diffLines(file);8687 if (88 Option.isSome(serverLanguageOf(file.file.path)) &&89 Option.isSome(lines) &&90 spent + lines.value <= SERVER_LINES91 ) {92 spent += lines.value;93 paths.add(file.file.path);94 }95 }9697 return paths;98};99

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

line 100why, one step back
100/** Settled ones say so, so a render never waits on them. */

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 101–142why, one step back
101type Drawing = Promise<string | undefined> & {
102 status?: "fulfilled";103 value?: string | undefined;104};105106const KEPT = { count: 24, size: 8_000_000 } as const;107108const kept = new Map<string, { readonly drawing: Drawing; size: number }>();109110const sizeOf = () =>111 [...kept.values()].reduce((sum, entry) => sum + entry.size, 0);112113const trim = () => {114 for (const id of kept.keys()) {115 if (kept.size <= KEPT.count && sizeOf() <= KEPT.size) {116 return;117 }118119 kept.delete(id);120 }121};122123const keptDrawing = <E>(124 id: string,125 make: Effect.Effect<string | undefined, E>126): Drawing => {127 const known = kept.get(id);128129 if (known !== undefined) {130 kept.delete(id);131 kept.set(id, known);132133 return known.drawing;134 }135136 const drawing: Drawing = Effect.runPromise(137 make.pipe(Effect.orElseSucceed((): string | undefined => undefined))138 );139140 const entry = { drawing, size: 0 };141142 kept.set(id, entry);

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

line 143why, one step back
143 // Subscribed first, so whoever awaits it next finds it marked.

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 144–161why, one step back
144 Effect.runFork(
145 Effect.promise(() => drawing).pipe(146 Effect.andThen((html) =>147 Effect.sync(() => {148 drawing.status = "fulfilled";149 drawing.value = html;150 entry.size = html?.length ?? 0;151 trim();152 })153 )154 )155 );156 trim();157158 return drawing;159};160161/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 162–163why, one step back
162 * `import.meta.env.SSR` is false in the browser's build, so this import is dead
163 * code there.

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 164–222why, one step back
164 */
165const server = () =>166 import.meta.env.SSR167 ? Effect.tryPromise(() => import("./prerender-server.ts"))168 : Effect.die("Only the server draws code ahead");169170export const fileDrawingId = (file: {171 readonly path: string;172 readonly sha: string;173}) => `file:${file.sha}:${file.path}`;174175export const diffDrawingId = (drawn: DrawnFile) =>176 `${drawn.file.before ?? "none"}:${drawn.file.after ?? "none"}:${drawn.file.path}`;177178export const fileDrawing = (file: {179 readonly path: string;180 readonly sha: string;181 readonly text: string;182}) =>183 keptDrawing(184 fileDrawingId(file),185 server().pipe(Effect.andThen(({ prerenderFile }) => prerenderFile(file)))186 );187188export const diffDrawing = (drawn: DrawnFile) =>189 keptDrawing(190 diffDrawingId(drawn),191 server().pipe(Effect.andThen(({ prerenderDiff }) => prerenderDiff(drawn)))192 );193194export const drawFileAhead = ({195 path,196 sha,197 text,198}: {199 readonly path: string;200 readonly sha: string;201 readonly text?: string | undefined;202}) =>203 Effect.runPromise(204 text === undefined || !prerendersFile({ path, text })205 ? Effect.void206 : Effect.promise(() => fileDrawing({ path, sha, text })).pipe(207 Effect.asVoid208 )209 );210211export const drawDiffAhead = (files: readonly ChangedFile[]) => {212 const drawn = drawnFiles(files);213 const paths = prerenderedPaths(drawn);214215 return Effect.runPromise(216 Effect.forEach(217 drawn.filter((file) => paths.has(file.file.path)),218 (file) => Effect.promise(() => diffDrawing(file)),219 { concurrency: "unbounded", discard: true }220 )221 );222};