app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit c6c1ff55cb4577297e5a67f9e88832daf44a0f3b
parent 2d314401f17cafca00deb9a63ee8ac4adfbf4f1d
Author: triesap <tyson@radroots.org>
Date:   Mon,  5 Oct 2026 06:04:20 +0000

design: build the shared application shell (HCP-014)

- Wire guest navigation, identity disclosure and footer into the actual layout.
- Keep unfinished routes and commands visibly unavailable during development.
- Preserve validated links, current-page emphasis and keyboard skip semantics.
- Verify shell browsers and admit the exact emitted Kit state compiler module.

Diffstat:
Mweb/src/app.css | 21+++++++++++++++++++++
Aweb/src/lib/components/AppShell.svelte | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/routes/+layout.svelte | 7++++---
Mweb/tests/conformance/static.test.ts | 4++--
Mweb/tests/e2e/bootstrap.spec.ts | 31++++++++++++++++++++++++++-----
Aweb/tests/e2e/harness/shell.svelte | 37+++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/shell.spec.ts | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/integration/loopback.test.ts | 5++++-
Mweb/tests/provenance/output.test.mjs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mweb/tests/unit/bootstrap.test.ts | 16++++++++++++----
Aweb/tests/unit/components/AppShellHarness.svelte | 39+++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/components/shell.test.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 3++-
13 files changed, 768 insertions(+), 18 deletions(-)

diff --git a/web/src/app.css b/web/src/app.css @@ -297,3 +297,24 @@ border: 0; } } + +@layer components { + .shell-link { + display: inline-flex; + align-items: center; + min-block-size: var(--control-min-height); + max-inline-size: 100%; + padding-block: var(--space-2); + overflow-wrap: anywhere; + } + .shell-link[aria-current='page'] { + font-weight: var(--font-weight-emphasis); + text-decoration: underline; + } + .skip-link:focus-visible { + display: block; + min-block-size: var(--control-min-height); + padding: var(--space-3) var(--space-4); + background: var(--color-surface); + } +} diff --git a/web/src/lib/components/AppShell.svelte b/web/src/lib/components/AppShell.svelte @@ -0,0 +1,105 @@ +<script lang="ts"> + import type { Snippet } from 'svelte'; + import { internalHref } from '../navigation-url'; + import Button from './primitives/Button.svelte'; + import Disclosure from './primitives/Disclosure.svelte'; + + type ShellRoute = + '/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy'; + type Identity = + | { kind: 'guest'; onconnect?: () => void } + | { kind: 'connected'; publicKey: string; ondisconnect?: () => void }; + let { + children, + currentPath = '/', + availableRoutes = [], + identity = { kind: 'guest' } + }: { + children: Snippet; + currentPath?: string; + availableRoutes?: readonly ShellRoute[]; + identity?: Identity; + } = $props(); + + const unavailable = $derived( + !availableRoutes.includes('/search') || + !availableRoutes.includes('/about') || + !availableRoutes.includes('/privacy') || + (identity.kind === 'guest' + ? !availableRoutes.includes('/sell') || !identity.onconnect + : !availableRoutes.includes('/selling') || + !availableRoutes.includes('/messages') || + !identity.ondisconnect) + ); + + function available(href: string) { + return ( + href === '/' || + availableRoutes.some((route) => route === href.split('#')[0]) + ); + } +</script> + +{#snippet navigation(label: string, href: string, brand = false)} + {#if available(href) && internalHref(href)} + <a + href={internalHref(href)} + class="shell-link" + class:brand + aria-current={currentPath === href ? 'page' : undefined}>{label}</a + > + {:else} + <span + class="shell-link text-muted" + aria-disabled="true" + aria-describedby="shell-availability" + aria-current={currentPath === href ? 'page' : undefined}>{label}</span + > + {/if} +{/snippet} + +<a href={internalHref('#main-content')} class="skip-link visually-hidden" + >Skip to main content</a +> +<header class="navbar"> + <nav aria-label="Primary" class="page navbar__inner"> + <div class="cluster"> + {@render navigation('HarvestCircle', '/', true)} + {@render navigation('Search', '/search')} + {#if identity.kind === 'guest'} + {@render navigation('List food', '/sell')} + <Button + label="Connect extension" + disabled={!identity.onconnect} + onclick={identity.onconnect} + /> + {:else} + {@render navigation('Messages', '/messages')} + {@render navigation('Selling', '/selling')} + <Disclosure summary="Identity"> + <p class="key">{identity.publicKey}</p> + <Button + label="Disconnect" + disabled={!identity.ondisconnect} + onclick={identity.ondisconnect} + /> + </Disclosure> + {/if} + </div> + {#if unavailable} + <p id="shell-availability" class="text-small text-muted"> + Unavailable during development: disabled navigation and actions. + </p> + {/if} + </nav> +</header> +<main id="main-content" tabindex="-1" class="page"> + {@render children()} +</main> +<footer class="footer"> + <nav aria-label="Footer" class="page cluster"> + {@render navigation('About', '/about')} + {@render navigation('Privacy', '/privacy')} + {@render navigation('Help / report', '/about#help')} + </nav> +</footer> diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte @@ -2,11 +2,12 @@ import '../theme.css'; import '../app.css'; import type { Snippet } from 'svelte'; + import { page } from '$app/state'; + import AppShell from '../lib/components/AppShell.svelte'; let { children }: { children: Snippet } = $props(); </script> -<main> - <h1>HarvestCircle</h1> +<AppShell currentPath={page.url.pathname}> {@render children()} -</main> +</AppShell> diff --git a/web/tests/conformance/static.test.ts b/web/tests/conformance/static.test.ts @@ -10,11 +10,11 @@ await test('actual static shell is prerendered and excludes controlled harness c files.some((entry) => entry.isFile() && entry.name === 'index.html') ); const html = await readFile(new URL('index.html', root), 'utf8'); - assert.match(html, /<h1>HarvestCircle<\/h1>/); + assert.match(html, /<a[^>]*href="\/"[^>]*>HarvestCircle<\/a>/); assert.match(html, /<title>HarvestCircle<\/title>/); const fallback = await readFile(new URL('200.html', root), 'utf8'); assert.notEqual(fallback, html); - assert.doesNotMatch(fallback, /<h1>HarvestCircle<\/h1>/); + assert.doesNotMatch(fallback, /<a[^>]*href="\/"[^>]*>HarvestCircle<\/a>/); assert.match(fallback, /<script[\s\S]*_app\/immutable/); for (const document of [html, fallback]) { assert.doesNotMatch( diff --git a/web/tests/e2e/bootstrap.spec.ts b/web/tests/e2e/bootstrap.spec.ts @@ -23,14 +23,14 @@ test('copied nested navigation and refresh boot the real shell without fabricati const staticPage = await withoutJavaScript.newPage(); await staticPage.goto(server.url); await expect( - staticPage.getByRole('heading', { name: 'HarvestCircle' }) + staticPage.getByRole('link', { name: 'HarvestCircle', exact: true }) ).toBeVisible(); await expect(staticPage).toHaveTitle('HarvestCircle'); const fallback = await staticPage.goto(server.url + copiedPath); expect(fallback?.status()).toBe(200); // The separate SPA document has no prerendered product or browser state. await expect( - staticPage.getByRole('heading', { name: 'HarvestCircle' }) + staticPage.getByRole('link', { name: 'HarvestCircle', exact: true }) ).toHaveCount(0); const page = await context.newPage(); @@ -43,7 +43,7 @@ test('copied nested navigation and refresh boot the real shell without fabricati const result = await navigate(); expect(result?.status()).toBe(200); await expect( - page.getByRole('heading', { name: 'HarvestCircle' }) + page.getByRole('link', { name: 'HarvestCircle', exact: true }) ).toBeVisible(); // Future product route controllers remain unimplemented in this slice. await expect( @@ -85,9 +85,30 @@ test('actual browser loads guest shell without an extension', async ({ const page = await context.newPage(); await page.goto(server.url); await expect( - page.getByRole('heading', { name: 'HarvestCircle' }) + page.getByRole('link', { name: 'HarvestCircle', exact: true }) ).toBeVisible(); await expect(page).toHaveTitle('HarvestCircle'); + await expect(page.getByRole('main')).toHaveCount(1); + await expect( + page.getByRole('navigation', { name: 'Primary', exact: true }) + ).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Connect extension' }) + ).toBeDisabled(); + await expect( + page.getByText( + 'Unavailable during development: disabled navigation and actions.' + ) + ).toBeVisible(); + await expect( + page.getByRole('link', { name: 'Search', exact: true }) + ).toHaveCount(0); + await page.keyboard.press('Tab'); + await expect( + page.getByRole('link', { name: 'Skip to main content' }) + ).toBeFocused(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('main')).toBeFocused(); expect(await page.evaluate(() => 'nostr' in window)).toBe(false); console.log(`Controlled browser version: ${browser.version()}`); } finally { @@ -114,7 +135,7 @@ test('controlled provider and actual loopback socket are isolated and torn down' const page = await context.newPage(); await page.goto(server.url); await expect( - page.getByRole('heading', { name: 'HarvestCircle' }) + page.getByRole('link', { name: 'HarvestCircle', exact: true }) ).toBeVisible(); const result = await page.evaluate(async (url) => { const provider = ( diff --git a/web/tests/e2e/harness/shell.svelte b/web/tests/e2e/harness/shell.svelte @@ -0,0 +1,37 @@ +<script lang="ts"> + import AppShell from '../../../src/lib/components/AppShell.svelte'; + let connected = $state(false); + let commands = $state(0); + let enabled = $state(true); + const publicKey = 'HC_TEST_ONLY_PUBLIC_KEY_' + 'a'.repeat(64); + function connect() { + commands++; + connected = true; + } + function disconnect() { + commands++; + connected = false; + } +</script> + +<AppShell + currentPath="/search" + availableRoutes={['/search', '/sell', '/selling', '/about', '/privacy']} + identity={connected + ? { + kind: 'connected', + publicKey, + ondisconnect: enabled ? disconnect : undefined + } + : { kind: 'guest', onconnect: enabled ? connect : undefined }} +> + <h1>HC_TEST_ONLY_SHELL</h1> + <p role="status">Commands: {commands}</p> + <button + type="button" + class="button button--secondary" + onclick={() => { + enabled = !enabled; + }}>Toggle command availability</button + > +</AppShell> diff --git a/web/tests/e2e/shell.spec.ts b/web/tests/e2e/shell.spec.ts @@ -0,0 +1,343 @@ +import { expect, test } from '@playwright/test'; +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { + cp, + mkdtemp, + mkdir, + readFile, + readdir, + rm, + writeFile +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createStaticHarness } from '../integration/harness/static.ts'; + +// Isolated qualification clone: actual components compile into disposable output. +// The primary static payload and product route source are never overwritten. +const capsule = fileURLToPath(new URL('../../../', import.meta.url)); +let directory: string; +let server: Awaited<ReturnType<typeof createStaticHarness>>; +test.beforeAll(async () => { + test.setTimeout(120_000); + directory = await mkdtemp(path.join(tmpdir(), 'hcp014-shell-')); + try { + const checkout = path.join(directory, 'checkout'); + execFileSync('git', [ + 'clone', + '--quiet', + '--no-hardlinks', + capsule, + checkout + ]); + for (const relative of [ + 'web/src/lib/components/AppShell.svelte', + 'web/src/app.css', + 'web/src/routes/+layout.svelte', + 'web/tests/unit/components/shell.test.ts', + 'web/tests/e2e/shell.spec.ts', + 'web/tests/e2e/harness/shell.svelte', + 'web/tests/integration/harness/static.ts' + ]) + await cp(path.join(capsule, relative), path.join(checkout, relative), { + recursive: true + }); + const fixture = await readFile( + path.join(capsule, 'web/tests/e2e/harness/shell.svelte'), + 'utf8' + ); + await writeFile( + path.join(checkout, 'web/src/routes/+page.svelte'), + fixture.replaceAll('../../../src/lib/', '../lib/') + ); + await cp( + path.join(capsule, 'web/node_modules'), + path.join(checkout, 'web/node_modules'), + { recursive: true, verbatimSymlinks: true } + ); + const fixtureLayout = + '<script lang="ts">import "../theme.css"; import "../app.css"; import type { Snippet } from "svelte"; let { children }: { children: Snippet } = $props();</script>{@render children()}'; + await writeFile( + path.join(checkout, 'web/src/routes/+layout.svelte'), + fixtureLayout + ); + // Labelled test destinations only: no product feature/controller qualification. + const derivedTargets = []; + for (const route of ['search', 'sell', 'selling', 'about', 'privacy']) { + const relative = 'web/src/routes/' + route + '/+page.svelte'; + const source = + '<h1>HC_TEST_ONLY_NAVIGATION_TARGET</h1><p id="help">Test destination: ' + + route + + '</p>'; + await mkdir(path.dirname(path.join(checkout, relative)), { + recursive: true + }); + await writeFile(path.join(checkout, relative), source); + derivedTargets.push({ + path: relative, + source, + sha256: createHash('sha256').update(source).digest('hex') + }); + } + const sourceAudit = execFileSync( + process.execPath, + ['tools/check-source.mjs'], + { cwd: path.join(checkout, 'web') } + ).toString(); + const identities = []; + for (const relative of [ + 'web/src/lib/components/AppShell.svelte', + 'web/src/app.css' + ]) { + identities.push({ + name: relative, + sha256: createHash('sha256') + .update(await readFile(path.join(checkout, relative))) + .digest('hex') + }); + } + execFileSync(process.execPath, ['tools/build-info.mjs'], { + cwd: path.join(checkout, 'web') + }); + const compiled = execFileSync( + 'corepack', + ['pnpm', 'exec', 'vite', 'build'], + { + cwd: path.join(checkout, 'web'), + stdio: 'pipe', + timeout: 90_000 + } + ); + async function payload( + directory: string, + prefix = '' + ): Promise<{ path: string; sha256: string }[]> { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const relative = prefix + entry.name; + if (entry.isDirectory()) + files.push( + ...(await payload(path.join(directory, entry.name), relative + '/')) + ); + else + files.push({ + path: relative, + sha256: createHash('sha256') + .update(await readFile(path.join(directory, entry.name))) + .digest('hex') + }); + } + return files.sort((left, right) => left.path.localeCompare(right.path)); + } + console.log( + JSON.stringify({ + fixture: 'HCP014_TEST_ONLY_COMPILE', + identities, + sourceAudit, + fixtureSourceSha256: createHash('sha256').update(fixture).digest('hex'), + compiledRouteSha256: createHash('sha256') + .update( + await readFile(path.join(checkout, 'web/src/routes/+page.svelte')) + ) + .digest('hex'), + compiledLayoutSha256: createHash('sha256') + .update(fixtureLayout) + .digest('hex'), + compiledLayout: fixtureLayout, + derivedTargets, + payload: await payload(path.join(checkout, 'web/build')), + compiled: compiled.toString(), + metadata: JSON.parse( + await readFile( + path.join(checkout, 'web/build/build-info.json'), + 'utf8' + ) + ) as unknown + }) + ); + server = await createStaticHarness({ + buildRoot: path.join(checkout, 'web/build') + }); + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } +}); +test.afterAll(async () => { + await server?.close(); + if (directory) await rm(directory, { recursive: true, force: true }); + if (server) + expect(server.state()).toEqual({ listening: false, childProcesses: 0 }); +}); + +async function measure(page: import('@playwright/test').Page, stage: string) { + const measured = await page.evaluate(() => ({ + width: innerWidth, + scroll: globalThis.document.documentElement.scrollWidth, + navigation: Array.from( + globalThis.document.querySelectorAll( + 'nav[aria-label="Primary"] > .cluster > *' + ) + ).map((element) => { + const rect = element.getBoundingClientRect(); + return { + label: element.textContent?.trim().replace(/\s+/g, ' '), + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height + }; + }), + heights: Array.from( + globalThis.document.querySelectorAll( + 'nav a,nav span[aria-disabled],button,summary' + ) + ) + .filter((element) => element.getBoundingClientRect().height > 0) + .map((element) => element.getBoundingClientRect().height) + })); + expect(measured.scroll).toBeLessThanOrEqual(measured.width); + for (const height of measured.heights) + expect(height).toBeGreaterThanOrEqual(44); + for (let index = 1; index < measured.navigation.length; index++) { + const previous = measured.navigation[index - 1]; + const current = measured.navigation[index]; + expect(current.y + current.height / 2).toBeGreaterThanOrEqual( + previous.y + previous.height / 2 + ); + if (current.y < previous.y + previous.height) + expect(current.x).toBeGreaterThanOrEqual(previous.x + previous.width); + } + if (measured.width === 320) + expect(measured.navigation.at(-1)!.y).toBeGreaterThan( + measured.navigation[0].y + ); + console.log( + JSON.stringify({ + fixture: 'HCP014_CONTROLLED_PRESENTATION_ONLY', + stage, + measured + }) + ); + return measured; +} + +for (const width of [320, 1024]) { + test(`actual shell keyboard, guest/connected order and unavailable callbacks at ${width}px`, async ({ + browser + }) => { + const context = await browser.newContext({ + viewport: { width, height: 900 } + }); + const external: string[] = []; + try { + await context.route('**/*', (route) => { + if (new URL(route.request().url()).origin === server.url) + return route.continue(); + external.push(route.request().url()); + return route.abort(); + }); + const page = await context.newPage(); + await page.goto(server.url); + const skip = page.getByRole('link', { name: 'Skip to main content' }); + await page.keyboard.press('Tab'); + await expect(skip).toBeFocused(); + await expect(skip).toBeVisible(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('main')).toBeFocused(); + await expect(page.locator('main')).toHaveCount(1); + await expect(page.locator('[id="main-content"]')).toHaveCount(1); + const primary = page.getByRole('navigation', { + name: 'Primary', + exact: true + }); + await expect(primary).toHaveText( + 'HarvestCircle Search List food Connect extension' + ); + await expect( + page.getByRole('link', { name: 'Search', exact: true }) + ).toHaveAttribute('aria-current', 'page'); + expect(await page.locator('a[aria-current="page"]').count()).toBe(1); + const guest = await measure(page, 'guest'); + expect(guest.navigation.map((item) => item.label)).toEqual([ + 'HarvestCircle', + 'Search', + 'List food', + 'Connect extension' + ]); + await page.getByRole('button', { name: 'Connect extension' }).focus(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('status')).toHaveText('Commands: 1'); + await expect(primary).toContainText( + 'HarvestCircle Search Messages Selling Identity' + ); + await expect(page.getByText('Messages', { exact: true })).toHaveAttribute( + 'aria-disabled', + 'true' + ); + await expect(page.getByRole('link', { name: 'Messages' })).toHaveCount(0); + await expect(page.getByRole('link', { name: 'Selling' })).toHaveAttribute( + 'href', + '/selling' + ); + const connectedClosed = await measure(page, 'connected-closed'); + expect( + connectedClosed.navigation.map((item) => item.label?.split(' ')[0]) + ).toEqual(['HarvestCircle', 'Search', 'Messages', 'Selling', 'Identity']); + const summary = page.locator('summary'); + await summary.focus(); + await page.keyboard.press('Enter'); + await expect(page.locator('details')).toHaveAttribute('open', ''); + await page.keyboard.press('Space'); + await expect(page.locator('details')).not.toHaveAttribute('open', ''); + await page.keyboard.press('Enter'); + await expect(page.locator('details')).toHaveAttribute('open', ''); + await expect(page.locator('.key')).toHaveText( + 'HC_TEST_ONLY_PUBLIC_KEY_' + 'a'.repeat(64) + ); + await page.keyboard.press('Tab'); + const disconnect = page.getByRole('button', { + name: 'Disconnect', + exact: true + }); + await expect(disconnect).toBeFocused(); + await page + .getByRole('button', { name: 'Toggle command availability' }) + .click(); + await expect(disconnect).toBeDisabled(); + await disconnect.evaluate((element) => + (element as HTMLButtonElement).click() + ); + await disconnect.evaluate((element) => + element.dispatchEvent(new MouseEvent('click', { bubbles: true })) + ); + await expect(page.getByRole('status')).toHaveText('Commands: 1'); + await measure(page, 'connected-open-long-key'); + await expect(page.locator('header')).not.toContainText(/unread/i); + await page + .getByRole('button', { name: 'Toggle command availability' }) + .click(); + await disconnect.focus(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('status')).toHaveText('Commands: 2'); + await page + .getByRole('button', { name: 'Toggle command availability' }) + .click(); + const connect = page.getByRole('button', { name: 'Connect extension' }); + await expect(connect).toBeDisabled(); + await connect.evaluate((element) => + (element as HTMLButtonElement).click() + ); + await connect.evaluate((element) => + element.dispatchEvent(new MouseEvent('click', { bubbles: true })) + ); + await expect(page.getByRole('status')).toHaveText('Commands: 2'); + expect(external).toEqual([]); + } finally { + await context.close(); + } + expect(context.pages()).toHaveLength(0); + }); +} diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts @@ -152,7 +152,10 @@ await test('loopback static fixture serves actual output and closes its listener try { const result = await fetch(server.url); assert.equal(result.status, 200); - assert.match(await result.text(), /<h1>HarvestCircle<\/h1>/); + assert.match( + await result.text(), + /<a[^>]*href="\/"[^>]*>HarvestCircle<\/a>/ + ); assert.equal((await fetch(`${server.url}/missing.js`)).status, 404); } finally { await server.close(); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -101,8 +101,8 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => { async (t) => { const f = await fixture(t); const files = await f.audit(); - // The once-imported theme/compositions add one actual compiled CSS asset. - assert.equal(files.length, 16); + // The route-state import adds one compiler-owned state chunk; CSS stays once-imported. + assert.equal(files.length, 17); assert.equal(files.filter((name) => name.endsWith('.css')).length, 1); assert.ok( files.some((name) => @@ -121,6 +121,79 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => { ); } ); + await t.test( + 'actual route-state compiler module has an owned client counterpart', + async (t) => { + const f = await fixture(t); + const manifest = JSON.parse( + await readFile( + path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), + 'utf8' + ) + ); + const entries = Object.entries(manifest).filter( + ([, record]) => record.name === 'state' + ); + assert.equal(entries.length, 1); + const [key, state] = entries[0]; + assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); + assert.ok( + state.imports.some( + /** @param {string} dependency */ + (dependency) => manifest[dependency].name === 'client.svelte' + ) + ); + assert.deepEqual( + await readFile(path.join(f.web, 'build', state.file)), + await readFile( + path.join(f.web, '.svelte-kit/output/client', state.file) + ) + ); + assert.ok((await f.audit()).includes(state.file)); + } + ); + for (const mutation of [ + 'unknown-name', + 'duplicate-state', + 'missing-counterpart', + 'changed-counterpart' + ]) { + await t.test('state module fails closed: ' + mutation, async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const state = Object.values(manifest).find( + (record) => record.name === 'state' + ); + assert.ok( + state, + 'The actual route-state module must exist before mutation' + ); + if (mutation === 'unknown-name') state.name = 'state-unapproved'; + if (mutation === 'duplicate-state') + manifest['_HCduplicate.js'] = { ...state }; + if (mutation === 'missing-counterpart') + await rm(path.join(f.web, 'build', state.file)); + if (mutation === 'changed-counterpart') + await writeFile( + path.join(f.web, 'build', state.file), + Buffer.concat([ + await readFile(path.join(f.web, 'build', state.file)), + Buffer.from('changed counterpart') + ]) + ); + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects( + f.audit, + mutation.endsWith('name') || mutation === 'duplicate-state' + ? /Undeclared compiler module/ + : /Static output inventory mismatch|Static output differs from owned compiler input/ + ); + }); + } for (const name of [ 'notes.txt', '_app/immutable/chunks/innocent.ABC12345.js', diff --git a/web/tests/unit/bootstrap.test.ts b/web/tests/unit/bootstrap.test.ts @@ -1,8 +1,12 @@ import { render } from 'svelte/server'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import Shell from './Shell.svelte'; import { prerender, ssr } from '../../src/routes/+layout'; +vi.mock('$app/state', () => ({ + page: { url: new URL('https://ssr.invalid/') } +})); + describe('static guest shell', () => { it('keeps browser globals absent and enforces effect tripwires', () => { expect('window' in globalThis).toBe(false); @@ -18,16 +22,20 @@ describe('static guest shell', () => { }); it('imports and renders on the server without browser capabilities', () => { const output = render(Shell); - expect(output.body).toContain('<h1>HarvestCircle</h1>'); + expect(output.body).toMatch(/<a[^>]*href="\/"[^>]*>HarvestCircle<\/a>/); expect(output.head).toContain('<title>HarvestCircle</title>'); expect(prerender).toBe(true); expect(ssr).toBe(true); }); - it('composes the root layout and route with semantic guest content', () => { + it('composes the actual shared shell and preserves the route body without a global h1', () => { const output = render(Shell); expect(output.body).toMatch( - /<main>[\s\S]*<h1>HarvestCircle<\/h1>[\s\S]*<\/main>/ + /<main id="main-content" tabindex="-1"[^>]*>[\s\S]*<\/main>/ ); + expect(output.body).toContain('aria-label="Primary"'); + expect(output.body).toContain('aria-label="Footer"'); + expect(output.body).toContain('Unavailable during development'); + expect(output.body).not.toContain('<h1>HarvestCircle'); expect(output.body).not.toContain('private'); }); }); diff --git a/web/tests/unit/components/AppShellHarness.svelte b/web/tests/unit/components/AppShellHarness.svelte @@ -0,0 +1,39 @@ +<script lang="ts"> + import AppShell from '../../../src/lib/components/AppShell.svelte'; + let { + connected = false, + available = false, + messages = true, + currentPath = '/', + publicKey = 'HC_TEST_ONLY_PUBLIC_KEY_' + 'a'.repeat(64), + onconnect, + ondisconnect + }: { + connected?: boolean; + available?: boolean; + messages?: boolean; + currentPath?: string; + publicKey?: string; + onconnect?: () => void; + ondisconnect?: () => void; + } = $props(); +</script> + +<AppShell + {currentPath} + availableRoutes={available + ? [ + '/search', + '/sell', + ...(connected ? ['/selling' as const] : []), + ...(connected && messages ? ['/messages' as const] : []), + '/about', + '/privacy' + ] + : []} + identity={connected + ? { kind: 'connected', publicKey, ondisconnect } + : { kind: 'guest', onconnect }} +> + <h1>Fixture route heading</h1> +</AppShell> diff --git a/web/tests/unit/components/shell.test.ts b/web/tests/unit/components/shell.test.ts @@ -0,0 +1,98 @@ +import { render } from 'svelte/server'; +import type { ComponentProps } from 'svelte'; +import { describe, expect, it } from 'vitest'; +import AppShellHarness from './AppShellHarness.svelte'; + +function body(props: ComponentProps<typeof AppShellHarness> = {}) { + return render(AppShellHarness, { props }).body; +} + +describe('shared application shell SSR', () => { + it('keeps guest order, semantic landmarks, skip target and route heading', () => { + const html = body({ available: true }); + const labels = [ + 'HarvestCircle', + 'Search', + 'List food', + 'Connect extension' + ]; + for (let index = 1; index < labels.length; index++) + expect(html.indexOf(labels[index - 1])).toBeLessThan( + html.indexOf(labels[index]) + ); + expect(html).toContain('<header'); + expect(html).toContain('aria-label="Primary"'); + expect(html).toContain('href="#main-content"'); + expect(html).toContain('id="main-content" tabindex="-1"'); + expect(html).toContain('<h1>Fixture route heading</h1>'); + expect(html).not.toContain('<h1>HarvestCircle'); + expect(html).toContain('<footer'); + expect(html).toContain('href="/about#help"'); + }); + it('keeps connected order, unchanged public key, native disclosure and no unread promise', () => { + const publicKey = 'HC_TEST_ONLY_<' + 'b'.repeat(64); + const html = body({ connected: true, available: true, publicKey }); + const labels = [ + 'HarvestCircle', + 'Search', + 'Messages', + 'Selling', + 'Identity' + ]; + for (let index = 1; index < labels.length; index++) + expect(html.indexOf(labels[index - 1])).toBeLessThan( + html.indexOf(labels[index]) + ); + expect(html).toContain('href="/selling"'); + expect(html).toContain('<summary>Identity</summary>'); + expect(html).toContain('HC_TEST_ONLY_&lt;' + 'b'.repeat(64)); + expect(html).toContain('Disconnect'); + expect(html).not.toMatch( + /unread|aria-live|account|settings|Connect extension/ + ); + }); + it('marks only the real current route and never navigates an invalid current path', () => { + const html = body({ available: true, currentPath: '/search' }); + expect(html).toMatch(/href="\/search"[^>]*aria-current="page"/); + expect(html.match(/aria-current="page"/g)).toHaveLength(1); + expect(body({ currentPath: '//invalid.example' })).not.toContain( + 'href="//invalid.example' + ); + }); + it('keeps unfinished routes and missing callbacks visibly unavailable without links', () => { + const html = body({ connected: true }); + expect(html).toContain('Unavailable during development'); + expect(html).not.toMatch( + /href="\/(search|sell|selling|messages|about|privacy)/ + ); + expect(html).toMatch(/<button[^>]*disabled[^>]*>Disconnect/); + expect(html).toContain('aria-disabled="true"'); + expect(html).toContain('Messages'); + }); + it('reports only currently visible unavailable routes and commands', () => { + const forbidden = () => { + throw new Error('SSR invoked command'); + }; + expect(body({ available: true, onconnect: forbidden })).not.toContain( + 'Unavailable during development' + ); + const html = body({ + connected: true, + available: true, + messages: false, + ondisconnect: forbidden + }); + expect(html).toContain('Unavailable during development'); + expect(html).toContain('Messages'); + expect(html).not.toContain('href="/messages"'); + }); + it('never invokes callbacks or browser effects while server rendering', () => { + const forbidden = () => { + throw new Error('SSR invoked command'); + }; + expect(() => body({ onconnect: forbidden })).not.toThrow(); + expect(() => + body({ connected: true, ondisconnect: forbidden }) + ).not.toThrow(); + }); +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -212,7 +212,8 @@ export async function auditOutput(webDirectory) { 'preload-helper', 'client', 'client.svelte', - 'client-entry' + 'client-entry', + 'state' ]); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set();