// Page-builder lead conversions + audience pixel fixes (2026-10-22, Marty approved B2/B3/B4). Two parts: // 1) unit: audiences.js on a throwaway data dir: event names stored (and kept off old rows), counted per audience, // pruned with their hits; old {key: ts} rows still count and match. // 2) end to end: boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB, no mail key, devCode // sign-in, no curtain, no outbound). Spin link click -> member page (?lsid and cookie-only) -> built-in form -> // lead stored WITH lsid -> rotator 'lead' conversion -> postback attempt logged. Then the pixel: N cookieless hits // from one IP + UA count as one visitor, the e= name is stored. // node qa/lsid-pixel.test.mjs (from the site dir; no internet needed) // Env: PORT (default 8971) import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import http from 'node:http'; import crypto from 'node:crypto'; import { spawn } from 'node:child_process'; import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); const PORT = Number(process.env.PORT || 8971); const results = []; let failed = 0; const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; }; const sleep = ms => new Promise(r => setTimeout(r, ms)); // ---------- 1) unit: audiences.js ---------- { const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'aud-unit-')); const now = Date.now(); // an old-shape file: hits values are plain timestamps, no ev map fs.writeFileSync(path.join(UD, 'audiences.json'), JSON.stringify({ v: 1, audiences: { 'la-aaaaaa': { id: 'la-aaaaaa', owner: 'm@x.test', name: 'Old', auto: false, created: now - 1e6 } }, hits: { 'la-aaaaaa': { 'aaaaaaaaaaaaaaaaaaaa': now - 1000, 'bbbbbbbbbbbbbbbbbbbb': now - 31 * 86400000, 's:cccccccccccccccccccc': now - 1000 } } })); const A = require(path.join(site, 'audiences.js')); A.init({ dataDir: UD }); let s = A.list('m@x.test').find(a => a.id === 'la-aaaaaa'); check(s && s.size30 === 1 && s.soft === 1 && JSON.stringify(s.events) === '{}', 'old-shape rows still count (1 live vid, 1 soft, stale vid ignored)', JSON.stringify(s)); check(A.has('la-aaaaaa', 'aaaaaaaaaaaaaaaaaaaa', null) && !A.has('la-aaaaaa', 'bbbbbbbbbbbbbbbbbbbb', null), 'old-shape rows still match'); check(A.cleanEvent('Lead') === 'lead' && A.cleanEvent('sign_up-2') === 'sign_up-2' && A.cleanEvent('bad name') === '' && A.cleanEvent('') === '' && A.cleanEvent('a'.repeat(33)) === '' && A.cleanEvent(null) === '', 'event names sanitized to [a-z0-9_-]{1,32}'); A.hit('la-aaaaaa', 'dddddddddddddddddddd', 's:eeeeeeeeeeeeeeeeeeee', 'lead'); A.hit('la-aaaaaa', 'aaaaaaaaaaaaaaaaaaaa', null, 'Purchase'); A.hit('la-aaaaaa', 'ffffffffffffffffffff', null, 'no good!'); s = A.list('m@x.test').find(a => a.id === 'la-aaaaaa'); check(s.size30 === 3 && s.soft === 2, 'new hits count alongside old rows', JSON.stringify(s)); check(s.events.lead === 1 && s.events.purchase === 1 && Object.keys(s.events).length === 2 && s.eventsSoft.lead === 1, 'events counted per audience (cookie visitors and soft keys apart), bad name dropped', JSON.stringify([s.events, s.eventsSoft])); A.hit('la-aaaaaa', 'dddddddddddddddddddd', null, ''); s = A.list('m@x.test').find(a => a.id === 'la-aaaaaa'); check(s.events.lead === 1, 'a hit without an event keeps the last event name', JSON.stringify(s.events)); const pr = A.prune(); A.flush(); const disk = JSON.parse(fs.readFileSync(path.join(UD, 'audiences.json'), 'utf8')); check(pr === 1 && !('bbbbbbbbbbbbbbbbbbbb' in disk.hits['la-aaaaaa']) && typeof disk.hits['la-aaaaaa'].dddddddddddddddddddd === 'number' && disk.ev['la-aaaaaa'].dddddddddddddddddddd === 'lead', 'prune drops the stale row; hits stay timestamps, events live in the ev map', JSON.stringify(disk.ev)); fs.rmSync(UD, { recursive: true, force: true }); } // ---------- 2) end to end on a local server ---------- const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'lsid-qa-')); fs.mkdirSync(path.join(DATA, 'uploads')); const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest-lp', ADMIN_EMAIL: 'admin@lp.test', SITE_HOST: 'linkspin.test' }); for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY']) delete env[k]; const logFile = path.join(DATA, 'server.log'); const log = fs.createWriteStream(logFile); const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] }); srv.stdout.pipe(log); srv.stderr.pipe(log); const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) LsidQA'; function req(method, p, o) { o = o || {}; return new Promise((resolve, reject) => { const headers = Object.assign({ 'User-Agent': UA }, o.headers || {}); if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip; let body = o.body; if (body && !Buffer.isBuffer(body)) { if (o.form) { body = Buffer.from(new URLSearchParams(body).toString()); headers['Content-Type'] = 'application/x-www-form-urlencoded'; } else { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; } } if (body) headers['Content-Length'] = body.length; const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, text: buf.toString(), json: j }); }); }); r.on('error', reject); if (body) r.write(body); r.end(); }); } const readJson = f => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8')); const formLsid = html => { const m = /
c.split(';')[0]).join('; '); check(!!cM, 'member signed in on the local copy'); // a published squeeze page with the built-in form const pc = await req('POST', '/api/my/pages', { cookie: cM, body: { type: 'squeeze', title: 'Lsid QA page', content: { headline: 'Get the guide', cta: { text: 'Send it', url: 'https://example.com/thanks' } } } }); check(pc.status === 200 && pc.json.page, 'page created', pc.text.slice(0, 160)); const pg = pc.json.page; const pp = await req('POST', '/api/my/pages/' + pg.id, { cookie: cM, body: { status: 'published' } }); check(pp.status === 200, 'page published', pp.text.slice(0, 160)); // a spin link that points at the page, and a postback that listens for 'lead' const rc = await req('POST', '/api/my/rotations', { cookie: cM, body: { name: 'Lsid QA spin' } }); check(rc.status === 200, 'spin link created', rc.text.slice(0, 160)); const rot = rc.json.rotation; const rd = await req('POST', '/api/my/rotations/' + rot.id + '/dest', { cookie: cM, body: { url: 'https://linkspin.test/p/' + pg.slug, weight: 1 } }); check(rd.status === 200, 'destination added', rd.text.slice(0, 160)); const pb = await req('POST', '/api/my/postbacks', { cookie: cM, body: { name: 'QA tracker', url: 'https://tracker.qa.invalid/pb?cid={clickid}&e={event}&ls={lsid}', events: ['lead'] } }); check(pb.status === 200, 'postback created (an .invalid host, so nothing leaves this machine)', pb.text.slice(0, 160)); // visitor 1: clicks the spin link, lands on the page with ?lsid, submits the built-in form const click = await req('GET', '/r/' + rot.code + '?clickid=QA123', { ip: '203.0.113.10' }); const loc = String(click.headers.location || ''); const lsid1 = (/[?&]lsid=([a-z0-9]+)/i.exec(loc) || [])[1] || ''; check(click.status === 302 && /^[a-z0-9]{6,20}$/i.test(lsid1), 'spin link redirects to the page with a click id', loc); const view1 = await req('GET', '/p/' + pg.slug + '?lsid=' + lsid1, { ip: '203.0.113.10' }); check(view1.status === 200 && formLsid(view1.text) === lsid1, 'built-in form rendered with the click id filled in', 'value=' + formLsid(view1.text)); check(/\/assets\/pt\.js\?v=2/.test(view1.text), 'page loads pt.js with the bumped cache tag'); const ck1 = [].concat(view1.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; '); check(/ls\.click=/.test(ck1), 'page visit sets the ls.click cookie'); const sub1 = await req('POST', '/p/' + pg.slug + '/lead', { ip: '203.0.113.10', cookie: ck1, form: true, body: { name: 'Pat', email: 'visitor1@lp.test', website: '', lsid: formLsid(view1.text) } }); check(sub1.status === 302, 'lead form submits', 'HTTP ' + sub1.status); await sleep(300); let leads = readJson('pages.json').leads; let L = leads.find(l => l.email === 'visitor1@lp.test'); check(L && L.lsid === lsid1, 'lead stored WITH the click id', JSON.stringify(L)); let conv = readJson('rotator.json').conv.filter(c => c.lsid === lsid1); check(conv.length === 1 && conv[0].ev === 'lead', "rotator recorded the 'lead' conversion", JSON.stringify(conv)); // visitor 2: clicks, then comes back to the page WITHOUT ?lsid (cookie only); the server still fills the form const click2 = await req('GET', '/r/' + rot.code, { ip: '203.0.113.11' }); const lsid2 = (/[?&]lsid=([a-z0-9]+)/i.exec(String(click2.headers.location || '')) || [])[1] || ''; const land2 = await req('GET', '/p/' + pg.slug + '?lsid=' + lsid2, { ip: '203.0.113.11' }); const ck2 = [].concat(land2.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; '); const view2 = await req('GET', '/p/' + pg.slug, { ip: '203.0.113.11', cookie: ck2 }); check(formLsid(view2.text) === lsid2, 'cookie-only return visit: form still carries the click id', 'value=' + formLsid(view2.text)); // and a form that posts an empty lsid (an old cached page) falls back to the cookie const sub2 = await req('POST', '/p/' + pg.slug + '/lead', { ip: '203.0.113.11', cookie: ck2, form: true, body: { email: 'visitor2@lp.test', website: '', lsid: '' } }); await sleep(300); L = readJson('pages.json').leads.find(l => l.email === 'visitor2@lp.test'); check(sub2.status === 302 && L && L.lsid === lsid2, 'empty lsid in the post falls back to the ls.click cookie', JSON.stringify(L)); // a plain visitor with no click id: the form value stays empty, the lead is stored without one, no conversion const view3 = await req('GET', '/p/' + pg.slug, { ip: '203.0.113.12' }); check(formLsid(view3.text) === '', 'no click id known: hidden field stays empty'); // the postback attempts land in the log (the .invalid host never resolves: logged as not delivered, plus one retry ~4 s) let plog = []; for (let i = 0; i < 30; i++) { plog = readJson('postbacks.json').log.filter(l => l.event === 'lead'); if (plog.some(l => l.lsid === lsid1) && plog.some(l => l.lsid === lsid2)) break; await sleep(500); } const p1 = plog.find(l => l.lsid === lsid1); check(!!p1 && /cid=QA123/.test(p1.url) && /e=lead/.test(p1.url) && plog.some(l => l.lsid === lsid2), 'postback attempt logged for both leads, macros filled', p1 ? p1.url + ' | ' + p1.note : JSON.stringify(plog)); conv = readJson('rotator.json').conv; check(conv.filter(c => c.ev === 'lead').length === 2, 'exactly two lead conversions in total', String(conv.length)); // ---- the pixel: cookieless hits count once, the event name is stored const aud = (/\/p\.gif\?a=(la-[a-f0-9]{6})/.exec(view1.text) || [])[1]; check(!!aud, "page carries the owner's audience pixel", aud); const before = (await req('GET', '/api/my/audiences', { cookie: cM })).json; const N = 6; let setCookie = 0; for (let i = 0; i < N; i++) { const g = await req('GET', '/p.gif?a=' + aud + '&e=Signup&t=' + i, { ip: '198.51.100.7' }); if (/ls\.vid=/.test(String(g.headers['set-cookie'] || ''))) setCookie++; } check(setCookie === N, 'cookieless pixel hits still offer the ls.vid cookie', setCookie + '/' + N); const vid = 'abcdef0123456789abcd'; await req('GET', '/p.gif?a=' + aud + '&e=purchase', { ip: '198.51.100.8', cookie: 'ls.vid=' + vid }); await req('GET', '/p.gif?a=' + aud + '&e=bad%20name', { ip: '198.51.100.9', cookie: 'ls.vid=' + vid.replace('a', 'b') }); await sleep(6000); // audiences.json flushes every 5 s const ad = readJson('audiences.json'); const h = ad.hits[aud] || {}; const vidKeys = Object.keys(h).filter(k => !k.startsWith('s:')); check(vidKeys.length === 2 && vidKeys.includes(vid), 'N cookieless hits added no 30-day visitor ids (only the two cookie hits did)', JSON.stringify(vidKeys)); const softFrom7 = Object.keys(h).filter(k => k.startsWith('s:')); const ev = (ad.ev || {})[aud] || {}; check(ev[vid] === 'purchase' && Object.values(ev).filter(x => x === 'signup').length === 1 && !Object.values(ev).includes('bad name'), 'event names stored per hit, sanitized', JSON.stringify(ev)); check(Object.values(h).every(t => typeof t === 'number'), 'hits values stay plain timestamps'); const list = (await req('GET', '/api/my/audiences', { cookie: cM })).json; const A0 = (before && (before.audiences || before).find ? (before.audiences || before).find(a => a.id === aud) : null) || { soft: 0, size30: 0 }; const A1 = list && (list.audiences || list).find ? (list.audiences || list).find(a => a.id === aud) : null; check(A1 && A1.size30 - A0.size30 === 2 && A1.soft - A0.soft === 3 && A1.events.purchase === 1 && !A1.events.signup && A1.eventsSoft.signup === 1 && A1.eventsSoft.purchase === 1, 'audiences API: the 6 cookieless hits count as one soft visitor (3 soft keys from 3 IPs), events counted', JSON.stringify({ before: A0, after: A1, soft: softFrom7.length })); } catch (e) { check(false, 'run', e && e.stack || String(e)); } finally { srv.kill(); await sleep(500); const fails = results.filter(r => r.startsWith('FAIL')); console.log(results.join('\n')); console.log('\n' + (results.length - fails.length) + ' passed, ' + fails.length + ' failed' + (fails.length ? ' (server log: ' + logFile + ')' : '')); if (!fails.length) try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} process.exit(failed ? 1 : 0); }