1
2
3
4
5import { Actor } from 'apify';
6await Actor.init();
7const input = (await Actor.getInput()) ?? {};
8const { event_types = [], days = 7, new_only = true, min_revenue_usd = 0, max_items = 500 } = input;
9const want = event_types.length ? event_types : ['ipo_filings', 'mergers_completed', 'material_agreements', 'deal_terms'];
10const UA = 'apify-ma-ipo-deal-tracker/0.2 (data source: SEC EDGAR; served by POPS4 Filing Boards)';
11const H = { headers: { 'user-agent': UA, accept: 'application/json' } };
12const SITE = 'https://www.pops4.com';
13const UPDATE = { live: 'Live feed read from SEC EDGAR every 2 minutes during EDGAR hours; enrichment board rebuilt at 13:15 UTC on the next business day and hourly after', ipo: 'IPO board rebuilt from the SEC index at 13:15 UTC on the next business day and hourly after', terms: 'Deal terms rebuilt daily at 13:00 UTC from new merger proxies (DEFM14A)' };
14async function getJson(url) { const r = await fetch(url, H); if (!r.ok) throw new Error(`HTTP ${r.status} ${url}`); return r.json(); }
15const state = await Actor.openKeyValueStore('pops4-ma-ipo-deal-tracker-state');
16const prev = (await state.getValue('WATERMARK')) ?? {};
17const nowIso = new Date().toISOString(); const windowStart = new Date(Date.now() - days * 86400000).toISOString();
18let pushed = 0; const marks = { ...prev };
19async function push(row, key, mark) { if (pushed >= max_items) return false; await Actor.pushData({ ...row, data_as_of: nowIso, license: 'Served by POPS4 Filing Boards, CC BY 4.0' }); pushed += 1; if (mark && String(mark) > String(marks[key] ?? '')) marks[key] = String(mark); await Actor.charge({ eventName: key === 'terms' ? 'deal_terms_row' : 'deal_event' }).catch(() => {}); return true; }
20const base = (t, e, b) => ({ event_type: t, company: e.company, ticker: e.ticker ?? null, cik: e.cik, exchange: b?.exchange ?? null, sector: b?.sector ?? null, filer_category: b?.filerCategory ?? null, revenue_usd: b?.revenue ?? null, city: b?.city ?? null, state: b?.hq ?? null, event_date: b?.event ?? null, filed: b?.filed ?? String(e.sec_accepted ?? e.filed ?? '').slice(0, 10), form: e.form ?? b?.form ?? null, items: (e.items ?? b?.items ?? []).join('; '), what_the_filing_says: b?.quote ?? e.what ?? '', cash_per_share: null, termination_fee_usd: null, reverse_termination_fee_usd: null, financing_commitment_usd: null, expense_reimbursement_cap_usd: null, golden_parachute_usd: null, sec_accepted: e.sec_accepted ?? null, filing_url: e.filing ?? b?.source ?? null, update_frequency: UPDATE.live, data_source: "SEC EDGAR, the company's own filing" });
21
22const liveTypes = want.filter((t) => t === 'material_agreements' || t === 'mergers_completed');
23if (liveTypes.length) {
24 const since = new_only && prev.live ? prev.live : windowStart;
25 let events = []; let url = `${SITE}/boards/now/changes.json?since=${encodeURIComponent(since)}`;
26 for (let p = 0; p < 20; p++) { const d = await getJson(url); events.push(...(d.events ?? [])); if (!d.has_more || !d.next_cursor) break; url = `${SITE}/boards/now/changes.json?cursor=${encodeURIComponent(d.next_cursor)}`; }
27 const seen = new Set(prev.live_ids ?? []); const ids = [];
28 const boards = {}; for (const [t, b] of [['material_agreements', 'agreements'], ['mergers_completed', 'mergers']]) if (liveTypes.includes(t)) boards[t] = new Map(((await getJson(`${SITE}/boards/${b}.json?limit=2600`).catch(() => ({ rows: [] }))).rows ?? []).map((r) => [r.id, r]));
29 const uniq = new Map(); for (const e of events) { if (e.form !== '8-K') continue; const cur = uniq.get(e.accession); const rank = (x) => (['2.01', '5.01'].includes(x.item) ? 2 : x.item === '1.01' ? 1 : 0); if (!cur || rank(e) > rank(cur)) uniq.set(e.accession, e); }
30 for (const e of [...uniq.values()].sort((a, b) => String(b.sec_accepted).localeCompare(String(a.sec_accepted)))) {
31 const items = e.items ?? []; const t = items.includes('2.01') || items.includes('5.01') ? 'mergers_completed' : items.includes('1.01') ? 'material_agreements' : null;
32 if (!t || !liveTypes.includes(t) || seen.has(e.accession)) continue;
33 const row = base(t, e, boards[t]?.get(e.accession));
34 if (min_revenue_usd && (row.revenue_usd ?? 0) < min_revenue_usd) continue;
35 if (!(await push(row, 'live', e.sec_accepted))) break; ids.push(e.accession);
36 }
37 marks.live_ids = [...new Set([...ids, ...[...seen].slice(0, 2000)])].slice(0, 3000);
38}
39if (want.includes('ipo_filings') && pushed < max_items) {
40 const d = await getJson(`${SITE}/boards/ipo-watch.json?limit=1200`); const since = new_only && prev.ipo ? prev.ipo : windowStart.slice(0, 10);
41 for (const r of (d.rows ?? []).sort((a, b) => String(b.filed).localeCompare(String(a.filed)))) {
42 if ((r.filed ?? '') <= since && new_only) continue; if ((r.filed ?? '') < windowStart.slice(0, 10)) continue;
43 if (min_revenue_usd && (r.revenue ?? 0) < min_revenue_usd) continue;
44 const row = { ...base('ipo_filings', { company: r.company, ticker: r.ticker, cik: r.cik, form: r.form, items: r.items, filing: r.source, what: r.quote, filed: r.filed }, r), update_frequency: UPDATE.ipo };
45 if (!(await push(row, 'ipo', r.filed))) break;
46 }
47}
48if (want.includes('deal_terms') && pushed < max_items) {
49 const d = await getJson(`${SITE}/boards/deal-terms.json`); const since = new_only && prev.terms ? prev.terms : new Date(Date.now() - Math.max(days, 30) * 86400000).toISOString().slice(0, 10);
50 const amt = (x) => (x && typeof x === 'object' ? x.amount ?? null : typeof x === 'number' ? x : null);
51 for (const r of [...(d.rows ?? [])].sort((a, b) => String(b.date ?? '').localeCompare(String(a.date ?? '')))) {
52 if ((r.date ?? '') <= since) continue;
53 const quote = [r.terminationFee, r.cashPerShare, r.goldenParachute, r.expenseReimbursementCap].map((x) => (x && typeof x === 'object' ? x.quote : '')).filter(Boolean)[0] ?? '';
54 const row = { ...base('deal_terms', { company: r.company, ticker: r.ticker, cik: r.cik, form: 'DEFM14A', items: [], filing: r.proxy, what: quote, filed: r.date }, null), cash_per_share: typeof r.cashPerShare === 'number' ? r.cashPerShare : amt(r.cashPerShare), termination_fee_usd: amt(r.terminationFee), reverse_termination_fee_usd: amt(r.reverseTerminationFee), financing_commitment_usd: amt(r.financingCommitment), expense_reimbursement_cap_usd: amt(r.expenseReimbursementCap), golden_parachute_usd: amt(r.goldenParachute), update_frequency: UPDATE.terms, data_source: 'SEC EDGAR, the merger proxy (DEFM14A) itself', deal_terms_built: d.built ?? null };
55 if (!(await push(row, 'terms', r.date))) break;
56 }
57}
58if (new_only) await state.setValue('WATERMARK', { ...marks, updated: nowIso });
59await Actor.setValue('RUN_SUMMARY', { rows: pushed, new_only, watermarks: marks, data_as_of: nowIso });
60console.log(`Done: ${pushed} rows; new_only=${new_only}; watermarks ${JSON.stringify({ live: marks.live, ipo: marks.ipo, terms: marks.terms })}.`);
61await Actor.exit();