app

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

selling-view.ts (18747B)


      1 import {
      2   identityViewSession,
      3   identityViewMatchesOwner,
      4   subscribeIdentityView,
      5   type IdentityViewContext
      6 } from '../runtime/view-context.ts';
      7 import { identitySessionSnapshot } from '../runtime/identity-session.ts';
      8 import {
      9   openBrowserDatabase,
     10   closeBrowserDatabase,
     11   type BrowserDatabase
     12 } from '../persistence/database.ts';
     13 import {
     14   createPublicPublicationRepository,
     15   publicPublicationDraftRepository,
     16   publicPublicationQuotaRepository,
     17   readPublicListingIntent
     18 } from '../persistence/public-publications.ts';
     19 import { listPublicDrafts } from '../persistence/drafts.ts';
     20 import {
     21   inspectPublicStorage,
     22   publicInventorySnapshot
     23 } from '../persistence/quota.ts';
     24 import { publicRecordSnapshot } from '../persistence/records.ts';
     25 import { inspectLocalTemplate } from '../nostr/local-template.ts';
     26 import {
     27   verifyEnvelope,
     28   verifiedEnvelopeSnapshot
     29 } from '../nostr/verified-envelope.ts';
     30 import { encodeProductReference } from '../nostr/references.ts';
     31 import { internalHref } from '../navigation-url.ts';
     32 import {
     33   projectFoodParts,
     34   type FoodProjection
     35 } from '../contracts/food-availability-v1/read.ts';
     36 import {
     37   readListingOperationView,
     38   listingOperationSnapshot,
     39   closeListingOperationView,
     40   type ListingOperationView
     41 } from './listing-operation-view.ts';
     42 import {
     43   openOwnedEditSource,
     44   ownedEditSourceSnapshot,
     45   closeOwnedEditSource
     46 } from './edit-source.ts';
     47 import {
     48   createPublicView,
     49   beginPublicViewRun,
     50   subscribePublicView,
     51   disposePublicView,
     52   publicViewOwnsRun,
     53   publicViewProjectionAvailable,
     54   publicViewRunCurrent,
     55   publicViewPublisherAllowed,
     56   subscribePublicViewVisibility,
     57   type PublicRuntime,
     58   type PublicView
     59 } from '../runtime/public-runtime.ts';
     60 import {
     61   createPublicHeadCandidate,
     62   publicHeadKey,
     63   publicHeadSnapshot,
     64   selectPublicHead,
     65   type PublicHead
     66 } from '../catalog/heads.ts';
     67 import {
     68   createPublicViewHeadResolver,
     69   resolveHeads,
     70   headResolutionSnapshot,
     71   closeHeadResolver,
     72   type HeadResolver
     73 } from '../catalog/resolve-head.ts';
     74 import {
     75   publicRequestScopeSnapshot,
     76   publicRunSnapshot,
     77   type PublicRequest,
     78   type PublicRun
     79 } from '../nostr/request-scope.ts';
     80 import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';
     81 
     82 declare const viewBrand: unique symbol;
     83 export type SellingView = Readonly<{ [viewBrand]: true }>;
     84 export type SellingRow = Readonly<{
     85   key: string;
     86   title: string;
     87   status: string;
     88   provenance: string;
     89   href?: string;
     90   editHref?: string;
     91   draftHref?: string;
     92   operations: readonly ListingOperationView[];
     93 }>;
     94 export type SellingSnapshot = Readonly<{
     95   attention: readonly SellingRow[];
     96   drafts: readonly SellingRow[];
     97   listings: readonly SellingRow[];
     98   remote: 'checking' | 'bounded' | 'partial' | 'unavailable';
     99   local: 'ready' | 'unavailable';
    100 }>;
    101 type Controller = {
    102   snapshot(): SellingSnapshot | undefined;
    103   subscribe(listener: () => void): () => void;
    104   close(): void;
    105 };
    106 type Group = {
    107   key: string;
    108   food: FoodProjection;
    109   createdAt: number;
    110   eventId: string;
    111   removal: boolean;
    112   operations: ListingOperationView[];
    113   attention: boolean;
    114   supportedEventId?: string;
    115   draftId?: string;
    116 };
    117 const views = new WeakMap<SellingView, Controller>();
    118 const active = new WeakMap<IdentityViewContext, Controller>();
    119 
    120 // Account-local presentation only. Neither a row, link nor operation disclosure
    121 // grants signing, delivery, adopted-source or current-head permission.
    122 export async function openSellingView(
    123   context: IdentityViewContext,
    124   runtime?: PublicRuntime
    125 ): Promise<SellingView | undefined> {
    126   const identity = identityViewSession(context);
    127   const observed = identity && identitySessionSnapshot(identity);
    128   const owner =
    129     observed && 'publicKey' in observed ? observed.publicKey : undefined;
    130   if (!identity || !owner || !identityViewMatchesOwner(context, owner)) return;
    131   active.get(context)?.close();
    132   let alive = true,
    133     database: BrowserDatabase | undefined;
    134   let publicView: PublicView | undefined, run: PublicRun | undefined;
    135   let resolver: HeadResolver | undefined, discovery: PublicRequest | undefined;
    136   let timer: ReturnType<typeof setTimeout> | undefined;
    137   let offIdentity = () => {};
    138   let offVisibility = () => {};
    139   let local: SellingSnapshot['local'] = 'unavailable';
    140   let remote: SellingSnapshot['remote'] = runtime ? 'checking' : 'unavailable';
    141   const listeners = new Map<symbol, () => void>();
    142   const groups = new Map<string, Group>();
    143   const draftRows = new Map<string, SellingRow>();
    144   let operationViews = Array.from<ListingOperationView>([]);
    145   const heads = new Map<string, PublicHead>();
    146   const linkedDrafts = new Map<string, true>();
    147   const current = () =>
    148     alive &&
    149     active.get(context) === controller &&
    150     identityViewSession(context) === identity &&
    151     identityViewMatchesOwner(context, owner);
    152   function notify() {
    153     for (const listener of listeners.values()) {
    154       try {
    155         listener();
    156       } catch {
    157         /* Presentation cannot interrupt owned cleanup. */
    158       }
    159     }
    160   }
    161   function close() {
    162     if (!alive) return;
    163     alive = false;
    164     offIdentity();
    165     offVisibility();
    166     if (timer !== undefined) clearTimeout(timer);
    167     for (const view of operationViews) closeListingOperationView(view);
    168     try {
    169       if (resolver) closeHeadResolver(resolver);
    170     } finally {
    171       try {
    172         if (publicView) disposePublicView(publicView);
    173       } finally {
    174         if (database) closeBrowserDatabase(database);
    175       }
    176     }
    177     if (active.get(context) === controller) active.delete(context);
    178     groups.clear();
    179     draftRows.clear();
    180     heads.clear();
    181     notify();
    182     listeners.clear();
    183   }
    184   const hrefFor = (identifier: string) => {
    185     const naddr = encodeProductReference({
    186       kind: 30402,
    187       pubkey: owner,
    188       identifier
    189     });
    190     return naddr ? internalHref(`/products/${naddr}`) : undefined;
    191   };
    192   function snapshot(): SellingSnapshot | undefined {
    193     if (!current()) return;
    194     let attention = Array.from<SellingRow>([]),
    195       listings = Array.from<SellingRow>([]);
    196     const rows =
    197       resolver &&
    198       publicView &&
    199       run &&
    200       publicViewOwnsRun(publicView, run) &&
    201       publicViewProjectionAvailable(publicView)
    202         ? headResolutionSnapshot(resolver)
    203         : [];
    204     const remoteByIdentifier = new Map(
    205       rows.map((row) => [row.state.head.identifier, row])
    206     );
    207     for (const group of groups.values()) {
    208       const known = remoteByIdentifier.get(group.food.identifier);
    209       const food = known?.state.food ?? group.food;
    210       const suppressed = known?.deletion.outcome === 'suppressed';
    211       const hidden =
    212         publicView && !publicViewPublisherAllowed(publicView, owner ?? '');
    213       const href = hidden ? undefined : hrefFor(food.identifier);
    214       const canEdit = !!(
    215         href &&
    216         group.supportedEventId &&
    217         !group.removal &&
    218         !suppressed &&
    219         (!known ||
    220           (known.state.head.id === group.supportedEventId &&
    221             known.state.display === 'focused_known'))
    222       );
    223       const row: SellingRow = {
    224         key: group.key,
    225         title: food.title,
    226         status: group.removal
    227           ? 'Removal request retained locally'
    228           : suppressed
    229             ? 'Listing no longer shown; delivery records retained'
    230             : known?.state.food
    231               ? food.status === 'sold'
    232                 ? 'Marked sold'
    233                 : 'Marked available'
    234               : 'Saved public operation; current availability unconfirmed',
    235         provenance: hidden
    236           ? 'Public source hidden here · Local publication evidence retained'
    237           : 'Local publication evidence · Remote discovery is bounded',
    238         ...(href ? { href } : {}),
    239         ...(canEdit ? { editHref: internalHref(`${href}/edit`) } : {}),
    240         ...(group.attention &&
    241         group.draftId &&
    242         draftRows.get(group.draftId)?.draftHref
    243           ? { draftHref: draftRows.get(group.draftId)?.draftHref }
    244           : {}),
    245         operations: group.operations.slice()
    246       };
    247       if (group.attention) attention = attention.concat(row);
    248       else listings = listings.concat(row);
    249       remoteByIdentifier.delete(group.food.identifier);
    250     }
    251     for (const row of remoteByIdentifier.values()) {
    252       if (
    253         !row.state.food ||
    254         (publicView && !publicViewPublisherAllowed(publicView, owner ?? '')) ||
    255         row.state.head.pubkey !== owner ||
    256         row.state.display !== 'focused_known' ||
    257         row.deletion.outcome === 'suppressed'
    258       )
    259         continue;
    260       const href = hrefFor(row.state.food.identifier);
    261       if (!href) continue;
    262       listings = listings.concat({
    263         key: row.key,
    264         title: row.state.food.title,
    265         status:
    266           row.state.food.status === 'sold' ? 'Marked sold' : 'Marked available',
    267         provenance:
    268           'Bounded remote discovery · Read-only; no supported retained prototype source',
    269         href,
    270         operations: []
    271       });
    272     }
    273     return {
    274       attention,
    275       drafts: Array.from(draftRows, ([id, row]) =>
    276         linkedDrafts.has(id) ? undefined : row
    277       ).filter((row): row is SellingRow => !!row),
    278       listings,
    279       local,
    280       remote
    281     };
    282   }
    283   const controller: Controller = {
    284     snapshot,
    285     subscribe(listener) {
    286       const stamp = Symbol();
    287       listeners.set(stamp, listener);
    288       return () => {
    289         listeners.delete(stamp);
    290       };
    291     },
    292     close
    293   };
    294   active.set(context, controller);
    295   offIdentity = subscribeIdentityView(context, () => {
    296     if (!current()) close();
    297   });
    298   try {
    299     const opened = await openBrowserDatabase();
    300     if (opened.state !== 'ready') {
    301       close();
    302       return;
    303     }
    304     if (!current()) {
    305       closeBrowserDatabase(opened.owner);
    306       close();
    307       return;
    308     }
    309     database = opened.owner;
    310     const repository = createPublicPublicationRepository(database, owner);
    311     const drafts = repository && publicPublicationDraftRepository(repository);
    312     const quota = repository && publicPublicationQuotaRepository(repository);
    313     if (!repository || !drafts || !quota) {
    314       close();
    315       return;
    316     }
    317     const saved = await listPublicDrafts(drafts);
    318     if (!current() || !saved.ok) {
    319       close();
    320       return;
    321     }
    322     for (const draft of saved.value) {
    323       const href = internalHref(`/selling/drafts/${draft.id}`);
    324       if (href)
    325         draftRows.set(draft.id, {
    326           key: `draft:${draft.id}`,
    327           title: draft.form.title || 'Untitled draft',
    328           status: 'Saved in this browser · Not published',
    329           provenance: 'Local draft',
    330           draftHref: href,
    331           operations: []
    332         });
    333     }
    334     const inspected = await inspectPublicStorage(quota);
    335     if (!current() || !inspected.ok) {
    336       close();
    337       return;
    338     }
    339     const inventory = publicInventorySnapshot(quota, inspected.value);
    340     if (!inventory) {
    341       close();
    342       return;
    343     }
    344     for (const item of inventory.rows) {
    345       if (item.family !== 'public_operation') continue;
    346       const read = await readPublicListingIntent(repository, item.id);
    347       if (!current() || read.status !== 'found') {
    348         close();
    349         return;
    350       }
    351       const record = publicRecordSnapshot(read.record, owner, item.id);
    352       if (!record || record.family !== 'public_operation') {
    353         close();
    354         return;
    355       }
    356       if (record.capture.kind !== 30402 && record.capture.kind !== 5) continue;
    357       const template = inspectLocalTemplate(
    358         record.capture.wire,
    359         owner,
    360         record.capture.kind
    361       );
    362       const base =
    363         record.capture.kind === 5 && record.source.type === 'public_head'
    364           ? verifyEnvelope(record.source.wire)
    365           : undefined;
    366       const source = base?.ok ? verifiedEnvelopeSnapshot(base.value) : template;
    367       const projected = source && projectFoodParts(source);
    368       if (!template || !projected || projected.outcome !== 'focused') continue;
    369       const key = JSON.stringify([
    370         30402,
    371         owner,
    372         projected.projection.identifier
    373       ]);
    374       const presented = await readListingOperationView(
    375         repository,
    376         identity,
    377         item.id
    378       );
    379       if (!current() || presented.status !== 'found') {
    380         if (presented.status === 'found')
    381           closeListingOperationView(presented.view);
    382         close();
    383         return;
    384       }
    385       operationViews = operationViews.concat(presented.view);
    386       const facts = listingOperationSnapshot(presented.view);
    387       if (!facts) {
    388         close();
    389         return;
    390       }
    391       let group = groups.get(key);
    392       if (!group) {
    393         group = {
    394           key,
    395           food: projected.projection,
    396           createdAt: template.created_at,
    397           eventId: record.capture.hash,
    398           removal: template.kind === 5,
    399           attention: false,
    400           operations: [],
    401           ...(record.source.type === 'draft'
    402             ? { draftId: record.source.id }
    403             : {})
    404         };
    405         groups.set(key, group);
    406       }
    407       if (
    408         template.created_at > group.createdAt ||
    409         (template.created_at === group.createdAt &&
    410           record.capture.hash < group.eventId)
    411       ) {
    412         group = {
    413           ...group,
    414           food: projected.projection,
    415           createdAt: template.created_at,
    416           eventId: record.capture.hash,
    417           removal: template.kind === 5,
    418           ...(record.source.type === 'draft'
    419             ? { draftId: record.source.id }
    420             : {})
    421         };
    422       }
    423       group = {
    424         ...group,
    425         operations: group.operations.concat(presented.view),
    426         attention:
    427           group.attention ||
    428           facts.needsAction ||
    429           !record.artifact ||
    430           facts.targets.some(
    431             (target) => !target.accepted || target.readback !== 'confirmed'
    432           )
    433       };
    434       groups.set(key, group);
    435       const capturedSource = record.source;
    436       if (
    437         capturedSource.type === 'draft' &&
    438         saved.value.some(
    439           (draft) =>
    440             draft.id === capturedSource.id &&
    441             draft.revision === capturedSource.revision
    442         )
    443       )
    444         linkedDrafts.set(capturedSource.id, true);
    445       if (record.artifact && record.capture.kind === 30402) {
    446         const proof = verifyEnvelope(record.artifact.wire);
    447         const head = proof.ok && createPublicHeadCandidate(proof.value);
    448         if (head) {
    449           const prior = heads.get(publicHeadKey(head));
    450           heads.set(publicHeadKey(head), selectPublicHead(prior, head).head);
    451         }
    452       }
    453     }
    454     // Reuse the original retained-source verifier without starting a network
    455     // run or adopting a remote source. Edit's route performs its own fresh
    456     // independent current-head checks; this metadata grants no effect custody.
    457     for (const group of groups.values()) {
    458       if (group.attention && group.draftId && draftRows.has(group.draftId))
    459         linkedDrafts.set(group.draftId, true);
    460       const naddr = encodeProductReference({
    461         kind: 30402,
    462         pubkey: owner,
    463         identifier: group.food.identifier
    464       });
    465       const source =
    466         naddr && (await openOwnedEditSource(repository, context, naddr));
    467       if (!current()) {
    468         if (source) closeOwnedEditSource(source);
    469         close();
    470         return;
    471       }
    472       const supported = source ? ownedEditSourceSnapshot(source) : undefined;
    473       if (supported)
    474         groups.set(group.key, {
    475           ...group,
    476           supportedEventId: supported.sourceEventId
    477         });
    478       if (source) closeOwnedEditSource(source);
    479     }
    480     local = 'ready';
    481     if (runtime) {
    482       try {
    483         publicView = createPublicView(runtime);
    484         offVisibility = subscribePublicViewVisibility(publicView, notify);
    485         run = beginPublicViewRun(publicView);
    486         resolver = createPublicViewHeadResolver(publicView, run, {
    487           nowSeconds: () => Math.floor(Date.now() / 1000)
    488         });
    489         discovery = subscribePublicView(
    490           publicView,
    491           run,
    492           'head',
    493           [
    494             {
    495               kinds: [30402],
    496               authors: [owner],
    497               limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay
    498             }
    499           ],
    500           (proof) => {
    501             if (!current()) return;
    502             const head = createPublicHeadCandidate(proof);
    503             if (!head || publicHeadSnapshot(head).pubkey !== owner) return;
    504             const key = publicHeadKey(head);
    505             if (
    506               !heads.has(key) &&
    507               heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun
    508             )
    509               return;
    510             heads.set(key, selectPublicHead(heads.get(key), head).head);
    511           }
    512         );
    513         function observe() {
    514           if (!current()) return;
    515           if (
    516             !publicView ||
    517             !run ||
    518             !resolver ||
    519             !discovery ||
    520             !publicViewOwnsRun(publicView, run) ||
    521             !publicViewProjectionAvailable(publicView)
    522           ) {
    523             remote = 'unavailable';
    524             notify();
    525             return;
    526           }
    527           try {
    528             if (publicViewRunCurrent(publicView, run))
    529               resolveHeads(
    530                 resolver,
    531                 Array.from(heads.values()).slice(
    532                   0,
    533                   PUBLIC_QUERY_BUDGETS.coordinatesPerRun
    534                 )
    535               );
    536             const rows = headResolutionSnapshot(resolver);
    537             const source = publicRequestScopeSnapshot(discovery);
    538             remote =
    539               source.state === 'eose' &&
    540               source.result.coverage === 'bounded-eose' &&
    541               rows.every((row) => row.coverage === 'bounded-eose')
    542                 ? 'bounded'
    543                 : publicRunSnapshot(run).activeRequests > 0
    544                   ? 'checking'
    545                   : 'partial';
    546           } catch {
    547             remote = 'partial';
    548           }
    549           notify();
    550           if (
    551             current() &&
    552             publicRunSnapshot(run).active &&
    553             publicRunSnapshot(run).activeRequests > 0
    554           )
    555             timer = setTimeout(observe, 250);
    556         }
    557         observe();
    558       } catch {
    559         remote = 'unavailable';
    560       }
    561     }
    562     if (!current()) {
    563       close();
    564       return;
    565     }
    566     const token = Object.freeze({}) as SellingView;
    567     views.set(token, controller);
    568     return token;
    569   } catch {
    570     close();
    571     return;
    572   }
    573 }
    574 export function sellingViewSnapshot(
    575   view: SellingView
    576 ): SellingSnapshot | undefined {
    577   return views.get(view)?.snapshot();
    578 }
    579 export function subscribeSellingView(
    580   view: SellingView,
    581   listener: () => void
    582 ): () => void {
    583   return views.get(view)?.subscribe(listener) ?? (() => {});
    584 }
    585 export function closeSellingView(view: SellingView): void {
    586   views.get(view)?.close();
    587 }