commit 9dd0a55c3d1fe63bb9fb4b35414f9967fe0c5f50
parent e2ed160a423dfb35d398a8524a2bb27403dc911a
Author: triesap <tyson@radroots.org>
Date: Sat, 10 Oct 2026 16:27:52 +0000
publishing: publish owned revisions and sold status (HCP-119)
- Preserve original coordinate and publication time in reviewed updates.
- Confirm sold availability through the existing durable publisher.
- Fence competing native captures and retain original owner custody.
- Verify exact source, browser, output and dependency evidence.
Diffstat:
19 files changed, 1984 insertions(+), 105 deletions(-)
diff --git a/web/src/lib/components/ConfirmPanel.svelte b/web/src/lib/components/ConfirmPanel.svelte
@@ -0,0 +1,26 @@
+<script lang="ts">
+ let {
+ title,
+ text,
+ confirmLabel,
+ onconfirm,
+ oncancel
+ }: {
+ title: string;
+ text: string;
+ confirmLabel: string;
+ onconfirm: () => void;
+ oncancel: () => void;
+ } = $props();
+</script>
+
+<section class="stack" aria-label={title}>
+ <h2>{title}</h2>
+ <p>{text}</p>
+ <div class="cluster">
+ <button type="button" class="button button--primary" onclick={onconfirm}
+ >{confirmLabel}</button
+ >
+ <button type="button" onclick={oncancel}>Keep editing</button>
+ </div>
+</section>
diff --git a/web/src/lib/components/ListingEditor.svelte b/web/src/lib/components/ListingEditor.svelte
@@ -3,6 +3,7 @@
import { getContext, onMount, tick } from 'svelte';
import ListingReview from './ListingReview.svelte';
import ConflictNotice from './ConflictNotice.svelte';
+ import ConfirmPanel from './ConfirmPanel.svelte';
import InboxSetup from './InboxSetup.svelte';
import {
PUBLIC_RUNTIME_CONTEXT,
@@ -21,9 +22,12 @@
openEditorReview,
editorReviewSnapshot,
closeEditorReview,
+ publishEditorRevision,
+ editorPublicationOperation,
type EditorReview,
type EditorFormError
} from '../publishing/editor-workflow.ts';
+ import type { ListingOperationView } from '../publishing/listing-operation-view.ts';
import CapabilityGate from './CapabilityGate.svelte';
import Notice from './Notice.svelte';
import OperationStatus from './OperationStatus.svelte';
@@ -71,6 +75,9 @@
let setupState = $state(inboxSetupViewSnapshot(undefined));
let review = $state.raw<EditorReview | undefined>(),
reviewBusy = $state(false);
+ let soldConfirm = $state(false),
+ publishBusy = $state(false);
+ let publicationOperation = $state.raw<ListingOperationView | undefined>();
let errors = $state<readonly EditorFormError[]>([]),
reviewMessage = $state('');
let identity = $state(identityViewSnapshot(context)),
@@ -112,6 +119,9 @@
identity.identity.publicKey === snapshot.owner &&
listingEditorSnapshot(editor)
);
+ const editable = $derived(
+ !!(visible && visible.editable && !publicationOperation && !publishBusy)
+ );
onMount(() => {
mounted = true;
const off = subscribeIdentityView(context, (next) => {
@@ -154,7 +164,13 @@
};
});
const visibleReview = $derived.by(() => {
- if (!setupState.owner || !snapshot || !visible || !review) return;
+ if (
+ (!setupState.owner && route.mode !== 'edit') ||
+ !snapshot ||
+ !visible ||
+ !review
+ )
+ return;
return editorReviewSnapshot(review) ? review : undefined;
});
$effect(() => {
@@ -181,6 +197,8 @@
editor = undefined;
snapshot = undefined;
review = undefined;
+ publicationOperation = undefined;
+ soldConfirm = false;
errors = [];
reviewMessage = '';
form = blankForm();
@@ -244,6 +262,7 @@
cancellation.abort();
off();
if (owned) closeListingEditor(owned);
+ if (editor === owned && review) closeEditorReview(review);
form = blankForm();
};
});
@@ -253,22 +272,30 @@
if (review) closeEditorReview(review);
review = undefined;
errors = [];
+ soldConfirm = false;
void editListingEditor(original, { ...form });
}
- async function showReview() {
+ async function showReview(status: 'active' | 'sold' = 'active') {
const original = editor,
resource = route,
author = admittedAuthor;
if (
reviewBusy ||
closeBusy ||
+ publishBusy ||
+ publicationOperation ||
!original ||
!listingEditorSnapshot(original)?.editable
)
return;
reviewBusy = true;
try {
- const result = await openEditorReview(original, setup, { ...form });
+ const result = await openEditorReview(
+ original,
+ setup,
+ { ...form },
+ status
+ );
if (
!mounted ||
editor !== original ||
@@ -306,6 +333,38 @@
if (mounted && editor && listingEditorSnapshot(editor)?.editable)
document.querySelector<HTMLInputElement>('#listing-title')?.focus();
}
+ async function publishChanges() {
+ const original = review,
+ resource = route,
+ author = admittedAuthor;
+ if (
+ !original ||
+ publishBusy ||
+ publicationOperation ||
+ route.mode !== 'edit'
+ )
+ return;
+ publishBusy = true;
+ try {
+ const result = await publishEditorRevision(
+ original,
+ 'publish_reviewed_revision'
+ );
+ if (
+ !mounted ||
+ review !== original ||
+ route !== resource ||
+ admittedAuthor !== author
+ )
+ return;
+ publicationOperation = editorPublicationOperation(original);
+ if (result.status !== 'completed')
+ reviewMessage =
+ 'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.';
+ } finally {
+ publishBusy = false;
+ }
+ }
function fieldError(field: keyof PublicDraftForm) {
return errors.find((value) => value.field === field);
}
@@ -326,7 +385,13 @@
const original = editor,
resource = route,
author = admittedAuthor;
- if (closeBusy || !original || !listingEditorSnapshot(original)?.editable)
+ if (
+ closeBusy ||
+ publishBusy ||
+ publicationOperation ||
+ !original ||
+ !listingEditorSnapshot(original)?.editable
+ )
return;
closeBusy = true;
try {
@@ -399,12 +464,12 @@
source={listingEditorEditSource(editor)!}
proposed={form}
/>
- {#if visible.editable}<Notice
+ {#if editable}<Notice
tone="info"
- text="These changes can be saved locally. Publishing changes is not available."
+ text="Changes stay local until you review and publish them."
/>{/if}
{/if}
- {#if !visible.editable}<Notice
+ {#if !editable}<Notice
tone="info"
text={route.mode === 'draft'
? 'This draft has a retained listing operation. Keep its original outcome for reconciliation.'
@@ -412,11 +477,30 @@
/>{:else}<p>
Changes are saved in this browser. Browser storage is not a backup.
</p>{/if}
+ {#if reviewMessage}<Notice tone="warning" text={reviewMessage} />{/if}
+ {#if soldConfirm && editable}<ConfirmPanel
+ title="Confirm sold update"
+ text="Marking this listing as sold is a public availability update, not a payment or stock reservation receipt. Review the exact update before publishing."
+ confirmLabel="Review sold update"
+ onconfirm={() => {
+ soldConfirm = false;
+ void showReview('sold');
+ }}
+ oncancel={() => {
+ soldConfirm = false;
+ }}
+ />{/if}
{#if visibleReview}<ListingReview
review={visibleReview}
onedit={editDetails}
+ onpublish={route.mode === 'edit'
+ ? () => {
+ void publishChanges();
+ }
+ : undefined}
+ publishing={publishBusy}
+ captured={!!publicationOperation}
/>{:else}
- {#if reviewMessage}<Notice tone="warning" text={reviewMessage} />{/if}
{#if errors.length}<div
id="listing-review-errors"
tabindex="-1"
@@ -449,7 +533,7 @@
form = { ...form, title: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}
+ readonly={!editable}
/>
{#if fieldError('title')}<p id="listing-title-error">
{fieldError('title')?.message}
@@ -469,7 +553,7 @@
form = { ...form, description: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}></textarea>
+ readonly={!editable}></textarea>
{#if fieldError('description')}<p id="listing-description-error">
{fieldError('description')?.message}
</p>{/if}
@@ -492,7 +576,7 @@
form = { ...form, location: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}
+ readonly={!editable}
/>
{#if fieldError('location')}<p id="listing-location-error">
{fieldError('location')?.message}
@@ -513,7 +597,7 @@
form = { ...form, amount: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}
+ readonly={!editable}
/>
{#if fieldError('amount')}<p id="listing-amount-error">
{fieldError('amount')?.message}
@@ -533,7 +617,7 @@
form = { ...form, currency: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}
+ readonly={!editable}
/>
{#if fieldError('currency')}<p id="listing-currency-error">
{fieldError('currency')?.message}
@@ -551,7 +635,7 @@
form = { ...form, unit: event.currentTarget.value };
changed();
}}
- disabled={!visible.editable}
+ disabled={!editable}
><option value="">Choose a unit</option
>{#each foodUnits as unit (unit)}<option value={unit}
>{unit}</option
@@ -583,7 +667,7 @@
form = { ...form, quantity: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}
+ readonly={!editable}
/>
{#if fieldError('quantity')}<p id="listing-quantity-error">
{fieldError('quantity')?.message}
@@ -615,7 +699,7 @@
changed();
}
}}
- disabled={!visible.editable}
+ disabled={!editable}
><option value="">No public contact</option><option
value="email">Email</option
><option value="phone">Phone</option><option value="https"
@@ -641,7 +725,7 @@
form = { ...form, contactValue: event.currentTarget.value };
changed();
}}
- readonly={!visible.editable}
+ readonly={!editable}
/>
{#if fieldError('contactValue')}<p
id="listing-contact-value-error"
@@ -652,21 +736,40 @@
</div>
</details>
</form>
- {#if visible.editable && route.mode !== 'edit'}<button
+ {#if editable}<button
type="button"
- onclick={showReview}
+ onclick={() => {
+ void showReview();
+ }}
disabled={reviewBusy || closeBusy}
- >{reviewBusy ? 'Preparing review' : 'Review listing'}</button
+ >{reviewBusy
+ ? 'Preparing review'
+ : route.mode === 'edit'
+ ? 'Review changes'
+ : 'Review listing'}</button
>{/if}
{/if}
- {#if visible.editable && route.mode !== 'edit' && setup}<InboxSetup
+ {#if editable && route.mode === 'edit' && !visibleReview}<details>
+ <summary>Other listing actions</summary>
+ <button
+ type="button"
+ onclick={() => {
+ soldConfirm = true;
+ }}
+ disabled={reviewBusy || closeBusy}>Mark as sold</button
+ >
+ </details>{/if}
+ {#if publicationOperation}<OperationStatus
+ publicOperation={publicationOperation}
+ />{/if}
+ {#if editable && route.mode !== 'edit' && setup}<InboxSetup
controller={setup}
inline
/>{/if}
{#each visible.operations as operation (operation)}<OperationStatus
publicOperation={operation}
/>{/each}
- {#if visible.editable}<button
+ {#if editable}<button
type="button"
onclick={saveClose}
disabled={closeBusy || reviewBusy}>Save and close</button
@@ -675,7 +778,7 @@
tone="warning"
text="Navigation did not complete. Your saved local data remains in this browser."
/>{/if}
- {#if visible.editable}<p role="status">
+ {#if editable}<p role="status">
{visible.state === 'saved'
? 'Saved in this browser.'
: visible.state === 'saving'
diff --git a/web/src/lib/components/ListingReview.svelte b/web/src/lib/components/ListingReview.svelte
@@ -4,8 +4,19 @@
editorReviewSnapshot,
type EditorReview
} from '../publishing/editor-workflow.ts';
- let { review, onedit }: { review: EditorReview; onedit: () => void } =
- $props();
+ let {
+ review,
+ onedit,
+ onpublish,
+ publishing = false,
+ captured = false
+ }: {
+ review: EditorReview;
+ onedit: () => void;
+ onpublish?: () => void;
+ publishing?: boolean;
+ captured?: boolean;
+ } = $props();
const preview = $derived(editorReviewSnapshot(review));
function tag(name: string) {
return (
@@ -34,6 +45,14 @@
<dd>{tag('radroots:quantity')}</dd>{/if}
<dt>Publisher</dt>
<dd class="key">{preview.owner}</dd>
+ {#if preview.revision}
+ <dt>Unchanged listing coordinate</dt>
+ <dd class="key">{preview.revision.coordinate}</dd>
+ <dt>Original publication time</dt>
+ <dd>{preview.revision.publishedAtSeconds}</dd>
+ <dt>Proposed availability</dt>
+ <dd>{preview.revision.status === 'sold' ? 'Sold' : 'Available'}</dd>
+ {/if}
<dt>Public destinations</dt>
<dd>
<ul>
@@ -43,9 +62,30 @@
</ul>
</dd>
</dl>
- <p>Messages: ready to receive replies</p>
- <p>This review has not requested a signature or published the listing.</p>
- <button type="button" onclick={onedit}>Edit details</button>
+ {#if !preview.revision}<p>Messages: ready to receive replies</p>{/if}
+ {#if !captured && !publishing}<p>
+ This review has not requested a signature or published the listing.
+ </p>{/if}
+ {#if preview.revision?.status === 'sold'}<p>
+ This is a public availability update, not a payment or stock reservation
+ receipt.
+ </p>{/if}
+ {#if preview.revision && onpublish && !captured}
+ <button
+ type="button"
+ class="button button--primary"
+ onclick={onpublish}
+ disabled={publishing}
+ >{publishing
+ ? 'Publishing update'
+ : preview.revision.status === 'sold'
+ ? 'Publish sold update'
+ : 'Publish changes'}</button
+ >
+ {/if}
+ <button type="button" onclick={onedit} disabled={publishing || captured}
+ >Edit details</button
+ >
</section>
{:else}
<Notice
diff --git a/web/src/lib/nostr/listing-publisher.ts b/web/src/lib/nostr/listing-publisher.ts
@@ -198,13 +198,18 @@ export async function withListingDeliveryOwnership<T>(
if (!lock) return { status: 'busy' };
if (!(await recheckDeliveryOwner(original.identity, retry?.signal)))
return { status: 'stopped' };
- const identity = identityMessagingOwnership(original.identity),
- operation =
+ const operation =
signed &&
identityPublicOperationOwnership(
original.identity,
signed.operation
- );
+ ),
+ // A signed public update retains its original public operation.
+ // New-listing inbox readiness stays in original.current(); edits
+ // do not require a messaging probe. Resumptions keep their gate.
+ identity = signed
+ ? operation
+ : identityMessagingOwnership(original.identity);
if (
!identity ||
(signed && !operation) ||
diff --git a/web/src/lib/persistence/public-publications.ts b/web/src/lib/persistence/public-publications.ts
@@ -160,7 +160,8 @@ export async function savePublicListingIntent(
expected: PublicDraftRecord,
editVersion: number,
command: string,
- current: (this: void) => boolean
+ current: (this: void) => boolean,
+ revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>
): Promise<PublicListingSave> {
try {
const scope = scopeOf(repository),
@@ -195,6 +196,7 @@ export async function savePublicListingIntent(
{
expected,
current: fresh,
+ ...(revisionBase ? { revisionBase } : {}),
draftCurrent: () =>
custody.current(JSON.stringify(expected), editVersion)
}
diff --git a/web/src/lib/persistence/quota.ts b/web/src/lib/persistence/quota.ts
@@ -29,6 +29,7 @@ import {
type PublicOperationTransition
} from './artifact-records.ts';
import { decideFrozenTransition } from './operation-transactions.ts';
+import { inspectLocalTemplate } from '../nostr/local-template.ts';
declare const repositoryBrand: unique symbol;
declare const inventoryBrand: unique symbol;
@@ -294,6 +295,7 @@ type DraftAdmission = Readonly<{
expected: PublicDraftRecord;
current(this: void): boolean;
draftCurrent(this: void): boolean;
+ revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>;
}>;
// Storage-only atomic draft/CAS reservation. Current original account/review
// ownership is supplied by the public listing command owner, never a UI flag.
@@ -370,6 +372,66 @@ function claimOperation(
return { ok: true, value: { state: 'existing', record: decoded.value } };
}
if (draft) {
+ if (draft.revisionBase) {
+ const revisionBase = draft.revisionBase;
+ const witness = publicRecordSnapshot(
+ revisionBase.record,
+ scope.owner,
+ revisionBase.command
+ );
+ const base = rows.find(
+ (row) =>
+ row.record.family === 'public_operation' &&
+ row.record.id === revisionBase.command
+ )?.record;
+ const oldTemplate =
+ witness?.family === 'public_operation' &&
+ inspectLocalTemplate(witness.capture.wire, scope.owner, 30402);
+ const nextTemplate =
+ record.family === 'public_operation' &&
+ inspectLocalTemplate(record.capture.wire, scope.owner, 30402);
+ const tag = (
+ template: NonNullable<ReturnType<typeof inspectLocalTemplate>>,
+ key: string
+ ) => template.tags.find((value) => value[0] === key)?.[1];
+ if (
+ !witness ||
+ witness.family !== 'public_operation' ||
+ !witness.artifact ||
+ !base ||
+ base.family !== 'public_operation' ||
+ !oldTemplate ||
+ !nextTemplate ||
+ JSON.stringify(base.source) !== JSON.stringify(witness.source) ||
+ JSON.stringify(base.capture) !== JSON.stringify(witness.capture) ||
+ JSON.stringify(base.artifact) !== JSON.stringify(witness.artifact) ||
+ tag(oldTemplate, 'd') !== tag(nextTemplate, 'd') ||
+ tag(oldTemplate, 'published_at') !==
+ tag(nextTemplate, 'published_at') ||
+ nextTemplate.created_at <= oldTemplate.created_at ||
+ rows.some((row) => {
+ if (
+ row.record.family !== 'public_operation' ||
+ row.record.id === base.id ||
+ row.record.capture.kind !== 30402
+ )
+ return false;
+ const other = inspectLocalTemplate(
+ row.record.capture.wire,
+ scope.owner,
+ 30402
+ );
+ return (
+ !!other &&
+ tag(other, 'd') === tag(oldTemplate, 'd') &&
+ other.created_at >= oldTemplate.created_at
+ );
+ })
+ ) {
+ refuse('conflict');
+ return;
+ }
+ }
const source =
record.family === 'public_operation' ? record.source : undefined;
const previousDraft = rows.find(
diff --git a/web/src/lib/publishing/edit-source.ts b/web/src/lib/publishing/edit-source.ts
@@ -21,7 +21,10 @@ import {
inspectPublicStorage,
publicInventorySnapshot
} from '../persistence/quota.ts';
-import { publicRecordSnapshot } from '../persistence/records.ts';
+import {
+ publicRecordSnapshot,
+ type PublicRecordHandle
+} from '../persistence/records.ts';
import { readPublicDraft } from '../persistence/drafts.ts';
import {
identityViewSession,
@@ -36,6 +39,7 @@ import {
publicViewOwnsRun,
publicViewRunCurrent,
publicViewProjectionAvailable,
+ publicRuntimePolicy,
type PublicRuntime,
type PublicView
} from '../runtime/public-runtime.ts';
@@ -46,7 +50,14 @@ import {
closeHeadResolver,
type HeadResolver
} from '../catalog/resolve-head.ts';
-import { createPublicHeadCandidate, publicHeadKey } from '../catalog/heads.ts';
+import {
+ createPublicHeadCandidate,
+ publicHeadKey,
+ publicHeadSnapshot,
+ selectPublicHead
+} from '../catalog/heads.ts';
+import type { RelayPolicy } from '../config/relays.ts';
+import type { IdentitySession } from '../runtime/identity-session.ts';
declare const sourceBrand: unique symbol;
export type OwnedEditSource = Readonly<{ [sourceBrand]: true }>;
@@ -72,7 +83,11 @@ type Source = {
coordinate: string;
baseWire: string;
sourceCommand: string;
+ sourceRecord: PublicRecordHandle;
publishedAtSeconds: number;
+ identity: IdentitySession;
+ policy: RelayPolicy;
+ currentRevision(eventId: string): boolean;
current(): boolean;
}>
| undefined;
@@ -125,7 +140,11 @@ export async function openOwnedEditSource(
identityViewSession(context) === session &&
identityViewMatchesOwner(context, owner) &&
publicPublicationOwner(repository) === owner;
- off = subscribeIdentityInvalidation(session, close);
+ off = subscribeIdentityInvalidation(session, () => {
+ // A delivery recheck also notifies after observing the unchanged owner.
+ // Only loss of this original mounted owner closes its source custody.
+ if (!current()) close();
+ });
signal?.addEventListener('abort', close, { once: true });
const inspected = await inspectPublicStorage(quota);
if (!current() || !inspected.ok) {
@@ -144,8 +163,10 @@ export async function openOwnedEditSource(
command: string;
publishedAt: number;
eventId: string;
+ record: PublicRecordHandle;
}>
| undefined;
+ let captures = Array.from<{ hash: string; createdAt: number }>([]);
for (const item of inventory.rows) {
if (item.family !== 'public_operation') continue;
const read = await readPublicListingIntent(repository, item.id);
@@ -157,16 +178,15 @@ export async function openOwnedEditSource(
read.status === 'found' &&
publicRecordSnapshot(read.record, owner, item.id);
// Incomplete critical storage is not an absence that permits adoption.
- if (!row || row.family !== 'public_operation') {
+ if (
+ read.status !== 'found' ||
+ !row ||
+ row.family !== 'public_operation'
+ ) {
close();
return;
}
- if (
- row.capture.kind !== 30402 ||
- !row.artifact ||
- row.source.type !== 'draft'
- )
- continue;
+ if (row.capture.kind !== 30402 || row.source.type !== 'draft') continue;
const template = inspectLocalTemplate(row.capture.wire, owner, 30402),
projected = template && projectFoodParts(template);
if (
@@ -176,6 +196,11 @@ export async function openOwnedEditSource(
projected.projection.identifier !== reference.identifier
)
continue;
+ captures = captures.concat({
+ hash: row.capture.hash,
+ createdAt: template.created_at
+ });
+ if (!row.artifact) continue;
const source = await readPublicDraft(drafts, row.source.id);
if (!current()) {
close();
@@ -221,6 +246,7 @@ export async function openOwnedEditSource(
const verified = verifyEnvelope(row.artifact.wire),
signed = verified.ok && verifiedEnvelopeSnapshot(verified.value);
if (
+ !verified.ok ||
!signed ||
signed.id !== row.artifact.eventId ||
signed.id !== row.capture.hash ||
@@ -234,15 +260,30 @@ export async function openOwnedEditSource(
)
continue;
if (retained) {
- close();
- return;
+ const priorProof = verifyEnvelope(retained.wire);
+ const prior =
+ priorProof.ok && createPublicHeadCandidate(priorProof.value);
+ const next = createPublicHeadCandidate(verified.value);
+ // Supported revisions have strict advancing time and unchanged initial
+ // publication time. Equal-time/duplicate/unrelated captures are ambiguous.
+ if (
+ !prior ||
+ !next ||
+ retained.publishedAt !== food.published_at ||
+ publicHeadSnapshot(prior).created_at === signed.created_at
+ ) {
+ close();
+ return;
+ }
+ if (selectPublicHead(prior, next).head === prior) continue;
}
retained = {
form,
wire: row.artifact.wire,
command: row.id,
publishedAt: food.published_at,
- eventId: signed.id
+ eventId: signed.id,
+ record: read.record
};
}
if (!retained || !current()) {
@@ -252,7 +293,14 @@ export async function openOwnedEditSource(
const base = retained,
proof = verifyEnvelope(base.wire);
const head = proof.ok && createPublicHeadCandidate(proof.value);
- if (!head) {
+ if (
+ !head ||
+ captures.some(
+ (capture) =>
+ capture.hash !== base.eventId &&
+ capture.createdAt >= publicHeadSnapshot(head).created_at
+ )
+ ) {
close();
return;
}
@@ -329,14 +377,54 @@ export async function openOwnedEditSource(
snapshot,
close,
authorize() {
- if (snapshot()?.status !== 'ready') return;
+ const policy = runtime && publicRuntimePolicy(runtime);
+ if (snapshot()?.status !== 'ready' || !policy) return;
return {
repository,
owner,
coordinate: reference.naddr,
baseWire: base.wire,
sourceCommand: base.command,
+ sourceRecord: base.record,
publishedAtSeconds: base.publishedAt,
+ identity: session,
+ policy,
+ currentRevision(eventId: string) {
+ const state = snapshot();
+ if (
+ !current() ||
+ !runtime ||
+ publicRuntimePolicy(runtime) !== policy
+ )
+ return false;
+ if (state?.status === 'ready') return true;
+ // Continuity for the original immutable revision capture only. The
+ // independent resolver must verify its exact new event, both scopes
+ // and focused clock/display state; a competing hash remains fenced.
+ const row =
+ resolver && networkOwned()
+ ? headResolutionSnapshot(resolver).find(
+ (value) => value.key === key
+ )
+ : undefined;
+ return !!(
+ state?.status === 'conflict' &&
+ state.currentEventId === eventId &&
+ row?.state.food &&
+ row.state.display === 'focused_known' &&
+ row.coverage === 'bounded-eose' &&
+ !row.lastKnown &&
+ row.deletion.outcome !== 'suppressed' &&
+ view &&
+ run &&
+ publicViewRunCurrent(view, run) &&
+ [row.headSources, row.deletionSources].every(
+ (scope) =>
+ scope?.state === 'eose' &&
+ scope.result.coverage === 'bounded-eose'
+ )
+ );
+ },
current: () => snapshot()?.status === 'ready'
};
}
diff --git a/web/src/lib/publishing/editor-workflow.ts b/web/src/lib/publishing/editor-workflow.ts
@@ -10,13 +10,33 @@ import type { InboxSetupView } from '../messaging/inbox-setup-view.ts';
import {
reviewListingEditor,
listingEditorReviewCurrent,
+ editListingEditor,
+ listingEditorSnapshot,
type ListingEditor
} from './listing-editor.ts';
import {
listingReviewSnapshot,
+ listingReviewOwnership,
+ reserveNewListing,
type ListingReview,
type ListingPreview
} from './prepare-listing.ts';
+import {
+ beginListingSigning,
+ runListingSigning,
+ stopListingSigning,
+ type ListingSigning
+} from './sign-listing.ts';
+import {
+ deliverListing,
+ type ListingDeliveryResult
+} from './deliver-listing.ts';
+import { getPublicPool } from '../nostr/public-pool.ts';
+import {
+ readListingOperationView,
+ closeListingOperationView,
+ type ListingOperationView
+} from './listing-operation-view.ts';
export type EditorFormError = Readonly<{
field: keyof PublicDraftForm;
@@ -120,14 +140,52 @@ export function validateEditorForm(
}
declare const reviewBrand: unique symbol;
export type EditorReview = Readonly<{ [reviewBrand]: true }>;
-type Owned = Readonly<{ editor: ListingEditor; original: ListingReview }>;
+type Owned = Readonly<{
+ editor: ListingEditor;
+ original: ListingReview;
+ active(): boolean;
+ close(): void;
+ signing(): ListingSigning | undefined;
+ setSigning(value: ListingSigning): void;
+ operation(): ListingOperationView | undefined;
+ setOperation(value: ListingOperationView): void;
+}>;
+function createReviewOwner(
+ editor: ListingEditor,
+ original: ListingReview
+): Owned {
+ let active = true;
+ let signing: ListingSigning | undefined;
+ let operation: ListingOperationView | undefined;
+ return {
+ editor,
+ original,
+ active: () => active,
+ signing: () => signing,
+ setSigning(value) {
+ signing = value;
+ },
+ operation: () => operation,
+ setOperation(value) {
+ if (operation) closeListingOperationView(operation);
+ operation = value;
+ },
+ close() {
+ active = false;
+ if (signing) stopListingSigning(signing);
+ if (operation) closeListingOperationView(operation);
+ }
+ };
+}
const reviews = new WeakMap<EditorReview, Owned>();
+const publishing = new WeakMap<EditorReview, Promise<ListingDeliveryResult>>();
export type EditorReviewSnapshot = ListingPreview &
Readonly<{ content: string; tags: readonly (readonly string[])[] }>;
export async function openEditorReview(
editor: ListingEditor,
setup: InboxSetupView | undefined,
- form: PublicDraftForm
+ form: PublicDraftForm,
+ status: 'active' | 'sold' = 'active'
): Promise<
| Readonly<{ status: 'review'; review: EditorReview }>
| Readonly<{
@@ -143,7 +201,17 @@ export async function openEditorReview(
errors,
message: 'Check the linked fields. Your input remains here.'
};
- const result = await reviewListingEditor(editor, setup, form);
+ if (
+ listingEditorSnapshot(editor)?.mode === 'edit' &&
+ !(await editListingEditor(editor, form))
+ )
+ return {
+ status: 'blocked',
+ errors: [],
+ message:
+ 'Keep your proposed changes. The current listing could not be safely prepared.'
+ };
+ const result = await reviewListingEditor(editor, setup, form, status);
if (
result.status !== 'review' ||
!listingEditorReviewCurrent(editor, result.review)
@@ -157,7 +225,7 @@ export async function openEditorReview(
: 'The saved listing or account changed. Keep your input and review the current values again.'
};
const review = Object.freeze({}) as EditorReview;
- reviews.set(review, { editor, original: result.review });
+ reviews.set(review, createReviewOwner(editor, result.review));
return { status: 'review', review };
}
export function editorReviewSnapshot(
@@ -175,5 +243,93 @@ export function editorReviewSnapshot(
return { ...preview, content: wire.content, tags: wire.tags };
}
export function closeEditorReview(review: EditorReview): void {
+ const owned = reviews.get(review);
+ owned?.close();
reviews.delete(review);
}
+export function editorPublicationOperation(
+ review: EditorReview
+): ListingOperationView | undefined {
+ const owned = reviews.get(review);
+ return owned?.active() ? owned.operation() : undefined;
+}
+// Existing publication pipeline only. One original review deduplicates clicks;
+// explicit consent does not bypass original editor/source/draft/current-head.
+export function publishEditorRevision(
+ review: EditorReview,
+ consent: unknown
+): Promise<ListingDeliveryResult> {
+ const owned = reviews.get(review);
+ const preview = owned && listingReviewSnapshot(owned.original);
+ if (
+ !owned?.active() ||
+ !preview?.revision ||
+ consent !== 'publish_reviewed_revision'
+ )
+ return Promise.resolve({ status: 'invalid' });
+ const pending = publishing.get(review);
+ if (pending) return pending;
+ const job = (async (): Promise<ListingDeliveryResult> => {
+ const original = listingReviewOwnership(owned.original);
+ if (!original || !listingEditorReviewCurrent(owned.editor, owned.original))
+ return { status: 'unavailable' };
+ const current = () =>
+ owned.active() &&
+ reviews.get(review) === owned &&
+ listingEditorReviewCurrent(owned.editor, owned.original);
+ try {
+ const reserved = await reserveNewListing(
+ owned.original,
+ 'publish_reviewed_listing'
+ );
+ if (!current()) return { status: 'stopped' };
+ if (reserved.status !== 'saved' && reserved.status !== 'existing')
+ return {
+ status: reserved.status === 'busy' ? 'busy' : 'storage_failed'
+ };
+ const signing = beginListingSigning(
+ owned.original,
+ 'sign_reviewed_listing'
+ );
+ if (!signing) return { status: 'unavailable' };
+ owned.setSigning(signing);
+ const signed = await runListingSigning(signing, 'sign_reviewed_listing');
+ if (!current()) return { status: 'stopped' };
+ if (signed.status !== 'prepared')
+ return {
+ status:
+ signed.status === 'busy'
+ ? 'busy'
+ : signed.status === 'stopped'
+ ? 'stopped'
+ : 'needs_action'
+ };
+ const pool = getPublicPool(original.readiness.policy);
+ if (!pool || !current()) return { status: 'unavailable' };
+ return await deliverListing(
+ signed.publication,
+ pool,
+ original.readiness.policy,
+ 'publish_stored_listing'
+ );
+ } catch {
+ return { status: 'needs_action' };
+ } finally {
+ const read = await readListingOperationView(
+ original.repository,
+ original.readiness.identity,
+ original.command,
+ owned.signing()
+ );
+ if (read.status === 'found') {
+ if (owned.active() && reviews.get(review) === owned) {
+ owned.setOperation(read.view);
+ } else closeListingOperationView(read.view);
+ }
+ }
+ })().finally(() => {
+ if (publishing.get(review) === job) publishing.delete(review);
+ });
+ publishing.set(review, job);
+ return job;
+}
diff --git a/web/src/lib/publishing/listing-editor.ts b/web/src/lib/publishing/listing-editor.ts
@@ -13,9 +13,12 @@ import {
reviewNewListing,
listingReviewSnapshot,
listingReviewOwnership,
+ closeListingReview,
type ListingReview,
type ListingReviewResult
} from './prepare-listing.ts';
+import { reviewOwnedRevision } from './revise-listing.ts';
+import { reviewMarkSold } from './mark-sold.ts';
import { decodeProductReference } from '../nostr/references.ts';
import {
openOwnedEditSource,
@@ -98,7 +101,8 @@ type Editor = Readonly<{
saveClose(): Promise<boolean>;
review(
setup: InboxSetupView | undefined,
- form: PublicDraftForm
+ form: PublicDraftForm,
+ status: 'active' | 'sold'
): Promise<ListingReviewResult>;
reviewCurrent(review: ListingReview): boolean;
source(): OwnedEditSource | undefined;
@@ -187,15 +191,18 @@ export async function openListingEditor(
let reviewed:
| {
setup: InboxSetupView | undefined;
- proof: NewListingReadiness;
+ proof?: NewListingReadiness;
+ status: 'active' | 'sold';
review: ListingReview;
}
| undefined;
let reviewing: Promise<ListingReviewResult> | undefined;
let reviewingForm: string | undefined;
let reviewingSetup: InboxSetupView | undefined;
+ let reviewingStatus: 'active' | 'sold' | undefined;
function clearReview() {
- if (reviewed) closeNewListingReadiness(reviewed.proof);
+ if (reviewed?.proof) closeNewListingReadiness(reviewed.proof);
+ if (reviewed) closeListingReview(reviewed.review);
reviewed = undefined;
}
function current() {
@@ -241,7 +248,11 @@ export async function openListingEditor(
listeners.clear();
}
active.set(context, { stamp, retire });
- unsubscribe = subscribeIdentityInvalidation(session, retire);
+ unsubscribe = subscribeIdentityInvalidation(session, () => {
+ // An owned revision's delivery rechecks the same installed author. Keep
+ // this exact editor while its original route/account/storage stay current.
+ if (route.mode !== 'edit' || !current()) retire();
+ });
signal?.addEventListener('abort', retire, { once: true });
if (signal?.aborted) retire();
function unavailable(reason: 'resource' | 'storage' | 'source') {
@@ -333,7 +344,6 @@ export async function openListingEditor(
!closing &&
!operations.size &&
route &&
- route.mode !== 'edit' &&
reviewed?.review === review &&
listingReviewOwnership(review)?.current() &&
preview &&
@@ -479,14 +489,15 @@ export async function openListingEditor(
closing = false;
}
},
- review(setup, input) {
+ review(setup, input, status) {
const local = controller && publicDraftControllerSnapshot(controller);
if (
!current() ||
closing ||
!controller ||
!local ||
- route.mode === 'edit' ||
+ (route.mode === 'edit' && !editSource) ||
+ (route.mode !== 'edit' && status !== 'active') ||
operations.size ||
!exactLocalFields(input, Object.keys(emptyForm)) ||
JSON.stringify(input) !== JSON.stringify(local.form)
@@ -497,36 +508,64 @@ export async function openListingEditor(
});
if (
reviewed &&
+ reviewed.status === status &&
reviewed.setup === setup &&
reviewCurrent(reviewed.review)
)
return Promise.resolve({ status: 'review', review: reviewed.review });
const formWire = JSON.stringify(local.form);
if (reviewing)
- return reviewingForm === formWire && reviewingSetup === setup
+ return reviewingForm === formWire &&
+ reviewingSetup === setup &&
+ reviewingStatus === status
? reviewing
: Promise.resolve({ status: 'blocked', reason: 'conflict' });
clearReview();
- const proof = captureNewListingReadiness(
- session,
- setup,
- 'reviewed_new_listing_inbox'
- ),
+ const proof =
+ route.mode === 'edit'
+ ? undefined
+ : captureNewListingReadiness(
+ session,
+ setup,
+ 'reviewed_new_listing_inbox'
+ ),
command = newLocalId();
- if (!proof || !command) {
+ if ((!proof && route.mode !== 'edit') || !command) {
if (proof) closeNewListingReadiness(proof);
return Promise.resolve({ status: 'blocked', reason: 'unavailable' });
}
const original = controller;
reviewingForm = formWire;
reviewingSetup = setup;
- const pending = reviewNewListing(
- publications,
- original,
- proof,
- command,
- 'reviewed_new_listing'
- )
+ reviewingStatus = status;
+ const prepared =
+ route.mode === 'edit' && editSource
+ ? status === 'sold'
+ ? reviewMarkSold(
+ editSource,
+ original,
+ command,
+ 'reviewed_sold_availability'
+ )
+ : reviewOwnedRevision(
+ editSource,
+ original,
+ command,
+ 'reviewed_owned_revision'
+ )
+ : proof
+ ? reviewNewListing(
+ publications,
+ original,
+ proof,
+ command,
+ 'reviewed_new_listing'
+ )
+ : Promise.resolve<ListingReviewResult>({
+ status: 'blocked',
+ reason: 'unavailable'
+ });
+ const pending = prepared
.then((result): ListingReviewResult => {
const actual = publicDraftControllerSnapshot(original);
if (
@@ -536,12 +575,13 @@ export async function openListingEditor(
JSON.stringify(actual.form) !== formWire ||
result.status !== 'review'
) {
- closeNewListingReadiness(proof);
+ if (proof) closeNewListingReadiness(proof);
+ if (result.status === 'review') closeListingReview(result.review);
return result.status === 'blocked'
? result
: { status: 'blocked', reason: 'conflict' };
}
- reviewed = { setup, proof, review: result.review };
+ reviewed = { setup, proof, status, review: result.review };
if (!reviewCurrent(result.review)) {
clearReview();
return { status: 'blocked', reason: 'conflict' };
@@ -553,6 +593,7 @@ export async function openListingEditor(
reviewing = undefined;
reviewingForm = undefined;
reviewingSetup = undefined;
+ reviewingStatus = undefined;
}
});
reviewing = pending;
@@ -615,10 +656,11 @@ export function subscribeListingEditor(
export function reviewListingEditor(
editor: ListingEditor,
setup: InboxSetupView | undefined,
- form: PublicDraftForm
+ form: PublicDraftForm,
+ status: 'active' | 'sold' = 'active'
): Promise<ListingReviewResult> {
return (
- editors.get(editor)?.review(setup, form) ??
+ editors.get(editor)?.review(setup, form, status) ??
Promise.resolve({ status: 'blocked', reason: 'invalid_scope' })
);
}
diff --git a/web/src/lib/publishing/mark-sold.ts b/web/src/lib/publishing/mark-sold.ts
@@ -0,0 +1,12 @@
+import { reviewOwnedListing } from './prepare-listing.ts';
+import type { OwnedEditSource } from './edit-source.ts';
+import type { PublicDraftController } from './draft-controller.ts';
+// Sold changes public availability only; no payment/reservation record exists.
+export function reviewMarkSold(
+ source: OwnedEditSource,
+ controller: PublicDraftController,
+ command: unknown,
+ consent: unknown
+) {
+ return reviewOwnedListing(source, controller, command, 'sold', consent);
+}
diff --git a/web/src/lib/publishing/new-listing-readiness.ts b/web/src/lib/publishing/new-listing-readiness.ts
@@ -15,6 +15,10 @@ import {
import { existingInboxSetupSnapshot } from '../messaging/inbox-setup-verification.ts';
import type { InboxAccessObservation } from '../messaging/readiness.ts';
import type { RelayPolicy } from '../config/relays.ts';
+import {
+ authorizeOwnedEditSource,
+ type OwnedEditSource
+} from './edit-source.ts';
declare const readinessBrand: unique symbol;
export type NewListingReadiness = Readonly<{ [readinessBrand]: true }>;
@@ -213,3 +217,30 @@ export function newListingReadinessOwnership(
export function closeNewListingReadiness(token: NewListingReadiness): void {
reviews.get(token)?.close();
}
+// Existing announcements need original source/current-head custody, rather than
+// minting or changing an inbox preference. Final signing still uses its own lease.
+export function captureOwnedListingReadiness(
+ source: OwnedEditSource,
+ eventId: string,
+ review: unknown
+): NewListingReadiness | undefined {
+ if (review !== 'reviewed_owned_listing') return;
+ const original = authorizeOwnedEditSource(source);
+ if (!original) return;
+ let active = true;
+ const current = () => active && original.currentRevision(eventId);
+ const token = Object.freeze({}) as NewListingReadiness;
+ reviews.set(token, {
+ ownership: {
+ owner: original.owner,
+ identity: original.identity,
+ policy: original.policy,
+ current,
+ signingCurrent: current
+ },
+ close: () => {
+ active = false;
+ }
+ });
+ return token;
+}
diff --git a/web/src/lib/publishing/prepare-listing.ts b/web/src/lib/publishing/prepare-listing.ts
@@ -7,6 +7,10 @@ import { canonicalLocalId, newLocalId } from '../private-handles.ts';
import { readRelayPolicy, publicRelayTargets } from '../config/relays.ts';
import { inspectLocalTemplate } from '../nostr/local-template.ts';
import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from '../nostr/verified-envelope.ts';
+import {
decodePublicRecord,
type PublicRecordHandle
} from '../persistence/records.ts';
@@ -25,8 +29,18 @@ import {
} from './draft-controller.ts';
import {
newListingReadinessOwnership,
+ captureOwnedListingReadiness,
+ closeNewListingReadiness,
type NewListingReadiness
} from './new-listing-readiness.ts';
+import {
+ authorizeOwnedEditSource,
+ type OwnedEditSource
+} from './edit-source.ts';
+import {
+ assessFutureTimestamp,
+ wallClockAvailable
+} from '../catalog/clock-policy.ts';
declare const reviewBrand: unique symbol;
export type ListingReview = Readonly<{ [reviewBrand]: true }>;
@@ -43,6 +57,11 @@ export type ListingPreview = Readonly<{
expectedHash: string;
targets: readonly string[];
policyFingerprint: string;
+ revision?: Readonly<{
+ coordinate: string;
+ publishedAtSeconds: number;
+ status: 'active' | 'sold';
+ }>;
}>;
type Review = Readonly<{
repository: PublicPublicationRepository;
@@ -51,7 +70,10 @@ type Review = Readonly<{
editVersion: number;
command: string;
readiness: NewListingReadiness;
+ source?: OwnedEditSource;
+ status?: 'active' | 'sold';
record: PublicRecordHandle;
+ revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>;
previewWire: string;
current(this: void): boolean;
}>;
@@ -86,6 +108,51 @@ export async function reviewNewListing(
command: unknown,
consent: unknown
): Promise<ListingReviewResult> {
+ return reviewListing(repository, controller, readiness, command, consent);
+}
+// Pure declared clock policy; production supplies actual Date.now below.
+export function ownedRevisionTimestamp(
+ head: number,
+ now: number
+): number | undefined {
+ if (
+ !Number.isSafeInteger(head) ||
+ head < 0 ||
+ head >= Number.MAX_SAFE_INTEGER ||
+ !wallClockAvailable(now)
+ )
+ return;
+ const next = Math.max(head + 1, Math.floor(now));
+ return assessFutureTimestamp(next, now) === 'within_policy'
+ ? next
+ : undefined;
+}
+export async function reviewOwnedListing(
+ source: OwnedEditSource,
+ controller: PublicDraftController,
+ command: unknown,
+ status: 'active' | 'sold',
+ consent: unknown
+): Promise<ListingReviewResult> {
+ const original = authorizeOwnedEditSource(source);
+ if (!original) return { status: 'blocked', reason: 'invalid_scope' };
+ return reviewListing(
+ original.repository,
+ controller,
+ undefined,
+ command,
+ consent,
+ { source, status }
+ );
+}
+async function reviewListing(
+ repository: PublicPublicationRepository,
+ controller: PublicDraftController,
+ readiness: NewListingReadiness | undefined,
+ command: unknown,
+ consent: unknown,
+ revision?: Readonly<{ source: OwnedEditSource; status: 'active' | 'sold' }>
+): Promise<ListingReviewResult> {
try {
const custody = publicDraftControllerOwnership(controller),
owner = publicPublicationOwner(repository);
@@ -97,12 +164,18 @@ export async function reviewNewListing(
return { status: 'blocked', reason: 'invalid_scope' };
const id = canonicalLocalId(command);
if (!id) return { status: 'blocked', reason: 'invalid_command' };
- const ready = newListingReadinessOwnership(readiness);
+ const retained = revision && authorizeOwnedEditSource(revision.source);
+ const ready = revision ? retained : newListingReadinessOwnership(readiness);
if (
!ready ||
ready.owner !== owner ||
!ready.current() ||
- consent !== 'reviewed_new_listing'
+ consent !==
+ (revision
+ ? revision.status === 'sold'
+ ? 'reviewed_sold_availability'
+ : 'reviewed_owned_revision'
+ : 'reviewed_new_listing')
)
return { status: 'blocked', reason: 'unavailable' };
if (!(await flushPublicDraft(controller)))
@@ -122,7 +195,10 @@ export async function reviewNewListing(
if (
original &&
original.controller === controller &&
- original.readiness === readiness &&
+ (revision
+ ? original.source === revision.source &&
+ original.status === revision.status
+ : original.readiness === readiness) &&
JSON.stringify(original.expected) === JSON.stringify(expected) &&
original.current() &&
custody.current(JSON.stringify(expected), snapshot.editVersion)
@@ -131,9 +207,22 @@ export async function reviewNewListing(
}
return { status: 'blocked', reason: 'conflict' };
}
- const identifier = newLocalId(),
- createdAtSeconds = Math.floor(Date.now() / 1000);
- if (!identifier) return { status: 'blocked', reason: 'unavailable' };
+ const baseProof = retained && verifyEnvelope(retained.baseWire);
+ const base = baseProof?.ok
+ ? verifiedEnvelopeSnapshot(baseProof.value)
+ : undefined;
+ const identifier = revision
+ ? base?.tags.find((tag) => tag[0] === 'd')?.[1]
+ : newLocalId();
+ const now = Math.floor(Date.now() / 1000);
+ const createdAtSeconds = revision
+ ? base && ownedRevisionTimestamp(base.created_at, now)
+ : now;
+ if (!identifier || createdAtSeconds === undefined)
+ return {
+ status: 'blocked',
+ reason: revision ? 'conflict' : 'unavailable'
+ };
const form = expected.form;
if (form.contactType === '' && form.contactValue !== '')
return { status: 'blocked', reason: 'invalid_form' };
@@ -155,8 +244,8 @@ export async function reviewNewListing(
unit: form.unit,
...(form.quantity === '' ? {} : { quantity: form.quantity }),
created_at: createdAtSeconds,
- published_at: createdAtSeconds,
- status: 'active',
+ published_at: retained ? retained.publishedAtSeconds : createdAtSeconds,
+ status: revision?.status ?? 'active',
...(contact ? { contact } : {})
});
if (!built.ok) return { status: 'blocked', reason: 'invalid_form' };
@@ -194,7 +283,10 @@ export async function reviewNewListing(
if (
original &&
original.controller === controller &&
- original.readiness === readiness &&
+ (revision
+ ? original.source === revision.source &&
+ original.status === revision.status
+ : original.readiness === readiness) &&
JSON.stringify(original.expected) === JSON.stringify(expected) &&
original.current() &&
custody.current(JSON.stringify(expected), snapshot.editVersion)
@@ -224,6 +316,16 @@ export async function reviewNewListing(
id
);
if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' };
+ const proof = revision
+ ? captureOwnedListingReadiness(
+ revision.source,
+ template.hash,
+ 'reviewed_owned_listing'
+ )
+ : readiness;
+ const finalReady = newListingReadinessOwnership(proof);
+ if (!proof || !finalReady || !finalReady.current())
+ return { status: 'blocked', reason: 'conflict' };
const review = Object.freeze({}) as ListingReview;
reviews.set(review, {
repository,
@@ -231,8 +333,17 @@ export async function reviewNewListing(
expected,
editVersion: snapshot.editVersion,
command: id,
- readiness,
+ readiness: proof,
+ ...(revision ? { source: revision.source, status: revision.status } : {}),
record: admitted.value,
+ ...(retained
+ ? {
+ revisionBase: {
+ command: retained.sourceCommand,
+ record: retained.sourceRecord
+ }
+ }
+ : {}),
previewWire: JSON.stringify({
owner,
command: id,
@@ -245,10 +356,25 @@ export async function reviewNewListing(
templateWire,
expectedHash: template.hash,
targets,
- policyFingerprint
+ policyFingerprint,
+ ...(retained && revision
+ ? {
+ revision: {
+ coordinate: retained.coordinate,
+ publishedAtSeconds: retained.publishedAtSeconds,
+ status: revision.status
+ }
+ }
+ : {})
}),
current: () =>
- ready.current() && publicPublicationOwner(repository) === owner
+ finalReady.current() &&
+ publicPublicationOwner(repository) === owner &&
+ (!revision ||
+ assessFutureTimestamp(
+ createdAtSeconds,
+ Math.floor(Date.now() / 1000)
+ ) === 'within_policy')
});
const cache = commands.get(repository) ?? new Map<string, ListingReview>();
cache.set(id, review);
@@ -264,6 +390,10 @@ export function listingReviewSnapshot(
const value = reviews.get(review);
return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;
}
+export function closeListingReview(review: ListingReview): void {
+ const original = reviews.get(review);
+ if (original) closeNewListingReadiness(original.readiness);
+}
// Internal original custody, not a signing or transport permission. The later
// controller must reread the persisted intent and obtain its own effect lease.
export function listingReviewOwnership(review: ListingReview) {
@@ -297,7 +427,8 @@ export function reserveNewListing(
value.expected,
value.editVersion,
value.command,
- value.current
+ value.current,
+ value.revisionBase
).finally(() => {
if (activeReservations.get(review) === work)
activeReservations.delete(review);
diff --git a/web/src/lib/publishing/revise-listing.ts b/web/src/lib/publishing/revise-listing.ts
@@ -0,0 +1,13 @@
+import { reviewOwnedListing } from './prepare-listing.ts';
+import type { OwnedEditSource } from './edit-source.ts';
+import type { PublicDraftController } from './draft-controller.ts';
+export { ownedRevisionTimestamp as nextOwnedRevisionTime } from './prepare-listing.ts';
+// One immutable ListingReview and the existing durable publisher own the effect.
+export function reviewOwnedRevision(
+ source: OwnedEditSource,
+ controller: PublicDraftController,
+ command: unknown,
+ consent: unknown
+) {
+ return reviewOwnedListing(source, controller, command, 'active', consent);
+}
diff --git a/web/src/lib/runtime/public-runtime.ts b/web/src/lib/runtime/public-runtime.ts
@@ -214,6 +214,19 @@ export function publicRuntimeReady(
): Promise<PublicRuntime | undefined> {
return contextOf(context).ready;
}
+// Original runtime policy observation only, never a pool or effect capability.
+export function publicRuntimePolicy(
+ runtime: PublicRuntime
+): RelayPolicy | undefined {
+ try {
+ const owner = runtimeOf(runtime);
+ return !owner.closed() && owner.projectionValid()
+ ? owner.policy
+ : undefined;
+ } catch {
+ return;
+ }
+}
export function mountPublicRuntime(
context: PublicRuntimeContext,
policy: RelayPolicy = deploymentRelayPolicy,
diff --git a/web/tests/e2e/harness/revise-listing.ts b/web/tests/e2e/harness/revise-listing.ts
@@ -0,0 +1,163 @@
+// HC_TEST_ONLY_RELAY/QUALIFICATION_PORT: actual signed retained source,
+// original mounted editor and native operation rows. No live/operator Q.
+import { createFixture as sourceFixture } from './edit-source.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase,
+ browserDatabaseTransaction
+} from '../../../src/lib/persistence/database.ts';
+import type { PublicOperationRecord } from '../../../src/lib/contracts/local-records.ts';
+import { nextOwnedRevisionTime } from '../../../src/lib/publishing/revise-listing.ts';
+import { mount, unmount } from 'svelte';
+import ListingEditor from '../../../src/lib/components/ListingEditor.svelte';
+import {
+ createIdentityViewContext,
+ mountIdentityView,
+ connectIdentityView,
+ closeIdentityView,
+ IDENTITY_VIEW_CONTEXT
+} from '../../../src/lib/runtime/view-context.ts';
+import {
+ createPublicRuntimeContext,
+ mountPublicRuntime,
+ closePublicRuntime,
+ PUBLIC_RUNTIME_CONTEXT
+} from '../../../src/lib/runtime/public-runtime.ts';
+import { fixturePolicy } from './inbox-setup.ts';
+import { makeFixture } from './approved-signing.ts';
+export type ControlledSignInput = Parameters<
+ ReturnType<typeof makeFixture>['sign']
+>[0];
+
+export async function createFixture() {
+ const original = await sourceFixture();
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error(opened.reason);
+ const database = opened.owner;
+ let release = () => {},
+ restore = () => {},
+ signRequests = 0;
+ return {
+ ...original,
+ clock: nextOwnedRevisionTime,
+ async signOriginal(input: ControlledSignInput) {
+ const provider = window.nostr as
+ | {
+ signEvent(
+ input: ControlledSignInput
+ ): Promise<ReturnType<ReturnType<typeof makeFixture>['sign']>>;
+ }
+ | undefined;
+ if (!provider) throw Error('original provider missing');
+ return await provider.signEvent(input);
+ },
+ holdNextSignature() {
+ const provider = window.nostr as
+ | {
+ signEvent(
+ input: Parameters<ReturnType<typeof makeFixture>['sign']>[0]
+ ): Promise<ReturnType<ReturnType<typeof makeFixture>['sign']>>;
+ }
+ | undefined;
+ if (!provider) throw Error('original provider missing');
+ const sign = provider.signEvent.bind(provider);
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ provider.signEvent = async (input) => {
+ signRequests++;
+ await held;
+ return sign(input);
+ };
+ restore = () => {
+ provider.signEvent = sign;
+ };
+ },
+ refuseNextSignature() {
+ const provider = window.nostr as
+ | {
+ signEvent(
+ input: Parameters<ReturnType<typeof makeFixture>['sign']>[0]
+ ): Promise<ReturnType<ReturnType<typeof makeFixture>['sign']>>;
+ }
+ | undefined;
+ if (!provider) throw Error('original provider missing');
+ const sign = provider.signEvent.bind(provider);
+ let refused = false;
+ provider.signEvent = async (input) => {
+ signRequests++;
+ if (!refused) {
+ refused = true;
+ throw Error('controlled refusal after actual durable signing marker');
+ }
+ return sign(input);
+ };
+ restore = () => {
+ provider.signEvent = sign;
+ };
+ },
+ signRequests: () => signRequests,
+ releaseSignature() {
+ release();
+ },
+ async operations() {
+ const transaction = browserDatabaseTransaction(
+ database,
+ ['public_operations'],
+ 'readonly'
+ );
+ const request = transaction.objectStore('public_operations').getAll();
+ return await new Promise<PublicOperationRecord[]>((resolve, reject) => {
+ transaction.addEventListener('complete', () =>
+ resolve(
+ (request.result as { owner: string; wire: string }[])
+ .filter((row) => row.owner === original.owner)
+ .map((row) => JSON.parse(row.wire) as PublicOperationRecord)
+ )
+ );
+ transaction.addEventListener('abort', () =>
+ reject(Error('actual native operation read failed'))
+ );
+ });
+ },
+ async close() {
+ release();
+ restore();
+ closeBrowserDatabase(database);
+ await original.close();
+ }
+ };
+}
+
+export async function openSecondEditor(owner: string, naddr: string) {
+ const context = createIdentityViewContext();
+ mountIdentityView(context);
+ const connected = await connectIdentityView(context);
+ if (
+ connected.identity.state === 'guest' ||
+ connected.identity.state === 'pending' ||
+ connected.identity.publicKey !== owner
+ )
+ throw Error('actual second-tab owner mismatch');
+ const publicContext = createPublicRuntimeContext();
+ mountPublicRuntime(publicContext, fixturePolicy());
+ const target = document.createElement('div');
+ target.id = 'hcp119-second';
+ document.body.append(target);
+ const editor = mount(ListingEditor, {
+ target,
+ props: { route: { mode: 'edit', naddr } },
+ context: new Map<string, unknown>([
+ [IDENTITY_VIEW_CONTEXT, context],
+ [PUBLIC_RUNTIME_CONTEXT, publicContext]
+ ])
+ });
+ return {
+ async close() {
+ await unmount(editor);
+ target.remove();
+ closePublicRuntime(publicContext);
+ closeIdentityView(context);
+ }
+ };
+}
diff --git a/web/tests/e2e/revise-listing.spec.ts b/web/tests/e2e/revise-listing.spec.ts
@@ -0,0 +1,555 @@
+import { expect, test } from '@playwright/test';
+import { build } from 'vite';
+import { svelte } from '@sveltejs/vite-plugin-svelte';
+import { fileURLToPath } from 'node:url';
+import { once } from 'node:events';
+import { writeFile } from 'node:fs/promises';
+import { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/revise-listing.ts';
+import type { NostrEvent } from 'applesauce-core/helpers';
+declare global {
+ interface Window {
+ hcp119: typeof Fixture;
+ hcp119Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
+ hcp119Second: Awaited<ReturnType<typeof Fixture.openSecondEditor>>;
+ hcp119OriginalSign(input: Fixture.ControlledSignInput): Promise<NostrEvent>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let event: NostrEvent | undefined,
+ partial = false,
+ effects: NostrEvent[] = [];
+let tabs: import('@playwright/test').Page[] = [];
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 262144
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string') throw Error('loopback missing');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket) =>
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes);
+ const frame = JSON.parse(raw.toString()) as unknown[];
+ if (frame[0] === 'EVENT') {
+ event = frame[1] as NostrEvent;
+ effects.push(event);
+ socket.send(JSON.stringify(['OK', event.id, true, '']));
+ return;
+ }
+ if (frame[0] !== 'REQ') return;
+ const filters = frame.slice(2) as {
+ kinds?: number[];
+ ids?: string[];
+ authors?: string[];
+ '#d'?: string[];
+ }[];
+ if (
+ event &&
+ filters.some(
+ (filter) =>
+ (!filter.kinds || filter.kinds.includes(event!.kind)) &&
+ (!filter.ids || filter.ids.includes(event!.id)) &&
+ (!filter.authors || filter.authors.includes(event!.pubkey)) &&
+ (!filter['#d'] ||
+ filter['#d'].includes(
+ event!.tags.find((tag) => tag[0] === 'd')?.[1] ?? ''
+ ))
+ )
+ )
+ socket.send(JSON.stringify(['EVENT', frame[1], event]));
+ if (!(partial && filters.some((filter) => filter.kinds?.includes(5))))
+ socket.send(JSON.stringify(['EOSE', frame[1]]));
+ })
+ );
+ 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/revise-listing.ts', import.meta.url)
+ ),
+ name: 'hcp119',
+ formats: ['iife']
+ }
+ }
+ });
+ const result = Array.isArray(built) ? built[0] : built;
+ if (!('output' in result)) throw Error('actual fixture bundle missing');
+ const chunks = result.output.filter((row) => row.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => {
+ for (const socket of sockets?.clients ?? []) socket.terminate();
+ if (sockets)
+ await new Promise<void>((resolve, reject) =>
+ sockets.close((error) => (error ? reject(error) : resolve()))
+ );
+ await server?.close();
+});
+test.beforeEach(async ({ page }) => {
+ tabs = [];
+ event = undefined;
+ partial = false;
+ effects = [];
+ await page.addInitScript((endpoint) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (
+ ![
+ 'wss://discovery.example.org',
+ 'wss://inbox.example.org',
+ 'wss://second.example.org'
+ ].includes(new URL(url.toString()).origin)
+ )
+ throw Error('no live relay permission');
+ super(endpoint, protocols);
+ }
+ };
+ }, endpoint);
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ event = await page.evaluate(async () => {
+ window.hcp119Fixture = await window.hcp119.createFixture();
+ return window.hcp119Fixture.event;
+ });
+});
+test.afterEach(async ({ page }) => {
+ for (const tab of tabs) {
+ if (!tab.isClosed()) {
+ await tab.evaluate(async () => {
+ await window.hcp119Second?.close();
+ });
+ await tab.close();
+ }
+ }
+ await page.evaluate(async () => {
+ await window.hcp119Fixture?.close();
+ });
+});
+async function editor(page: import('@playwright/test').Page) {
+ await page.evaluate(() => window.hcp119Fixture.renderEditor());
+ await expect(page.locator('#listing-title')).not.toHaveAttribute(
+ 'readonly',
+ ''
+ );
+}
+async function review(page: import('@playwright/test').Page) {
+ await editor(page);
+ await page.locator('#listing-title').fill('Actual revised carrots');
+ await page
+ .locator('#listing-description')
+ .fill('Complete exact revised public description.');
+ await page
+ .getByRole('button', { name: 'Review changes', exact: true })
+ .click();
+ await expect(
+ page.getByRole('region', { name: 'Public listing review' })
+ ).toBeVisible();
+}
+test('HCP119 exact review retains coordinate/published_at and performs no reservation sign or send', async ({
+ page
+}) => {
+ const before = await page.evaluate(() => window.hcp119Fixture.counts());
+ await review(page);
+ const region = page.getByRole('region', { name: 'Public listing review' });
+ await expect(region).toContainText(
+ 'Complete exact revised public description.'
+ );
+ await expect(region).toContainText(
+ await page.evaluate(() => window.hcp119Fixture.naddr)
+ );
+ expect(await page.evaluate(() => window.hcp119Fixture.counts())).toEqual(
+ before
+ );
+ expect(
+ await page.evaluate(() => window.hcp119Fixture.operations())
+ ).toHaveLength(1);
+ expect(effects).toHaveLength(0);
+ await page.getByRole('button', { name: 'Edit details', exact: true }).click();
+ await expect(page.locator('#listing-title')).toHaveValue(
+ 'Actual revised carrots'
+ );
+ await expect(page.locator('#listing-title')).toBeFocused();
+});
+test('HCP119 explicit Publish changes persists one genuine signed update with original coordinate and durable target facts', async ({
+ page
+}) => {
+ const base = await page.evaluate(() => window.hcp119Fixture.event);
+ const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
+ await review(page);
+ await page
+ .getByRole('button', { name: 'Publish changes', exact: true })
+ .click();
+ await expect.poll(() => effects.length).toBeGreaterThan(0);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ async () =>
+ (await window.hcp119Fixture.operations())
+ .find(
+ (row) => row.artifact?.eventId !== window.hcp119Fixture.event.id
+ )
+ ?.receipts.filter((fact) => fact.readbackWire !== null).length ?? 0
+ )
+ )
+ .toBe(1);
+ const rows = await page.evaluate(() => window.hcp119Fixture.operations());
+ expect(rows).toHaveLength(2);
+ const revised = rows.find((row) => row.artifact?.eventId !== base.id);
+ expect(revised?.capture.targets).toEqual(['wss://discovery.example.org']);
+ expect(revised?.artifact).toBeTruthy();
+ const wire = JSON.parse(revised!.artifact!.wire) as NostrEvent;
+ expect(wire.kind).toBe(30402);
+ expect(wire.pubkey).toBe(base.pubkey);
+ expect(wire.tags.find((tag) => tag[0] === 'd')).toEqual(
+ base.tags.find((tag) => tag[0] === 'd')
+ );
+ expect(wire.tags.find((tag) => tag[0] === 'published_at')).toEqual(
+ base.tags.find((tag) => tag[0] === 'published_at')
+ );
+ expect(wire.created_at).toBeGreaterThan(base.created_at);
+ expect(wire.created_at - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(
+ 300
+ );
+ expect(
+ effects.every((effect) => effect.id === wire.id && effect.kind === 30402)
+ ).toBe(true);
+ expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
+ before + 1
+ );
+ expect(
+ rows.find((row) => row.artifact?.eventId === base.id)?.artifact?.wire
+ ).toBe(JSON.stringify(base));
+ await page.evaluate(() => window.hcp119Fixture.open());
+ await expect
+ .poll(() => page.evaluate(() => window.hcp119Fixture.snapshot()?.status))
+ .toBe('ready');
+ const reopened = await page.evaluate(() => window.hcp119Fixture.snapshot());
+ expect(reopened?.sourceEventId).toBe(wire.id);
+ expect(reopened?.form.title).toBe('Actual revised carrots');
+ expect(reopened?.publishedAtSeconds).toBe(
+ Number(base.tags.find((tag) => tag[0] === 'published_at')![1])
+ );
+});
+test('HCP119 separate sold consequence review is not payment or stock reservation and emits only reviewed kind30402', async ({
+ page
+}) => {
+ await editor(page);
+ const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
+ await page.getByText('Other listing actions', { exact: true }).click();
+ await page.getByRole('button', { name: 'Mark as sold', exact: true }).click();
+ await expect(
+ page.getByRole('region', { name: 'Confirm sold update' })
+ ).toContainText('not a payment or stock reservation receipt');
+ expect(effects).toHaveLength(0);
+ await page
+ .getByRole('button', { name: 'Review sold update', exact: true })
+ .click();
+ await expect(
+ page.getByRole('region', { name: 'Public listing review' })
+ ).toContainText('Sold');
+ expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
+ before
+ );
+ await page
+ .getByRole('button', { name: 'Publish sold update', exact: true })
+ .click();
+ await expect.poll(() => effects.length).toBeGreaterThan(0);
+ expect(
+ effects.every(
+ (effect) =>
+ effect.kind === 30402 &&
+ effect.tags.some((tag) => tag[0] === 'status' && tag[1] === 'sold')
+ )
+ ).toBe(true);
+ expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
+ before + 1
+ );
+});
+test('HCP119 cancel sold confirmation preserves proposal and performs no effect', async ({
+ page
+}) => {
+ await editor(page);
+ await page.locator('#listing-title').fill('Keep my exact proposal');
+ const before = await page.evaluate(() => window.hcp119Fixture.counts());
+ await page.getByText('Other listing actions', { exact: true }).click();
+ await page.getByRole('button', { name: 'Mark as sold', exact: true }).click();
+ await page.getByRole('button', { name: 'Keep editing', exact: true }).click();
+ await expect(page.locator('#listing-title')).toHaveValue(
+ 'Keep my exact proposal'
+ );
+ expect(await page.evaluate(() => window.hcp119Fixture.counts())).toEqual(
+ before
+ );
+ expect(effects).toHaveLength(0);
+});
+test('HCP119 independently changed head fences an already reviewed proposal before publication', async ({
+ page
+}) => {
+ await review(page);
+ event = await page.evaluate(() => window.hcp119Fixture.competing());
+ const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
+ await page.evaluate(() => window.hcp119Fixture.lookupAgain());
+ await expect(
+ page.getByRole('button', { name: 'Publish changes', exact: true })
+ ).toHaveCount(0);
+ await expect(page.locator('#listing-title')).toHaveValue(
+ 'Actual revised carrots'
+ );
+ await expect(page.locator('#listing-title')).toHaveAttribute('readonly', '');
+ expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
+ before
+ );
+ expect(effects).toHaveLength(0);
+});
+test('HCP119 incomplete critical deletion coverage cannot expose revision or sold actions', async ({
+ page
+}) => {
+ partial = true;
+ await page.evaluate(() => window.hcp119Fixture.renderEditor());
+ await expect(page.locator('#listing-title')).toHaveAttribute('readonly', '');
+ await expect(
+ page.getByRole('button', { name: /Review changes|Mark as sold/ })
+ ).toHaveCount(0);
+ expect(effects).toHaveLength(0);
+});
+test('HCP119 actual backward wall-clock change fences the captured review without inventing a later timestamp', async ({
+ page
+}) => {
+ await review(page);
+ const before = await page.evaluate(() => window.hcp119Fixture.counts().signs);
+ await page.evaluate(() => {
+ const actualNow = Date.now;
+ Date.now = () => actualNow() - 301000;
+ });
+ await expect(
+ page.getByRole('button', { name: 'Publish changes', exact: true })
+ ).toHaveCount(0);
+ await expect(page.locator('#listing-title')).toHaveValue(
+ 'Actual revised carrots'
+ );
+ expect(await page.evaluate(() => window.hcp119Fixture.counts().signs)).toBe(
+ before
+ );
+ expect(
+ await page.evaluate(() => window.hcp119Fixture.operations())
+ ).toHaveLength(1);
+ expect(effects).toHaveLength(0);
+});
+for (const width of [320, 1024])
+ test(`HCP119 ${width}px exact revision review and sold confirmation remain readable`, async ({
+ page
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await review(page);
+ await expect(
+ page.getByRole('region', { name: 'Public listing review' })
+ ).toContainText('Actual revised carrots');
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth
+ )
+ ).toBe(true);
+ await page
+ .getByRole('button', { name: 'Edit details', exact: true })
+ .click();
+ await page.getByText('Other listing actions', { exact: true }).click();
+ await page
+ .getByRole('button', { name: 'Mark as sold', exact: true })
+ .click();
+ await expect(
+ page.getByRole('region', { name: 'Confirm sold update' })
+ ).toBeVisible();
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth
+ )
+ ).toBe(true);
+ expect(effects).toHaveLength(0);
+ });
+
+test('HCP119 two original editors cannot reserve against an unresolved retained coordinate capture', async ({
+ page
+}) => {
+ await review(page);
+ const first = page.locator('#hcp118-conflict');
+ const tab = await page.context().newPage();
+ tabs.push(tab);
+ const errors: string[] = [];
+ tab.on('pageerror', (error) => errors.push(error.message));
+ const source = await page.evaluate(() => ({
+ owner: window.hcp119Fixture.owner,
+ naddr: window.hcp119Fixture.naddr
+ }));
+ await tab.exposeFunction(
+ 'hcp119OriginalSign',
+ async (input: Fixture.ControlledSignInput) =>
+ await page.evaluate(
+ (input) => window.hcp119Fixture.signOriginal(input),
+ input
+ )
+ );
+ await tab.addInitScript(
+ ({ endpoint, owner }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ if (
+ ![
+ 'wss://discovery.example.org',
+ 'wss://inbox.example.org',
+ 'wss://second.example.org'
+ ].includes(new URL(url.toString()).origin)
+ )
+ throw Error('no live relay permission');
+ super(endpoint, protocols);
+ }
+ };
+ Object.defineProperty(window, 'nostr', {
+ configurable: true,
+ value: {
+ getPublicKey: () => Promise.resolve(owner),
+ signEvent: (input: Fixture.ControlledSignInput) =>
+ window.hcp119OriginalSign(input)
+ }
+ });
+ },
+ { endpoint, owner: source.owner }
+ );
+ await tab.goto(server.url + '/search');
+ await tab.addScriptTag({ content: bundle });
+ await tab.evaluate(async ({ owner, naddr }) => {
+ window.hcp119Second = await window.hcp119.openSecondEditor(owner, naddr);
+ }, source);
+ const second = tab.locator('#hcp119-second');
+ await expect(second.locator('#listing-title')).not.toHaveAttribute(
+ 'readonly',
+ ''
+ );
+ await second.locator('#listing-title').fill('Second tab proposed carrots');
+ await second
+ .getByRole('button', { name: 'Review changes', exact: true })
+ .click();
+ await expect(
+ second.getByRole('region', { name: 'Public listing review' })
+ ).toBeVisible();
+ await page.evaluate(() => window.hcp119Fixture.refuseNextSignature());
+ await first
+ .getByRole('button', { name: 'Publish changes', exact: true })
+ .click();
+ await expect(
+ first.getByText(
+ 'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.',
+ { exact: true }
+ )
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.hcp119Fixture.signRequests())).toBe(
+ 1
+ );
+ expect(
+ await page.evaluate(() => window.hcp119Fixture.operations())
+ ).toHaveLength(2);
+ expect(effects).toHaveLength(0);
+ await second
+ .getByRole('button', { name: 'Publish changes', exact: true })
+ .click();
+ // Wait for either genuine settled outcome, then assert the exact native rows.
+ // The assertion never equates a still-pending request with successful fencing.
+ await writeFile(
+ test.info().outputPath('actual-second-tab-early-public-state.json'),
+ JSON.stringify({
+ phase: 'EARLY_AFTER_ACTION_NO_SETTLED_OR_ASSERTION_CREDIT',
+ errors,
+ secondText: await second.innerText(),
+ operations: await page.evaluate(() => window.hcp119Fixture.operations()),
+ signRequests: await page.evaluate(() =>
+ window.hcp119Fixture.signRequests()
+ ),
+ effects
+ })
+ );
+ try {
+ await expect
+ .poll(
+ async () =>
+ errors.length +
+ (await second
+ .getByText(
+ /Relay acceptance recorded for|The update did not complete\.|Supported local listing values are not available for editing/
+ )
+ .count())
+ )
+ .toBeGreaterThan(0);
+ } finally {
+ const actualState = JSON.stringify({
+ errors,
+ secondText: await second.innerText(),
+ publishingButtons: await second
+ .getByRole('button', { name: 'Publishing update', exact: true })
+ .count(),
+ operations: await page.evaluate(() => window.hcp119Fixture.operations()),
+ signRequests: await page.evaluate(() =>
+ window.hcp119Fixture.signRequests()
+ ),
+ effects
+ });
+ await writeFile(
+ test.info().outputPath('actual-second-tab-public-state.json'),
+ actualState
+ );
+ await test.info().attach('actual-second-tab-public-state', {
+ path: test.info().outputPath('actual-second-tab-public-state.json'),
+ contentType: 'application/json'
+ });
+ }
+ expect(errors).toEqual([]);
+ expect(
+ await page.evaluate(() => window.hcp119Fixture.operations())
+ ).toHaveLength(2);
+ expect(await page.evaluate(() => window.hcp119Fixture.signRequests())).toBe(
+ 1
+ );
+ expect(effects).toHaveLength(0);
+ await expect(
+ second.getByRole('region', { name: 'Public listing review' })
+ ).toContainText('Second tab proposed carrots');
+});
+
+test('HCP119 a retained pending signature fences a fresh editor without adopting another local capture', async ({
+ page
+}) => {
+ await review(page);
+ await page.evaluate(() => window.hcp119Fixture.holdNextSignature());
+ await page
+ .getByRole('button', { name: 'Publish changes', exact: true })
+ .click();
+ await expect
+ .poll(() => page.evaluate(() => window.hcp119Fixture.signRequests()))
+ .toBe(1);
+ expect(
+ await page.evaluate(() => window.hcp119Fixture.open())
+ ).toBeUndefined();
+ expect(effects).toHaveLength(0);
+ await page.evaluate(() => window.hcp119Fixture.releaseSignature());
+ await expect.poll(() => effects.length).toBeGreaterThan(0);
+});
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -29,6 +29,78 @@ import { auditOutput } from '../../tools/check-output.mjs';
// Exact HCP043 product shell bytes, immutable compatibility evidence only.
const historicalProduct =
'<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';
+ // Exact unchanged118 producer closure for historical compatibility variants.
+ // Restore before the immutable older overlays; no ancestor Git runtime dependency.
+ /** @type {Record<string, {source:string, sha256:string}>} */
+ const historicalPublicProducerClosure = {
+ 'src/lib/publishing/prepare-listing.ts': {
+ source:
+ "import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport type {\n PublicDraftRecord,\n PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId, newLocalId } from '../private-handles.ts';\nimport { readRelayPolicy, publicRelayTargets } from '../config/relays.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n decodePublicRecord,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n publicPublicationOwner,\n publicPublicationDraftRepository,\n savePublicListingIntent,\n type PublicPublicationRepository,\n type PublicListingSave\n} from '../persistence/public-publications.ts';\nimport {\n publicDraftControllerOwnership,\n publicDraftControllerSnapshot,\n flushPublicDraft,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n newListingReadinessOwnership,\n type NewListingReadiness\n} from './new-listing-readiness.ts';\n\ndeclare const reviewBrand: unique symbol;\nexport type ListingReview = Readonly<{ [reviewBrand]: true }>;\nexport type ListingPreview = Readonly<{\n owner: string;\n command: string;\n draftId: string;\n draftRevision: number;\n identifier: string;\n createdAtSeconds: number;\n form: PublicDraftForm;\n summary: string;\n templateWire: string;\n expectedHash: string;\n targets: readonly string[];\n policyFingerprint: string;\n}>;\ntype Review = Readonly<{\n repository: PublicPublicationRepository;\n controller: PublicDraftController;\n expected: PublicDraftRecord;\n editVersion: number;\n command: string;\n readiness: NewListingReadiness;\n record: PublicRecordHandle;\n previewWire: string;\n current(this: void): boolean;\n}>;\nconst reviews = new WeakMap<ListingReview, Review>();\nconst commands = new WeakMap<\n PublicPublicationRepository,\n Map<string, ListingReview>\n>();\nconst activeReservations = new WeakMap<\n ListingReview,\n Promise<ListingReservation>\n>();\nexport type ListingReviewResult =\n | Readonly<{ status: 'review'; review: ListingReview }>\n | Readonly<{\n status: 'blocked';\n reason:\n | 'invalid_scope'\n | 'invalid_command'\n | 'unavailable'\n | 'invalid_form'\n | 'conflict';\n }>;\nexport type ListingReservation =\n PublicListingSave | Readonly<{ status: 'invalid' }>;\n// Review flushes local draft state and prepares an exact immutable template;\n// it neither reserves a publication nor asks the extension to sign.\nexport async function reviewNewListing(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n readiness: NewListingReadiness,\n command: unknown,\n consent: unknown\n): Promise<ListingReviewResult> {\n try {\n const custody = publicDraftControllerOwnership(controller),\n owner = publicPublicationOwner(repository);\n if (\n !custody ||\n !owner ||\n custody.repository !== publicPublicationDraftRepository(repository)\n )\n return { status: 'blocked', reason: 'invalid_scope' };\n const id = canonicalLocalId(command);\n if (!id) return { status: 'blocked', reason: 'invalid_command' };\n const ready = newListingReadinessOwnership(readiness);\n if (\n !ready ||\n ready.owner !== owner ||\n !ready.current() ||\n consent !== 'reviewed_new_listing'\n )\n return { status: 'blocked', reason: 'unavailable' };\n if (!(await flushPublicDraft(controller)))\n return { status: 'blocked', reason: 'unavailable' };\n const snapshot = publicDraftControllerSnapshot(controller),\n expected = snapshot?.draft;\n if (\n !snapshot ||\n !expected ||\n expected.owner !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n const cached = commands.get(repository)?.get(id);\n if (cached) {\n const original = reviews.get(cached);\n if (\n original &&\n original.controller === controller &&\n original.readiness === readiness &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n ) {\n return { status: 'review', review: cached };\n }\n return { status: 'blocked', reason: 'conflict' };\n }\n const identifier = newLocalId(),\n createdAtSeconds = Math.floor(Date.now() / 1000);\n if (!identifier) return { status: 'blocked', reason: 'unavailable' };\n const form = expected.form;\n if (form.contactType === '' && form.contactValue !== '')\n return { status: 'blocked', reason: 'invalid_form' };\n const contact =\n form.contactType === ''\n ? undefined\n : {\n type: form.contactType,\n value: form.contactValue,\n public: true as const\n };\n const built = buildFoodTemplate({\n identifier,\n title: form.title,\n description: form.description,\n location: form.location,\n amount: form.amount,\n currency: form.currency,\n unit: form.unit,\n ...(form.quantity === '' ? {} : { quantity: form.quantity }),\n created_at: createdAtSeconds,\n published_at: createdAtSeconds,\n status: 'active',\n ...(contact ? { contact } : {})\n });\n if (!built.ok) return { status: 'blocked', reason: 'invalid_form' };\n const manifest = readRelayPolicy(ready.policy),\n targets = publicRelayTargets(ready.policy, 'write');\n const templateWire = JSON.stringify({\n pubkey: owner,\n kind: 30402,\n created_at: createdAtSeconds,\n tags: built.wire_parts.tags,\n content: built.wire_parts.content\n });\n const template = inspectLocalTemplate(templateWire, owner, 30402);\n if (!template || !manifest.postingEnabled || targets.length === 0)\n return { status: 'blocked', reason: 'unavailable' };\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(manifest))\n );\n const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>\n value.toString(16).padStart(2, '0')\n ).join('');\n // Hashing is outside any IDB transaction; recheck original mutable owners.\n if (\n !ready.current() ||\n publicPublicationOwner(repository) !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n // Another review may have completed while this one awaited hashing. The\n // first retained command owns its ID/time/template; never replace it.\n const racing = commands.get(repository)?.get(id);\n if (racing) {\n const original = reviews.get(racing);\n if (\n original &&\n original.controller === controller &&\n original.readiness === readiness &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'review', review: racing };\n return { status: 'blocked', reason: 'conflict' };\n }\n const admitted = decodePublicRecord(\n JSON.stringify({\n schema: 1,\n family: 'public_operation',\n owner,\n id,\n revision: 0,\n source: { type: 'draft', id: expected.id, revision: expected.revision },\n capture: {\n kind: 30402,\n wire: templateWire,\n hash: template.hash,\n targets,\n policyFingerprint\n },\n artifact: null,\n receipts: []\n }),\n owner,\n id\n );\n if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' };\n const review = Object.freeze({}) as ListingReview;\n reviews.set(review, {\n repository,\n controller,\n expected,\n editVersion: snapshot.editVersion,\n command: id,\n readiness,\n record: admitted.value,\n previewWire: JSON.stringify({\n owner,\n command: id,\n draftId: expected.id,\n draftRevision: expected.revision,\n identifier,\n createdAtSeconds,\n form,\n summary: built.summary,\n templateWire,\n expectedHash: template.hash,\n targets,\n policyFingerprint\n }),\n current: () =>\n ready.current() && publicPublicationOwner(repository) === owner\n });\n const cache = commands.get(repository) ?? new Map<string, ListingReview>();\n cache.set(id, review);\n commands.set(repository, cache);\n return { status: 'review', review };\n } catch {\n return { status: 'blocked', reason: 'unavailable' };\n }\n}\nexport function listingReviewSnapshot(\n review: ListingReview\n): ListingPreview | undefined {\n const value = reviews.get(review);\n return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;\n}\n// Internal original custody, not a signing or transport permission. The later\n// controller must reread the persisted intent and obtain its own effect lease.\nexport function listingReviewOwnership(review: ListingReview) {\n const original = reviews.get(review);\n const ready = original && newListingReadinessOwnership(original.readiness);\n return original && ready && original.current()\n ? {\n repository: original.repository,\n record: original.record,\n command: original.command,\n readiness: ready,\n current: original.current\n }\n : undefined;\n}\n// One original review deduplicates simultaneous clicks. Failed/uncertain work\n// remains the same capture for later explicit retry; no fresh ID/time/template.\nexport function reserveNewListing(\n review: ListingReview,\n consent: unknown\n): Promise<ListingReservation> {\n const value = reviews.get(review);\n if (!value || consent !== 'publish_reviewed_listing')\n return Promise.resolve({ status: 'invalid' });\n const active = activeReservations.get(review);\n if (active) return active;\n const work = savePublicListingIntent(\n value.repository,\n value.controller,\n value.record,\n value.expected,\n value.editVersion,\n value.command,\n value.current\n ).finally(() => {\n if (activeReservations.get(review) === work)\n activeReservations.delete(review);\n });\n activeReservations.set(review, work);\n return work;\n}\n",
+ sha256: 'a362b18fce125b16d9f488b702cecdda1fc683f8feab25b9dca368712a40fd4e'
+ },
+ 'src/lib/publishing/new-listing-readiness.ts': {
+ source:
+ "import {\n identityMessagingOwnership,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport { privateSessionOwnership } from '../runtime/private-session.ts';\nimport {\n inboxSetupViewOwnership,\n inboxSetupViewSnapshot,\n type InboxSetupView\n} from '../messaging/inbox-setup-view.ts';\nimport {\n inboxResolutionSnapshot,\n inboxResolverCurrentAfterSample\n} from '../messaging/resolve-inbox.ts';\nimport { existingInboxSetupSnapshot } from '../messaging/inbox-setup-verification.ts';\nimport type { InboxAccessObservation } from '../messaging/readiness.ts';\nimport type { RelayPolicy } from '../config/relays.ts';\n\ndeclare const readinessBrand: unique symbol;\nexport type NewListingReadiness = Readonly<{ [readinessBrand]: true }>;\ntype Ownership = Readonly<{\n owner: string;\n identity: IdentitySession;\n policy: RelayPolicy;\n current(this: void): boolean;\n signingCurrent(this: void): boolean;\n}>;\nconst reviews = new WeakMap<\n NewListingReadiness,\n {\n ownership: Ownership;\n close(): void;\n }\n>();\n\n// Readiness is a prerequisite for a later new-listing command, not permission\n// to sign, write a preference, reserve a listing or publish an event. Its owners\n// must still validate the exact draft/author/template and final explicit action.\nfunction sample(identity: IdentitySession, setup: InboxSetupView | undefined) {\n try {\n if (typeof window === 'undefined') return;\n const actor = identityMessagingOwnership(identity);\n const own = inboxSetupViewOwnership(setup);\n const state = inboxSetupViewSnapshot(setup);\n if (\n !actor?.current() ||\n !own?.current() ||\n own.identity !== identity ||\n !own.session ||\n !own.resolver ||\n state.busy ||\n !state.setupComplete\n )\n return;\n const privateOwner = privateSessionOwnership(own.session);\n if (\n !privateOwner?.current() ||\n privateOwner.owner !== actor.owner ||\n privateOwner.session !== actor.session\n )\n return;\n const initial = inboxResolutionSnapshot(own.resolver);\n if (!initial.knownBase || initial.author !== actor.owner) return;\n let access: InboxAccessObservation | undefined;\n const ready = existingInboxSetupSnapshot(\n identity,\n own.session,\n own.policy,\n own.resolver,\n own.observeAccess\n ? (context) => {\n access = own.observeAccess!(context);\n return access;\n }\n : undefined\n );\n const final = inboxResolutionSnapshot(own.resolver);\n const accessCurrent = access?.current() ?? false;\n const actual = inboxSetupViewOwnership(setup);\n const finalState = inboxSetupViewSnapshot(setup);\n if (\n !ready.setupComplete ||\n !ready.newListingReady ||\n !accessCurrent ||\n final.knownBase?.id !== initial.knownBase.id ||\n final.status !== 'ready' ||\n !actor.current() ||\n !privateOwner.current() ||\n !own.current() ||\n !actual?.current() ||\n actual.identity !== identity ||\n actual.policy !== own.policy ||\n actual.session !== own.session ||\n actual.resolver !== own.resolver ||\n finalState.busy ||\n !finalState.setupComplete ||\n !inboxResolverCurrentAfterSample(own.resolver)\n )\n return;\n return {\n actor,\n own,\n privateOwner,\n preferenceId: final.knownBase.id,\n accessCurrent: () => access?.current() ?? false\n };\n } catch {\n return;\n }\n}\n\n// Detached display information never mints or replaces the original review.\n// Draft saving has no dependency on this module and remains available here.\nexport function newListingReadinessSnapshot(\n identity: IdentitySession,\n setup: InboxSetupView | undefined\n) {\n const ready = !!sample(identity, setup);\n return {\n draft: true as const,\n readyToReview: ready,\n preferenceWrite: 'not_requested' as const,\n copy: ready\n ? 'Messages: ready to receive replies'\n : 'Enable messages before publishing so buyers can contact you.'\n };\n}\nexport function captureNewListingReadiness(\n identity: IdentitySession,\n setup: InboxSetupView | undefined,\n review: unknown\n): NewListingReadiness | undefined {\n if (review !== 'reviewed_new_listing_inbox') return;\n const captured = sample(identity, setup);\n if (!captured) return;\n const capturedResolver = captured.own.resolver;\n if (!capturedResolver) return;\n let active = true;\n // Continuity of an already admitted original signing action. Reacquiring\n // messaging capability during that action would reject its own busy prompt.\n // This checks retained original generations/access, never admits a new action.\n const signingCurrent = () => {\n const actual = inboxSetupViewOwnership(setup);\n const state = inboxSetupViewSnapshot(setup);\n const resolved = inboxResolutionSnapshot(capturedResolver);\n return (\n active &&\n captured.actor.current() &&\n captured.own.current() &&\n captured.privateOwner.current() &&\n captured.accessCurrent() &&\n !!actual?.current() &&\n actual.identity === captured.own.identity &&\n actual.policy === captured.own.policy &&\n actual.session === captured.own.session &&\n actual.resolver === captured.own.resolver &&\n !state.busy &&\n state.setupComplete &&\n resolved.status === 'ready' &&\n resolved.author === captured.actor.owner &&\n resolved.knownBase?.id === captured.preferenceId &&\n inboxResolverCurrentAfterSample(capturedResolver) &&\n active &&\n captured.actor.current() &&\n captured.privateOwner.current()\n );\n };\n const current = () => {\n if (\n !active ||\n !captured.actor.current() ||\n !captured.own.current() ||\n !captured.privateOwner.current()\n )\n return false;\n const actual = sample(identity, setup);\n return (\n !!actual &&\n active &&\n actual.actor.owner === captured.actor.owner &&\n actual.actor.session === captured.actor.session &&\n actual.own.identity === captured.own.identity &&\n actual.own.policy === captured.own.policy &&\n actual.own.session === captured.own.session &&\n actual.own.resolver === captured.own.resolver &&\n actual.preferenceId === captured.preferenceId &&\n captured.actor.current() &&\n captured.own.current() &&\n captured.privateOwner.current()\n );\n };\n const token = Object.freeze({}) as NewListingReadiness;\n reviews.set(token, {\n ownership: {\n owner: captured.actor.owner,\n identity,\n policy: captured.own.policy,\n current,\n signingCurrent\n },\n close: () => {\n active = false;\n }\n });\n return token;\n}\nexport function newListingReadinessOwnership(\n token: NewListingReadiness | undefined\n): Ownership | undefined {\n const original = token && reviews.get(token);\n return original?.ownership.current() ? { ...original.ownership } : undefined;\n}\nexport function closeNewListingReadiness(token: NewListingReadiness): void {\n reviews.get(token)?.close();\n}\n",
+ sha256: '0f88210b837998dbc459986e2648e0a11f3a688451a9a60f1da58d3b9d1d6e1d'
+ },
+ 'src/lib/publishing/listing-editor.ts': {
+ source:
+ "import {\n exactLocalFields,\n type PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId, newLocalId } from '../private-handles.ts';\nimport type { InboxSetupView } from '../messaging/inbox-setup-view.ts';\nimport {\n captureNewListingReadiness,\n closeNewListingReadiness,\n type NewListingReadiness\n} from './new-listing-readiness.ts';\nimport {\n reviewNewListing,\n listingReviewSnapshot,\n listingReviewOwnership,\n type ListingReview,\n type ListingReviewResult\n} from './prepare-listing.ts';\nimport { decodeProductReference } from '../nostr/references.ts';\nimport {\n openOwnedEditSource,\n ownedEditSourceSnapshot,\n authorizeOwnedEditSource,\n closeOwnedEditSource,\n type OwnedEditSource\n} from './edit-source.ts';\nimport type { PublicRuntime } from '../runtime/public-runtime.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicPublicationRepository,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport {\n publicDraftRepositoryOwner,\n type PublicDraftRepository\n} from '../persistence/drafts.ts';\nimport {\n createPublicDraftController,\n publicDraftControllerSnapshot,\n editPublicDraft,\n flushPublicDraft,\n retryPublicDraft,\n saveAndClosePublicDraft,\n closePublicDraftController,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n identityViewSession,\n identityViewMatchesOwner,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport {\n identitySessionSnapshot,\n subscribeIdentityInvalidation\n} from '../runtime/identity-session.ts';\nimport {\n readListingOperationView,\n closeListingOperationView,\n type ListingOperationView\n} from './listing-operation-view.ts';\n\ndeclare const editorBrand: unique symbol;\nexport type ListingEditor = Readonly<{ [editorBrand]: true }>;\nexport type ListingEditorRoute =\n | Readonly<{ mode: 'new' }>\n | Readonly<{ mode: 'draft'; draftId: string }>\n | Readonly<{ mode: 'edit'; naddr: string }>;\nexport type ListingEditorSnapshot = Readonly<{\n mode: ListingEditorRoute['mode'];\n owner: string;\n form: PublicDraftForm;\n editable: boolean;\n draftId: string | null;\n state: 'editing' | 'saving' | 'saved' | 'failed' | 'read-only';\n failure: string | null;\n coordinate: string | null;\n sourceEventId: string | null;\n sourcePublishedAtSeconds?: number;\n operations: readonly ListingOperationView[];\n}>;\ntype Editor = Readonly<{\n current(): boolean;\n retire(): void;\n snapshot(): ListingEditorSnapshot | undefined;\n edit(form: unknown): Promise<boolean>;\n flush(): Promise<boolean>;\n saveClose(): Promise<boolean>;\n review(\n setup: InboxSetupView | undefined,\n form: PublicDraftForm\n ): Promise<ListingReviewResult>;\n reviewCurrent(review: ListingReview): boolean;\n source(): OwnedEditSource | undefined;\n observe(): void;\n subscribe(listener: () => void): () => void;\n}>;\nconst editors = new WeakMap<ListingEditor, Editor>();\nconst active = new WeakMap<\n IdentityViewContext,\n Readonly<{ stamp: symbol; retire(): void }>\n>();\nconst emptyForm: PublicDraftForm = {\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n};\nfunction routeSnapshot(value: unknown): ListingEditorRoute | undefined {\n try {\n if (exactLocalFields(value, ['mode']) && value.mode === 'new')\n return { mode: 'new' };\n if (\n exactLocalFields(value, ['mode', 'draftId']) &&\n value.mode === 'draft'\n ) {\n const draftId = canonicalLocalId(value.draftId);\n return draftId ? { mode: 'draft', draftId } : undefined;\n }\n if (exactLocalFields(value, ['mode', 'naddr']) && value.mode === 'edit') {\n const reference = decodeProductReference(value.naddr);\n return reference ? { mode: 'edit', naddr: reference.naddr } : undefined;\n }\n } catch {\n return;\n }\n}\n// Owner admission precedes database opening and all protected hydration. Edit\n// mode presents validated local values; independent head authorization is later.\nexport async function openListingEditor(\n context: IdentityViewContext,\n input: unknown,\n signal?: AbortSignal,\n runtime?: PublicRuntime\n): Promise<\n | Readonly<{ status: 'ready'; editor: ListingEditor }>\n | Readonly<{\n status: 'unavailable';\n reason: 'owner' | 'resource' | 'storage' | 'source';\n }>\n> {\n const session = identityViewSession(context),\n route = routeSnapshot(input);\n if (!session || signal?.aborted)\n return { status: 'unavailable', reason: 'owner' };\n const identity = identitySessionSnapshot(session),\n owner = 'publicKey' in identity ? identity.publicKey : undefined;\n if (!owner || !identityViewMatchesOwner(context, owner))\n return { status: 'unavailable', reason: 'owner' };\n if (\n !route ||\n (route.mode === 'edit' &&\n decodeProductReference(route.naddr)?.pubkey !== owner)\n )\n return { status: 'unavailable', reason: 'resource' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable', reason: 'storage' };\n active.get(context)?.retire();\n const stamp = Symbol(),\n listeners = new Map<symbol, () => void>(),\n cancellation = new AbortController();\n let alive = true,\n closing = false,\n unsubscribe = () => {},\n database: BrowserDatabase | undefined,\n repository: PublicDraftRepository | undefined,\n controller: PublicDraftController | undefined;\n const operations = new Map<string, ListingOperationView>();\n let editSource: OwnedEditSource | undefined;\n let acquiringEditDraft:\n Promise<PublicDraftController | undefined> | undefined;\n let reviewed:\n | {\n setup: InboxSetupView | undefined;\n proof: NewListingReadiness;\n review: ListingReview;\n }\n | undefined;\n let reviewing: Promise<ListingReviewResult> | undefined;\n let reviewingForm: string | undefined;\n let reviewingSetup: InboxSetupView | undefined;\n function clearReview() {\n if (reviewed) closeNewListingReadiness(reviewed.proof);\n reviewed = undefined;\n }\n function current() {\n return (\n alive &&\n active.get(context)?.stamp === stamp &&\n identityViewSession(context) === session &&\n identityViewMatchesOwner(context, owner) &&\n (!repository || publicDraftRepositoryOwner(repository) === owner)\n );\n }\n let notifying = false;\n function notify() {\n if (notifying) return;\n notifying = true;\n try {\n for (const [key, listener] of Array.from(listeners.entries()))\n if (listeners.get(key) === listener) {\n try {\n listener();\n } catch {\n /*Presentation observers cannot authorize or retain ownership.*/\n }\n }\n } finally {\n notifying = false;\n }\n }\n function retire() {\n if (!alive) return;\n alive = false;\n unsubscribe();\n signal?.removeEventListener('abort', retire);\n cancellation.abort();\n clearReview();\n if (editSource) closeOwnedEditSource(editSource);\n if (controller) closePublicDraftController(controller);\n for (const operation of operations.values())\n closeListingOperationView(operation);\n if (database) closeBrowserDatabase(database);\n if (active.get(context)?.stamp === stamp) active.delete(context);\n notify();\n listeners.clear();\n }\n active.set(context, { stamp, retire });\n unsubscribe = subscribeIdentityInvalidation(session, retire);\n signal?.addEventListener('abort', retire, { once: true });\n if (signal?.aborted) retire();\n function unavailable(reason: 'resource' | 'storage' | 'source') {\n retire();\n return { status: 'unavailable' as const, reason };\n }\n try {\n const opened = await openBrowserDatabase(cancellation.signal);\n if (opened.state !== 'ready') return unavailable('storage');\n if (!current()) {\n closeBrowserDatabase(opened.owner);\n return unavailable('storage');\n }\n database = opened.owner;\n const publications = createPublicPublicationRepository(database, owner);\n repository = publications && publicPublicationDraftRepository(publications);\n if (!publications || !repository || !current())\n return unavailable('storage');\n const drafts = repository;\n let sourceForm: PublicDraftForm | undefined,\n coordinate: string | null = null,\n sourceEventId: string | null = null;\n if (route.mode === 'edit') {\n editSource = await openOwnedEditSource(\n publications,\n context,\n route.naddr,\n runtime,\n cancellation.signal\n );\n if (!current()) return unavailable('source');\n const retained = editSource && ownedEditSourceSnapshot(editSource);\n if (!retained) return unavailable('source');\n sourceForm = retained.form;\n coordinate = route.naddr;\n sourceEventId = retained.sourceEventId;\n } else {\n const acquired = await createPublicDraftController(\n drafts,\n emptyForm,\n route.mode === 'draft' ? route.draftId : undefined\n );\n if (!current()) {\n if (acquired) closePublicDraftController(acquired);\n return unavailable('resource');\n }\n controller = acquired;\n if (!controller) return unavailable('resource');\n if (route.mode === 'draft') {\n const quota = publicPublicationQuotaRepository(publications);\n if (!quota) return unavailable('source');\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) return unavailable('source');\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) return unavailable('source');\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(publications, item.id);\n if (!current()) return unavailable('source');\n const row =\n read.status === 'found' &&\n publicRecordSnapshot(read.record, owner, item.id);\n if (!row || row.family !== 'public_operation')\n return unavailable('source');\n if (row.source.type !== 'draft' || row.source.id !== route.draftId)\n continue;\n if (operations.size >= 100) return unavailable('source');\n const operation = await readListingOperationView(\n publications,\n session,\n item.id\n );\n if (!current()) {\n if (operation.status === 'found')\n closeListingOperationView(operation.view);\n return unavailable('source');\n }\n if (operation.status !== 'found') return unavailable('source');\n operations.set(item.id, operation.view);\n }\n }\n }\n if (!current()) return unavailable('source');\n function reviewCurrent(review: ListingReview) {\n const preview = listingReviewSnapshot(review),\n local = controller && publicDraftControllerSnapshot(controller);\n return !!(\n current() &&\n !closing &&\n !operations.size &&\n route &&\n route.mode !== 'edit' &&\n reviewed?.review === review &&\n listingReviewOwnership(review)?.current() &&\n preview &&\n local?.state === 'saved' &&\n local.draft &&\n preview.owner === owner &&\n preview.draftId === local.draft.id &&\n preview.draftRevision === local.draft.revision &&\n JSON.stringify(preview.form) === JSON.stringify(local.form)\n );\n }\n const value: Editor = {\n current,\n retire,\n source: () => (current() ? editSource : undefined),\n observe: () => {\n if (current()) notify();\n },\n snapshot() {\n if (!current()) {\n retire();\n return;\n }\n const local = controller && publicDraftControllerSnapshot(controller);\n return {\n mode: route.mode,\n owner,\n form: local ? local.form : { ...(sourceForm ?? emptyForm) },\n editable:\n operations.size === 0 &&\n (route.mode !== 'edit' ||\n !!(editSource && authorizeOwnedEditSource(editSource))),\n draftId: local?.draft?.id ?? null,\n state:\n local && operations.size === 0\n ? local.state === 'closed'\n ? 'failed'\n : local.state\n : 'read-only',\n failure: local?.failure ?? null,\n coordinate,\n sourceEventId,\n ...(editSource\n ? {\n sourcePublishedAtSeconds:\n ownedEditSourceSnapshot(editSource)?.publishedAtSeconds\n }\n : {}),\n operations: Array.from(operations.values())\n };\n },\n async edit(input) {\n if (!current()) {\n retire();\n return false;\n }\n if (route.mode === 'edit') {\n if (\n !editSource ||\n !authorizeOwnedEditSource(editSource) ||\n !sourceForm\n )\n return false;\n if (!controller) {\n acquiringEditDraft ??= createPublicDraftController(\n drafts,\n sourceForm\n );\n const acquired = await acquiringEditDraft;\n if (!current() || !authorizeOwnedEditSource(editSource)) {\n if (acquired) closePublicDraftController(acquired);\n return false;\n }\n controller = acquired;\n }\n }\n if (!controller || operations.size) return false;\n if (!editPublicDraft(controller, input)) return false;\n clearReview();\n notify();\n const pending = flushPublicDraft(controller);\n await Promise.resolve();\n if (!current()) {\n retire();\n return false;\n }\n notify();\n const saved = await pending;\n if (!current()) {\n retire();\n return false;\n }\n notify();\n return saved;\n },\n async flush() {\n if (!current()) {\n retire();\n return false;\n }\n if (!controller || operations.size) return false;\n const pending = flushPublicDraft(controller);\n await Promise.resolve();\n if (!current()) {\n retire();\n return false;\n }\n notify();\n const saved = await pending;\n if (!current()) {\n retire();\n return false;\n }\n notify();\n return saved;\n },\n async saveClose() {\n if (!current() || !controller || operations.size || closing)\n return false;\n closing = true;\n try {\n if (publicDraftControllerSnapshot(controller)?.state === 'failed') {\n const retried = await retryPublicDraft(controller);\n if (!current()) {\n retire();\n return false;\n }\n notify();\n if (!retried) return false;\n }\n const saved = await saveAndClosePublicDraft(controller);\n if (!current()) {\n retire();\n return false;\n }\n if (!saved) {\n notify();\n return false;\n }\n retire();\n return true;\n } finally {\n closing = false;\n }\n },\n review(setup, input) {\n const local = controller && publicDraftControllerSnapshot(controller);\n if (\n !current() ||\n closing ||\n !controller ||\n !local ||\n route.mode === 'edit' ||\n operations.size ||\n !exactLocalFields(input, Object.keys(emptyForm)) ||\n JSON.stringify(input) !== JSON.stringify(local.form)\n )\n return Promise.resolve({\n status: 'blocked',\n reason: 'invalid_scope'\n });\n if (\n reviewed &&\n reviewed.setup === setup &&\n reviewCurrent(reviewed.review)\n )\n return Promise.resolve({ status: 'review', review: reviewed.review });\n const formWire = JSON.stringify(local.form);\n if (reviewing)\n return reviewingForm === formWire && reviewingSetup === setup\n ? reviewing\n : Promise.resolve({ status: 'blocked', reason: 'conflict' });\n clearReview();\n const proof = captureNewListingReadiness(\n session,\n setup,\n 'reviewed_new_listing_inbox'\n ),\n command = newLocalId();\n if (!proof || !command) {\n if (proof) closeNewListingReadiness(proof);\n return Promise.resolve({ status: 'blocked', reason: 'unavailable' });\n }\n const original = controller;\n reviewingForm = formWire;\n reviewingSetup = setup;\n const pending = reviewNewListing(\n publications,\n original,\n proof,\n command,\n 'reviewed_new_listing'\n )\n .then((result): ListingReviewResult => {\n const actual = publicDraftControllerSnapshot(original);\n if (\n !current() ||\n closing ||\n !actual ||\n JSON.stringify(actual.form) !== formWire ||\n result.status !== 'review'\n ) {\n closeNewListingReadiness(proof);\n return result.status === 'blocked'\n ? result\n : { status: 'blocked', reason: 'conflict' };\n }\n reviewed = { setup, proof, review: result.review };\n if (!reviewCurrent(result.review)) {\n clearReview();\n return { status: 'blocked', reason: 'conflict' };\n }\n return result;\n })\n .finally(() => {\n if (reviewing === pending) {\n reviewing = undefined;\n reviewingForm = undefined;\n reviewingSetup = undefined;\n }\n });\n reviewing = pending;\n return pending;\n },\n reviewCurrent,\n subscribe(listener) {\n if (!current()) return () => {};\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n }\n };\n const editor = Object.freeze({}) as ListingEditor;\n editors.set(editor, value);\n return { status: 'ready', editor };\n } catch {\n return unavailable('storage');\n }\n}\nexport function listingEditorSnapshot(\n editor: ListingEditor\n): ListingEditorSnapshot | undefined {\n return editors.get(editor)?.snapshot();\n}\nexport function editListingEditor(\n editor: ListingEditor,\n form: unknown\n): Promise<boolean> {\n return editors.get(editor)?.edit(form) ?? Promise.resolve(false);\n}\nexport function flushListingEditor(editor: ListingEditor): Promise<boolean> {\n return editors.get(editor)?.flush() ?? Promise.resolve(false);\n}\nexport function closeListingEditor(editor: ListingEditor): void {\n editors.get(editor)?.retire();\n}\nexport function listingEditorEditSource(\n editor: ListingEditor\n): OwnedEditSource | undefined {\n return editors.get(editor)?.source();\n}\nexport function observeListingEditor(editor: ListingEditor): void {\n editors.get(editor)?.observe();\n}\nexport function saveAndCloseListingEditor(\n editor: ListingEditor\n): Promise<boolean> {\n return editors.get(editor)?.saveClose() ?? Promise.resolve(false);\n}\nexport function subscribeListingEditor(\n editor: ListingEditor,\n listener: () => void\n): () => void {\n return editors.get(editor)?.subscribe(listener) ?? (() => {});\n}\n// Original editor custody remains private. Review never reserves or signs.\nexport function reviewListingEditor(\n editor: ListingEditor,\n setup: InboxSetupView | undefined,\n form: PublicDraftForm\n): Promise<ListingReviewResult> {\n return (\n editors.get(editor)?.review(setup, form) ??\n Promise.resolve({ status: 'blocked', reason: 'invalid_scope' })\n );\n}\nexport function listingEditorReviewCurrent(\n editor: ListingEditor,\n review: ListingReview\n): boolean {\n return editors.get(editor)?.reviewCurrent(review) ?? false;\n}\n",
+ sha256: 'fa2c698892b820f10adc0c816641da6a2c40b5cfc3df8db2880f61659d81b4ec'
+ },
+ 'src/lib/publishing/edit-source.ts': {
+ source:
+ "import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport {\n projectFoodParts,\n type FoodProjection\n} from '../contracts/food-availability-v1/read.ts';\nimport type { PublicDraftForm } from '../contracts/local-records.ts';\nimport { decodeProductReference } from '../nostr/references.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport {\n publicPublicationOwner,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from '../persistence/public-publications.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport { readPublicDraft } from '../persistence/drafts.ts';\nimport {\n identityViewSession,\n identityViewMatchesOwner,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n publicViewOwnsRun,\n publicViewRunCurrent,\n publicViewProjectionAvailable,\n type PublicRuntime,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n createPublicViewHeadResolver,\n resolveHeads,\n headResolutionSnapshot,\n closeHeadResolver,\n type HeadResolver\n} from '../catalog/resolve-head.ts';\nimport { createPublicHeadCandidate, publicHeadKey } from '../catalog/heads.ts';\n\ndeclare const sourceBrand: unique symbol;\nexport type OwnedEditSource = Readonly<{ [sourceBrand]: true }>;\nexport type OwnedEditSourceSnapshot = Readonly<{\n owner: string;\n coordinate: string;\n sourceEventId: string;\n sourceCommand: string;\n publishedAtSeconds: number;\n form: PublicDraftForm;\n status:\n 'read-only' | 'checking' | 'ready' | 'partial' | 'conflict' | 'withdrawn';\n current?: FoodProjection;\n currentEventId?: string;\n definitiveAbsence: false;\n}>;\ntype Source = {\n snapshot(): OwnedEditSourceSnapshot | undefined;\n authorize():\n | Readonly<{\n repository: PublicPublicationRepository;\n owner: string;\n coordinate: string;\n baseWire: string;\n sourceCommand: string;\n publishedAtSeconds: number;\n current(): boolean;\n }>\n | undefined;\n close(): void;\n};\nconst sources = new WeakMap<OwnedEditSource, Source>();\n// Retained prototype custody precedes network work. A public/Tera event, a\n// snapshot, or an arbitrary same-author signature is not adopted as local source.\nexport async function openOwnedEditSource(\n repository: PublicPublicationRepository,\n context: IdentityViewContext,\n value: unknown,\n runtime?: PublicRuntime,\n signal?: AbortSignal\n): Promise<OwnedEditSource | undefined> {\n let view: PublicView | undefined, resolver: HeadResolver | undefined;\n let closed = false,\n off = () => {};\n function close() {\n if (closed) return;\n closed = true;\n off();\n signal?.removeEventListener('abort', close);\n try {\n if (resolver) closeHeadResolver(resolver);\n } finally {\n if (view) disposePublicView(view);\n }\n }\n try {\n const owner = publicPublicationOwner(repository),\n session = identityViewSession(context),\n reference = decodeProductReference(value),\n drafts = publicPublicationDraftRepository(repository),\n quota = publicPublicationQuotaRepository(repository);\n if (\n !owner ||\n !session ||\n !reference ||\n reference.pubkey !== owner ||\n !drafts ||\n !quota ||\n signal?.aborted ||\n !identityViewMatchesOwner(context, owner)\n )\n return;\n const current = () =>\n !closed &&\n !signal?.aborted &&\n identityViewSession(context) === session &&\n identityViewMatchesOwner(context, owner) &&\n publicPublicationOwner(repository) === owner;\n off = subscribeIdentityInvalidation(session, close);\n signal?.addEventListener('abort', close, { once: true });\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) {\n close();\n return;\n }\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) {\n close();\n return;\n }\n let retained:\n | Readonly<{\n form: PublicDraftForm;\n wire: string;\n command: string;\n publishedAt: number;\n eventId: string;\n }>\n | undefined;\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(repository, item.id);\n if (!current()) {\n close();\n return;\n }\n const row =\n read.status === 'found' &&\n publicRecordSnapshot(read.record, owner, item.id);\n // Incomplete critical storage is not an absence that permits adoption.\n if (!row || row.family !== 'public_operation') {\n close();\n return;\n }\n if (\n row.capture.kind !== 30402 ||\n !row.artifact ||\n row.source.type !== 'draft'\n )\n continue;\n const template = inspectLocalTemplate(row.capture.wire, owner, 30402),\n projected = template && projectFoodParts(template);\n if (\n !template ||\n !projected ||\n projected.outcome !== 'focused' ||\n projected.projection.identifier !== reference.identifier\n )\n continue;\n const source = await readPublicDraft(drafts, row.source.id);\n if (!current()) {\n close();\n return;\n }\n if (!source.ok || source.value.revision !== row.source.revision) continue;\n const form = source.value.form,\n food = projected.projection;\n if (form.contactType === '' && form.contactValue !== '') continue;\n const built = buildFoodTemplate({\n identifier: food.identifier,\n title: form.title,\n description: form.description,\n location: form.location,\n amount: form.amount,\n currency: form.currency,\n unit: form.unit,\n ...(form.quantity === '' ? {} : { quantity: form.quantity }),\n published_at: food.published_at,\n created_at: template.created_at,\n status: food.status,\n ...(form.contactType === ''\n ? {}\n : {\n contact: {\n type: form.contactType,\n value: form.contactValue,\n public: true as const\n }\n })\n });\n if (\n !built.ok ||\n JSON.stringify({\n pubkey: owner,\n kind: 30402,\n created_at: template.created_at,\n tags: built.wire_parts.tags,\n content: built.wire_parts.content\n }) !== row.capture.wire\n )\n continue;\n const verified = verifyEnvelope(row.artifact.wire),\n signed = verified.ok && verifiedEnvelopeSnapshot(verified.value);\n if (\n !signed ||\n signed.id !== row.artifact.eventId ||\n signed.id !== row.capture.hash ||\n JSON.stringify({\n pubkey: signed.pubkey,\n kind: signed.kind,\n created_at: signed.created_at,\n tags: signed.tags,\n content: signed.content\n }) !== row.capture.wire\n )\n continue;\n if (retained) {\n close();\n return;\n }\n retained = {\n form,\n wire: row.artifact.wire,\n command: row.id,\n publishedAt: food.published_at,\n eventId: signed.id\n };\n }\n if (!retained || !current()) {\n close();\n return;\n }\n const base = retained,\n proof = verifyEnvelope(base.wire);\n const head = proof.ok && createPublicHeadCandidate(proof.value);\n if (!head) {\n close();\n return;\n }\n const key = publicHeadKey(head);\n let run: ReturnType<typeof beginPublicViewRun> | undefined;\n if (runtime) {\n // A separate view/run and exact coordinate+deletion requests are independent\n // of keyword search. Genuine retained proof seeds the ordinary selector.\n view = createPublicView(runtime);\n run = beginPublicViewRun(view);\n resolver = createPublicViewHeadResolver(view, run, {\n nowSeconds: () => Math.floor(Date.now() / 1000)\n });\n resolveHeads(resolver, [head]);\n }\n const networkOwned = () =>\n !!(\n view &&\n run &&\n publicViewOwnsRun(view, run) &&\n publicViewProjectionAvailable(view)\n );\n function snapshot(): OwnedEditSourceSnapshot | undefined {\n if (!current()) {\n close();\n return;\n }\n const row =\n resolver && networkOwned()\n ? headResolutionSnapshot(resolver).find((row) => row.key === key)\n : undefined;\n const scopes = row && [row.headSources, row.deletionSources];\n const complete = !!(\n row &&\n view &&\n run &&\n publicViewRunCurrent(view, run) &&\n row.coverage === 'bounded-eose' &&\n !row.lastKnown &&\n scopes?.every(\n (scope) =>\n scope?.state === 'eose' && scope.result.coverage === 'bounded-eose'\n )\n );\n const competing = row && row.state.head.id !== base.eventId;\n const status: OwnedEditSourceSnapshot['status'] = !runtime\n ? 'read-only'\n : row?.deletion.outcome === 'suppressed'\n ? 'withdrawn'\n : competing\n ? 'conflict'\n : complete &&\n row?.state.food &&\n row.state.display === 'focused_known'\n ? 'ready'\n : scopes?.some((scope) => scope?.state === 'active')\n ? 'checking'\n : 'partial';\n return {\n owner: owner!,\n coordinate: reference!.naddr,\n sourceEventId: base.eventId,\n sourceCommand: base.command,\n publishedAtSeconds: base.publishedAt,\n form: { ...base.form },\n status,\n ...(row?.state.food ? { current: row.state.food } : {}),\n ...(row ? { currentEventId: row.state.head.id } : {}),\n definitiveAbsence: false\n };\n }\n const token = Object.freeze({}) as OwnedEditSource;\n sources.set(token, {\n snapshot,\n close,\n authorize() {\n if (snapshot()?.status !== 'ready') return;\n return {\n repository,\n owner,\n coordinate: reference.naddr,\n baseWire: base.wire,\n sourceCommand: base.command,\n publishedAtSeconds: base.publishedAt,\n current: () => snapshot()?.status === 'ready'\n };\n }\n });\n return token;\n } catch {\n close();\n return;\n }\n}\nexport function ownedEditSourceSnapshot(\n source: OwnedEditSource\n): OwnedEditSourceSnapshot | undefined {\n return sources.get(source)?.snapshot();\n}\n// Internal original edit custody only, never a signing/delivery lease.\nexport function authorizeOwnedEditSource(source: OwnedEditSource) {\n return sources.get(source)?.authorize();\n}\nexport function closeOwnedEditSource(source: OwnedEditSource): void {\n sources.get(source)?.close();\n}\n",
+ sha256: '985634e4c4eb2cd12839409552b1c56cd518021d4f031166a3c1ab8c4a0e7eff'
+ },
+ 'src/lib/runtime/public-runtime.ts': {
+ source:
+ "import { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport type { RelayPolicy } from '../config/relays.ts';\nimport { qualifiedNip50Sources } from '../nostr/search-sources.ts';\nimport {\n getPublicPool,\n subscribePublicPool,\n closePublicPool,\n type PublicPool\n} from '../nostr/public-pool.ts';\nimport {\n getPublicStore,\n insertPublicEnvelope,\n closePublicStore,\n publicStoreRetention,\n publicStoreKnownEvidence,\n publicStoreEnvelope,\n type PublicStore\n} from '../nostr/public-store.ts';\nimport {\n createPublicScheduler,\n createPublicRun,\n openPublicRequest,\n openInboxRequest,\n disposePublicRun,\n closePublicScheduler,\n publicRunSnapshot,\n type PublicScheduler,\n type PublicRun,\n type PublicRequest,\n type RequestKind,\n type RequestClock\n} from '../nostr/request-scope.ts';\nimport type { PublicFilter } from '../nostr/exports.ts';\nimport { inboxPreferenceQueries } from '../nostr/inbox-queries.ts';\nimport {\n publicHeadEnvelope,\n publicHeadSnapshot,\n type PublicHead\n} from '../catalog/heads.ts';\nimport type { KnownPublicEvidence } from '../catalog/retention.ts';\nimport type { VerifiedEnvelope } from '../nostr/verified-envelope.ts';\ndeclare const contextBrand: unique symbol;\ndeclare const runtimeBrand: unique symbol;\ndeclare const viewBrand: unique symbol;\nexport type PublicRuntimeContext = Readonly<{ readonly [contextBrand]: true }>;\nexport type PublicRuntime = Readonly<{ readonly [runtimeBrand]: true }>;\nexport type PublicView = Readonly<{ readonly [viewBrand]: true }>;\nexport const PUBLIC_RUNTIME_CONTEXT = 'harvestcircle_public_runtime';\ninterface RuntimeOwner {\n readonly pool: PublicPool;\n readonly store: PublicStore;\n readonly scheduler: PublicScheduler;\n readonly policy: RelayPolicy;\n readonly views: Map<PublicView, () => boolean>;\n readonly closed: () => boolean;\n readonly projectionValid: (retry?: boolean) => boolean;\n readonly invalidateProjection: () => void;\n readonly close: () => void;\n}\ninterface ContextOwner {\n readonly value: () => PublicRuntime | undefined;\n readonly mount: (\n policy: RelayPolicy,\n clock?: RequestClock\n ) => PublicRuntime | undefined;\n readonly ready: Promise<PublicRuntime | undefined>;\n readonly close: () => void;\n}\ninterface ViewOwner {\n readonly runtime: RuntimeOwner;\n readonly begin: () => PublicRun;\n readonly current: (run: PublicRun) => boolean;\n readonly settling: () => boolean;\n readonly settleWith: (refresh: () => void) => void;\n readonly dispose: () => boolean;\n}\nconst contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(),\n runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(),\n views = new WeakMap<PublicView, ViewOwner>();\nlet browserContext: PublicRuntimeContext | undefined;\nfunction contextOf(token: PublicRuntimeContext): ContextOwner {\n const owner = contexts.get(token);\n if (!owner) throw new Error('public_runtime_context_invalid');\n return owner;\n}\nfunction runtimeOf(token: PublicRuntime): RuntimeOwner {\n const owner = runtimes.get(token);\n if (!owner) throw new Error('public_runtime_invalid');\n if (owner.closed()) throw new Error('public_runtime_closed');\n return owner;\n}\nfunction viewOf(token: PublicView): ViewOwner {\n const owner = views.get(token);\n if (!owner) throw new Error('public_view_invalid');\n return owner;\n}\n// Context construction is SSR-pure. Root onMount acquires the browser lifetime;\n// children can await readiness even when their onMount runs before the root's.\nexport function createPublicRuntimeContext(): PublicRuntimeContext {\n let value: PublicRuntime | undefined,\n closed = false;\n let ready: (value: PublicRuntime | undefined) => void = () => {};\n let selectedClock: RequestClock | undefined;\n const promise = new Promise<PublicRuntime | undefined>((resolve) => {\n ready = resolve;\n });\n const owner: ContextOwner = {\n value: () => (closed ? undefined : value),\n ready: promise,\n mount(policy, clock) {\n if (closed) throw new Error('public_runtime_closed');\n if (typeof window === 'undefined') return undefined;\n if (value) {\n const prior = runtimes.get(value);\n if (!prior || prior.policy !== policy)\n throw new Error('public_runtime_policy_changed');\n if (clock !== selectedClock)\n throw new Error('public_runtime_clock_changed');\n return value;\n }\n if (browserContext && browserContext !== contextToken)\n throw new Error('public_runtime_owner_changed');\n const pool = getPublicPool(policy),\n store = getPublicStore();\n if (!pool || !store) return undefined;\n const scheduler = createPublicScheduler(clock),\n registered = new Map<PublicView, () => boolean>();\n let terminal = false,\n invalidated = false,\n invalidating = false;\n const token = Object.freeze({}) as PublicRuntime;\n const runtime: RuntimeOwner = {\n pool,\n store,\n scheduler,\n policy,\n views: registered,\n closed: () => terminal,\n projectionValid(retry = true) {\n const retained = publicStoreRetention(store);\n if (retained.stopped || (!terminal && retained.closed))\n invalidated = true;\n // A settler reads the terminal flag without recursively retrying its\n // own disposal. The outer cleanup loop keeps failed controls live.\n if (invalidated && retry) runtime.invalidateProjection();\n return !invalidated;\n },\n invalidateProjection() {\n invalidated = true;\n if (invalidating) return;\n invalidating = true;\n let failed = false;\n try {\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n } finally {\n invalidating = false;\n }\n if (failed) throw new Error('public_projection_close_failed');\n },\n close() {\n terminal = true;\n let failed = false;\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n // Reentrant or failed settlement cannot preserve a coherent projection\n // across store teardown. Terminal uncertainty clears every view.\n if (failed) invalidated = true;\n try {\n closePublicScheduler(scheduler);\n } catch {\n failed = true;\n }\n try {\n closePublicPool(pool);\n } catch {\n failed = true;\n }\n try {\n closePublicStore(store);\n } catch {\n failed = true;\n }\n if (failed) throw new Error('public_runtime_close_failed');\n }\n };\n runtimes.set(token, runtime);\n value = token;\n browserContext = contextToken;\n selectedClock = clock;\n ready(token);\n return token;\n },\n close() {\n closed = true;\n ready(undefined);\n if (value) {\n const runtime = runtimes.get(value);\n if (runtime) runtime.close();\n }\n }\n };\n const contextToken = Object.freeze({}) as PublicRuntimeContext;\n contexts.set(contextToken, owner);\n return contextToken;\n}\nexport function publicRuntime(\n context: PublicRuntimeContext\n): PublicRuntime | undefined {\n return contextOf(context).value();\n}\nexport function publicRuntimeReady(\n context: PublicRuntimeContext\n): Promise<PublicRuntime | undefined> {\n return contextOf(context).ready;\n}\nexport function mountPublicRuntime(\n context: PublicRuntimeContext,\n policy: RelayPolicy = deploymentRelayPolicy,\n clock?: RequestClock\n): PublicRuntime | undefined {\n return contextOf(context).mount(policy, clock);\n}\nexport function closePublicRuntime(context: PublicRuntimeContext): void {\n contextOf(context).close();\n}\nexport function createPublicView(runtime: PublicRuntime): PublicView {\n const shared = runtimeOf(runtime);\n if (!shared.projectionValid())\n throw new Error('public_projection_unavailable');\n const token = Object.freeze({}) as PublicView;\n let run: PublicRun | undefined,\n disposed = false;\n let generation = 0,\n settler: (() => void) | undefined,\n settling = false;\n function settle() {\n const refresh = settler;\n settler = undefined; // Detach before any caller-controlled clock reentry.\n if (!refresh) return;\n settling = true;\n try {\n refresh?.();\n } catch (error) {\n if (!settler) settler = refresh;\n throw error;\n } finally {\n settling = false;\n }\n }\n const owner: ViewOwner = {\n runtime: shared,\n begin() {\n if (disposed || shared.closed() || !shared.projectionValid())\n throw new Error('public_view_closed');\n const operation = ++generation,\n previous = run;\n // Generation reserves the transition; keep failed old controls retryable.\n try {\n settle();\n } finally {\n if (previous) disposePublicRun(previous);\n }\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n )\n throw new Error('public_view_run_superseded');\n const candidate = createPublicRun(shared.scheduler, shared.policy);\n // Run creation samples the injected clock. It may synchronously start a\n // newer view generation before returning; never overwrite that owner.\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n ) {\n disposePublicRun(candidate);\n throw new Error('public_view_run_superseded');\n }\n run = candidate;\n return run;\n },\n settling: () => settling,\n settleWith(refresh) {\n const previous = settler;\n settler = refresh;\n previous?.();\n },\n current(candidate) {\n return !disposed && !shared.closed() && run === candidate;\n },\n dispose() {\n disposed = true;\n generation++;\n if (settling) return false;\n try {\n settle();\n if (run) disposePublicRun(run);\n shared.views.delete(token);\n return true;\n } catch {\n return false;\n }\n }\n };\n views.set(token, owner);\n shared.views.set(token, () => owner.dispose());\n return token;\n}\nexport function beginPublicViewRun(view: PublicView): PublicRun {\n return viewOf(view).begin();\n}\nexport function publicViewRunCurrent(\n view: PublicView,\n run: PublicRun\n): boolean {\n return viewOf(view).current(run) && publicRunSnapshot(run).active;\n}\n// Ownership survives an ordinary deadline so a foreground owner can publish\n// its terminal result once. Supersession/disposal/shared closure revoke it.\nexport function publicViewOwnsRun(view: PublicView, run: PublicRun): boolean {\n return viewOf(view).current(run);\n}\nexport function disposePublicView(view: PublicView): void {\n if (!viewOf(view).dispose()) throw new Error('public_view_close_failed');\n}\nexport function subscribePublicView(\n view: PublicView,\n run: PublicRun,\n kind: RequestKind,\n filters: readonly PublicFilter[],\n onVerified: (event: VerifiedEnvelope) => void,\n sampleSource?: string\n): PublicRequest {\n const owner = viewOf(view);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n // Copy the request template once before SDK effects; caller mutations cannot\n // retarget this request. Product filter builders remain HCP038 and later.\n const frozen = JSON.stringify(filters);\n return openPublicRequest(\n run,\n kind,\n (next) =>\n subscribePublicPool(\n owner.runtime.pool,\n JSON.parse(frozen) as PublicFilter[],\n next,\n sampleSource\n ),\n (event) => {\n if (!owner.current(run)) return;\n const result = insertPublicEnvelope(owner.runtime.store, event);\n if (result === 'limit' || result === 'rejected' || result === 'closed') {\n owner.runtime.invalidateProjection();\n return;\n }\n if (\n (result === 'accepted' || result === 'duplicate') &&\n owner.current(run)\n )\n onVerified(event);\n },\n sampleSource\n );\n}\n\nexport function publicViewNip50Sources(view: PublicView): readonly string[] {\n return qualifiedNip50Sources(viewOf(view).runtime.policy);\n}\n\n// Public metadata, dedicated ownership: no preference enters the food store.\n// Fixed anonymous origins, clocks, scheduler and aggregate ingress stay shared.\nexport function subscribeInboxPreference(\n view: PublicView,\n run: PublicRun,\n author: unknown,\n onVerified: (event: VerifiedEnvelope, inboxSource?: string) => void\n): PublicRequest {\n const owner = viewOf(view),\n filters = inboxPreferenceQueries(author);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n return openInboxRequest(\n run,\n author,\n (next) => subscribePublicPool(owner.runtime.pool, filters, next),\n (event, inboxSource) => {\n if (owner.current(run)) onVerified(event, inboxSource);\n }\n );\n}\n\n// Capacity invalidation differs from ordinary teardown: last-known snapshots\n// remain available on normal close, while a breached working set clears all views.\nexport function publicViewProjectionAvailable(view: PublicView): boolean {\n const owner = viewOf(view);\n return owner.runtime.projectionValid(!owner.settling());\n}\nexport function publicViewKnownEvidence(\n view: PublicView,\n head: PublicHead\n): KnownPublicEvidence {\n return publicStoreKnownEvidence(viewOf(view).runtime.store, head);\n}\nexport function retainPublicViewHeads(\n view: PublicView,\n run: PublicRun,\n heads: readonly PublicHead[]\n): boolean {\n const owner = viewOf(view);\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n const active = publicRunSnapshot(run).active;\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n if (!active) {\n // Inactive materialization cannot install or charge another event. Require\n // every genuine head to have already passed the shared retained cache.\n for (const head of heads) {\n if (\n !publicStoreEnvelope(owner.runtime.store, publicHeadSnapshot(head).id)\n )\n throw new Error('public_view_uncached_head');\n }\n return owner.current(run) && owner.runtime.projectionValid();\n }\n for (const head of heads) {\n const result = insertPublicEnvelope(\n owner.runtime.store,\n publicHeadEnvelope(head)\n );\n if (result !== 'accepted' && result !== 'duplicate') {\n owner.runtime.invalidateProjection();\n return false;\n }\n }\n return owner.runtime.projectionValid();\n}\n\n// Trusted model binding holds only the current projection for this view.\n// Replacement/disposal settles it while retained shared lifecycle proof is live.\nexport function settlePublicViewProjection(\n view: PublicView,\n refresh: () => void\n): void {\n viewOf(view).settleWith(refresh);\n}\n",
+ sha256: 'fa2e27d72b82b6bef73693cf93f19614e61ea51ebd11eb40d8ca4ec723f0c14e'
+ },
+ 'src/lib/publishing/editor-workflow.ts': {
+ source:
+ "import {\n exactLocalFields,\n type PublicDraftForm\n} from '../contracts/local-records.ts';\nimport {\n buildFoodTemplate,\n type FoodDraftErrorCode\n} from '../contracts/food-availability-v1/write.ts';\nimport type { InboxSetupView } from '../messaging/inbox-setup-view.ts';\nimport {\n reviewListingEditor,\n listingEditorReviewCurrent,\n type ListingEditor\n} from './listing-editor.ts';\nimport {\n listingReviewSnapshot,\n type ListingReview,\n type ListingPreview\n} from './prepare-listing.ts';\n\nexport type EditorFormError = Readonly<{\n field: keyof PublicDraftForm;\n message: string;\n}>;\nconst fields = [\n 'title',\n 'description',\n 'location',\n 'amount',\n 'currency',\n 'unit',\n 'quantity',\n 'contactType',\n 'contactValue'\n] as const;\nexport function validateEditorForm(\n input: PublicDraftForm\n): readonly EditorFormError[] {\n try {\n if (\n !exactLocalFields(input, fields) ||\n fields.some((field) => typeof input[field] !== 'string')\n )\n return [{ field: 'title', message: 'Keep all listing fields as text.' }];\n if (input.contactType === '' && input.contactValue !== '')\n return [\n {\n field: 'contactValue',\n message: 'Choose a public contact type or remove the contact details.'\n }\n ];\n const built = buildFoodTemplate({\n identifier: '00000000-0000-4000-8000-000000000001',\n created_at: 1,\n published_at: 1,\n status: 'active',\n title: input.title,\n description: input.description,\n location: input.location,\n amount: input.amount,\n currency: input.currency,\n unit: input.unit,\n ...(input.quantity === '' ? {} : { quantity: input.quantity }),\n ...(input.contactType === ''\n ? {}\n : {\n contact: {\n type: input.contactType,\n value: input.contactValue,\n public: true as const\n }\n })\n });\n if (built.ok) return [];\n const messages: Partial<Record<FoodDraftErrorCode, EditorFormError>> = {\n title_invalid: {\n field: 'title',\n message: 'Use a product name within the public text limit.'\n },\n location_invalid: {\n field: 'location',\n message: 'Use a public area within the text limit.'\n },\n description_invalid: {\n field: 'description',\n message: 'Add a complete description within the public text limit.'\n },\n summary_invalid: {\n field: 'description',\n message: 'Use supported public text in the description.'\n },\n price_invalid: {\n field: 'amount',\n message: 'Use a supported price, currency and price unit.'\n },\n quantity_invalid: {\n field: 'quantity',\n message: 'Use a supported advertised quantity in the selected unit.'\n },\n contact_invalid: {\n field: 'contactValue',\n message: 'Use supported public contact details for the selected type.'\n }\n };\n return [\n messages[built.error.code] ?? {\n field: 'description',\n message: 'The public listing exceeds its supported limits.'\n }\n ];\n } catch {\n return [\n {\n field: 'title',\n message:\n 'The listing fields could not be read. Keep your current input.'\n }\n ];\n }\n}\ndeclare const reviewBrand: unique symbol;\nexport type EditorReview = Readonly<{ [reviewBrand]: true }>;\ntype Owned = Readonly<{ editor: ListingEditor; original: ListingReview }>;\nconst reviews = new WeakMap<EditorReview, Owned>();\nexport type EditorReviewSnapshot = ListingPreview &\n Readonly<{ content: string; tags: readonly (readonly string[])[] }>;\nexport async function openEditorReview(\n editor: ListingEditor,\n setup: InboxSetupView | undefined,\n form: PublicDraftForm\n): Promise<\n | Readonly<{ status: 'review'; review: EditorReview }>\n | Readonly<{\n status: 'blocked';\n errors: readonly EditorFormError[];\n message: string;\n }>\n> {\n const errors = validateEditorForm(form);\n if (errors.length)\n return {\n status: 'blocked',\n errors,\n message: 'Check the linked fields. Your input remains here.'\n };\n const result = await reviewListingEditor(editor, setup, form);\n if (\n result.status !== 'review' ||\n !listingEditorReviewCurrent(editor, result.review)\n )\n return {\n status: 'blocked',\n errors: [],\n message:\n result.status === 'blocked' && result.reason === 'unavailable'\n ? 'Enable messages before reviewing this listing. Your draft remains in this browser.'\n : 'The saved listing or account changed. Keep your input and review the current values again.'\n };\n const review = Object.freeze({}) as EditorReview;\n reviews.set(review, { editor, original: result.review });\n return { status: 'review', review };\n}\nexport function editorReviewSnapshot(\n review: EditorReview\n): EditorReviewSnapshot | undefined {\n const owned = reviews.get(review);\n if (!owned || !listingEditorReviewCurrent(owned.editor, owned.original))\n return;\n const preview = listingReviewSnapshot(owned.original);\n if (!preview) return;\n const wire = JSON.parse(preview.templateWire) as {\n content: string;\n tags: string[][];\n };\n return { ...preview, content: wire.content, tags: wire.tags };\n}\nexport function closeEditorReview(review: EditorReview): void {\n reviews.delete(review);\n}\n",
+ sha256: '5bc8827c5ff167e0974f03a87e4e9db350e42f30c511f199b785c30ad365d838'
+ },
+ 'src/lib/components/ListingEditor.svelte': {
+ source:
+ "<script lang=\"ts\">\n /* global document, setInterval, clearInterval */\n import { getContext, onMount, tick } from 'svelte';\n import ListingReview from './ListingReview.svelte';\n import ConflictNotice from './ConflictNotice.svelte';\n import InboxSetup from './InboxSetup.svelte';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n type PublicRuntimeContext,\n type PublicRuntime\n } from '../runtime/public-runtime.ts';\n import {\n createRuntimeInboxSetupView,\n inboxSetupViewSnapshot,\n subscribeInboxSetupView,\n closeInboxSetupView,\n type InboxSetupView\n } from '../messaging/inbox-setup-view.ts';\n import {\n openEditorReview,\n editorReviewSnapshot,\n closeEditorReview,\n type EditorReview,\n type EditorFormError\n } from '../publishing/editor-workflow.ts';\n import CapabilityGate from './CapabilityGate.svelte';\n import Notice from './Notice.svelte';\n import OperationStatus from './OperationStatus.svelte';\n import { foodUnits } from '../contracts/food-availability-v1/values.ts';\n import type { PublicDraftForm } from '../contracts/local-records.ts';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n type IdentityViewContext\n } from '../runtime/view-context.ts';\n import {\n openListingEditor,\n listingEditorSnapshot,\n editListingEditor,\n saveAndCloseListingEditor,\n closeListingEditor,\n subscribeListingEditor,\n listingEditorEditSource,\n observeListingEditor,\n type ListingEditor as Editor,\n type ListingEditorRoute,\n type ListingEditorSnapshot\n } from '../publishing/listing-editor.ts';\n import { internalHref } from '../navigation-url.ts';\n let {\n route,\n onfirstsave,\n onsavedclose,\n inboxController\n }: {\n route: ListingEditorRoute;\n onfirstsave?: (draftId: string, current: () => boolean) => Promise<void>;\n onsavedclose?: () => Promise<void>;\n inboxController?: InboxSetupView;\n } = $props();\n const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);\n const publicContext = getContext<PublicRuntimeContext>(\n PUBLIC_RUNTIME_CONTEXT\n );\n let runtime = $state.raw<PublicRuntime | undefined>(),\n setup = $state.raw<InboxSetupView | undefined>();\n let setupState = $state(inboxSetupViewSnapshot(undefined));\n let review = $state.raw<EditorReview | undefined>(),\n reviewBusy = $state(false);\n let errors = $state<readonly EditorFormError[]>([]),\n reviewMessage = $state('');\n let identity = $state(identityViewSnapshot(context)),\n mounted = $state(false),\n editor = $state.raw<Editor | undefined>(),\n snapshot = $state<ListingEditorSnapshot>(),\n unavailable = $state(false);\n let closeBusy = $state(false),\n navigationFailed = $state(false);\n let firstNavigation: Promise<void> | undefined;\n let firstOwner: Editor | undefined;\n type Form = {\n -readonly [Key in keyof PublicDraftForm]: PublicDraftForm[Key];\n };\n const blankForm = (): Form => ({\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n });\n let form = $state<Form>(blankForm());\n const admittedAuthor = $derived(\n identity.identity.state !== 'guest' && identity.identity.state !== 'pending'\n ? identity.identity.publicKey\n : undefined\n );\n const active = $derived(mounted && identity.mounted);\n const visible = $derived(\n snapshot &&\n editor &&\n identity.mounted &&\n identity.identity.state !== 'guest' &&\n identity.identity.state !== 'pending' &&\n identity.identity.publicKey === snapshot.owner &&\n listingEditorSnapshot(editor)\n );\n onMount(() => {\n mounted = true;\n const off = subscribeIdentityView(context, (next) => {\n identity = next;\n });\n if (publicContext)\n void publicRuntimeReady(publicContext)\n .then((value) => {\n if (mounted) runtime = value;\n })\n .catch(() => {\n /* Draft saving does not depend on inbox setup. */\n });\n return () => {\n mounted = false;\n off();\n };\n });\n $effect(() => {\n const author = admittedAuthor,\n available = active,\n source = runtime,\n supplied = inboxController;\n if (!available || !author) {\n setup = undefined;\n setupState = inboxSetupViewSnapshot(undefined);\n return;\n }\n const owned =\n supplied ?? (source && createRuntimeInboxSetupView(context, source));\n setup = owned;\n const off = owned\n ? subscribeInboxSetupView(owned, (next) => {\n setupState = next;\n })\n : () => {};\n return () => {\n off();\n if (owned) closeInboxSetupView(owned);\n };\n });\n const visibleReview = $derived.by(() => {\n if (!setupState.owner || !snapshot || !visible || !review) return;\n return editorReviewSnapshot(review) ? review : undefined;\n });\n $effect(() => {\n const resource = route,\n author = admittedAuthor,\n editRuntime = route.mode === 'edit' ? runtime : undefined;\n if (!active || !author) {\n editor = undefined;\n snapshot = undefined;\n form = blankForm();\n unavailable = false;\n return;\n }\n const cancellation = new AbortController();\n let alive = true,\n owned: Editor | undefined,\n off = () => {};\n const observer =\n resource.mode === 'edit'\n ? setInterval(() => {\n if (owned) observeListingEditor(owned);\n }, 250)\n : undefined;\n editor = undefined;\n snapshot = undefined;\n review = undefined;\n errors = [];\n reviewMessage = '';\n form = blankForm();\n unavailable = false;\n void openListingEditor(\n context,\n resource,\n cancellation.signal,\n editRuntime\n ).then((result) => {\n if (!alive) {\n if (result.status === 'ready') closeListingEditor(result.editor);\n return;\n }\n if (result.status !== 'ready') {\n unavailable = true;\n return;\n }\n owned = result.editor;\n editor = owned;\n const next = listingEditorSnapshot(owned);\n if (!next) {\n unavailable = true;\n return;\n }\n snapshot = next;\n form = { ...next.form };\n off = subscribeListingEditor(owned, () => {\n snapshot = owned && listingEditorSnapshot(owned);\n if (\n snapshot?.state === 'saved' &&\n snapshot.draftId &&\n resource.mode === 'new' &&\n owned &&\n firstOwner !== owned &&\n !closeBusy &&\n onfirstsave\n ) {\n firstOwner = owned;\n firstNavigation = onfirstsave(\n snapshot.draftId,\n () =>\n alive &&\n mounted &&\n editor === owned &&\n !!owned &&\n !!listingEditorSnapshot(owned)\n ).catch(() => {\n if (alive) navigationFailed = true;\n });\n }\n if (!snapshot) {\n unavailable = true;\n form = blankForm();\n }\n });\n });\n return () => {\n alive = false;\n if (observer !== undefined) clearInterval(observer);\n cancellation.abort();\n off();\n if (owned) closeListingEditor(owned);\n form = blankForm();\n };\n });\n function changed() {\n const original = editor;\n if (!original || !listingEditorSnapshot(original)?.editable) return;\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n void editListingEditor(original, { ...form });\n }\n async function showReview() {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (\n reviewBusy ||\n closeBusy ||\n !original ||\n !listingEditorSnapshot(original)?.editable\n )\n return;\n reviewBusy = true;\n try {\n const result = await openEditorReview(original, setup, { ...form });\n if (\n !mounted ||\n editor !== original ||\n route !== resource ||\n admittedAuthor !== author ||\n !listingEditorSnapshot(original)\n ) {\n if (result.status === 'review') closeEditorReview(result.review);\n return;\n }\n if (result.status === 'blocked') {\n errors = result.errors;\n reviewMessage = result.message;\n await tick();\n document.querySelector<HTMLElement>('#listing-review-errors')?.focus();\n return;\n }\n if (review) closeEditorReview(review);\n review = result.review;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor === original && editorReviewSnapshot(result.review))\n document.querySelector<HTMLElement>('#listing-review-heading')?.focus();\n } finally {\n reviewBusy = false;\n }\n }\n async function editDetails() {\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor && listingEditorSnapshot(editor)?.editable)\n document.querySelector<HTMLInputElement>('#listing-title')?.focus();\n }\n function fieldError(field: keyof PublicDraftForm) {\n return errors.find((value) => value.field === field);\n }\n function fieldId(field: keyof PublicDraftForm) {\n return (\n 'listing-' +\n (field === 'contactType'\n ? 'contact-type'\n : field === 'contactValue'\n ? 'contact-value'\n : field)\n );\n }\n function connect() {\n return connectIdentityView(context);\n }\n async function saveClose() {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (closeBusy || !original || !listingEditorSnapshot(original)?.editable)\n return;\n closeBusy = true;\n try {\n const saved = await saveAndCloseListingEditor(original);\n await firstNavigation;\n if (\n !saved ||\n !mounted ||\n editor !== original ||\n route !== resource ||\n !author ||\n admittedAuthor !== author\n )\n return;\n await onsavedclose?.();\n } catch {\n if (mounted) navigationFailed = true;\n } finally {\n closeBusy = false;\n }\n }\n function disconnect() {\n disconnectIdentityView(context);\n }\n const title = $derived(\n route.mode === 'new'\n ? 'New listing'\n : route.mode === 'draft'\n ? 'Continue draft'\n : 'Edit listing'\n );\n</script>\n\n<svelte:head\n ><title>{title} \u00b7 HarvestCircle</title><meta\n name=\"robots\"\n content=\"noindex\"\n /></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a\n href={internalHref(\n route.mode === 'edit' ? `/products/${route.naddr}` : '/selling'\n )}>{route.mode === 'edit' ? 'Back to listing' : 'Back to Selling'}</a\n >\n <h1>{title}</h1>\n {#if !visible}\n <CapabilityGate\n identity={identity.identity}\n required=\"connection\"\n focusTarget=\"protected\"\n onconnect={mounted ? connect : undefined}\n ondisconnect={disconnect}\n />\n {#if unavailable}<Notice\n tone=\"warning\"\n text={route.mode === 'draft'\n ? 'This draft is not available here.'\n : route.mode === 'edit'\n ? 'Supported local listing values are not available for editing. Keep this listing read-only.'\n : 'Browser storage is unavailable. Your existing local data has not been reset.'}\n />{:else if identity.identity.state !== 'guest' && identity.identity.state !== 'pending'}<p\n role=\"status\"\n >\n Loading local values.\n </p>{/if}\n {:else}\n {#if route.mode === 'edit' && editor && listingEditorEditSource(editor)}\n <ConflictNotice\n source={listingEditorEditSource(editor)!}\n proposed={form}\n />\n {#if visible.editable}<Notice\n tone=\"info\"\n text=\"These changes can be saved locally. Publishing changes is not available.\"\n />{/if}\n {/if}\n {#if !visible.editable}<Notice\n tone=\"info\"\n text={route.mode === 'draft'\n ? 'This draft has a retained listing operation. Keep its original outcome for reconciliation.'\n : 'These retained local values are read-only until the current listing is checked.'}\n />{:else}<p>\n Changes are saved in this browser. Browser storage is not a backup.\n </p>{/if}\n {#if visibleReview}<ListingReview\n review={visibleReview}\n onedit={editDetails}\n />{:else}\n {#if reviewMessage}<Notice tone=\"warning\" text={reviewMessage} />{/if}\n {#if errors.length}<div\n id=\"listing-review-errors\"\n tabindex=\"-1\"\n role=\"alert\"\n >\n <p>Check these listing fields. Your input remains here.</p>\n <ul>\n {#each errors as error (error.field)}<li>\n <a href={internalHref('#' + fieldId(error.field))}\n >{error.message}</a\n >\n </li>{/each}\n </ul>\n </div>{/if}\n <form\n class=\"stack\"\n onsubmit={(event) => event.preventDefault()}\n novalidate\n >\n <div class=\"field\">\n <label class=\"label\" for=\"listing-title\">Product name</label><input\n id=\"listing-title\"\n aria-invalid={fieldError('title') ? 'true' : undefined}\n aria-errormessage={fieldError('title')\n ? 'listing-title-error'\n : undefined}\n type=\"text\"\n value={form.title}\n oninput={(event) => {\n form = { ...form, title: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('title')}<p id=\"listing-title-error\">\n {fieldError('title')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-description\">Description</label\n ><textarea\n id=\"listing-description\"\n aria-invalid={fieldError('description') ? 'true' : undefined}\n aria-errormessage={fieldError('description')\n ? 'listing-description-error'\n : undefined}\n rows=\"6\"\n value={form.description}\n oninput={(event) => {\n form = { ...form, description: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}></textarea>\n {#if fieldError('description')}<p id=\"listing-description-error\">\n {fieldError('description')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-location\">Public area</label>\n <p id=\"listing-location-hint\" class=\"text-small\">\n A town or collection area is enough.\n </p>\n <input\n id=\"listing-location\"\n aria-invalid={fieldError('location') ? 'true' : undefined}\n aria-errormessage={fieldError('location')\n ? 'listing-location-error'\n : undefined}\n type=\"text\"\n aria-describedby=\"listing-location-hint\"\n value={form.location}\n oninput={(event) => {\n form = { ...form, location: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('location')}<p id=\"listing-location-error\">\n {fieldError('location')?.message}\n </p>{/if}\n </div>\n <div class=\"cluster\">\n <div class=\"field\">\n <label class=\"label\" for=\"listing-amount\">Price</label><input\n id=\"listing-amount\"\n aria-invalid={fieldError('amount') ? 'true' : undefined}\n aria-errormessage={fieldError('amount')\n ? 'listing-amount-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n value={form.amount}\n oninput={(event) => {\n form = { ...form, amount: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('amount')}<p id=\"listing-amount-error\">\n {fieldError('amount')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-currency\">Currency</label><input\n id=\"listing-currency\"\n aria-invalid={fieldError('currency') ? 'true' : undefined}\n aria-errormessage={fieldError('currency')\n ? 'listing-currency-error'\n : undefined}\n type=\"text\"\n maxlength=\"3\"\n value={form.currency}\n oninput={(event) => {\n form = { ...form, currency: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('currency')}<p id=\"listing-currency-error\">\n {fieldError('currency')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-unit\">Per</label><select\n id=\"listing-unit\"\n aria-invalid={fieldError('unit') ? 'true' : undefined}\n aria-errormessage={fieldError('unit')\n ? 'listing-unit-error'\n : undefined}\n value={form.unit}\n onchange={(event) => {\n form = { ...form, unit: event.currentTarget.value };\n changed();\n }}\n disabled={!visible.editable}\n ><option value=\"\">Choose a unit</option\n >{#each foodUnits as unit (unit)}<option value={unit}\n >{unit}</option\n >{/each}</select\n >\n {#if fieldError('unit')}<p id=\"listing-unit-error\">\n {fieldError('unit')?.message}\n </p>{/if}\n </div>\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-quantity\"\n >Advertised quantity (optional)</label\n >\n <p id=\"listing-quantity-unit\">\n {form.unit || 'Uses the selected price unit'}\n </p>\n <input\n id=\"listing-quantity\"\n aria-invalid={fieldError('quantity') ? 'true' : undefined}\n aria-errormessage={fieldError('quantity')\n ? 'listing-quantity-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n aria-describedby=\"listing-quantity-unit\"\n value={form.quantity}\n oninput={(event) => {\n form = { ...form, quantity: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('quantity')}<p id=\"listing-quantity-error\">\n {fieldError('quantity')?.message}\n </p>{/if}\n </div>\n <details>\n <summary>Add public contact details (optional)</summary>\n <div class=\"stack\">\n <p>Only add contact details you want to include publicly.</p>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-type\"\n >Public contact type</label\n ><select\n id=\"listing-contact-type\"\n aria-invalid={fieldError('contactType') ? 'true' : undefined}\n aria-errormessage={fieldError('contactType')\n ? 'listing-contact-type-error'\n : undefined}\n value={form.contactType}\n onchange={(event) => {\n const value = event.currentTarget.value;\n if (\n value === '' ||\n value === 'email' ||\n value === 'phone' ||\n value === 'https'\n ) {\n form = { ...form, contactType: value };\n changed();\n }\n }}\n disabled={!visible.editable}\n ><option value=\"\">No public contact</option><option\n value=\"email\">Email</option\n ><option value=\"phone\">Phone</option><option value=\"https\"\n >Website</option\n ></select\n >\n {#if fieldError('contactType')}<p id=\"listing-contact-type-error\">\n {fieldError('contactType')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-value\"\n >Public contact details</label\n ><input\n id=\"listing-contact-value\"\n aria-invalid={fieldError('contactValue') ? 'true' : undefined}\n aria-errormessage={fieldError('contactValue')\n ? 'listing-contact-value-error'\n : undefined}\n type=\"text\"\n value={form.contactValue}\n oninput={(event) => {\n form = { ...form, contactValue: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('contactValue')}<p\n id=\"listing-contact-value-error\"\n >\n {fieldError('contactValue')?.message}\n </p>{/if}\n </div>\n </div>\n </details>\n </form>\n {#if visible.editable && route.mode !== 'edit'}<button\n type=\"button\"\n onclick={showReview}\n disabled={reviewBusy || closeBusy}\n >{reviewBusy ? 'Preparing review' : 'Review listing'}</button\n >{/if}\n {/if}\n {#if visible.editable && route.mode !== 'edit' && setup}<InboxSetup\n controller={setup}\n inline\n />{/if}\n {#each visible.operations as operation (operation)}<OperationStatus\n publicOperation={operation}\n />{/each}\n {#if visible.editable}<button\n type=\"button\"\n onclick={saveClose}\n disabled={closeBusy || reviewBusy}>Save and close</button\n >{/if}\n {#if navigationFailed}<Notice\n tone=\"warning\"\n text=\"Navigation did not complete. Your saved local data remains in this browser.\"\n />{/if}\n {#if visible.editable}<p role=\"status\">\n {visible.state === 'saved'\n ? 'Saved in this browser.'\n : visible.state === 'saving'\n ? 'Saving in this browser.'\n : visible.state === 'failed'\n ? 'Not saved. Keep your current input here.'\n : 'Not yet saved.'}\n </p>\n {#if visible.failure}<Notice\n tone=\"warning\"\n text=\"Saving did not complete. Keep your current input. Existing local data has not been reset.\"\n />{/if}{/if}\n {/if}\n</div>\n",
+ sha256: '3b1d6248c256ce02a668a2c92654816dd0c2659b7b430d5e1d3aeba6f9326bfa'
+ },
+ 'src/lib/components/ListingReview.svelte': {
+ source:
+ '<script lang="ts">\n import Notice from \'./Notice.svelte\';\n import {\n editorReviewSnapshot,\n type EditorReview\n } from \'../publishing/editor-workflow.ts\';\n let { review, onedit }: { review: EditorReview; onedit: () => void } =\n $props();\n const preview = $derived(editorReviewSnapshot(review));\n function tag(name: string) {\n return (\n preview?.tags\n .find((value) => value[0] === name)\n ?.slice(1)\n .join(\' \') ?? \'\'\n );\n }\n</script>\n\n{#if preview}\n <section class="stack" aria-label="Public listing review">\n <h2 id="listing-review-heading" tabindex="-1">Public review</h2>\n <p>Check the complete public listing before any signing or publication.</p>\n <h3>{tag(\'title\')}</h3>\n <p class="description" id="listing-review-content">{preview.content}</p>\n <dl>\n <dt>Derived summary</dt>\n <dd>{preview.summary}</dd>\n <dt>Public area</dt>\n <dd>{tag(\'location\')}</dd>\n <dt>Price</dt>\n <dd>{tag(\'price\')} per {tag(\'radroots:price_unit\')}</dd>\n {#if tag(\'radroots:quantity\')}<dt>Advertised quantity</dt>\n <dd>{tag(\'radroots:quantity\')}</dd>{/if}\n <dt>Publisher</dt>\n <dd class="key">{preview.owner}</dd>\n <dt>Public destinations</dt>\n <dd>\n <ul>\n {#each preview.targets as target (target)}<li class="key">\n {target}\n </li>{/each}\n </ul>\n </dd>\n </dl>\n <p>Messages: ready to receive replies</p>\n <p>This review has not requested a signature or published the listing.</p>\n <button type="button" onclick={onedit}>Edit details</button>\n </section>\n{:else}\n <Notice\n tone="warning"\n text="This review is no longer current. Return to the current listing values."\n />\n <button type="button" onclick={onedit}>Edit details</button>\n{/if}\n',
+ sha256: 'bf4e6bf0fc76fa12672fabc441e1058d73c1f281a0a560aeafbdaa2aa36f6f90'
+ },
+ 'src/lib/persistence/public-publications.ts': {
+ source:
+ "import type { PublicDraftRecord } from '../contracts/local-records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n createPublicDraftRepository,\n publicDraftRepositoryOwner,\n type PublicDraftRepository\n} from './drafts.ts';\nimport {\n browserDatabaseTransaction,\n type BrowserDatabase\n} from './database.ts';\nimport {\n createPublicQuotaRepository,\n publicQuotaOwner,\n claimPublicDraftOperation,\n type PublicQuotaRepository,\n type PublicQuotaFailure\n} from './quota.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n publicDraftControllerOwnership,\n type PublicDraftController\n} from '../publishing/draft-controller.ts';\nimport { exactLocalFields } from '../contracts/local-records.ts';\n\ndeclare const repositoryBrand: unique symbol;\nexport type PublicPublicationRepository = Readonly<{ [repositoryBrand]: true }>;\ntype Scope = Readonly<{\n database: BrowserDatabase;\n drafts: PublicDraftRepository;\n quota: PublicQuotaRepository;\n owner: string;\n}>;\nconst repositories = new WeakMap<PublicPublicationRepository, Scope>();\nfunction scopeOf(repository: PublicPublicationRepository): Scope | undefined {\n const scope = repositories.get(repository);\n return scope &&\n publicDraftRepositoryOwner(scope.drafts) === scope.owner &&\n publicQuotaOwner(scope.quota) === scope.owner\n ? scope\n : undefined;\n}\nexport function createPublicPublicationRepository(\n database: BrowserDatabase,\n owner: unknown\n): PublicPublicationRepository | undefined {\n const drafts = createPublicDraftRepository(database, owner),\n quota = createPublicQuotaRepository(database, owner);\n const admittedOwner = drafts && publicDraftRepositoryOwner(drafts);\n if (\n !drafts ||\n !quota ||\n !admittedOwner ||\n publicQuotaOwner(quota) !== admittedOwner\n )\n return undefined;\n const handle = Object.freeze({}) as PublicPublicationRepository;\n repositories.set(handle, { database, drafts, quota, owner: admittedOwner });\n return handle;\n}\nexport function publicPublicationDraftRepository(\n repository: PublicPublicationRepository\n): PublicDraftRepository | undefined {\n return scopeOf(repository)?.drafts;\n}\nexport function publicPublicationOwner(\n repository: PublicPublicationRepository\n): string | undefined {\n return scopeOf(repository)?.owner;\n}\n// Original same-database quota custody only; it does not mint an identity,\n// extension approval, lock lease or public network capability.\nexport function publicPublicationQuotaRepository(\n repository: PublicPublicationRepository\n): PublicQuotaRepository | undefined {\n return scopeOf(repository)?.quota;\n}\nexport type PublicListingSave =\n | Readonly<{ status: 'saved' | 'existing'; record: PublicRecordHandle }>\n | Readonly<{ status: PublicQuotaFailure | 'busy' }>;\nexport type PublicListingRead =\n | Readonly<{ status: 'found'; record: PublicRecordHandle }>\n | Readonly<{ status: 'missing' | 'unavailable' | 'corrupt_record' }>;\n// Readback is exact local observation, never global absence or relay receipt.\nexport function readPublicListingIntent(\n repository: PublicPublicationRepository,\n command: unknown\n): Promise<PublicListingRead> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(command);\n if (!scope || !id) return Promise.resolve({ status: 'unavailable' });\n let transaction: IDBTransaction;\n try {\n transaction = browserDatabaseTransaction(\n scope.database,\n ['public_operations'],\n 'readonly'\n );\n } catch {\n return Promise.resolve({ status: 'unavailable' });\n }\n return new Promise((resolve) => {\n let decision: PublicListingRead | undefined;\n transaction.addEventListener('complete', () =>\n resolve(\n scopeOf(repository)\n ? (decision ?? { status: 'unavailable' })\n : { status: 'unavailable' }\n )\n );\n transaction.addEventListener('abort', () =>\n resolve({ status: 'unavailable' })\n );\n try {\n const request = transaction\n .objectStore('public_operations')\n .get([scope.owner, id]);\n request.addEventListener('success', () => {\n const value: unknown = request.result;\n if (value === undefined) {\n decision = { status: 'missing' };\n return;\n }\n if (\n !exactLocalFields(value, ['owner', 'id', 'wire']) ||\n value.owner !== scope.owner ||\n value.id !== id\n ) {\n decision = { status: 'corrupt_record' };\n return;\n }\n const decoded = decodePublicRecord(value.wire, scope.owner, id);\n const row =\n decoded.ok && publicRecordSnapshot(decoded.value, scope.owner, id);\n decision =\n decoded.ok && row && row.family === 'public_operation'\n ? { status: 'found', record: decoded.value }\n : { status: 'corrupt_record' };\n });\n } catch {\n decision = { status: 'unavailable' };\n try {\n transaction.abort();\n } catch {\n resolve({ status: 'unavailable' });\n }\n }\n });\n}\n// Only a short local transaction is held. Extension/relay effects are later\n// checkpoint owners and are absent from this repository.\nexport async function savePublicListingIntent(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n record: PublicRecordHandle,\n expected: PublicDraftRecord,\n editVersion: number,\n command: string,\n current: (this: void) => boolean\n): Promise<PublicListingSave> {\n try {\n const scope = scopeOf(repository),\n custody = publicDraftControllerOwnership(controller);\n const row = scope && publicRecordSnapshot(record, scope.owner, command);\n if (\n !scope ||\n !custody ||\n custody.repository !== scope.drafts ||\n !row ||\n row.family !== 'public_operation' ||\n row.source.type !== 'draft'\n )\n return { status: 'invalid_scope' };\n if (\n !current() ||\n typeof window === 'undefined' ||\n !navigator.locks?.request\n )\n return { status: 'unavailable' };\n return await navigator.locks.request(\n 'harvestcircle:owner:' + scope.owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<PublicListingSave> => {\n if (!lock) return { status: 'busy' };\n const fresh = (): boolean => scopeOf(repository) === scope && current();\n if (!fresh()) return { status: 'unavailable' };\n const claimed = await claimPublicDraftOperation(\n scope.quota,\n row.id,\n record,\n {\n expected,\n current: fresh,\n draftCurrent: () =>\n custody.current(JSON.stringify(expected), editVersion)\n }\n );\n if (!fresh()) return { status: 'unavailable' };\n if (claimed.ok)\n return {\n status: claimed.value.state === 'created' ? 'saved' : 'existing',\n record: claimed.value.record\n };\n if (claimed.reason === 'unknown_completion') {\n const observed = await readPublicListingIntent(repository, row.id);\n const original =\n observed.status === 'found' &&\n publicRecordSnapshot(observed.record, scope.owner, row.id);\n if (!fresh()) return { status: 'unavailable' };\n if (\n observed.status === 'found' &&\n original &&\n original.family === 'public_operation' &&\n JSON.stringify(original.source) === JSON.stringify(row.source) &&\n JSON.stringify(original.capture) === JSON.stringify(row.capture)\n )\n return { status: 'existing', record: observed.record };\n if (original) return { status: 'conflict' };\n }\n return { status: claimed.reason };\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n",
+ sha256: '5a995002cbae1a62ecce9b34770baad102c5c90340da922593e3cc8d9f5c3384'
+ },
+ 'src/lib/persistence/quota.ts': {
+ source:
+ "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport {\n exactLocalFields,\n type PublicRecord,\n type PublicDraftRecord\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';\nimport {\n browserDatabaseState,\n browserDatabaseTransaction,\n type BrowserDatabase\n} from './database.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n publicInventoryRow,\n PUBLIC_CLEANUP_CONSEQUENCES,\n type PublicInventoryRow\n} from './local-inventory.ts';\n\nimport {\n publicTransitionIdentity,\n publicTransitionSnapshot,\n type PublicOperationTransition\n} from './artifact-records.ts';\nimport { decideFrozenTransition } from './operation-transactions.ts';\n\ndeclare const repositoryBrand: unique symbol;\ndeclare const inventoryBrand: unique symbol;\ndeclare const cleanupBrand: unique symbol;\nexport type PublicQuotaRepository = Readonly<{ [repositoryBrand]: true }>;\nexport type PublicInventory = Readonly<{ [inventoryBrand]: true }>;\nexport type PublicCleanup = Readonly<{ [cleanupBrand]: true }>;\nexport type PublicQuotaFailure =\n | 'invalid_scope'\n | 'invalid_record'\n | 'invalid_selection'\n | 'protected'\n | 'conflict'\n | 'capacity'\n | 'corrupt_record'\n | 'unavailable'\n | 'aborted'\n | 'unknown_completion';\nexport type PublicQuotaResult<T> =\n | Readonly<{ ok: true; value: T }>\n | Readonly<{ ok: false; reason: PublicQuotaFailure }>;\ntype Scope = Readonly<{ database: BrowserDatabase; owner: string }>;\ntype Store = 'public_drafts' | 'public_operations' | 'preference_operations';\ntype Row = Readonly<{\n store: Store;\n wire: string;\n record: PublicRecord;\n bytes: number;\n}>;\ntype Inspection = Readonly<{\n repository: PublicQuotaRepository;\n rows: readonly Row[];\n}>;\ntype Cleanup = Readonly<{ inventory: Inspection; selected: readonly string[] }>;\nconst repositories = new WeakMap<PublicQuotaRepository, Scope>();\nconst inventories = new WeakMap<PublicInventory, Inspection>();\nconst cleanups = new WeakMap<PublicCleanup, Cleanup>();\nconst stores: readonly Store[] = [\n 'public_drafts',\n 'public_operations',\n 'preference_operations'\n];\nfunction failed(reason: PublicQuotaFailure): PublicQuotaResult<never> {\n return { ok: false, reason };\n}\nfunction scopeOf(repository: PublicQuotaRepository): Scope | undefined {\n const scope = repositories.get(repository);\n try {\n return scope && browserDatabaseState(scope.database).state === 'ready'\n ? scope\n : undefined;\n } catch {\n return undefined;\n }\n}\n// Metadata only; this does not grant installed-account or effect authority.\nexport function publicQuotaOwner(\n repository: PublicQuotaRepository\n): string | undefined {\n return scopeOf(repository)?.owner;\n}\n// A namespace capability only; installed-account authorization belongs to the\n// account workflow. This repository never acquires any private store.\nexport function createPublicQuotaRepository(\n database: BrowserDatabase,\n expectedOwner: unknown\n): PublicQuotaRepository | undefined {\n const owner = canonicalPublicKey(expectedOwner);\n try {\n if (!owner || browserDatabaseState(database).state !== 'ready')\n return undefined;\n const handle = Object.freeze({}) as PublicQuotaRepository;\n repositories.set(handle, { database, owner });\n return handle;\n } catch {\n return undefined;\n }\n}\nfunction stored(\n value: unknown,\n store: Store,\n owner: string,\n id: string\n): Row | undefined {\n if (\n !exactLocalFields(value, ['owner', 'id', 'wire']) ||\n value.owner !== owner ||\n value.id !== id ||\n typeof value.wire !== 'string'\n )\n return undefined;\n const admitted = decodePublicRecord(value.wire, owner, id);\n if (!admitted.ok) return undefined;\n const record = publicRecordSnapshot(admitted.value, owner, id);\n const family =\n store === 'public_drafts'\n ? 'public_draft'\n : store === 'public_operations'\n ? 'public_operation'\n : 'preference_operation';\n return record?.family === family\n ? {\n store,\n record,\n wire: value.wire,\n bytes: new TextEncoder().encode(value.wire).length\n }\n : undefined;\n}\nfunction transaction<T>(\n scope: Scope,\n mode: 'readonly' | 'readwrite',\n finish: (\n rows: readonly Row[],\n transaction: IDBTransaction,\n refuse: (reason: PublicQuotaFailure) => void\n ) => PublicQuotaResult<T> | undefined\n): Promise<PublicQuotaResult<T>> {\n let active: IDBTransaction;\n try {\n active = browserDatabaseTransaction(scope.database, stores, mode);\n } catch {\n return Promise.resolve(failed('unavailable'));\n }\n return new Promise((resolve) => {\n let result: PublicQuotaResult<T> | undefined;\n let rows = Array.from<Row>([]),\n draftCount = 0,\n operationCount = 0,\n operationBytes = 0;\n function refuse(reason: PublicQuotaFailure) {\n result = failed(reason);\n try {\n active.abort();\n } catch {\n result = failed('unknown_completion');\n }\n }\n active.addEventListener('complete', () =>\n resolve(result ?? failed('unknown_completion'))\n );\n active.addEventListener('abort', () =>\n resolve(result && !result.ok ? result : failed('aborted'))\n );\n function scan(index: number): void {\n try {\n const store = stores[index];\n if (store === undefined) {\n const finished = finish(rows, active, refuse);\n if (finished !== undefined) result = finished;\n return;\n }\n const request = active\n .objectStore(store)\n .index('by_owner')\n .openCursor(IDBKeyRange.only(scope.owner));\n request.addEventListener('success', () => {\n try {\n const cursor = request.result;\n if (!cursor) {\n scan(index + 1);\n return;\n }\n const key = cursor.primaryKey;\n const id =\n Array.isArray(key) && key.length === 2 && key[0] === scope.owner\n ? canonicalLocalId(key[1])\n : undefined;\n const row = id && stored(cursor.value, store, scope.owner, id);\n if (!row) {\n refuse('corrupt_record');\n return;\n }\n if (row.record.family === 'public_draft') draftCount++;\n else {\n operationCount++;\n operationBytes += row.bytes;\n }\n if (\n draftCount > LOCAL_PERSISTENCE_BUDGETS.publicDrafts ||\n operationCount > LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operationBytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n rows = rows.concat(row);\n cursor.continue();\n } catch {\n refuse('aborted');\n }\n });\n } catch {\n refuse('aborted');\n }\n }\n scan(0);\n });\n}\n// Explicit new-row admission only. Artifact/CAS transitions retain HCP050.\n// Logical bytes include the exact stored record wire, not browser disk/heap use.\nexport function admitPublicOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle\n): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n const record = publicRecordSnapshot(handle, scope.owner, id),\n wire = publicRecordWire(handle, scope.owner, id);\n if (\n !record ||\n !wire ||\n record.family === 'public_draft' ||\n record.revision !== 0\n )\n return Promise.resolve(failed('invalid_record'));\n const store: Store =\n record.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const bytes = new TextEncoder().encode(wire).length;\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const previous = rows.find(\n (row) => row.store === store && row.record.id === id\n );\n if (previous)\n return previous.wire === wire\n ? { ok: true, value: { id, revision: 0 } }\n : (refuse('conflict'), undefined);\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n if (\n operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operations.reduce((sum, row) => sum + row.bytes, bytes) >\n LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n active.objectStore(store).put({ owner: scope.owner, id, wire });\n return { ok: true, value: { id, revision: 0 } };\n });\n}\n// Claim under the caller's origin/author Web Lock. A previous capture is never\n// overwritten or automatically signed again, even after a page lost its lock.\n// No extension/network await occurs inside the short transaction.\nexport function claimPublicOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n return claimOperation(repository, expectedId, handle);\n}\ntype DraftAdmission = Readonly<{\n expected: PublicDraftRecord;\n current(this: void): boolean;\n draftCurrent(this: void): boolean;\n}>;\n// Storage-only atomic draft/CAS reservation. Current original account/review\n// ownership is supplied by the public listing command owner, never a UI flag.\n// Existing commands retain their original capture even after future draft edits.\nexport function claimPublicDraftOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle,\n admission: DraftAdmission\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n return claimOperation(repository, expectedId, handle, admission);\n}\nfunction claimOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle,\n draft?: DraftAdmission\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n const record = publicRecordSnapshot(handle, scope.owner, id),\n wire = publicRecordWire(handle, scope.owner, id);\n if (\n !record ||\n !wire ||\n record.family === 'public_draft' ||\n record.revision !== 0 ||\n record.artifact !== null\n )\n return Promise.resolve(failed('invalid_record'));\n const store: Store =\n record.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const bytes = new TextEncoder().encode(wire).length;\n return transaction<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >(scope, 'readwrite', (rows, active, refuse) => {\n if (draft && !draft.current()) {\n refuse('unavailable');\n return;\n }\n const previous = rows.find(\n (row) => row.record.family !== 'public_draft' && row.record.id === id\n );\n if (previous) {\n const original = previous.record;\n if (\n original.family === 'public_draft' ||\n original.family !== record.family ||\n JSON.stringify(original.source) !== JSON.stringify(record.source) ||\n JSON.stringify(original.capture) !== JSON.stringify(record.capture) ||\n ('consent' in original ? original.consent : null) !==\n ('consent' in record ? record.consent : null)\n ) {\n refuse('conflict');\n return;\n }\n const decoded = decodePublicRecord(previous.wire, scope.owner, id);\n if (!decoded.ok) {\n refuse('corrupt_record');\n return;\n }\n return { ok: true, value: { state: 'existing', record: decoded.value } };\n }\n if (draft) {\n const source =\n record.family === 'public_operation' ? record.source : undefined;\n const previousDraft = rows.find(\n (row) =>\n row.record.family === 'public_draft' &&\n row.record.id === draft.expected.id\n );\n if (\n !source ||\n source.type !== 'draft' ||\n draft.expected.owner !== scope.owner ||\n source.id !== draft.expected.id ||\n source.revision !== draft.expected.revision ||\n !previousDraft ||\n JSON.stringify(previousDraft.record) !==\n JSON.stringify(draft.expected) ||\n !draft.draftCurrent()\n ) {\n refuse('conflict');\n return;\n }\n }\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n if (\n operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operations.reduce((sum, row) => sum + row.bytes, bytes) >\n LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n if (draft && (!draft.current() || !draft.draftCurrent())) {\n refuse('conflict');\n return;\n }\n active.objectStore(store).put({ owner: scope.owner, id, wire });\n return { ok: true, value: { state: 'created', record: handle } };\n });\n}\nexport function inspectPublicStorage(\n repository: PublicQuotaRepository\n): Promise<PublicQuotaResult<PublicInventory>> {\n const scope = scopeOf(repository);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n return transaction(scope, 'readonly', (rows) => {\n const handle = Object.freeze({}) as PublicInventory;\n inventories.set(handle, { repository, rows });\n return { ok: true, value: handle };\n });\n}\nexport function publicInventorySnapshot(\n repository: PublicQuotaRepository,\n handle: PublicInventory\n):\n | Readonly<{ rows: readonly PublicInventoryRow[]; consequences: string }>\n | undefined {\n const inventory = inventories.get(handle);\n return scopeOf(repository) && inventory?.repository === repository\n ? {\n rows: inventory.rows.map((row) =>\n publicInventoryRow(row.record, row.bytes)\n ),\n consequences: PUBLIC_CLEANUP_CONSEQUENCES\n }\n : undefined;\n}\nexport function reviewPublicCleanup(\n repository: PublicQuotaRepository,\n handle: PublicInventory,\n selection: unknown\n): PublicQuotaResult<PublicCleanup> {\n const inventory = inventories.get(handle);\n if (!scopeOf(repository) || inventory?.repository !== repository)\n return failed('invalid_scope');\n try {\n if (!Array.isArray(selection)) return failed('invalid_selection');\n const length = selection.length;\n if (\n !Number.isSafeInteger(length) ||\n length <= 0 ||\n length >\n LOCAL_PERSISTENCE_BUDGETS.publicDrafts +\n LOCAL_PERSISTENCE_BUDGETS.publicOperations\n )\n return failed('invalid_selection');\n let selected = Array.from<string>([]);\n for (let index = 0; index < length; index++) {\n const key: unknown = selection[index];\n if (typeof key !== 'string' || selected.includes(key))\n return failed('invalid_selection');\n const row = inventory.rows.find(\n (row) => publicInventoryRow(row.record, row.bytes).key === key\n );\n if (!row) return failed('invalid_selection');\n if (publicInventoryRow(row.record, row.bytes).state !== 'settled')\n return failed('protected');\n selected = selected.concat(key);\n }\n if (!scopeOf(repository)) return failed('invalid_scope');\n const token = Object.freeze({}) as PublicCleanup;\n cleanups.set(token, { inventory, selected });\n return { ok: true, value: token };\n } catch {\n return failed('invalid_selection');\n }\n}\nexport function publicCleanupSnapshot(\n repository: PublicQuotaRepository,\n handle: PublicCleanup\n):\n | Readonly<{\n selected: readonly PublicInventoryRow[];\n logicalBytesRemoved: number;\n consequences: string;\n }>\n | undefined {\n const cleanup = cleanups.get(handle);\n if (!scopeOf(repository) || cleanup?.inventory.repository !== repository)\n return undefined;\n const selected = cleanup.inventory.rows\n .map((row) => publicInventoryRow(row.record, row.bytes))\n .filter((row) => cleanup.selected.includes(row.key));\n return {\n selected,\n logicalBytesRemoved: selected.reduce(\n (sum, row) => sum + row.logicalBytes,\n 0\n ),\n consequences: PUBLIC_CLEANUP_CONSEQUENCES\n };\n}\nexport function commitPublicCleanup(\n repository: PublicQuotaRepository,\n handle: PublicCleanup\n): Promise<PublicQuotaResult<readonly string[]>> {\n const cleanup = cleanups.get(handle),\n scope = scopeOf(repository);\n if (!scope || cleanup?.inventory.repository !== repository)\n return Promise.resolve(failed('invalid_scope'));\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const before = cleanup.inventory.rows;\n if (\n rows.length !== before.length ||\n rows.some(\n (row, i) =>\n row.store !== before[i].store ||\n row.record.id !== before[i].record.id ||\n row.wire !== before[i].wire\n )\n ) {\n refuse('conflict');\n return;\n }\n const selected = rows.filter((row) =>\n cleanup.selected.includes(publicInventoryRow(row.record, row.bytes).key)\n );\n if (\n selected.length !== cleanup.selected.length ||\n selected.some(\n (row) => publicInventoryRow(row.record, row.bytes).state !== 'settled'\n )\n ) {\n refuse('protected');\n return;\n }\n for (const row of selected)\n active.objectStore(row.store).delete([scope.owner, row.record.id]);\n return { ok: true, value: Array.from(cleanup.selected) };\n });\n}\n\n// No signer/network await exists inside this transaction. It consumes only a\n// genuine immutable typed transition captured before storage acquisition.\n// Exact owner-scoped actual stored preference, not a caller's structural row.\n// Read is bounded by the same complete quota/codec scan and transaction ack.\nexport function loadPreferenceOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown\n): Promise<PublicQuotaResult<PublicRecordHandle>> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n return transaction(scope, 'readonly', (rows) => {\n const row = rows.find(\n (row) => row.store === 'preference_operations' && row.record.id === id\n );\n if (!row) return failed('invalid_record');\n const decoded = decodePublicRecord(row.wire, scope.owner, id);\n return decoded.ok ? decoded : failed('corrupt_record');\n });\n}\nexport function commitPublicOperationTransition(\n repository: PublicQuotaRepository,\n handle: PublicOperationTransition\n): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {\n const scope = scopeOf(repository);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n const identity = publicTransitionIdentity(handle);\n const command =\n identity && publicTransitionSnapshot(handle, scope.owner, identity.id);\n if (!command) return Promise.resolve(failed('invalid_record'));\n const store: Store =\n command.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const previous = rows.find(\n (row) => row.store === store && row.record.id === command.id\n );\n const decision = decideFrozenTransition(\n previous?.wire,\n command.baseWire,\n command.nextWire\n );\n if (decision === 'conflict') {\n refuse('conflict');\n return;\n }\n if (decision === 'committed')\n return {\n ok: true,\n value: { id: command.id, revision: command.revision }\n };\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n const bytes =\n operations.reduce((sum, row) => sum + row.bytes, 0) -\n (previous?.bytes ?? 0) +\n new TextEncoder().encode(command.nextWire).length;\n if (bytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes) {\n refuse('capacity');\n return;\n }\n active\n .objectStore(store)\n .put({ owner: scope.owner, id: command.id, wire: command.nextWire });\n return { ok: true, value: { id: command.id, revision: command.revision } };\n });\n}\nexport async function observePublicOperationTransition(\n repository: PublicQuotaRepository,\n handle: PublicOperationTransition\n): Promise<\n | Readonly<{ state: 'committed'; id: string; revision: number }>\n | Readonly<{ state: 'base_observed' | 'conflict' | 'unavailable' }>\n> {\n const scope = scopeOf(repository),\n identity = publicTransitionIdentity(handle);\n const command =\n scope &&\n identity &&\n publicTransitionSnapshot(handle, scope.owner, identity.id);\n if (!scope || !command) return { state: 'unavailable' };\n const store: Store =\n command.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const read = await transaction(scope, 'readonly', (rows) => ({\n ok: true,\n value: decideFrozenTransition(\n rows.find((row) => row.store === store && row.record.id === command.id)\n ?.wire,\n command.baseWire,\n command.nextWire\n )\n }));\n if (!read.ok || !scopeOf(repository)) return { state: 'unavailable' };\n return read.value === 'committed'\n ? { state: 'committed', id: command.id, revision: command.revision }\n : { state: read.value };\n}\n",
+ sha256: '7bff93f40c55d5f0899deb50309d4d69107fb299d1aee10c348fda23e71761bf'
+ },
+ 'src/lib/nostr/listing-publisher.ts': {
+ source:
+ "import type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n listingPublicationOwnership,\n type ListingPublication\n} from '../publishing/sign-listing.ts';\nimport {\n listingResumeOwnership,\n type ListingResumption\n} from '../publishing/resume-listing.ts';\nimport {\n listingRetryOwnership,\n type ListingRetry\n} from '../publishing/retry-listing.ts';\nimport {\n identityMessagingOwnership,\n identityPublicOperationOwnership,\n recheckIdentityOwner,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport { preferencePolicyFingerprint } from './inbox-preference-publication.ts';\nimport { readPublicListingIntent } from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\ndeclare const leaseBrand: unique symbol;\ndeclare const permissionBrand: unique symbol;\nexport type ListingDeliveryLease = Readonly<{ [leaseBrand]: true }>;\nexport type ListingAttemptPermission = Readonly<{ [permissionBrand]: true }>;\ntype Original = NonNullable<\n | ReturnType<typeof listingPublicationOwnership>\n | ReturnType<typeof listingResumeOwnership>\n>;\ntype Owner = Readonly<{\n original: Original;\n policy: RelayPolicy;\n signal?: AbortSignal;\n current(): boolean;\n}>;\ntype Permission = Readonly<{\n owner: Owner;\n origin: string;\n mode: 'publish' | 'readback';\n wire: string;\n}>;\nconst leases = new WeakMap<ListingDeliveryLease, Owner>();\nconst permissions = new WeakMap<ListingAttemptPermission, Permission>();\n// Stop releases this action's wait and author lock. The extension promise may\n// settle later; it cannot resurrect the revoked network lease or a signer.\nasync function recheckDeliveryOwner(\n identity: IdentitySession,\n signal?: AbortSignal\n): Promise<boolean> {\n if (signal?.aborted) return false;\n if (!signal) {\n await recheckIdentityOwner(identity);\n return true;\n }\n let stop = () => {};\n const stopped = new Promise<boolean>((resolve) => {\n stop = () => resolve(false);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n });\n try {\n return await Promise.race([\n recheckIdentityOwner(identity).then(() => true),\n stopped\n ]);\n } finally {\n signal.removeEventListener('abort', stop);\n }\n}\n// Receipt revisions may grow, but the complete original operation payload and\n// verified artifact stay exact. No new command, author or destination is adopted.\nexport async function readRetainedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner) return;\n const original = owner.original;\n const expected = decodePublicRecord(\n original.recordWire,\n original.owner,\n original.command\n );\n if (!expected.ok) return;\n const baseline = publicRecordSnapshot(\n expected.value,\n original.owner,\n original.command\n );\n if (\n baseline?.family !== 'public_operation' ||\n baseline.capture.kind !== 30402 ||\n !baseline.artifact ||\n baseline.revision !== 2\n )\n return;\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n if (read.status !== 'found') return;\n const row = publicRecordSnapshot(\n read.record,\n original.owner,\n original.command\n );\n if (\n row?.family !== 'public_operation' ||\n row.revision < baseline.revision ||\n JSON.stringify({\n ...row,\n revision: baseline.revision,\n receipts: baseline.receipts\n }) !== JSON.stringify(baseline)\n )\n return;\n return read.record;\n}\n// Current authority is mandatory for every new network permission. Retained\n// exact storage observation above remains usable for bookkeeping after Stop.\nexport async function readOwnedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner?.current()) return;\n const read = readRetainedListingDelivery(lease);\n let stop = () => {};\n const stopped =\n owner.signal &&\n new Promise<undefined>((resolve) => {\n stop = () => resolve(undefined);\n owner.signal!.addEventListener('abort', stop, { once: true });\n if (owner.signal!.aborted) stop();\n });\n let record: PublicRecordHandle | undefined;\n try {\n record = await (stopped ? Promise.race([read, stopped]) : read);\n } finally {\n owner.signal?.removeEventListener('abort', stop);\n }\n return owner.current() ? record : undefined;\n}\nexport function listingDeliveryOwnership(lease: ListingDeliveryLease) {\n const owner = leases.get(lease);\n return owner?.current()\n ? {\n repository: owner.original.repository,\n owner: owner.original.owner,\n command: owner.original.command,\n current: owner.current\n }\n : undefined;\n}\nexport type ListingOwnershipResult<T> =\n | Readonly<{ status: 'completed'; value: T }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'busy' | 'stopped' }>;\n// One original author lock spans this finite explicitly requested network\n// action. It never spans a native IDB transaction and cannot mint a signer.\nexport async function withListingDeliveryOwnership<T>(\n publication: ListingPublication | ListingResumption,\n policy: RelayPolicy,\n consent: unknown,\n work: (lease: ListingDeliveryLease) => Promise<T>,\n control?: ListingRetry\n): Promise<ListingOwnershipResult<T>> {\n const signed = listingPublicationOwnership(publication as ListingPublication),\n resumed = listingResumeOwnership(publication as ListingResumption),\n original = signed ?? resumed,\n retry = control && listingRetryOwnership(control);\n if (\n !original ||\n (control\n ? !retry ||\n retry.source !== publication ||\n retry.policy !== policy ||\n retry.consent !== consent\n : !signed || consent !== 'publish_stored_listing') ||\n original.policy !== policy\n )\n return { status: 'invalid' };\n if (retry && !retry.current()) return { status: 'stopped' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n try {\n return await navigator.locks.request(\n 'harvestcircle:owner:' + original.owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<ListingOwnershipResult<T>> => {\n if (!lock) return { status: 'busy' };\n if (!(await recheckDeliveryOwner(original.identity, retry?.signal)))\n return { status: 'stopped' };\n const identity = identityMessagingOwnership(original.identity),\n operation =\n signed &&\n identityPublicOperationOwnership(\n original.identity,\n signed.operation\n );\n if (\n !identity ||\n (signed && !operation) ||\n identity.owner !== original.owner ||\n (operation &&\n (operation.owner !== original.owner ||\n operation.session !== identity.session)) ||\n !original.current() ||\n (retry && !retry.current())\n )\n return { status: 'stopped' };\n let active = true;\n const owner: Owner = {\n original,\n policy,\n signal: retry?.signal,\n current: () =>\n active &&\n original.current() &&\n identity.current() &&\n (!operation || operation.current()) &&\n (!retry || retry.current())\n };\n const lease = Object.freeze({}) as ListingDeliveryLease;\n leases.set(lease, owner);\n try {\n if (!(await readOwnedListingDelivery(lease)))\n return {\n status: retry && !retry.current() ? 'stopped' : 'unavailable'\n };\n return { status: 'completed', value: await work(lease) };\n } finally {\n active = false;\n }\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Each permission comes from actual stored signed bytes, fresh identity and\n// unchanged original policy. Preference/private capabilities cannot enter it.\nexport async function authorizeListingAttempt(\n lease: ListingDeliveryLease,\n origin: string,\n mode: 'publish' | 'readback'\n): Promise<ListingAttemptPermission | undefined> {\n const owner = leases.get(lease);\n if (!owner || !owner.current() || (mode !== 'publish' && mode !== 'readback'))\n return;\n try {\n const record = await readOwnedListingDelivery(lease),\n original = owner.original;\n const row =\n record && publicRecordSnapshot(record, original.owner, original.command);\n const manifest = readRelayPolicy(owner.policy),\n targets = publicRelayTargets(owner.policy, 'write'),\n fingerprint = await preferencePolicyFingerprint(owner.policy);\n if (\n row?.family !== 'public_operation' ||\n !row.artifact ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ||\n !row.capture.targets.includes(origin)\n )\n return;\n if (!(await recheckDeliveryOwner(original.identity, owner.signal))) return;\n if (!owner.current()) return;\n const token = Object.freeze({}) as ListingAttemptPermission;\n permissions.set(token, { owner, origin, mode, wire: row.artifact.wire });\n return token;\n } catch {\n return;\n }\n}\n// Original once-only token: detached metadata, wrong role, policy or origin\n// cannot supply a raw event. SDK effects remain owned by the public pool.\nexport function takeListingPublication(\n token: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n mode: 'publish' | 'readback'\n):\n | Readonly<{ event: NostrEvent; wire: string; current(): boolean }>\n | undefined {\n const saved = permissions.get(token);\n if (!saved) return;\n permissions.delete(token);\n if (\n saved.owner.policy !== policy ||\n saved.origin !== origin ||\n saved.mode !== mode ||\n !saved.owner.current()\n )\n return;\n return {\n event: JSON.parse(saved.wire) as NostrEvent,\n wire: saved.wire,\n current: saved.owner.current\n };\n}\n",
+ sha256: '1c8c3445513329d57fcddc75da63991f0c1c27c28caf87db381d32bba739c872'
+ }
+ };
+ /** @param {string} web */
+ async function restoreHistoricalPublicProducers(web) {
+ for (const [name, value] of Object.entries(
+ historicalPublicProducerClosure
+ )) {
+ assert.equal(
+ createHash('sha256').update(value.source).digest('hex'),
+ value.sha256
+ );
+ await writeFile(path.join(web, name), value.source);
+ }
+ }
// Frozen public-only HCP055 producers, source6023db01169aa82cb6fe68ca94e1a73750247e72.
// Compatibility evidence only; runtime tests never require ancestor Git history.
/** @type {Record<string, {source:string, sha256:string}>} */
@@ -238,6 +310,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
{ timeout: 1800000 },
async (t) => {
const f = await fixture(t);
+ await restoreHistoricalPublicProducers(f.web);
const historical = {
'src/routes/sell/+page.svelte': {
source:
@@ -311,6 +384,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
{ timeout: 1800000 },
async (t) => {
const f = await fixture(t);
+ await restoreHistoricalPublicProducers(f.web);
for (const [name, value] of Object.entries(historicalPublicOnly)) {
assert.equal(
createHash('sha256').update(value.source).digest('hex'),
@@ -388,6 +462,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
{ timeout: 1800000 },
async (t) => {
const f = await fixture(t);
+ await restoreHistoricalPublicProducers(f.web);
// This historical graph predates identity activation. Restore its
// immutable public-only producers before compiling the former routes.
for (const [name, value] of Object.entries(historicalPublicOnly))
@@ -429,6 +504,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
{ timeout: 1800000 },
async (t) => {
const f = await fixture(t);
+ await restoreHistoricalPublicProducers(f.web);
for (const [name, value] of Object.entries(historicalPublicOnly))
await writeFile(path.join(f.web, name), value.source);
await writeFile(
@@ -454,7 +530,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, 55);
+ assert.equal(files.length, 53);
// 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(
@@ -557,7 +633,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
if (mutation === 'missing-private-edge')
row.imports = row.imports.slice(1);
if (mutation === 'private-dynamic')
- row.dynamicImports = [find('read')[0]];
+ row.dynamicImports = [find('InboxSetup')[0]];
if (mutation === 'publisher-extra-edge')
find('publishers')[1].imports = find(
'publishers'
@@ -654,7 +730,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
if (mutation === 'thread-dynamic')
row.dynamicImports = [
Object.keys(manifest).find(
- (key) => manifest[key].name === 'read'
+ (key) => manifest[key].name === 'InboxSetup'
)
];
if (mutation === 'thread-entry-role') row.isEntry = false;
@@ -665,7 +741,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
);
if (mutation === 'reply-missing-owner-key') {
const key = Object.keys(manifest).find(
- (key) => manifest[key].name === 'public-key'
+ (key) => manifest[key].name === 'public-runtime'
);
assert.ok(
key && row.imports.includes(key),
@@ -673,7 +749,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
);
row.imports = row.imports.filter(
(/** @type {string} */ value) =>
- manifest[value].name !== 'public-key'
+ manifest[value].name !== 'public-runtime'
);
}
await writeFile(file, JSON.stringify(manifest));
@@ -700,7 +776,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
}
);
for (const name of [
- 'public-key',
+ 'references',
'public-runtime',
'AccountGate',
'Disclosure'
@@ -738,13 +814,13 @@ 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, 55);
+ assert.equal((await f.audit()).length, 53);
}
);
for (const mutation of [
'unknown-name',
- 'missing-public-key',
+ 'missing-references',
'missing-dist',
'missing-negentropy',
'missing-root-edge',
@@ -831,7 +907,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
if (mutation === 'css') m[sdkKey].css = [];
if (mutation === 'wrong-import')
m[sdkKey].imports = [
- Object.keys(m).find((k) => m[k].name === 'public-key')
+ Object.keys(m).find((k) => m[k].name === 'Button')
];
if (mutation === 'chunk-src') dist[1].src = dist[0];
if (mutation === 'chunk-entry') dist[1].isEntry = false;
@@ -1302,7 +1378,16 @@ import { auditOutput } from '../../tools/check-output.mjs';
'src/lib/components/ListingReview.svelte',
'src/lib/publishing/editor-workflow.ts',
'src/lib/components/ConflictNotice.svelte',
- 'src/lib/publishing/edit-source.ts'
+ 'src/lib/publishing/edit-source.ts',
+ 'src/lib/publishing/prepare-listing.ts',
+ 'src/lib/publishing/new-listing-readiness.ts',
+ 'src/lib/runtime/public-runtime.ts',
+ 'src/lib/persistence/public-publications.ts',
+ 'src/lib/persistence/quota.ts',
+ 'src/lib/publishing/revise-listing.ts',
+ 'src/lib/publishing/mark-sold.ts',
+ 'src/lib/components/ConfirmPanel.svelte',
+ 'src/lib/nostr/listing-publisher.ts'
]) {
await check(
'listing editor rejects changed owned producer ' + producer,
@@ -1374,7 +1459,9 @@ import { auditOutput } from '../../tools/check-output.mjs';
await refresh(f);
await assert.rejects(
f.audit,
- /Invalid owned product presentation source/
+ producer === 'src/lib/runtime/public-runtime.ts'
+ ? /Invalid owned (product presentation|listing editor) source/
+ : /Invalid owned product presentation source/
);
}
);
@@ -1613,7 +1700,7 @@ import { auditOutput } from '../../tools/check-output.mjs';
find('navigation')[1].dynamicImports = [find('client-entry')[0]];
else if (mutation === 'shared-import')
shared.imports = shared.imports.filter(
- (/** @type {string} */ k) => k !== find('public-key')[0]
+ (/** @type {string} */ k) => k !== find('references')[0]
);
else shared.dynamicImports = [];
await writeFile(file, JSON.stringify(manifest));
diff --git a/web/tests/unit/revise-listing.test.ts b/web/tests/unit/revise-listing.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import {
+ nextOwnedRevisionTime,
+ reviewOwnedRevision
+} from '../../src/lib/publishing/revise-listing.ts';
+import { reviewMarkSold } from '../../src/lib/publishing/mark-sold.ts';
+import type { OwnedEditSource } from '../../src/lib/publishing/edit-source.ts';
+import type { PublicDraftController } from '../../src/lib/publishing/draft-controller.ts';
+
+describe('HCP119 owned revision clock and original custody', () => {
+ it('uses actual forward wall time and advances the same-second head once', () => {
+ expect(nextOwnedRevisionTime(100, 200)).toBe(200);
+ expect(nextOwnedRevisionTime(100, 100)).toBe(101);
+ });
+ it('stops before advancing beyond the original future-clock allowance', () => {
+ expect(nextOwnedRevisionTime(399, 100)).toBe(400);
+ expect(nextOwnedRevisionTime(400, 100)).toBeUndefined();
+ expect(nextOwnedRevisionTime(1000, 100)).toBeUndefined();
+ });
+ it('repeated updates cannot indefinitely beat a frozen/backward clock', () => {
+ let head = 100;
+ for (let index = 0; index < 300; index++) {
+ const next = nextOwnedRevisionTime(head, 100);
+ expect(next).toBe(head + 1);
+ if (next === undefined) throw Error('clock stopped before its limit');
+ head = next;
+ }
+ expect(head).toBe(400);
+ expect(nextOwnedRevisionTime(head, 100)).toBeUndefined();
+ expect(nextOwnedRevisionTime(head, 0)).toBeUndefined();
+ });
+ it.each([NaN, Infinity, -1, Number.MAX_SAFE_INTEGER + 1])(
+ 'unavailable wall clock %s cannot prepare a revision',
+ (now) => expect(nextOwnedRevisionTime(100, now)).toBeUndefined()
+ );
+ it.each([-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER])(
+ 'unsupported or overflowing head %s cannot advance',
+ (head) => expect(nextOwnedRevisionTime(head, 100)).toBeUndefined()
+ );
+ it('copied source/controller and boolean review cannot mint revision custody', async () => {
+ expect(
+ await reviewOwnedRevision(
+ {} as OwnedEditSource,
+ {} as PublicDraftController,
+ '3d030bf5-901d-45e1-8251-41cbdf805e96',
+ true
+ )
+ ).toEqual({ status: 'blocked', reason: 'invalid_scope' });
+ });
+ it('sold also requires original retained source and explicit reviewed consequence', async () => {
+ expect(
+ await reviewMarkSold(
+ {} as OwnedEditSource,
+ {} as PublicDraftController,
+ '3d030bf5-901d-45e1-8251-41cbdf805e96',
+ true
+ )
+ ).toEqual({ status: 'blocked', reason: 'invalid_scope' });
+ });
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -494,7 +494,13 @@ async function productPresentationAdmission(web) {
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);
publicText(bytes);
- if (createHash('sha256').update(bytes).digest('hex') !== pin)
+ if (
+ createHash('sha256').update(bytes).digest('hex') !== pin &&
+ !(
+ name === 'src/lib/runtime/public-runtime.ts' &&
+ (await listingEditorAdmission(web)) === 'owned-revision'
+ )
+ )
throw new Error('Invalid owned product presentation source');
}
return hasRequest ? 'request' : hasEnquiry ? 'enquiry' : true;
@@ -575,7 +581,13 @@ async function listingPublicationAdmission(web) {
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);
publicText(bytes);
- if (createHash('sha256').update(bytes).digest('hex') !== pin)
+ if (
+ createHash('sha256').update(bytes).digest('hex') !== pin &&
+ !(
+ name === 'src/lib/nostr/listing-publisher.ts' &&
+ (await listingEditorAdmission(web)) === 'owned-revision'
+ )
+ )
throw new Error('Invalid owned listing publication source');
}
return true;
@@ -660,10 +672,50 @@ async function listingEditorAdmission(web) {
'src/lib/publishing/edit-source.ts':
'985634e4c4eb2cd12839409552b1c56cd518021d4f031166a3c1ab8c4a0e7eff'
};
+ /** @type {Record<string,string>} */
+ const revisionProducers = {
+ 'src/routes/sell/+page.svelte':
+ '97f22f9a0309621e9acb5f1b328d3376bc9c5affbe5a7ea1b85ece76097b9c08',
+ 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte':
+ '1df59a753fbef2bc2ebf77890a79cbd3d7a5bb0dcef34c219df1b5e8043cf787',
+ 'src/routes/products/[naddr=naddr]/edit/+page.svelte':
+ '09c3a6bde766045319cd36a00a82ca565f9f3b5cd5322982be9482836f312998',
+ 'src/lib/components/ListingEditor.svelte':
+ 'f0f19095619b4b4ab961ac58af86fd0c8e92f2034a55173382929894fe36bd6a',
+ 'src/lib/publishing/listing-editor.ts':
+ '03e79904e6eb2dff06067a2e42c8d97b7081f7845221d4804649e9cb7df09f1f',
+ 'src/lib/components/ListingReview.svelte':
+ '311d6bafb883f170faa8962698d5cafd4cca7b4a7237a6eca671eb1f19379a99',
+ 'src/lib/publishing/editor-workflow.ts':
+ '0f8d718bbdad6697a8f9b519d8eafc80ca415e1d8ce245a3507111cc080f23ef',
+ 'src/lib/components/ConflictNotice.svelte':
+ 'f0a71cab9e8f1f12a3421402e3bc3b2f96c2ddb35ad8949c6e9599b850c3a17c',
+ 'src/lib/publishing/edit-source.ts':
+ 'bd0850df99dc0511fc0f9aa8bbb2526cab7a17ada9fd4d60464d5e3c9344811a',
+ 'src/lib/publishing/prepare-listing.ts':
+ '0c396643de10d31fb8c28ef46386c3b54f331ddf1e784955139b2f834fce11ed',
+ 'src/lib/publishing/new-listing-readiness.ts':
+ '46f4e89b435e732439add225166e80799f192a4f95ff5d8236a66b8614ac4172',
+ 'src/lib/runtime/public-runtime.ts':
+ '8d2b840e94448b55642b1481d12785ed76d326735a4461e9795f57a98e8d2530',
+ 'src/lib/persistence/public-publications.ts':
+ '58c3c230280616415d03020e0e4de6880afb754544fae205ae03d4a437c0424f',
+ 'src/lib/persistence/quota.ts':
+ 'c5332782042fa2561b237c8fd1f0c0c930390346c1f31f9b075dd9a0eacdf7e1',
+ 'src/lib/publishing/revise-listing.ts':
+ '1f03d43f460feb12a02489226131ec2f7b95df5f534fcbb0b49ccc686a1b0c06',
+ 'src/lib/publishing/mark-sold.ts':
+ '80beaf8ad38b396154d5556e50e2cf5cd9f327bcdbc05f0db1ce190bf29f7234',
+ 'src/lib/components/ConfirmPanel.svelte':
+ '9e25745303bdf408a14df5153a28e9579bfa019ab083225acb7d874e93a17d59',
+ 'src/lib/nostr/listing-publisher.ts':
+ '1d7e1f99fe393626a3dda6796867be0d52ce4bcd064c185c9f4b3a24290183e2'
+ };
let historical = true,
current = true,
reviewed = true,
- editing = true;
+ editing = true,
+ revising = true;
for (const [name, pin] of Object.entries(producers)) {
const bytes = await readOwned(web, name);
publicText(bytes);
@@ -672,6 +724,7 @@ async function listingEditorAdmission(web) {
current = current && actual === continuity[name];
reviewed = reviewed && actual === reviewProducers[name];
editing = editing && actual === editProducers[name];
+ revising = revising && actual === revisionProducers[name];
}
if (reviewed) {
for (const name of [
@@ -701,6 +754,31 @@ async function listingEditorAdmission(web) {
editProducers[name];
}
}
+ if (revising) {
+ for (const name of [
+ 'src/lib/components/ListingReview.svelte',
+ 'src/lib/publishing/editor-workflow.ts',
+ 'src/lib/components/ConflictNotice.svelte',
+ 'src/lib/publishing/edit-source.ts',
+ 'src/lib/publishing/prepare-listing.ts',
+ 'src/lib/publishing/new-listing-readiness.ts',
+ 'src/lib/runtime/public-runtime.ts',
+ 'src/lib/persistence/public-publications.ts',
+ 'src/lib/persistence/quota.ts',
+ 'src/lib/publishing/revise-listing.ts',
+ 'src/lib/publishing/mark-sold.ts',
+ 'src/lib/components/ConfirmPanel.svelte',
+ 'src/lib/nostr/listing-publisher.ts'
+ ]) {
+ const bytes = await readOwned(web, name);
+ publicText(bytes);
+ revising =
+ revising &&
+ createHash('sha256').update(bytes).digest('hex') ===
+ revisionProducers[name];
+ }
+ }
+ if (revising) return 'owned-revision';
if (editing) return 'edit-source';
if (!historical && !current && !reviewed)
throw new Error('Invalid owned listing editor source');
@@ -901,7 +979,9 @@ export async function auditOutput(webDirectory) {
const hasListingEditor = hasFullRoutes && (await listingEditorAdmission(web));
if (hasListingEditor && !(hasListingPublication && hasInboxSetup))
throw new Error('Invalid owned listing editor runtime authority');
- const hasListingEdit = hasListingEditor === 'edit-source';
+ const hasListingRevision = hasListingEditor === 'owned-revision';
+ const hasListingEdit =
+ hasListingEditor === 'edit-source' || hasListingRevision;
const hasListingReview = hasListingEditor === 'review' || hasListingEdit;
const hasListingContinuity =
hasListingEditor === 'continuity' || hasListingReview;
@@ -1017,6 +1097,11 @@ export async function auditOutput(webDirectory) {
names.add(name);
}
if (hasListingEdit) names.add('resolve-head');
+ if (hasListingRevision) {
+ for (const name of ['read', 'public-key', 'resolve-head'])
+ names.delete(name);
+ names.add('rolldown-runtime');
+ }
const admitted = new Map([['build-info.json', expectedMetadata]]);
const seen = new Set();
for (const [key, record] of Object.entries(manifest)) {
@@ -2770,6 +2855,211 @@ export async function auditOutput(webDirectory) {
imports: ['public-key', 'public-runtime', 'Button', 'resolve-head']
}
});
+ if (hasListingRevision)
+ Object.assign(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', '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: [
+ 'rolldown-runtime',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'state',
+ 'CapabilityGate',
+ 'Disclosure'
+ ],
+ css: ['_app/immutable/assets/0.HASH.css']
+ },
+ '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: [
+ 'references',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'legacy',
+ 'routes',
+ 'ListingEditor'
+ ]
+ },
+ '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: [
+ 'rolldown-runtime',
+ 'client',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'ListingEditor'
+ ]
+ },
+ '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: [
+ 'rolldown-runtime',
+ 'references',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'state',
+ 'legacy',
+ 'inbox-view',
+ 'InboxStatus',
+ 'MessageComposer'
+ ]
+ },
+ '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: [
+ 'rolldown-runtime',
+ 'references',
+ 'public-runtime',
+ '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: [
+ 'rolldown-runtime',
+ 'client',
+ 'client.svelte',
+ 'navigation',
+ '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: [
+ 'references',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'Disclosure',
+ 'SearchForm',
+ 'routes',
+ 'publishers'
+ ]
+ },
+ MessageComposer: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'MessageComposer',
+ imports: [
+ 'references',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'navigation',
+ 'inbox-view',
+ 'publishers'
+ ]
+ },
+ ListingEditor: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'ListingEditor',
+ imports: [
+ 'references',
+ 'public-runtime',
+ 'client',
+ 'Button',
+ 'CapabilityGate',
+ 'InboxSetup'
+ ]
+ },
+ 'public-runtime': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'public-runtime',
+ imports: [
+ 'rolldown-runtime',
+ 'preload-helper',
+ 'references',
+ 'Button'
+ ],
+ dynamicImports: ['negentropy']
+ },
+ routes: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'routes',
+ imports: ['references', 'Button']
+ },
+ 'rolldown-runtime': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'rolldown-runtime'
+ },
+ references: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'references',
+ imports: ['rolldown-runtime']
+ },
+ 'inbox-view': {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'inbox-view',
+ imports: ['references', 'public-runtime', 'Button']
+ },
+ publishers: {
+ file: '_app/immutable/chunks/HASH.js',
+ name: 'publishers',
+ imports: ['references', 'public-runtime', 'Button']
+ }
+ });
for (const record of Object.values(manifest)) {
const actual = { ...record };
actual.file = actual.file.includes('/chunks/')