app

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

commit 2e2243db2c9f625926fb7b51c6f0cfbf466c7792
parent 045ac2d10bf7b56786751412ca467a31eb8c4428
Author: triesap <tyson@radroots.org>
Date:   Sat, 10 Oct 2026 09:25:54 +0000

web: build one listing editor for new draft resume and edit (HCP-115)

Diffstat:
Aweb/src/lib/components/ListingEditor.svelte | 352+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/publishing/listing-editor.ts | 410+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/routes/products/[naddr=naddr]/edit/+page.svelte | 10++++++++--
Mweb/src/routes/sell/+page.svelte | 4++--
Mweb/src/routes/selling/drafts/[draftId=local_id]/+page.svelte | 10++++++++--
Aweb/tests/e2e/harness/listing-editor.ts | 563+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/e2e/listing-editor.spec.ts | 727+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/e2e/route-inventory.spec.ts | 60+++++++++++++++++++++++++++++++++++++++++++-----------------
Mweb/tests/integration/loopback.test.ts | 17++++++++++++++---
Mweb/tests/provenance/output.test.mjs | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aweb/tests/unit/listing-editor.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/unit/route-inventory.test.ts | 26+++++++++++++++++++++++++-
Mweb/tools/check-output.mjs | 517++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
13 files changed, 2828 insertions(+), 50 deletions(-)

diff --git a/web/src/lib/components/ListingEditor.svelte b/web/src/lib/components/ListingEditor.svelte @@ -0,0 +1,352 @@ +<script lang="ts"> + import { getContext, onMount } from 'svelte'; + import CapabilityGate from './CapabilityGate.svelte'; + import Notice from './Notice.svelte'; + import { foodUnits } from '../contracts/food-availability-v1/values.ts'; + import type { PublicDraftForm } from '../contracts/local-records.ts'; + import { + IDENTITY_VIEW_CONTEXT, + identityViewSnapshot, + subscribeIdentityView, + connectIdentityView, + disconnectIdentityView, + type IdentityViewContext + } from '../runtime/view-context.ts'; + import { + openListingEditor, + listingEditorSnapshot, + editListingEditor, + closeListingEditor, + subscribeListingEditor, + type ListingEditor as Editor, + type ListingEditorRoute, + type ListingEditorSnapshot + } from '../publishing/listing-editor.ts'; + import { internalHref } from '../navigation-url.ts'; + let { route }: { route: ListingEditorRoute } = $props(); + const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT); + let identity = $state(identityViewSnapshot(context)), + mounted = $state(false), + editor = $state.raw<Editor | undefined>(), + snapshot = $state<ListingEditorSnapshot>(), + unavailable = $state(false); + type Form = { + -readonly [Key in keyof PublicDraftForm]: PublicDraftForm[Key]; + }; + const blankForm = (): Form => ({ + title: '', + description: '', + location: '', + amount: '', + currency: '', + unit: '', + quantity: '', + contactType: '', + contactValue: '' + }); + let form = $state<Form>(blankForm()); + const admittedAuthor = $derived( + identity.identity.state !== 'guest' && identity.identity.state !== 'pending' + ? identity.identity.publicKey + : undefined + ); + const active = $derived(mounted && identity.mounted); + const visible = $derived( + snapshot && + editor && + identity.mounted && + identity.identity.state !== 'guest' && + identity.identity.state !== 'pending' && + identity.identity.publicKey === snapshot.owner && + listingEditorSnapshot(editor) + ); + onMount(() => { + mounted = true; + const off = subscribeIdentityView(context, (next) => { + identity = next; + }); + return () => { + mounted = false; + off(); + }; + }); + $effect(() => { + const resource = route, + author = admittedAuthor; + if (!active || !author) { + editor = undefined; + snapshot = undefined; + form = blankForm(); + unavailable = false; + return; + } + const cancellation = new AbortController(); + let alive = true, + owned: Editor | undefined, + off = () => {}; + editor = undefined; + snapshot = undefined; + form = blankForm(); + unavailable = false; + void openListingEditor(context, resource, cancellation.signal).then( + (result) => { + if (!alive) { + if (result.status === 'ready') closeListingEditor(result.editor); + return; + } + if (result.status !== 'ready') { + unavailable = true; + return; + } + owned = result.editor; + editor = owned; + const next = listingEditorSnapshot(owned); + if (!next) { + unavailable = true; + return; + } + snapshot = next; + form = { ...next.form }; + off = subscribeListingEditor(owned, () => { + snapshot = owned && listingEditorSnapshot(owned); + if (!snapshot) { + unavailable = true; + form = blankForm(); + } + }); + } + ); + return () => { + alive = false; + cancellation.abort(); + off(); + if (owned) closeListingEditor(owned); + form = blankForm(); + }; + }); + function changed() { + const original = editor; + if (!original || !listingEditorSnapshot(original)?.editable) return; + void editListingEditor(original, { ...form }); + } + function connect() { + return connectIdentityView(context); + } + function disconnect() { + disconnectIdentityView(context); + } + const title = $derived( + route.mode === 'new' + ? 'New listing' + : route.mode === 'draft' + ? 'Continue draft' + : 'Edit listing' + ); +</script> + +<svelte:head + ><title>{title} · HarvestCircle</title><meta + name="robots" + content="noindex" + /></svelte:head +> +<div class="page page--reading stack"> + <a + href={internalHref( + route.mode === 'edit' ? `/products/${route.naddr}` : '/selling' + )}>{route.mode === 'edit' ? 'Back to listing' : 'Back to Selling'}</a + > + <h1>{title}</h1> + {#if !visible} + <CapabilityGate + identity={identity.identity} + required="connection" + focusTarget="protected" + onconnect={mounted ? connect : undefined} + ondisconnect={disconnect} + /> + {#if unavailable}<Notice + tone="warning" + text={route.mode === 'draft' + ? 'This draft is not available here.' + : route.mode === 'edit' + ? 'Supported local listing values are not available for editing. Keep this listing read-only.' + : 'Browser storage is unavailable. Your existing local data has not been reset.'} + />{:else if identity.identity.state !== 'guest' && identity.identity.state !== 'pending'}<p + role="status" + > + Loading local values. + </p>{/if} + {:else} + {#if !visible.editable}<Notice + tone="info" + text="These retained local values are read-only until the current listing is checked." + />{:else}<p> + Changes are saved in this browser. Browser storage is not a backup. + </p>{/if} + <form class="stack" onsubmit={(event) => event.preventDefault()} novalidate> + <div class="field"> + <label class="label" for="listing-title">Product name</label><input + id="listing-title" + type="text" + value={form.title} + oninput={(event) => { + form = { ...form, title: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable} + /> + </div> + <div class="field"> + <label class="label" for="listing-description">Description</label + ><textarea + id="listing-description" + rows="6" + value={form.description} + oninput={(event) => { + form = { ...form, description: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable}></textarea> + </div> + <div class="field"> + <label class="label" for="listing-location">Public area</label> + <p id="listing-location-hint" class="text-small"> + A town or collection area is enough. + </p> + <input + id="listing-location" + type="text" + aria-describedby="listing-location-hint" + value={form.location} + oninput={(event) => { + form = { ...form, location: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable} + /> + </div> + <div class="cluster"> + <div class="field"> + <label class="label" for="listing-amount">Price</label><input + id="listing-amount" + type="text" + inputmode="decimal" + value={form.amount} + oninput={(event) => { + form = { ...form, amount: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable} + /> + </div> + <div class="field"> + <label class="label" for="listing-currency">Currency</label><input + id="listing-currency" + type="text" + maxlength="3" + value={form.currency} + oninput={(event) => { + form = { ...form, currency: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable} + /> + </div> + <div class="field"> + <label class="label" for="listing-unit">Per</label><select + id="listing-unit" + value={form.unit} + onchange={(event) => { + form = { ...form, unit: event.currentTarget.value }; + changed(); + }} + disabled={!visible.editable} + ><option value="">Choose a unit</option + >{#each foodUnits as unit (unit)}<option value={unit}>{unit}</option + >{/each}</select + > + </div> + </div> + <div class="field"> + <label class="label" for="listing-quantity" + >Advertised quantity (optional)</label + > + <p id="listing-quantity-unit"> + {form.unit || 'Uses the selected price unit'} + </p> + <input + id="listing-quantity" + type="text" + inputmode="decimal" + aria-describedby="listing-quantity-unit" + value={form.quantity} + oninput={(event) => { + form = { ...form, quantity: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable} + /> + </div> + <details> + <summary>Add public contact details (optional)</summary> + <div class="stack"> + <p>Only add contact details you want to include publicly.</p> + <div class="field"> + <label class="label" for="listing-contact-type" + >Public contact type</label + ><select + id="listing-contact-type" + value={form.contactType} + onchange={(event) => { + const value = event.currentTarget.value; + if ( + value === '' || + value === 'email' || + value === 'phone' || + value === 'https' + ) { + form = { ...form, contactType: value }; + changed(); + } + }} + disabled={!visible.editable} + ><option value="">No public contact</option><option value="email" + >Email</option + ><option value="phone">Phone</option><option value="https" + >Website</option + ></select + > + </div> + <div class="field"> + <label class="label" for="listing-contact-value" + >Public contact details</label + ><input + id="listing-contact-value" + type="text" + value={form.contactValue} + oninput={(event) => { + form = { ...form, contactValue: event.currentTarget.value }; + changed(); + }} + readonly={!visible.editable} + /> + </div> + </div> + </details> + </form> + {#if visible.editable}<p role="status"> + {visible.state === 'saved' + ? 'Saved in this browser.' + : visible.state === 'saving' + ? 'Saving in this browser.' + : visible.state === 'failed' + ? 'Not saved. Keep your current input here.' + : 'Not yet saved.'} + </p> + {#if visible.failure}<Notice + tone="warning" + text="Saving did not complete. Keep your current input. Existing local data has not been reset." + />{/if}{/if} + {/if} +</div> diff --git a/web/src/lib/publishing/listing-editor.ts b/web/src/lib/publishing/listing-editor.ts @@ -0,0 +1,410 @@ +import { + exactLocalFields, + type PublicDraftForm +} from '../contracts/local-records.ts'; +import { canonicalLocalId } from '../private-handles.ts'; +import { decodeProductReference } from '../nostr/references.ts'; +import { inspectLocalTemplate } from '../nostr/local-template.ts'; +import { projectFoodParts } from '../contracts/food-availability-v1/read.ts'; +import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + type BrowserDatabase +} from '../persistence/database.ts'; +import { + createPublicPublicationRepository, + publicPublicationDraftRepository, + publicPublicationQuotaRepository, + readPublicListingIntent +} from '../persistence/public-publications.ts'; +import { + inspectPublicStorage, + publicInventorySnapshot +} from '../persistence/quota.ts'; +import { publicRecordSnapshot } from '../persistence/records.ts'; +import { + readPublicDraft, + publicDraftRepositoryOwner, + type PublicDraftRepository +} from '../persistence/drafts.ts'; +import { + createPublicDraftController, + publicDraftControllerSnapshot, + editPublicDraft, + flushPublicDraft, + closePublicDraftController, + type PublicDraftController +} from './draft-controller.ts'; +import { + identityViewSession, + identityViewMatchesOwner, + type IdentityViewContext +} from '../runtime/view-context.ts'; +import { + identitySessionSnapshot, + subscribeIdentityInvalidation +} from '../runtime/identity-session.ts'; + +declare const editorBrand: unique symbol; +export type ListingEditor = Readonly<{ [editorBrand]: true }>; +export type ListingEditorRoute = + | Readonly<{ mode: 'new' }> + | Readonly<{ mode: 'draft'; draftId: string }> + | Readonly<{ mode: 'edit'; naddr: string }>; +export type ListingEditorSnapshot = Readonly<{ + mode: ListingEditorRoute['mode']; + owner: string; + form: PublicDraftForm; + editable: boolean; + draftId: string | null; + state: 'editing' | 'saving' | 'saved' | 'failed' | 'read-only'; + failure: string | null; + coordinate: string | null; + sourceEventId: string | null; +}>; +type Editor = Readonly<{ + current(): boolean; + retire(): void; + snapshot(): ListingEditorSnapshot | undefined; + edit(form: unknown): Promise<boolean>; + flush(): Promise<boolean>; + subscribe(listener: () => void): () => void; +}>; +const editors = new WeakMap<ListingEditor, Editor>(); +const active = new WeakMap< + IdentityViewContext, + Readonly<{ stamp: symbol; retire(): void }> +>(); +const emptyForm: PublicDraftForm = { + title: '', + description: '', + location: '', + amount: '', + currency: '', + unit: '', + quantity: '', + contactType: '', + contactValue: '' +}; +function routeSnapshot(value: unknown): ListingEditorRoute | undefined { + try { + if (exactLocalFields(value, ['mode']) && value.mode === 'new') + return { mode: 'new' }; + if ( + exactLocalFields(value, ['mode', 'draftId']) && + value.mode === 'draft' + ) { + const draftId = canonicalLocalId(value.draftId); + return draftId ? { mode: 'draft', draftId } : undefined; + } + if (exactLocalFields(value, ['mode', 'naddr']) && value.mode === 'edit') { + const reference = decodeProductReference(value.naddr); + return reference ? { mode: 'edit', naddr: reference.naddr } : undefined; + } + } catch { + return; + } +} +// Owner admission precedes database opening and all protected hydration. Edit +// mode presents validated local values; independent head authorization is later. +export async function openListingEditor( + context: IdentityViewContext, + input: unknown, + signal?: AbortSignal +): Promise< + | Readonly<{ status: 'ready'; editor: ListingEditor }> + | Readonly<{ + status: 'unavailable'; + reason: 'owner' | 'resource' | 'storage' | 'source'; + }> +> { + const session = identityViewSession(context), + route = routeSnapshot(input); + if (!session || signal?.aborted) + return { status: 'unavailable', reason: 'owner' }; + const identity = identitySessionSnapshot(session), + owner = 'publicKey' in identity ? identity.publicKey : undefined; + if (!owner || !identityViewMatchesOwner(context, owner)) + return { status: 'unavailable', reason: 'owner' }; + if ( + !route || + (route.mode === 'edit' && + decodeProductReference(route.naddr)?.pubkey !== owner) + ) + return { status: 'unavailable', reason: 'resource' }; + if (typeof window === 'undefined' || !navigator.locks?.request) + return { status: 'unavailable', reason: 'storage' }; + active.get(context)?.retire(); + const stamp = Symbol(), + listeners = new Map<symbol, () => void>(), + cancellation = new AbortController(); + let alive = true, + unsubscribe = () => {}, + database: BrowserDatabase | undefined, + repository: PublicDraftRepository | undefined, + controller: PublicDraftController | undefined; + function current() { + return ( + alive && + active.get(context)?.stamp === stamp && + identityViewSession(context) === session && + identityViewMatchesOwner(context, owner) && + (!repository || publicDraftRepositoryOwner(repository) === owner) + ); + } + let notifying = false; + function notify() { + if (notifying) return; + notifying = true; + try { + for (const [key, listener] of Array.from(listeners.entries())) + if (listeners.get(key) === listener) { + try { + listener(); + } catch { + /*Presentation observers cannot authorize or retain ownership.*/ + } + } + } finally { + notifying = false; + } + } + function retire() { + if (!alive) return; + alive = false; + unsubscribe(); + signal?.removeEventListener('abort', retire); + cancellation.abort(); + if (controller) closePublicDraftController(controller); + if (database) closeBrowserDatabase(database); + if (active.get(context)?.stamp === stamp) active.delete(context); + notify(); + listeners.clear(); + } + active.set(context, { stamp, retire }); + unsubscribe = subscribeIdentityInvalidation(session, retire); + signal?.addEventListener('abort', retire, { once: true }); + if (signal?.aborted) retire(); + function unavailable(reason: 'resource' | 'storage' | 'source') { + retire(); + return { status: 'unavailable' as const, reason }; + } + try { + const opened = await openBrowserDatabase(cancellation.signal); + if (opened.state !== 'ready') return unavailable('storage'); + if (!current()) { + closeBrowserDatabase(opened.owner); + return unavailable('storage'); + } + database = opened.owner; + const publications = createPublicPublicationRepository(database, owner); + repository = publications && publicPublicationDraftRepository(publications); + if (!publications || !repository || !current()) + return unavailable('storage'); + const drafts = repository; + let sourceForm: PublicDraftForm | undefined, + coordinate: string | null = null, + sourceEventId: string | null = null; + if (route.mode === 'edit') { + const reference = decodeProductReference(route.naddr), + quota = publicPublicationQuotaRepository(publications); + if (!reference || !quota) return unavailable('source'); + const inspected = await inspectPublicStorage(quota); + if (!current() || !inspected.ok) return unavailable('source'); + const inventory = publicInventorySnapshot(quota, inspected.value); + if (!inventory) return unavailable('source'); + let matching: + Readonly<{ form: PublicDraftForm; eventId: string }> | undefined; + for (const item of inventory.rows) { + if (item.family !== 'public_operation') continue; + const read = await readPublicListingIntent(publications, item.id); + if (!current()) return unavailable('source'); + const row = + read.status === 'found' && + publicRecordSnapshot(read.record, owner, item.id); + if ( + !row || + row.family !== 'public_operation' || + row.capture.kind !== 30402 || + !row.artifact || + row.source.type !== 'draft' + ) + continue; + const template = inspectLocalTemplate(row.capture.wire, owner, 30402); + if (!template) continue; + const projected = projectFoodParts(template); + if ( + projected.outcome !== 'focused' || + projected.projection.identifier !== reference.identifier + ) + continue; + const source = await readPublicDraft(drafts, row.source.id); + if (!current()) return unavailable('source'); + if (!source.ok || source.value.revision !== row.source.revision) + continue; + const value = source.value.form, + p = projected.projection; + if (value.contactType === '' && value.contactValue !== '') continue; + const built = buildFoodTemplate({ + identifier: p.identifier, + title: value.title, + description: value.description, + location: value.location, + amount: value.amount, + currency: value.currency, + unit: value.unit, + ...(value.quantity === '' ? {} : { quantity: value.quantity }), + published_at: p.published_at, + created_at: template.created_at, + status: p.status, + ...(value.contactType === '' + ? {} + : { + contact: { + type: value.contactType, + value: value.contactValue, + public: true as const + } + }) + }); + if ( + !built.ok || + JSON.stringify({ + pubkey: owner, + kind: 30402, + created_at: template.created_at, + tags: built.wire_parts.tags, + content: built.wire_parts.content + }) !== row.capture.wire + ) + continue; + if (matching) return unavailable('source'); + matching = { form: value, eventId: row.artifact.eventId }; + } + if (!matching) return unavailable('source'); + sourceForm = matching.form; + coordinate = route.naddr; + sourceEventId = matching.eventId; + } else { + const acquired = await createPublicDraftController( + drafts, + emptyForm, + route.mode === 'draft' ? route.draftId : undefined + ); + if (!current()) { + if (acquired) closePublicDraftController(acquired); + return unavailable('resource'); + } + controller = acquired; + if (!controller) return unavailable('resource'); + } + if (!current()) return unavailable('source'); + const value: Editor = { + current, + retire, + snapshot() { + if (!current()) { + retire(); + return; + } + const local = controller && publicDraftControllerSnapshot(controller); + return { + mode: route.mode, + owner, + form: local ? local.form : { ...(sourceForm ?? emptyForm) }, + editable: route.mode !== 'edit', + draftId: local?.draft?.id ?? null, + state: local + ? local.state === 'closed' + ? 'failed' + : local.state + : 'read-only', + failure: local?.failure ?? null, + coordinate, + sourceEventId + }; + }, + async edit(input) { + if (!current()) { + retire(); + return false; + } + if (!controller || route.mode === 'edit') return false; + if (!editPublicDraft(controller, input)) return false; + notify(); + const pending = flushPublicDraft(controller); + await Promise.resolve(); + if (!current()) { + retire(); + return false; + } + notify(); + const saved = await pending; + if (!current()) { + retire(); + return false; + } + notify(); + return saved; + }, + async flush() { + if (!current()) { + retire(); + return false; + } + if (!controller || route.mode === 'edit') return false; + const pending = flushPublicDraft(controller); + await Promise.resolve(); + if (!current()) { + retire(); + return false; + } + notify(); + const saved = await pending; + if (!current()) { + retire(); + return false; + } + notify(); + return saved; + }, + subscribe(listener) { + if (!current()) return () => {}; + const key = Symbol(); + listeners.set(key, listener); + return () => { + listeners.delete(key); + }; + } + }; + const editor = Object.freeze({}) as ListingEditor; + editors.set(editor, value); + return { status: 'ready', editor }; + } catch { + return unavailable('storage'); + } +} +export function listingEditorSnapshot( + editor: ListingEditor +): ListingEditorSnapshot | undefined { + return editors.get(editor)?.snapshot(); +} +export function editListingEditor( + editor: ListingEditor, + form: unknown +): Promise<boolean> { + return editors.get(editor)?.edit(form) ?? Promise.resolve(false); +} +export function flushListingEditor(editor: ListingEditor): Promise<boolean> { + return editors.get(editor)?.flush() ?? Promise.resolve(false); +} +export function closeListingEditor(editor: ListingEditor): void { + editors.get(editor)?.retire(); +} +export function subscribeListingEditor( + editor: ListingEditor, + listener: () => void +): () => void { + return editors.get(editor)?.subscribe(listener) ?? (() => {}); +} diff --git a/web/src/routes/products/[naddr=naddr]/edit/+page.svelte b/web/src/routes/products/[naddr=naddr]/edit/+page.svelte @@ -1,5 +1,11 @@ <script lang="ts"> - import AccountGate from '../../../../lib/components/AccountGate.svelte'; + import { page } from '$app/state'; + import ListingEditor from '../../../../lib/components/ListingEditor.svelte'; + import type { ListingEditorRoute } from '../../../../lib/publishing/listing-editor.ts'; + const route = $derived({ + mode: 'edit', + naddr: page.params.naddr ?? '' + } satisfies ListingEditorRoute); </script> -<AccountGate /> +<ListingEditor {route} /> diff --git a/web/src/routes/sell/+page.svelte b/web/src/routes/sell/+page.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import AccountGate from '../../lib/components/AccountGate.svelte'; + import ListingEditor from '../../lib/components/ListingEditor.svelte'; </script> -<AccountGate /> +<ListingEditor route={{ mode: 'new' }} /> diff --git a/web/src/routes/selling/drafts/[draftId=local_id]/+page.svelte b/web/src/routes/selling/drafts/[draftId=local_id]/+page.svelte @@ -1,5 +1,11 @@ <script lang="ts"> - import AccountGate from '../../../../lib/components/AccountGate.svelte'; + import { page } from '$app/state'; + import ListingEditor from '../../../../lib/components/ListingEditor.svelte'; + import type { ListingEditorRoute } from '../../../../lib/publishing/listing-editor.ts'; + const route = $derived({ + mode: 'draft', + draftId: page.params.draftId ?? '' + } satisfies ListingEditorRoute); </script> -<AccountGate /> +<ListingEditor {route} /> diff --git a/web/tests/e2e/harness/listing-editor.ts b/web/tests/e2e/harness/listing-editor.ts @@ -0,0 +1,563 @@ +// HC_TEST_ONLY_QUALIFICATION_PORT: original production owners and actual native +// IndexedDB. Controlled installed provider is not extension/operator/live Q. +import { mount, unmount, type ComponentProps } from 'svelte'; +import ListingEditor from '../../../src/lib/components/ListingEditor.svelte'; +import { makeFixture } from './approved-signing.ts'; +import { createFixture as createOperationFixture } from './listing-operation-view.ts'; +import { + createIdentityViewContext, + mountIdentityView, + connectIdentityView, + disconnectIdentityView, + closeIdentityView, + identityViewSnapshot, + IDENTITY_VIEW_CONTEXT +} from '../../../src/lib/runtime/view-context.ts'; +import { + openListingEditor, + listingEditorSnapshot, + editListingEditor, + flushListingEditor, + closeListingEditor, + subscribeListingEditor, + type ListingEditor as Editor, + type ListingEditorRoute +} from '../../../src/lib/publishing/listing-editor.ts'; +import { + browserDatabaseName, + browserSchemaVersion +} from '../../../src/lib/persistence/schema.ts'; +import { + openBrowserDatabase, + closeBrowserDatabase, + browserDatabaseTransaction +} from '../../../src/lib/persistence/database.ts'; +import { + createPublicPublicationRepository, + publicPublicationDraftRepository +} from '../../../src/lib/persistence/public-publications.ts'; +import { + readPublicDraft, + capturePublicDraftSave, + commitPublicDraftWrite +} from '../../../src/lib/persistence/drafts.ts'; +import { inspectLocalTemplate } from '../../../src/lib/nostr/local-template.ts'; +import { projectFoodParts } from '../../../src/lib/contracts/food-availability-v1/read.ts'; +import { encodeProductReference } from '../../../src/lib/nostr/references.ts'; +import type { PublicDraftForm } from '../../../src/lib/contracts/local-records.ts'; +export const reference = ( + identifier: string, + owner = makeFixture(30402).owner +) => encodeProductReference({ kind: 30402, pubkey: owner, identifier }); +export const blank = (): PublicDraftForm => ({ + title: '', + description: '', + location: '', + amount: '', + currency: '', + unit: '', + quantity: '', + contactType: '', + contactValue: '' +}); +export function installProvider() { + const signer = makeFixture(30402); + let signs = 0, + keys = 0; + Object.defineProperty(window, 'nostr', { + configurable: true, + value: { + getPublicKey: () => { + keys++; + return Promise.resolve(signer.owner); + }, + signEvent: (value: Parameters<typeof signer.sign>[0]) => { + signs++; + return Promise.resolve(signer.sign(value)); + } + } + }); + return { owner: signer.owner, counts: () => ({ signs, keys }) }; +} +export async function createFixture(guest = false) { + const prior = Object.getOwnPropertyDescriptor(window, 'nostr'), + provider = installProvider(), + context = createIdentityViewContext(); + let activeOwner = provider.owner; + mountIdentityView(context); + if (!guest) await connectIdentityView(context); + let editor: Editor | undefined, + mounted: ReturnType<typeof mount> | undefined, + target: HTMLElement | undefined; + let operation: Awaited<ReturnType<typeof createOperationFixture>> | undefined; + const cancel = new AbortController(); + async function database() { + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + return opened.owner; + } + async function inspect() { + const db = await database(); + try { + const transaction = browserDatabaseTransaction( + db, + ['public_drafts', 'public_operations'], + 'readonly' + ); + const result = await new Promise<{ + drafts: unknown[]; + operations: unknown[]; + }>((resolve, reject) => { + const a = transaction.objectStore('public_drafts').getAll(), + b = transaction.objectStore('public_operations').getAll(); + transaction.addEventListener('complete', () => + resolve({ drafts: a.result, operations: b.result }) + ); + transaction.addEventListener('abort', () => + reject(Error('native inspection aborted')) + ); + }); + return result; + } finally { + closeBrowserDatabase(db); + } + } + return { + get owner() { + return activeOwner; + }, + counts: () => (operation ? operation.counts() : provider.counts()), + identity: () => identityViewSnapshot(context), + inspect, + async open(route: ListingEditorRoute, forged = false) { + const result = await openListingEditor( + forged ? { ...context } : context, + route, + cancel.signal + ); + if (result.status === 'ready') editor = result.editor; + return result.status === 'ready' + ? { status: 'ready', snapshot: listingEditorSnapshot(result.editor) } + : result; + }, + snapshot: () => editor && listingEditorSnapshot(editor), + async edit(form: PublicDraftForm, copied = false) { + return editor + ? await editListingEditor(copied ? { ...editor } : editor, form) + : false; + }, + async flush(copied = false) { + return editor + ? await flushListingEditor(copied ? { ...editor } : editor) + : false; + }, + copiedClose() { + if (editor) closeListingEditor({ ...editor }); + }, + copiedSubscribe() { + let calls = 0; + const off = editor + ? subscribeListingEditor({ ...editor }, () => { + calls++; + }) + : () => {}; + off(); + return calls; + }, + cancel() { + cancel.abort(); + }, + disconnect() { + disconnectIdentityView(context); + }, + async render(route: ListingEditorRoute) { + if (mounted) await unmount(mounted); + target?.remove(); + target = document.createElement('div'); + target.id = 'hcp115-editor'; + document.body.append(target); + mounted = mount(ListingEditor, { + target, + props: { route } as ComponentProps<typeof ListingEditor>, + context: new Map([[IDENTITY_VIEW_CONTEXT, context]]) + }); + }, + async unmount() { + if (mounted) await unmount(mounted); + mounted = undefined; + target?.remove(); + target = undefined; + }, + async prototype() { + operation = await createOperationFixture(); + if ((await operation.signed()) !== 'prepared') + throw Error('genuine original signature did not settle'); + const row = await operation.row(); + disconnectIdentityView(context); + await connectIdentityView(context); + const observed = identityViewSnapshot(context).identity; + if ( + observed.state === 'guest' || + observed.state === 'pending' || + observed.publicKey !== row.owner + ) + throw Error('actual original prototype author admission failed'); + if (row.source.type !== 'draft') + throw Error('original source unavailable'); + const template = inspectLocalTemplate(row.capture.wire, row.owner, 30402), + projection = template && projectFoodParts(template); + if (!projection || projection.outcome !== 'focused') + throw Error('actual prototype unavailable'); + activeOwner = row.owner; + const naddr = encodeProductReference({ + kind: 30402, + pubkey: row.owner, + identifier: projection.projection.identifier + }); + if (!naddr) throw Error('actual coordinate unavailable'); + return { + naddr, + draftId: row.source.id, + sourceRevision: row.source.revision, + eventId: row.artifact?.eventId + }; + }, + async advanceDraft(id: string) { + const db = await database(); + try { + const publications = createPublicPublicationRepository(db, activeOwner), + repository = + publications && publicPublicationDraftRepository(publications); + if (!repository) throw Error('original draft repo unavailable'); + const read = await readPublicDraft(repository, id); + if (!read.ok) throw Error(read.reason); + const captured = capturePublicDraftSave( + repository, + id, + read.value.revision, + { + ...read.value.form, + description: read.value.form.description + ' changed' + } + ); + if (!captured.ok) throw Error(captured.reason); + const saved = await commitPublicDraftWrite(repository, captured.value); + if (!saved.ok) throw Error(saved.reason); + return saved.value; + } finally { + closeBrowserDatabase(db); + } + }, + async deleteDraft(id: string) { + const db = await database(); + try { + const transaction = browserDatabaseTransaction( + db, + ['public_drafts'], + 'readwrite' + ); + const done = new Promise<void>((resolve, reject) => { + transaction.addEventListener('complete', () => resolve()); + transaction.addEventListener('abort', () => + reject(Error('controlled native deletion aborted')) + ); + }); + transaction.objectStore('public_drafts').delete([activeOwner, id]); + await done; + } finally { + closeBrowserDatabase(db); + } + }, + async damageSource( + mode: 'advanced' | 'deleted' | 'mismatched' | 'ambiguous' | 'external', + id: string + ) { + if (mode === 'advanced') return await this.advanceDraft(id); + if (mode === 'deleted') return await this.deleteDraft(id); + if (!operation) throw Error('actual original prototype missing'); + if (mode === 'external') { + await operation.externalSource(); + return; + } + const db = await database(); + try { + if (mode === 'ambiguous') { + const row = await operation.row(), + id = crypto.randomUUID(); + const transaction = browserDatabaseTransaction( + db, + ['public_operations'], + 'readwrite' + ); + const done = new Promise<void>((resolve, reject) => { + transaction.addEventListener('complete', () => resolve()); + transaction.addEventListener('abort', () => + reject(Error('controlled ambiguity abort')) + ); + }); + transaction.objectStore('public_operations').put({ + owner: row.owner, + id, + wire: JSON.stringify({ ...row, id }) + }); + await done; + return; + } + const publications = createPublicPublicationRepository(db, activeOwner), + repository = + publications && publicPublicationDraftRepository(publications); + if (!repository) throw Error('actual repository missing'); + const read = await readPublicDraft(repository, id); + if (!read.ok) throw Error(read.reason); + const row = { + ...read.value, + form: { + ...read.value.form, + title: 'Different actual bounded draft value' + } + }; + const transaction = browserDatabaseTransaction( + db, + ['public_drafts'], + 'readwrite' + ); + const done = new Promise<void>((resolve, reject) => { + transaction.addEventListener('complete', () => resolve()); + transaction.addEventListener('abort', () => + reject(Error('controlled original source mismatch abort')) + ); + }); + transaction + .objectStore('public_drafts') + .put({ owner: activeOwner, id, wire: JSON.stringify(row) }); + await done; + } finally { + closeBrowserDatabase(db); + } + }, + async close() { + cancel.abort(); + if (editor) closeListingEditor(editor); + if (mounted) await unmount(mounted); + target?.remove(); + closeIdentityView(context); + operation?.close(); + if (prior) Object.defineProperty(window, 'nostr', prior); + else delete window.nostr; + } + }; +} +// Observe actual native calls. Holds defer original application listeners only; +// native completion remains genuine. No synthetic request/transaction/result. +export function nativeObservation() { + const requestDescriptor = Object.getOwnPropertyDescriptor( + IDBRequest.prototype, + 'addEventListener' + ), + transactionDescriptor = Object.getOwnPropertyDescriptor( + IDBTransaction.prototype, + 'addEventListener' + ); + const get = Object.getOwnPropertyDescriptor(IDBObjectStore.prototype, 'get')! + .value as IDBObjectStore['get']; + const put = Object.getOwnPropertyDescriptor(IDBObjectStore.prototype, 'put')! + .value as IDBObjectStore['put']; + const open = Object.getOwnPropertyDescriptor(IDBFactory.prototype, 'open')! + .value as IDBFactory['open']; + const close = Object.getOwnPropertyDescriptor(IDBDatabase.prototype, 'close')! + .value as IDBDatabase['close']; + const inherited = Object.getOwnPropertyDescriptor( + EventTarget.prototype, + 'addEventListener' + ); + if (!inherited) throw Error('actual native registration unavailable'); + const requestAdd = (requestDescriptor ?? inherited) + .value as IDBRequest['addEventListener']; + const transactionAdd = (transactionDescriptor ?? inherited) + .value as IDBTransaction['addEventListener']; + let opens = 0, + closes = 0, + completions = 0, + gets = 0, + puts = 0, + mode: 'none' | 'open-hold' | 'draft-hold' | 'save-hold' | 'open-after' = + 'none', + held: (() => void) | undefined, + after: (() => void) | undefined; + IDBObjectStore.prototype.get = function (...args: Parameters<typeof get>) { + if (this.name === 'public_drafts' || this.name === 'public_operations') + gets++; + return get.call(this, ...args); + }; + IDBObjectStore.prototype.put = function (...args: Parameters<typeof put>) { + if (this.name === 'public_drafts' || this.name === 'public_operations') + puts++; + return put.call(this, ...args); + }; + IDBFactory.prototype.open = function (...args: Parameters<typeof open>) { + opens++; + return open.call(this, ...args); + }; + IDBDatabase.prototype.close = function () { + closes++; + return close.call(this); + }; + IDBRequest.prototype.addEventListener = function ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions + ) { + if (!listener) return; + if ( + this instanceof IDBOpenDBRequest && + type === 'success' && + listener && + (mode === 'open-hold' || mode === 'open-after') + ) { + const chosen = mode; + mode = 'none'; + return requestAdd.call( + this, + type, + (event: Event) => { + const original = event.currentTarget; + if (!(original instanceof EventTarget)) + throw Error('actual native completion target unavailable'); + completions++; + const invoke = () => + typeof listener === 'function' + ? listener.call(original, event) + : listener.handleEvent(event); + if (chosen === 'open-hold') held = invoke; + else { + invoke(); + after?.(); + } + }, + options + ); + } + return requestAdd.call(this, type, listener, options); + }; + IDBTransaction.prototype.addEventListener = function ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions + ) { + if (!listener) return; + if ( + type === 'complete' && + listener && + this.objectStoreNames.contains('public_drafts') && + ((mode === 'draft-hold' && this.mode === 'readonly') || + (mode === 'save-hold' && this.mode === 'readwrite')) + ) { + mode = 'none'; + return transactionAdd.call( + this, + type, + (event: Event) => { + const original = event.currentTarget; + if (!(original instanceof EventTarget)) + throw Error('actual native completion target unavailable'); + completions++; + held = () => + typeof listener === 'function' + ? listener.call(original, event) + : listener.handleEvent(event); + }, + options + ); + } + return transactionAdd.call(this, type, listener, options); + }; + return { + holdOpen() { + mode = 'open-hold'; + }, + holdDraft() { + mode = 'draft-hold'; + }, + holdSave() { + mode = 'save-hold'; + }, + afterOpen(callback: () => void) { + mode = 'open-after'; + after = callback; + }, + state: () => ({ opens, closes, completions, gets, puts, held: !!held }), + release() { + const callback = held; + held = undefined; + callback?.(); + }, + restore() { + IDBObjectStore.prototype.get = get; + IDBObjectStore.prototype.put = put; + IDBFactory.prototype.open = open; + IDBDatabase.prototype.close = close; + if (requestDescriptor) + Object.defineProperty( + IDBRequest.prototype, + 'addEventListener', + requestDescriptor + ); + else Reflect.deleteProperty(IDBRequest.prototype, 'addEventListener'); + if (transactionDescriptor) + Object.defineProperty( + IDBTransaction.prototype, + 'addEventListener', + transactionDescriptor + ); + else Reflect.deleteProperty(IDBTransaction.prototype, 'addEventListener'); + } + }; +} + +export async function inspectNative() { + const opened = await openBrowserDatabase(); + if (opened.state !== 'ready') throw Error(opened.reason); + try { + const transaction = browserDatabaseTransaction( + opened.owner, + ['public_drafts', 'public_operations'], + 'readonly' + ); + return await new Promise<{ drafts: unknown[]; operations: unknown[] }>( + (resolve, reject) => { + const drafts = transaction.objectStore('public_drafts').getAll(), + operations = transaction.objectStore('public_operations').getAll(); + transaction.addEventListener('complete', () => + resolve({ drafts: drafts.result, operations: operations.result }) + ); + transaction.addEventListener('abort', () => + reject(Error('actual native inspection aborted')) + ); + } + ); + } finally { + closeBrowserDatabase(opened.owner); + } +} + +export async function nativeVersionChange() { + const request = indexedDB.open(browserDatabaseName, browserSchemaVersion + 1); + return await new Promise<{ drafts: unknown[] }>((resolve, reject) => { + request.addEventListener('success', () => { + const database = request.result, + transaction = database.transaction(['public_drafts'], 'readonly'), + drafts = transaction.objectStore('public_drafts').getAll(); + transaction.addEventListener('complete', () => { + database.close(); + resolve({ drafts: drafts.result }); + }); + transaction.addEventListener('abort', () => { + database.close(); + reject(Error('controlled upgraded read aborted')); + }); + }); + request.addEventListener('error', () => + reject(request.error ?? Error('native upgrade failed')) + ); + }); +} diff --git a/web/tests/e2e/listing-editor.spec.ts b/web/tests/e2e/listing-editor.spec.ts @@ -0,0 +1,727 @@ +import type { PublicDraftRecord } from '../../src/lib/contracts/local-records.ts'; +import { expect, test } from '@playwright/test'; +import { build } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { fileURLToPath } from 'node:url'; +import { createStaticHarness } from '../integration/harness/static.ts'; +import type * as Fixture from './harness/listing-editor.ts'; +declare global { + interface Window { + hcp115: typeof Fixture; + hcp115Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>; + hcp115Observation: ReturnType<typeof Fixture.nativeObservation>; + hcp115Pending: Promise<unknown>; + } +} +let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string; +const partial = { + title: 'Unfinished local product', + description: ' Retain exact lines\n', + location: '', + amount: '2,50', + currency: '', + unit: 'kg', + quantity: '03', + contactType: '', + contactValue: '' +} as const; +test.beforeAll(async () => { + server = await createStaticHarness(); + const built = await build({ + configFile: false, + plugins: [svelte({ configFile: false })], + resolve: { conditions: ['browser'] }, + logLevel: 'silent', + build: { + write: false, + minify: false, + lib: { + entry: fileURLToPath( + new URL('./harness/listing-editor.ts', import.meta.url) + ), + name: 'hcp115', + formats: ['iife'] + } + } + }); + const output = Array.isArray(built) ? built[0] : built; + if (!('output' in output)) throw Error('actual bundle missing'); + const chunks = output.output.filter((row) => row.type === 'chunk'); + expect(chunks).toHaveLength(1); + bundle = chunks[0].code; +}); +test.afterAll(async () => { + await server?.close(); +}); +test.beforeEach(async ({ page }) => { + await page.addInitScript(() => { + window.WebSocket = class extends WebSocket { + constructor() { + super( + (() => { + throw Error('HCP115 source assertions authorize no relay traffic'); + })() + ); + } + }; + }); + await page.goto(server.url + '/search'); + await page.addScriptTag({ content: bundle }); + await page.evaluate(async () => { + window.hcp115Fixture = await window.hcp115.createFixture(); + }); +}); +test.afterEach(async ({ page }) => { + await page.evaluate(async () => { + window.hcp115Observation?.restore(); + await window.hcp115Fixture?.close(); + }); +}); +test('new GET hydrates nine empty strings without creating a draft or requesting a signature', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const f = window.hcp115Fixture; + const before = f.counts(); + const opened = await f.open({ mode: 'new' }); + return { opened, rows: await f.inspect(), before, after: f.counts() }; + }); + expect(result.opened.status).toBe('ready'); + if (result.opened.status !== 'ready') return; + expect(result.opened.snapshot?.form).toEqual({ + title: '', + description: '', + location: '', + amount: '', + currency: '', + unit: '', + quantity: '', + contactType: '', + contactValue: '' + }); + expect(result.opened.snapshot?.draftId).toBeNull(); + expect(result.rows.drafts).toHaveLength(0); + expect(result.after).toEqual(result.before); +}); +test('sign-only owner saves incomplete exact strings without messaging admission or invalid paint', async ({ + page +}) => { + await page.evaluate(async () => { + await window.hcp115Fixture.render({ mode: 'new' }); + }); + await expect(page.locator('#hcp115-editor form')).toBeVisible(); + await page.getByLabel('Product name', { exact: true }).fill(partial.title); + await page.getByLabel('Price', { exact: true }).fill(partial.amount); + await page.getByLabel('Per', { exact: true }).selectOption('kg'); + await page + .getByLabel('Advertised quantity (optional)', { exact: true }) + .fill('03'); + await expect( + page.getByText('Saved in this browser.', { exact: true }) + ).toBeVisible(); + const actual = await page.evaluate(async () => ({ + rows: await window.hcp115Fixture.inspect(), + identity: window.hcp115Fixture.identity(), + counts: window.hcp115Fixture.counts() + })); + const rows = actual.rows.drafts as { wire: string }[]; + expect(rows).toHaveLength(1); + expect((JSON.parse(rows[0].wire) as PublicDraftRecord).form).toMatchObject({ + title: partial.title, + amount: '2,50', + currency: '', + unit: 'kg', + quantity: '03' + }); + expect(actual.counts.signs).toBe(0); + await expect( + page.locator('#hcp115-editor [aria-invalid="true"]') + ).toHaveCount(0); +}); +test('resume opens the exact original incomplete draft without replacement or validation paint', async ({ + page +}) => { + const id = await page.evaluate(async (form) => { + const f = window.hcp115Fixture; + await f.open({ mode: 'new' }); + if (!(await f.edit(form))) throw Error('actual partial save failed'); + return f.snapshot()?.draftId; + }, partial); + expect(id).toBeTruthy(); + const result = await page.evaluate(async (id) => { + const f = window.hcp115Fixture; + const before = await f.inspect(); + const opened = await f.open({ mode: 'draft', draftId: id! }); + await f.render({ mode: 'draft', draftId: id! }); + return { before, opened, after: await f.inspect() }; + }, id); + expect(result.opened.status).toBe('ready'); + if (result.opened.status === 'ready') + expect(result.opened.snapshot?.form).toEqual(partial); + expect(result.after).toEqual(result.before); + await expect(page.locator('#hcp115-editor form')).toBeVisible(); + await expect( + page.locator('#hcp115-editor [aria-invalid="true"]') + ).toHaveCount(0); +}); +test('all three modes share mandatory fields and optional public contact without SKU image or shipping', async ({ + page +}) => { + const prototype = await page.evaluate( + async () => await window.hcp115Fixture.prototype() + ); + for (const route of [ + { mode: 'new' } as const, + { mode: 'draft', draftId: prototype.draftId } as const, + { mode: 'edit', naddr: prototype.naddr } as const + ]) { + await page.evaluate(async (route) => { + await window.hcp115Fixture.render(route); + }, route); + await expect(page.locator('#hcp115-editor form')).toBeVisible(); + await expect( + page.locator( + '#hcp115-editor input, #hcp115-editor textarea, #hcp115-editor select' + ) + ).toHaveCount(9); + await expect( + page.getByLabel('Product name', { exact: true }) + ).toBeVisible(); + await expect(page.getByLabel('Public area', { exact: true })).toBeVisible(); + await expect(page.getByLabel('Price', { exact: true })).toHaveAttribute( + 'type', + 'text' + ); + await page + .getByText('Add public contact details (optional)', { exact: true }) + .click(); + await expect( + page.getByText('Only add contact details you want to include publicly.', { + exact: true + }) + ).toBeVisible(); + await expect(page.locator('#hcp115-editor')).not.toContainText( + /SKU|shipping/i + ); + await expect( + page.locator( + '#hcp115-editor input[type="file"],#hcp115-editor img,[aria-invalid="true"]' + ) + ).toHaveCount(0); + } +}); +test('edit hydrates only genuine exact original source values and remains read-only without effects', async ({ + page +}) => { + const result = await page.evaluate(async () => { + const f = window.hcp115Fixture, + p = await f.prototype(), + before = await f.inspect(), + counts = f.counts(); + const opened = await f.open({ mode: 'edit', naddr: p.naddr }); + const edit = await f.edit(window.hcp115.blank()), + flush = await f.flush(); + return { + p, + before, + opened, + edit, + flush, + after: await f.inspect(), + counts, + afterCounts: f.counts() + }; + }); + expect(result.opened.status).toBe('ready'); + if (result.opened.status === 'ready') { + expect(result.opened.snapshot?.editable).toBe(false); + expect(result.opened.snapshot?.sourceEventId).toBe(result.p.eventId); + const native = result.before.drafts as { wire: string }[]; + const source = native + .map((row) => JSON.parse(row.wire) as PublicDraftRecord) + .find((row) => row.id === result.p.draftId); + if (!source) throw Error('actual original source draft missing'); + expect(result.opened.snapshot?.form).toEqual(source.form); + } + expect(result.edit).toBe(false); + expect(result.flush).toBe(false); + expect(result.after).toEqual(result.before); + expect(result.afterCounts).toEqual(result.counts); +}); +for (const damage of [ + 'advanced', + 'deleted', + 'mismatched', + 'ambiguous', + 'external' +] as const) + test(`edit refuses ${damage} original source without capture inversion or data reset`, async ({ + page + }) => { + const result = await page.evaluate(async (damage) => { + const f = window.hcp115Fixture, + p = await f.prototype(); + await f.damageSource(damage, p.draftId); + const before = await f.inspect(), + counts = f.counts(), + opened = await f.open({ mode: 'edit', naddr: p.naddr }); + return { + before, + opened, + after: await f.inspect(), + counts, + afterCounts: f.counts() + }; + }, damage); + expect(result.opened).toEqual({ status: 'unavailable', reason: 'source' }); + expect(result.after).toEqual(result.before); + expect(result.afterCounts).toEqual(result.counts); + }); +test('foreign edit author is rejected before native opening or hydration', async ({ + page +}) => { + const actual = await page.evaluate(async () => { + window.hcp115Observation = window.hcp115.nativeObservation(); + return { + result: await window.hcp115Fixture.open({ + mode: 'edit', + naddr: window.hcp115.reference('foreign')! + }), + native: window.hcp115Observation.state() + }; + }); + expect(actual.result).toEqual({ status: 'unavailable', reason: 'resource' }); + expect(actual.native).toMatchObject({ opens: 0, gets: 0, puts: 0 }); +}); +test('missing original draft never creates a replacement', async ({ page }) => { + const actual = await page.evaluate(async () => ({ + result: await window.hcp115Fixture.open({ + mode: 'draft', + draftId: crypto.randomUUID() + }), + rows: await window.hcp115Fixture.inspect() + })); + expect(actual.result.status).toBe('unavailable'); + expect(actual.rows.drafts).toHaveLength(0); +}); +test('copied editor cannot subscribe close save or flush while original remains usable', async ({ + page +}) => { + const actual = await page.evaluate(async (form) => { + const f = window.hcp115Fixture; + await f.open({ mode: 'new' }); + const copied = await f.edit(form, true), + flush = await f.flush(true), + calls = f.copiedSubscribe(); + f.copiedClose(); + const before = await f.inspect(), + alive = !!f.snapshot(), + original = await f.edit(form); + return { + copied, + flush, + calls, + before, + alive, + original, + after: await f.inspect() + }; + }, partial); + expect(actual).toMatchObject({ + copied: false, + flush: false, + calls: 0, + alive: true, + original: true + }); + expect(actual.before.drafts).toHaveLength(0); + expect(actual.after.drafts).toHaveLength(1); +}); +test('malformed route and copied identity are rejected before native opening', async ({ + page +}) => { + const actual = await page.evaluate(async () => { + window.hcp115Observation = window.hcp115.nativeObservation(); + const f = window.hcp115Fixture; + return { + malformed: await f.open({ mode: 'draft', draftId: '../other' }), + copied: await f.open({ mode: 'new' }, true), + native: window.hcp115Observation.state() + }; + }); + expect(actual.malformed.status).toBe('unavailable'); + expect(actual.copied).toEqual({ status: 'unavailable', reason: 'owner' }); + expect(actual.native).toMatchObject({ opens: 0, gets: 0, puts: 0 }); +}); +test('logout hides protected mounted values and retains original native draft bytes', async ({ + page +}) => { + await page.evaluate(async () => { + await window.hcp115Fixture.render({ mode: 'new' }); + }); + await expect(page.locator('#hcp115-editor form')).toBeVisible(); + await page + .getByLabel('Product name', { exact: true }) + .fill('Private unfinished input'); + await expect( + page.getByText('Saved in this browser.', { exact: true }) + ).toBeVisible(); + const before = await page.evaluate( + async () => await window.hcp115Fixture.inspect() + ); + await page.evaluate(() => window.hcp115Fixture.disconnect()); + await expect(page.locator('#hcp115-editor form')).toHaveCount(0); + await expect(page.locator('#hcp115-editor')).not.toContainText( + 'Private unfinished input' + ); + expect( + await page.evaluate(async () => await window.hcp115Fixture.inspect()) + ).toEqual(before); +}); +test('cancel during genuine open completion closes the late connection before protected hydration', async ({ + page +}) => { + await page.evaluate(() => { + window.hcp115Observation = window.hcp115.nativeObservation(); + window.hcp115Observation.holdOpen(); + window.hcp115Pending = window.hcp115Fixture.open({ mode: 'new' }); + }); + await expect + .poll( + async () => + await page.evaluate(() => window.hcp115Observation.state().held) + ) + .toBe(true); + await page.evaluate(() => { + window.hcp115Fixture.cancel(); + window.hcp115Observation.release(); + }); + const result = await page.evaluate(async () => ({ + result: await window.hcp115Pending, + native: window.hcp115Observation.state(), + snapshot: window.hcp115Fixture.snapshot() + })); + expect(result.result).toMatchObject({ status: 'unavailable' }); + expect(result.native).toMatchObject({ + opens: 1, + closes: 1, + gets: 0, + puts: 0, + completions: 1 + }); + expect(result.snapshot).toBeUndefined(); +}); +test('cancellation between original open resolution and await custody closes the actual ready owner', async ({ + page +}) => { + const result = await page.evaluate(async () => { + window.hcp115Observation = window.hcp115.nativeObservation(); + window.hcp115Observation.afterOpen(() => window.hcp115Fixture.cancel()); + return { + result: await window.hcp115Fixture.open({ mode: 'new' }), + native: window.hcp115Observation.state() + }; + }); + expect(result.result).toMatchObject({ status: 'unavailable' }); + expect(result.native).toMatchObject({ + opens: 1, + closes: 1, + gets: 0, + puts: 0, + completions: 1 + }); +}); +test('cancel after original draft native read completion retires the late controller without writes', async ({ + page +}) => { + const id = await page.evaluate(async (form) => { + const f = window.hcp115Fixture; + await f.open({ mode: 'new' }); + await f.edit(form); + return f.snapshot()?.draftId; + }, partial); + await page.evaluate((id) => { + window.hcp115Observation = window.hcp115.nativeObservation(); + window.hcp115Observation.holdDraft(); + window.hcp115Pending = window.hcp115Fixture.open({ + mode: 'draft', + draftId: id! + }); + }, id); + await expect + .poll( + async () => + await page.evaluate(() => window.hcp115Observation.state().held) + ) + .toBe(true); + await page.evaluate(() => { + window.hcp115Fixture.cancel(); + window.hcp115Observation.release(); + }); + const result = await page.evaluate(async () => ({ + result: await window.hcp115Pending, + native: window.hcp115Observation.state(), + snapshot: window.hcp115Fixture.snapshot() + })); + expect(result.result).toMatchObject({ status: 'unavailable' }); + expect(result.native.gets).toBeGreaterThan(0); + expect(result.native.puts).toBe(0); + expect(result.native.closes).toBeGreaterThan(0); + expect(result.snapshot).toBeUndefined(); +}); +test('superseded pending acquisition cannot replace or retire the newer editor', async ({ + page +}) => { + await page.evaluate(() => { + window.hcp115Observation = window.hcp115.nativeObservation(); + window.hcp115Observation.holdOpen(); + window.hcp115Pending = window.hcp115Fixture.open({ mode: 'new' }); + }); + await expect + .poll( + async () => + await page.evaluate(() => window.hcp115Observation.state().held) + ) + .toBe(true); + const newer = await page.evaluate( + async () => await window.hcp115Fixture.open({ mode: 'new' }) + ); + expect(newer.status).toBe('ready'); + await page.evaluate(() => window.hcp115Observation.release()); + const actual = await page.evaluate(async () => ({ + old: await window.hcp115Pending, + current: window.hcp115Fixture.snapshot(), + native: window.hcp115Observation.state() + })); + expect(actual.old).toMatchObject({ status: 'unavailable' }); + expect(actual.current?.editable).toBe(true); + expect(actual.native.puts).toBe(0); + expect(actual.native.closes).toBeGreaterThan(0); +}); +test('component unmount cancels genuine pending acquisition before late resources arrive', async ({ + page +}) => { + await page.evaluate(async () => { + window.hcp115Observation = window.hcp115.nativeObservation(); + window.hcp115Observation.holdOpen(); + await window.hcp115Fixture.render({ mode: 'new' }); + }); + await expect + .poll( + async () => + await page.evaluate(() => window.hcp115Observation.state().held) + ) + .toBe(true); + await page.evaluate(async () => { + await window.hcp115Fixture.unmount(); + window.hcp115Observation.release(); + }); + await expect + .poll( + async () => + await page.evaluate(() => window.hcp115Observation.state().closes) + ) + .toBe(1); + await expect(page.locator('#hcp115-editor')).toHaveCount(0); + expect(await page.evaluate(() => window.hcp115Observation.state().puts)).toBe( + 0 + ); +}); +test('genuine submitted save shows Saving and late acknowledgment cannot repaint after unmount', async ({ + page +}) => { + await page.evaluate( + async () => await window.hcp115Fixture.render({ mode: 'new' }) + ); + await expect(page.locator('#hcp115-editor form')).toBeVisible(); + await page.evaluate(() => { + window.hcp115Observation = window.hcp115.nativeObservation(); + window.hcp115Observation.holdSave(); + }); + await page + .getByLabel('Product name', { exact: true }) + .fill('Actual submitted native partial draft'); + await expect + .poll( + async () => + await page.evaluate(() => window.hcp115Observation.state().held) + ) + .toBe(true); + await expect( + page.getByText('Saving in this browser.', { exact: true }) + ).toBeVisible(); + await page.evaluate(async () => { + await window.hcp115Fixture.unmount(); + window.hcp115Observation.release(); + }); + await expect(page.locator('#hcp115-editor')).toHaveCount(0); + const actual = await page.evaluate(async () => ({ + rows: await window.hcp115Fixture.inspect(), + native: window.hcp115Observation.state() + })); + expect(actual.rows.drafts).toHaveLength(1); + expect( + ( + JSON.parse( + (actual.rows.drafts[0] as { wire: string }).wire + ) as PublicDraftRecord + ).form.title + ).toBe('Actual submitted native partial draft'); + expect(actual.native.puts).toBe(1); +}); +test('actual compiled guest routes never hydrate protected listing fields or connect implicitly', async ({ + page +}) => { + const naddr = await page.evaluate(() => window.hcp115.reference('guest')!); + for (const route of [ + '/sell', + '/selling/drafts/' + crypto.randomUUID(), + '/products/' + naddr + '/edit' + ]) { + await page.goto(server.url + route); + await expect(page.locator('main h1')).toBeVisible(); + await expect(page.locator('main form')).toHaveCount(0); + await expect( + page + .getByRole('button', { name: 'Connect extension', exact: true }) + .last() + ).toBeVisible(); + } +}); +test('actual compiled connected routes share original new draft and read-only edit hydration', async ({ + page +}) => { + const prototype = await page.evaluate( + async () => await window.hcp115Fixture.prototype() + ); + async function navigate(path: string) { + await page.evaluate((path) => { + const anchor = document.createElement('a'); + anchor.href = path; + anchor.textContent = 'HCP115 controlled local route'; + anchor.id = 'hcp115-route-link'; + document.body.append(anchor); + }, path); + await page.locator('#hcp115-route-link').click(); + await expect(page).toHaveURL(server.url + path); + await page.evaluate(() => + document.querySelector('#hcp115-route-link')?.remove() + ); + } + await navigate('/sell'); + await page + .getByRole('button', { name: 'Connect extension', exact: true }) + .last() + .click(); + await expect(page.locator('main form')).toBeVisible(); + await expect( + page.locator('main input,main textarea,main select') + ).toHaveCount(9); + await expect(page.getByLabel('Product name', { exact: true })).toHaveValue( + '' + ); + await page + .getByLabel('Product name', { exact: true }) + .fill('Compiled partial route value'); + await expect( + page.getByText('Saved in this browser.', { exact: true }) + ).toBeVisible(); + const native = await page.evaluate( + async () => await window.hcp115.inspectNative() + ); + const draft = (native.drafts as { wire: string }[]) + .map((row) => JSON.parse(row.wire) as PublicDraftRecord) + .find((row) => row.form.title === 'Compiled partial route value'); + expect(draft).toBeTruthy(); + if (!draft) throw Error('actual compiled route draft missing'); + await navigate('/selling/drafts/' + draft.id); + await expect(page.getByLabel('Product name', { exact: true })).toHaveValue( + 'Compiled partial route value' + ); + await expect( + page.locator('main input,main textarea,main select') + ).toHaveCount(9); + await navigate('/products/' + prototype.naddr + '/edit'); + await expect(page.locator('main form')).toBeVisible(); + await expect( + page.getByLabel('Product name', { exact: true }) + ).toHaveAttribute('readonly', ''); + await expect(page.getByLabel('Per', { exact: true })).toBeDisabled(); + await expect( + page.getByText( + 'These retained local values are read-only until the current listing is checked.', + { exact: true } + ) + ).toBeVisible(); +}); +test('actual native versionchange retires editor instead of saving new input through a closed owner', async ({ + page +}) => { + await page.evaluate( + async () => await window.hcp115Fixture.render({ mode: 'new' }) + ); + await expect(page.locator('#hcp115-editor form')).toBeVisible(); + await page + .getByLabel('Product name', { exact: true }) + .fill('Persisted before native closure'); + await expect( + page.getByText('Saved in this browser.', { exact: true }) + ).toBeVisible(); + const native = await page.evaluate( + async () => await window.hcp115.nativeVersionChange() + ); + expect(native.drafts).toHaveLength(1); + await page + .getByLabel('Product name', { exact: true }) + .fill('Must not save through closed native owner'); + await expect(page.locator('#hcp115-editor form')).toHaveCount(0); + await expect( + page.getByText( + 'Browser storage is unavailable. Your existing local data has not been reset.', + { exact: true } + ) + ).toBeVisible(); + expect( + ( + JSON.parse( + (native.drafts[0] as { wire: string }).wire + ) as PublicDraftRecord + ).form.title + ).toBe('Persisted before native closure'); +}); + +test('foreign retained draft stays unavailable to a different genuine connected author without reset', async ({ + page +}) => { + const actual = await page.evaluate(async () => { + const first = window.hcp115Fixture, + prototype = await first.prototype(), + owner = first.owner, + before = await first.inspect(); + await first.close(); + window.hcp115Fixture = await window.hcp115.createFixture(); + const next = window.hcp115Fixture; + if (next.owner === owner) + throw Error('controlled independent authors must differ'); + const opened = await next.open({ + mode: 'draft', + draftId: prototype.draftId + }); + await next.render({ mode: 'draft', draftId: prototype.draftId }); + return { + opened, + snapshot: next.snapshot(), + before, + after: await next.inspect(), + counts: next.counts() + }; + }); + expect(actual.opened.status).toBe('unavailable'); + expect(actual.snapshot).toBeUndefined(); + expect(actual.after).toEqual(actual.before); + expect(actual.counts.signs).toBe(0); + await expect( + page.getByText('This draft is not available here.', { exact: true }) + ).toBeVisible(); + await expect(page.locator('#hcp115-editor form')).toHaveCount(0); +}); diff --git a/web/tests/e2e/route-inventory.spec.ts b/web/tests/e2e/route-inventory.spec.ts @@ -61,7 +61,7 @@ test('current source has no revision-one aliases or query-driven redirects', asy const target = server.url + '/sell?' + query.toString(); expect((await page.goto(target))?.status()).toBe(200); await expect( - page.getByRole('heading', { name: 'Connect or unlock', exact: true }) + page.getByRole('heading', { name: 'Connect to continue', exact: true }) ).toBeVisible(); expect(page.url()).toBe(target); // Exercise the real initialized client and Back, rather than SSR alone. @@ -69,7 +69,7 @@ test('current source has no revision-one aliases or query-driven redirects', asy await expect(page.getByLabel('What are you looking for?')).toBeEnabled(); await page.goBack(); await expect( - page.getByRole('heading', { name: 'Connect or unlock', exact: true }) + page.getByRole('heading', { name: 'Connect to continue', exact: true }) ).toBeVisible(); expect(page.url()).toBe(target); await expect( @@ -91,13 +91,24 @@ const cases = [ { path: '/', title: 'HarvestCircle', private: false }, { path: '/search', title: 'Search food — HarvestCircle', private: false }, { path: '/products/' + naddr, title: 'Food — HarvestCircle', private: false }, - { path: '/sell', title: 'HarvestCircle', private: true }, + { + path: '/sell', + title: 'New listing · HarvestCircle', + private: true, + editor: true + }, { path: '/selling', title: 'HarvestCircle', private: true }, - { path: '/selling/drafts/' + handle, title: 'HarvestCircle', private: true }, + { + path: '/selling/drafts/' + handle, + title: 'Continue draft · HarvestCircle', + private: true, + editor: true + }, { path: '/products/' + naddr + '/edit', - title: 'HarvestCircle', - private: true + title: 'Edit listing · HarvestCircle', + private: true, + editor: true }, { path: '/messages', title: 'HarvestCircle', private: true }, { path: '/messages/' + handle, title: 'HarvestCircle', private: true }, @@ -144,7 +155,9 @@ for (const routeCase of cases) { if (routeCase.private) { await expect( page.getByRole('heading', { - name: 'Connect or unlock', + name: routeCase.editor + ? 'Connect to continue' + : 'Connect or unlock', exact: true }) ).toBeVisible(); @@ -152,16 +165,29 @@ for (const routeCase of cases) { 'content', 'noindex' ); - await expect( - page.getByRole('button', { - name: 'Check current preference', - exact: true - }) - ).toBeDisabled(); - await expect(page.locator('main button')).toHaveCount(3); - await expect( - page.getByRole('button', { name: 'Not now', exact: true }) - ).toBeEnabled(); + if (routeCase.editor) { + await expect(page.locator('main button')).toHaveCount(1); + await expect( + page.getByRole('button', { + name: 'Check current preference', + exact: true + }) + ).toHaveCount(0); + await expect( + page.getByRole('button', { name: 'Not now', exact: true }) + ).toHaveCount(0); + } else { + await expect( + page.getByRole('button', { + name: 'Check current preference', + exact: true + }) + ).toBeDisabled(); + await expect(page.locator('main button')).toHaveCount(3); + await expect( + page.getByRole('button', { name: 'Not now', exact: true }) + ).toBeEnabled(); + } await expect( page.getByRole('button', { name: 'Unlock inbox', exact: true }) ).toHaveCount(0); diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts @@ -63,12 +63,23 @@ await test('navigation fallback serves actual separate output and preserves miss for (const pathname of ['/sell', '/selling', '/messages']) { const html = prerendered.get(pathname); assert.ok(html); - assert.match(html, /<title>HarvestCircle<\/title>/); - assert.match(html, /name="robots" content="noindex"/); assert.match( html, - /Private views and editing are unavailable during development/ + pathname === '/sell' + ? /<title>New listing · HarvestCircle<\/title>/ + : /<title>HarvestCircle<\/title>/ ); + assert.match(html, /name="robots" content="noindex"/); + if (pathname === '/sell') { + assert.match(html, /Connect to continue/); + assert.match(html, /<button[^>]*disabled[^>]*>Connect extension/); + assert.doesNotMatch(html, /Inbox setup|Check current preference/); + } else { + assert.match( + html, + /Private views and editing are unavailable during development/ + ); + } assert.doesNotMatch(html, /<form|<input|<textarea/); } assert.notEqual(search, fallback); diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -31,6 +31,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; '<svelte:head><title>Food — HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>Food</h1>\n <p class="notice">Food details are unavailable during development.</p>\n</div>\n'; // Frozen public-only HCP055 producers, source6023db01169aa82cb6fe68ca94e1a73750247e72. // Compatibility evidence only; runtime tests never require ancestor Git history. + /** @type {Record<string, {source:string, sha256:string}>} */ const historicalPublicOnly = { 'src/routes/+layout.svelte': { source: @@ -47,6 +48,22 @@ import { auditOutput } from '../../tools/check-output.mjs'; '<script lang="ts">\n import Button from \'./primitives/Button.svelte\';\n</script>\n\n<svelte:head>\n <title>HarvestCircle</title>\n <meta name="robots" content="noindex" />\n</svelte:head>\n<div class="page page--reading stack">\n <h1>Connect or unlock</h1>\n <p>Connect an extension and unlock your account to continue.</p>\n <p class="notice">Account access is unavailable during development.</p>\n <div class="cluster">\n <Button label="Connect extension" disabled />\n <Button label="Unlock" disabled />\n </div>\n</div>\n', sha256: 'd5f90fb4b9af50037ed19dde626552e82df67017a39408bdbdeff1e712c10fbd' }, + // Exact predecessor AccountGate route bytes, historical compatibility only. + 'src/routes/sell/+page.svelte': { + source: + '<script lang="ts">\n import AccountGate from \'../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', + sha256: '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a' + }, + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte': { + source: + '<script lang="ts">\n import AccountGate from \'../../../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', + sha256: '465852393264789ceae4133e8d79416ebf37d5485b08fb54c61056fa3714dc5d' + }, + 'src/routes/products/[naddr=naddr]/edit/+page.svelte': { + source: + '<script lang="ts">\n import AccountGate from \'../../../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', + sha256: '465852393264789ceae4133e8d79416ebf37d5485b08fb54c61056fa3714dc5d' + }, // Historical public-only variants must also restore their original private // shell. The successor route imports owned identity context, which those // historical roots never provided. Current actual-output cases retain it. @@ -364,7 +381,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; 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, 53); + assert.equal(files.length, 55); // 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( @@ -640,7 +657,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; assert.ok(Buffer.byteLength(expanded) > 64 * 1024); await writeFile(file, expanded); await refresh(f); - assert.equal((await f.audit()).length, 53); + assert.equal((await f.audit()).length, 55); } ); @@ -1138,6 +1155,110 @@ import { auditOutput } from '../../tools/check-output.mjs'; assert.ok((await f.audit()).includes(budget.file)); } ); + for (const name of [ + 'ListingEditor', + 'view-context', + 'nodes/8', + 'nodes/10', + 'nodes/12' + ]) { + for (const mutation of [ + 'missing', + 'missing-edge', + 'extra-edge', + 'duplicate-edge', + 'permuted-edges', + 'dynamic', + 'entry', + 'css' + ]) { + await check( + 'exact listing editor compiler rejects ' + name + ' ' + mutation, + async (t) => { + const f = await fixture(t), + file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const manifest = JSON.parse(await readFile(file, 'utf8')); + const entry = Object.entries(manifest).find( + ([, row]) => row.name === name + ); + assert.ok(entry); + const [key, row] = entry; + if (mutation === 'missing') delete manifest[key]; + if (mutation === 'missing-edge') + row.imports = row.imports.slice(1); + if (mutation === 'extra-edge') + row.imports = row.imports.concat( + Object.keys(manifest).find( + (key) => manifest[key].name === 'AccountGate' + ) + ); + if (mutation === 'duplicate-edge') + row.imports = row.imports.concat(row.imports[0]); + if (mutation === 'permuted-edges') + row.imports = [...row.imports].reverse(); + if (mutation === 'dynamic') + row.dynamicImports = [row.imports[0]]; + if (mutation === 'entry') { + if (row.isEntry === true) delete row.isEntry; + else row.isEntry = true; + } + if (mutation === 'css') row.css = []; + await writeFile(file, JSON.stringify(manifest)); + await assert.rejects(f.audit, /compiler|references|import/); + } + ); + } + } + for (const producer of [ + 'src/routes/sell/+page.svelte', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte', + 'src/lib/components/ListingEditor.svelte', + 'src/lib/publishing/listing-editor.ts' + ]) { + await check( + 'listing editor 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// owned editor source mutation\n' + ); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned listing editor source/ + ); + } + ); + } + for (const route of [ + 'src/routes/sell/+page.svelte', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte' + ]) { + await check( + 'listing editor rejects partial three-route activation ' + route, + async (t) => { + const f = await fixture(t); + const historical = historicalPublicOnly[route]; + assert.equal( + createHash('sha256').update(historical.source).digest('hex'), + historical.sha256 + ); + await writeFile(path.join(f.web, route), historical.source); + await refresh(f); + await assert.rejects( + f.audit, + /Invalid owned listing editor activation/ + ); + } + ); + } for (const producer of [ 'src/routes/products/[naddr=naddr]/+page.svelte', 'src/lib/catalog/product-view.ts', @@ -1203,9 +1324,7 @@ import { auditOutput } from '../../tools/check-output.mjs'; row.imports = row.imports.concat(row.imports[0]); } await writeFile(file, JSON.stringify(manifest)); - if (mutation === 'permuted-edges') - assert.equal((await f.audit()).length, 53); - else await assert.rejects(f.audit, /compiler|references/); + await assert.rejects(f.audit, /compiler|references/); } ); } diff --git a/web/tests/unit/listing-editor.test.ts b/web/tests/unit/listing-editor.test.ts @@ -0,0 +1,53 @@ +import { expect, it } from 'vitest'; +import { render } from 'svelte/server'; +import ListingEditor from '../../src/lib/components/ListingEditor.svelte'; +import { + openListingEditor, + listingEditorSnapshot, + editListingEditor, + flushListingEditor, + closeListingEditor, + subscribeListingEditor, + type ListingEditor as Editor, + type ListingEditorRoute +} from '../../src/lib/publishing/listing-editor.ts'; +import type { IdentityViewContext } from '../../src/lib/runtime/view-context.ts'; +it('HCP115 copied unmounted identity cannot admit or hydrate a protected editor', async () => { + expect( + await openListingEditor({} as IdentityViewContext, { mode: 'new' }) + ).toEqual({ status: 'unavailable', reason: 'owner' }); +}); +it('HCP115 copied success data cannot become an editor or borrow edit effects', async () => { + const copied = { + mode: 'new', + editable: true, + owner: '0'.repeat(64) + } as unknown as Editor; + expect(listingEditorSnapshot(copied)).toBeUndefined(); + expect(await editListingEditor(copied, {})).toBe(false); + expect(await flushListingEditor(copied)).toBe(false); +}); +it('HCP115 copied Close and subscriptions cannot retire an original owner', () => { + const copied = {} as Editor; + let calls = 0; + const off = subscribeListingEditor(copied, () => { + calls++; + }); + closeListingEditor(copied); + off(); + expect(calls).toBe(0); +}); +it('HCP115 all three SSR routes show connection before protected values or effects', () => { + for (const route of [ + { mode: 'new' }, + { mode: 'draft', draftId: '00000000-0000-4000-8000-000000000001' }, + { mode: 'edit', naddr: 'unsupported' } + ] as ListingEditorRoute[]) { + const html = render(ListingEditor, { props: { route } }).body; + expect(html).toContain('Connect to continue'); + expect(html).not.toMatch(/<input|<textarea|<form|<select/); + expect(html).not.toMatch( + /Public contact details|Saved in this browser|Account-specific draft/ + ); + } +}); diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts @@ -58,6 +58,11 @@ describe('approved route inventory', () => { }); describe('thin protected route SSR', () => { + const editorTitles: Readonly<Record<string, string>> = { + Sell: 'New listing', + Draft: 'Continue draft', + Edit: 'Edit listing' + }; for (const [name, renderComponent] of Object.entries({ Sell: () => render(Sell), Selling: () => render(Selling), @@ -68,9 +73,28 @@ describe('thin protected route SSR', () => { })) { it( name + - ' renders only a generic unavailable connection/unlock gate without browser effects', + (editorTitles[name] + ? ' renders the shared editor connection gate before protected values or browser effects' + : ' renders only a generic unavailable connection/unlock gate without browser effects'), () => { const output = renderComponent(); + const editorTitle = editorTitles[name]; + if (editorTitle) { + expect(output.head).toContain( + '<title>' + editorTitle + ' · HarvestCircle</title>' + ); + expect(output.head).toMatch(/name="robots" content="noindex"/); + expect(output.body).toContain('Connect to continue'); + expect(output.body).toMatch( + /<button[^>]*disabled[^>]*>Connect extension/ + ); + expect(output.body).not.toMatch( + /<form|<textarea|<input|<select|PRIVATE_TEST_ONLY|naddr1|Inbox setup|Check current preference/ + ); + // Original SSR effect tripwires still reject IDB/extension/socket/fetch. + return; + } + expect(output.head).toContain('<title>HarvestCircle</title>'); expect(output.head).toMatch(/name="robots" content="noindex"/); expect(output.body).toContain('Connect or unlock'); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -580,6 +580,43 @@ async function listingPublicationAdmission(web) { } return true; } +// HCP115 one shared editor activates all three routes together. Historical +// AccountGate routes remain labelled compatibility producers only. +/** @param {string} web */ +async function listingEditorAdmission(web) { + const routes = [ + 'src/routes/sell/+page.svelte', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte' + ]; + const enabled = await Promise.all( + routes.map(async (name) => + publicText(await readOwned(web, name)).includes('ListingEditor.svelte') + ) + ); + if (!enabled.some(Boolean)) return false; + if (!enabled.every(Boolean)) + throw new Error('Invalid owned listing editor activation'); + const producers = { + 'src/routes/sell/+page.svelte': + '3e99a6121e9ea317d30e631d9edfb05e6596301678f9ae0538e446f0438ae3f4', + 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte': + '98935ebb01f950aee5da850758801c28303b042ba219759c4fb04c4974376a76', + 'src/routes/products/[naddr=naddr]/edit/+page.svelte': + '5c50dc2ba4c5734ffe4bd1c2e406e6699581b374fab3849d5c5a0072d9bad1e6', + 'src/lib/components/ListingEditor.svelte': + 'fed47cd7257ab3fe1878ef5779b74a4a3e01404d93956806477943190ffb2b18', + 'src/lib/publishing/listing-editor.ts': + 'f2f1be3c614c861f50293f33f5bf1d3ae1851f4b4452fb9e2f3a7b8963a1d1f9' + }; + 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 listing editor source'); + } + return true; +} /** @param {string} web */ async function inboxSetupAdmission(web) { const gate = await readOwned(web, 'src/lib/components/AccountGate.svelte'); @@ -770,11 +807,16 @@ export async function auditOutput(webDirectory) { (await inboxSetupAdmission(web)); const hasInboxPresentation = hasInboxSetup && (await inboxPresentationAdmission(web)); - const identityCompilerModule = hasInboxSetup - ? 'public-runtime' - : hasPreferencePublication - ? 'identity-session' - : 'heads'; + const hasListingEditor = hasFullRoutes && (await listingEditorAdmission(web)); + if (hasListingEditor && !(hasListingPublication && hasInboxSetup)) + throw new Error('Invalid owned listing editor runtime authority'); + const identityCompilerModule = hasListingEditor + ? 'view-context' + : hasInboxSetup + ? 'public-runtime' + : hasPreferencePublication + ? 'identity-session' + : 'heads'; // Admit compiler-owned module identities, not arbitrary extensions/copy roots. const names = new Set([ 'entry/app', @@ -828,6 +870,9 @@ export async function auditOutput(webDirectory) { ? ['InboxStatus', 'InboxSetup', 'read'] : ['InboxStatus', 'InboxSetup', 'read', 'resolve-head']) names.add(name); + if (hasListingEditor) + for (const name of ['ListingEditor', 'view-context', 'public-runtime']) + names.add(name); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); for (const [key, record] of Object.entries(manifest)) { @@ -972,11 +1017,13 @@ export async function auditOutput(webDirectory) { throw new Error('Invalid owned SDK compiler identity'); equal( sdk.imports, - hasInboxSetup - ? [dist[0]] - : hasPublicRuntime === 'public_identity' - ? [requiredRecord(identityCompilerModule)[0], dist[0]] - : [dist[0]], + hasListingEditor + ? [requiredRecord('view-context')[0], dist[0]] + : hasInboxSetup + ? [dist[0]] + : hasPublicRuntime === 'public_identity' + ? [requiredRecord(identityCompilerModule)[0], dist[0]] + : [dist[0]], 'Invalid owned SDK compiler dependency' ); equal( @@ -1006,7 +1053,13 @@ export async function auditOutput(webDirectory) { equal( dist[1].imports, (hasInboxSetup - ? ['public-key', 'preload-helper', 'private-handles', 'Button'] + ? [ + 'public-key', + 'preload-helper', + 'private-handles', + ...(hasListingEditor ? ['view-context'] : []), + 'Button' + ] : hasPublicRuntime === 'public_identity' ? [ 'public-key', @@ -1080,9 +1133,11 @@ export async function auditOutput(webDirectory) { ], [ identityCompilerModule, - hasInboxSetup - ? ['public-key', 'preload-helper', 'private-handles', 'Button'] - : ['public-key', 'Button'] + hasListingEditor + ? ['public-key', 'private-handles', 'Button'] + : hasInboxSetup + ? ['public-key', 'preload-helper', 'private-handles', 'Button'] + : ['public-key', 'Button'] ], ...(hasInboxSetup ? [/** @type {[string, string[]]} */ (['private-handles', []])] @@ -1130,7 +1185,7 @@ export async function auditOutput(webDirectory) { gate.imports, (hasListingPublication ? [ - 'public-runtime', + hasListingEditor ? 'view-context' : 'public-runtime', 'client', identityViewCompilerModule, 'InboxSetup' @@ -1194,6 +1249,7 @@ export async function auditOutput(webDirectory) { [ 'InboxStatus', [ + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'client', 'Button', @@ -1203,13 +1259,22 @@ export async function auditOutput(webDirectory) { 'inbox-view' ] ], - ['InboxSetup', ['public-runtime', 'client', 'Button']], - ['read', ['public-runtime']], + [ + 'InboxSetup', + [ + ...(hasListingEditor ? ['view-context'] : []), + 'public-runtime', + 'client', + 'Button' + ] + ], + ['read', [hasListingEditor ? 'view-context' : 'public-runtime']], ['nodes/4', ['client', 'AccountGate', 'InboxStatus']], [ 'nodes/5', [ 'public-key', + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'references', 'client', @@ -1228,6 +1293,7 @@ export async function auditOutput(webDirectory) { [ 'public-key', 'private-handles', + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'references', 'Button', @@ -1238,6 +1304,7 @@ export async function auditOutput(webDirectory) { 'MessageComposer', [ 'private-handles', + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'references', 'client', @@ -1251,6 +1318,7 @@ export async function auditOutput(webDirectory) { 'nodes/0', [ 'public-key', + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'client', 'Button', @@ -1546,7 +1614,13 @@ export async function auditOutput(webDirectory) { equal( publisher.imports, (hasProductRequest - ? ['public-key', 'public-runtime', 'Button', 'read'] + ? [ + 'public-key', + ...(hasListingEditor ? ['view-context'] : []), + 'public-runtime', + 'Button', + 'read' + ] : hasInboxSetup ? [ 'public-key', @@ -1565,6 +1639,7 @@ export async function auditOutput(webDirectory) { (hasProductRequest ? [ 'public-key', + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'references', 'client', @@ -1622,6 +1697,7 @@ export async function auditOutput(webDirectory) { entry('nodes/9')[1].imports?.toSorted(), (hasProductRequest ? [ + ...(hasListingEditor ? ['view-context'] : []), 'public-runtime', 'references', 'client', @@ -1683,6 +1759,411 @@ export async function auditOutput(webDirectory) { ) throw new Error('Invalid owned product compiler dynamic imports'); } + if (hasListingEditor) { + // Complete measured HCP115 compiler graph, including roles and ordered + // edges for all existing consumers. Only actual compiler hashes vary. + /** @type {Record<string, unknown>} */ + const expected = { + 'entry/app': { + file: '_app/immutable/entry/app.HASH.js', + name: 'entry/app', + src: '.svelte-kit/generated/build/client-optimized/app.js', + isEntry: true, + imports: [ + 'preload-helper', + 'shared-errors', + 'private-handles', + 'references' + ], + dynamicImports: [ + 'nodes/0', + 'nodes/1', + 'nodes/2', + 'nodes/3', + 'nodes/4', + 'nodes/5', + 'nodes/6', + 'nodes/7', + 'nodes/8', + 'nodes/9', + 'nodes/10', + 'nodes/11', + 'nodes/12', + 'error-template' + ] + }, + 'nodes/0': { + file: '_app/immutable/nodes/0.HASH.js', + name: 'nodes/0', + src: '.svelte-kit/generated/build/client-optimized/nodes/0.js', + isEntry: true, + imports: [ + 'public-key', + 'view-context', + 'public-runtime', + 'client', + 'Button', + 'client.svelte', + 'state', + 'CapabilityGate', + 'Disclosure' + ], + css: ['_app/immutable/assets/0.HASH.css'] + }, + 'nodes/1': { + file: '_app/immutable/nodes/1.HASH.js', + name: 'nodes/1', + src: '.svelte-kit/generated/build/client-optimized/nodes/1.js', + isEntry: true, + imports: ['client', 'client.svelte', 'state', 'legacy'] + }, + 'nodes/10': { + file: '_app/immutable/nodes/10.HASH.js', + name: 'nodes/10', + src: '.svelte-kit/generated/build/client-optimized/nodes/10.js', + isEntry: true, + imports: ['client', 'legacy', 'ListingEditor'] + }, + 'nodes/11': { + file: '_app/immutable/nodes/11.HASH.js', + name: 'nodes/11', + src: '.svelte-kit/generated/build/client-optimized/nodes/11.js', + isEntry: true, + imports: ['client', 'legacy', 'AccountGate'] + }, + 'nodes/12': { + file: '_app/immutable/nodes/12.HASH.js', + name: 'nodes/12', + src: '.svelte-kit/generated/build/client-optimized/nodes/12.js', + isEntry: true, + imports: [ + 'public-key', + 'client', + 'client.svelte', + 'state', + 'ListingEditor' + ] + }, + 'nodes/2': { + file: '_app/immutable/nodes/2.HASH.js', + name: 'nodes/2', + src: '.svelte-kit/generated/build/client-optimized/nodes/2.js', + isEntry: true, + imports: ['client', 'Button', 'routes'] + }, + 'nodes/3': { + file: '_app/immutable/nodes/3.HASH.js', + name: 'nodes/3', + src: '.svelte-kit/generated/build/client-optimized/nodes/3.js', + isEntry: true, + imports: ['client', 'legacy'] + }, + 'nodes/4': { + file: '_app/immutable/nodes/4.HASH.js', + name: 'nodes/4', + src: '.svelte-kit/generated/build/client-optimized/nodes/4.js', + isEntry: true, + imports: ['client', 'AccountGate', 'InboxStatus'] + }, + 'nodes/5': { + file: '_app/immutable/nodes/5.HASH.js', + name: 'nodes/5', + src: '.svelte-kit/generated/build/client-optimized/nodes/5.js', + isEntry: true, + imports: [ + 'public-key', + 'view-context', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'state', + 'legacy', + 'inbox-view', + 'InboxStatus', + 'publishers', + 'MessageComposer' + ] + }, + 'nodes/6': { + file: '_app/immutable/nodes/6.HASH.js', + name: 'nodes/6', + src: '.svelte-kit/generated/build/client-optimized/nodes/6.js', + isEntry: true, + imports: ['client', 'legacy'] + }, + 'nodes/7': { + file: '_app/immutable/nodes/7.HASH.js', + name: 'nodes/7', + src: '.svelte-kit/generated/build/client-optimized/nodes/7.js', + isEntry: true, + imports: [ + 'public-key', + 'view-context', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'state', + 'CapabilityGate', + 'Disclosure', + 'InboxSetup', + 'MessageComposer' + ] + }, + 'nodes/8': { + file: '_app/immutable/nodes/8.HASH.js', + name: 'nodes/8', + src: '.svelte-kit/generated/build/client-optimized/nodes/8.js', + isEntry: true, + imports: [ + 'public-key', + 'client', + 'client.svelte', + 'state', + 'ListingEditor' + ] + }, + 'nodes/9': { + file: '_app/immutable/nodes/9.HASH.js', + name: 'nodes/9', + src: '.svelte-kit/generated/build/client-optimized/nodes/9.js', + isEntry: true, + imports: [ + 'view-context', + 'public-runtime', + 'references', + 'client', + 'Button', + 'client.svelte', + 'navigation', + 'state', + 'Disclosure', + 'routes', + 'publishers' + ] + }, + 'error-template': { + file: '_app/immutable/chunks/HASH.js', + name: 'error-template', + src: '.svelte-kit/generated/build/shared/error-template.js', + isDynamicEntry: true + }, + 'inbox-view': { + file: '_app/immutable/chunks/HASH.js', + name: 'inbox-view', + imports: [ + 'public-key', + 'private-handles', + 'view-context', + 'public-runtime', + 'references', + 'Button', + 'read' + ] + }, + 'private-handles': { + file: '_app/immutable/chunks/HASH.js', + name: 'private-handles' + }, + routes: { + file: '_app/immutable/chunks/HASH.js', + name: 'routes', + imports: ['references', 'client', 'Button'] + }, + InboxSetup: { + file: '_app/immutable/chunks/HASH.js', + name: 'InboxSetup', + imports: ['view-context', 'public-runtime', 'client', 'Button'] + }, + 'preload-helper': { + file: '_app/immutable/chunks/HASH.js', + name: 'preload-helper' + }, + Disclosure: { + file: '_app/immutable/chunks/HASH.js', + name: 'Disclosure', + imports: ['client'] + }, + AccountGate: { + file: '_app/immutable/chunks/HASH.js', + name: 'AccountGate', + imports: ['view-context', 'client', 'CapabilityGate', 'InboxSetup'] + }, + publishers: { + file: '_app/immutable/chunks/HASH.js', + name: 'publishers', + imports: [ + 'public-key', + 'view-context', + 'public-runtime', + 'Button', + 'read' + ] + }, + InboxStatus: { + file: '_app/immutable/chunks/HASH.js', + name: 'InboxStatus', + imports: [ + 'view-context', + 'public-runtime', + 'client', + 'Button', + 'navigation', + 'CapabilityGate', + 'InboxSetup', + 'inbox-view' + ] + }, + Button: { + file: '_app/immutable/chunks/HASH.js', + name: 'Button', + imports: ['client'] + }, + references: { + file: '_app/immutable/chunks/HASH.js', + name: 'references', + imports: ['public-key'] + }, + client: { + file: '_app/immutable/chunks/HASH.js', + name: 'client' + }, + legacy: { + file: '_app/immutable/chunks/HASH.js', + name: 'legacy', + imports: ['client'] + }, + ListingEditor: { + file: '_app/immutable/chunks/HASH.js', + name: 'ListingEditor', + imports: [ + 'private-handles', + 'view-context', + 'references', + 'client', + 'Button', + 'CapabilityGate', + 'read' + ] + }, + 'public-key': { + file: '_app/immutable/chunks/HASH.js', + name: 'public-key' + }, + navigation: { + file: '_app/immutable/chunks/HASH.js', + name: 'navigation', + imports: ['entry/payload', 'shared-errors', 'client', 'client.svelte'] + }, + 'public-runtime': { + file: '_app/immutable/chunks/HASH.js', + name: 'public-runtime', + imports: [ + 'public-key', + 'preload-helper', + 'private-handles', + 'view-context', + 'Button' + ], + dynamicImports: ['negentropy'] + }, + 'shared-errors': { + file: '_app/immutable/chunks/HASH.js', + name: 'shared-errors' + }, + 'client.svelte': { + file: '_app/immutable/chunks/HASH.js', + name: 'client.svelte', + imports: ['entry/payload', 'shared-errors', 'client'] + }, + MessageComposer: { + file: '_app/immutable/chunks/HASH.js', + name: 'MessageComposer', + imports: [ + 'private-handles', + 'view-context', + 'public-runtime', + 'references', + 'client', + 'Button', + 'navigation', + 'inbox-view', + 'publishers' + ] + }, + 'view-context': { + file: '_app/immutable/chunks/HASH.js', + name: 'view-context', + imports: ['public-key', 'private-handles', 'Button'] + }, + CapabilityGate: { + file: '_app/immutable/chunks/HASH.js', + name: 'CapabilityGate', + imports: ['client', 'Button'] + }, + read: { + file: '_app/immutable/chunks/HASH.js', + name: 'read', + imports: ['view-context'] + }, + state: { + file: '_app/immutable/chunks/HASH.js', + name: 'state', + imports: ['client.svelte'] + }, + 'client-entry': { + file: '_app/immutable/chunks/HASH.js', + name: 'client-entry', + src: 'node_modules/.pnpm/@sveltejs+kit@3.0.0_@opentelemetry+api@1.9.1_@sveltejs+vite-plugin-svelte@7.3.1_svelte@_6edc02734bfa45cbf85e92e62b52fb36/node_modules/@sveltejs/kit/src/runtime/client/client-entry.js', + isDynamicEntry: true, + imports: ['navigation'] + }, + 'entry/start': { + file: '_app/immutable/entry/start.HASH.js', + name: 'entry/start', + src: 'node_modules/.pnpm/@sveltejs+kit@3.0.0_@opentelemetry+api@1.9.1_@sveltejs+vite-plugin-svelte@7.3.1_svelte@_6edc02734bfa45cbf85e92e62b52fb36/node_modules/@sveltejs/kit/src/runtime/client/entry.js', + isEntry: true, + imports: ['entry/payload', 'preload-helper'], + dynamicImports: ['client-entry'] + }, + 'entry/payload': { + file: '_app/immutable/entry/payload.HASH.js', + name: 'entry/payload', + src: 'node_modules/.pnpm/@sveltejs+kit@3.0.0_@opentelemetry+api@1.9.1_@sveltejs+vite-plugin-svelte@7.3.1_svelte@_6edc02734bfa45cbf85e92e62b52fb36/node_modules/@sveltejs/kit/src/runtime/client/payload.js', + isEntry: true + }, + negentropy: { + file: '_app/immutable/chunks/HASH.js', + name: 'negentropy', + src: 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js', + isDynamicEntry: true, + imports: ['view-context', 'public-runtime'] + } + }; + for (const record of Object.values(manifest)) { + const actual = { ...record }; + actual.file = actual.file.includes('/chunks/') + ? actual.file.replace(/(?<=\/chunks\/)[A-Za-z0-9_-]+(?=\.js$)/, 'HASH') + : actual.file.replace(/\.[A-Za-z0-9_-]+\.js$/, '.HASH.js'); + for (const field of ['imports', 'dynamicImports']) + if (actual[field] !== undefined) + actual[field] = actual[field].map( + (/** @type {string} */ key) => manifest[key].name + ); + if (actual.css !== undefined) + actual.css = actual.css.map((/** @type {string} */ file) => + file.replace(/\.[A-Za-z0-9_-]+\.css$/, '.HASH.css') + ); + equal( + actual, + expected[record.name], + 'Invalid owned listing editor compiler graph' + ); + } + } if (hasFullRoutes) { const robots = await readOwned(web, 'static/robots.txt'); publicText(robots);