Skip to content
Myr

production-bundle.test.ts

This file

Path

apps/web/test/production-bundle.test.ts

437 lines · 13.6 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

lines 1–2why, one step back
1// The Cloudflare plugin rewrites `.wrangler/deploy/config.json` at each build to point at its output;
2// the redirect is put back as it was, so a deploy never follows it into a folder this test removed.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 3–36why, one step back
3import { NodeServices } from "@effect/platform-node";
4import { expect, layer } from "@effect/vitest";5import { Brand } from "@repo/brand";6import {7 Context,8 Effect,9 FileSystem,10 Layer,11 Option,12 Path,13 Schema,14 Stream,15} from "effect";16import { ChildProcess, ChildProcessSpawner } from "effect/process";1718const BUILD = 180_000;1920const DEV_STRINGS = [21 "src/dev/",22 "devWorld",23 "seedDev",24 "devSessions",25 "RepoHostMemory",26 "MemorySessions",27 "/auth/dev",28 "@repo/testkit",29 "isomorphic-git",30] as const;3132const DEV_MODULES = [33 "packages/project/src/project-store/memory",34 "packages/artifacts/src/repo-host/memory",35] as const;36

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

lines 37–38why, one step back
37// About 10% above what the root's preloads weighed once the landing read its projects on the server.
38// A route's `head`, `loader` and server functions ride in the route tree every page loads, so what they import counts here.

Merge build/landing-ceiling into mainoscabrielbefore adoption1b5d02e

line 39why, one step back
39const ROOT_PRELOADS_GZIP = 268_000;

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

line 40why, one step back
40

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 41–42why, one step back
41const GRAMMAR = /node_modules\/@shikijs\/langs\/dist\/(?<name>[\w-]+)\.mjs$/u;
42

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

line 43why, one step back
43// By Shiki's module names: HTML brings JavaScript and CSS with it.

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 44–60why, one step back
44const SERVER_GRAMMARS = [
45 "css",46 "html",47 "javascript",48 "json",49 "jsx",50 "markdown",51 "shellscript",52 "toml",53 "tsx",54 "typescript",55 "yaml",56];5758const drawing = (held: readonly string[]) =>59 held.some((module) => module.endsWith("features/code/prerender-server.ts"));60

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 61–81why, one step back
61const BINARY = /\.(?:ico|png|woff2)$/u;
6263const decodeSourceMap = Schema.decodeUnknownEffect(64 Schema.fromJsonString(Schema.Struct({ sources: Schema.Array(Schema.String) }))65);6667const decodeManifest = Schema.decodeUnknownEffect(68 Schema.fromJsonString(69 Schema.Struct({70 display: Schema.String,71 icons: Schema.Array(Schema.Struct({ src: Schema.String })),72 name: Schema.String,73 start_url: Schema.String,74 })75 )76);7778interface Output {79 readonly texts: ReadonlyMap<string, string>;80 readonly paths: ReadonlySet<string>;81 readonly modules: ReadonlySet<string>;

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

line 82why, one step back
82 readonly holding: ReadonlyMap<string, readonly string[]>;

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 83–127why, one step back
83}
8485const where = Effect.gen(function* () {86 const path = yield* Path.Path;87 const web = yield* path.fromFileUrl(new URL("..", import.meta.url));8889 return { repo: path.resolve(web, "../.."), web };90});9192const keepDeployRedirect = (web: string) =>93 Effect.gen(function* () {94 const fs = yield* FileSystem.FileSystem;95 const path = yield* Path.Path;96 const redirect = path.join(web, ".wrangler/deploy/config.json");97 const before = yield* Effect.option(fs.readFileString(redirect));9899 yield* Effect.addFinalizer(() =>100 Option.match(before, {101 onNone: () => fs.remove(redirect, { force: true }),102 onSome: (text) => fs.writeFileString(redirect, text),103 }).pipe(Effect.orDie)104 );105 });106107const modulesIn = (map: string, text: string, repo: string) =>108 Effect.gen(function* () {109 const path = yield* Path.Path;110 const { sources } = yield* decodeSourceMap(text);111112 return sources.map((source) =>113 path.relative(114 repo,115 path.resolve(path.dirname(map), source.replace(/\?.*$/u, ""))116 )117 );118 });119120const readOutput = (out: string, repo: string) =>121 Effect.gen(function* () {122 const fs = yield* FileSystem.FileSystem;123 const path = yield* Path.Path;124 const entries = yield* fs.readDirectory(out, { recursive: true });125 const texts = new Map<string, string>();126 const modules = new Set<string>();127 const paths = new Set<string>();

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

line 128why, one step back
128 const holding = new Map<string, readonly string[]>();

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 129–139why, one step back
129
130 for (const entry of entries) {131 const at = path.join(out, entry);132133 if ((yield* fs.stat(at)).type !== "File") {134 continue;135 }136137 paths.add(entry);138139 if (entry.endsWith(".map")) {

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

lines 140–144why, one step back
140 const held = yield* modulesIn(at, yield* fs.readFileString(at), repo);
141142 holding.set(entry.replace(/\.map$/u, ""), held);143144 for (const module of held) {

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 145–151why, one step back
145 modules.add(module);
146 }147 } else if (!BINARY.test(entry)) {148 texts.set(entry, yield* fs.readFileString(at));149 }150 }151

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

line 152why, one step back
152 return { holding, modules, paths, texts } satisfies Output;

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 153–202why, one step back
153 });
154155const productionBuild = Effect.gen(function* () {156 const fs = yield* FileSystem.FileSystem;157 const path = yield* Path.Path;158 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;159 const { repo, web } = yield* where;160 const out = yield* fs.makeTempDirectoryScoped({ prefix: "web-bundle-" });161162 yield* keepDeployRedirect(web);163164 const child = yield* spawner.spawn(165 ChildProcess.make(166 path.join(web, "node_modules/.bin/vite"),167 ["build", "--sourcemap", "--outDir", out, "--logLevel", "error"],168 {169 cwd: web,170 env: { NODE_ENV: "production", WRANGLER_SEND_METRICS: "false" },171 extendEnv: true,172 stdout: "ignore",173 }174 )175 );176177 const [stderr, exitCode] = yield* Effect.all(178 [child.stderr.pipe(Stream.decodeText(), Stream.mkString), child.exitCode],179 { concurrency: "unbounded" }180 );181182 if (exitCode !== 0) {183 return yield* Effect.die(`vite build exited ${exitCode}:\n${stderr}`);184 }185186 return yield* readOutput(out, repo);187}).pipe(Effect.scoped, Effect.orDie, Effect.provide(NodeServices.layer));188189class Built extends Context.Service<Built, Output>()("test/Built") {}190191const textsUnder = (output: Output, folder: "client" | "server") =>192 [...output.texts].filter(([at]) => at.startsWith(`${folder}/`));193194const holds = (output: Output, folder: "client" | "server", pattern: RegExp) =>195 textsUnder(output, folder).some(([, text]) => pattern.test(text));196197const routePath = (path: string) =>198 new RegExp(199 `(?<quote>["'\`])${path.replaceAll(/[$.]/gu, "\\$&")}\\k<quote>`,200 "u"201 );202

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

lines 203–208why, one step back
203const rootPreloads = (output: Output) => {
204 const manifest = textsUnder(output, "server").find(([at]) =>205 at.includes("tanstack-start-manifest")206 )?.[1];207208 // Lazily up to the first `preloads`, the root's own: a child route's path

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 209why, one step back
209 // may hold a brace (`/$owner/$project/asks/{$ask}.md`). The minified server

Merge perf/minify-web into mainoscabrielbefore adoption260fd43

lines 210–211why, one step back
210 // build writes the list as one string it splits on commas
211 // (`` `/assets/a.js,/assets/b.js`.split(`,`) ``), an unminified one as an array.

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

line 212why, one step back
212 const preloads =

Merge perf/minify-web into mainoscabrielbefore adoption260fd43

line 213why, one step back
213 /__root__:\s*\{[\s\S]*?preloads:\s*(?<list>\[[^\]]*\]|`[^`]*`)/u.exec(

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

lines 214–216why, one step back
214 manifest ?? ""
215 )?.groups?.list;216

Merge perf/minify-web into mainoscabrielbefore adoption260fd43

lines 217–218why, one step back
217 return [...(preloads ?? "").matchAll(/\/assets\/[^"`,\s]+/gu)].map(
218 ([chunk]) => chunk

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

lines 219–234why, one step back
219 );
220};221222const gzipped = (text: string) =>223 Stream.fromReadableStream({224 evaluate: () =>225 new Blob([text]).stream().pipeThrough(new CompressionStream("gzip")),226 onError: (cause) => cause,227 }).pipe(228 Stream.runFold(229 () => 0,230 (size, chunk: Uint8Array) => size + chunk.byteLength231 ),232 Effect.orDie233 );234

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 235–238why, one step back
235layer(Layer.effect(Built, productionBuild), { timeout: BUILD })(
236 "the web's production build",237 (it) => {238 it.effect(

Merge redesign into mainoscabrielbefore adoptioncaedd21

line 239why, one step back
239 "carries the web app manifest, which opens the inbox, and every icon it names",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 240–251why, one step back
240 () =>
241 Effect.gen(function* () {242 const output = yield* Built;243 const manifest = output.texts.get("client/manifest.webmanifest");244245 expect(manifest, "client/manifest.webmanifest").toBeDefined();246247 const { icons, ...installs } = yield* decodeManifest(manifest);248249 expect(installs).toStrictEqual({250 display: "standalone",251 name: Brand.name,

Merge redesign into mainoscabrielbefore adoptioncaedd21

line 252why, one step back
252 start_url: "/inbox",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 253–271why, one step back
253 });
254 expect(icons.length).toBeGreaterThan(0);255 expect(256 icons.flatMap(({ src }) =>257 output.paths.has(`client${src}`) ? [] : [src]258 )259 ).toStrictEqual([]);260 })261 );262263 it.effect(264 "serves llms.txt and the MCP card, and passes the skills, the install script and the releases on",265 () =>266 Effect.gen(function* () {267 const output = yield* Built;268269 expect(270 [271 "/llms.txt",

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 272why, one step back
272 "/$owner/$project/llms.txt",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 273–281why, one step back
273 "/.well-known/mcp.json",
274 "/.well-known/agent-skills/$",275 "/install.sh",276 "/releases/$",277 ].filter((path) => !holds(output, "server", routePath(path)))278 ).toStrictEqual([]);279 })280 );281

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

line 282why, one step back
282 // A build that resolves `#backend` to `src/dev/backend.ts` fails here and in the next case.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 283–320why, one step back
283 it.effect("resolves #backend to the forward to PLATFORM", () =>
284 Effect.gen(function* () {285 const output = yield* Built;286287 expect({288 devBackend: output.modules.has("apps/web/src/dev/backend.ts"),289 forwards: holds(output, "server", /\bPLATFORM\.fetch\(/u),290 serverBackend: output.modules.has("apps/web/src/server/backend.ts"),291 }).toStrictEqual({292 devBackend: false,293 forwards: true,294 serverBackend: true,295 });296 })297 );298299 it.effect(300 "carries no dev module, no memory adapter, no seed, no dev sign-in and no test kit",301 () =>302 Effect.gen(function* () {303 const output = yield* Built;304305 expect(output.modules.size).toBeGreaterThan(10);306 expect(307 [...output.modules].filter(308 (module) =>309 module.startsWith("apps/web/src/dev/") ||310 DEV_MODULES.some((folder) => module.startsWith(folder))311 )312 ).toStrictEqual([]);313 expect(314 [...output.texts].flatMap(([at, text]) =>315 DEV_STRINGS.flatMap((dev) =>316 text.includes(dev) ? [`${at}: ${dev}`] : []317 )318 )319 ).toStrictEqual([]);320 })

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

lines 321–346why, one step back
321 );
322323 it.effect(324 "preloads on every page no chunk that holds the Markdown renderer, and stays under its ceiling",325 () =>326 Effect.gen(function* () {327 const output = yield* Built;328 const preloads = rootPreloads(output);329330 expect(preloads.length).toBeGreaterThan(0);331332 const sizes = yield* Effect.forEach(preloads, (chunk) =>333 gzipped(output.texts.get(`client${chunk}`) ?? "")334 );335336 const total = sizes.reduce((sum, size) => sum + size, 0);337338 expect({339 markdown: preloads.filter((chunk) =>340 (output.holding.get(`client${chunk}`) ?? []).some((module) =>341 module.includes("node_modules/react-markdown/")342 )343 ),344 missing: preloads.filter(345 (chunk) => !output.texts.has(`client${chunk}`)346 ),

Merge build/landing-ceiling into mainoscabrielbefore adoption1b5d02e

lines 347–352why, one step back
347 }).toStrictEqual({ markdown: [], missing: [] });
348 // The weight itself, so a failure says how far over it is.349 expect(350 total,351 `${preloads.length} root preloads, gzipped`352 ).toBeLessThanOrEqual(ROOT_PRELOADS_GZIP);

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 353–356why, one step back
353 })
354 );355356 it.effect(

Merge redesign into mainoscabrielbefore adoptioncaedd21

line 357why, one step back
357 "preloads on every page no grammar, nothing of the server's highlighting, and neither the landing's view, Explore's nor the import page's",

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 358–361why, one step back
358 () =>
359 Effect.gen(function* () {360 const output = yield* Built;361

Merge redesign into mainoscabrielbefore adoptioncaedd21

line 362why, one step back
362 // Nor the landing's view, Explore's or the import page's: a route's head or

Merge build/1411-web-import into mainoscabrielbefore adoption059c75c

lines 363–364why, one step back
363 // loader that imported one would carry the whole page into every
364 // page's preloads.

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 365–367why, one step back
365 expect(
366 rootPreloads(output).flatMap((chunk) =>367 (output.holding.get(`client${chunk}`) ?? []).filter(

Merge build/landing-ceiling into mainoscabrielbefore adoption1b5d02e

lines 368–370why, one step back
368 (module) =>
369 GRAMMAR.test(module) ||370 module.includes("prerender") ||

Merge build/1411-web-import into mainoscabrielbefore adoption059c75c

line 371why, one step back
371 module.endsWith("features/landing/landing-page.tsx") ||

Merge redesign into mainoscabrielbefore adoptioncaedd21

line 372why, one step back
372 module.endsWith("features/explore/explore-page.tsx") ||

Merge build/1411-web-import into mainoscabrielbefore adoption059c75c

line 373why, one step back
373 module.includes("features/import/")

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 374–423why, one step back
374 )
375 )376 ).toStrictEqual([]);377378 // The server's highlighting is the Worker's alone.379 expect({380 browser: [...output.holding].flatMap(([at, held]) =>381 at.startsWith("client/") && drawing(held) ? [at] : []382 ),383 worker: [...output.holding].some(384 ([at, held]) => at.startsWith("server/") && drawing(held)385 ),386 }).toStrictEqual({ browser: [], worker: true });387 })388 );389390 it.effect(391 "bundles into the Worker its few grammars alone, off its entry, and no theme collection or WebAssembly",392 () =>393 Effect.gen(function* () {394 const output = yield* Built;395396 const server = [...output.holding].filter(([at]) =>397 at.startsWith("server/")398 );399400 const grammars = new Set(401 server.flatMap(([, held]) =>402 held.flatMap((module) => {403 const name = GRAMMAR.exec(module)?.groups?.name;404405 return name === undefined ? [] : [name];406 })407 )408 );409410 expect([...grammars].toSorted()).toStrictEqual(SERVER_GRAMMARS);411 expect(412 server.flatMap(([at, held]) =>413 held.filter(414 (module) =>415 module.includes("node_modules/@shikijs/themes/") ||416 module.includes("node_modules/@pierre/theme/") ||417 module.includes("node_modules/@shikijs/engine-oniguruma/") ||418 (at === "server/index.js" &&419 (GRAMMAR.test(module) ||420 module.includes("features/code/prerender-server.ts")))421 )422 )423 ).toStrictEqual([]);

Fold every page's project events once, keep Markdown off the first load, and cache what never changesoscabrielbefore adoption38e5215

lines 424–434why, one step back
424 })
425 );426427 it.effect("tells browsers to keep the hashed assets for good", () =>428 Effect.gen(function* () {429 const output = yield* Built;430431 expect(output.texts.get("client/_headers")).toMatch(432 /^\/assets\/\*\n {2}Cache-Control: public, max-age=31536000, immutable$/mu433 );434 })

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 435–437why, one step back
435 );
436 }437);