// Whether the renderer draws on a server as a browser hydrates it: each // tree in trees/ (Grain's screens, made by `just ssr-data`), drawn by the // renderer's `Tree` compiled for the server (server.ts) with Svelte's // `render` in Node, with no browser's globals (no window, document, // navigator or storage: one touched as the code loads or draws throws), // given `now` and an `hrefOf` as an app drawing pages would; then // hydrated, compiled for the browser in development (client.ts), with // Svelte's `hydrate` in a document of happy-dom's, with the same props. // // cd web && npm run ssr `just check` runs it, and CI's web job // // It fails where a tree's drawing throws, draws nothing, draws otherwise a // second time, has no link (``) to a call it opens, or puts a link // or button inside another; where its hero (`ui.hero`, the first picture // drawn large) is not loaded at once and first (`loading="eager"`, // `fetchpriority="high"`); where a picture first on the screen by its // place (the tree's top, a list's first item, the pane shown: there an // Image, a gallery's first picture) is not loaded at once, at low // priority beside a hero (with none of its own in a tree without one), // or another is not lazy; Home (a strip of // stories over a feed, its hero the first card's first photo, as the // server names it past the strip) fails where its first card's face and // its first story's are not those loaded at once; where a // carousel draws a picture past its second, or the gallery's photos lack // their sizes (`srcset`, with `sizes` the `Tree`'s area, `auto` first for // one drawn lazily, its hero's as `ui.heroSrcset`; a cover's its tile's), // or `heroPreload` would // preload its hero otherwise than it is drawn; or where hydrating it warns // (Svelte's // hydration_mismatch and the rest), throws, or changes what the server // drew (a text, an attribute). A tree with a `Bar` over it (the profile's, // a Share button in it) is drawn as an app with a bar of its own draws it // too, `bar: 'apart'` and `bar: 'only'`, and fails where the tree still // draws its Bar or the bar draws anything but its buttons; each hydrated // as the rest. A clamped text the server cut (a Text's or RichText's // `shownRuns` or `shownBlocks`) fails where the server does not draw it // cut with its "more" button after it, where hydrated it draws more than // the cut, and where its button, clicked, does not draw it whole. A // screen opened at its form (an empty story screen's Add to your story, // `open`) fails where the server draws the form open, hydrating it // changes it, or once hydrated it does not open by itself. Stories fail // where the server draws a picture but the one showing, or draws it // without its sizes, or hydrated they do not load the next two ahead with // theirs (a page drawn ahead in a pager, the one it starts from alone), or // their bar fills before its picture loads, or // not once it loads or fails; a carousel near the screen, where it does // not load its next photo ahead at its width. A feed's card fails where a // tap on it does not open it, or a tap on its carousel, a touch that moved // or one that came as its page scrolled does, or a mouse's click does not. // A form opened from a menu's row fails where an @ typed in its text does // not ask for accounts and list them in a popover, or one picked by a // press does not take the @'s place or closes the menu and its form. // A profile's ⋯ menu in its Bar, with the build's stylesheet, fails where // a row (a Link, an Action however deep in Stacks, a Compose, a Toggle) is // not the whole width with its words from the start at the inset the // others have, a Stack in it puts a gap between rows, an icon's words are // hidden, Block is not in the danger colour, or Report is marked as the // Bar's own form. // A place's header fails where a Stack with gap none is drawn otherwise, // or once mounted its Map draws a pin with pins false, or none without. // Profile's panes, at a phone's width with the build's stylesheet, fail // where two covers picked draw a bar other than Cancel, 2 selected and // Delete 2, or one not sticky, or in a box that scrolls or hides it (the // strip of panes, which would hold it to its own bottom, off the screen), // or where Cancel leaves the strip not scrolling again. The feed fails // where a page's translation may touch its ALT badge or a byline's // @handle (no `translate="no"` on them or around them), or may not its // Spanish caption; or where it may touch a link that shows its address, // or the line break and the space beside it in a caption, or may not // that caption's words. // A long feed, on a page giving everything border-box (as the shell and // the workspace do), fails where an item it lets go is held at a height // that takes its padding and border out (not content-box), so letting it // go above the view would move what is in view. // Both builds go to a directory of their own in the system's temporary // directory, taken away after. import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import { build, defaultClientConditions, defaultServerConditions } from 'vite'; const here = dirname(fileURLToPath(import.meta.url)); const web = resolve(here, '../..'); const trees = join(here, 'trees'); const out = mkdtempSync(join(tmpdir(), 'hud-ssr-')); const say = (line) => console.log(`==> ${line}`); const problems = []; // The server in one time zone, the browser in another a day away: a date written in either's own, before the page is mounted, differs. process.env.TZ = 'America/Los_Angeles'; /** The moment the trees are drawn at, the same on the server and in the browser. */ const NOW = Date.parse('2026-11-18T12:00:00.000Z'); /** Where an app drawing pages would put each call: a path of its own. */ const hrefOf = (call) => `/open/${call.name}?${new URLSearchParams({ args: JSON.stringify(call.args) })}`; /** How wide the app draws the tree's main area, as Grain's does: its column, up to 1200 pixels right of its 245-pixel sidebar above a 600-pixel screen, the screen below. */ const SLOT = '(min-width: 601px) min(1200px, 100vw - 245px), 100vw'; /** A picture's sizes in a tile of a grid three across at most, none under 6rem (`sm`), 0.75rem apart, in that slot. */ const TILE = '(min-width: 601px) min(min(1200px, 100vw - 245px), max(2 * 6rem + 0.75rem, (min(1200px, 100vw - 245px) - 2 * 0.75rem) / 3)), min(100vw, max(2 * 6rem + 0.75rem, (100vw - 2 * 0.75rem) / 3))'; /** A cover's sizes in a tile of tiles three across at most, none under 6rem, 0.125rem apart (../src/Covers.svelte), in that slot. */ const COVER = '(min-width: 601px) min(min(1200px, 100vw - 245px), max(2 * 6rem + 0.125rem, (min(1200px, 100vw - 245px) - 2 * 0.125rem) / 3)), min(100vw, max(2 * 6rem + 0.125rem, (100vw - 2 * 0.125rem) / 3))'; /** Parts that lay out by their box: a Split (its aside first) in a Stack held to reading width, a Profile in it, a grid of carousels three across at most, tiles likewise, and one pane whose row a wide box draws; drawn too in boxes of a phone's, a column's and a wide screen's width. */ const photo = (n) => ({ src: { src: `https://cdn.test/p${n}.jpg`, fallback: null }, alt: '', ratio: 1, srcset: `https://cdn.test/p${n}-small.jpg 1000w, https://cdn.test/p${n}.jpg 2000w` }); const opening = (n) => ({ call: { name: 'query', args: { method: 'test.layout.get', params: { n } } } }); const LAYOUT = { v: 1, trusted: true, measure: 'wide', root: { c: 'Stack', p: { gap: 'md' }, k: [ { c: 'Stack', p: { gap: 'md', measure: 'content' }, k: [{ c: 'Split', p: { side: 'start', aside: 'sm' }, k: [{ c: 'Text', p: { runs: [{ text: 'Beside' }], style: 'body' } }, { c: 'Profile', p: { name: 'Alice', handle: 'alice.test', avatar: null, banner: null } }] }] }, { c: 'List', p: { style: 'grid', min: 'sm', columns: 3 }, items: [1, 2, 3, 4].map((n) => ({ open: opening(n), k: [{ c: 'Gallery', p: { style: 'carousel' }, items: [photo(n), photo(n + 10)] }] })) }, { c: 'Covers', p: { style: 'tiles', min: 'sm', columns: 3 }, items: [1, 2].map((n) => ({ src: { src: `https://cdn.test/c${n}.jpg`, fallback: null }, title: `C${n}`, count: '1', stat: null, date: null, labels: [], open: opening(n), srcset: `https://cdn.test/c${n}-640.jpg 640w, https://cdn.test/c${n}.jpg 1000w` })) }, { c: 'Panes', k: [{ c: 'Pane', p: { label: 'Galleries', icon: 'grid' }, k: [{ c: 'Text', p: { runs: [{ text: 'Alone' }], style: 'body' } }] }] } ] } }; /** One's own profile's panes: its galleries, which may be picked, its favorites and its stories. */ const pick = { label: 'Select', action: 'Delete', one: 'gallery', many: 'galleries', method: 'test.gallery.delete', service: 'did:web:test' }; const paneOf = (label, icon, k) => ({ c: 'Pane', p: { label, icon }, k: [{ c: 'Text', p: { runs: [{ text: `${label} here` }], style: 'body' } }, ...k] }); const PANES = { v: 1, trusted: true, root: { c: 'Panes', k: [ paneOf('Galleries', 'grid', [{ c: 'Covers', p: { style: 'tiles', select: pick }, items: [1, 2].map((n) => ({ src: { src: `https://cdn.test/g${n}.jpg`, fallback: null }, title: `G${n}`, count: '1', stat: null, date: null, labels: [], open: opening(n), pick: { n } })) }]), paneOf('Favorites', 'heart', []), paneOf('Stories', 'clock', []) ] } }; /** Home as Grain draws it: a strip of stories over a feed of cards, each a face and a carousel of three; its hero the first card's first photo, as the server names it past the strip (crates/hud-core's `ui::hero`). */ const face = (name) => ({ src: { src: `https://cdn.test/${name}.jpg`, fallback: null }, alt: '', ratio: 1 }); const card = (n) => ({ open: opening(n), k: [{ c: 'Row', k: [{ c: 'Image', p: { ...face(`face${n}`), size: 'face' } }] }, { c: 'Gallery', p: { style: 'carousel' }, items: [photo(n), photo(n + 10), photo(n + 20)] }] }); const HOME = { v: 1, trusted: true, hero: photo(1).src.src, heroSrcset: photo(1).srcset, root: { c: 'Stack', k: [ { c: 'List', p: { style: 'strip' }, items: [1, 2].map((n) => ({ open: opening(n + 100), k: [{ c: 'Image', p: { ...face(`story${n}`), size: 'large' } }] })) }, { c: 'List', p: { style: 'rows' }, items: [1, 2, 3].map(card) } ] } }; const BOXES = ['360px', '600px', '1200px']; const props = (ui, bar = 'here', root = true) => ({ ui, bar, root, now: NOW, hrefOf, area: SLOT, oncall: () => {}, onreplace: () => {}, onopenlink: () => {}, onaction: async () => ({ uri: null }) }); /** Where `a` and `b` first differ, a little of each around it. */ function difference(a, b) { let i = 0; while (i < a.length && a[i] === b[i]) i++; const at = Math.max(0, i - 80); return `server: …${a.slice(at, i + 80)}…\n hydrated: …${b.slice(at, i + 80)}…`; } /** Text as Svelte's server writes it between tags. */ const escaped = (text) => text.replaceAll('&', '&').replaceAll('<', '<'); /** The texts of runs, or of blocks' runs, in order. */ const texts = (v) => (Array.isArray(v) ? v.flatMap(texts) : v && typeof v === 'object' ? (typeof v.text === 'string' ? [v.text] : Object.values(v).flatMap(texts)) : []); /** Each Text and RichText in a tree the server cut: its button's words, what it shows until opened and its whole, each as its texts. */ function clamped(v, found = []) { if (Array.isArray(v)) v.forEach((x) => clamped(x, found)); else if (v && typeof v === 'object') { const shown = v.p?.shownRuns ?? v.p?.shownBlocks; if ((v.c === 'Text' || v.c === 'RichText') && shown) found.push({ more: v.c === 'Text' ? 'more' : 'Show more', shown: texts(shown), whole: texts(v.p.runs ?? v.p.blocks) }); Object.values(v).forEach((x) => clamped(x, found)); } return found; } /** The pictures a tree draws first on the screen by their place, and those it draws later, by src (../src/hero.ts): first are the tree's top, a list's first item and the pane shown, and in them an Image and the first picture of a Gallery (a Covers' wait, but its hero: one under a gallery is far down its page). */ function byPlace(v, first = true, found = { first: new Set(), later: new Set() }) { const put = (src, at) => src && found[at ? 'first' : 'later'].add(src); if (Array.isArray(v)) v.forEach((x) => byPlace(x, first, found)); else if (v && typeof v === 'object') { if (v.c === 'Image') put(v.p?.src?.src, first); if (v.c === 'Gallery') (v.items ?? []).forEach((item, i) => put(item.src?.src, first && i === 0)); else if (v.c === 'List') (v.items ?? []).forEach((item, i) => byPlace(item, first && i === 0, found)); else if (v.c === 'Panes') (v.k ?? []).filter((pane) => pane.c === 'Pane').forEach((pane, i) => byPlace(pane, first && i === 0, found)); else Object.entries(v).forEach(([key, x]) => key !== 'p' && byPlace(x, first, found)); } return found; } try { // Each build its own Svelte plugin: one compiles for the server, the // other for the browser; HUD's packages as their source (vite.config.ts). const options = () => ({ configFile: false, root: web, publicDir: false, logLevel: 'warn', resolve: { conditions: ['@hud/source', ...defaultClientConditions] }, plugins: [svelte({ compilerOptions: { runes: true } })] }); await build({ ...options(), ssr: { noExternal: true, resolve: { conditions: ['@hud/source', ...defaultServerConditions] } }, build: { ssr: join(here, 'server.ts'), outDir: join(out, 'server'), emptyOutDir: true, minify: false, rollupOptions: { output: { entryFileNames: 'server.mjs' } } } }); // Svelte's development build, which says what does not hydrate as drawn. process.env.NODE_ENV = 'development'; await build({ ...options(), mode: 'development', build: { outDir: join(out, 'client'), emptyOutDir: true, minify: false, lib: { entry: join(here, 'client.ts'), formats: ['es'], fileName: 'client' } } }); // The server's in development too, as the browser's: a component unknown to the renderer draws otherwise there (unknown.ts), the same on both. await build({ ...options(), mode: 'development', ssr: { noExternal: true, resolve: { conditions: ['@hud/source', ...defaultServerConditions] } }, build: { ssr: join(here, 'server.ts'), outDir: join(out, 'server-dev'), emptyOutDir: true, minify: false, rollupOptions: { output: { entryFileNames: 'server.mjs' } } } }); // A server has no browser: Node's own navigator (and storage, where it has it) taken away too. for (const name of ['navigator', 'localStorage', 'sessionStorage']) Reflect.deleteProperty(globalThis, name); for (const name of ['window', 'document', 'navigator', 'localStorage']) if (typeof globalThis[name] !== 'undefined') throw new Error(`${name} is still there`); const server = await import(pathToFileURL(join(out, 'server/server.mjs')).href); const drawn = []; const sources = readdirSync(trees) .filter((f) => f.endsWith('.json')) .sort() .map((file) => ({ name: file.slice(0, -5), ui: JSON.parse(readFileSync(join(trees, file), 'utf8')) })); for (const { name, ui } of [...sources, { name: 'layout', ui: LAYOUT }, { name: 'home', ui: HOME }]) { let body; try { body = server.render(server.Tree, { props: props(ui) }).body; } catch (e) { problems.push(`${name}: drawing it threw: ${e.stack}`); continue; } if (body.replace(//gs, '').trim() === '') problems.push(`${name}: it drew nothing`); if (server.render(server.Tree, { props: props(ui) }).body !== body) problems.push(`${name}: drawn again, it drew otherwise`); const links = (body.match(/]*href="\/open\//g) ?? []).length; if (links === 0) problems.push(`${name}: no link to a call it opens`); const open = []; for (const [, close, tag] of body.matchAll(/<(\/?)(a|button)\b[^>]*>/g)) { if (close) open.pop(); else { if (open.length) problems.push(`${name}: an <${tag}> inside an <${open.at(-1)}>`); open.push(tag); } } const pictures = [...body.matchAll(/]*>/g)].map(([tag]) => ({ src: tag.match(/ src="([^"]*)"/)?.[1]?.replaceAll('&', '&'), srcset: tag.match(/ srcset="([^"]*)"/)?.[1]?.replaceAll('&', '&'), sizes: tag.match(/ sizes="([^"]*)"/)?.[1], first: / loading="eager"/.test(tag) && / fetchpriority="high"/.test(tag), atOnce: / loading="eager"/.test(tag) && (ui.hero === undefined ? !/ fetchpriority=/.test(tag) : / fetchpriority="low"/.test(tag)), lazy: / loading="lazy"/.test(tag) && !/ fetchpriority=/.test(tag) })); const heroes = pictures.filter((p) => ui.hero !== undefined && p.src === ui.hero); if (ui.hero !== undefined && (heroes.length === 0 || !heroes.every((p) => p.first))) problems.push(`${name}: its hero is not loaded at once and first`); if (heroes.some((p) => p.srcset !== ui.heroSrcset)) problems.push(`${name}: its hero is drawn with other sizes than ui.heroSrcset`); const preload = server.heroPreload(ui, SLOT); const drawnAs = heroes[0] && { href: heroes[0].src, imagesrcset: heroes[0].srcset, imagesizes: heroes[0].srcset && heroes[0].sizes, fetchpriority: 'high' }; if (drawnAs && JSON.stringify(preload) !== JSON.stringify(Object.fromEntries(Object.entries(drawnAs).filter(([, v]) => v !== undefined)))) problems.push(`${name}: its hero is preloaded as ${JSON.stringify(preload)}, drawn as ${JSON.stringify(drawnAs)}`); // Past the hero, a picture first on the screen by its place loads at once, at low priority beside a hero, and the rest lazily; one drawn both first and later (an account's face on two cards) is either. const placed = byPlace(ui.root); for (const p of pictures.filter((p) => !heroes.includes(p))) { const first = placed.first.has(p.src); const later = placed.later.has(p.src); if (first && !later && !p.atOnce) problems.push(`${name}: a picture first on the screen by its place is not loaded at once, at low priority beside a hero: ${p.src}`); if (!first && !p.lazy) problems.push(`${name}: a picture not first on the screen by its place is not lazy: ${p.src}`); } if (name === 'home') { const atOnce = pictures.filter((p) => p.atOnce).map((p) => p.src.replace('https://cdn.test/', '')); if (atOnce.join(' ') !== 'story1.jpg face1.jpg') problems.push(`home: past its hero, it loads at once ${atOnce.join(' ') || 'nothing'}, not the first story's face and the first card's`); if (!pictures.some((p) => p.src === photo(11).src.src && p.lazy)) problems.push("home: the first card's carousel's second photo is not drawn lazily"); } // A picture's sizes are its slot's: a lazy one's `auto` first; a grid's tiles', the slot shared among them, a cover's its tiles'. const slotOf = (p) => (name !== 'layout' ? SLOT : p.src.startsWith('https://cdn.test/c') ? COVER : TILE); if (pictures.some((p) => p.srcset !== undefined && p.sizes !== (p.first || p.atOnce ? slotOf(p) : `auto, ${slotOf(p)}`).replaceAll('&', '&'))) problems.push(`${name}: a picture with sizes other than its slot's: ${pictures.find((p) => p.srcset !== undefined)?.sizes}`); if (name === 'layout' && pictures.filter((p) => p.src.startsWith('https://cdn.test/c') && p.srcset).length !== 2) problems.push('layout: its covers are not drawn with their sizes'); if (name === 'layout') { if (!/
]*>()*
]*>()*
]*>Galleries<\/span>/.test(body)) problems.push("layout: its pane's word is not drawn beside its icon"); } // A carousel's pictures past its second are not drawn until it is swiped near them. const carousels = []; const walk = (v) => (Array.isArray(v) ? v.forEach(walk) : v && typeof v === 'object' && ((v.c === 'Gallery' && v.p?.style === 'carousel' && carousels.push(v)), Object.values(v).forEach(walk))); walk(ui.root); const later = new Set(carousels.flatMap((c) => (c.items ?? []).slice(2).map((item) => item.src?.src))); const early = new Set(carousels.flatMap((c) => (c.items ?? []).slice(0, 2).map((item) => item.src?.src))); if (pictures.some((p) => later.has(p.src) && !early.has(p.src))) problems.push(`${name}: a carousel draws a picture past its second`); if (name === 'gallery') { const photos = carousels[0]?.items ?? []; if (photos.length < 3 || !photos.every((item) => item.srcset)) problems.push('gallery: its photos are not three or more, each with its sizes'); if (pictures.filter((p) => p.srcset !== undefined).length !== 2) problems.push('gallery: it does not draw its shown photo and the next alone, with their sizes'); // Under its comments, Add a comment… signed in; Sign in to comment signed out where the app signs in; neither where it can't. const as = (more) => server.render(server.Tree, { props: { ...props(ui), ...more } }).body; if (!/