product-view.test.ts (6789B)
1 import test from 'node:test'; 2 import assert from 'node:assert/strict'; 3 import { once } from 'node:events'; 4 import { readFile } from 'node:fs/promises'; 5 import { finalizeEvent } from 'applesauce-core/helpers'; 6 import WebSocket, { WebSocketServer } from 'ws'; 7 import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; 8 import { 9 createPublicRuntimeContext, 10 mountPublicRuntime, 11 createPublicView, 12 closePublicRuntime 13 } from '../../src/lib/runtime/public-runtime.ts'; 14 import { 15 createProductView, 16 productViewSnapshot, 17 closeProductView 18 } from '../../src/lib/catalog/product-view.ts'; 19 import { encodeProductReference } from '../../src/lib/nostr/references.ts'; 20 await test('actual SDK direct coordinate detail publishes genuine facts and asserted metadata with bounded teardown', async () => { 21 const corpus = JSON.parse( 22 await readFile( 23 new URL( 24 '../../../contracts/interop/food_availability/corpus.v1.json', 25 import.meta.url 26 ), 27 'utf8' 28 ) 29 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 30 const base = JSON.parse( 31 corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous 32 ) as { tags: string[][]; content: string; created_at: number }; 33 const keys: Uint8Array[] = []; 34 const listings = Array.from({ length: 21 }, (_, n) => { 35 const key = crypto.getRandomValues(new Uint8Array(32)); 36 keys.push(key); 37 return finalizeEvent( 38 { 39 kind: 30402, 40 created_at: base.created_at - n, 41 tags: base.tags.map((t) => 42 t[0] === 'd' ? ['d', `listing_${n}`] : [...t] 43 ), 44 content: base.content 45 }, 46 key 47 ); 48 }); 49 const profiles = keys.map((key, n) => 50 finalizeEvent( 51 { 52 kind: 0, 53 created_at: base.created_at, 54 tags: [], 55 content: JSON.stringify({ 56 display_name: `<script>Farmer ${n}</script>`, 57 pubkey: 'forged', 58 nip05: 'identity@example.org', 59 picture: 'https://tracking.example.org' 60 }) 61 }, 62 key 63 ) 64 ); 65 for (const key of keys) key.fill(0); 66 const origin = 'wss://one.example.org', 67 server = new WebSocketServer({ 68 host: '127.0.0.1', 69 port: 0, 70 maxPayload: 65536 71 }); 72 const sockets: WebSocket[] = [], 73 filters: Record<string, unknown>[] = []; 74 server.on('connection', (socket) => { 75 sockets.push(socket); 76 socket.on('message', (bytes) => { 77 const buffer = Array.isArray(bytes) 78 ? Buffer.concat(bytes) 79 : Buffer.isBuffer(bytes) 80 ? bytes 81 : Buffer.from(bytes); 82 const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; 83 if (frame[0] !== 'REQ') return; 84 const id = String(frame[1]), 85 queries = frame.slice(2) as Record<string, unknown>[]; 86 filters.push(...queries); 87 const kind = (queries[0].kinds as number[])[0]; 88 const matches = (pubkey: string, identifier?: string) => 89 queries.some((q) => { 90 const authors = q.authors as string[] | undefined; 91 return ( 92 !authors || 93 (authors.includes(pubkey) && 94 (identifier === undefined || 95 (q['#d'] as string[]).includes(identifier))) 96 ); 97 }); 98 const values = 99 kind === 0 100 ? profiles.filter((v) => matches(v.pubkey)) 101 : kind === 30402 102 ? listings.filter((v) => 103 matches(v.pubkey, v.tags.find((t) => t[0] === 'd')![1]) 104 ) 105 : []; 106 for (const value of values) 107 socket.send(JSON.stringify(['EVENT', id, value])); 108 socket.send(JSON.stringify(['EOSE', id])); 109 }); 110 }); 111 await once(server, 'listening'); 112 const address = server.address(); 113 assert.ok(address && typeof address !== 'string'); 114 const port = address.port; 115 const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), 116 oldSocket = globalThis.WebSocket; 117 class FixtureSocket extends WebSocket { 118 constructor(url: string | URL) { 119 assert.equal(String(url).replace(/\/$/, ''), origin); 120 super(`ws://127.0.0.1:${port}`); 121 } 122 } 123 Object.defineProperty(globalThis, 'window', { 124 configurable: true, 125 value: {} 126 }); 127 globalThis.WebSocket = 128 FixtureSocket as unknown as typeof globalThis.WebSocket; 129 const context = createPublicRuntimeContext(); 130 try { 131 const policy = validateRelayPolicy( 132 JSON.stringify({ 133 schemaVersion: 1, 134 public: [{ origin, read: true, write: false, nip50: false }], 135 inbox: [], 136 postingEnabled: false, 137 messagingEnabled: false, 138 operatorDenylist: [] 139 }) 140 )!; 141 const view = createPublicView(mountPublicRuntime(context, policy)!); 142 const updates: string[] = []; 143 const target = listings[0]; 144 const naddr = encodeProductReference({ 145 kind: 30402, 146 pubkey: target.pubkey, 147 identifier: target.tags.find((t) => t[0] === 'd')![1] 148 })!; 149 const owner = createProductView( 150 view, 151 naddr, 152 { nowSeconds: () => base.created_at + 10 }, 153 (snapshot) => updates.push(snapshot.outcome) 154 ); 155 for ( 156 let n = 0; 157 n < 300 && 158 (!productViewSnapshot(owner).publisher.assertedName || 159 productViewSnapshot(owner).outcome !== 'active'); 160 n++ 161 ) 162 await new Promise((resolve) => setTimeout(resolve, 10)); 163 const first = productViewSnapshot(owner); 164 assert.equal(first.outcome, 'active'); 165 assert.equal(first.eventId, target.id); 166 assert.equal( 167 first.food?.title, 168 base.tags.find((t) => t[0] === 'title')![1] 169 ); 170 assert.equal(first.publisher.pubkey, target.pubkey); 171 assert.equal(first.publisher.assertedName, true); 172 for (let n = 0; n < 300 && !updates.includes('active'); n++) 173 await new Promise((resolve) => setTimeout(resolve, 10)); 174 assert.ok(updates.includes('active')); 175 assert.ok(filters.length >= 3); 176 assert.ok( 177 filters.every( 178 (f) => 179 Array.isArray(f.authors) && 180 (f.authors as string[]).length === 1 && 181 (f.authors as string[])[0] === target.pubkey 182 ) 183 ); 184 closeProductView(owner); 185 const settled = filters.length; 186 await new Promise((resolve) => setTimeout(resolve, 300)); 187 assert.equal(filters.length, settled); 188 assert.equal(productViewSnapshot(owner).outcome, 'unavailable'); 189 } finally { 190 closePublicRuntime(context); 191 for (const key of keys) key.fill(0); 192 globalThis.WebSocket = oldSocket; 193 if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); 194 else delete (globalThis as { window?: unknown }).window; 195 for (const socket of sockets) socket.terminate(); 196 await new Promise<void>((resolve, reject) => 197 server.close((e) => (e ? reject(e) : resolve())) 198 ); 199 } 200 });