1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
|
// A plain link in a post becomes the card its page describes: the registrar
// is asked for the page's Open Graph data (shimmed here), the picture is
// warmed with the rest of the post, and the row paints whole. A page with
// nothing to say stays a bare link; pictures and YouTube keep their own
// boxes.
// Run: bun tools/link-preview-test.js
import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js';
import { cacheKeyFor } from '../src/wallet.js';
import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
import { privateKeyFromSeedWords } from 'nostr-tools/nip06';
import { buildHtml } from '../build.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let ok = true;
const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
const AUTHOR = generateSecretKey(); const APK = getPublicKey(AUTHOR);
const now = Math.floor(Date.now() / 1000);
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
const POSTS = [
finalizeEvent({ kind: 1, created_at: now - 30, tags: [], content: 'Well, yeah https://news.example/story/1' }, AUTHOR),
finalizeEvent({ kind: 1, created_at: now - 60, tags: [], content: 'nothing here https://blank.example/page' }, AUTHOR),
finalizeEvent({ kind: 1, created_at: now - 90, tags: [], content: 'a picture http://localhost:5311/pic.png' }, AUTHOR),
finalizeEvent({ kind: 1, created_at: now - 120, tags: [], content: 'film night https://paff.club/movie/1382-hackers-1995/play?q=1080p&t=4910' }, AUTHOR),
];
const PROFILE = finalizeEvent({ kind: 0, created_at: now - 100, tags: [], content: JSON.stringify({ name: 'Linker', picture: 'http://localhost:5311/face.png' }) }, AUTHOR);
const html = await buildHtml({ minify: true, pwa: false });
const previewHits = [];
const server = Bun.serve({ port: 5311, fetch: (req) => {
const u = new URL(req.url);
if (u.pathname === '/preview') {
const target = u.searchParams.get('url'); previewHits.push(target);
const meta = target === 'https://news.example/story/1'
? { url: target, title: 'Lawmakers doubt the plan', description: 'A story in one line.', image: 'http://localhost:5311/card.png', site: 'News Example' }
: target === 'https://movies.example/movie/1382/play?t=4910' || target.startsWith('https://paff.club/movie/1382')
? { url: target, title: 'Hackers (1995) · from 1:21:50', description: 'Teenage hackers.', image: 'http://localhost:5311/movie.png', site: 'PAFF' }
: {};
return new Response(JSON.stringify(meta), { headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' } });
}
if (u.pathname.endsWith('.png')) return new Response(PNG, { headers: { 'content-type': 'image/png' } });
if (u.pathname.startsWith('/punks') || u.pathname === '/verify-worker.js') return new Response(Bun.file('dist' + u.pathname));
return new Response(html, { headers: { 'content-type': 'text/html' } });
} });
const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] });
const page = await browser.newPage();
await page.evaluateOnNewDocument((posts, profile) => {
// the registrar's preview endpoint answers from this test's server
const realFetch = window.fetch;
window.fetch = (u, o) => realFetch(String(u).startsWith('https://names.coinos.io/preview') ? String(u).replace('https://names.coinos.io', 'http://localhost:5311') : u, o);
const Real = window.WebSocket;
window.WebSocket = function (...a) {
const ws = new Real(...a);
const send = ws.send.bind(ws);
ws.send = (data) => {
try {
const m = JSON.parse(data);
if (m[0] === 'REQ') {
const f = m[2] || {};
let evs = [];
if ((f.kinds || []).includes(1) && (f.authors || []).includes(profile.pubkey)) evs = posts;
if ((f.kinds || []).includes(0) && (f.authors || []).includes(profile.pubkey)) evs = [profile];
setTimeout(() => {
for (const e of evs) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], e]) }));
ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) }));
}, 0);
return;
}
if (m[0] === 'EVENT') return;
} catch {}
return send(data);
};
return ws;
};
window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
}, POSTS, PROFILE);
const errs = [];
page.on('pageerror', (e) => errs.push(String(e)));
const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
try {
await page.setViewport({ width: 390, height: 844 });
await page.goto('http://localhost:5311/', { waitUntil: 'domcontentloaded' });
await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400);
await click('create a new wallet'); await sleep(600);
await seedWords(page);
const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
await skipSeedCheck(page);
await waitText('receive', 20000);
const base = cacheKeyFor(mn + '\n');
// follow the author, so the feed asks for their posts
await page.evaluate(([k, pk]) => {
localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) }));
localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Linker', t: Date.now() } }));
localStorage.setItem('btc-wallet-feed:' + k, 'following'); // new wallets open on Popular
}, [base, APK]);
await page.reload({ waitUntil: 'domcontentloaded' });
await waitText('receive', 20000);
await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click());
await page.waitForSelector('.notes-feed:not([data-booting]) > .row', { timeout: 30000 });
await sleep(800);
const rows = await page.evaluate(() => [...document.querySelectorAll('.notes-feed > .row')].map((r) => ({
text: r.textContent.trim().slice(0, 60),
card: !!r.querySelector('.link-card'),
title: r.querySelector('.link-title')?.textContent,
thumb: r.querySelector('.link-thumb')?.getAttribute('src') || r.querySelector('.link-thumb')?.dataset.lazySrc,
thumbShown: (() => { const i = r.querySelector('.link-thumb'); return !!i && i.complete && i.naturalWidth > 0; })(),
bareLink: !!r.querySelector('a[href^="https://blank.example"]'),
img: !!r.querySelector('img.note-img'),
})));
const story = rows.find((r) => /well, yeah/i.test(r.text));
const blank = rows.find((r) => /nothing here/i.test(r.text));
const pic = rows.find((r) => /a picture/i.test(r.text));
check('a post with a link paints its card', !!story && story.card, JSON.stringify(story));
check('...with the page\'s title', story?.title === 'Lawmakers doubt the plan', story?.title);
check('...and its picture, already decoded', !!story?.thumb && story.thumbShown, JSON.stringify({ thumb: story?.thumb, shown: story?.thumbShown }));
check('a page with nothing to show stays a bare link', !!blank && blank.bareLink && !blank.card, JSON.stringify(blank));
check('a picture link is still a picture, not a card', !!pic && pic.img && !pic.card, JSON.stringify(pic));
// a PAFF film link plays in the post, PAFF's bare player loaded only on a tap
const paff = await page.evaluate(() => {
const r = [...document.querySelectorAll('.notes-feed > .row')].find((n) => /film night/.test(n.textContent));
const b = r && r.querySelector('.paff-embed');
return b && { title: b.querySelector('.paff-title')?.textContent, poster: !!b.querySelector('img.yt-poster'), frame: !!b.querySelector('iframe') };
});
check('a PAFF film link shows as a player with its backdrop and title', !!paff && paff.poster && /Hackers/.test(paff.title || '') && !paff.frame, JSON.stringify(paff));
const src = await page.evaluate(() => {
const b = [...document.querySelectorAll('.paff-embed')][0];
b.querySelector('.yt-play').click();
const f = b.querySelector('iframe'), s = f && f.getAttribute('src');
if (f) f.src = 'about:blank'; // (the test doesn't stream the film)
return s;
});
check('...and a tap loads PAFF\'s embed player there, the link\'s query kept', src === 'https://paff.club/embed/movie/1382-hackers-1995?q=1080p&t=4910', src);
check('the registrar was asked once per link', previewHits.filter((u) => u === 'https://news.example/story/1').length === 1 && !previewHits.some((u) => u.endsWith('.png')), JSON.stringify(previewHits));
let kept = 0; // written behind, a second after the card was learned
for (let i = 0; i < 12 && kept < 2; i++) { kept = await page.evaluate(() => JSON.parse((window.coinosCache || localStorage).getItem('coinos-link-previews') || '[]').length); if (kept < 2) await sleep(300); }
check('the cards are remembered for next time', kept === 2, kept + ' kept'); // the story's and the film's
// a draft's preview shows the card too (Adam, 2026-11-17: a paff.club
// movie link stayed a bare URL in Preview), once the typing settles
const opened = await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((n) => (n.getAttribute('aria-label') || n.textContent).trim().toLowerCase() === 'new post'); if (b) { b.click(); return true; } return false; });
await sleep(400);
const typeDraft = (v) => page.evaluate((val) => { const e = document.querySelector('coinos-text'); e.focus(); e.value = val; e.dispatchEvent(new Event('input', { bubbles: true })); }, v);
await typeDraft('watch this\n\nhttps://movies.example/movie/1382/play?t=4910');
await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /preview/i.test(b.getAttribute('aria-label') || ''))?.click());
let draft = null;
for (let i = 0; i < 20; i++) { draft = await page.evaluate(() => { const p = document.querySelector('.draft-preview'); return p && { card: !!p.querySelector('.link-card'), title: p.querySelector('.link-title')?.textContent }; }); if (draft?.card) break; await sleep(250); }
check('a draft\'s preview shows the link as its card', opened && draft?.card && /Hackers/.test(draft.title || ''), JSON.stringify(draft));
check('...asked for once the typing settled, not per keystroke', previewHits.filter((u) => u.startsWith('https://movies.example')).length === 1, JSON.stringify(previewHits));
check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} finally { await browser.close(); server.stop(true); }
console.log(ok ? '\n✅ links show as the cards their pages describe' : '\n❌ failed');
process.exit(ok ? 0 : 1);
|