app

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

commit e481b041f69402b94ab00c64b02fca56a1f4b748
parent 1e9be275a3d2d4e257829a508a476a6fddecaf60
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 19:59:07 +0000

web: wire the real search page and list components (HCP-043)

- Render genuine public listings with bounded foreground search and publisher views.
- Preserve uncertainty, explicit Older reads, local More and public query history.
- Guard initialization and teardown while retaining shared runtime ownership.
- Verify search behavior, browser history and exact compiler boundary controls.

Diffstat:
Aweb/src/lib/catalog/search-view.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/components/ListingRow.svelte | 34++++++++++++++++++++++++++++++++++
Aweb/src/lib/components/SourceStatus.svelte | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/navigation-scroll.ts | 20++++++++++++++++++++
Mweb/src/routes/search/+page.svelte | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mweb/tests/e2e/query-navigation.spec.ts | 2+-
Aweb/tests/e2e/search-results.spec.ts | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/integration/loopback.test.ts | 4++--
Aweb/tests/integration/search-view.test.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 145++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mweb/tests/provenance/source-boundaries.test.mjs | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/components/search-listings.test.ts | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/search-view.test.ts | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mweb/tools/source-boundaries.mjs | 40+++++++++++++++++++++++++++++++++++-----
15 files changed, 1930 insertions(+), 30 deletions(-)

diff --git a/web/src/lib/catalog/search-view.ts b/web/src/lib/catalog/search-view.ts @@ -0,0 +1,172 @@ +import type { PublicView } from '../runtime/public-runtime.ts'; +import type { PublicHead } from './heads.ts'; +import type { WallClock } from './clock-policy.ts'; +import type { SearchSnapshot } from './search-state.ts'; +import { + createFoodSearchCoordinator, + beginFoodSearch, + sampleFoodSearch, + chronologicalFoodSearch, + foodSearchSnapshot, + resolveFoodSearchPublishers, + showMoreFoodSearch, + searchOlderFoodSearch, + closeFoodSearchCoordinator, + type FoodSearchRun +} from './search-run.ts'; +export type SearchViewSnapshot = SearchSnapshot<FoodSearchRun>; +export type ForegroundSchedule = ( + callback: () => void, + delay: number +) => () => void; +declare const viewBrand: unique symbol; +export type SearchView = Readonly<{ readonly [viewBrand]: true }>; +interface Owner { + readonly start: (query: unknown, known: readonly PublicHead[]) => void; + readonly more: () => void; + readonly older: () => void; + readonly snapshot: () => SearchViewSnapshot | undefined; + readonly close: () => void; +} +const owners = new WeakMap<SearchView, Owner>(); +function ownerOf(view: SearchView): Owner { + const owner = owners.get(view); + if (!owner) throw Error('search_view_invalid'); + return owner; +} +function foreground(callback: () => void, delay: number): () => void { + const timer = setTimeout(() => { + callback(); + }, delay); + return () => { + clearTimeout(timer); + }; +} +// This owner observes a finite public run; it never creates a background poll, +// transport, shared cache or new deadline. Explicit actions alone restart runs. +export function createSearchView( + view: PublicView, + clock: WallClock, + onUpdate: (value: SearchViewSnapshot) => void, + schedule: ForegroundSchedule = foreground +): SearchView { + const coordinator = createFoodSearchCoordinator(view, clock); + let generation: FoodSearchRun | undefined, + cancel: (() => void) | undefined, + closed = false; + function stop() { + const previous = cancel; + cancel = undefined; + previous?.(); + } + function current(token: FoodSearchRun) { + return !closed && generation === token; + } + function requireOpen() { + if (closed) throw Error('search_view_closed'); + } + function publish(token: FoodSearchRun) { + const value = foodSearchSnapshot(coordinator); + if (value && current(token) && value.generation === token) onUpdate(value); + return value; + } + function queue(token: FoodSearchRun) { + if (!current(token)) return; + const value = foodSearchSnapshot(coordinator); + if (!value?.run?.active || !current(token)) return; + const pending = schedule(() => { + if (!current(token)) return; + cancel = undefined; + observe(token); + }, 250); + if (current(token)) cancel = pending; + else pending(); + } + function observe(token: FoodSearchRun) { + if (!current(token)) return; + const value = foodSearchSnapshot(coordinator); + if (!value || !current(token)) return; + if (value.run?.active && value.available && value.listings.length) { + try { + resolveFoodSearchPublishers(token); + } catch { + /* Failed metadata retains key fallback and source uncertainty. */ + } + } + if (!current(token)) return; + const updated = publish(token); + if (updated?.run?.active && updated.run.activeRequests > 0) queue(token); + } + const token = Object.freeze({}) as SearchView; + owners.set(token, { + start(query, known) { + requireOpen(); + // Coordinator validates the complete query and seeds before any effects; + // a rejected edit cannot cancel a previously accepted foreground observer. + const next = beginFoodSearch(coordinator, query, known); + stop(); + generation = next; + try { + sampleFoodSearch(next); + } catch { + /* Retain ordinary chronological fallback. */ + } + if (!current(next)) return; + try { + chronologicalFoodSearch(next); + } catch { + /* Snapshot reports the actual failed source; known rows survive. */ + } + if (current(next)) { + publish(next); + queue(next); + } + }, + more() { + requireOpen(); + if (!generation) throw Error('search_view_inactive'); + const next = generation; + showMoreFoodSearch(next); + stop(); + publish(next); + queue(next); + }, + older() { + requireOpen(); + const next = searchOlderFoodSearch(coordinator); + stop(); + generation = next; + publish(next); + queue(next); + }, + snapshot: () => foodSearchSnapshot(coordinator), + close() { + closed = true; + stop(); + closeFoodSearchCoordinator(coordinator); + generation = undefined; + } + }); + return token; +} +export function startSearchView( + view: SearchView, + query: unknown, + known: readonly PublicHead[] = [] +): void { + ownerOf(view).start(query, known); +} +export function moreSearchView(view: SearchView): void { + ownerOf(view).more(); +} +export function olderSearchView(view: SearchView): void { + ownerOf(view).older(); +} +export function searchViewSnapshot( + view: SearchView +): SearchViewSnapshot | undefined { + return ownerOf(view).snapshot(); +} +export function closeSearchView(view: SearchView): void { + ownerOf(view).close(); +} diff --git a/web/src/lib/components/ListingRow.svelte b/web/src/lib/components/ListingRow.svelte @@ -0,0 +1,34 @@ +<script lang="ts"> + import type { ListingView } from '../catalog/listing-view.ts'; + import { internalHref } from '../navigation-url.ts'; + import Disclosure from './primitives/Disclosure.svelte'; + let { listing }: { listing: ListingView } = $props(); + function timestamp(seconds: number): string { + const milliseconds = seconds * 1000; + return Number.isFinite(milliseconds) && + Math.abs(milliseconds) <= 8640000000000000 + ? new Date(milliseconds).toISOString() + : `${seconds} seconds since the Unix epoch`; + } +</script> + +<article class="stack"> + <h2><a href={internalHref(listing.href)}>{listing.title}</a></h2> + <p>{listing.price.currency} {listing.price.amount} / {listing.price.unit}</p> + <p>{listing.publisher.label} · {listing.location}</p> + {#if listing.quantity}<p> + Advertised quantity: {listing.quantity.amount} + {listing.quantity.unit} + </p>{:else}<p>Advertised quantity not specified</p>{/if} + <p>{listing.summary}</p> + <p>Seller updated: {timestamp(listing.createdAt)}</p> + {#if listing.lastKnown}<p class="notice"> + Last known listing. Availability has not been confirmed. + </p>{/if} + <Disclosure summary="Publisher details"> + {#if listing.publisher.assertedName}<p> + This name is asserted by the publisher. + </p>{/if} + <p>Publisher key: <code>{listing.publisher.pubkey}</code></p> + </Disclosure> +</article> diff --git a/web/src/lib/components/SourceStatus.svelte b/web/src/lib/components/SourceStatus.svelte @@ -0,0 +1,70 @@ +<script lang="ts"> + import type { SearchRefresh, SearchScope } from '../catalog/search-state.ts'; + import Disclosure from './primitives/Disclosure.svelte'; + let { + refresh, + gap, + scopes + }: { refresh: SearchRefresh; gap: boolean; scopes: readonly SearchScope[] } = + $props(); + const failedSources = $derived( + scopes + .flatMap((scope) => + scope.result.sources + .filter( + (source) => source.state === 'error' || source.state === 'closed' + ) + .map((source) => source.source) + ) + .filter((source, index, values) => values.indexOf(source) === index) + ); +</script> + +<div class="stack"> + {#if refresh === 'unavailable'}<p class="notice"> + Search sources are unavailable. + </p> + {:else if failedSources.length === 1}<p class="notice"> + One source could not complete the search. These results may be incomplete. + </p> + {:else if failedSources.length > 1}<p class="notice"> + Some sources could not complete the search. These results may be + incomplete. + </p> + {:else if refresh === 'refreshing' || refresh === 'idle'}<p> + Checking search sources… + </p> + {:else if refresh === 'cancelled'}<p class="notice"> + Search was cancelled. These results may be incomplete. + </p> + {:else if refresh === 'deadline'}<p class="notice"> + The search time limit was reached. These results may be incomplete. + </p> + {:else if refresh === 'limit'}<p class="notice"> + The search resource limit was reached. These results may be incomplete. + </p> + {:else if refresh === 'error'}<p class="notice"> + The search could not finish. These results may be incomplete. + </p> + {:else if refresh !== 'bounded-eose'}<p class="notice"> + These results may be incomplete. + </p> + {:else}<p>Results are limited to the sources checked.</p>{/if} + {#if gap}<p class="notice"> + The sources returned too many listings at the same timestamp. Older + results may be missing. + </p>{/if} + <Disclosure summary="Source details"> + {#each scopes as scope (scope.result.context)}<p> + Source request: {scope.state}. Coverage: {scope.result.coverage}. + </p> + {#each scope.result.sources as source (source.source)}<p> + {source.source}: {source.state}. {source.accepted} verified deliveries admitted. + </p>{/each} + {/each} + <p> + Searches check a bounded set of sources. They do not prove complete + coverage or current stock. + </p> + </Disclosure> +</div> diff --git a/web/src/lib/navigation-scroll.ts b/web/src/lib/navigation-scroll.ts @@ -0,0 +1,20 @@ +// Reviewed scalar history capability. Import is SSR-pure; callers own the +// current public query/generation and render/disposal lifetime. No DOM handle, +// callable browser method, timer, storage or global object leaves this module. +function validPosition(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isFinite(value) && + value >= 0 && + value <= Number.MAX_SAFE_INTEGER + ); +} +export function captureSearchScroll(): number | undefined { + if (typeof window === 'undefined') return undefined; + const position = window.scrollY; + return validPosition(position) ? position : undefined; +} +export function restoreSearchScroll(position: unknown): void { + if (typeof window === 'undefined' || !validPosition(position)) return; + window.scrollTo(0, position); +} diff --git a/web/src/routes/search/+page.svelte b/web/src/routes/search/+page.svelte @@ -1,34 +1,211 @@ <script lang="ts"> + import { getContext, onMount, tick } from 'svelte'; import { page } from '$app/state'; + import { goto } from '$app/navigation'; import SearchForm from '../../lib/components/SearchForm.svelte'; + import ListingRow from '../../lib/components/ListingRow.svelte'; + import SourceStatus from '../../lib/components/SourceStatus.svelte'; + import Button from '../../lib/components/primitives/Button.svelte'; import { normalizePublicQuery, queryErrorMessage, - readPublicQuery - } from '../../lib/catalog/query-input'; - import type { PublicQuery } from '../../lib/catalog/query-input'; + readPublicQuery, + type PublicQuery + } from '../../lib/catalog/query-input.ts'; import { searchHref } from '../../lib/routes'; - import { internalHref } from '../../lib/navigation-url'; - let query = $state<PublicQuery>(normalizePublicQuery('')); - let error = $state<string | undefined>(); + import { internalHref } from '../../lib/navigation-url.ts'; + import { + PUBLIC_RUNTIME_CONTEXT, + publicRuntimeReady, + createPublicView, + disposePublicView, + type PublicView, + type PublicRuntimeContext + } from '../../lib/runtime/public-runtime.ts'; + import { + createSearchView, + startSearchView, + moreSearchView, + olderSearchView, + closeSearchView, + type SearchView, + type SearchViewSnapshot + } from '../../lib/catalog/search-view.ts'; + import { + captureSearchScroll, + restoreSearchScroll + } from '../../lib/navigation-scroll.ts'; + let pendingScroll = $state.raw< + { query: string; position: number } | undefined + >(); + let mounted = false; + export const snapshot = { + capture: () => { + const current = readPublicQuery(page.url); + return { + query: current.ok ? current.text : undefined, + position: captureSearchScroll() + }; + }, + restore: (value: unknown) => { + if ( + typeof value !== 'object' || + value === null || + !('query' in value) || + typeof value.query !== 'string' || + !('position' in value) || + typeof value.position !== 'number' + ) + return; + const query = normalizePublicQuery(value.query); + if (!query.ok || query.text !== value.query) return; + pendingScroll = { query: query.text, position: value.position }; + } + }; + const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT); + let query = $state<PublicQuery>(normalizePublicQuery('')), + error = $state<string | undefined>(); + let owner = $state.raw<SearchView | undefined>(), + result = $state.raw<SearchViewSnapshot | undefined>(); + let activeQuery: string | undefined; + onMount(() => { + mounted = true; + let disposed = false; + const unavailable = () => { + if (!disposed) { + owner = undefined; + error = 'Search sources are unavailable.'; + } + }; + try { + void publicRuntimeReady(context) + .then((runtime) => { + if (disposed || !runtime) return; + let acquired: PublicView | undefined; + try { + acquired = createPublicView(runtime); + owner = createSearchView( + acquired, + { nowSeconds: () => Math.floor(Date.now() / 1000) }, + (value) => { + result = value; + } + ); + } catch { + // Only this page's partial view is owned here; the shared runtime + // retains its public budget and any retryable failed disposer. + if (acquired) disposePublicView(acquired); + unavailable(); + } + }) + .catch(unavailable); + } catch { + unavailable(); + } + return () => { + disposed = true; + mounted = false; + pendingScroll = undefined; + if (owner) closeSearchView(owner); + }; + }); $effect(() => { query = readPublicQuery(page.url); error = undefined; }); + $effect(() => { + if (owner && query.ok && activeQuery !== query.text) { + const next = query.text; + activeQuery = next; + try { + startSearchView(owner, next); + } catch { + error = 'Search could not start. Please try again.'; + } + } + }); + $effect(() => { + const saved = pendingScroll, + current = result; + if ( + !saved || + !current?.listings.length || + !query.ok || + saved.query !== query.text || + current.query !== saved.query + ) + return; + void tick().then(() => { + const currentQuery = readPublicQuery(page.url); + if ( + mounted && + pendingScroll === saved && + result?.generation === current.generation && + page.url.pathname === '/search' && + currentQuery.ok && + currentQuery.text === saved.query && + result.query === saved.query + ) { + restoreSearchScroll(saved.position); + pendingScroll = undefined; + } + }); + }); function search(input: string) { + pendingScroll = undefined; const next = normalizePublicQuery(input); if (!next.ok) { error = queryErrorMessage(next.error); return; } - error = undefined; const target = internalHref(searchHref(next.text)); if (target === undefined) { error = queryErrorMessage('invalid_query'); return; } - globalThis.location.assign(target); + error = undefined; + if (owner && query.ok && query.text === next.text) { + try { + startSearchView(owner, next); + } catch { + error = 'Search could not start. Please try again.'; + } + return; + } + if (target !== undefined) void goto(target); + } + function more() { + pendingScroll = undefined; + if (owner) moreSearchView(owner); } + function older() { + pendingScroll = undefined; + if (owner) { + try { + olderSearchView(owner); + } catch { + error = + 'Older listings could not be checked. These results may be incomplete.'; + } + } + } + const noSources = $derived( + result?.scopes + .filter((scope) => scope.kind === 'search') + .every( + (scope) => + scope.result.sources.length === 0 || + scope.result.sources.every( + (source) => source.state === 'error' || source.state === 'closed' + ) + ) ?? false + ); + const refresh = $derived( + (noSources || (result?.refresh === 'error' && !result.scopes.length)) && + !result?.listings.length + ? 'unavailable' + : (result?.refresh ?? 'unavailable') + ); </script> <svelte:head><title>Search food — HarvestCircle</title></svelte:head> @@ -39,5 +216,31 @@ initialValue={query.ok ? query.text : ''} error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))} /> - <p class="notice">Search data is unavailable during development.</p> + <SourceStatus + {refresh} + gap={result?.continuation.gap ?? false} + scopes={result?.scopes ?? []} + /> + {#if result?.listings.length} + <p> + {result.listings.length} listings shown in the sources checked. Newest updates + first. + </p> + <ul class="stack"> + {#each result.listings as listing (listing.href)}<li> + <ListingRow {listing} /> + </li>{/each} + </ul> + {:else if refresh === 'bounded-eose'}<p> + No matches in the sources checked. Try fewer words or search older + listings. + </p>{/if} + <div class="cluster"> + {#if result?.hasMore}<Button label="Show more" onclick={more} />{/if} + {#if result?.continuation.until !== undefined}<Button + label="Search older listings" + onclick={older} + disabled={result.continuation.active || result.continuation.gap} + />{/if} + </div> </div> diff --git a/web/tests/e2e/query-navigation.spec.ts b/web/tests/e2e/query-navigation.spec.ts @@ -28,7 +28,7 @@ test('real public query navigation normalizes copies and restores Back/Forward s ); await expect(input).toHaveValue('carrots victoria 菜'); await expect( - page.getByText('Search data is unavailable during development.') + page.getByText('Search sources are unavailable.') ).toBeVisible(); await input.fill('Turnips'); await page.getByRole('button', { name: 'Search', exact: true }).click(); diff --git a/web/tests/e2e/search-results.spec.ts b/web/tests/e2e/search-results.spec.ts @@ -0,0 +1,346 @@ +import { expect, test } from '@playwright/test'; +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { + cp, + mkdtemp, + readFile, + readdir, + rm, + writeFile +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { once } from 'node:events'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import WebSocket, { WebSocketServer, type RawData } from 'ws'; +function wireText(bytes: RawData): string { + const buffer = Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes); + return buffer.toString('utf8'); +} +import { createStaticHarness } from '../integration/harness/static.ts'; +const capsule = fileURLToPath(new URL('../../../', import.meta.url)); +let directory: string; +let server: Awaited<ReturnType<typeof createStaticHarness>>; +// Verification fixture: compile exact primary source, deriving only its fixed +// deployment allowlist. Never alter the primary output or production policy. +test.beforeAll(async () => { + test.setTimeout(120000); + directory = await mkdtemp(path.join(tmpdir(), 'hcp043-search-')); + try { + const checkout = path.join(directory, 'checkout'), + web = path.join(checkout, 'web'); + execFileSync('git', [ + 'clone', + '--quiet', + '--no-hardlinks', + capsule, + checkout + ]); + await cp(path.join(capsule, 'web/src'), path.join(web, 'src'), { + recursive: true + }); + const identities: { path: string; sha256: string }[] = []; + async function identify(dir: string, prefix = '') { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const relative = prefix + entry.name; + if (entry.isDirectory()) + await identify(path.join(dir, entry.name), relative + '/'); + else + identities.push({ + path: relative, + sha256: createHash('sha256') + .update(await readFile(path.join(dir, entry.name))) + .digest('hex') + }); + } + } + await identify(path.join(web, 'src')); + await cp( + path.join(capsule, 'web/tools/source-boundaries.mjs'), + path.join(web, 'tools/source-boundaries.mjs') + ); + identities.push({ + path: 'tools/source-boundaries.mjs', + sha256: createHash('sha256') + .update(await readFile(path.join(web, 'tools/source-boundaries.mjs'))) + .digest('hex') + }); + const policy = + "import { validateRelayPolicy } from './relays.ts'; const policy=validateRelayPolicy(JSON.stringify({schemaVersion:1,public:[{origin:'wss://one.example.org',read:true,write:false,nip50:false},{origin:'wss://failed.example.org',read:true,write:false,nip50:false}],inbox:[],postingEnabled:false,messagingEnabled:false,operatorDenylist:[]})); if(!policy) throw new Error('fixture_policy'); export const deploymentRelayPolicy=policy;"; + await writeFile( + path.join(web, 'src/lib/config/deployment-relays.ts'), + policy + ); + const installed = execFileSync( + 'corepack', + ['pnpm', 'install', '--offline', '--frozen-lockfile'], + { cwd: web, timeout: 90000 } + ).toString(); + const sourceAudit = execFileSync( + process.execPath, + ['tools/check-source.mjs'], + { cwd: web } + ).toString(); + execFileSync(process.execPath, ['tools/build-info.mjs'], { cwd: web }); + const compiled = execFileSync( + process.execPath, + ['node_modules/vite/bin/vite.js', 'build'], + { cwd: web, timeout: 90000 } + ).toString(); + console.log( + JSON.stringify({ + fixture: 'HCP043_TEST_ONLY_FIXED_POLICY', + identities, + policy, + policySha256: createHash('sha256').update(policy).digest('hex'), + installed, + sourceAudit, + compiled + }) + ); + server = await createStaticHarness({ buildRoot: path.join(web, 'build') }); + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } +}); +test.afterAll(async () => { + if (server) await server.close(); + if (directory) await rm(directory, { recursive: true, force: true }); +}); +test('real search renders verified loopback rows, persistent partial notices, independent row actions and restored query/scroll', async ({ + browser +}) => { + const corpus = JSON.parse( + await readFile( + path.join(capsule, 'contracts/interop/food_availability/corpus.v1.json'), + 'utf8' + ) + ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; + const base = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous + ) as { tags: string[][]; content: string; created_at: number }; + const key = crypto.getRandomValues(new Uint8Array(32)); + const listings = Array.from({ length: 26 }, (_, n) => + finalizeEvent( + { + kind: 30402, + created_at: base.created_at - n, + tags: base.tags.map((t) => + t[0] === 'd' + ? ['d', `browser_${n}`] + : t[0] === 'title' + ? ['title', `Carrots ${n}`] + : [...t] + ), + content: base.content + }, + key + ) + ); + const profile = finalizeEvent( + { + kind: 0, + created_at: base.created_at, + tags: [], + content: JSON.stringify({ + display_name: '<img src=https://tracking.example.org>' + }) + }, + key + ); + key.fill(0); + const relay = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + const queries: Record<string, unknown>[] = [], + closed: string[] = []; + relay.on('connection', (socket) => { + socket.on('message', (bytes) => { + const frame = JSON.parse(wireText(bytes)) as unknown[]; + if (frame[0] === 'CLOSE') { + closed.push(String(frame[1])); + return; + } + if (frame[0] !== 'REQ') return; + const id = String(frame[1]), + filters = frame.slice(2) as Record<string, unknown>[]; + queries.push(...filters); + const kind = (filters[0].kinds as number[])[0]; + const values = + kind === 0 + ? [profile] + : kind === 30402 + ? listings.filter((v) => + filters.some( + (f) => + (!f.authors || + (f.authors as string[]).includes(v.pubkey)) && + (!f['#d'] || + (f['#d'] as string[]).includes( + v.tags.find((t) => t[0] === 'd')![1] + )) && + (!f.until || v.created_at <= Number(f.until)) + ) + ) + : []; + for (const value of values) + socket.send(JSON.stringify(['EVENT', id, value])); + socket.send(JSON.stringify(['EOSE', id])); + }); + }); + await once(relay, 'listening'); + const address = relay.address(); + if (!address || typeof address === 'string') throw Error('fixture_port'); + const context = await browser.newContext({ + viewport: { width: 320, height: 700 } + }), + bridges: WebSocket[] = [], + external: string[] = [], + failures: 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(); + }); + await context.routeWebSocket('**/*', (route) => { + if (new URL(route.url()).hostname === 'failed.example.org') { + route.onMessage((message) => { + const frame = JSON.parse(String(message)) as unknown[]; + if (frame[0] === 'REQ') + route.send( + JSON.stringify(['CLOSED', frame[1], 'fixture source unavailable']) + ); + }); + return; + } + expect(new URL(route.url()).hostname).toBe('one.example.org'); + const bridge = new WebSocket(`ws://127.0.0.1:${address.port}`); + bridges.push(bridge); + const pending: (string | Buffer)[] = []; + bridge.on('open', () => { + for (const message of pending.splice(0)) bridge.send(message); + }); + bridge.on('message', (bytes) => route.send(wireText(bytes))); + route.onMessage((message) => { + if (bridge.readyState === WebSocket.OPEN) bridge.send(message); + else pending.push(message); + }); + route.onClose(() => { + bridge.close(); + }); + }); + const page = await context.newPage(); + page.on('pageerror', (e) => failures.push(e.message)); + await page.goto(server.url + '/search?q=carrots'); + const input = page.getByRole('textbox', { + name: 'What are you looking for?' + }); + await expect(input).toBeEnabled(); + await input.focus(); + const rows = page + .getByRole('listitem') + .filter({ has: page.getByRole('link', { name: /^Carrots / }) }); + try { + await expect(rows).toHaveCount(20); + } catch (error) { + console.log( + JSON.stringify({ + fixtureFailure: true, + failures, + queries, + external, + body: await page.locator('body').innerText() + }) + ); + throw error; + } + await expect(input).toBeFocused(); + await expect( + page.getByText('These results may be incomplete.', { exact: false }) + ).toBeVisible(); + await expect( + page.getByRole('button', { name: 'Show more', exact: true }) + ).toBeVisible(); + const discovery = () => + queries.filter((q) => (q.kinds as number[])[0] === 30402 && !q.authors) + .length; + const before = discovery(); + await page.getByRole('button', { name: 'Show more', exact: true }).click(); + await expect(rows).toHaveCount(26); + expect(discovery()).toBe(before); + await page.waitForTimeout(350); + expect(discovery()).toBe(before); + const first = rows.first(); + await first.getByText('Publisher details', { exact: true }).click(); + await expect( + first.getByText(profile.pubkey, { exact: true }) + ).toBeVisible(); + expect(new URL(page.url()).pathname).toBe('/search'); + await expect( + page.getByRole('button', { name: 'Search older listings', exact: true }) + ).toBeVisible(); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + ) + ).toBe(true); + await rows.nth(3).getByRole('link').scrollIntoViewIfNeeded(); + const scroll = await page.evaluate(() => scrollY); + await rows.nth(3).getByRole('link').click(); + await expect(page).toHaveURL(/\/products\/naddr/); + await page.goBack(); + await expect( + page.getByRole('textbox', { name: 'What are you looking for?' }) + ).toHaveValue('carrots'); + // Kit history snapshots and the reviewed scalar helper restore public query + // position after genuine rows render. No private context is retained. + await expect + .poll(() => page.evaluate(() => scrollY)) + .toBeCloseTo(scroll, -1); + await page + .getByRole('textbox', { name: 'What are you looking for?' }) + .fill('turnips'); + await page.getByRole('button', { name: 'Search', exact: true }).click(); + await expect(page).toHaveURL(server.url + '/search?q=turnips'); + await expect(rows).toHaveCount(0); + await page.goBack(); + await expect( + page.getByRole('textbox', { name: 'What are you looking for?' }) + ).toHaveValue('carrots'); + await expect(rows).toHaveCount(20); + await page.goForward(); + await expect(input).toHaveValue('turnips'); + await expect(rows).toHaveCount(0); + await page.goBack(); + await expect(input).toHaveValue('carrots'); + await expect(rows).toHaveCount(20); + const olderCount = discovery(); + await page + .getByRole('button', { name: 'Search older listings', exact: true }) + .click(); + await expect.poll(discovery).toBe(olderCount + 1); + await page.goto(server.url + '/about'); + await expect.poll(() => closed.length).toBeGreaterThan(0); + expect(external).toEqual([]); + expect(failures).toEqual([]); + expect(await page.evaluate(() => 'nostr' in window)).toBe(false); + } finally { + await context.close(); + for (const bridge of bridges) bridge.terminate(); + for (const socket of relay.clients) socket.terminate(); + await new Promise<void>((resolve, reject) => + relay.close((e) => (e ? reject(e) : resolve())) + ); + } +}); diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts @@ -36,7 +36,6 @@ await test('real loopback REQ/CLOSE and active teardown release owned resources' }); await test('navigation fallback serves actual separate output and preserves missing assets', async () => { - const server = await createStaticHarness(); const fallback = await readFile( new URL('../../build/200.html', import.meta.url), 'utf8' @@ -71,8 +70,9 @@ await test('navigation fallback serves actual separate output and preserves miss } assert.notEqual(search, fallback); assert.match(search, /<title>Search food — HarvestCircle<\/title>/); - assert.match(search, /Search data is unavailable during development\./); + assert.match(search, /Search sources are unavailable\./); const document = { accept: 'text/html', 'sec-fetch-dest': 'document' }; + const server = await createStaticHarness(); try { for (const pathname of [ '/search?q=food', diff --git a/web/tests/integration/search-view.test.ts b/web/tests/integration/search-view.test.ts @@ -0,0 +1,209 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { readFile } from 'node:fs/promises'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import WebSocket, { WebSocketServer } from 'ws'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { + createPublicRuntimeContext, + mountPublicRuntime, + createPublicView, + closePublicRuntime +} from '../../src/lib/runtime/public-runtime.ts'; +import { + createSearchView, + startSearchView, + searchViewSnapshot, + moreSearchView, + closeSearchView +} from '../../src/lib/catalog/search-view.ts'; +await test('actual SDK foreground search publishes genuine rows and metadata and local pages without older discovery', async () => { + const corpus = JSON.parse( + await readFile( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) + ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; + const base = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous + ) as { tags: string[][]; content: string; created_at: number }; + const keys: Uint8Array[] = []; + const listings = Array.from({ length: 21 }, (_, n) => { + const key = crypto.getRandomValues(new Uint8Array(32)); + keys.push(key); + return finalizeEvent( + { + kind: 30402, + created_at: base.created_at - n, + tags: base.tags.map((t) => + t[0] === 'd' ? ['d', `listing_${n}`] : [...t] + ), + content: base.content + }, + key + ); + }); + const profiles = keys.map((key, n) => + finalizeEvent( + { + kind: 0, + created_at: base.created_at, + tags: [], + content: JSON.stringify({ + display_name: `<script>Farmer ${n}</script>`, + pubkey: 'forged', + nip05: 'identity@example.org', + picture: 'https://tracking.example.org' + }) + }, + key + ) + ); + for (const key of keys) key.fill(0); + const origin = 'wss://one.example.org', + server = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 65536 + }); + const sockets: WebSocket[] = [], + filters: Record<string, unknown>[] = []; + server.on('connection', (socket) => { + sockets.push(socket); + socket.on('message', (bytes) => { + const buffer = Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes); + const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; + if (frame[0] !== 'REQ') return; + const id = String(frame[1]), + queries = frame.slice(2) as Record<string, unknown>[]; + filters.push(...queries); + const kind = (queries[0].kinds as number[])[0]; + const matches = (pubkey: string, identifier?: string) => + queries.some((q) => { + const authors = q.authors as string[] | undefined; + return ( + !authors || + (authors.includes(pubkey) && + (identifier === undefined || + (q['#d'] as string[]).includes(identifier))) + ); + }); + const values = + kind === 0 + ? profiles.filter((v) => matches(v.pubkey)) + : kind === 30402 + ? listings.filter((v) => + matches(v.pubkey, v.tags.find((t) => t[0] === 'd')![1]) + ) + : []; + for (const value of values) + socket.send(JSON.stringify(['EVENT', id, value])); + socket.send(JSON.stringify(['EOSE', id])); + }); + }); + await once(server, 'listening'); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + const port = address.port; + const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), + oldSocket = globalThis.WebSocket; + class FixtureSocket extends WebSocket { + constructor(url: string | URL) { + assert.equal(String(url).replace(/\/$/, ''), origin); + super(`ws://127.0.0.1:${port}`); + } + } + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + globalThis.WebSocket = + FixtureSocket as unknown as typeof globalThis.WebSocket; + const context = createPublicRuntimeContext(); + try { + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [{ origin, read: true, write: false, nip50: false }], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + const view = createPublicView(mountPublicRuntime(context, policy)!); + const updates: number[] = []; + const owner = createSearchView( + view, + { nowSeconds: () => base.created_at + 10 }, + (snapshot) => { + updates.push(snapshot.listings.length); + } + ); + startSearchView(owner, ''); + for ( + let n = 0; + n < 300 && + !searchViewSnapshot(owner)?.listings.every( + (v) => v.publisher.assertedName + ); + n++ + ) + await new Promise((resolve) => setTimeout(resolve, 10)); + // Empty initial arrays are not success; wait for actual signed rows as well. + for ( + let n = 0; + n < 300 && searchViewSnapshot(owner)?.listings.length !== 20; + n++ + ) + await new Promise((resolve) => setTimeout(resolve, 10)); + const first = searchViewSnapshot(owner)!; + assert.equal(first.listings.length, 20); + assert.equal(first.hasMore, true); + assert.deepEqual( + first.listings.map((v) => v.eventId), + listings.slice(0, 20).map((v) => v.id) + ); + for ( + let n = 0; + n < 300 && + !searchViewSnapshot(owner)?.listings.every( + (v) => v.publisher.assertedName + ); + n++ + ) + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.ok( + searchViewSnapshot(owner)!.listings.every((v) => v.publisher.assertedName) + ); + assert.ok(updates.includes(20)); + const count = filters.length; + moreSearchView(owner); + assert.equal(filters.length, count); + assert.equal(searchViewSnapshot(owner)!.listings.length, 21); + assert.equal(searchViewSnapshot(owner)!.definitiveAbsence, false); + closeSearchView(owner); + const settled = filters.length; + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.equal(filters.length, settled); + assert.throws(() => startSearchView(owner, '')); + } finally { + closePublicRuntime(context); + for (const key of keys) key.fill(0); + globalThis.WebSocket = oldSocket; + if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); + else delete (globalThis as { window?: unknown }).window; + for (const socket of sockets) socket.terminate(); + await new Promise<void>((resolve, reject) => + server.close((e) => (e ? reject(e) : resolve())) + ); + } +}); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -114,7 +114,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { const f = await fixture(t); const files = await f.audit(); // Exact eleven-route module/page/static admission; CSS stays once-imported. - assert.equal(files.length, 45); + assert.equal(files.length, 46); // The actual SDK payload crosses the reader scratch boundary; a reused // scratch buffer must still preserve every compiler/static byte exactly. const sizes = await Promise.all( @@ -170,11 +170,52 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { assert.ok(Buffer.byteLength(expanded) > 64 * 1024); await writeFile(file, expanded); await refresh(f); - assert.equal((await f.audit()).length, 45); + assert.equal((await f.audit()).length, 46); } ); const sdkKey = 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; + await check( + 'predecessor SDK graph remains qualified with the historical search form fixture', + async (t) => { + const f = await fixture(t); + // Immutable former route bytes are a labelled verification variant only. + const historical = + "<script lang=\"ts\">\n import { page } from '$app/state';\n import SearchForm from '../../lib/components/SearchForm.svelte';\n import {\n normalizePublicQuery,\n queryErrorMessage,\n readPublicQuery\n } from '../../lib/catalog/query-input';\n import type { PublicQuery } from '../../lib/catalog/query-input';\n import { searchHref } from '../../lib/routes';\n import { internalHref } from '../../lib/navigation-url';\n let query = $state<PublicQuery>(normalizePublicQuery(''));\n let error = $state<string | undefined>();\n $effect(() => {\n query = readPublicQuery(page.url);\n error = undefined;\n });\n function search(input: string) {\n const next = normalizePublicQuery(input);\n if (!next.ok) {\n error = queryErrorMessage(next.error);\n return;\n }\n error = undefined;\n const target = internalHref(searchHref(next.text));\n if (target === undefined) {\n error = queryErrorMessage('invalid_query');\n return;\n }\n globalThis.location.assign(target);\n }\n</script>\n\n<svelte:head><title>Search food \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Search food</h1>\n <SearchForm\n onsubmit={search}\n initialValue={query.ok ? query.text : ''}\n error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))}\n />\n <p class=\"notice\">Search data is unavailable during development.</p>\n</div>\n"; + await writeFile( + path.join(f.web, 'src/routes/search/+page.svelte'), + historical + ); + await refresh(f); + await cp( + path.join(base, 'web/node_modules'), + path.join(f.web, 'node_modules'), + { recursive: true, verbatimSymlinks: true } + ); + execFileSync( + process.execPath, + [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], + { cwd: f.web, stdio: 'pipe', timeout: 60000 } + ); + const manifest = JSON.parse( + await readFile( + path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), + 'utf8' + ) + ); + assert.ok( + Object.values(manifest).some((record) => record.name === 'dist') + ); + assert.ok( + !Object.values(manifest).some( + (record) => + record.name === 'Disclosure' || record.name === 'navigation' + ) + ); + assert.equal((await f.audit()).length, 45); + }, + 60000 + ); for (const mutation of [ 'unknown-name', 'missing-public-key', @@ -203,7 +244,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { ); const m = JSON.parse(await readFile(file, 'utf8')); const root = Object.values(m).find((v) => v.name === 'nodes/0'); - const dist = Object.entries(m).find(([, v]) => v.name === 'dist'); + const dist = Object.entries(m).find(([, v]) => v.name === 'Disclosure'); assert.ok(m[sdkKey] && root && dist, 'Actual successor SDK identities'); if (mutation === 'unknown-name') m[sdkKey].name = 'unapproved-sdk'; if ( @@ -211,12 +252,14 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { mutation !== 'missing-root-edge' ) { const entry = Object.entries(m).find( - ([, v]) => v.name === mutation.slice(8) + ([, v]) => + v.name === + (mutation === 'missing-dist' ? 'Disclosure' : mutation.slice(8)) ); assert.ok(entry); delete m[entry[0]]; } - if (mutation === 'missing-root-edge') root.dynamicImports = []; + if (mutation === 'missing-root-edge') dist[1].dynamicImports = []; if ( [ 'random-key', @@ -239,7 +282,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { m[next] = m[sdkKey]; delete m[sdkKey]; m[next].src = next; - root.dynamicImports = root.dynamicImports.map( + dist[1].dynamicImports = dist[1].dynamicImports.map( (/** @type {string} */ k) => (k === sdkKey ? next : k) ); } @@ -447,7 +490,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { assert.equal(entries.length, 1); const [key, budget] = entries[0]; assert.deepEqual(Object.keys(budget).sort(), ['file', 'name']); - for (const name of ['nodes/0', 'routes']) + for (const name of ['Disclosure', 'nodes/9', 'routes']) assert.ok( Object.values(manifest) .find((record) => record.name === name) @@ -462,6 +505,92 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { assert.ok((await f.audit()).includes(budget.file)); } ); + for (const producer of [ + 'src/routes/search/+page.svelte', + 'src/lib/catalog/search-view.ts', + 'src/lib/components/ListingRow.svelte', + 'src/lib/components/SourceStatus.svelte', + 'src/lib/navigation-scroll.ts', + 'src/lib/components/primitives/Disclosure.svelte' + ]) { + await check( + 'real search compiler rejects changed owned producer ' + producer, + async (t) => { + const f = await fixture(t); + await writeFile( + path.join(f.web, producer), + (await readFile(path.join(f.web, producer), 'utf8')) + + '\n// source mutation\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned search presentation source/ + ); + } + ); + } + for (const mutation of [ + 'missing-shared', + 'missing-navigation', + 'root-edge', + 'search-edge', + 'budget-edge', + 'negentropy-edge', + 'sdk-backedge', + 'navigation-edge', + 'navigation-import', + 'navigation-dynamic', + 'shared-import' + ]) { + await check('real search compiler rejects ' + 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 records = Object.entries(manifest); + const find = (/** @type {string} */ name) => { + const entry = records.find(([, v]) => v.name === name); + assert.ok(entry, 'Missing actual compiler record ' + name); + return entry; + }; + const [sharedKey, shared] = find('Disclosure'); + const [budgetKey] = find('budgets'); + if (mutation === 'missing-shared') delete manifest[sharedKey]; + else if (mutation === 'missing-navigation') + delete manifest[find('navigation')[0]]; + else if (mutation === 'root-edge') + find('nodes/0')[1].imports = find('nodes/0')[1].imports.filter( + (/** @type {string} */ k) => k !== sharedKey + ); + else if (mutation === 'search-edge') + find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( + (/** @type {string} */ k) => k !== sharedKey + ); + else if (mutation === 'budget-edge') + shared.imports = shared.imports.filter( + (/** @type {string} */ k) => k !== budgetKey + ); + else if (mutation === 'sdk-backedge') find('negentropy')[1].imports = []; + else if (mutation === 'navigation-edge') + find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( + (/** @type {string} */ k) => k !== find('navigation')[0] + ); + else if (mutation === 'navigation-import') + find('navigation')[1].imports = [find('client')[0]]; + else if (mutation === 'navigation-dynamic') + find('navigation')[1].dynamicImports = [find('client-entry')[0]]; + else if (mutation === 'shared-import') + shared.imports = shared.imports.filter( + (/** @type {string} */ k) => k !== find('public-key')[0] + ); + else shared.dynamicImports = []; + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler|SDK|budgets/); + }); + } for (const mutation of [ 'unknown-name', 'duplicate', @@ -492,7 +621,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { mutation === 'missing-root-edge' || mutation === 'missing-routes-edge' ) { - const name = mutation === 'missing-root-edge' ? 'nodes/0' : 'routes'; + const name = mutation === 'missing-root-edge' ? 'nodes/9' : 'routes'; const consumer = Object.values(manifest).find( (record) => record.name === name ); diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs @@ -1936,3 +1936,78 @@ for (const source of [ reject(execute(), /descriptor|reflection|mutation|owned/); }); }); + +test('only the exact reviewed scroll owner admits scalar history restoration', async () => { + await fixture(async ({ put, execute }) => { + const helper = await readFile( + path.join(root, 'src/lib/navigation-scroll.ts'), + 'utf8' + ); + await put('src/lib/navigation-scroll.ts', helper); + await put( + 'src/routes/+page.ts', + "import {captureSearchScroll,restoreSearchScroll} from '../lib/navigation-scroll.ts'; export function restore(){restoreSearchScroll(captureSearchScroll());}" + ); + assert.equal(execute().status, 0); + for (const extra of [ + 'window.scrollTo(0,1);', + 'const scroll=window.scrollTo; scroll(0,1);', + "window['scrollTo'](0,1);", + 'const owner=window; owner.scrollTo(0,1);', + 'window.scrollTo(0,Infinity);', + 'window.scrollTo(0,-1);', + 'export const escaped=window;', + 'window.document.body.innerHTML="changed";' + ]) { + await put('src/lib/navigation-scroll.ts', helper + '\n' + extra); + assert.notEqual(execute().status, 0, extra); + } + await put('src/lib/navigation-scroll.ts', helper); + await put('src/routes/+page.ts', 'export const position=window.scrollY;'); + assert.notEqual(execute().status, 0); + await put('src/routes/+page.ts', 'window.scrollTo(0,1);'); + assert.notEqual(execute().status, 0); + await put('src/routes/+page.ts', 'export const value=1;'); + await put('src/lib/copied-scroll.ts', helper); + assert.notEqual(execute().status, 0); + }); +}); + +test('history scroll owner rejects malformed values without coercion or SSR effects', async () => { + const { captureSearchScroll, restoreSearchScroll } = + await import('../../src/lib/navigation-scroll.ts'); + const previous = Object.getOwnPropertyDescriptor(globalThis, 'window'); + /** @type {number[][]} */ + const calls = []; + try { + Reflect.deleteProperty(globalThis, 'window'); + assert.equal(captureSearchScroll(), undefined); + restoreSearchScroll(42); + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: { + scrollY: 2317, + scrollTo: (/** @type {number[]} */ ...args) => calls.push(args) + } + }); + assert.equal(captureSearchScroll(), 2317); + for (const value of [ + NaN, + Infinity, + -1, + '42', + {}, + null, + Number.MAX_SAFE_INTEGER + 1 + ]) + restoreSearchScroll(value); + assert.equal(calls.length, 0); + restoreSearchScroll(2317); + assert.deepEqual(calls, [[0, 2317]]); + globalThis.window.scrollY = Infinity; + assert.equal(captureSearchScroll(), undefined); + } finally { + if (previous) Object.defineProperty(globalThis, 'window', previous); + else Reflect.deleteProperty(globalThis, 'window'); + } +}); diff --git a/web/tests/unit/components/search-listings.test.ts b/web/tests/unit/components/search-listings.test.ts @@ -0,0 +1,224 @@ +import { render } from 'svelte/server'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import ListingRow from '../../../src/lib/components/ListingRow.svelte'; +import SourceStatus from '../../../src/lib/components/SourceStatus.svelte'; +import type { ListingView } from '../../../src/lib/catalog/listing-view.ts'; +import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; +import { finalizeEvent } from 'applesauce-core/helpers'; +function listing(): ListingView { + const key = crypto.getRandomValues(new Uint8Array(32)); + let pubkey: string; + try { + pubkey = finalizeEvent( + { kind: 0, created_at: 1, tags: [], content: '{}' }, + key + ).pubkey; + } finally { + key.fill(0); + } + return { + eventId: 'a'.repeat(64), + createdAt: 1700000000, + identifier: 'listing', + href: + '/products/' + + encodeProductReference({ kind: 30402, pubkey, identifier: 'listing' }), + title: '<script>Carrots</script>', + summary: 'Seller summary', + content: 'Text', + location: 'Public area', + price: { + amount: '9007199254740993.123456789' as ListingView['price']['amount'], + currency: 'CAD' as ListingView['price']['currency'], + unit: 'kg' + }, + quantity: null, + publisher: { + pubkey, + label: '<img src=https://tracking.example>', + assertedName: true + }, + lastKnown: true, + coverage: 'partial' + }; +} +describe('truthful search rows and persistent source notices', () => { + it('renders advertised decimal/unit/area/unknown quantity and asserted publisher as text', () => { + const value = listing(), + html = render(ListingRow, { props: { listing: value } }).body; + expect(html).toContain('9007199254740993.123456789'); + expect(html).toContain('CAD'); + expect(html).toContain('kg'); + expect(html).toContain('Public area'); + expect(html).toContain('Advertised quantity not specified'); + expect(html).toContain(value.publisher.pubkey); + expect(html).toContain('&lt;script>'); + expect(html).toContain('&lt;img'); + expect(html).not.toMatch(/<script|<img|onclick|certified/); + expect(html).toContain('href="' + value.href + '"'); + expect(html).toContain('<details'); + }); + it('renders supplied quantity without calculating a comparison price or inventing stock', () => { + const value = { + ...listing(), + quantity: { + amount: '20' as NonNullable<ListingView['quantity']>['amount'], + unit: 'kg' as const + } + }; + const html = render(ListingRow, { props: { listing: value } }).body; + expect(html).toMatch(/20\s+kg/); + expect(html).not.toContain('not specified'); + }); + it('keeps failed-source uncertainty visible outside its details and separates unavailable from bounded empty', () => { + const html = render(SourceStatus, { + props: { refresh: 'partial', gap: false, scopes: [] } + }).body; + expect(html).toContain('These results may be incomplete.'); + expect(html.indexOf('may be incomplete')).toBeLessThan( + html.indexOf('<details') + ); + const unavailable = render(SourceStatus, { + props: { refresh: 'unavailable', gap: false, scopes: [] } + }).body; + expect(unavailable).toContain('Search sources are unavailable.'); + expect(unavailable).not.toContain('No matches'); + const gap = render(SourceStatus, { + props: { refresh: 'partial', gap: true, scopes: [] } + }).body; + expect(gap).toContain('same timestamp'); + expect(gap).not.toContain('complete search'); + }); +}); + +it('does not invent a source failure for cancelled, deadline or capped work', () => { + for (const refresh of ['cancelled', 'deadline', 'limit', 'error'] as const) { + const html = render(SourceStatus, { + props: { refresh, gap: false, scopes: [] } + }).body; + expect(html).toContain('These results may be incomplete.'); + expect(html).not.toContain('One source did not respond.'); + } +}); + +it('renders an admitted numeric timestamp beyond Date range without crashing or changing it', () => { + const value = { ...listing(), createdAt: Number.MAX_SAFE_INTEGER }; + const html = render(ListingRow, { props: { listing: value } }).body; + expect(html).toContain(String(value.createdAt)); +}); + +const mounted = vi.hoisted<{ + callbacks: (() => void | (() => void))[]; + context: unknown; +}>(() => ({ callbacks: [], context: undefined })); +vi.mock('svelte', async (original) => ({ + ...(await original<typeof import('svelte')>()), + getContext: () => mounted.context, + onMount: (callback: () => void | (() => void)) => { + mounted.callbacks.push(callback); + } +})); +vi.mock('$app/state', () => ({ + page: { url: new URL('https://harvestcircle.example/search?q=carrots') } +})); +vi.mock('$app/navigation', () => ({ goto: vi.fn() })); +describe('actual search route mounted initialization', () => { + let runtime: typeof import('../../../src/lib/runtime/public-runtime.ts'); + let context: ReturnType<typeof runtime.createPublicRuntimeContext>; + let cleanup: void | (() => void); + const unhandled: unknown[] = []; + const record = (error: unknown) => { + unhandled.push(error); + }; + beforeEach(async () => { + vi.resetModules(); + vi.stubGlobal('window', {}); + mounted.callbacks.length = 0; + unhandled.length = 0; + cleanup = undefined; + runtime = await import('../../../src/lib/runtime/public-runtime.ts'); + context = runtime.createPublicRuntimeContext(); + mounted.context = context; + process.on('unhandledRejection', record); + }); + afterEach(() => { + if (typeof cleanup === 'function') cleanup(); + runtime.closePublicRuntime(context); + process.off('unhandledRejection', record); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + async function mountCallback() { + const { render } = await import('svelte/server'); + const { default: SearchPage } = + await import('../../../src/routes/search/+page.svelte'); + const html = render(SearchPage, { + context: new Map([[runtime.PUBLIC_RUNTIME_CONTEXT, context]]) + }).body; + expect(html).toContain('Search sources are unavailable.'); + expect(mounted.callbacks.length).toBeGreaterThan(0); + cleanup = mounted.callbacks[0](); + } + const settle = () => new Promise<void>((resolve) => setImmediate(resolve)); + it('handles a genuine unavailable public projection without requests, timers or an unhandled rejection', async () => { + runtime.mountPublicRuntime(context); + const { getPublicStore, closePublicStore } = + await import('../../../src/lib/nostr/public-store.ts'); + const store = getPublicStore(); + expect(store).toBeDefined(); + closePublicStore(store!); + const { RelayPool } = await import('applesauce-relay/pool'); + const request = vi.spyOn(RelayPool.prototype, 'req'); + const timer = vi.spyOn(globalThis, 'setTimeout'); + const create = vi.spyOn(runtime, 'createPublicView'); + await mountCallback(); + await settle(); + expect(create).toHaveBeenCalledTimes(1); + expect(create.mock.results[0].value).toMatchObject({ + message: 'public_projection_unavailable' + }); + expect(request).not.toHaveBeenCalled(); + expect(timer).not.toHaveBeenCalled(); + expect(unhandled).toEqual([]); + }); + it('disposes exactly the partially created view when search-owner construction fails', async () => { + const shared = runtime.mountPublicRuntime(context)!; + const other = runtime.createPublicView(shared); + const views = await import('../../../src/lib/catalog/search-view.ts'); + vi.spyOn(views, 'createSearchView').mockImplementation(() => { + throw Error('fixture_search_owner_failed'); + }); + const create = vi.spyOn(runtime, 'createPublicView'); + const dispose = vi.spyOn(runtime, 'disposePublicView'); + await mountCallback(); + await settle(); + expect(create).toHaveBeenCalledTimes(1); + expect(dispose).toHaveBeenCalledExactlyOnceWith( + create.mock.results[0].value + ); + expect(runtime.publicViewProjectionAvailable(other)).toBe(true); + expect(unhandled).toEqual([]); + runtime.disposePublicView(other); + }); + it('handles rejected readiness without acquiring a view', async () => { + vi.spyOn(runtime, 'publicRuntimeReady').mockRejectedValue( + Error('fixture_ready_failed') + ); + const create = vi.spyOn(runtime, 'createPublicView'); + await mountCallback(); + await settle(); + expect(create).not.toHaveBeenCalled(); + expect(unhandled).toEqual([]); + }); + it('keeps late genuine readiness after page disposal inert', async () => { + const create = vi.spyOn(runtime, 'createPublicView'); + await mountCallback(); + expect(typeof cleanup).toBe('function'); + if (typeof cleanup === 'function') cleanup(); + cleanup = undefined; + runtime.mountPublicRuntime(context); + await settle(); + expect(create).not.toHaveBeenCalled(); + expect(unhandled).toEqual([]); + }); +}); diff --git a/web/tests/unit/search-view.test.ts b/web/tests/unit/search-view.test.ts @@ -0,0 +1,305 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts'; +import type { RequestClock } from '../../src/lib/nostr/request-scope.ts'; +let search: typeof import('../../src/lib/catalog/search-run.ts'); +let runtime: typeof import('../../src/lib/runtime/public-runtime.ts'); +let context: ReturnType<typeof runtime.createPublicRuntimeContext>; +const keys: Uint8Array[] = []; +beforeEach(async () => { + vi.resetModules(); + vi.stubGlobal('window', {}); + search = await import('../../src/lib/catalog/search-run.ts'); + runtime = await import('../../src/lib/runtime/public-runtime.ts'); +}); +afterEach(() => { + if (context) runtime.closePublicRuntime(context); + for (const key of keys.splice(0)) key.fill(0); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); +const corpus = JSON.parse( + readFileSync( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) +) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; +const base = JSON.parse( + corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous +) as { tags: string[][]; content: string; created_at: number }; +async function fixture(nip50 = false, sourceCount = 1) { + const { RelayPool } = await import('applesauce-relay/pool'); + const { validateRelayPolicy } = + await import('../../src/lib/config/relays.ts'); + const { verifyEnvelope } = + await import('../../src/lib/nostr/verified-envelope.ts'); + const { createPublicHeadCandidate } = + await import('../../src/lib/catalog/heads.ts'); + const channels: { + emit: (value: PublicPoolMessage) => void; + stopped: () => boolean; + }[] = []; + const provider = vi.spyOn(RelayPool.prototype, 'req').mockImplementation( + () => + ({ + subscribe(subscriber: { next?: (value: PublicPoolMessage) => void }) { + let stopped = false; + channels.push({ + emit: (value: PublicPoolMessage) => { + if (!stopped) subscriber.next?.(value); + }, + stopped: () => stopped + }); + return { + get closed() { + return stopped; + }, + unsubscribe() { + stopped = true; + } + }; + } + }) as unknown as ReturnType<InstanceType<typeof RelayPool>['req']> + ); + const origin = 'wss://one.example.org'; + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: Array.from({ length: sourceCount }, (_, n) => ({ + origin: n === 0 ? origin : `wss://source${n}.example.org`, + read: true, + write: false, + nip50 + })), + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + const key = crypto.getRandomValues(new Uint8Array(32)); + keys.push(key); + const wire = ( + title = 'Carrots', + d?: string, + time = base.created_at, + content = base.content + ) => + finalizeEvent( + { + kind: 30402, + created_at: time, + content, + tags: base.tags.map((tag) => + tag[0] === 'title' + ? ['title', title] + : tag[0] === 'd' && d !== undefined + ? ['d', d] + : [...tag] + ) + }, + key + ); + const head = (event = wire()) => { + const p = verifyEnvelope(JSON.stringify(event)); + if (!p.ok) throw Error('fixture proof'); + const h = createPublicHeadCandidate(p.value); + if (!h) throw Error('fixture head'); + return h; + }; + let now = 0, + reads = 0; + let onNow = () => {}; + const timers = new Map<() => void, { at: number; callback: () => void }>(); + const clock: RequestClock = { + now: () => { + reads++; + onNow(); + return now; + }, + schedule: (callback, delay) => { + const cancel = () => { + timers.delete(cancel); + }; + timers.set(cancel, { at: now + delay, callback }); + return cancel; + } + }; + context = runtime.createPublicRuntimeContext(); + const owner = runtime.mountPublicRuntime(context, policy, clock)!; + const view = runtime.createPublicView(owner); + const wallClock = { + nowSeconds: () => base.created_at + 10 + }; + const coordinator = search.createFoodSearchCoordinator(view, wallClock); + const begin = (query = '', heads: readonly ReturnType<typeof head>[] = []) => + search.beginFoodSearch(coordinator, query, heads); + const snapshot = () => search.foodSearchSnapshot(coordinator)!; + const emit = (i: number, event: ReturnType<typeof wire>) => + channels[i].emit({ type: 'EVENT', id: 'fixture', from: origin, event }); + return { + eose: (i: number) => { + const selected = provider.mock.calls[i][0]; + if (!Array.isArray(selected)) throw new Error('fixture source array'); + for (const source of selected) + channels[i].emit({ type: 'EOSE', id: 'fixture', from: String(source) }); + }, + coordinator, + view, + wallClock, + begin, + snapshot, + head, + wire, + emit, + channels, + provider, + origin, + timers, + reads: () => reads, + reenter: (callback: () => void) => { + onNow = callback; + }, + advance: (value: number) => { + now = value; + for (const timer of [...timers.values()]) + if (timer.at <= now) timer.callback(); + } + }; +} +let views: typeof import('../../src/lib/catalog/search-view.ts'); +beforeEach(async () => { + views = await import('../../src/lib/catalog/search-view.ts'); +}); +function renderClock() { + const callbacks = new Map<() => void, true>(); + return { + schedule: (callback: () => void) => { + callbacks.set(callback, true); + return () => { + callbacks.delete(callback); + }; + }, + tick: () => { + const values = Array.from(callbacks.keys()); + callbacks.clear(); + for (const callback of values) callback(); + }, + size: () => callbacks.size + }; +} +describe('bounded foreground search presentation owner', () => { + it('rejects invalid queries before losing retained rows or starting effects', async () => { + const f = await fixture(), + clock = renderClock(), + updates: unknown[] = []; + const owner = views.createSearchView( + f.view, + f.wallClock, + (value) => { + updates.push(value); + }, + clock.schedule + ); + views.startSearchView(owner, 'carrots', [f.head()]); + const before = f.provider.mock.calls.length; + expect(() => views.startSearchView(owner, 'x'.repeat(513))).toThrow(); + expect(f.provider).toHaveBeenCalledTimes(before); + expect(views.searchViewSnapshot(owner)?.rows).toHaveLength(1); + expect(updates.length).toBeGreaterThan(0); + views.closeSearchView(owner); + expect(clock.size()).toBe(0); + }); + it('does not schedule older discovery when showing another local page', async () => { + const f = await fixture(), + clock = renderClock(); + const owner = views.createSearchView( + f.view, + f.wallClock, + () => {}, + clock.schedule + ); + const heads = Array.from({ length: 26 }, (_, n) => + f.head(f.wire('Carrots', `view_${n}`, base.created_at - n)) + ); + views.startSearchView(owner, 'carrots', heads); + const before = f.provider.mock.calls.length; + views.moreSearchView(owner); + expect(views.searchViewSnapshot(owner)?.rows).toHaveLength(26); + expect(f.provider).toHaveBeenCalledTimes(before); + views.closeSearchView(owner); + expect(f.channels.every((c) => c.stopped())).toBe(true); + }); + it('cancels superseded callbacks and terminates foreground updates at the original deadline', async () => { + const f = await fixture(), + clock = renderClock(); + const owner = views.createSearchView( + f.view, + f.wallClock, + () => {}, + clock.schedule + ); + views.startSearchView(owner, 'carrots', [f.head()]); + const old = views.searchViewSnapshot(owner)!.generation; + views.startSearchView(owner, 'celery'); + expect(views.searchViewSnapshot(owner)!.generation).not.toBe(old); + expect(f.channels.slice(0, 3).every((c) => c.stopped())).toBe(true); + f.advance(15000); + clock.tick(); + expect(clock.size()).toBe(0); + expect(views.searchViewSnapshot(owner)?.query).toBe('celery'); + views.closeSearchView(owner); + }); + it('closes only its own view while another public view remains active', async () => { + const f = await fixture(), + clock = renderClock(); + const other = runtime.createPublicView(runtime.publicRuntime(context)!); + const run = runtime.beginPublicViewRun(other); + runtime.subscribePublicView( + other, + run, + 'search', + [{ kinds: [30402], limit: 200 }], + () => {} + ); + const owner = views.createSearchView( + f.view, + f.wallClock, + () => {}, + clock.schedule + ); + views.startSearchView(owner, 'carrots'); + views.closeSearchView(owner); + expect(f.channels[0].stopped()).toBe(false); + expect(f.channels.slice(1).every((c) => c.stopped())).toBe(true); + expect(() => views.startSearchView(owner, '')).toThrow(); + runtime.disposePublicView(other); + }); +}); + +it('preserves a successor foreground observer started by a local-page update callback', async () => { + const f = await fixture(), + clock = renderClock(); + let reenter = false; + const owner = views.createSearchView( + f.view, + f.wallClock, + () => { + if (reenter) { + reenter = false; + views.startSearchView(owner, 'turnips'); + } + }, + clock.schedule + ); + views.startSearchView(owner, 'carrots', [f.head()]); + reenter = true; + views.moreSearchView(owner); + expect(views.searchViewSnapshot(owner)?.query).toBe('turnips'); + expect(clock.size()).toBe(1); + views.closeSearchView(owner); +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -1,4 +1,5 @@ import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import { constants } from 'node:fs'; import { lstat, open, opendir, realpath } from 'node:fs/promises'; @@ -296,6 +297,36 @@ async function hasOwnedPublicRuntime(web) { publicText(await readOwned(web, 'src/lib/' + name)); return true; } +// This exact reviewed producer set owns the shared presentation/runtime split. +// A successor changes these identities only with new compiler qualification. +/** @param {string} web */ +async function searchPresentationAdmission(web) { + const route = publicText( + await readOwned(web, 'src/routes/search/+page.svelte') + ); + if (!route.includes('../../lib/catalog/search-view.ts')) return false; + const producers = { + 'src/routes/search/+page.svelte': + '0dea04fc5a5a41599774215c9157d8eb2076eb3fa4fe6355184a9a467a9cc72a', + 'src/lib/catalog/search-view.ts': + '398cc2db59fb78d33df8cb8ce59d4e10a84feb3842709f2a7047033424798768', + 'src/lib/components/ListingRow.svelte': + '48c6ab9b5fe887206b77a27bd0de697d346133ecb44d8ba973c8ffacc0cf5f03', + 'src/lib/components/SourceStatus.svelte': + 'd3cdb173fdeb4e7783f4b3b909a90c32ae4a66a5d87cba6a2766e718317775de', + 'src/lib/navigation-scroll.ts': + '9a3dcd9bbde8bcdb18d8962816fa062262505bc3e8ad34d88c78d18dba3a8398', + 'src/lib/components/primitives/Disclosure.svelte': + 'c6d8361f31218644ac487a3d43412627cb8cc50906a921b95cf053047ce32bf3' + }; + for (const [name, pin] of Object.entries(producers)) { + const bytes = await readOwned(web, name); + publicText(bytes); + if (createHash('sha256').update(bytes).digest('hex') !== pin) + throw new Error('Invalid owned search presentation source'); + } + return true; +} /** @param {string} webDirectory */ export async function auditOutput(webDirectory) { const web = path.resolve(webDirectory); @@ -391,6 +422,8 @@ export async function auditOutput(webDirectory) { const hasPublicRuntime = await hasOwnedPublicRuntime(web); if (hasPublicRuntime && !hasFullRoutes) throw new Error('Incomplete owned root runtime routes'); + const hasSearchPresentation = + hasSearch && hasPublicRuntime && (await searchPresentationAdmission(web)); // Admit compiler-owned module identities, not arbitrary extensions/copy roots. const names = new Set([ 'entry/app', @@ -423,7 +456,12 @@ export async function auditOutput(webDirectory) { names.add(name); } if (hasPublicRuntime) - for (const name of ['public-key', 'dist', 'negentropy', 'budgets']) + for (const name of [ + 'public-key', + ...(hasSearchPresentation ? ['Disclosure', 'navigation'] : ['dist']), + 'negentropy', + 'budgets' + ]) names.add(name); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); @@ -516,7 +554,7 @@ export async function auditOutput(webDirectory) { if (!entry) throw new Error('Incomplete owned SDK compiler module'); return entry; } - const dist = requiredRecord('dist'); + const dist = requiredRecord(hasSearchPresentation ? 'Disclosure' : 'dist'); const root = requiredRecord('nodes/0')[1]; const [budgetKey, budget] = requiredRecord('budgets'); if ( @@ -524,7 +562,9 @@ export async function auditOutput(webDirectory) { Object.keys(budget).some((field) => !['file', 'name'].includes(field)) ) throw new Error('Invalid owned budgets compiler identity'); - for (const consumer of ['nodes/0', 'routes']) { + for (const consumer of hasSearchPresentation + ? ['Disclosure', 'nodes/9', 'routes'] + : ['nodes/0', 'routes']) { if (!requiredRecord(consumer)[1].imports?.includes(budgetKey)) throw new Error('Invalid owned budgets compiler edge'); } @@ -541,11 +581,54 @@ export async function auditOutput(webDirectory) { throw new Error('Invalid owned SDK compiler identity'); equal(sdk.imports, [dist[0]], 'Invalid owned SDK compiler dependency'); equal( - root.dynamicImports, + hasSearchPresentation ? dist[1].dynamicImports : root.dynamicImports, [sdkNegentropy], 'Invalid owned root compiler edge' ); - for (const name of ['dist', 'public-key']) { + if (hasSearchPresentation) { + if ( + root.dynamicImports !== undefined || + !root.imports?.includes(dist[0]) || + !requiredRecord('nodes/9')[1].imports?.includes(dist[0]) + ) + throw new Error('Invalid owned shared compiler edge'); + const navigation = requiredRecord('navigation'); + if (!requiredRecord('nodes/9')[1].imports?.includes(navigation[0])) + throw new Error('Invalid owned navigation compiler edge'); + equal( + navigation[1].imports, + ['entry/payload', 'shared-errors', 'client', 'client.svelte'].map( + (name) => requiredRecord(name)[0] + ), + 'Invalid owned navigation compiler dependencies' + ); + if (navigation[1].dynamicImports !== undefined) + throw new Error('Invalid owned navigation compiler dynamic imports'); + equal( + dist[1].imports, + [ + 'rolldown-runtime', + 'preload-helper', + 'public-key', + 'client', + 'budgets' + ].map((name) => requiredRecord(name)[0]), + 'Invalid owned shared compiler dependencies' + ); + for (const [key, record] of [dist, navigation]) { + if ( + !/^_[A-Za-z0-9_-]+\.js$/.test(key) || + record.src !== undefined || + record.isEntry !== undefined || + record.isDynamicEntry !== undefined || + record.css !== undefined + ) + throw new Error('Invalid owned search compiler chunk'); + } + } + for (const name of hasSearchPresentation + ? ['public-key'] + : ['dist', 'public-key']) { const [key, record] = requiredRecord(name); if ( !/^_[A-Za-z0-9_-]+\.js$/.test(key) || diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs @@ -113,7 +113,12 @@ function sourceAst(file, text) { // DOM updates. Mutable application data must be locally owned plain data, with // pure values and lexical aliases. Future imperative UI work needs explicit // admission and negative tests rather than a type cast or an ignored diagnostic. -function mutationAdmission(ast, report, identity = () => null) { +function mutationAdmission( + ast, + report, + identity = () => null, + reviewedScroll = false +) { // Bind this admitted AST only, without libs, module resolution, file reads, // config loading or evaluation. Symbols distinguish aliases and shadowing. const options = { @@ -890,6 +895,11 @@ function mutationAdmission(ast, report, identity = () => null) { !eventStoreAdd(node) && !locationMethod && !( + reviewedScroll && + name === 'scrollTo' && + global(node.expression, ['window']) + ) && + !( animationMethods.has(name) && owned(node.expression) && !ts.isCallExpression(node.parent) @@ -1007,9 +1017,18 @@ function mutationAdmission(ast, report, identity = () => null) { if ( !ts.isPropertyAccessExpression(parent) || parent.expression !== node || - !['nostr', 'indexedDB', 'crypto', 'navigator', 'location'].includes( - parent.name.text - ) + (![ + 'nostr', + 'indexedDB', + 'crypto', + 'navigator', + 'location' + ].includes(parent.name.text) && + !( + reviewedScroll && + node.text === 'window' && + ['scrollY', 'scrollTo'].includes(parent.name.text) + )) ) report('opaque browser/DOM global capability access is forbidden'); } @@ -1468,6 +1487,16 @@ export async function auditSource(root) { complain(file, `unresolved production import ${specifier}`); } } + const scrollFile = path.join(root, 'src/lib/navigation-scroll.ts'); + const scrollTrusted = + files.has(scrollFile) && + createHash('sha256').update(files.get(scrollFile)).digest('hex') === + '9a3dcd9bbde8bcdb18d8962816fa062262505bc3e8ad34d88c78d18dba3a8398'; + if (files.has(scrollFile) && !scrollTrusted) + complain( + scrollFile, + 'scroll helper source identity does not match reviewed pin' + ); const helperFile = path.join(root, 'src/lib/navigation-url.ts'); const helperPin = '4ce96334d7cf57ccba518132078278b71d3bf70f519202e491a5f6a8840f7b19'; @@ -1960,7 +1989,8 @@ export async function auditSource(root) { ? 'goto' : null : exportIdentity(target, exported); - } + }, + file === scrollFile && scrollTrusted ); if (ast.referencedFiles.length || ast.typeReferenceDirectives.length) complain(file, 'source reference directives are forbidden');