Skip to content

Commit 3523b9e

Browse files
authored
perf(site): cut each page's JavaScript by about 40% (#62272)
1 parent d86331c commit 3523b9e

27 files changed

Lines changed: 2446 additions & 788 deletions

‎services/site/script/check-client-bundle.ts‎

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22
// Design mode (design-mode.tsx, design-overlay.tsx) or the device preview (device-preview.tsx,
33
// device-preview-panel.tsx). They load only on the development server, through loaders a production
44
// build compiles away: `import.meta.env.DEV ? lazy(() => import("./settings-panel")) : undefined`.
5+
// Also fails when server-only code reaches it: the Worker's cache, GitHub calls and the build-time
6+
// GitHub snapshot. Pages may import their modules for the queries, whose "use server" bodies the
7+
// browser build drops along with everything only those bodies read.
8+
// Last, it fails when a page's initial JavaScript (the entry and every chunk the page's route imports
9+
// statically, which the server modulepreloads) passes its budget below, gzipped. Code a page needs
10+
// only later belongs behind a dynamic import.
511
// Run after `vite build`, optionally with the output directory: `bun script/check-client-bundle.ts .output`.
612
import path from "node:path"
713
import { Glob } from "bun"
@@ -16,13 +22,15 @@ const scriptMarkers = [
1622
'opencode-site-device-preview"', // device-preview-panel.tsx: the saved device
1723
"Toggle Design mode", // search-index.ts: the ⌘K action
1824
"Open Settings", // search-index.ts: the ⌘K action
25+
"edge-cache.opencode.internal", // lib/edge-cache.ts
26+
"api.github.com", // lib/changelog-releases.ts
1927
]
2028
// The tools' styles (settings-panel.css, design-mode.css, device-preview.css).
2129
const styleMarker =
2230
/\[data-component="?(settings-panel|settings-backdrop|design-overlay|design-controls|design-export|history-toast|device-preview)"?\]/
23-
// Chunks named after the tools' modules.
31+
// Chunks named after the tools' modules, or after the GitHub snapshot (lib/github-snapshot.json).
2432
const chunkName =
25-
/(^|\/)(design-mode|design-overlay|settings-panel|device-preview|device-preview-panel|page-settings|settings-transfer)-[\w-]+\.(js|css)$/
33+
/(^|\/)(design-mode|design-overlay|settings-panel|device-preview|device-preview-panel|page-settings|settings-transfer|github-snapshot)-[\w-]+\.(js|css)$/
2634

2735
const files = await Array.fromAsync(new Glob("**/*.{js,mjs,css}").scan({ cwd: root }))
2836
if (!files.length) {
@@ -32,7 +40,7 @@ if (!files.length) {
3240
const found = (
3341
await Promise.all(
3442
files.map(async (file) => {
35-
if (chunkName.test(file)) return [`${file}: a development tool's chunk`]
43+
if (chunkName.test(file)) return [`${file}: a development tool's or server-only chunk`]
3644
const text = await Bun.file(path.join(root, file)).text()
3745
if (file.endsWith(".css")) {
3846
const match = text.match(styleMarker)
@@ -44,9 +52,77 @@ const found = (
4452
).flat()
4553
if (found.length) {
4654
console.error(
47-
"check-client-bundle: Settings, Design mode or device preview code is in the client bundle:\n " +
55+
"check-client-bundle: Settings, Design mode, device preview or server-only code is in the client bundle:\n " +
4856
found.join("\n "),
4957
)
5058
process.exit(1)
5159
}
52-
console.log(`check-client-bundle: ${files.length} client files, no Settings, Design mode or device preview code`)
60+
console.log(
61+
`check-client-bundle: ${files.length} client files, no Settings, Design mode, device preview or server-only code`,
62+
)
63+
64+
// Each page's budget in kB, gzipped: what it was when last measured, plus a kB of room. Lower a
65+
// budget when a page gets lighter; a page without one fails until it has one.
66+
const budgets: Record<string, number> = {
67+
"[...404].tsx": 144,
68+
"brand/index.tsx": 153,
69+
"changelog/[tag].tsx": 167,
70+
"changelog/index.tsx": 166,
71+
"desktop.tsx": 178,
72+
"devices.tsx": 83,
73+
"extensions/browse.tsx": 155,
74+
"font/index.tsx": 174,
75+
"ide.tsx": 178,
76+
"index.tsx": 183,
77+
"legal/index.tsx": 193,
78+
"legal/privacy-policy/index.tsx": 193,
79+
"legal/terms-of-service/index.tsx": 193,
80+
"mini.tsx": 178,
81+
"mobile.tsx": 178,
82+
"press/index.tsx": 155,
83+
"product/index.tsx": 168,
84+
"sdk.tsx": 178,
85+
"terminal.tsx": 178,
86+
"video-editor/index.tsx": 81,
87+
}
88+
type Chunk = { file: string; imports?: string[] }
89+
const manifest: Record<string, Chunk> = await Bun.file(path.join(root, ".vite/manifest.json")).json()
90+
const sizes = new Map<string, number>()
91+
const gzipped = async (file: string) => {
92+
const known = sizes.get(file)
93+
if (known !== undefined) return known
94+
const size = Bun.gzipSync(await Bun.file(path.join(root, file)).bytes(), { level: 9 }).length
95+
sizes.set(file, size)
96+
return size
97+
}
98+
const closure = (key: string, seen = new Set<string>()): Set<string> => {
99+
if (seen.has(key)) return seen
100+
seen.add(key)
101+
manifest[key].imports?.forEach((next) => closure(next, seen))
102+
return seen
103+
}
104+
const entry = closure("src/entry-client.tsx")
105+
const pages = await Promise.all(
106+
Object.keys(manifest)
107+
.filter((key) => key.startsWith("src/routes/") && key.includes("?pick=default"))
108+
.map(async (key) => {
109+
const chunks = [...new Set([...entry, ...closure(key)])].map((chunk) => manifest[chunk].file)
110+
const bytes = (await Promise.all(chunks.map(gzipped))).reduce((sum, size) => sum + size, 0)
111+
return { route: key.slice("src/routes/".length).split("?")[0], kB: Math.round(bytes / 100) / 10 }
112+
}),
113+
)
114+
const over = pages.filter((page) => !(page.kB <= budgets[page.route]))
115+
if (over.length) {
116+
console.error(
117+
"check-client-bundle: initial JavaScript (gzipped) over its page's budget:\n " +
118+
over.map((page) => `${page.route}: ${page.kB} kB, budget ${budgets[page.route] ?? "none"}`).join("\n "),
119+
)
120+
process.exit(1)
121+
}
122+
console.log(
123+
"check-client-bundle: initial JavaScript within budget (kB gzipped): " +
124+
pages
125+
.toSorted((a, b) => b.kB - a.kB)
126+
.map((page) => `${page.route} ${page.kB}`)
127+
.join(", "),
128+
)
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Writes src/component/site/legal-search.json, the ⌘K search's entries for the legal documents
2+
// (legalSearch in lib/legal.ts), so the search doesn't load the documents themselves. Run after
3+
// changing a legal document; test/legal-search.test.ts fails while the file is out of date.
4+
import path from "node:path"
5+
import { legalSearch } from "../src/lib/legal"
6+
7+
const file = path.join(import.meta.dir, "../src/component/site/legal-search.json")
8+
await Bun.write(file, JSON.stringify(legalSearch(), null, 2) + "\n")
9+
console.log(`legal-search.json: ${legalSearch().length} documents`)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Writes src/component/site/settings-defaults.json: the default settings, which production renders
2+
// without building the settings schema, so zod stays out of the browser's bundle (settings.ts). Run
3+
// after changing a setting or its default; test/settings-defaults.test.ts fails while the file is out
4+
// of date.
5+
import path from "node:path"
6+
import { siteSettingsSchema } from "../src/component/site/settings"
7+
8+
const file = path.join(import.meta.dir, "../src/component/site/settings-defaults.json")
9+
const defaults = siteSettingsSchema().parse({})
10+
await Bun.write(file, JSON.stringify(defaults, null, 2) + "\n")
11+
console.log(`settings-defaults.json: ${Object.keys(defaults).length} settings`)

‎services/site/src/component/site/arcade/coin-tuning.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,6 @@ const defaults = () =>
9595
) as CoinValues
9696

9797
const storageKey = "opencode-arcade-coin-v1"
98-
const saved = z.record(z.string(), z.record(z.string(), z.number()))
9998

10099
export const [coinValues, setCoinValues] = createStore<CoinValues>(defaults())
101100
/** Settings › Coin › Preview: the token held still over the cabinet, in its held pose. */
@@ -105,7 +104,12 @@ export const [coinReplay, setCoinReplay] = createSignal(0)
105104

106105
/** Saved values over the defaults, each kept inside its control's range. */
107106
export function loadCoinValues() {
108-
const parsed = saved.safeParse(readJson(localStorage.getItem(storageKey)))
107+
// Values are saved from Settings, a development tool, so production keeps the defaults, and its
108+
// bundle leaves zod out.
109+
if (import.meta.env.PROD) return
110+
const parsed = z
111+
.record(z.string(), z.record(z.string(), z.number()))
112+
.safeParse(readJson(localStorage.getItem(storageKey)))
109113
if (!parsed.success) return
110114
const next = defaults()
111115
for (const [group, entry] of Object.entries(coinControls) as [CoinGroup, Controls[CoinGroup]][])

‎services/site/src/component/site/arcade/layers-tuning.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,17 @@ const defaults = () =>
6868
) as LayerValues
6969

7070
const storageKey = "opencode-arcade-layers-v1"
71-
const saved = z.record(z.string(), z.record(z.string(), z.number()))
7271

7372
export const [layerValues, setLayerValues] = createStore<LayerValues>(defaults())
7473

7574
/** Reads saved values over the defaults, keeping each one inside its control's range. */
7675
export function loadLayerValues() {
77-
const parsed = saved.safeParse(readJson(localStorage.getItem(storageKey)))
76+
// Values are saved from Settings, a development tool, so production keeps the defaults, and its
77+
// bundle leaves zod out.
78+
if (import.meta.env.PROD) return
79+
const parsed = z
80+
.record(z.string(), z.record(z.string(), z.number()))
81+
.safeParse(readJson(localStorage.getItem(storageKey)))
7882
if (!parsed.success) return
7983
const next = defaults()
8084
for (const [group, entry] of Object.entries(layerControls) as [keyof Controls, Controls[keyof Controls]][])

‎services/site/src/component/site/arcade3d/tuning.ts‎

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -128,31 +128,30 @@ const defaults = () =>
128128
["quality", "auto"],
129129
]) as Values
130130

131-
const schema = z
132-
.object({
133-
...Object.fromEntries(
134-
Object.entries(controls).map(([group, section]) => [
135-
group,
136-
z
137-
.object(
138-
Object.fromEntries(
139-
Object.entries(section.items).map(([key, item]) => [key, z.number().min(item.min).max(item.max)]),
140-
),
141-
)
142-
.partial(),
143-
]),
144-
),
145-
quality: z.enum(qualities),
146-
})
147-
.partial()
148-
149131
const [tuning, setTuning] = createStore<Values>(defaults())
150132
export { tuning }
151133
const [fps, setFps] = createSignal(0)
152134
export { fps, setFps }
153135

154136
/** Merge saved values over the defaults; anything missing or out of range falls back. */
155137
export function applyTuning(input: unknown) {
138+
const schema = z
139+
.object({
140+
...Object.fromEntries(
141+
Object.entries(controls).map(([group, section]) => [
142+
group,
143+
z
144+
.object(
145+
Object.fromEntries(
146+
Object.entries(section.items).map(([key, item]) => [key, z.number().min(item.min).max(item.max)]),
147+
),
148+
)
149+
.partial(),
150+
]),
151+
),
152+
quality: z.enum(qualities),
153+
})
154+
.partial()
156155
const parsed = schema.safeParse(input)
157156
if (!parsed.success) return false
158157
const next = defaults()
@@ -168,6 +167,9 @@ export function applyTuning(input: unknown) {
168167
* the rest; this follows that setting, including Reset and Import from the Settings panel.
169168
*/
170169
export function followTuning() {
170+
// Production always renders the default settings, so there is nothing to follow, and its bundle
171+
// leaves zod out.
172+
if (import.meta.env.PROD) return
171173
createEffect(() => {
172174
if (!applyTuning(siteSettings.arcade3d)) setTuning(reconcile(defaults()))
173175
})

0 commit comments

Comments
 (0)