app

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

listing-editor.ts (22496B)


      1 import {
      2   exactLocalFields,
      3   type PublicDraftForm
      4 } from '../contracts/local-records.ts';
      5 import { canonicalLocalId, newLocalId } from '../private-handles.ts';
      6 import type { InboxSetupView } from '../messaging/inbox-setup-view.ts';
      7 import {
      8   captureNewListingReadiness,
      9   closeNewListingReadiness,
     10   type NewListingReadiness
     11 } from './new-listing-readiness.ts';
     12 import {
     13   reviewNewListing,
     14   listingReviewSnapshot,
     15   listingReviewOwnership,
     16   closeListingReview,
     17   type ListingReview,
     18   type ListingReviewResult
     19 } from './prepare-listing.ts';
     20 import { reviewOwnedRevision } from './revise-listing.ts';
     21 import { reviewMarkSold } from './mark-sold.ts';
     22 import { reviewOwnedWithdrawal } from './withdraw-listing.ts';
     23 import { decodeProductReference } from '../nostr/references.ts';
     24 import {
     25   openOwnedEditSource,
     26   ownedEditSourceSnapshot,
     27   authorizeOwnedEditSource,
     28   closeOwnedEditSource,
     29   type OwnedEditSource
     30 } from './edit-source.ts';
     31 import type { PublicRuntime } from '../runtime/public-runtime.ts';
     32 import {
     33   openBrowserDatabase,
     34   closeBrowserDatabase,
     35   type BrowserDatabase
     36 } from '../persistence/database.ts';
     37 import {
     38   createPublicPublicationRepository,
     39   publicPublicationDraftRepository,
     40   publicPublicationQuotaRepository,
     41   readPublicListingIntent
     42 } from '../persistence/public-publications.ts';
     43 import {
     44   inspectPublicStorage,
     45   publicInventorySnapshot
     46 } from '../persistence/quota.ts';
     47 import { publicRecordSnapshot } from '../persistence/records.ts';
     48 import {
     49   publicDraftRepositoryOwner,
     50   type PublicDraftRepository
     51 } from '../persistence/drafts.ts';
     52 import {
     53   createPublicDraftController,
     54   publicDraftControllerSnapshot,
     55   editPublicDraft,
     56   flushPublicDraft,
     57   retryPublicDraft,
     58   saveAndClosePublicDraft,
     59   closePublicDraftController,
     60   type PublicDraftController
     61 } from './draft-controller.ts';
     62 import {
     63   identityViewSession,
     64   identityViewMatchesOwner,
     65   type IdentityViewContext
     66 } from '../runtime/view-context.ts';
     67 import {
     68   identitySessionSnapshot,
     69   subscribeIdentityInvalidation
     70 } from '../runtime/identity-session.ts';
     71 import {
     72   readListingOperationView,
     73   closeListingOperationView,
     74   type ListingOperationView
     75 } from './listing-operation-view.ts';
     76 
     77 declare const editorBrand: unique symbol;
     78 export type ListingEditor = Readonly<{ [editorBrand]: true }>;
     79 export type ListingEditorRoute =
     80   | Readonly<{ mode: 'new' }>
     81   | Readonly<{ mode: 'draft'; draftId: string }>
     82   | Readonly<{ mode: 'edit'; naddr: string }>;
     83 export type ListingEditorSnapshot = Readonly<{
     84   mode: ListingEditorRoute['mode'];
     85   owner: string;
     86   form: PublicDraftForm;
     87   editable: boolean;
     88   draftId: string | null;
     89   state: 'editing' | 'saving' | 'saved' | 'failed' | 'read-only';
     90   failure: string | null;
     91   coordinate: string | null;
     92   sourceEventId: string | null;
     93   sourcePublishedAtSeconds?: number;
     94   operations: readonly ListingOperationView[];
     95 }>;
     96 type Editor = Readonly<{
     97   current(): boolean;
     98   retire(): void;
     99   snapshot(): ListingEditorSnapshot | undefined;
    100   edit(form: unknown): Promise<boolean>;
    101   flush(): Promise<boolean>;
    102   saveClose(): Promise<boolean>;
    103   review(
    104     setup: InboxSetupView | undefined,
    105     form: PublicDraftForm,
    106     status: 'active' | 'sold' | 'withdrawal'
    107   ): Promise<ListingReviewResult>;
    108   reviewCurrent(review: ListingReview): boolean;
    109   source(): OwnedEditSource | undefined;
    110   observe(): void;
    111   subscribe(listener: () => void): () => void;
    112 }>;
    113 const editors = new WeakMap<ListingEditor, Editor>();
    114 const active = new WeakMap<
    115   IdentityViewContext,
    116   Readonly<{ stamp: symbol; retire(): void }>
    117 >();
    118 const emptyForm: PublicDraftForm = {
    119   title: '',
    120   description: '',
    121   location: '',
    122   amount: '',
    123   currency: '',
    124   unit: '',
    125   quantity: '',
    126   contactType: '',
    127   contactValue: ''
    128 };
    129 function routeSnapshot(value: unknown): ListingEditorRoute | undefined {
    130   try {
    131     if (exactLocalFields(value, ['mode']) && value.mode === 'new')
    132       return { mode: 'new' };
    133     if (
    134       exactLocalFields(value, ['mode', 'draftId']) &&
    135       value.mode === 'draft'
    136     ) {
    137       const draftId = canonicalLocalId(value.draftId);
    138       return draftId ? { mode: 'draft', draftId } : undefined;
    139     }
    140     if (exactLocalFields(value, ['mode', 'naddr']) && value.mode === 'edit') {
    141       const reference = decodeProductReference(value.naddr);
    142       return reference ? { mode: 'edit', naddr: reference.naddr } : undefined;
    143     }
    144   } catch {
    145     return;
    146   }
    147 }
    148 // Owner admission precedes database opening and all protected hydration. Edit
    149 // mode presents validated local values; independent head authorization is later.
    150 export async function openListingEditor(
    151   context: IdentityViewContext,
    152   input: unknown,
    153   signal?: AbortSignal,
    154   runtime?: PublicRuntime
    155 ): Promise<
    156   | Readonly<{ status: 'ready'; editor: ListingEditor }>
    157   | Readonly<{
    158       status: 'unavailable';
    159       reason: 'owner' | 'resource' | 'storage' | 'source';
    160     }>
    161 > {
    162   const session = identityViewSession(context),
    163     route = routeSnapshot(input);
    164   if (!session || signal?.aborted)
    165     return { status: 'unavailable', reason: 'owner' };
    166   const identity = identitySessionSnapshot(session),
    167     owner = 'publicKey' in identity ? identity.publicKey : undefined;
    168   if (!owner || !identityViewMatchesOwner(context, owner))
    169     return { status: 'unavailable', reason: 'owner' };
    170   if (
    171     !route ||
    172     (route.mode === 'edit' &&
    173       decodeProductReference(route.naddr)?.pubkey !== owner)
    174   )
    175     return { status: 'unavailable', reason: 'resource' };
    176   if (typeof window === 'undefined' || !navigator.locks?.request)
    177     return { status: 'unavailable', reason: 'storage' };
    178   active.get(context)?.retire();
    179   const stamp = Symbol(),
    180     listeners = new Map<symbol, () => void>(),
    181     cancellation = new AbortController();
    182   let alive = true,
    183     closing = false,
    184     unsubscribe = () => {},
    185     database: BrowserDatabase | undefined,
    186     repository: PublicDraftRepository | undefined,
    187     controller: PublicDraftController | undefined;
    188   const operations = new Map<string, ListingOperationView>();
    189   let editSource: OwnedEditSource | undefined;
    190   let acquiringEditDraft:
    191     Promise<PublicDraftController | undefined> | undefined;
    192   let reviewed:
    193     | {
    194         setup: InboxSetupView | undefined;
    195         proof?: NewListingReadiness;
    196         status: 'active' | 'sold' | 'withdrawal';
    197         review: ListingReview;
    198       }
    199     | undefined;
    200   let reviewing: Promise<ListingReviewResult> | undefined;
    201   let reviewingForm: string | undefined;
    202   let reviewingSetup: InboxSetupView | undefined;
    203   let reviewingStatus: 'active' | 'sold' | 'withdrawal' | undefined;
    204   function clearReview() {
    205     if (reviewed?.proof) closeNewListingReadiness(reviewed.proof);
    206     if (reviewed) closeListingReview(reviewed.review);
    207     reviewed = undefined;
    208   }
    209   function current() {
    210     return (
    211       alive &&
    212       active.get(context)?.stamp === stamp &&
    213       identityViewSession(context) === session &&
    214       identityViewMatchesOwner(context, owner) &&
    215       (!repository || publicDraftRepositoryOwner(repository) === owner)
    216     );
    217   }
    218   let notifying = false;
    219   function notify() {
    220     if (notifying) return;
    221     notifying = true;
    222     try {
    223       for (const [key, listener] of Array.from(listeners.entries()))
    224         if (listeners.get(key) === listener) {
    225           try {
    226             listener();
    227           } catch {
    228             /*Presentation observers cannot authorize or retain ownership.*/
    229           }
    230         }
    231     } finally {
    232       notifying = false;
    233     }
    234   }
    235   function retire() {
    236     if (!alive) return;
    237     alive = false;
    238     unsubscribe();
    239     signal?.removeEventListener('abort', retire);
    240     cancellation.abort();
    241     clearReview();
    242     if (editSource) closeOwnedEditSource(editSource);
    243     if (controller) closePublicDraftController(controller);
    244     for (const operation of operations.values())
    245       closeListingOperationView(operation);
    246     if (database) closeBrowserDatabase(database);
    247     if (active.get(context)?.stamp === stamp) active.delete(context);
    248     notify();
    249     listeners.clear();
    250   }
    251   active.set(context, { stamp, retire });
    252   unsubscribe = subscribeIdentityInvalidation(session, () => {
    253     // An owned revision's delivery rechecks the same installed author. Keep
    254     // this exact editor while its original route/account/storage stay current.
    255     if (route.mode !== 'edit' || !current()) retire();
    256   });
    257   signal?.addEventListener('abort', retire, { once: true });
    258   if (signal?.aborted) retire();
    259   function unavailable(reason: 'resource' | 'storage' | 'source') {
    260     retire();
    261     return { status: 'unavailable' as const, reason };
    262   }
    263   try {
    264     const opened = await openBrowserDatabase(cancellation.signal);
    265     if (opened.state !== 'ready') return unavailable('storage');
    266     if (!current()) {
    267       closeBrowserDatabase(opened.owner);
    268       return unavailable('storage');
    269     }
    270     database = opened.owner;
    271     const publications = createPublicPublicationRepository(database, owner);
    272     repository = publications && publicPublicationDraftRepository(publications);
    273     if (!publications || !repository || !current())
    274       return unavailable('storage');
    275     const drafts = repository;
    276     let sourceForm: PublicDraftForm | undefined,
    277       coordinate: string | null = null,
    278       sourceEventId: string | null = null;
    279     if (route.mode === 'edit') {
    280       editSource = await openOwnedEditSource(
    281         publications,
    282         context,
    283         route.naddr,
    284         runtime,
    285         cancellation.signal
    286       );
    287       if (!current()) return unavailable('source');
    288       const retained = editSource && ownedEditSourceSnapshot(editSource);
    289       if (!retained) return unavailable('source');
    290       sourceForm = retained.form;
    291       coordinate = route.naddr;
    292       sourceEventId = retained.sourceEventId;
    293     } else {
    294       const acquired = await createPublicDraftController(
    295         drafts,
    296         emptyForm,
    297         route.mode === 'draft' ? route.draftId : undefined
    298       );
    299       if (!current()) {
    300         if (acquired) closePublicDraftController(acquired);
    301         return unavailable('resource');
    302       }
    303       controller = acquired;
    304       if (!controller) return unavailable('resource');
    305       if (route.mode === 'draft') {
    306         const quota = publicPublicationQuotaRepository(publications);
    307         if (!quota) return unavailable('source');
    308         const inspected = await inspectPublicStorage(quota);
    309         if (!current() || !inspected.ok) return unavailable('source');
    310         const inventory = publicInventorySnapshot(quota, inspected.value);
    311         if (!inventory) return unavailable('source');
    312         for (const item of inventory.rows) {
    313           if (item.family !== 'public_operation') continue;
    314           const read = await readPublicListingIntent(publications, item.id);
    315           if (!current()) return unavailable('source');
    316           const row =
    317             read.status === 'found' &&
    318             publicRecordSnapshot(read.record, owner, item.id);
    319           if (!row || row.family !== 'public_operation')
    320             return unavailable('source');
    321           if (row.source.type !== 'draft' || row.source.id !== route.draftId)
    322             continue;
    323           if (operations.size >= 100) return unavailable('source');
    324           const operation = await readListingOperationView(
    325             publications,
    326             session,
    327             item.id
    328           );
    329           if (!current()) {
    330             if (operation.status === 'found')
    331               closeListingOperationView(operation.view);
    332             return unavailable('source');
    333           }
    334           if (operation.status !== 'found') return unavailable('source');
    335           operations.set(item.id, operation.view);
    336         }
    337       }
    338     }
    339     if (!current()) return unavailable('source');
    340     function reviewCurrent(review: ListingReview) {
    341       const preview = listingReviewSnapshot(review),
    342         local = controller && publicDraftControllerSnapshot(controller);
    343       return !!(
    344         current() &&
    345         !closing &&
    346         !operations.size &&
    347         route &&
    348         reviewed?.review === review &&
    349         listingReviewOwnership(review)?.current() &&
    350         preview &&
    351         local?.state === 'saved' &&
    352         local.draft &&
    353         preview.owner === owner &&
    354         preview.draftId === local.draft.id &&
    355         preview.draftRevision === local.draft.revision &&
    356         JSON.stringify(preview.form) === JSON.stringify(local.form)
    357       );
    358     }
    359     const value: Editor = {
    360       current,
    361       retire,
    362       source: () => (current() ? editSource : undefined),
    363       observe: () => {
    364         if (current()) notify();
    365       },
    366       snapshot() {
    367         if (!current()) {
    368           retire();
    369           return;
    370         }
    371         const local = controller && publicDraftControllerSnapshot(controller);
    372         return {
    373           mode: route.mode,
    374           owner,
    375           form: local ? local.form : { ...(sourceForm ?? emptyForm) },
    376           editable:
    377             operations.size === 0 &&
    378             (route.mode !== 'edit' ||
    379               !!(editSource && authorizeOwnedEditSource(editSource))),
    380           draftId: local?.draft?.id ?? null,
    381           state:
    382             local && operations.size === 0
    383               ? local.state === 'closed'
    384                 ? 'failed'
    385                 : local.state
    386               : 'read-only',
    387           failure: local?.failure ?? null,
    388           coordinate,
    389           sourceEventId,
    390           ...(editSource
    391             ? {
    392                 sourcePublishedAtSeconds:
    393                   ownedEditSourceSnapshot(editSource)?.publishedAtSeconds
    394               }
    395             : {}),
    396           operations: Array.from(operations.values())
    397         };
    398       },
    399       async edit(input) {
    400         if (!current()) {
    401           retire();
    402           return false;
    403         }
    404         if (route.mode === 'edit') {
    405           if (
    406             !editSource ||
    407             !authorizeOwnedEditSource(editSource) ||
    408             !sourceForm
    409           )
    410             return false;
    411           if (!controller) {
    412             acquiringEditDraft ??= createPublicDraftController(
    413               drafts,
    414               sourceForm
    415             );
    416             const acquired = await acquiringEditDraft;
    417             if (!current() || !authorizeOwnedEditSource(editSource)) {
    418               if (acquired) closePublicDraftController(acquired);
    419               return false;
    420             }
    421             controller = acquired;
    422           }
    423         }
    424         if (!controller || operations.size) return false;
    425         if (!editPublicDraft(controller, input)) return false;
    426         clearReview();
    427         notify();
    428         const pending = flushPublicDraft(controller);
    429         await Promise.resolve();
    430         if (!current()) {
    431           retire();
    432           return false;
    433         }
    434         notify();
    435         const saved = await pending;
    436         if (!current()) {
    437           retire();
    438           return false;
    439         }
    440         notify();
    441         return saved;
    442       },
    443       async flush() {
    444         if (!current()) {
    445           retire();
    446           return false;
    447         }
    448         if (!controller || operations.size) return false;
    449         const pending = flushPublicDraft(controller);
    450         await Promise.resolve();
    451         if (!current()) {
    452           retire();
    453           return false;
    454         }
    455         notify();
    456         const saved = await pending;
    457         if (!current()) {
    458           retire();
    459           return false;
    460         }
    461         notify();
    462         return saved;
    463       },
    464       async saveClose() {
    465         if (!current() || !controller || operations.size || closing)
    466           return false;
    467         closing = true;
    468         try {
    469           if (publicDraftControllerSnapshot(controller)?.state === 'failed') {
    470             const retried = await retryPublicDraft(controller);
    471             if (!current()) {
    472               retire();
    473               return false;
    474             }
    475             notify();
    476             if (!retried) return false;
    477           }
    478           const saved = await saveAndClosePublicDraft(controller);
    479           if (!current()) {
    480             retire();
    481             return false;
    482           }
    483           if (!saved) {
    484             notify();
    485             return false;
    486           }
    487           retire();
    488           return true;
    489         } finally {
    490           closing = false;
    491         }
    492       },
    493       review(setup, input, status) {
    494         const local = controller && publicDraftControllerSnapshot(controller);
    495         if (
    496           !current() ||
    497           closing ||
    498           !controller ||
    499           !local ||
    500           (route.mode === 'edit' && !editSource) ||
    501           (route.mode !== 'edit' && status !== 'active') ||
    502           operations.size ||
    503           !exactLocalFields(input, Object.keys(emptyForm)) ||
    504           JSON.stringify(input) !== JSON.stringify(local.form)
    505         )
    506           return Promise.resolve({
    507             status: 'blocked',
    508             reason: 'invalid_scope'
    509           });
    510         if (
    511           reviewed &&
    512           reviewed.status === status &&
    513           reviewed.setup === setup &&
    514           reviewCurrent(reviewed.review)
    515         )
    516           return Promise.resolve({ status: 'review', review: reviewed.review });
    517         const formWire = JSON.stringify(local.form);
    518         if (reviewing)
    519           return reviewingForm === formWire &&
    520             reviewingSetup === setup &&
    521             reviewingStatus === status
    522             ? reviewing
    523             : Promise.resolve({ status: 'blocked', reason: 'conflict' });
    524         clearReview();
    525         const proof =
    526             route.mode === 'edit'
    527               ? undefined
    528               : captureNewListingReadiness(
    529                   session,
    530                   setup,
    531                   'reviewed_new_listing_inbox'
    532                 ),
    533           command = newLocalId();
    534         if ((!proof && route.mode !== 'edit') || !command) {
    535           if (proof) closeNewListingReadiness(proof);
    536           return Promise.resolve({ status: 'blocked', reason: 'unavailable' });
    537         }
    538         const original = controller;
    539         reviewingForm = formWire;
    540         reviewingSetup = setup;
    541         reviewingStatus = status;
    542         const prepared =
    543           route.mode === 'edit' && editSource
    544             ? status === 'withdrawal'
    545               ? reviewOwnedWithdrawal(
    546                   editSource,
    547                   original,
    548                   command,
    549                   'reviewed_owned_withdrawal'
    550                 )
    551               : status === 'sold'
    552                 ? reviewMarkSold(
    553                     editSource,
    554                     original,
    555                     command,
    556                     'reviewed_sold_availability'
    557                   )
    558                 : reviewOwnedRevision(
    559                     editSource,
    560                     original,
    561                     command,
    562                     'reviewed_owned_revision'
    563                   )
    564             : proof
    565               ? reviewNewListing(
    566                   publications,
    567                   original,
    568                   proof,
    569                   command,
    570                   'reviewed_new_listing'
    571                 )
    572               : Promise.resolve<ListingReviewResult>({
    573                   status: 'blocked',
    574                   reason: 'unavailable'
    575                 });
    576         const pending = prepared
    577           .then((result): ListingReviewResult => {
    578             const actual = publicDraftControllerSnapshot(original);
    579             if (
    580               !current() ||
    581               closing ||
    582               !actual ||
    583               JSON.stringify(actual.form) !== formWire ||
    584               result.status !== 'review'
    585             ) {
    586               if (proof) closeNewListingReadiness(proof);
    587               if (result.status === 'review') closeListingReview(result.review);
    588               return result.status === 'blocked'
    589                 ? result
    590                 : { status: 'blocked', reason: 'conflict' };
    591             }
    592             reviewed = { setup, proof, status, review: result.review };
    593             if (!reviewCurrent(result.review)) {
    594               clearReview();
    595               return { status: 'blocked', reason: 'conflict' };
    596             }
    597             return result;
    598           })
    599           .finally(() => {
    600             if (reviewing === pending) {
    601               reviewing = undefined;
    602               reviewingForm = undefined;
    603               reviewingSetup = undefined;
    604               reviewingStatus = undefined;
    605             }
    606           });
    607         reviewing = pending;
    608         return pending;
    609       },
    610       reviewCurrent,
    611       subscribe(listener) {
    612         if (!current()) return () => {};
    613         const key = Symbol();
    614         listeners.set(key, listener);
    615         return () => {
    616           listeners.delete(key);
    617         };
    618       }
    619     };
    620     const editor = Object.freeze({}) as ListingEditor;
    621     editors.set(editor, value);
    622     return { status: 'ready', editor };
    623   } catch {
    624     return unavailable('storage');
    625   }
    626 }
    627 export function listingEditorSnapshot(
    628   editor: ListingEditor
    629 ): ListingEditorSnapshot | undefined {
    630   return editors.get(editor)?.snapshot();
    631 }
    632 export function editListingEditor(
    633   editor: ListingEditor,
    634   form: unknown
    635 ): Promise<boolean> {
    636   return editors.get(editor)?.edit(form) ?? Promise.resolve(false);
    637 }
    638 export function flushListingEditor(editor: ListingEditor): Promise<boolean> {
    639   return editors.get(editor)?.flush() ?? Promise.resolve(false);
    640 }
    641 export function closeListingEditor(editor: ListingEditor): void {
    642   editors.get(editor)?.retire();
    643 }
    644 export function listingEditorEditSource(
    645   editor: ListingEditor
    646 ): OwnedEditSource | undefined {
    647   return editors.get(editor)?.source();
    648 }
    649 export function observeListingEditor(editor: ListingEditor): void {
    650   editors.get(editor)?.observe();
    651 }
    652 export function saveAndCloseListingEditor(
    653   editor: ListingEditor
    654 ): Promise<boolean> {
    655   return editors.get(editor)?.saveClose() ?? Promise.resolve(false);
    656 }
    657 export function subscribeListingEditor(
    658   editor: ListingEditor,
    659   listener: () => void
    660 ): () => void {
    661   return editors.get(editor)?.subscribe(listener) ?? (() => {});
    662 }
    663 // Original editor custody remains private. Review never reserves or signs.
    664 export function reviewListingEditor(
    665   editor: ListingEditor,
    666   setup: InboxSetupView | undefined,
    667   form: PublicDraftForm,
    668   status: 'active' | 'sold' | 'withdrawal' = 'active'
    669 ): Promise<ListingReviewResult> {
    670   return (
    671     editors.get(editor)?.review(setup, form, status) ??
    672     Promise.resolve({ status: 'blocked', reason: 'invalid_scope' })
    673   );
    674 }
    675 export function listingEditorReviewCurrent(
    676   editor: ListingEditor,
    677   review: ListingReview
    678 ): boolean {
    679   return editors.get(editor)?.reviewCurrent(review) ?? false;
    680 }