diff options
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/connect-relays-test.js | 18 | ||||
| -rw-r--r-- | tools/extension-test.js | 198 | ||||
| -rw-r--r-- | tools/feed-picture-pager-test.js | 15 | ||||
| -rw-r--r-- | tools/gif-loop-test.js | 21 | ||||
| -rw-r--r-- | tools/live-stream-test.js | 24 | ||||
| -rw-r--r-- | tools/profile-depth-test.js | 45 |
6 files changed, 321 insertions, 0 deletions
diff --git a/tools/connect-relays-test.js b/tools/connect-relays-test.js new file mode 100644 index 0000000..f54407d --- /dev/null +++ b/tools/connect-relays-test.js @@ -0,0 +1,18 @@ +// The relays a nostrconnect:// link names: relay.coinos.io first, then the +// next live ones, three in all, leaving out any this device found dead. +// Run: bun tools/connect-relays-test.js +import { connectRelays } from '../src/nostr-login.js'; +import { markRelaySick } from '../src/nostr.js'; +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const fresh = connectRelays(); +check('three relays, ours first, primal second', fresh.length === 3 && fresh[0] === 'wss://relay.coinos.io' && fresh[1] === 'wss://relay.primal.net', fresh.join(' ')); +check('nos.lol is no longer second', fresh[1] !== 'wss://nos.lol'); +markRelaySick('wss://nos.lol', 'test'); +const after = connectRelays(); +check('a relay found dead is left out, the next one takes its place', !after.includes('wss://nos.lol') && after.includes('wss://offchain.pub') && after.length === 3, after.join(' ')); +markRelaySick('wss://relay.primal.net', 'test'); markRelaySick('wss://offchain.pub', 'test'); +const one = connectRelays(); +check('relay.coinos.io stays whatever else is down', one[0] === 'wss://relay.coinos.io', one.join(' ')); +console.log(ok ? '\n✅ connect links name live relays' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/extension-test.js b/tools/extension-test.js new file mode 100644 index 0000000..6ea9e2a --- /dev/null +++ b/tools/extension-test.js @@ -0,0 +1,198 @@ +// The browser extension (extension/): a site is asked once, then signing and +// paying go through without a prompt; a blocked site stays blocked. +// Loads the built extension into Chrome, with a relay and a wallet service +// (NIP-47) of its own on this machine. +// bun extension/build.js && bun tools/extension-test.js +import puppeteer from 'puppeteer-core'; +import { finalizeEvent, generateSecretKey, getPublicKey, nip04, nip19, nip44, verifyEvent } from 'nostr-tools'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +let failed = 0; +const check = (name, ok, extra = '') => { console.log(`${ok ? '✓' : '✗'} ${name}${ok ? '' : ' ' + extra}`); if (!ok) failed++; }; +const hex = (b) => Buffer.from(b).toString('hex'); + +// ── a relay with a wallet service behind it ──────────────────────────────── +const walletSk = generateSecretKey(); +const walletPk = getPublicKey(walletSk); +const clientSk = generateSecretKey(); +const clientPk = getPublicKey(clientSk); +const asked = []; +const socks = new Set(); +const relay = Bun.serve({ + port: 0, + fetch(req, server) { return server.upgrade(req) ? undefined : new Response('relay'); }, + websocket: { + open(ws) { ws.data = { subs: new Set() }; socks.add(ws); }, + close(ws) { socks.delete(ws); }, + async message(ws, raw) { + const m = JSON.parse(raw); + if (m[0] === 'REQ') { ws.data.subs.add(m[1]); ws.send(JSON.stringify(['EOSE', m[1]])); return; } + if (m[0] === 'CLOSE') { ws.data.subs.delete(m[1]); return; } + if (m[0] !== 'EVENT') return; + const ev = m[1]; + ws.send(JSON.stringify(['OK', ev.id, true, ''])); + if (ev.kind !== 23194 || ev.pubkey !== clientPk) return; + const req = JSON.parse(await nip04.decrypt(walletSk, ev.pubkey, ev.content)); + asked.push(req); + const result = { + get_balance: { balance: 21_000_000 }, + pay_invoice: { preimage: 'ab'.repeat(32) }, + make_invoice: { invoice: 'lnbc50n1made', payment_hash: 'cd'.repeat(32) }, + list_transactions: { transactions: [{ type: 'incoming', amount: 5000_000, description: 'coffee', settled_at: 1 }] }, + }[req.method]; + const body = req.method === 'pay_invoice' && req.params.invoice === 'lnbc1toobig' + ? { result_type: req.method, error: { code: 'QUOTA_EXCEEDED', message: 'Over this connection\'s budget' } } + : { result_type: req.method, result }; + const res = finalizeEvent({ kind: 23195, created_at: Math.floor(Date.now() / 1000), tags: [['p', ev.pubkey], ['e', ev.id]], content: await nip04.encrypt(walletSk, ev.pubkey, JSON.stringify(body)) }, walletSk); + for (const s of socks) for (const sub of s.data.subs) s.send(JSON.stringify(['EVENT', sub, res])); + }, + }, +}); +const site = Bun.serve({ port: 0, fetch: () => new Response('<!doctype html><title>site</title><h1>a site</h1>', { headers: { 'content-type': 'text/html' } }) }); +const nwcUri = `nostr+walletconnect://${walletPk}?relay=${encodeURIComponent('ws://127.0.0.1:' + relay.port)}&secret=${hex(clientSk)}`; + +const userSk = generateSecretKey(); +const userPk = getPublicKey(userSk); +const peerSk = generateSecretKey(); +const peerPk = getPublicKey(peerSk); + +const browser = await puppeteer.launch({ + executablePath: process.env.CHROME || '/usr/bin/google-chrome', + headless: true, pipe: true, enableExtensions: [join(root, 'extension', 'dist')], + args: ['--no-sandbox'], +}); +try { + const sw = await browser.waitForTarget((t) => t.type() === 'service_worker' && t.url().endsWith('/background.js'), { timeout: 15000 }); + const base = sw.url().replace(/\/background\.js$/, ''); + const prompts = () => browser.targets().filter((t) => t.url().startsWith(base + '/prompt.html')); + const promptPage = async () => (await browser.waitForTarget((t) => t.url().startsWith(base + '/prompt.html'), { timeout: 8000 })).asPage(); + const noPrompt = async () => { await new Promise((r) => setTimeout(r, 400)); return prompts().length === 0; }; + // run a call in the page and report { ok, value | error } + const call = (page, expr) => page.evaluate(`(async () => { try { return { ok: true, value: await (${expr}) }; } catch (e) { return { ok: false, error: e.message }; } })()`); + + const page = await browser.newPage(); + await page.goto(`http://127.0.0.1:${site.port}/`); + check('the page has window.nostr and window.webln', await page.evaluate(() => !!(window.nostr && window.nostr._coinos && window.webln && window.webln._coinos))); + + let r = await call(page, 'window.nostr.getPublicKey()'); + check('without a key a site is told to set the extension up', !r.ok && /no key yet/.test(r.error), JSON.stringify(r)); + + // set the key up in the popup + const popup = await browser.newPage(); + await popup.goto(base + '/popup.html?tab'); + await popup.waitForSelector('#key-input', { visible: true }); + await popup.type('#key-input', 'not a key'); + await popup.click('#key-save'); + await popup.waitForFunction(() => document.getElementById('key-err').textContent.length > 0); + check('a wrong key is refused with a reason', true); + await popup.$eval('#key-input', (e) => { e.value = ''; }); + await popup.type('#key-input', nip19.nsecEncode(userSk)); + await popup.click('#key-save'); + await popup.waitForSelector('#main', { visible: true }); + const npub = nip19.npubEncode(userPk); + check('the popup shows the key\'s npub', (await popup.$eval('#npub', (e) => e.textContent)).startsWith(npub.slice(0, 14))); + + // first call from a site: one question, then the answer + await page.bringToFront(); + let pending = call(page, 'window.nostr.getPublicKey()'); + let ask = await promptPage(); + await ask.waitForSelector('#allow'); + check('the prompt names the site', (await ask.$eval('#origin', (e) => e.textContent)).includes('127.0.0.1:' + site.port)); + await ask.click('#allow'); + r = await pending; + check('after Always allow the site gets the public key', r.ok && r.value === userPk, JSON.stringify(r)); + + r = await call(page, `window.nostr.signEvent({ kind: 1, content: 'hello', tags: [['t', 'x']], created_at: 1700000000 })`); + check('signing needs no second prompt', r.ok && (await noPrompt())); + check('the signature verifies under the key', r.ok && r.value.pubkey === userPk && verifyEvent(r.value) && r.value.content === 'hello'); + + r = await call(page, `window.nostr.nip44.encrypt('${peerPk}', 'secret words')`); + check('nip44 encrypts to a peer', r.ok && nip44.decrypt(r.value, nip44.getConversationKey(peerSk, userPk)) === 'secret words', JSON.stringify(r)); + const fromPeer = nip44.encrypt('back to you', nip44.getConversationKey(peerSk, userPk)); + r = await call(page, `window.nostr.nip44.decrypt('${peerPk}', '${fromPeer}')`); + check('nip44 decrypts from a peer', r.ok && r.value === 'back to you', JSON.stringify(r)); + r = await call(page, `window.nostr.nip04.encrypt('${peerPk}', 'old style')`); + check('nip04 encrypts to a peer', r.ok && (await nip04.decrypt(peerSk, userPk, r.value)) === 'old style', JSON.stringify(r)); + + // the wallet + r = await call(page, 'window.webln.enable()'); + check('with no wallet connected, paying says so', !r.ok && /No wallet is connected/.test(r.error), JSON.stringify(r)); + await popup.bringToFront(); + await popup.type('#nwc-input', nwcUri); + await popup.click('#nwc-save'); + await popup.waitForFunction(() => /21,000/.test(document.getElementById('balance').textContent), { timeout: 10000 }); + check('the popup shows the wallet\'s balance', true); + await popup.waitForFunction(() => /coffee/.test(document.getElementById('txs').textContent), { timeout: 10000 }); + check('the popup lists recent payments', true); + if (process.env.SHOTS) { await popup.setViewport({ width: 360, height: 560 }); await popup.screenshot({ path: process.env.SHOTS + '/popup.png' }); } + + await page.bringToFront(); + pending = call(page, 'window.webln.enable()'); + ask = await promptPage(); + await ask.waitForSelector('#allow'); + if (process.env.SHOTS) await ask.screenshot({ path: process.env.SHOTS + '/prompt.png' }); + check('paying is asked about separately', /wallet/.test(await ask.$eval('#what', (e) => e.textContent))); + await ask.click('#allow'); + r = await pending; + check('the site is enabled for payments', r.ok && r.value.enabled === true, JSON.stringify(r)); + r = await call(page, 'window.webln.getBalance()'); + check('the site reads the balance in sats', r.ok && r.value.balance === 21000, JSON.stringify(r)); + r = await call(page, `window.webln.sendPayment('lnbc1invoice')`); + check('a payment returns the preimage, with no prompt', r.ok && r.value.preimage === 'ab'.repeat(32) && (await noPrompt()), JSON.stringify(r)); + check('the wallet was asked to pay that invoice', asked.some((a) => a.method === 'pay_invoice' && a.params.invoice === 'lnbc1invoice')); + r = await call(page, `window.webln.sendPayment('lnbc1toobig')`); + check('the wallet\'s refusal reaches the site', !r.ok && /budget/.test(r.error), JSON.stringify(r)); + r = await call(page, `window.webln.makeInvoice({ amount: 5, defaultMemo: 'tea' })`); + check('an invoice is made for the amount in sats', r.ok && r.value.paymentRequest === 'lnbc50n1made' && asked.some((a) => a.method === 'make_invoice' && a.params.amount === 5000 && a.params.description === 'tea'), JSON.stringify(r)); + + // another site: blocked for good + const other = await browser.newPage(); + await other.goto(`http://localhost:${site.port}/`); + pending = call(other, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + await ask.waitForSelector('#never'); + await ask.click('#never'); + r = await pending; + check('Never for this site refuses the call', !r.ok && /blocked/.test(r.error), JSON.stringify(r)); + r = await call(other, 'window.nostr.getPublicKey()'); + check('and it stays refused without asking again', !r.ok && /blocked/.test(r.error) && (await noPrompt()), JSON.stringify(r)); + + // a dismissed prompt refuses once and asks again later + const third = await browser.newPage(); + await third.goto(`http://127.0.0.1:${relay.port}/`); + pending = call(third, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + await ask.close(); + r = await pending; + check('closing the prompt refuses that one call', !r.ok && /dismissed/.test(r.error), JSON.stringify(r)); + pending = call(third, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + await ask.waitForSelector('#deny'); + await ask.click('#deny'); + r = await pending; + check('the site is asked again, and Not now refuses', !r.ok && /denied/.test(r.error), JSON.stringify(r)); + + // the popup lists the sites and can forget one + await popup.bringToFront(); + await popup.reload(); + await popup.waitForSelector('#sites li'); + const rows = await popup.$$eval('#sites li', (ls) => ls.map((l) => l.textContent)); + check('the popup lists the allowed site as signing and paying', rows.some((t) => t.includes('127.0.0.1:' + site.port) && t.includes('signs') && t.includes('pays')), rows.join(' | ')); + check('and the blocked one as blocked', rows.some((t) => t.includes('localhost') && t.includes('blocked')), rows.join(' | ')); + await popup.click(`#sites button[aria-label="Remove http://127.0.0.1:${site.port}"]`); + await popup.waitForFunction((n) => document.querySelectorAll('#sites li').length === n, {}, rows.length - 1); + await page.bringToFront(); + pending = call(page, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + check('a removed site is asked again', !!ask); + await ask.close(); + await pending; +} finally { + await browser.close(); + relay.stop(true); + site.stop(true); +} +console.log(failed ? `\n${failed} check(s) failed` : '\nall checks passed'); +process.exit(failed ? 1 : 0); diff --git a/tools/feed-picture-pager-test.js b/tools/feed-picture-pager-test.js index 947c6aa..5b5b80f 100644 --- a/tools/feed-picture-pager-test.js +++ b/tools/feed-picture-pager-test.js @@ -13,6 +13,8 @@ let ok = true; const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; const png = (size) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=' + size, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout; const PICS = { a1: png('400x300'), a2: png('300x400'), b: png('320x320'), d: png('360x240') }; +// a GIF made without a loop instruction (plays once in a browser) +const GIF = Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=5:duration=1', '-loop', '-1', '-f', 'gif', 'pipe:1']).stdout; const SK = generateSecretKey(), AUTHOR = getPublicKey(SK); const now = Math.floor(Date.now() / 1000); @@ -23,6 +25,7 @@ const server = Bun.serve({ port: 0, fetch: (req) => { if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); const m = /^\/(a1|a2|b|d)\.png$/.exec(path); if (m) return new Response(PICS[m[1]], { headers: { 'content-type': 'image/png' } }); + if (path === '/once.gif') return new Response(GIF, { headers: { 'content-type': 'image/gif' } }); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); const U = (n) => server.url.origin + '/' + n + '.png'; @@ -30,6 +33,7 @@ const seeded = [ post('two pictures ' + U('a1') + ' ' + U('a2'), 100), post('one picture ' + U('b'), 200), post('only words here, nothing to look at', 300), + post('a gif reply ' + server.url.origin + '/once.gif', 3000), // (past the fillers: the pager walk above doesn't meet it) post('a last picture ' + U('d'), 400), ...Array.from({ length: 12 }, (_, i) => post('filler ' + i + ' ' + 'lorem ipsum dolor sit amet. '.repeat(5), 500 + i * 60)), ]; @@ -93,6 +97,17 @@ try { }); check('two pictures in a post: one gallery, side by side, one height', gal.n === 2 && gal.sameRow && gal.h > 50 && gal.h < 300, JSON.stringify(gal)); check('a lone picture is not put in a gallery', gal.lone); + // a GIF that would play once is painted from a copy that loops + await waitFor(() => { window.scrollTo(0, document.body.scrollHeight); return [...document.querySelectorAll('.notes-feed [data-key]')].some((n) => n.textContent.includes('a gif reply') && n.querySelector('img.note-img')); }, null, 10000); + const gifLoop = await page.evaluate(async () => { + const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a gif reply')); + const img = r && r.querySelector('img.note-img'); + if (!img || !/^blob:/.test(img.src)) return { src: img && img.src.slice(0, 40) }; + const b = new Uint8Array(await (await fetch(img.src)).arrayBuffer()); + return { src: 'blob', loops: new TextDecoder('latin1').decode(b).includes('NETSCAPE2.0') }; + }); + check('a GIF without a loop is painted from a copy that loops', gifLoop.src === 'blob' && gifLoop.loops, JSON.stringify(gifLoop)); + await page.evaluate(() => window.scrollTo(0, 0)); await sleep(500); // painted from the tile copy (a proper resize), not the column copy shrunk by the browser check('gallery tiles are painted from the tile copies', await waitFor(() => { const g = document.querySelector('.notes-feed .note-gallery'); diff --git a/tools/gif-loop-test.js b/tools/gif-loop-test.js new file mode 100644 index 0000000..a135e36 --- /dev/null +++ b/tools/gif-loop-test.js @@ -0,0 +1,21 @@ +// A GIF made without a loop instruction plays once in every browser; the +// copy the feed paints from gets "loop forever" added. One that loops +// already, or isn't a GIF, is left alone. +// Run: bun tools/gif-loop-test.js +import { loopGif } from '../src/image-thumbnails.js'; +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const make = (args) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=64x48:rate=5:duration=1', ...args, '-f', 'gif', 'pipe:1']).stdout; +const once = new Uint8Array(make(['-loop', '-1'])), looping = new Uint8Array(make(['-loop', '0'])); +const has = (b) => Buffer.from(b).includes('NETSCAPE2.0'); +check('ffmpeg made one GIF without a loop and one with', !has(once) && has(looping)); +const fixed = loopGif(once); +check('the one-shot GIF gets the loop extension', !!fixed && has(fixed)); +const i = Buffer.from(fixed).indexOf('NETSCAPE2.0'); +check('…loop forever (count 0), right after the colour table', fixed[i + 11] === 3 && fixed[i + 12] === 1 && fixed[i + 13] === 0 && fixed[i + 14] === 0 && fixed[i + 15] === 0 && fixed[i - 3] === 0x21 && fixed[i - 2] === 0xff); +const probe = Bun.spawnSync(['ffprobe', '-v', 'error', '-count_frames', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', '-i', 'pipe:0'], { stdin: fixed }).stdout.toString().trim(); +check('the patched GIF still decodes, every frame', probe === '5', probe); +check('a GIF that loops already is left alone', loopGif(looping) === null); +check('not a GIF: left alone', loopGif(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])) === null); +console.log(ok ? '\n✅ GIFs loop' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/live-stream-test.js b/tools/live-stream-test.js index 56dcb71..cf5e056 100644 --- a/tools/live-stream-test.js +++ b/tools/live-stream-test.js @@ -224,6 +224,30 @@ try { const rowSel = '.live-message[data-key="' + chat.id + '"]'; check('comments use the group-chat bubble and shared composer', await page.$(rowSel + ' .chat-bubble') && await page.$('.live-page coinos-text#msg-draft')); check('...drawn plain on a phone, no bubble walls', await page.evaluate((q) => { const b = document.querySelector(q); return b && getComputedStyle(b).borderStyle === 'none' && getComputedStyle(b).display === 'block'; }, rowSel + ' .chat-bubble')); + // the message box is on screen without scrolling the page: the chat takes + // the room left under the stream, down to the nav (it was a fixed 60vh and + // the card ran off the bottom, where a swipe inside the chat couldn't + // bring it up) + { + const fit = await page.evaluate(() => { + window.scrollTo(0, 0); + const r = (q) => document.querySelector(q)?.getBoundingClientRect(); + const box = r('.live-page coinos-text#msg-draft'), nav = r('.app-bottom-nav'), chat = document.querySelector('.live-page .live-chat'); + return { box: box && Math.round(box.bottom), nav: nav ? Math.round(nav.top) : innerHeight, chat: chat.clientHeight, behaviour: getComputedStyle(chat).overscrollBehaviorY }; + }); + check('on a phone the message box sits on screen, over the nav', fit.box && fit.box <= fit.nav && fit.chat >= 120, JSON.stringify(fit)); + check('...and the chat no longer holds a scroll that reaches its end', fit.behaviour === 'auto'); + // a wall of chat: the box stays where it is, the newest line just above it + await page.addStyleTag({ content: '.live-page .live-chat::before{content:"";flex:none;height:3000px}' }).then((el) => el.evaluate((n) => { n.id = 'tall-chat'; })); + await page.evaluate(() => { const c = document.querySelector('.live-page .live-chat'); c.scrollTop = c.scrollHeight; }); + const tall = await page.evaluate(() => { + const r = (q) => document.querySelector(q)?.getBoundingClientRect(); + const c = document.querySelector('.live-page .live-chat'), last = c.lastElementChild.getBoundingClientRect(), nav = r('.app-bottom-nav'); + return { box: Math.round(r('.live-page coinos-text#msg-draft').bottom), nav: nav ? Math.round(nav.top) : innerHeight, last: Math.round(last.bottom), chatBottom: Math.round(c.getBoundingClientRect().bottom), pageY: window.scrollY }; + }); + check('...with a long chat too, the newest line showing above it', tall.box <= tall.nav && tall.last <= tall.chatBottom + 1 && tall.pageY === 0, JSON.stringify(tall)); + await page.evaluate(() => document.getElementById('tall-chat')?.remove()); + } check('another client’s e-only reaction arrives on the comment', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .chat-reacts')?.textContent.includes('👍'), 6000, chat.id)); check('per-comment zap receipts show under the bubble', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .zap-tally')?.textContent.includes('5'), 6000, chat.id)); await page.click(rowSel + ' .chat-bubble'); diff --git a/tools/profile-depth-test.js b/tools/profile-depth-test.js new file mode 100644 index 0000000..5aea719 --- /dev/null +++ b/tools/profile-depth-test.js @@ -0,0 +1,45 @@ +// A profile's older posts, page after page, with no months skipped. Relays +// hold different parts of an author's history: paging "older than the oldest +// post on the page" jumped from late September to April on Ben Arc's profile +// because one relay held six stray copies reaching back that far, and the +// posts around his Napstr launch (2026-08-21) are on none of the relays we +// ask — only in Primal's cache. Reads real relays (relays: 'read'; nothing +// is published). +// Run: bun tools/profile-depth-test.js +import puppeteer from './puppeteer.js'; +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 NPUB = process.env.NPUB || 'npub1c878wu04lfqcl5avfy3p5x83ndpvedaxv0dg7pxthakq3jqdyzcs2n8avm'; +const WANT = process.env.WANT || 'For all the seeders out there'; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: () => 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(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e.stack || e).slice(0, 600))); +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href + NPUB, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.notes-feed:not(.note-ghosts) > [data-key]', { timeout: 20000 }); + const seen = new Map(); // key -> text + let found = false, still = 0, last = 0; + const t0 = Date.now(); + for (let i = 0; i < 400 && !found && still < 40; i++) { + const rows = await page.evaluate(() => [...document.querySelectorAll('.notes-feed > [data-key]')].map((r) => [r.dataset.key, r.textContent.slice(0, 300)])); + for (const [k, t] of rows) seen.set(k, t); + found = [...seen.values()].some((t) => t.includes(WANT)); + still = seen.size === last ? still + 1 : 0; + last = seen.size; + await page.evaluate(() => window.scrollBy(0, 1400)); + await sleep(350); + } + console.log(` ${seen.size} posts read in ${((Date.now() - t0) / 1000).toFixed(1)} s`); + check('scrolling back reaches the Napstr launch post', found, WANT); + check('...past more than a first page', seen.size > 40, seen.size + ' posts'); + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); |
