app

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

write.ts (5301B)


      1 import { publicContact, type PublicContactInput } from './contact.ts';
      2 import { foodPrice, foodQuantity } from './values.ts';
      3 import {
      4   boundedUtf8,
      5   foodTextValid,
      6   foodIdentifierValid,
      7   foodContentPresent
      8 } from './text.ts';
      9 import {
     10   boundedEnvelopeNumbers,
     11   safeUnsignedInteger
     12 } from '../../nostr/envelope-bounds.ts';
     13 export type FoodDraft = Readonly<{
     14   identifier: string;
     15   title: string;
     16   description: string;
     17   location: string;
     18   amount: string;
     19   currency: string;
     20   unit: string;
     21   quantity?: string;
     22   published_at: number;
     23   created_at: number;
     24   status: 'active' | 'sold';
     25   contact?: PublicContactInput;
     26 }>;
     27 export type UnsignedFoodParts = Readonly<{
     28   kind: 30402;
     29   content: string;
     30   tags: readonly (readonly string[])[];
     31 }>;
     32 export type FoodDraftErrorCode =
     33   | 'identifier_invalid'
     34   | 'title_invalid'
     35   | 'location_invalid'
     36   | 'description_invalid'
     37   | 'summary_invalid'
     38   | 'price_invalid'
     39   | 'quantity_invalid'
     40   | 'timestamp_invalid'
     41   | 'status_invalid'
     42   | 'contact_invalid'
     43   | 'wire_too_large';
     44 export type FoodBuildResult =
     45   | Readonly<{ ok: true; wire_parts: UnsignedFoodParts; summary: string }>
     46   | Readonly<{
     47       ok: false;
     48       error: Readonly<{ code: FoodDraftErrorCode; message: string }>;
     49     }>;
     50 function failure(code: FoodDraftErrorCode): FoodBuildResult {
     51   return {
     52     ok: false,
     53     error: {
     54       code,
     55       message:
     56         'Public food draft does not satisfy the selected field or size limit'
     57     }
     58   };
     59 }
     60 function text(value: string, maximum: number): boolean {
     61   return (
     62     typeof value === 'string' &&
     63     foodTextValid(value) &&
     64     Array.from(value).length <= maximum
     65   );
     66 }
     67 function normalizedDescription(value: string): string {
     68   return value.split('\r\n').join('\n').split('\r').join('\n').trim();
     69 }
     70 function summary(value: string): string {
     71   // The signed content retains its normalized line layout. Only this derived
     72   // review field collapses whitespace; complete Unicode code points survive.
     73   return Array.from(
     74     Array.from(value)
     75       .map((character) =>
     76         /\p{White_Space}/u.test(character) ? ' ' : character
     77       )
     78       .join('')
     79       .split(' ')
     80       .filter((word) => word.length > 0)
     81       .join(' ')
     82   )
     83     .slice(0, 240)
     84     .join('')
     85     .trimEnd();
     86 }
     87 export function buildFoodTemplate(input: FoodDraft): FoodBuildResult {
     88   // Snapshot only known fields once; accessors cannot swap validated values.
     89   const {
     90     identifier,
     91     title,
     92     description: sourceDescription,
     93     location,
     94     amount,
     95     currency,
     96     unit,
     97     quantity: sourceQuantity,
     98     published_at,
     99     created_at,
    100     status,
    101     contact: sourceContact
    102   } = input;
    103   if (typeof identifier !== 'string' || !foodIdentifierValid(identifier))
    104     return failure('identifier_invalid');
    105   if (!text(title, 160)) return failure('title_invalid');
    106   if (!text(location, 160)) return failure('location_invalid');
    107   if (
    108     typeof sourceDescription !== 'string' ||
    109     !boundedUtf8(sourceDescription, 16384)
    110   )
    111     return failure('description_invalid');
    112   const description = normalizedDescription(sourceDescription);
    113   if (!foodContentPresent(description)) return failure('description_invalid');
    114   const derived = summary(description);
    115   if (!foodTextValid(derived)) return failure('summary_invalid');
    116   const price = foodPrice(amount, currency, unit);
    117   if (price === undefined) return failure('price_invalid');
    118   const quantity =
    119     sourceQuantity === undefined
    120       ? undefined
    121       : foodQuantity(sourceQuantity, unit);
    122   if (sourceQuantity !== undefined && quantity === undefined)
    123     return failure('quantity_invalid');
    124   const numbers = boundedEnvelopeNumbers(30402, created_at);
    125   const publishedAt = safeUnsignedInteger(published_at);
    126   if (
    127     numbers === undefined ||
    128     publishedAt === undefined ||
    129     publishedAt === 0 ||
    130     publishedAt > numbers.created_at
    131   )
    132     return failure('timestamp_invalid');
    133   if (status !== 'active' && status !== 'sold')
    134     return failure('status_invalid');
    135   const contact =
    136     sourceContact === undefined ? undefined : publicContact(sourceContact);
    137   if (sourceContact !== undefined && contact === undefined)
    138     return failure('contact_invalid');
    139   const content =
    140     description +
    141     (contact === undefined ? '' : `\n\nPublic contact: ${contact.href}`);
    142   if (!boundedUtf8(content, 16384)) return failure('description_invalid');
    143   const tags: readonly (readonly string[])[] = [
    144     ['d', identifier],
    145     ['title', title],
    146     ['summary', derived],
    147     ['published_at', String(publishedAt)],
    148     ['location', location],
    149     ['price', price.amount, price.currency],
    150     ['radroots:price_unit', price.unit],
    151     ...(quantity === undefined
    152       ? []
    153       : [['radroots:quantity', quantity.amount, quantity.unit]]),
    154     ['status', status]
    155   ];
    156   // Bound the prospective compact signed envelope using fixed-size public hex
    157   // placeholders. No signature, key, image or caller extra is manufactured.
    158   const maximumWire = JSON.stringify({
    159     id: '0'.repeat(64),
    160     pubkey: '0'.repeat(64),
    161     created_at: numbers.created_at,
    162     kind: 30402,
    163     tags,
    164     content,
    165     sig: '0'.repeat(128)
    166   });
    167   if (!boundedUtf8(maximumWire, 262144)) return failure('wire_too_large');
    168   return {
    169     ok: true,
    170     wire_parts: { kind: 30402, content, tags },
    171     summary: derived
    172   };
    173 }