Compare commits
1 Commits
main
...
distributi
| Author | SHA1 | Date | |
|---|---|---|---|
| ceac68cc0e |
1
.gitignore
vendored
1
.gitignore
vendored
@ -9,3 +9,4 @@ __pycache__/
|
||||
yc_founders*.json
|
||||
yc_founders*.csv
|
||||
*_apify_raw.json
|
||||
.gstack/
|
||||
|
||||
@ -1,85 +0,0 @@
|
||||
# yc-outreach — Architecture (2026-10-23)
|
||||
|
||||
Scope: real current system only (no proposed components). Covers what `PLAN-2026-10-23-DEEP.md` does not: competitive positioning was covered in `STRATEGY-2026-10-23.md`; this doc covers technical architecture, data flow, and risks.
|
||||
|
||||
## Confirmed facts (read from repo, not assumed)
|
||||
|
||||
- Hosting: **Vercel** (`.vercel/project.json` → `projectName: yc-outreach`; `vercel.json` sets a 60s timeout on `api/yc.py`). This is NOT one of the portfolio's Oracle boxes and NOT Cloudflare Workers/Pages — it is Vercel's Python serverless runtime.
|
||||
- Git remotes: `origin` = `adityajha2005/yc-outreach` (upstream, not ours), `fork` = `caelum0x/yc-outreach` (ours). 13 commits total on `main`.
|
||||
- No database. No queue/broker. No CI config (no `.github/workflows`, no `package.json`). Stdlib-only Python, zero npm dependencies.
|
||||
- No `.env` committed; `APIFY_TOKEN` (CLI-only) is read from env or a gitignored local `.env`.
|
||||
|
||||
## 1. System diagram
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
User["Visitor's browser"]
|
||||
HTML["index.html\n(static, Vercel CDN)\nvanilla JS, inline CSS\nlocalStorage: template, sent marks, per-batch cache"]
|
||||
API["api/yc.py\nVercel Python serverless function\nactions: batches / companies / founders"]
|
||||
YCAlgolia["YC Algolia search\n(ycombinator.com/companies\nAlgolia key scraped at runtime)"]
|
||||
YCPage["YC company page\nycombinator.com/companies/<slug>\n(data-page JSON: founders, jobs)"]
|
||||
CompanySite["Company's own website\n(homepage + /contact)"]
|
||||
Apify["Apify actor\nsnipercoder/email-finder-by-name-and-domain"]
|
||||
CLI1["yc_scraper.py\n(offline CLI, local JSON/CSV)"]
|
||||
CLI2["apify_enrich.py\n(offline CLI, needs APIFY_TOKEN)"]
|
||||
|
||||
User -- "GET /" --> HTML
|
||||
HTML -- "fetch /api/yc?action=..." --> API
|
||||
API -- "Algolia query (batches, companies)" --> YCAlgolia
|
||||
API -- "GET per-company page (founders action)" --> YCPage
|
||||
API -- "GET homepage + /contact, 4s deadline" --> CompanySite
|
||||
HTML -- "direct browser fetch, user's own token,\nnever touches API server" --> Apify
|
||||
CLI1 -- "same scrape logic, 6 contact pages, retries" --> YCAlgolia
|
||||
CLI1 --> YCPage
|
||||
CLI1 --> CompanySite
|
||||
CLI2 -- "reads yc_scraper.py JSON output" --> Apify
|
||||
```
|
||||
|
||||
No message queue, no persistent datastore, no auth layer. The only "cache" tiers are: Vercel edge `Cache-Control: s-maxage` headers on API responses, and the browser's `localStorage`.
|
||||
|
||||
## 2. Data flow for the 2-3 key user actions
|
||||
|
||||
### A. Load a batch's companies (click "Load companies")
|
||||
1. Browser reads `tpl`/`sent`/per-batch cache from `localStorage` (key `yc-outreach-v2-batch-<batch>`).
|
||||
2. If not cached: browser `fetch("/api/yc?action=companies&batch=...")`.
|
||||
3. `api/yc.py` validates `batch` against `BATCH_RE`, calls `algolia()` → scrapes YC's Algolia app-id/key from `ycombinator.com/companies` (cached per warm Lambda instance in `_algolia` global), queries `YCCompany_production` index, paginates until `nbPages` exhausted.
|
||||
4. Response (list of `{name, slug, website, one_liner, industry, team_size, launched_at}`) returned with `Cache-Control: s-maxage=3600`.
|
||||
5. Browser sorts by `launched_at` desc, writes the array to `localStorage`, renders list skeleton, then immediately calls `loadMore()`.
|
||||
|
||||
### B. Load founders + open roles for 20 companies ("Load more")
|
||||
1. Browser batches the next 20 un-fetched slugs into 2 parallel requests of 10 slugs each: `fetch("/api/yc?action=founders&slugs=a,b,c...")`.
|
||||
2. `api/yc.py` validates slug count/format, fans out via `ThreadPoolExecutor` to `founders(slug)` per slug:
|
||||
- `GET https://www.ycombinator.com/companies/<slug>` → regex-extracts the `data-page="..."` JSON blob → `props.company` (founders, website, socials) and `props.jobPostings`.
|
||||
- Submits `site_emails(website, domain)` to a long-lived 32-thread pool with a **4-second** deadline; on timeout the result is simply dropped (`cf.TimeoutError` → `emails = []`), guesses still populate.
|
||||
- `site_emails` fetches homepage + `/contact` (2 pages, not the CLI's 6), extracts plain-text emails and Cloudflare `data-cfemail` obfuscated addresses (`cf_decode`), filters to the company's own domain.
|
||||
- DNS-resolves the domain (`socket.getaddrinfo`) before generating `first@`, `first.last@`, `flast@`, `firstlast@` guesses — skips guesses entirely if the domain doesn't resolve.
|
||||
3. Response cached `s-maxage=86400` (24h) at the edge; merged into the browser's `ALL`/`DATA` arrays and written back to `localStorage` so a reopened batch never re-fetches.
|
||||
4. Client renders each company's best-available contact: `apify verified > apify unverified > site email > guess > none`.
|
||||
|
||||
### C. Verified-email enrichment ("Find emails", optional)
|
||||
1. Browser reads the **visitor's own** Apify token from an `<input type=password>` (never sent to `api/yc.py`, never persisted to `localStorage`).
|
||||
2. Browser batches up to 50 founders per call, `POST https://api.apify.com/v2/acts/snipercoder~email-finder-by-name-and-domain/runs?maxTotalChargeUsd=<cap>` directly from the client, polls run status every 5s, then `GET .../datasets/<id>/items`.
|
||||
3. Matches returned items back to founders by lowercased name+domain, writes `apify_email`/`apify_status` onto the in-memory + `localStorage`-persisted company objects, re-renders.
|
||||
4. This path never touches the Vercel function — it is the deliberate trust boundary the README documents ("token never reaches this site's server").
|
||||
|
||||
### D. Offline bulk export (CLI path, out of band)
|
||||
1. `python3 yc_scraper.py --batches "..." --out yc_founders` — same Algolia/data-page/cf-decode logic, but 6 contact paths, HTTP retries, no serverless time limit; writes local JSON+CSV (gitignored, never committed).
|
||||
2. `python3 apify_enrich.py --input yc_founders.json` — reads that JSON, calls the same Apify actor server-side with `APIFY_TOKEN` from env/.env, writes an enriched JSON+CSV. Separate code path from the browser's Apify call; duplicated by design (different timeout/retry needs), per README's "Notes for AI agents."
|
||||
|
||||
## 3. Real architectural risks / bottlenecks (current scale, zero budget)
|
||||
|
||||
- **Single point of failure: scraping YC's own page markup.** Both `batches`/`companies` and `founders` depend on regex-extracting `window.AlgoliaOpts` and `data-page="..."` from YC's HTML. Any YC frontend redeploy that changes either string breaks the entire product with no fallback and no alerting (no monitoring exists at all).
|
||||
- **Cold-start + per-request Algolia key fetch.** `_algolia` is cached only per warm Lambda instance; every cold start re-fetches `ycombinator.com/companies` before the first real query, adding latency and an extra outbound call that can itself fail (YC rate-limiting or blocking the function's IP/UA would silently take down `batches`/`companies` for all users).
|
||||
- **No rate limiting or abuse protection on `api/yc.py`.** `MAX_SLUGS=10` caps one call's fan-out, but nothing stops a scripted client from hammering `action=founders` across many slugs/IPs — each call makes 10 outbound HTTPS requests to YC plus up to 10 company-website fetches. On Vercel's free/hobby tier this risks hitting function-invocation or bandwidth limits and taking the whole site down for real users, with no WAF or CAPTCHA in front of it.
|
||||
- **4-second site-check deadline silently degrades data quality, not just speed.** `SITE_DEADLINE=4` means any company on a slow host (common for early-stage startups on cheap hosting) gets `emails = []` and the user only ever sees a pattern guess — there's no retry, no backoff, no way to know afterward which companies were skipped for being slow vs. having no email at all.
|
||||
- **No backend persistence means no cross-session/cross-device state.** All "sent" marks, loaded batches, and the outreach template live in one browser's `localStorage`. Clearing site data, switching devices, or using a different browser loses everything — there is no account system (by design, for the free/no-signup pitch), but it also means the product cannot build any retention mechanism beyond the batch-cadence idea in the strategy doc without adding real backend state.
|
||||
- **Two independent scrape implementations (`api/yc.py` vs `yc_scraper.py`) will drift.** They already differ deliberately (2 vs 6 contact paths, timeouts, retries) but share no common module — a YC markup change or a bug fix in the email regex/guess logic has to be applied twice or will quietly diverge.
|
||||
- **Zero observability.** No logs are collected anywhere beyond Vercel's default function logs; a broken scrape (e.g., YC changes the Algolia key format) would only be noticed by a user reporting "batch won't load," with no server-side error tracking to catch it first.
|
||||
|
||||
## 4. Prioritized next-build list (effort vs. impact)
|
||||
|
||||
1. **Add a YC-markup health check + graceful fallback message** (low effort, high impact). A tiny scheduled check (even a manual pre-deploy `curl`) that asserts the Algolia-key regex and `data-page` regex still match, plus a user-facing "YC changed their page, we're on it" error string instead of a raw 502 — turns the single point of failure from silent breakage into a known, fast-to-fix incident. Directly protects every growth move: a broken tool during a Show HN/Reddit launch spike is the single worst outcome.
|
||||
2. **Extract the shared scrape/decode logic (`cf_decode`, `site_emails`, `guesses`, Algolia client) into one importable module used by both `api/yc.py` and `yc_scraper.py`** (low-medium effort, medium-high impact). Removes the drift risk called out above and makes the planned Gmail-send port (growth move #1 in the strategy doc) safer to build on, since it will need to reuse the same founder/email data shape.
|
||||
3. **Add minimal per-IP rate limiting on `api/yc.py`** (low-medium effort, high impact for the zero-budget constraint). Even a simple in-memory/edge-cache token count (Vercel supports `@vercel/edge-config` or a cheap header-based throttle) prevents one scripted client from exhausting the Vercel hobby-tier invocation/bandwidth quota and taking the whole site down — the one failure mode that would zero out all users at once, which matters most right before a distribution push.
|
||||
4. **Port lakshh07/yc-outreach's Gmail-send into `index.html`** (medium effort, high impact — this is strategy growth move #1). Architecturally this is additive: a new client-side OAuth flow calling Gmail's API directly from the browser, following the same trust pattern already proven by the Apify integration (token/credential never touches `api/yc.py`). Removing the copy-paste step is the single highest-leverage change to conversion from "tool used" to "email actually sent."
|
||||
5. **Instrument basic server-side error logging/alerting for `api/yc.py` failures** (low effort, medium impact). Vercel's function logs already exist but nothing surfaces a spike in 502s; even a free-tier log-drain or a simple "ping me if error rate > X" check closes the observability gap before traffic grows from the planned Reddit/HN/cross-fork distribution push.
|
||||
@ -1,151 +0,0 @@
|
||||
# Build log — 2026-10-23, round 1
|
||||
|
||||
Internal log of what shipped this round against the backlog in `PLAN-2026-10-23-DEEP.md` /
|
||||
`STRATEGY-2026-10-23.md`. Terse, points at the actual code.
|
||||
|
||||
## Shipped this round
|
||||
|
||||
### 1. Client-side Gmail direct-send (backlog #1)
|
||||
`index.html`: new "4. Connect Gmail" panel. Google Identity Services OAuth2 token client,
|
||||
`gmail.send` scope only. Token lives in `sessionStorage` + an in-memory variable — never sent to
|
||||
`api/yc.py`. MIME message built client-side (`mimeEncodeHeader`/`b64urlFromString`) and POSTed
|
||||
straight to `https://gmail.googleapis.com/gmail/v1/users/me/messages/send`. Persisted send queue
|
||||
(`localStorage["yc-outreach-v2-queue"]`) with a visible pending/sent-today/next-send countdown, a
|
||||
20–60s randomized delay between sends (`startQueueWorker`), and a configurable daily cap (default
|
||||
30, rolling 24h window via `yc-outreach-v2-sendlog`). Draft actions show a "➤ Send" button instead
|
||||
of "Copy body" once connected, falling back to Copy when not. A successful send auto-advances the
|
||||
company's pipeline stage (see #6).
|
||||
**Owner-only step, not done, noted inline in code**: `GOOGLE_CLIENT_ID` in `index.html` is a
|
||||
placeholder (`REPLACE_WITH_...`). Needs a free OAuth 2.0 Web application client from
|
||||
<https://console.cloud.google.com/apis/credentials> (enable Gmail API, add this origin to
|
||||
"Authorized JavaScript origins"). Zero cost, console-only. Until set, "Connect Gmail" shows a clear
|
||||
inline message and every other feature (Copy/mailto) works exactly as before — verified live.
|
||||
|
||||
### 2 + 13. Job-aware personalization + job-description endpoint (backlog #2, #13)
|
||||
`api/yc.py`: new `action=job&url=<ycombinator.com job url>` route. `JOB_URL_RE` restricts it to
|
||||
`ycombinator.com/companies/<slug>/jobs/<id>` (same allowlist spirit as the rest of this file — never
|
||||
an open proxy). `job_detail()` fetches the job's own page and parses `props.job` out of the
|
||||
`data-page` JSON: full `description`, `interview_process`, `location`, `salary_range`,
|
||||
`equity_range`, `min_experience`, `visa`, `skills`. Verified against a real live job
|
||||
(`stripe/jobs/jdBhPmD-...`) — returns the full role description.
|
||||
`index.html`: `{job_title}`/`{job_url}` added to the placeholder set (now 10) and wired into
|
||||
`fill()`. When a company has >1 open role, a per-company role-picker `<select>` (`jobPicker()`)
|
||||
appears, sticky per-slug in `localStorage["yc-outreach-v2-jobsel"]`, and the draft retargets live.
|
||||
Each job title is also a button that lazily fetches and caches (`yc-outreach-v2-jobcache`) the full
|
||||
description inline.
|
||||
|
||||
### 3. Confidence-ranked, Apify-free email resolution (backlog #3)
|
||||
`api/yc.py`:
|
||||
- `resolves_mx(domain)`: DNS-over-HTTPS against Cloudflare's resolver (stdlib `urllib`, no
|
||||
dnspython) — returns `True`/`False`/`None` (lookup inconclusive). Detects the RFC 7505 null-MX
|
||||
case (`example.com`'s `"0 ."` record) as "no mail server", not just an absent MX. Verified live:
|
||||
`stripe.com`→True, `example.com`→False, a nonexistent domain→None.
|
||||
- `founders()` now only offers guesses when `mx is not False`, and scales confidence down 25% when
|
||||
the MX lookup itself was inconclusive instead of blocking guesses outright.
|
||||
- `guesses()` returns `[{email, pattern, confidence}]` instead of a flat string list. Confidence
|
||||
numbers come straight from this project's own published benchmark (README: first guess right 80%
|
||||
of the time, right answer somewhere in the list 93% of the time) → `{first:80, first.last:7,
|
||||
flast:4, firstlast:2}`.
|
||||
- `infer_pattern()` + `apply_inferred_pattern()`: once any founder's real email (site-scraped) is
|
||||
known for a company, every other founder at that domain gets re-ranked to that same pattern first
|
||||
at 95% confidence. Unit-verified directly against the module.
|
||||
`index.html`: `best()` carries confidence through for every source (verified 99%, unverified 60%,
|
||||
on-site 97%, guess per the server's number); rendered as a `NN%` badge next to every email, plus a
|
||||
collapsible "other guesses" line showing the remaining candidates with their own percentages.
|
||||
|
||||
### 4 + 6. Pipeline stages + follow-up sequencing (backlog #4, #6)
|
||||
`index.html`: replaced the old boolean `sent` `Set` (commit `bfca064`) with a full stage enum per
|
||||
slug — `not_sent / sent / followed_up / replied / interview / rejected / closed`, each carrying its
|
||||
own timestamp (`stages[slug] = {stage, sentAt, followupDueAt, followedUpAt, repliedAt, ...}` in
|
||||
`localStorage["yc-outreach-v2-stages"]`). One-time migration on load folds the old `-sent` Set into
|
||||
the new shape. Marking "Sent" auto-schedules `followupDueAt` = `addBusinessDays(now, N)` (default 5,
|
||||
configurable). A second template pair (`followup_subject`/`followup_body`, own editor under a
|
||||
`<details>` in the template section) generates a shorter second-touch draft once a contact is
|
||||
`sent`/`followed_up`, with its own Copy/Send action. Toolbar gained a stage filter dropdown
|
||||
(including a derived "Follow-up due" value) and the "shown" summary now reports contacted/due
|
||||
counts. CSV export gained Stage/Sent-At/Follow-up-Due/Followed-Up-At/Replied-At columns.
|
||||
Both existing regression tests (`tests/test_sent_tracking.mjs`, `tests/test_industry_filter.mjs`)
|
||||
were updated to drive the new stage `<select>` instead of the removed checkbox and to stub the two
|
||||
new browser globals the script now touches at load (`sessionStorage`, `setInterval`) — both still
|
||||
pass, same slug-isolation guarantee as before.
|
||||
|
||||
### 7 + 14. New-batch / new-role watcher (backlog #7, #14)
|
||||
`api/yc.py`: new `action=digest&known_batches=<json>&slugs=<csv>&known_jobs=<json>` route.
|
||||
`company_jobs_quick()` is a cheap job-count-only fetch (no website scrape) so up to
|
||||
`MAX_DIGEST_SLUGS=40` companies can be checked in one round trip; the route always returns the full
|
||||
current batch list (`batches`) plus `job_counts` for every checked slug, not just the diffs, so the
|
||||
client can refresh its whole baseline from one call. Verified live end-to-end.
|
||||
`index.html`: `setInterval` + Page Visibility API poll every 5 minutes while the tab is visible
|
||||
(and immediately on becoming visible again), comparing against `localStorage` baselines
|
||||
(`-lastbatches`, `-lastjobs`) primed on first load so it never spams on the very first run. Fires a
|
||||
real `Notification` (after "Enable alerts" grants permission) plus a status line, for both new
|
||||
batches and new job postings on already-loaded companies. Fully client-side, no new backend state.
|
||||
|
||||
### 8. Fit-score ranking (backlog #8)
|
||||
`index.html`: new "Your skills / stack" field in step 1, persisted. `fitScore()` tokenizes the
|
||||
skills text and overlaps it against a company's open-role titles (always available) plus any job
|
||||
descriptions already fetched via #2/#13 (`jobCache`), as % of skill keywords matched. Rendered as a
|
||||
`NN% fit` badge on the card; a "Best fit first" toolbar button re-sorts the visible list by it.
|
||||
Verified live (50% fit on titles alone, 100% once the fetched description text was included).
|
||||
|
||||
### 9. Multi-batch search (backlog #9)
|
||||
`api/yc.py`: `companies()` now fans a comma-separated batch list out in parallel
|
||||
(`companies_one()` per batch) and de-dupes by slug; `route()` validates each batch name and caps
|
||||
the list at `MAX_BATCHES=8`.
|
||||
`index.html`: batch `<select>` is now `multiple`; `loadBatch()` reads every selected option, joins
|
||||
them into one cache key, and passes the list straight through. Verified live loading two batches
|
||||
(Summer 2027 + Winter 2027) in one pass, 6/6 companies.
|
||||
|
||||
### 11. Full session export/import (backlog #11)
|
||||
`index.html`: "Export session" dumps every `localStorage` key prefixed `yc-outreach-v2` (profile,
|
||||
templates, loaded batches, stages, job cache/selection, queue, settings — generic prefix scan, not
|
||||
a hardcoded list, so it can't silently miss a future key) into one timestamped JSON file. "Import
|
||||
session" (hidden file input behind a label) restores them after a confirm, then reloads. Verified
|
||||
live: exported, cleared `localStorage`, re-imported, pipeline-stage data for a marked-sent company
|
||||
came back exactly.
|
||||
|
||||
## Found and fixed along the way (not on the original backlog)
|
||||
- **Real bug, caught in browser testing**: `filter()` / "Expand all" / CSV export all used
|
||||
`document.querySelectorAll("details")` with no scope. Adding the new follow-up-template
|
||||
`<details>` disclosure in the template editor (item 4) made that selector match an extra,
|
||||
data-less element, breaking the "N shown" count (`8 of 7 shown`) and the CSV's visible-row
|
||||
selection. Fixed by scoping all three to `#list details`. Caught by actually running the app in a
|
||||
real browser (`gstack`/`browse`), not by reasoning about the diff.
|
||||
- `label.btn` (the new "Import session" control) wasn't covered by the `button,a.btn{...}` CSS
|
||||
selector and would have rendered unstyled; added `label.btn` to the rule.
|
||||
|
||||
## Verification performed this round
|
||||
- `python3 -c "import api.yc"` — backend module imports clean.
|
||||
- Direct unit calls against `guesses()`, `apply_inferred_pattern()`, `resolves_mx()` in a `python3`
|
||||
REPL against the real module (not mocks) — confirmed confidence numbers, pattern inference, and
|
||||
all three MX outcomes (`stripe.com`→True, `example.com`→False/null-MX, nonexistent domain→None)
|
||||
against live DNS.
|
||||
- `node --check` on the extracted inline `<script>` after every edit pass.
|
||||
- Full local run via `python3 serve.py` + `gstack`/`browse` (real headless Chromium): loaded two
|
||||
real batches end-to-end, expanded a card, set a stage to Sent and watched the follow-up draft and
|
||||
due-date appear, injected a real `stripe` founders() response to exercise the job picker/fit
|
||||
score/job-description fetch, drove the Gmail "Connect" button through its no-client-ID fallback
|
||||
path, exported+cleared+imported a full session, exported CSV and inspected its bytes, and
|
||||
confirmed zero console errors at every step (the `#list details` scoping bug above was found this
|
||||
way).
|
||||
- `node tests/test_sent_tracking.mjs`, `node tests/test_industry_filter.mjs`,
|
||||
`python3 tests/test_cf_email_decode.py` — all pass against the modified files.
|
||||
- No automated tests were added; the existing two JS regression tests were updated only because the
|
||||
API they drove (the boolean `sent` Set) was removed by this round's own work (item 6), not as new
|
||||
test authoring.
|
||||
|
||||
## Still remaining from the backlog (not started this round)
|
||||
- **#5 Reply detection via Gmail** — needs the OAuth connection from #1 (now built) extended with a
|
||||
`gmail.readonly`/`gmail.metadata` scope and `users.threads.get` polling to auto-flip a company to
|
||||
"Replied". Natural next-round item since #1 and #6 (the `replied` stage already exists) are both
|
||||
now in place.
|
||||
- **#10 Multi-template library** — only one subject/body + one follow-up subject/body pair exists;
|
||||
no named-template picker or per-template reply-rate stats yet.
|
||||
- **#12 Advanced filter bar** — team-size range, "founded after" date, reliability-level
|
||||
(verified/on-site-only), has-LinkedIn/has-Twitter toggle not added; only the stage/industry/hiring/
|
||||
email-type filters from before plus this round's stage filter exist.
|
||||
|
||||
## Owner-only step (noted, not blocking)
|
||||
- Gmail direct-send needs a Google Cloud OAuth client ID pasted into `GOOGLE_CLIENT_ID` in
|
||||
`index.html` (console-only, zero cost). Nothing else in this round depends on it; the app is fully
|
||||
usable without it exactly as before.
|
||||
@ -1,48 +0,0 @@
|
||||
# yc-outreach — build spec (2026-10-23)
|
||||
|
||||
Internal build doc. Terse, concrete, no restating self-evident code.
|
||||
|
||||
## Pages
|
||||
|
||||
### `/` — `index.html` (single static page, no router, no build step)
|
||||
Purpose: pick a YC batch → get founders+emails → draft+send cold emails, all client-side.
|
||||
|
||||
Sections (top to bottom):
|
||||
1. **Your details** — inputs: name, portfolio URL, github, resume URL. Persisted `localStorage["yc-outreach-v2"]`.
|
||||
2. **Template editor** — subject input + body textarea, placeholder-insertion toolbar (`{first_name} {company} {one_liner} {batch} {my_name} {portfolio} {github} {resume}`). Line auto-drops if its only placeholder is empty.
|
||||
3. **Batch picker** — `<select>` populated from `GET /api/yc?action=batches` + "Load companies" button (→ arrow/check icon, not text "Submit").
|
||||
4. **Verified-email opt-in** — Apify token `<input type=password>` (never persisted, never sent to this server) + USD cap input + "Find emails" button.
|
||||
5. **Toolbar** (sticky) — text search, email-status `<select>`, industry `<select>`, "hide sent" checkbox, "hiring" checkbox, Expand/Collapse-all toggle, Export CSV button (icon-only, e.g. download glyph).
|
||||
6. **Company list** — one `<details>` per company: summary = name + best-email badge + top founder + batch + roles count; body = one-liner/industry/website/YC/LinkedIn/X links, open-roles list, per-founder rows (name, title, email, badge), live draft `<pre>` (subject+body), Copy-body/Copy-email/Copy-subject buttons (clipboard glyph), mailto "open in mail app" link (envelope glyph), per-company "sent" checkbox.
|
||||
7. **Load more** button — paginates founder/job fetch 20 companies at a time.
|
||||
8. **Footer** — GitHub star link, data-source + etiquette note.
|
||||
|
||||
No other pages. SEO assets added this session: `<link rel=canonical>`, favicon (inline SVG data URI), `og:*`/`twitter:*` meta, `/robots.txt`, `/sitemap.xml`.
|
||||
|
||||
## APIs
|
||||
|
||||
Single module `api/yc.py`, Vercel Python serverless function, `maxDuration=60`. No auth (public, read-only, no secrets held server-side).
|
||||
|
||||
- **`GET /api/yc?action=batches`**
|
||||
Request: no params. Response `200`: `[{batch: "Summer 2026", companies: 168}, ...]` sorted newest-first. Cache: `s-maxage=86400`. Source: YC Algolia facet counts on `batch` field.
|
||||
|
||||
- **`GET /api/yc?action=companies&batch=<Season Year>`**
|
||||
Request: `batch` validated against `BATCH_RE`. Response `200`: `[{name, slug, batch, website, one_liner, industry, team_size, launched_at}, ...]`. `400` on invalid batch. Cache: `s-maxage=3600`.
|
||||
|
||||
- **`GET /api/yc?action=founders&slugs=a,b,c`** (max 10, `SLUG_RE`-validated)
|
||||
Fans out via `ThreadPoolExecutor`. Response `200`: `[{slug, founders:[{name,title,linkedin,twitter}], jobs:[{title,url}], job_count, site_emails:[...], resolves:bool, email_guesses:{...}} | {slug, error}]`. Cache: `s-maxage=86400`. Per-company website check capped at `SITE_DEADLINE=4s`.
|
||||
|
||||
- **Apify enrichment** — not a yc-outreach endpoint. Browser calls Apify's own API (`api.apify.com/v2/acts/snipercoder~email-finder-by-name-and-domain/runs`) directly with the visitor's token. Never proxied through `api/yc.py`.
|
||||
|
||||
## Features
|
||||
|
||||
- **Email resolution ladder** (`best()`/`RANK` in `index.html`): apify-verified > apify-unverified > site-scraped (incl. Cloudflare `data-cfemail` XOR decode, `cf_decode()`) > pattern guess (`first@`, `first.last@`, `flast@`, `firstlast@`, gated on DNS resolution) > none. Data: per-company object in `ALL`/`DATA` arrays, mirrored to `localStorage["yc-outreach-v2-batch-<batch>"]`. Dependency: `api/yc.py` founders action. Status: complete.
|
||||
- **Search/filter/CSV** — full-text (name/founder/one-liner/job titles), email-status filter, industry filter (`industryTop()`), hiring filter, hide-sent, CSV export of visible rows. Status: complete.
|
||||
- **Sent-tracking** — keyed by YC `slug` (not display name, handles name collisions). Status: complete, regression-tested (`tests/test_sent_tracking.mjs`).
|
||||
- **SEO/distribution metadata** — canonical link, favicon, OG/Twitter meta, `robots.txt`, `sitemap.xml`, GitHub-star footer CTA, README "Live" link. Status: **shipped this session** (previously stranded on stale `fork/distribution-metadata`, which predated and would have regressed the industry-filter/search/cf-decode work — reimplemented fresh on current `main` instead of merging that branch).
|
||||
- **Remaining gaps (not built yet)**:
|
||||
- No rate limiting on `api/yc.py` (only `MAX_SLUGS=10` + `SITE_DEADLINE=4s` caps per-call cost; no per-IP throttle).
|
||||
- Two independent scrape implementations (`api/yc.py` vs `yc_scraper.py`/`apify_enrich.py`) share no common module — logic/bug-fix drift risk.
|
||||
- No server-side error tracking/alerting if YC changes page markup (Algolia key scrape or `data-page` JSON shape) and scraping silently breaks.
|
||||
- No Gmail-send-from-browser (removes copy/paste step) — seen in fork `lakshh07/yc-outreach`, not ported here.
|
||||
- Local `main` still ahead of `origin/main` (upstream `adityajha2005/yc-outreach`) by unpushed commits — push target for this repo is `fork` (`caelum0x/yc-outreach`), not `origin`.
|
||||
@ -18,8 +18,7 @@ Python 3.9+, standard library only. Nothing to install.
|
||||
2. **Founders load 20 companies at a time** (about 5–10 s per 20); click **Load more** for the next 20. For each
|
||||
company the server reads its ycombinator.com page for the founders' names, titles, LinkedIn and X, and for how
|
||||
many roles that company has open on YC (title and link for each). Loaded companies are kept in your browser, so
|
||||
reopening a batch is instant. Check **hiring** to hide companies with no open roles, or pick an **industry**
|
||||
(B2B, Fintech, Healthcare, ...) from the dropdown to narrow the batch to the sector you actually want to reach.
|
||||
reopening a batch is instant. Check **hiring** to hide companies with no open roles.
|
||||
3. **Emails are filled in** for each founder, best source first:
|
||||
|
||||
| Label | Source | Reliability |
|
||||
@ -101,10 +100,6 @@ domain doesn't resolve.
|
||||
- **Founders and open roles:** the `data-page` JSON embedded in each `ycombinator.com/companies/<slug>` page
|
||||
(`props.company` and `props.jobPostings`). Incomplete postings are skipped. Browsers can't fetch these
|
||||
cross-origin, which is why this part runs on a server.
|
||||
- **On-site emails:** the homepage and `/contact` page, plain text and Cloudflare's "email protection"
|
||||
obfuscation (`data-cfemail="<hex>"`, shown on the page as `[email protected]`) decoded the same way browsers
|
||||
render it. About 1 in 16 company sites use this, so without decoding it those real, published addresses would
|
||||
silently fall back to a lower-reliability guess.
|
||||
- **Verified emails (optional):** the Apify actor
|
||||
[`snipercoder/email-finder-by-name-and-domain`](https://apify.com/snipercoder/email-finder-by-name-and-domain),
|
||||
called **from the browser** with the visitor's own token, so the token never reaches the server. Results are
|
||||
|
||||
@ -1,175 +0,0 @@
|
||||
# yc-outreach — Competitive Positioning, User Research, Technical Architecture Strategy (2026-10-23)
|
||||
|
||||
Scope note: a parallel workflow owns `PLAN-2026-10-23-DEEP.md` (pages/APIs/features) for this
|
||||
product; it did not exist at write time. This doc covers positioning, personas, journey, and
|
||||
growth only — no feature/page/API spec duplication.
|
||||
|
||||
What the repo actually does today (read from `README.md`, `index.html`, `api/yc.py`,
|
||||
`yc_scraper.py`, `apify_enrich.py`):
|
||||
- Single static page (`index.html`, no framework/build) + one Python serverless function
|
||||
(`api/yc.py`) deployed free on Vercel. No account, no database; all state (name, template,
|
||||
"sent" marks, loaded batches) lives in `localStorage`.
|
||||
- Lets a user pick a YC batch, loads 20 companies at a time, pulls each founder's name, title,
|
||||
LinkedIn/X, and the company's open YC job postings (title + link) straight from YC's own
|
||||
`ycombinator.com/companies/<slug>` page data.
|
||||
- Resolves an email per founder in priority order: Apify-verified (user's own token, client-side
|
||||
only) > Apify-unverified > scraped from the company site (including decoding Cloudflare's
|
||||
`data-cfemail` obfuscation) > pattern guess (`first@domain`, etc. — 80% first-guess accuracy on
|
||||
the README's own 151-email benchmark).
|
||||
- One editable template with `{first_name} {company} {one_liner} {batch} {my_name} {portfolio}
|
||||
{github} {resume}` placeholders; copy-to-clipboard per founder, mark as sent, CSV export.
|
||||
- Already forked 6+ times on GitHub under different usernames (wenayy, lakshh07, moizghumann,
|
||||
adityajha2005 — this repo's own `origin` — DevItaliya22, udayempire), i.e. it's an OSS template
|
||||
that already spreads organically; one fork (`lakshh07/yc-outreach`) is a CLI variant that sends
|
||||
directly from the user's Gmail instead of requiring copy-paste.
|
||||
|
||||
## 1. Direct competitors
|
||||
|
||||
- **Work at a Startup** (workatastartup.com, YC's own official job board) — Free.
|
||||
- Strongest feature: every YC company is on it; founders see your profile directly, zero spam
|
||||
stigma, the default channel job seekers already trust.
|
||||
- Weakest point: purely passive — you wait to be found; founders read roughly 5% of cold
|
||||
inbound applications on it (cited by standout.work), no outreach tooling, no email finding.
|
||||
- **Chiaro** (chiaroai.com, iOS app) — subscription/freemium, price not publicly listed.
|
||||
- Strongest feature: swipe-based discovery + "Autopilot" that auto-sends a hyper-personalized
|
||||
email to the founder instantly; targets $150K-$350K+ founding-engineer roles at YC/a16z
|
||||
startups.
|
||||
- Weakest point: iOS-only, auto-send is a black box (little control over exact wording sent),
|
||||
no bulk filtering by hiring status/industry/batch.
|
||||
- **Backdoor AI** (backdoorai.app) — subscription, price not publicly listed.
|
||||
- Strongest feature: full-funnel tracking with published stats (9 of 10 users who get a reply
|
||||
hear back within two weeks; 4 of 10 founder replies come after a follow-up it sent); keeps a
|
||||
human-approval step before sending.
|
||||
- Weakest point: closed SaaS, account required, no way to audit how it finds/verifies emails;
|
||||
recurring subscription for something this repo does for free.
|
||||
- **VCBacked.co** — Free tier (5 verified leads/week); paid $79/mo or $299/yr.
|
||||
- Strongest feature: verified founder emails across 6,302+ YC companies spanning 48 batches,
|
||||
one-click bulk CSV export.
|
||||
- Weakest point: paywalls exactly the data (verified emails) a job seeker needs most; built for
|
||||
sales/recruiting/investor deal-sourcing, not job search — no resume/portfolio personalization,
|
||||
no per-founder open-role matching.
|
||||
- **Plox YC Founder List** (tryplox.com) — Free CSV, 8,000+ founders.
|
||||
- Strongest feature: zero cost, drops straight into Clay/Apollo/Instantly.
|
||||
- Weakest point: static snapshot that goes stale as batches turn over; no live hiring-role data,
|
||||
no template/personalization/send workflow — just a raw list.
|
||||
- **Origami.chat** — Starter $29/mo (2,000 credits) up to Max $499/mo.
|
||||
- Strongest feature: built-in multi-channel sequencer (LinkedIn + email, up to 10 steps each,
|
||||
unlimited sends on paid plans, no per-seat fee).
|
||||
- Weakest point: general-purpose prospecting tool retrofitted with YC-themed blog content, not
|
||||
YC-native; credit-metered and overpriced for someone outreaching to a single ~100-230-company
|
||||
batch.
|
||||
- **Apollo.io / Hunter.io / Clay** (generic B2B contact/outreach platforms) — Apollo $49-119/
|
||||
user/mo, Hunter $34-349/mo, Clay $185-495/mo.
|
||||
- Strongest feature: huge general contact databases plus mature sequencing/CRM infrastructure.
|
||||
- Weakest point: zero YC-awareness (no batch/industry/hiring/job-title filters, no one-liner
|
||||
context); per-seat/per-credit pricing is overkill for a single-batch job search.
|
||||
- **lakshh07/yc-outreach** (sibling OSS fork, CLI) — Free.
|
||||
- Strongest feature: sends the email directly from the user's own Gmail — no copy-paste step.
|
||||
- Weakest point: CLI only, no live search/filter UI, no on-site email scraping or Cloudflare
|
||||
de-obfuscation, no cross-session "sent" tracking or CSV export.
|
||||
|
||||
## 2. Differentiation plan (concrete, per competitor)
|
||||
|
||||
- **vs VCBacked ($79/mo) and Apollo/Hunter/Clay (per-seat/per-credit)**: stay fully free, no
|
||||
signup, no card — this is already true today; the move is to keep it that way as the explicit
|
||||
wedge against the exact thing VCBacked paywalls (verified founder emails) and the per-seat fees
|
||||
the generic tools charge.
|
||||
- **vs Chiaro/Backdoor AI (app download + account + subscription)**: keep the zero-install,
|
||||
zero-account single-page flow — a user goes from opening the URL to a copyable personalized
|
||||
email in under two minutes, with no onboarding screen, no app store install, no login.
|
||||
- **vs VCBacked/Plox/Origami/Apollo (none surface open roles per founder)**: this repo already
|
||||
shows each founder's actual open job postings (title + link) next to their email — the one
|
||||
feature that lets a pitch say "saw you're hiring a {job_title}" instead of a generic line. None
|
||||
of the list/database competitors expose this; Chiaro/Backdoor do, but only behind a paid app.
|
||||
Lean harder into this by surfacing job title directly inside the template placeholders (it is
|
||||
not currently one of the eight listed vars) so every generated email can reference the specific
|
||||
open role automatically.
|
||||
- **vs VCBacked/Plox/Apollo/Hunter pattern-guessing (none special-case site obfuscation)**: this
|
||||
repo already decodes Cloudflare's `data-cfemail` obfuscation (README notes ~1-in-16 sites use
|
||||
it) to recover real published addresses that competitors' pattern-matching misses — a concrete,
|
||||
already-built technical edge to market explicitly rather than bury in a changelog line.
|
||||
- **vs lakshh07's Gmail-send CLI fork (the one thing the sibling fork has that this repo lacks)**:
|
||||
port a client-side Gmail send step into `index.html` (OAuth to the user's own Gmail, same "be
|
||||
decent" daily cap/delay the CLI fork already does) so copy-paste disappears entirely — this
|
||||
closes the only functional gap inside the same OSS family while staying no-account like the
|
||||
rest of the page.
|
||||
- **vs Work at a Startup's passive queue (5% founder read rate per standout.work)**: market the
|
||||
tool explicitly against this number — "founders read ~5% of inbound on Work at a Startup; this
|
||||
reaches the other 95% directly" — a named, quantified contrast rather than a vague "better"
|
||||
claim.
|
||||
- **vs Backdoor AI/Chiaro's closed black-box send**: stay open source and keep the Apify token
|
||||
flow client-side-only (already true) — the explicit trust pitch for a technical audience that
|
||||
can read the code and verify no data leaves the browser except their own optional Apify call.
|
||||
|
||||
## 3. Primary user persona / ICP
|
||||
|
||||
- **Primary**: individual software engineers (new-grad through senior, especially candidates
|
||||
chasing "founding engineer" roles) who want to skip the standard ATS/Work-at-a-Startup queue and
|
||||
email YC founders directly. The template's own placeholder set — `{portfolio} {github}
|
||||
{resume}` — is designed around this persona, not a sales rep or recruiter.
|
||||
- **Secondary**: recruiters/agencies and BD/sales reps prospecting YC companies (the industry and
|
||||
"hiring" filters serve this group too), but the resume/github/portfolio fields confirm the
|
||||
primary design target is the individual engineer pitching themselves, not a company pitching a
|
||||
service.
|
||||
- **Job-to-be-done**: "Give me a short, current list of YC companies that are actually hiring for
|
||||
my skill set right now, with the founder's real email and their specific open role, so I can
|
||||
send one honest, personalized email instead of mass-applying into Work at a Startup's queue
|
||||
where only ~5% of inbound gets read."
|
||||
|
||||
## 4. User journey map (discovery -> paying/retained)
|
||||
|
||||
1. **Discovery** — finds the tool via GitHub (already forked 6+ times under different usernames,
|
||||
i.e. organic template/search virality) or via a blog post/Reddit/HN thread about emailing YC
|
||||
founders for a job.
|
||||
2. **Landing** — opens the Vercel-deployed page (or runs `python3 serve.py` locally); no signup
|
||||
wall, reads the one-paragraph description at the top.
|
||||
3. **Setup** — fills in name/portfolio/github/resume and lightly edits the default subject/body
|
||||
template; everything saved to `localStorage`.
|
||||
4. **Target discovery** — picks a batch, toggles "hiring" and/or an industry filter, clicks "Load
|
||||
companies"/"Load more" repeatedly (20 companies per click, ~5-10s each).
|
||||
5. **Evaluation** — scans founders for high-reliability email badges and roles matching their
|
||||
skills; optionally pastes an Apify token to upgrade guesses to verified emails.
|
||||
6. **Action** — copies (today manually; see differentiation plan) the personalized email per
|
||||
founder and marks each company as "sent" to track progress.
|
||||
7. **Retention** — the natural return trigger is YC's batch cadence (new batch roughly every six
|
||||
months, or whenever "Load more" surfaces fresh postings within an open batch) — this is
|
||||
inherently a recurring, cadence-driven tool rather than a one-time-use one.
|
||||
8. **Monetization** — none today; fully free and open source. The only money that moves is the
|
||||
user's own optional, capped Apify spend (default $1/run), which this project never touches or
|
||||
collects.
|
||||
|
||||
**Biggest drop-off risk step**: step 5, the optional Apify-token decision. Most engineers job
|
||||
searching won't have an Apify account or know what Apify is, so they default to "guess" emails
|
||||
(only 80% first-guess accuracy per the README's own 151-email benchmark). That's exactly where
|
||||
emails bounce or go to the wrong inbox, the user's few outbound emails get no replies, trust in
|
||||
the tool collapses, and they abandon before ever sending anything — a silent failure mode with no
|
||||
feedback loop to tell the user *why* it didn't work.
|
||||
|
||||
Second-largest drop-off: step 6, the pure-friction copy-paste-into-mail-client step with no
|
||||
auto-send, which the sibling `lakshh07` CLI fork already solves but this page does not.
|
||||
|
||||
## 5. Three concrete growth moves (follow directly from 1-4)
|
||||
|
||||
1. **Ship direct-send to close the step-6 drop-off and the only gap vs. the sibling CLI fork.**
|
||||
Port `lakshh07/yc-outreach`'s Gmail-send logic into `index.html` as a client-side OAuth flow to
|
||||
the user's own Gmail, with the same "be decent" daily cap/delay already documented in this
|
||||
repo's README footer. This turns the product from "list + template" into a complete send loop
|
||||
without adding an account or a backend, which is the single highest-leverage fix identified in
|
||||
the journey map's top drop-off risk area (steps 5-6 combined).
|
||||
2. **Consolidate fork-traffic discovery instead of fragmenting it.** Open a PR/README note on the
|
||||
six existing GitHub forks (wenayy, lakshh07, moizghumann, DevItaliya22, udayempire, and this
|
||||
repo's own `adityajha2005` origin) cross-linking to whichever fork stays most actively
|
||||
maintained, then post a "Show HN" / r/cscareerquestions / r/ExperiencedDevs thread framed around
|
||||
the named, quantified pain point from section 2: "Work at a Startup gets founders to read ~5%
|
||||
of inbound — this reaches the other 95% directly, with their actual open role in the email."
|
||||
This targets an audience (engineers already job-hunting) that is already searching exactly this
|
||||
problem, per the "How to Find & Contact YC Founders" and "get a job at a YC startup" content
|
||||
already ranking for it.
|
||||
3. **Add a no-account, no-backend "new batch" notification** (browser push permission or a static
|
||||
RSS/webhook feed generated by the existing `api/yc.py` batches endpoint) that fires when YC
|
||||
opens a new batch's hiring postings. The journey map shows the product's only retention cadence
|
||||
is YC's own batch cycle (~every six months); without a push mechanism, a user who used the tool
|
||||
once during one batch has zero reason to come back on their own for the next one. This closes
|
||||
that retention gap while staying consistent with the product's existing all-client-side, no
|
||||
backend-state design (the notification target list itself can live in `localStorage`, same as
|
||||
everything else).
|
||||
242
api/yc.py
242
api/yc.py
@ -1,38 +1,24 @@
|
||||
"""Vercel serverless function: YC batches, companies, founders, jobs and a change digest. Stdlib only, no API key.
|
||||
"""Vercel serverless function: YC batches, companies and founders. Stdlib only, no API key.
|
||||
|
||||
GET /api/yc?action=batches
|
||||
GET /api/yc?action=companies&batch=Winter%202024[,Summer%202024,...] (multiple batches comma-separated)
|
||||
GET /api/yc?action=companies&batch=Winter%202024
|
||||
GET /api/yc?action=founders&slugs=airbnb,stripe (max 10 slugs per call)
|
||||
GET /api/yc?action=job&url=https://www.ycombinator.com/companies/stripe/jobs/<id>
|
||||
GET /api/yc?action=digest&known_batches=<json>&slugs=a,b,c&known_jobs=<json>
|
||||
|
||||
Founder names and job descriptions only live on each company's/job's ycombinator.com page, which
|
||||
browsers can't fetch cross-origin, so this runs server-side. Emails: addresses on the company site
|
||||
plus pattern guesses, ranked by a confidence score and an MX-record check. Optional verified lookup
|
||||
(Apify) runs in the browser, so visitors' tokens never reach this server.
|
||||
Founder names only live on each company's ycombinator.com page, which browsers can't fetch
|
||||
cross-origin, so this runs server-side. Emails: addresses on the company site plus pattern guesses.
|
||||
Optional verified lookup (Apify) runs in the browser, so visitors' tokens never reach this server.
|
||||
"""
|
||||
import concurrent.futures as cf, html, json, re, socket, ssl, time, unicodedata, urllib.parse, urllib.request
|
||||
import concurrent.futures as cf, html, json, re, socket, ssl, unicodedata, urllib.parse, urllib.request
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128 Safari/537.36"
|
||||
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
|
||||
CF_EMAIL_RE = re.compile(r'data-cfemail="([0-9a-fA-F]+)"') # Cloudflare's "email protection" obfuscation
|
||||
BAD_EMAIL = re.compile(r"\.(png|jpe?g|gif|svg|webp|css|js)$|sentry|wixpress|example\.|@2x|u00|domain\.com|email\.com", re.I)
|
||||
SLUG_RE = re.compile(r"^[a-z0-9-]{1,100}$")
|
||||
BATCH_RE = re.compile(r"^(Winter|Spring|Summer|Fall) \d{4}$|^[WSFX]\d{2}$|^IK12$|^Unspecified$")
|
||||
JOB_URL_RE = re.compile(r"^https://(www\.)?ycombinator\.com/companies/[a-z0-9-]{1,100}/jobs/[A-Za-z0-9_-]{1,200}(?:[/?].*)?$")
|
||||
MAX_SLUGS = 10
|
||||
MAX_BATCHES = 8 # multi-batch search: sanity cap, same spirit as MAX_SLUGS
|
||||
MAX_DIGEST_SLUGS = 40 # digest only checks job counts (no site scrape), so it can cover more than MAX_SLUGS
|
||||
CTX = ssl.create_default_context()
|
||||
SEASON = {"Winter": 1, "Spring": 2, "Summer": 3, "Fall": 4}
|
||||
# Confidence (%) that a given pattern guess is correct, taken from this project's own benchmark
|
||||
# (README: first guess right 80% of the time, correct address somewhere in the list 93% of the time).
|
||||
GUESS_CONFIDENCE = {"first": 80, "first.last": 7, "flast": 4, "firstlast": 2}
|
||||
GUESS_CONFIDENCE_NO_LAST = {"first": 55} # no last name on file: only one guess is possible, less certain
|
||||
INFERRED_CONFIDENCE = 95 # a same-domain founder already confirmed this exact pattern
|
||||
INFERRED_OTHER_CAP = 3 # once a pattern is inferred, every other guess for that domain is capped this low
|
||||
MX_UNKNOWN_FACTOR = 0.75 # DNS-over-HTTPS lookup failed/timed out: still offer guesses, less sure of them
|
||||
_algolia = None # (app, key), cached per warm instance
|
||||
_pool = cf.ThreadPoolExecutor(32) # site checks; outlives a request so a slow site can be abandoned
|
||||
SITE_DEADLINE = 4 # seconds per company before giving up on its website
|
||||
@ -76,7 +62,7 @@ def batches():
|
||||
return [{"batch": b, "count": n} for b, n in sorted(facets.items(), key=lambda x: batch_key(x[0]), reverse=True)]
|
||||
|
||||
|
||||
def companies_one(batch):
|
||||
def companies(batch):
|
||||
hits, page = [], 0
|
||||
while True:
|
||||
res = algolia({"hitsPerPage": 1000, "page": page, "facetFilters": json.dumps([[f"batch:{batch}"]])})
|
||||
@ -89,19 +75,6 @@ def companies_one(batch):
|
||||
"launched_at": h.get("launched_at") or 0} for h in hits]
|
||||
|
||||
|
||||
def companies(batch_list):
|
||||
# Multi-batch search: fetch each batch (in parallel) and merge, de-duplicating by slug in case
|
||||
# YC ever lists a company under more than one batch value.
|
||||
seen, out = set(), []
|
||||
with cf.ThreadPoolExecutor(max(1, len(batch_list))) as ex:
|
||||
for rows in ex.map(companies_one, batch_list):
|
||||
for r in rows:
|
||||
if r["slug"] not in seen:
|
||||
seen.add(r["slug"])
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def domain_of(website):
|
||||
host = urllib.parse.urlparse(website if "//" in (website or "") else f"https://{website}").hostname or ""
|
||||
return host.removeprefix("www.").lower()
|
||||
@ -111,94 +84,24 @@ def ascii_name(s):
|
||||
return re.sub(r"[^a-z ]", "", unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()).split()
|
||||
|
||||
|
||||
def cf_decode(hexstr):
|
||||
# Cloudflare's "email protection" shows "[email protected]" on the page and stashes the real
|
||||
# address XOR-masked in a data-cfemail="<hex>" attribute: byte 0 is the key, every later byte
|
||||
# is a masked character. Very common on small-business sites (Webflow/WordPress + Cloudflare);
|
||||
# EMAIL_RE alone never sees these addresses, so without this they silently fall back to a guess.
|
||||
try:
|
||||
key, rest = int(hexstr[:2], 16), hexstr[2:]
|
||||
if len(rest) < 2 or len(rest) % 2:
|
||||
return None
|
||||
return bytes(int(rest[i : i + 2], 16) ^ key for i in range(0, len(rest), 2)).decode("ascii")
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def site_emails(website, domain):
|
||||
found = set()
|
||||
for path in ("", "/contact"): # ponytail: 2 pages, not the CLI's 6, to fit in a function timeout
|
||||
raw = get(website.rstrip("/") + path, timeout=3) or ""
|
||||
candidates = EMAIL_RE.findall(urllib.parse.unquote(html.unescape(raw)))
|
||||
candidates += filter(None, (cf_decode(h) for h in CF_EMAIL_RE.findall(raw)))
|
||||
for e in candidates:
|
||||
body = get(website.rstrip("/") + path, timeout=3)
|
||||
for e in EMAIL_RE.findall(urllib.parse.unquote(html.unescape(body or ""))):
|
||||
e = e.lower().strip(".")
|
||||
host = e.split("@")[-1]
|
||||
if EMAIL_RE.fullmatch(e) and not BAD_EMAIL.search(e) and (host == domain or host.endswith("." + domain)):
|
||||
host = e.split("@")[1]
|
||||
if not BAD_EMAIL.search(e) and (host == domain or host.endswith("." + domain)):
|
||||
found.add(e)
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def guesses(full_name, domain, factor=1.0):
|
||||
# Returns [{email, pattern, confidence}], highest confidence first. `factor` scales confidence
|
||||
# down (e.g. when the MX lookup was inconclusive) without changing the ranking.
|
||||
def guesses(full_name, domain):
|
||||
parts = ascii_name(full_name)
|
||||
if not parts or not domain:
|
||||
return []
|
||||
first, last = parts[0], parts[-1] if len(parts) > 1 else ""
|
||||
if not last:
|
||||
pats = {"first": first}
|
||||
base = GUESS_CONFIDENCE_NO_LAST
|
||||
else:
|
||||
pats = {"first": first, "first.last": f"{first}.{last}", "flast": f"{first[0]}{last}", "firstlast": f"{first}{last}"}
|
||||
base = GUESS_CONFIDENCE
|
||||
return [{"email": f"{pats[p]}@{domain}", "pattern": p, "confidence": round(base[p] * factor)} for p in pats]
|
||||
|
||||
|
||||
def infer_pattern(local_part, full_name):
|
||||
# Does an already-known real email's local part match one of our own guess patterns for this
|
||||
# person? If so, every other founder at the same domain almost certainly uses that same pattern.
|
||||
parts = ascii_name(full_name)
|
||||
if not parts:
|
||||
return None
|
||||
first, last = parts[0], parts[-1] if len(parts) > 1 else ""
|
||||
if local_part == first:
|
||||
return "first"
|
||||
if last and local_part == f"{first}.{last}":
|
||||
return "first.last"
|
||||
if last and local_part == f"{first[0]}{last}":
|
||||
return "flast"
|
||||
if last and local_part == f"{first}{last}":
|
||||
return "firstlast"
|
||||
return None
|
||||
|
||||
|
||||
def apply_inferred_pattern(out):
|
||||
# Mutates `out` (list of founder dicts for one company) in place: once any founder's real email
|
||||
# (site_emails) reveals this company's address pattern, re-rank every other founder's guesses so
|
||||
# that same pattern comes first with high confidence, instead of leaving them on the generic
|
||||
# frequency-based order.
|
||||
inferred = None
|
||||
for f in out:
|
||||
for e in f["emails_found"]:
|
||||
inferred = infer_pattern(e.split("@")[0], f["name"])
|
||||
if inferred:
|
||||
break
|
||||
if inferred:
|
||||
break
|
||||
if not inferred:
|
||||
return
|
||||
for f in out:
|
||||
if f["emails_found"] or not f["email_guesses"]:
|
||||
continue
|
||||
match = next((g for g in f["email_guesses"] if g["pattern"] == inferred), None)
|
||||
if not match:
|
||||
continue
|
||||
match["confidence"] = INFERRED_CONFIDENCE
|
||||
others = [g for g in f["email_guesses"] if g is not match]
|
||||
for g in others:
|
||||
g["confidence"] = min(g["confidence"], INFERRED_OTHER_CAP)
|
||||
f["email_guesses"] = [match] + others
|
||||
return [f"{first}@{domain}"] + ([f"{first}.{last}@{domain}", f"{first[0]}{last}@{domain}", f"{first}{last}@{domain}"] if last else [])
|
||||
|
||||
|
||||
def resolves(domain):
|
||||
@ -209,28 +112,6 @@ def resolves(domain):
|
||||
return False
|
||||
|
||||
|
||||
def resolves_mx(domain):
|
||||
# DNS-over-HTTPS (Cloudflare's resolver) instead of a dnspython dependency. Returns True (has a
|
||||
# real mail server), False (confirmed no mail server, including an RFC 7505 null MX "0 ."), or
|
||||
# None if the lookup itself failed/timed out (caller should treat that as "unknown", not "no").
|
||||
raw = get(f"https://cloudflare-dns.com/dns-query?name={urllib.parse.quote(domain)}&type=MX",
|
||||
headers={"Accept": "application/dns-json"}, timeout=4)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
if data.get("Status") != 0:
|
||||
return None
|
||||
mx = [a for a in data.get("Answer") or [] if a.get("type") == 15]
|
||||
if not mx:
|
||||
return False
|
||||
if all(a.get("data", "").strip().rstrip(".").strip() == "0" for a in mx):
|
||||
return False # null MX: domain explicitly accepts no mail
|
||||
return True
|
||||
|
||||
|
||||
def open_jobs(props):
|
||||
# jobPostings is on the same company page as the founders, next to props.company
|
||||
jobs = []
|
||||
@ -258,11 +139,6 @@ def founders(slug):
|
||||
except cf.TimeoutError:
|
||||
emails = [] # ponytail: slow site skipped, guesses still cover it; the CLI waits longer
|
||||
dns = resolves(domain) if domain else False
|
||||
mx = resolves_mx(domain) if dns else None # None = DNS resolved but MX lookup itself was inconclusive
|
||||
# mx is False only when the lookup *succeeded* and confirmed there is no mail server: don't offer
|
||||
# guesses at all then. mx is None when the lookup failed/timed out: still guess, just less sure.
|
||||
offer_guesses = dns and mx is not False
|
||||
factor = 1.0 if mx else MX_UNKNOWN_FACTOR
|
||||
out = []
|
||||
for f in c.get("founders", []):
|
||||
name = f.get("full_name") or ""
|
||||
@ -270,75 +146,10 @@ def founders(slug):
|
||||
out.append({"name": name, "title": f.get("title") or "", "linkedin": f.get("linkedin_url") or "",
|
||||
"twitter": f.get("twitter_url") or "",
|
||||
"emails_found": [e for e in emails if first and e.split("@")[0].startswith(first)],
|
||||
"email_guesses": guesses(name, domain, factor) if offer_guesses else []})
|
||||
apply_inferred_pattern(out)
|
||||
"email_guesses": guesses(name, domain) if dns else []})
|
||||
return {"slug": slug, "website": website, "domain": domain, "linkedin": c.get("linkedin_url") or "",
|
||||
"twitter": c.get("twitter_url") or "", "site_emails": emails, "mx": mx, "job_count": len(jobs),
|
||||
"jobs": jobs, "founders": out}
|
||||
|
||||
|
||||
def job_detail(url):
|
||||
page = get(url)
|
||||
m = re.search(r'data-page="([^"]*)"', page or "")
|
||||
if not m:
|
||||
return {"error": "Couldn't load this job's YC page"}
|
||||
props = json.loads(html.unescape(m.group(1)))["props"]
|
||||
j = props.get("job") or {}
|
||||
if not j:
|
||||
return {"error": "This job posting couldn't be read"}
|
||||
return {"title": j.get("title") or "", "url": url, "location": j.get("location") or "",
|
||||
"type": j.get("type") or "", "role": j.get("prettyRole") or j.get("role") or "",
|
||||
"min_experience": j.get("minExperience") or "", "salary_range": j.get("salaryRange") or "",
|
||||
"equity_range": j.get("equityRange") or "", "visa": j.get("visa") or "",
|
||||
"skills": j.get("skills") or [], "description": (j.get("description") or "").strip(),
|
||||
"interview_process": (j.get("interview_process") or "").strip(),
|
||||
"company_name": j.get("companyName") or "", "company_one_liner": j.get("companyOneLiner") or ""}
|
||||
|
||||
|
||||
def company_jobs_quick(slug):
|
||||
# Cheaper than founders(): no website scrape, just the job count + titles for the new-role watcher.
|
||||
page = get(f"https://www.ycombinator.com/companies/{slug}")
|
||||
m = re.search(r'data-page="([^"]*)"', page or "")
|
||||
if not m:
|
||||
return {"slug": slug, "error": "Couldn't load this company's YC page"}
|
||||
props = json.loads(html.unescape(m.group(1)))["props"]
|
||||
jobs = open_jobs(props)
|
||||
return {"slug": slug, "job_count": len(jobs), "jobs": [j["title"] for j in jobs]}
|
||||
|
||||
|
||||
def digest(known_batches_json, slug_list, known_jobs_json):
|
||||
try:
|
||||
known_batches = json.loads(known_batches_json) if known_batches_json else {}
|
||||
known_jobs = json.loads(known_jobs_json) if known_jobs_json else {}
|
||||
except ValueError:
|
||||
known_batches, known_jobs = {}, {}
|
||||
current = batches()
|
||||
new_batches = [b for b in current if known_batches.get(b["batch"]) != b["count"]]
|
||||
changed_jobs = []
|
||||
job_counts = {}
|
||||
if slug_list:
|
||||
with cf.ThreadPoolExecutor(len(slug_list)) as ex:
|
||||
for r in ex.map(company_jobs_quick, slug_list):
|
||||
if r.get("error"):
|
||||
continue
|
||||
job_counts[r["slug"]] = r["job_count"]
|
||||
# Only flag a real change when we have an actual prior count for this slug. Defaulting
|
||||
# a missing baseline to 0 (the old behavior) meant every company's first-ever digest
|
||||
# check flagged its existing roles as "changed" -- confirmed live: a cold known_jobs={}
|
||||
# call returned 13/30 companies in changed_jobs, none of which had just posted anything.
|
||||
if r["slug"] in known_jobs and r["job_count"] != known_jobs[r["slug"]]:
|
||||
changed_jobs.append(r)
|
||||
# "batches" (every current batch, not just changed ones) and "job_counts" (every checked slug's
|
||||
# current count) let the client persist a complete baseline. Without them the client's
|
||||
# noteBaselineBatches() call throws on `d.batches.filter` (d.batches was undefined), which the
|
||||
# caller swallows silently -- the new-batch/new-role watcher never fires or errors visibly.
|
||||
return {
|
||||
"checked_at": int(time.time()),
|
||||
"batches": current,
|
||||
"new_batches": new_batches,
|
||||
"changed_jobs": changed_jobs,
|
||||
"job_counts": job_counts,
|
||||
}
|
||||
"twitter": c.get("twitter_url") or "", "site_emails": emails, "job_count": len(jobs), "jobs": jobs,
|
||||
"founders": out}
|
||||
|
||||
|
||||
def route(query):
|
||||
@ -347,29 +158,16 @@ def route(query):
|
||||
if action == "batches":
|
||||
return 200, batches(), 86400
|
||||
if action == "companies":
|
||||
batch_list = [b for b in (q.get("batch") or [""])[0].split(",") if b]
|
||||
if not batch_list or len(batch_list) > MAX_BATCHES or not all(BATCH_RE.match(b) for b in batch_list):
|
||||
return 400, {"error": f"Pass 1-{MAX_BATCHES} valid batches"}, 0
|
||||
return 200, companies(batch_list), 3600
|
||||
batch = (q.get("batch") or [""])[0]
|
||||
if not BATCH_RE.match(batch):
|
||||
return 400, {"error": "Invalid batch"}, 0
|
||||
return 200, companies(batch), 3600
|
||||
if action == "founders":
|
||||
slugs = [s for s in (q.get("slugs") or [""])[0].split(",") if s]
|
||||
if not slugs or len(slugs) > MAX_SLUGS or not all(SLUG_RE.match(s) for s in slugs):
|
||||
return 400, {"error": f"Pass 1-{MAX_SLUGS} valid slugs"}, 0
|
||||
with cf.ThreadPoolExecutor(len(slugs)) as ex:
|
||||
return 200, list(ex.map(founders, slugs)), 86400
|
||||
if action == "job":
|
||||
url = (q.get("url") or [""])[0]
|
||||
if not JOB_URL_RE.match(url):
|
||||
return 400, {"error": "Invalid job URL"}, 0
|
||||
result = job_detail(url)
|
||||
return (502 if "error" in result and len(result) == 1 else 200), result, 86400
|
||||
if action == "digest":
|
||||
slugs = [s for s in (q.get("slugs") or [""])[0].split(",") if s][:MAX_DIGEST_SLUGS]
|
||||
if not all(SLUG_RE.match(s) for s in slugs):
|
||||
return 400, {"error": "Invalid slug in digest request"}, 0
|
||||
known_batches = (q.get("known_batches") or [""])[0]
|
||||
known_jobs = (q.get("known_jobs") or [""])[0]
|
||||
return 200, digest(known_batches, slugs, known_jobs), 0
|
||||
return 400, {"error": "Unknown action"}, 0
|
||||
|
||||
|
||||
|
||||
564
index.html
564
index.html
@ -12,7 +12,6 @@
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:title" content="YC Founder Outreach">
|
||||
<meta name="twitter:description" content="Pick any YC batch, get every company's founders and likely email addresses, and draft a personalised cold email to each one from a single template. Free, no sign-up, no API key.">
|
||||
<script src="https://accounts.google.com/gsi/client" async defer></script>
|
||||
<style>
|
||||
:root{--bg:#f7f7f5;--card:#fff;--fg:#1c1c1a;--muted:#6b6b66;--line:#e4e3de;--accent:#e2561b;--ok:#1f8a4c;--warn:#a86b00;--err:#c0392b}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#141413;--card:#1e1e1c;--fg:#ecebe6;--muted:#9a998f;--line:#302f2b;--accent:#f07a45;--ok:#4cc27d;--warn:#e0a53a;--err:#e8705f}}
|
||||
@ -41,22 +40,10 @@ summary::before{content:"▸";color:var(--muted)}details[open] summary::before{c
|
||||
.one{color:var(--muted);font-size:14px;margin:10px 0 0}
|
||||
pre{white-space:pre-wrap;font:inherit;background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:12px;margin:10px 0}
|
||||
.acts{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
|
||||
button,a.btn,label.btn{font:inherit;font-size:13px;cursor:pointer;border-radius:8px;padding:6px 12px;border:1px solid var(--line);background:var(--card);color:var(--fg);text-decoration:none;display:inline-flex;align-items:center}
|
||||
button,a.btn{font:inherit;font-size:13px;cursor:pointer;border-radius:8px;padding:6px 12px;border:1px solid var(--line);background:var(--card);color:var(--fg);text-decoration:none}
|
||||
button.primary{background:var(--accent);border-color:var(--accent);color:#fff}button:disabled{opacity:.5;cursor:default}
|
||||
a.lnk{color:var(--muted);font-size:13px}
|
||||
footer{color:var(--muted);font-size:13px;margin-top:32px}
|
||||
.conf{font-size:11px;color:var(--muted);font-weight:400}
|
||||
.alt{font-size:12px;color:var(--muted);margin:4px 0 0;cursor:pointer}
|
||||
.altlist{font-size:12px;color:var(--muted);margin:4px 0 0;display:none}.altlist.show{display:block}
|
||||
.fit{font-size:12px;color:var(--accent);font-weight:600}
|
||||
.stageSel{font-size:13px;padding:4px 8px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:var(--fg)}
|
||||
.stage-followed_up{opacity:.8}.stage-replied{outline:2px solid var(--ok)}.stage-interview{outline:2px solid var(--accent)}
|
||||
.due{color:var(--err);font-weight:600}
|
||||
.jobsel{font-size:13px;margin:8px 0 0}
|
||||
.queue{display:flex;gap:10px;flex-wrap:wrap;align-items:center;font-size:13px;color:var(--muted)}
|
||||
#gmailPanel.connected{border-color:var(--ok)}
|
||||
.dot{display:inline-block;width:8px;height:8px;border-radius:99px;background:var(--muted)}
|
||||
.dot.on{background:var(--ok)}
|
||||
</style></head><body><main>
|
||||
<h1>YC Founder Outreach</h1>
|
||||
<p class="sub">Pick a YC batch, find founder emails, and write personalised cold emails from one template. Free without any keys; everything you type stays in your browser.</p>
|
||||
@ -69,58 +56,26 @@ footer{color:var(--muted);font-size:13px;margin-top:32px}
|
||||
<label class="f">GitHub<input data-k="github" placeholder="https://github.com/..."></label>
|
||||
<label class="f">Resume link<input data-k="resume" placeholder="https://..."></label>
|
||||
</div>
|
||||
<label class="f" style="margin-top:10px">Your skills / stack <span style="color:var(--muted)">(used to rank companies by fit — "Best fit first". A starred score, e.g. "12%*", means the company has no open roles listed yet, so it's estimated from its one-liner/industry instead of an actual job post.)</span>
|
||||
<textarea data-k="skills" style="min-height:60px" placeholder="e.g. TypeScript, React, Node, Postgres, Go, infra, founding engineer"></textarea></label>
|
||||
<h2 style="margin-top:16px">2. Email template</h2>
|
||||
<h2>2. Email template</h2>
|
||||
<label class="f">Subject<input data-k="subject"></label>
|
||||
<label class="f" style="margin-top:10px">Body<textarea data-k="body"></textarea></label>
|
||||
<p class="ph" id="vars">Click to insert: <code>{first_name}</code><code>{company}</code><code>{one_liner}</code><code>{batch}</code><code>{job_title}</code><code>{job_url}</code><code>{my_name}</code><code>{portfolio}</code><code>{github}</code><code>{resume}</code>
|
||||
<p class="ph" id="vars">Click to insert: <code>{first_name}</code><code>{company}</code><code>{one_liner}</code><code>{batch}</code><code>{my_name}</code><code>{portfolio}</code><code>{github}</code><code>{resume}</code>
|
||||
<button id="reset" type="button">Reset template</button></p>
|
||||
<p class="ph">Lines like <code>resume: {resume}</code> are dropped when you leave that field empty. Email labels: <span class="badge valid">verified</span> / <span class="badge unknown">unverified</span> come from Apify (step 4), <span class="badge site">on site</span> is listed on the company's website, <span class="badge guess">guess</span> shows a confidence percentage and may bounce. When a company has more than one open role, pick which one the draft targets from its role dropdown.</p>
|
||||
<details style="margin-top:10px"><summary style="cursor:pointer;color:var(--muted);font-size:13px">Follow-up email (sent automatically from the queue once a contact's follow-up is due)</summary>
|
||||
<div style="padding-top:10px">
|
||||
<label class="f">Follow-up subject<input data-k="followup_subject"></label>
|
||||
<label class="f" style="margin-top:10px">Follow-up body<textarea data-k="followup_body" style="min-height:160px"></textarea></label>
|
||||
<p class="ph">Same placeholders as above. Follow-up is scheduled
|
||||
<input id="followupDays" type="number" min="1" max="30" value="5" style="width:50px;display:inline-block;padding:2px 6px"> business days after a contact is marked <b>Sent</b>.</p>
|
||||
</div>
|
||||
</details>
|
||||
<p class="ph">Lines like <code>resume: {resume}</code> are dropped when you leave that field empty. Email labels: <span class="badge valid">verified</span> / <span class="badge unknown">unverified</span> come from Apify (step 4), <span class="badge site">on site</span> is listed on the company's website, <span class="badge guess">guess</span> is the most common pattern (right about 80% of the time) and may bounce.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>3. Pick YC batch(es)</h2>
|
||||
<h2>3. Pick a YC batch</h2>
|
||||
<div class="row2">
|
||||
<select id="batch" multiple size="6" aria-label="YC batches (select one or more)"><option value="">Loading batches…</option></select>
|
||||
<select id="batch" aria-label="YC batch"><option value="">Loading batches…</option></select>
|
||||
<button id="load" class="primary" type="button" disabled>Load companies</button>
|
||||
</div>
|
||||
<p class="ph" style="margin:6px 0 0">Ctrl/Cmd-click (or shift-click) to select several batches — e.g. every batch from the last year — and load them in one pass.</p>
|
||||
<p class="status" id="loadStatus"></p>
|
||||
</section>
|
||||
|
||||
<section class="panel" id="gmailPanel">
|
||||
<h2>4. Connect Gmail <span style="font-weight:400;color:var(--muted)">(optional — send without leaving this page)</span></h2>
|
||||
<p class="ph" style="margin:0 0 10px">Connects straight from your browser to the Gmail API with the narrowest possible scope (<code>gmail.send</code> only — this app can send as you, never read your mail).
|
||||
The token lives only in this tab's memory/session storage; it is never sent to this site's server. Sends go out through a queue with a random 20-60s delay between messages and a daily cap, so you don't blast everyone at once.
|
||||
Requires a free Google Cloud OAuth client ID (owner/operator sets this up once in the Google Cloud Console — zero cost, not needed to use Copy/mailto instead).</p>
|
||||
<div class="row2">
|
||||
<button id="gmailConnect" type="button">Connect Gmail</button>
|
||||
<button id="gmailDisconnect" type="button" hidden>Disconnect</button>
|
||||
<span class="chk"><span class="dot" id="gmailDot"></span><span id="gmailState">Not connected</span></span>
|
||||
<label class="f" style="flex:1;min-width:160px">Daily send cap<input id="dailyCap" type="number" min="1" max="200" value="30"></label>
|
||||
</div>
|
||||
<p class="status" id="gmailStatus"></p>
|
||||
<div class="queue" id="queuePanel" hidden>
|
||||
<span>Queue: <b id="qPending">0</b> pending</span>
|
||||
<span>Sent today: <b id="qSentToday">0</b>/<span id="qCapLabel">30</span></span>
|
||||
<span id="qNext"></span>
|
||||
<button id="qToggle" type="button">Pause</button>
|
||||
<button id="qClear" type="button">Clear queue</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>5. Find verified emails <span style="font-weight:400;color:var(--muted)">(optional)</span></h2>
|
||||
<p class="ph" style="margin:0 0 10px">Without this you get emails listed on company sites plus pattern guesses like <code>first@domain</code>, each with a confidence percentage based on this tool's own benchmark and, once any founder's real address is known, re-ranked to that company's actual pattern. For verified emails, paste your own
|
||||
<h2>4. Find verified emails <span style="font-weight:400;color:var(--muted)">(optional)</span></h2>
|
||||
<p class="ph" style="margin:0 0 10px">Without this you get emails listed on company sites plus pattern guesses like <code>first@domain</code> (right about 80% of the time). For verified emails, paste your own
|
||||
<a href="https://console.apify.com/settings/integrations" target="_blank" rel="noopener">Apify API token</a>. Lookups run from your browser straight to Apify on your account; the token is never sent to this site's server and isn't saved.</p>
|
||||
<div class="row2">
|
||||
<label class="f" style="flex:2">Apify token<input id="token" type="password" placeholder="apify_api_..." autocomplete="off"></label>
|
||||
@ -131,36 +86,21 @@ footer{color:var(--muted);font-size:13px;margin-top:32px}
|
||||
</section>
|
||||
|
||||
<div class="bar">
|
||||
<input id="q" placeholder="Search company, founder, role or description" aria-label="Search">
|
||||
<input id="q" placeholder="Search company or founder" aria-label="Search">
|
||||
<select id="st" aria-label="Email type"><option value="">All emails</option><option value="valid">Verified</option><option value="unknown">Unverified</option><option value="site">Found on site</option><option value="guess">Guess</option><option value="none">No email</option></select>
|
||||
<select id="ind" aria-label="Industry"><option value="">All industries</option></select>
|
||||
<select id="stageFilter" aria-label="Pipeline stage"><option value="">All stages</option><option value="not_sent">Not sent</option><option value="sent">Sent</option><option value="due">Follow-up due</option><option value="followed_up">Followed up</option><option value="replied">Replied</option><option value="interview">Interview</option><option value="rejected">Rejected</option><option value="closed">Closed</option></select>
|
||||
<label class="chk"><input type="checkbox" id="hideSent"> hide contacted</label>
|
||||
<label class="chk"><input type="checkbox" id="hideSent"> hide sent</label>
|
||||
<label class="chk"><input type="checkbox" id="hiring"> hiring</label>
|
||||
<button id="fitSort" type="button">Best fit first</button>
|
||||
<button id="notifyBtn" type="button" title="Notify me about new batches and new roles">Enable alerts</button>
|
||||
<button id="all" type="button">Expand all</button>
|
||||
<button id="exportCsv" type="button">Export CSV</button>
|
||||
<button id="exportJson" type="button" title="Back up every setting and loaded company to a file">Export session</button>
|
||||
<label class="btn" style="margin:0" title="Restore from an exported session file">Import session<input id="importJson" type="file" accept="application/json" hidden></label>
|
||||
</div>
|
||||
<p class="sub" id="shown" style="margin:0 0 10px"></p>
|
||||
<p class="status" id="watchStatus" style="margin:0 0 10px"></p>
|
||||
<div id="list"></div>
|
||||
<p style="text-align:center"><button id="more" class="primary" type="button" hidden>Load more</button></p>
|
||||
<footer><a class="lnk" href="https://github.com/adityajha2005/yc-outreach" target="_blank" rel="noopener">Open source</a> — star it on GitHub. Company and founder data comes from YC's public directory. Please write to people one at a time and respect "no".</footer>
|
||||
</main>
|
||||
<script>
|
||||
// Google OAuth client ID for the optional "Connect Gmail" direct-send feature (gmail.send scope only).
|
||||
// Owner/operator step (zero cost, console-only): create an OAuth 2.0 Web application client at
|
||||
// https://console.cloud.google.com/apis/credentials, add this page's origin to "Authorized JavaScript
|
||||
// origins", enable the Gmail API, and paste the client ID below. Until that's done, Connect Gmail shows
|
||||
// a clear error and every other feature (including Copy/mailto sending) works exactly as before.
|
||||
const GOOGLE_CLIENT_ID = "REPLACE_WITH_GOOGLE_OAUTH_CLIENT_ID.apps.googleusercontent.com";
|
||||
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
|
||||
|
||||
const DEFAULTS = {
|
||||
my_name: "", portfolio: "", github: "", resume: "", skills: "",
|
||||
my_name: "", portfolio: "", github: "", resume: "",
|
||||
subject: "interested in {company}",
|
||||
body: `Hey {first_name},
|
||||
|
||||
@ -175,66 +115,19 @@ would love to explore if there's a role at {company}.
|
||||
- {my_name}
|
||||
portfolio: {portfolio}
|
||||
github: {github}
|
||||
resume: {resume}`,
|
||||
followup_subject: "following up: {company}",
|
||||
followup_body: `Hey {first_name},
|
||||
|
||||
following up on my note about {company} (role: {job_title}) in case it got buried — still very interested.
|
||||
|
||||
- {my_name}
|
||||
portfolio: {portfolio}`
|
||||
resume: {resume}`
|
||||
};
|
||||
const KEY = "yc-outreach-v2";
|
||||
const ACTOR = "snipercoder~email-finder-by-name-and-domain";
|
||||
const APIFY = "https://api.apify.com/v2";
|
||||
const GMAIL = "https://gmail.googleapis.com/gmail/v1";
|
||||
// Pipeline stages, in order. "due" is a derived filter value, not a stored stage.
|
||||
const STAGES = ["not_sent", "sent", "followed_up", "replied", "interview", "rejected", "closed"];
|
||||
const STAGE_LABEL = { not_sent: "Not sent", sent: "Sent", followed_up: "Followed up", replied: "Replied",
|
||||
interview: "Interview", rejected: "Rejected", closed: "Closed" };
|
||||
const store = { get(k, d) { try { const v = JSON.parse(localStorage.getItem(k)); return v === null || v === undefined ? d : v } catch { return d } },
|
||||
const store = { get(k, d) { try { return JSON.parse(localStorage.getItem(k)) ?? d } catch { return d } },
|
||||
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)) } catch {} } };
|
||||
let tpl = Object.assign({}, DEFAULTS, store.get(KEY, {}));
|
||||
// Pipeline state, keyed by YC slug: { stage, sentAt, followupDueAt, followedUpAt, repliedAt, interviewAt, closedAt, template }
|
||||
let stages = store.get(KEY + "-stages", {});
|
||||
(function migrateSentSet() { // one-time: the old boolean "sent" Set becomes stage "sent" with no known timestamp
|
||||
const legacy = store.get(KEY + "-sent", null);
|
||||
if (!legacy) return;
|
||||
for (const slug of legacy) if (!stages[slug]) stages[slug] = { stage: "sent", sentAt: null };
|
||||
store.set(KEY + "-stages", stages);
|
||||
localStorage.removeItem(KEY + "-sent");
|
||||
})();
|
||||
function stageOf(slug) { return stages[slug]?.stage || "not_sent"; }
|
||||
function isDue(slug) {
|
||||
const s = stages[slug];
|
||||
return !!(s && s.stage === "sent" && s.followupDueAt && Date.now() >= s.followupDueAt);
|
||||
}
|
||||
function addBusinessDays(date, days) {
|
||||
const d = new Date(date);
|
||||
let left = days;
|
||||
while (left > 0) { d.setDate(d.getDate() + 1); if (d.getDay() !== 0 && d.getDay() !== 6) left--; }
|
||||
return d;
|
||||
}
|
||||
function setStage(slug, stage) {
|
||||
const now = Date.now(), prev = stages[slug] || {};
|
||||
const rec = { ...prev, stage };
|
||||
if (stage === "sent" && !prev.sentAt) { rec.sentAt = now; rec.followupDueAt = addBusinessDays(now, +$("followupDays").value || 5).getTime(); }
|
||||
if (stage === "followed_up") rec.followedUpAt = now;
|
||||
if (stage === "replied") rec.repliedAt = now;
|
||||
if (stage === "interview") rec.interviewAt = now;
|
||||
if (stage === "rejected") rec.rejectedAt = now;
|
||||
if (stage === "closed") rec.closedAt = now;
|
||||
stages[slug] = rec;
|
||||
store.set(KEY + "-stages", stages);
|
||||
}
|
||||
let ALL = [], DATA = [], batch = "", sortMode = "default";
|
||||
const jobSel = store.get(KEY + "-jobsel", {}); // slug -> index into c.jobs, for the role picker
|
||||
const jobCache = store.get(KEY + "-jobcache", {}); // job url -> full job detail (description etc.)
|
||||
let sent = new Set(store.get(KEY + "-sent", []));
|
||||
let ALL = [], DATA = [], batch = "";
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
const url = s => /^https?:\/\//i.test(s || "") ? esc(s) : "";
|
||||
// YC's industry field is "Top -> Sub" (or just "Top"); the filter only needs the top level.
|
||||
const industryTop = s => String(s || "").split("->")[0].trim();
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const say = (id, msg, err) => { $(id).textContent = msg; $(id).classList.toggle("err", !!err) };
|
||||
|
||||
@ -245,15 +138,12 @@ async function api(params) {
|
||||
return j;
|
||||
}
|
||||
|
||||
// Best email for a founder: verified > unverified (Apify) > on the company site > pattern guess.
|
||||
// Every source now carries a numeric confidence (%) so the UI can show one badge format throughout.
|
||||
// Best email for a founder: verified > unverified (Apify) > on the company site > pattern guess
|
||||
function best(f) {
|
||||
if (f.apify_email) return f.apify_status === "valid"
|
||||
? { email: f.apify_email, kind: "valid", label: "verified", confidence: 99 }
|
||||
: { email: f.apify_email, kind: "unknown", label: "unverified", confidence: 60 };
|
||||
if (f.emails_found?.length) return { email: f.emails_found[0], kind: "site", label: "on site", confidence: 97 };
|
||||
if (f.email_guesses?.length) { const g = f.email_guesses[0]; return { email: g.email, kind: "guess", label: "guess", confidence: g.confidence, pattern: g.pattern }; }
|
||||
return { email: "", kind: "none", label: "no email", confidence: 0 };
|
||||
if (f.apify_email) return { email: f.apify_email, kind: f.apify_status === "valid" ? "valid" : "unknown", label: f.apify_status === "valid" ? "verified" : "unverified" };
|
||||
if (f.emails_found?.length) return { email: f.emails_found[0], kind: "site", label: "on site" };
|
||||
if (f.email_guesses?.length) return { email: f.email_guesses[0], kind: "guess", label: "guess" };
|
||||
return { email: "", kind: "none", label: "no email" };
|
||||
}
|
||||
const RANK = { valid: 0, unknown: 1, site: 2, guess: 3, none: 4 };
|
||||
// Primary contact: best email first, then CEO
|
||||
@ -261,21 +151,12 @@ function contacts(c) {
|
||||
return [...(c.founders || [])].sort((a, b) => (RANK[best(a).kind] - RANK[best(b).kind]) || (!/ceo/i.test(a.title) - !/ceo/i.test(b.title)));
|
||||
}
|
||||
|
||||
// Which open role a company's draft targets. Defaults to the first/only role; sticky per-slug once picked.
|
||||
function selectedJob(c) {
|
||||
if (!c.jobs?.length) return null;
|
||||
const i = jobSel[c.slug] || 0;
|
||||
return c.jobs[Math.min(i, c.jobs.length - 1)];
|
||||
}
|
||||
|
||||
function fill(text, c, stageRec) {
|
||||
function fill(text, c) {
|
||||
const f = contacts(c)[0] || { name: "" };
|
||||
const job = selectedJob(c);
|
||||
const vars = { first_name: f.name.split(" ")[0] || "there", company: c.name, one_liner: (c.one_liner || "what you're building").replace(/\.$/, "").toLowerCase(),
|
||||
batch: c.batch, job_title: job?.title || "", job_url: job?.url || "",
|
||||
my_name: tpl.my_name, portfolio: tpl.portfolio, github: tpl.github, resume: tpl.resume };
|
||||
batch: c.batch, my_name: tpl.my_name, portfolio: tpl.portfolio, github: tpl.github, resume: tpl.resume };
|
||||
const out = text.replace(/\{(\w+)\}/g, (m, k) => k in vars ? vars[k] : m);
|
||||
return out.split("\n").filter(l => !/^\s*[\w ]+:\s*$/.test(l)).join("\n").replace(/\s*\(\s*role:\s*\)/gi, "").trim();
|
||||
return out.split("\n").filter(l => !/^\s*[\w ]+:\s*$/.test(l)).join("\n");
|
||||
}
|
||||
|
||||
function rolesLine(c) {
|
||||
@ -283,87 +164,34 @@ function rolesLine(c) {
|
||||
const word = c.job_count === 1 ? "open role" : "open roles";
|
||||
return `<br><span class="roles">${c.job_count} ${word}</span>`;
|
||||
}
|
||||
function jobPicker(c) {
|
||||
if (!c.jobs?.length) return "";
|
||||
if (c.jobs.length === 1) return "";
|
||||
const i = jobSel[c.slug] || 0;
|
||||
return `<div class="jobsel"><label>Draft targets role: <select data-a="jobpick" style="width:auto;display:inline-block">
|
||||
${c.jobs.map((j, idx) => `<option value="${idx}" ${idx === i ? "selected" : ""}>${esc(j.title)}</option>`).join("")}
|
||||
</select></label></div>`;
|
||||
}
|
||||
function jobsRow(c) {
|
||||
if (c.job_count == null) return "";
|
||||
if (!c.job_count) return `<div class="r"><b>Jobs</b>No open roles on YC</div>`;
|
||||
const rows = (c.jobs || []).map(j => {
|
||||
const cached = j.url && jobCache[j.url];
|
||||
const openLink = j.url ? ` <a class="lnk" href="${url(j.url)}" target="_blank" rel="noopener">↗</a>` : "";
|
||||
const title = j.url
|
||||
? `<button class="lnk" type="button" data-a="viewjob" data-u="${esc(j.url)}" style="border:none;background:none;padding:0;text-decoration:underline;cursor:pointer;font:inherit">${esc(j.title)}</button>`
|
||||
: esc(j.title);
|
||||
const descHtml = cached ? `<p class="one" style="margin:4px 0 10px">${esc(cached.description.slice(0, 500))}${cached.description.length > 500 ? "…" : ""}${cached.location ? ` · ${esc(cached.location)}` : ""}${cached.salary_range ? ` · ${esc(cached.salary_range)}` : ""}</p>` : "";
|
||||
return `<div class="one">${title}${openLink}</div>${descHtml}`;
|
||||
}).join("");
|
||||
return `<div class="r"><b>Jobs</b>${c.job_count} open on YC</div>${rows}${jobPicker(c)}`;
|
||||
}
|
||||
|
||||
// Fit score: overlap between the user's skills/stack and (a) a company's open-role titles, plus any
|
||||
// full job descriptions fetched via "view job" (item 2/13) — the strong signal, full weight — and
|
||||
// (b) the company's one-liner/industry — a weaker fallback signal, so companies with zero open roles
|
||||
// (the majority of any batch in practice) still rank instead of all tying at "no score" and sitting in
|
||||
// whatever order they loaded. Returns {score, roleBased} so the UI can label a description-only match
|
||||
// differently from a real open-role match, or null when there's nothing to score against at all.
|
||||
function tokenize(s) { return new Set(String(s || "").toLowerCase().match(/[a-z0-9+.#]+/g) || []); }
|
||||
const ABOUT_WEIGHT = 0.4; // one-liner/industry match counts for less than an actual open-role match
|
||||
function fitScore(c) {
|
||||
const skills = tokenize(tpl.skills);
|
||||
if (!skills.size) return null;
|
||||
const extra = (c.jobs || []).map(j => jobCache[j.url]?.description || "").join(" ");
|
||||
const jobText = tokenize((c.jobs || []).map(j => j.title).join(" ") + " " + extra);
|
||||
const aboutText = tokenize((c.one_liner || "") + " " + (c.industry || ""));
|
||||
if (!jobText.size && !aboutText.size) return null;
|
||||
let hit = 0;
|
||||
skills.forEach(s => { if (jobText.has(s)) hit += 1; else if (aboutText.has(s)) hit += ABOUT_WEIGHT; });
|
||||
return { score: Math.round(100 * hit / skills.size), roleBased: jobText.size > 0 };
|
||||
}
|
||||
|
||||
function guessAlts(e, o) {
|
||||
if (e.kind !== "guess" || !o.email_guesses || o.email_guesses.length < 2) return "";
|
||||
const others = o.email_guesses.slice(1).map(g => `${esc(g.email)} (${g.confidence}%)`).join(", ");
|
||||
return ` <span class="alt" data-a="togglealt">other guesses</span><div class="altlist">${others}</div>`;
|
||||
const links = (c.jobs || []).map(j => j.url
|
||||
? `<a class="lnk" href="${url(j.url)}" target="_blank" rel="noopener">${esc(j.title)}</a>`
|
||||
: esc(j.title)).join(" · ");
|
||||
return `<div class="r"><b>Jobs</b>${c.job_count} open on YC${links ? ` · ${links}` : ""}</div>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
$("list").innerHTML = DATA.map((c, i) => {
|
||||
const fs = contacts(c), f = fs[0], b = f ? best(f) : { kind: c.founders ? "none" : "", label: c.error ? "error" : c.founders ? "no email" : "loading…" };
|
||||
const stage = stageOf(c.slug), due = isDue(c.slug);
|
||||
const fit = fitScore(c);
|
||||
// Searchable text: company/founder names plus what's already fetched but otherwise hidden behind a
|
||||
// click — the one-liner and open-role titles — so "founding engineer" or "fintech" filters the batch
|
||||
// without expanding every company by hand.
|
||||
const key = (c.name + " " + fs.map(o => o.name).join(" ") + " " + (c.one_liner || "") + " " + (c.jobs || []).map(j => j.title).join(" ")).toLowerCase();
|
||||
return `<details data-i="${i}" data-k="${esc(key)}" data-s="${b.kind}" data-ind="${esc(industryTop(c.industry))}" data-jobs="${c.job_count == null ? "" : c.job_count}" data-stage="${stage}" data-due="${due ? "1" : ""}" class="${stage !== "not_sent" ? "sent" : ""} stage-${stage}">
|
||||
<summary><span class="name">${esc(c.name)}</span><span class="badge ${b.kind || "none"}">${esc(b.label)}${b.confidence ? ` ${b.confidence}%` : ""}</span>
|
||||
<span class="meta">${esc(f?.name || "")}<br>${esc(c.batch)}${rolesLine(c)}${fit != null ? `<br><span class="fit" title="${fit.roleBased ? "matches skills against this company's open-role titles/descriptions" : "no open roles yet — estimated from the company's one-liner/industry instead"}">${fit.score}% fit${fit.roleBased ? "" : "*"}</span>` : ""}${due ? `<br><span class="due">follow-up due</span>` : ""}</span></summary>
|
||||
const key = (c.name + " " + fs.map(o => o.name).join(" ")).toLowerCase();
|
||||
return `<details data-i="${i}" data-k="${esc(key)}" data-s="${b.kind}" data-jobs="${c.job_count == null ? "" : c.job_count}" class="${sent.has(c.slug) ? "sent" : ""}">
|
||||
<summary><span class="name">${esc(c.name)}</span><span class="badge ${b.kind || "none"}">${esc(b.label)}</span>
|
||||
<span class="meta">${esc(f?.name || "")}<br>${esc(c.batch)}${rolesLine(c)}</span></summary>
|
||||
<div class="body">
|
||||
<p class="one">${esc(c.one_liner)}${c.industry ? ` · <span class="lnk">${esc(c.industry)}</span>` : ""}${url(c.website) ? ` · <a class="lnk" href="${url(c.website)}" target="_blank" rel="noopener">website</a>` : ""} · <a class="lnk" href="https://www.ycombinator.com/companies/${esc(c.slug)}" target="_blank" rel="noopener">YC</a>${url(f?.linkedin) ? ` · <a class="lnk" href="${url(f.linkedin)}" target="_blank" rel="noopener">LinkedIn</a>` : ""}${url(f?.twitter) ? ` · <a class="lnk" href="${url(f.twitter)}" target="_blank" rel="noopener">X</a>` : ""}</p>
|
||||
<p class="one">${esc(c.one_liner)}${url(c.website) ? ` · <a class="lnk" href="${url(c.website)}" target="_blank" rel="noopener">website</a>` : ""} · <a class="lnk" href="https://www.ycombinator.com/companies/${esc(c.slug)}" target="_blank" rel="noopener">YC</a>${url(f?.linkedin) ? ` · <a class="lnk" href="${url(f.linkedin)}" target="_blank" rel="noopener">LinkedIn</a>` : ""}${url(f?.twitter) ? ` · <a class="lnk" href="${url(f.twitter)}" target="_blank" rel="noopener">X</a>` : ""}</p>
|
||||
${c.error ? `<p class="status err">${esc(c.error)}</p>` : ""}
|
||||
${jobsRow(c)}
|
||||
${fs.map(o => { const e = best(o); return `<div class="r"><b>${o === f ? "To" : "Also"}</b>${esc(o.name)}${o.title ? ` (${esc(o.title)})` : ""} · ${esc(e.email || "no email")} <span class="badge ${e.kind}">${e.label}${e.confidence ? ` ${e.confidence}%` : ""}</span>${guessAlts(e, o)}</div>` }).join("")}
|
||||
${fs.map(o => { const e = best(o); return `<div class="r"><b>${o === f ? "To" : "Also"}</b>${esc(o.name)}${o.title ? ` (${esc(o.title)})` : ""} · ${esc(e.email || "no email")} <span class="badge ${e.kind}">${e.label}</span></div>` }).join("")}
|
||||
<div class="r"><b>Subject</b><span class="subj"></span></div>
|
||||
<pre></pre>
|
||||
<div class="acts">
|
||||
<button class="primary" data-a="send" type="button" hidden>➤ Send</button>
|
||||
<button class="primary" data-a="body" type="button">Copy body</button><button data-a="to" type="button">Copy email</button><button data-a="subject" type="button">Copy subject</button>
|
||||
<a class="btn mail" href="#">Open in mail app</a>
|
||||
<select class="stageSel" data-a="stage">${STAGES.map(s => `<option value="${s}" ${s === stage ? "selected" : ""}>${STAGE_LABEL[s]}</option>`).join("")}</select>
|
||||
<label class="chk"><input type="checkbox" data-a="sent" ${sent.has(c.slug) ? "checked" : ""}> sent</label>
|
||||
</div>
|
||||
${stage === "sent" || stage === "followed_up" ? `
|
||||
<div class="r" style="margin-top:14px;border-top:1px dashed var(--line);padding-top:10px"><b>Follow-up</b><span class="fsubj"></span></div>
|
||||
<pre class="fpre"></pre>
|
||||
<div class="acts">
|
||||
<button class="primary" data-a="fsend" type="button" hidden>➤ Send follow-up</button>
|
||||
<button data-a="fbody" type="button">Copy follow-up</button>
|
||||
</div>` : ""}
|
||||
</div></details>`;
|
||||
}).join("");
|
||||
update();
|
||||
@ -376,45 +204,21 @@ function draft(d) {
|
||||
d.querySelector(".subj").textContent = subject;
|
||||
d.querySelector("pre").textContent = body;
|
||||
d.querySelector(".mail").href = `mailto:${encodeURIComponent(to ? best(to).email : "")}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
|
||||
const sendBtn = d.querySelector('[data-a="send"]'), copyBtn = d.querySelector('[data-a="body"]');
|
||||
const connected = !!gmailToken;
|
||||
sendBtn.hidden = !connected; copyBtn.hidden = connected;
|
||||
const fsubj = d.querySelector(".fsubj"), fpre = d.querySelector(".fpre");
|
||||
if (fsubj && fpre) {
|
||||
const fSubject = fill(tpl.followup_subject, c), fBody = fill(tpl.followup_body, c);
|
||||
fsubj.textContent = fSubject; fpre.textContent = fBody;
|
||||
const fSend = d.querySelector('[data-a="fsend"]'), fCopy = d.querySelector('[data-a="fbody"]');
|
||||
if (fSend) fSend.hidden = !connected;
|
||||
if (fCopy) fCopy.hidden = connected;
|
||||
}
|
||||
}
|
||||
function update() { document.querySelectorAll("details[open]").forEach(draft) }
|
||||
|
||||
function filter() {
|
||||
const q = $("q").value.trim().toLowerCase(), st = $("st").value, hide = $("hideSent").checked, hiring = $("hiring").checked, ind = $("ind").value, stageF = $("stageFilter").value;
|
||||
const q = $("q").value.trim().toLowerCase(), st = $("st").value, hide = $("hideSent").checked, hiring = $("hiring").checked;
|
||||
let n = 0;
|
||||
document.querySelectorAll("#list details").forEach(d => {
|
||||
const stageOk = !stageF || (stageF === "due" ? d.dataset.due === "1" : d.dataset.stage === stageF);
|
||||
document.querySelectorAll("details").forEach(d => {
|
||||
const ok = (!q || d.dataset.k.includes(q)) && (!st || d.dataset.s === st) && !(hide && d.classList.contains("sent"))
|
||||
&& (!hiring || +d.dataset.jobs > 0) && (!ind || d.dataset.ind === ind) && stageOk;
|
||||
&& (!hiring || +d.dataset.jobs > 0);
|
||||
d.style.display = ok ? "" : "none"; n += ok;
|
||||
});
|
||||
const contactedCount = DATA.filter(c => stageOf(c.slug) !== "not_sent").length;
|
||||
const dueCount = DATA.filter(c => isDue(c.slug)).length;
|
||||
$("shown").textContent = DATA.length ? `${n} of ${DATA.length} shown · ${contactedCount} contacted${dueCount ? ` · ${dueCount} follow-up due` : ""}` : "";
|
||||
$("shown").textContent = DATA.length ? `${n} of ${DATA.length} shown · ${sent.size} sent` : "";
|
||||
}
|
||||
|
||||
// Populate the industry dropdown from the companies actually in this batch, so the
|
||||
// list only ever offers choices that can return a result. Keeps the current
|
||||
// selection if it still exists in the new batch, otherwise resets to "All industries".
|
||||
function populateIndustries() {
|
||||
const prev = $("ind").value;
|
||||
const industries = [...new Set(ALL.map(c => industryTop(c.industry)).filter(Boolean))].sort();
|
||||
$("ind").innerHTML = `<option value="">All industries</option>` + industries.map(i => `<option value="${esc(i)}">${esc(i)}</option>`).join("");
|
||||
if (industries.includes(prev)) $("ind").value = prev;
|
||||
}
|
||||
|
||||
// ALL = every company in the selected batch(es); DATA = the ones whose founders are loaded (what the list shows)
|
||||
// ALL = every company in the batch; DATA = the ones whose founders are loaded (what the list shows)
|
||||
const PAGE = 20;
|
||||
const save = () => store.set(`${KEY}-batch-${batch}`, ALL);
|
||||
const busy = on => { $("load").disabled = $("more").disabled = on; $("enrich").disabled = on || !DATA.length };
|
||||
@ -429,23 +233,21 @@ function progress() {
|
||||
}
|
||||
|
||||
async function loadBatch() {
|
||||
const selected = [...$("batch").selectedOptions].map(o => o.value).filter(Boolean);
|
||||
if (!selected.length) return;
|
||||
batch = selected.slice().sort().join(",");
|
||||
batch = $("batch").value;
|
||||
if (!batch) return;
|
||||
busy(true);
|
||||
ALL = store.get(`${KEY}-batch-${batch}`, null) || [];
|
||||
try {
|
||||
if (!ALL.length) {
|
||||
say("loadStatus", selected.length > 1 ? `Loading ${selected.length} batches…` : "Loading companies…");
|
||||
say("loadStatus", "Loading companies…");
|
||||
ALL = (await api({ action: "companies", batch })).sort((a, b) => b.launched_at - a.launched_at);
|
||||
save();
|
||||
}
|
||||
} catch (e) {
|
||||
busy(false);
|
||||
return say("loadStatus", `Couldn't load ${selected.length > 1 ? "these batches" : "this batch"}: ${e.message}`, true);
|
||||
return say("loadStatus", `Couldn't load this batch: ${e.message}`, true);
|
||||
}
|
||||
DATA = ALL.filter(c => c.founders || c.error);
|
||||
populateIndustries();
|
||||
render();
|
||||
// Fetch on open only for an empty batch, or to fill job counts missing from an older cache
|
||||
const stale = ALL.some(c => c.founders && c.job_count == null && !c.error);
|
||||
@ -465,14 +267,6 @@ function mergeCompany(target, fresh) {
|
||||
}
|
||||
}
|
||||
|
||||
// New-batch/new-role watcher's baseline: a company freshly loaded already has its true job_count, so
|
||||
// record it immediately instead of letting the periodic digest treat it as a "new" role later.
|
||||
function noteJobBaseline(companies) {
|
||||
const base = store.get(KEY + "-lastjobs", {});
|
||||
companies.forEach(c => { if (c.job_count != null) base[c.slug] = c.job_count; });
|
||||
store.set(KEY + "-lastjobs", base);
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
const next = ALL.filter(needsFetch).slice(0, PAGE);
|
||||
if (!next.length) return progress();
|
||||
@ -484,7 +278,6 @@ async function loadMore() {
|
||||
try {
|
||||
const res = await api({ action: "founders", slugs: chunk.map(c => c.slug).join(",") });
|
||||
res.forEach((r, j) => mergeCompany(chunk[j], r));
|
||||
noteJobBaseline(chunk);
|
||||
} catch (e) { chunk.forEach(c => c.error = `Couldn't load founders: ${e.message}`) }
|
||||
DATA = ALL.filter(c => c.founders || c.error);
|
||||
render();
|
||||
@ -538,239 +331,36 @@ async function enrich() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Gmail direct-send (OAuth2 via Google Identity Services, gmail.send scope only) ----
|
||||
// The token never touches this site's server: it lives only in this tab's memory + sessionStorage,
|
||||
// and every API call below goes straight from the browser to googleapis.com.
|
||||
let gmailToken = sessionStorage.getItem(KEY + "-gmailtoken") || "";
|
||||
let gmailTokenExpiry = +sessionStorage.getItem(KEY + "-gmailexpiry") || 0;
|
||||
let tokenClient = null;
|
||||
function gmailConnected() { return !!gmailToken && Date.now() < gmailTokenExpiry; }
|
||||
|
||||
function initGis() {
|
||||
if (GOOGLE_CLIENT_ID.startsWith("REPLACE_WITH")) return false;
|
||||
if (typeof google === "undefined" || !google.accounts?.oauth2) return false;
|
||||
if (!tokenClient) {
|
||||
tokenClient = google.accounts.oauth2.initTokenClient({
|
||||
client_id: GOOGLE_CLIENT_ID,
|
||||
scope: GMAIL_SCOPE,
|
||||
callback: (resp) => {
|
||||
if (resp.error) return say("gmailStatus", `Connect failed: ${resp.error}`, true);
|
||||
gmailToken = resp.access_token;
|
||||
gmailTokenExpiry = Date.now() + ((resp.expires_in || 3600) * 1000) - 30000;
|
||||
sessionStorage.setItem(KEY + "-gmailtoken", gmailToken);
|
||||
sessionStorage.setItem(KEY + "-gmailexpiry", String(gmailTokenExpiry));
|
||||
setGmailUi(true);
|
||||
say("gmailStatus", "Connected. Drafts now show a Send button instead of Copy.");
|
||||
update(); render(); startQueueWorker();
|
||||
}
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function setGmailUi(on) {
|
||||
$("gmailDot").classList.toggle("on", on);
|
||||
$("gmailState").textContent = on ? "Connected" : "Not connected";
|
||||
$("gmailConnect").hidden = on; $("gmailDisconnect").hidden = !on; $("queuePanel").hidden = !on;
|
||||
$("gmailPanel").classList.toggle("connected", on);
|
||||
}
|
||||
$("gmailConnect").onclick = () => {
|
||||
if (!initGis()) return say("gmailStatus", GOOGLE_CLIENT_ID.startsWith("REPLACE_WITH")
|
||||
? "This deployment hasn't configured a Google OAuth client ID yet (owner/operator step in Google Cloud Console — zero cost). Copy and mailto below still work."
|
||||
: "Google's sign-in script hasn't finished loading — try again in a second.", true);
|
||||
tokenClient.requestAccessToken();
|
||||
};
|
||||
$("gmailDisconnect").onclick = () => {
|
||||
if (gmailToken && google?.accounts?.oauth2?.revoke) { try { google.accounts.oauth2.revoke(gmailToken, () => {}) } catch {} }
|
||||
gmailToken = ""; gmailTokenExpiry = 0;
|
||||
sessionStorage.removeItem(KEY + "-gmailtoken"); sessionStorage.removeItem(KEY + "-gmailexpiry");
|
||||
setGmailUi(false); stopQueueWorker(); say("gmailStatus", "Disconnected."); update(); render();
|
||||
};
|
||||
|
||||
function b64urlFromString(str) { return btoa(unescape(encodeURIComponent(str))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); }
|
||||
function mimeEncodeHeader(s) { return /[^\x00-\x7F]/.test(s) ? `=?UTF-8?B?${btoa(unescape(encodeURIComponent(s)))}?=` : s; }
|
||||
async function gmailSendMessage(to, subject, body) {
|
||||
if (!gmailConnected()) throw new Error("Gmail isn't connected");
|
||||
const raw = b64urlFromString([
|
||||
`To: ${to}`, `Subject: ${mimeEncodeHeader(subject)}`, "MIME-Version: 1.0",
|
||||
'Content-Type: text/plain; charset="UTF-8"', "Content-Transfer-Encoding: base64", "",
|
||||
btoa(unescape(encodeURIComponent(body))).replace(/(.{76})/g, "$1\n"),
|
||||
].join("\r\n"));
|
||||
const r = await fetch(`${GMAIL}/users/me/messages/send`, {
|
||||
method: "POST", headers: { Authorization: `Bearer ${gmailToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ raw }),
|
||||
});
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(j.error?.message || `Gmail HTTP ${r.status}`);
|
||||
return j;
|
||||
}
|
||||
|
||||
// ---- Send queue: persisted, rate-limited (20-60s random delay) and capped per day ----
|
||||
let queue = store.get(KEY + "-queue", []); // [{slug, kind: "main"|"followup", to, subject, body, queuedAt}]
|
||||
let queuePaused = store.get(KEY + "-queue-paused", false);
|
||||
let queueTimer = null, nextSendAt = 0;
|
||||
function sendLog() { return store.get(KEY + "-sendlog", []); }
|
||||
function sentInLast24h() { const cutoff = Date.now() - 86400000; return sendLog().filter(t => t > cutoff).length; }
|
||||
function logSend() { store.set(KEY + "-sendlog", [...sendLog(), Date.now()].filter(t => t > Date.now() - 86400000)); }
|
||||
function stopQueueWorker() { if (queueTimer) { clearTimeout(queueTimer); queueTimer = null } }
|
||||
|
||||
function enqueueSend(c, kind) {
|
||||
const to = contacts(c)[0];
|
||||
const email = to ? best(to).email : "";
|
||||
if (!email) return say("gmailStatus", `No email on file for ${c.name} yet.`, true);
|
||||
if (queue.some(q => q.slug === c.slug && q.kind === kind)) return say("gmailStatus", `${c.name} is already queued.`);
|
||||
const subject = kind === "followup" ? fill(tpl.followup_subject, c) : fill(tpl.subject, c);
|
||||
const body = kind === "followup" ? fill(tpl.followup_body, c) : fill(tpl.body, c);
|
||||
queue.push({ slug: c.slug, kind, to: email, subject, body, queuedAt: Date.now() });
|
||||
store.set(KEY + "-queue", queue);
|
||||
say("gmailStatus", `Queued ${c.name} (${kind === "followup" ? "follow-up" : "first email"}). ${queue.length} pending.`);
|
||||
renderQueue(); startQueueWorker();
|
||||
}
|
||||
|
||||
function renderQueue() {
|
||||
if ($("qPending")) $("qPending").textContent = queue.length;
|
||||
if ($("qSentToday")) $("qSentToday").textContent = sentInLast24h();
|
||||
if ($("qCapLabel")) $("qCapLabel").textContent = $("dailyCap").value || 30;
|
||||
if ($("qNext")) $("qNext").textContent = queuePaused ? "Paused"
|
||||
: nextSendAt > Date.now() ? `Next send in ${Math.ceil((nextSendAt - Date.now()) / 1000)}s`
|
||||
: queue.length ? "Sending…" : "";
|
||||
}
|
||||
setInterval(renderQueue, 1000);
|
||||
|
||||
function startQueueWorker() {
|
||||
if (queueTimer || queuePaused || !gmailConnected() || !queue.length) return;
|
||||
const cap = +$("dailyCap").value || 30;
|
||||
if (sentInLast24h() >= cap) {
|
||||
say("gmailStatus", `Daily cap of ${cap} reached — the queue resumes automatically as the 24h window rolls forward.`);
|
||||
queueTimer = setTimeout(() => { queueTimer = null; startQueueWorker(); }, 5 * 60000);
|
||||
return;
|
||||
}
|
||||
const delay = 20000 + Math.random() * 40000; // randomized 20-60s between sends, "be decent"
|
||||
nextSendAt = Date.now() + delay;
|
||||
queueTimer = setTimeout(async () => {
|
||||
queueTimer = null;
|
||||
const item = queue[0];
|
||||
if (!item) return;
|
||||
try {
|
||||
await gmailSendMessage(item.to, item.subject, item.body);
|
||||
logSend();
|
||||
queue.shift(); store.set(KEY + "-queue", queue);
|
||||
setStage(item.slug, item.kind === "followup" ? "followed_up" : "sent");
|
||||
say("gmailStatus", `Sent to ${item.to}. ${queue.length} left in queue.`);
|
||||
render();
|
||||
} catch (e) {
|
||||
say("gmailStatus", `Send failed for ${item.to}: ${e.message}. Left in queue — will retry.`, true);
|
||||
}
|
||||
startQueueWorker();
|
||||
}, delay);
|
||||
}
|
||||
$("qToggle").onclick = () => {
|
||||
queuePaused = !queuePaused; store.set(KEY + "-queue-paused", queuePaused);
|
||||
$("qToggle").textContent = queuePaused ? "Resume" : "Pause";
|
||||
if (queuePaused) stopQueueWorker(); else startQueueWorker();
|
||||
renderQueue();
|
||||
};
|
||||
$("qClear").onclick = () => {
|
||||
if (!queue.length || !confirm(`Clear ${queue.length} queued send(s)?`)) return;
|
||||
queue = []; store.set(KEY + "-queue", queue); stopQueueWorker(); renderQueue();
|
||||
};
|
||||
|
||||
// ---- New-batch / new-role watcher: cheap periodic /api/yc?action=digest round-trip, client-side only ----
|
||||
function notify(title, body) {
|
||||
say("watchStatus", `${title}: ${body}`);
|
||||
if (typeof Notification !== "undefined" && Notification.permission === "granted") {
|
||||
try { new Notification(title, { body }) } catch {}
|
||||
}
|
||||
}
|
||||
function noteBaselineBatches(bs) {
|
||||
const primed = store.get(KEY + "-watch-primed", false);
|
||||
const prior = store.get(KEY + "-lastbatches", {});
|
||||
if (primed) {
|
||||
const changed = bs.filter(b => b.batch !== "Unspecified" && prior[b.batch] !== b.count);
|
||||
if (changed.length) notify(`New YC batch${changed.length > 1 ? "es" : ""}`, changed.map(b => `${b.batch} (${b.count} companies)`).join(", "));
|
||||
}
|
||||
store.set(KEY + "-lastbatches", Object.fromEntries(bs.map(b => [b.batch, b.count])));
|
||||
store.set(KEY + "-watch-primed", true);
|
||||
}
|
||||
const WATCH_INTERVAL = 5 * 60000;
|
||||
let watchTimer = null;
|
||||
function startWatch() {
|
||||
if (watchTimer) return;
|
||||
watchTimer = setInterval(() => { if (document.visibilityState === "visible") checkDigest() }, WATCH_INTERVAL);
|
||||
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") checkDigest() });
|
||||
}
|
||||
async function checkDigest() {
|
||||
const slugs = DATA.filter(c => !c.error && c.slug).map(c => c.slug).slice(0, 40);
|
||||
const knownJobs = store.get(KEY + "-lastjobs", {});
|
||||
const knownBatches = store.get(KEY + "-lastbatches", {});
|
||||
try {
|
||||
const d = await api({ action: "digest", known_batches: JSON.stringify(knownBatches), slugs: slugs.join(","), known_jobs: JSON.stringify(knownJobs) });
|
||||
noteBaselineBatches(d.batches);
|
||||
if (d.changed_jobs?.length) {
|
||||
const msgs = d.changed_jobs.map(j => { const c = DATA.find(x => x.slug === j.slug); return `${c ? c.name : j.slug}: ${j.job_count} open role${j.job_count === 1 ? "" : "s"}` });
|
||||
notify(`New YC role${msgs.length > 1 ? "s" : ""}`, msgs.join(" · "));
|
||||
}
|
||||
store.set(KEY + "-lastjobs", { ...knownJobs, ...d.job_counts });
|
||||
} catch { /* background watcher: fail quietly, next tick retries */ }
|
||||
}
|
||||
$("notifyBtn").onclick = async () => {
|
||||
if (typeof Notification === "undefined") return say("watchStatus", "Notifications aren't supported in this browser.", true);
|
||||
const perm = await Notification.requestPermission();
|
||||
say("watchStatus", perm === "granted" ? "Alerts on: new batches and new roles will notify you while this tab is open." : "Notifications blocked by the browser — alerts still show in this status line.");
|
||||
};
|
||||
|
||||
$("list").addEventListener("toggle", e => { if (e.target.open) draft(e.target) }, true);
|
||||
$("list").addEventListener("change", e => {
|
||||
const stageSel = e.target.closest('[data-a="stage"]');
|
||||
if (stageSel) { const d = stageSel.closest("details"), c = DATA[d.dataset.i]; setStage(c.slug, stageSel.value); render(); return; }
|
||||
const jobSelEl = e.target.closest('[data-a="jobpick"]');
|
||||
if (jobSelEl) { const d = jobSelEl.closest("details"), c = DATA[d.dataset.i]; jobSel[c.slug] = +jobSelEl.value; store.set(KEY + "-jobsel", jobSel); update(); }
|
||||
});
|
||||
$("list").addEventListener("click", e => {
|
||||
const b = e.target.closest("[data-a]"); if (!b) return;
|
||||
const action = b.dataset.a;
|
||||
if (action === "stage" || action === "jobpick") return; // selects: handled by the change listener above
|
||||
const d = b.closest("details"), c = DATA[d.dataset.i];
|
||||
if (action === "send") return enqueueSend(c, "main");
|
||||
if (action === "fsend") return enqueueSend(c, "followup");
|
||||
if (action === "togglealt") return b.nextElementSibling?.classList.toggle("show");
|
||||
if (action === "viewjob") {
|
||||
const u = b.dataset.u, old = b.textContent;
|
||||
b.textContent = "Loading\u2026";
|
||||
return api({ action: "job", url: u }).then(detail => { jobCache[u] = detail; store.set(KEY + "-jobcache", jobCache); render() })
|
||||
.catch(err => { b.textContent = old; say("gmailStatus", `Couldn't load that job posting: ${err.message}`, true) });
|
||||
if (b.dataset.a === "sent") {
|
||||
b.checked ? sent.add(c.slug) : sent.delete(c.slug);
|
||||
d.classList.toggle("sent", b.checked); store.set(KEY + "-sent", [...sent]); filter(); return;
|
||||
}
|
||||
const to = contacts(c)[0];
|
||||
const txt = action === "body" ? d.querySelector("pre").textContent
|
||||
: action === "fbody" ? d.querySelector(".fpre")?.textContent
|
||||
: action === "subject" ? d.querySelector(".subj").textContent
|
||||
: action === "to" && to ? best(to).email : "";
|
||||
navigator.clipboard.writeText(txt || "").then(() => { const o = b.textContent; b.textContent = "Copied"; setTimeout(() => b.textContent = o, 1200) });
|
||||
const txt = b.dataset.a === "body" ? d.querySelector("pre").textContent : b.dataset.a === "subject" ? d.querySelector(".subj").textContent : to ? best(to).email : "";
|
||||
navigator.clipboard.writeText(txt).then(() => { const o = b.textContent; b.textContent = "Copied"; setTimeout(() => b.textContent = o, 1200) });
|
||||
});
|
||||
["q", "st", "ind", "hideSent", "hiring", "stageFilter"].forEach(id => $(id).addEventListener(id === "q" ? "input" : "change", filter));
|
||||
["q", "st", "hideSent", "hiring"].forEach(id => $(id).addEventListener(id === "q" ? "input" : "change", filter));
|
||||
$("all").onclick = e => {
|
||||
const open = e.target.textContent === "Expand all";
|
||||
document.querySelectorAll("#list details").forEach(d => { if (d.style.display !== "none") d.open = open });
|
||||
document.querySelectorAll("details").forEach(d => { if (d.style.display !== "none") d.open = open });
|
||||
e.target.textContent = open ? "Collapse all" : "Expand all";
|
||||
};
|
||||
$("fitSort").onclick = () => {
|
||||
sortMode = sortMode === "fit" ? "default" : "fit";
|
||||
DATA.sort(sortMode === "fit" ? (a, b) => (fitScore(b)?.score ?? -1) - (fitScore(a)?.score ?? -1) : (a, b) => (b.launched_at || 0) - (a.launched_at || 0));
|
||||
$("fitSort").textContent = sortMode === "fit" ? "Default order" : "Best fit first";
|
||||
render();
|
||||
};
|
||||
$("exportCsv").onclick = () => {
|
||||
const visibleIndices = Array.from(document.querySelectorAll("#list details"))
|
||||
const visibleIndices = Array.from(document.querySelectorAll("details"))
|
||||
.filter(d => d.style.display !== "none")
|
||||
.map(d => parseInt(d.dataset.i, 10));
|
||||
if (!visibleIndices.length) return alert("No data to export.");
|
||||
const headers = ["Company", "Batch", "Industry", "Founder Name", "Title", "Email", "Email Status", "Confidence %", "LinkedIn", "Twitter", "Jobs on YC", "Website", "Stage", "Sent At", "Follow-up Due", "Followed Up At", "Replied At"];
|
||||
const iso = t => t ? new Date(t).toISOString() : "";
|
||||
const headers = ["Company", "Batch", "Founder Name", "Title", "Email", "Email Status", "LinkedIn", "Twitter", "Jobs on YC", "Website"];
|
||||
const rows = visibleIndices.flatMap(i => {
|
||||
const c = DATA[i], fs = contacts(c), s = stages[c.slug] || {};
|
||||
const stageCols = [STAGE_LABEL[stageOf(c.slug)], iso(s.sentAt), iso(s.followupDueAt), iso(s.followedUpAt), iso(s.repliedAt)];
|
||||
if (!fs.length) return [[c.name, c.batch, c.industry || "", "", "", "", "", "", "", "", c.job_count || 0, c.website || "", ...stageCols]];
|
||||
const c = DATA[i], fs = contacts(c);
|
||||
if (!fs.length) return [[c.name, c.batch, "", "", "", "", "", "", c.job_count || 0, c.website || ""]];
|
||||
return fs.map(f => {
|
||||
const e = best(f);
|
||||
return [c.name, c.batch, c.industry || "", f.name, f.title || "", e.email || "", e.label || "", e.confidence || "", f.linkedin || "", f.twitter || "", c.job_count || 0, c.website || "", ...stageCols];
|
||||
const e = best(f);
|
||||
return [c.name, c.batch, f.name, f.title || "", e.email || "", e.label || "", f.linkedin || "", f.twitter || "", c.job_count || 0, c.website || ""];
|
||||
});
|
||||
});
|
||||
const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(",")).join("\r\n");
|
||||
@ -779,37 +369,13 @@ $("exportCsv").onclick = () => {
|
||||
link.download = `yc_outreach_${new Date().toISOString().slice(0,10)}.csv`;
|
||||
document.body.appendChild(link); link.click(); document.body.removeChild(link);
|
||||
};
|
||||
// Full session backup/restore: every localStorage key this app writes, prefixed with KEY, as one JSON
|
||||
// file \u2014 so clearing localStorage or moving to a new browser doesn't lose a user's whole pipeline.
|
||||
$("exportJson").onclick = () => {
|
||||
const dump = {};
|
||||
for (const k of Object.keys(localStorage)) if (k.startsWith(KEY)) dump[k] = localStorage.getItem(k);
|
||||
const blob = new Blob([JSON.stringify({ exportedAt: new Date().toISOString(), data: dump }, null, 2)], { type: "application/json" });
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = `yc_outreach_session_${new Date().toISOString().slice(0,10)}.json`;
|
||||
document.body.appendChild(link); link.click(); document.body.removeChild(link);
|
||||
};
|
||||
$("importJson").addEventListener("change", async e => {
|
||||
const file = e.target.files[0]; if (!file) return;
|
||||
try {
|
||||
const parsed = JSON.parse(await file.text());
|
||||
const data = parsed && typeof parsed === "object" ? (parsed.data || parsed) : null;
|
||||
const keys = data ? Object.keys(data).filter(k => k.startsWith(KEY)) : [];
|
||||
if (!keys.length) throw new Error("No recognisable yc-outreach data in that file");
|
||||
if (!confirm(`Import ${keys.length} saved item(s)? This replaces matching data in your current session \u2014 export first if unsure.`)) return;
|
||||
for (const k of keys) localStorage.setItem(k, data[k]);
|
||||
location.reload();
|
||||
} catch (err) { alert(`Couldn't import session: ${err.message}`); }
|
||||
finally { e.target.value = "" }
|
||||
});
|
||||
document.querySelectorAll("[data-k]").forEach(el => {
|
||||
if (!(el.dataset.k in tpl)) return;
|
||||
el.value = tpl[el.dataset.k];
|
||||
el.addEventListener("input", () => { tpl[el.dataset.k] = el.value; store.set(KEY, tpl); update(); });
|
||||
});
|
||||
let lastField = document.querySelector('textarea[data-k="body"]');
|
||||
document.querySelectorAll('input[data-k="subject"], textarea[data-k="body"], input[data-k="followup_subject"], textarea[data-k="followup_body"]').forEach(el => el.addEventListener("focus", () => lastField = el));
|
||||
document.querySelectorAll('input[data-k="subject"], textarea[data-k="body"]').forEach(el => el.addEventListener("focus", () => lastField = el));
|
||||
$("vars").addEventListener("click", e => {
|
||||
if (e.target.tagName !== "CODE") return;
|
||||
const el = lastField, s = el.selectionStart ?? el.value.length;
|
||||
@ -824,22 +390,12 @@ $("reset").onclick = () => {
|
||||
$("load").onclick = loadBatch;
|
||||
$("more").onclick = loadMore;
|
||||
$("enrich").onclick = enrich;
|
||||
$("batch").onchange = () => store.set(KEY + "-last", [...$("batch").selectedOptions].map(o => o.value));
|
||||
$("followupDays").value = store.get(KEY + "-followupdays", 5);
|
||||
$("followupDays").addEventListener("change", () => store.set(KEY + "-followupdays", +$("followupDays").value || 5));
|
||||
$("dailyCap").value = store.get(KEY + "-dailycap", 30);
|
||||
$("dailyCap").addEventListener("change", () => store.set(KEY + "-dailycap", +$("dailyCap").value || 30));
|
||||
$("qToggle").textContent = queuePaused ? "Resume" : "Pause";
|
||||
if (gmailConnected()) { setGmailUi(true); startQueueWorker() }
|
||||
renderQueue();
|
||||
$("batch").onchange = () => store.set(KEY + "-last", $("batch").value);
|
||||
|
||||
api({ action: "batches" }).then(bs => {
|
||||
const last = store.get(KEY + "-last", []);
|
||||
const lastArr = Array.isArray(last) ? last : (last ? [last] : []); // migrate the old single-select format
|
||||
const last = store.get(KEY + "-last", "");
|
||||
$("batch").innerHTML = bs.filter(b => b.batch !== "Unspecified")
|
||||
.map(b => `<option value="${esc(b.batch)}" ${lastArr.includes(b.batch) ? "selected" : ""}>${esc(b.batch)} (${b.count} companies)</option>`).join("");
|
||||
.map(b => `<option value="${esc(b.batch)}" ${b.batch === last ? "selected" : ""}>${esc(b.batch)} (${b.count} companies)</option>`).join("");
|
||||
$("load").disabled = false;
|
||||
noteBaselineBatches(bs);
|
||||
startWatch();
|
||||
}).catch(e => { $("batch").innerHTML = "<option value=''>Couldn't load batches</option>"; say("loadStatus", e.message, true) });
|
||||
</script></body></html>
|
||||
|
||||
@ -1,97 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests Cloudflare "email protection" decoding in both api/yc.py and yc_scraper.py.
|
||||
|
||||
Cloudflare's email obfuscation replaces a real mailto with "[email protected]" plus a
|
||||
data-cfemail="<hex>" attribute: byte 0 is an XOR key, every later byte is a masked character.
|
||||
Confirmed live on 2026-10-22 against 10/160 Fall 2026 YC company homepages (e.g. claimkit.co,
|
||||
herdr.dev) -- without decoding it, those real, site-published addresses were invisible to
|
||||
EMAIL_RE and the tool silently fell back to a lower-reliability pattern guess instead.
|
||||
|
||||
Stdlib only (unittest + unittest.mock), matching this repo's stdlib-only policy.
|
||||
Run: python3 tests/test_cf_email_decode.py
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent / "api"))
|
||||
|
||||
import yc # api/yc.py -- the live serverless handler
|
||||
import yc_scraper # the CLI, duplicates the same logic on purpose (see README)
|
||||
|
||||
|
||||
def cf_encode(email, key=0x2A):
|
||||
"""Inverse of Cloudflare's obfuscation, for building test fixtures."""
|
||||
return bytes([key] + [b ^ key for b in email.encode("ascii")]).hex()
|
||||
|
||||
|
||||
class CfDecodeTests(unittest.TestCase):
|
||||
"""Unit tests for the raw decode routine, run against both modules to catch drift between
|
||||
the two intentionally-duplicated implementations (api/yc.py vs yc_scraper.py)."""
|
||||
|
||||
def test_decodes_real_shaped_address_both_modules(self):
|
||||
hexstr = cf_encode("rachel@claimkit.co")
|
||||
self.assertEqual(yc.cf_decode(hexstr), "rachel@claimkit.co")
|
||||
self.assertEqual(yc_scraper.cf_decode(hexstr), "rachel@claimkit.co")
|
||||
|
||||
def test_different_xor_key(self):
|
||||
hexstr = cf_encode("hey@herdr.dev", key=0x7)
|
||||
self.assertEqual(yc.cf_decode(hexstr), "hey@herdr.dev")
|
||||
self.assertEqual(yc_scraper.cf_decode(hexstr), "hey@herdr.dev")
|
||||
|
||||
def test_malformed_hex_does_not_raise(self):
|
||||
for bad in ("", "a", "zz", "2a", "2a0", "not-hex-at-all"):
|
||||
self.assertIsNone(yc.cf_decode(bad))
|
||||
self.assertIsNone(yc_scraper.cf_decode(bad))
|
||||
|
||||
|
||||
class SiteEmailsIntegrationTests(unittest.TestCase):
|
||||
"""Exercises the full site_emails() pipeline (fetch -> plain-text + cf-decoded candidates ->
|
||||
domain/BAD_EMAIL filtering) with a mocked fetch, so it runs offline and deterministically."""
|
||||
|
||||
def _page_with(self, email, plain_email=None):
|
||||
hexstr = cf_encode(email)
|
||||
plain = f'<a href="mailto:{plain_email}">contact</a>' if plain_email else ""
|
||||
return (
|
||||
f'<html><body>{plain}'
|
||||
f'<a href="/cdn-cgi/l/email-protection#{hexstr}" class="__cf_email__" '
|
||||
f'data-cfemail="{hexstr}">[email protected]</a></body></html>'
|
||||
)
|
||||
|
||||
def test_api_yc_recovers_cf_protected_email_on_matching_domain(self):
|
||||
page = self._page_with("rachel@claimkit.co")
|
||||
with mock.patch.object(yc, "get", return_value=page):
|
||||
self.assertEqual(yc.site_emails("https://claimkit.co", "claimkit.co"), ["rachel@claimkit.co"])
|
||||
|
||||
def test_yc_scraper_recovers_cf_protected_email_on_matching_domain(self):
|
||||
page = self._page_with("rachel@claimkit.co")
|
||||
with mock.patch.object(yc_scraper, "get", return_value=page):
|
||||
self.assertEqual(
|
||||
yc_scraper.site_emails("https://claimkit.co", "claimkit.co"), ["rachel@claimkit.co"]
|
||||
)
|
||||
|
||||
def test_cf_protected_email_on_other_domain_is_dropped(self):
|
||||
# A support widget / embedded third-party script can carry its own cf-protected address;
|
||||
# the domain filter (same protection plain-text emails already get) must still apply.
|
||||
page = self._page_with("support@some-other-vendor.com")
|
||||
with mock.patch.object(yc, "get", return_value=page):
|
||||
self.assertEqual(yc.site_emails("https://claimkit.co", "claimkit.co"), [])
|
||||
|
||||
def test_plain_text_and_cf_protected_emails_combine_deduped(self):
|
||||
page = self._page_with("rachel@claimkit.co", plain_email="hello@claimkit.co")
|
||||
with mock.patch.object(yc, "get", return_value=page):
|
||||
self.assertEqual(
|
||||
yc.site_emails("https://claimkit.co", "claimkit.co"),
|
||||
["hello@claimkit.co", "rachel@claimkit.co"],
|
||||
)
|
||||
|
||||
def test_garbage_cfemail_attribute_does_not_crash_or_leak(self):
|
||||
page = '<span class="__cf_email__" data-cfemail="not-valid-hex">[email protected]</span>'
|
||||
with mock.patch.object(yc, "get", return_value=page):
|
||||
self.assertEqual(yc.site_emails("https://claimkit.co", "claimkit.co"), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@ -1,165 +0,0 @@
|
||||
// Exercises the real index.html <script> inside a sandboxed VM context to prove the
|
||||
// industry filter (added alongside the existing email/hiring/search filters) actually
|
||||
// narrows the visible list, and that the "Top -> Sub" industry string YC returns is
|
||||
// reduced to its top-level category consistently.
|
||||
//
|
||||
// No npm dependencies: node:vm + node:assert only, matching this repo's stdlib-only policy.
|
||||
// Run: node tests/test_industry_filter.mjs
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import vm from "node:vm";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const html = readFileSync(join(here, "..", "index.html"), "utf8");
|
||||
const scriptMatch = html.match(/<script>([\s\S]*?)<\/script>/);
|
||||
assert.ok(scriptMatch, "index.html must contain a single inline <script> block");
|
||||
|
||||
// Glue appended at the very end of the real script, same technique as
|
||||
// test_sent_tracking.mjs: `let`/`const` top-level bindings in index.html aren't exposed
|
||||
// on the vm context by default, but a trailing statement in the same scope can still
|
||||
// read them directly without altering a single line of the shipped code.
|
||||
const glue = `
|
||||
;globalThis.__test = {
|
||||
industryTop,
|
||||
filter,
|
||||
populateIndustries,
|
||||
setAll: (v) => { ALL = v; },
|
||||
setData: (v) => { DATA = v; },
|
||||
};
|
||||
`;
|
||||
const source = scriptMatch[1] + glue;
|
||||
|
||||
function makeEl(id) {
|
||||
return {
|
||||
id, value: "", textContent: "", innerHTML: "", checked: false, disabled: false, hidden: false,
|
||||
dataset: {}, style: {}, href: "", _listeners: {},
|
||||
classList: {
|
||||
_set: new Set(),
|
||||
toggle(cls, force) {
|
||||
if (force === undefined) { this._set.has(cls) ? this._set.delete(cls) : this._set.add(cls); }
|
||||
else if (force) this._set.add(cls); else this._set.delete(cls);
|
||||
},
|
||||
contains(cls) { return this._set.has(cls); },
|
||||
add(cls) { this._set.add(cls); },
|
||||
remove(cls) { this._set.delete(cls); },
|
||||
},
|
||||
addEventListener(type, fn) { (this._listeners[type] ||= []).push(fn); },
|
||||
closest() { return this; },
|
||||
querySelector() { return makeEl(); },
|
||||
querySelectorAll() { return []; },
|
||||
};
|
||||
}
|
||||
|
||||
function buildSandbox() {
|
||||
const elements = new Map();
|
||||
const detailsRegistry = [];
|
||||
const dataKFields = ["my_name", "portfolio", "github", "resume", "subject", "body"].map(k => {
|
||||
const el = makeEl();
|
||||
el.dataset.k = k;
|
||||
return el;
|
||||
});
|
||||
const storageMap = new Map();
|
||||
|
||||
const document = {
|
||||
getElementById(id) {
|
||||
if (!elements.has(id)) elements.set(id, makeEl(id));
|
||||
return elements.get(id);
|
||||
},
|
||||
querySelectorAll(sel) {
|
||||
if (sel === "details" || sel === "#list details") return detailsRegistry;
|
||||
if (sel === "[data-k]") return dataKFields;
|
||||
return [];
|
||||
},
|
||||
querySelector() { return makeEl(); },
|
||||
};
|
||||
|
||||
const localStorage = {
|
||||
getItem(k) { return storageMap.has(k) ? storageMap.get(k) : null; },
|
||||
setItem(k, v) { storageMap.set(k, String(v)); },
|
||||
removeItem(k) { storageMap.delete(k); },
|
||||
};
|
||||
// The real script also reads/writes sessionStorage (Gmail OAuth token) and uses
|
||||
// setInterval (queue countdown refresh) at the top level -- stub both so the whole
|
||||
// inline script can run unmodified inside this sandbox.
|
||||
const sessionMap = new Map();
|
||||
const sessionStorage = {
|
||||
getItem(k) { return sessionMap.has(k) ? sessionMap.get(k) : null; },
|
||||
setItem(k, v) { sessionMap.set(k, String(v)); },
|
||||
removeItem(k) { sessionMap.delete(k); },
|
||||
};
|
||||
|
||||
const sandbox = {
|
||||
document, localStorage, sessionStorage,
|
||||
fetch: async () => { throw new Error("network disabled in test"); },
|
||||
setTimeout, clearTimeout,
|
||||
// unref so the one real interval the script starts (the queue countdown ticker)
|
||||
// can't keep this short-lived test process alive after the assertions run.
|
||||
setInterval: (fn, ms) => { const t = setInterval(fn, ms); t.unref?.(); return t; },
|
||||
clearInterval, URLSearchParams, console,
|
||||
__detailsRegistry: detailsRegistry,
|
||||
};
|
||||
return vm.createContext(sandbox);
|
||||
}
|
||||
|
||||
function makeDetailsEl({ ind = "", s = "none", jobs = "0", k = "", sent = false } = {}) {
|
||||
const d = makeEl();
|
||||
d.dataset.i = "0";
|
||||
d.dataset.k = k;
|
||||
d.dataset.s = s;
|
||||
d.dataset.ind = ind;
|
||||
d.dataset.jobs = jobs;
|
||||
if (sent) d.classList.add("sent");
|
||||
return d;
|
||||
}
|
||||
|
||||
const ctx = buildSandbox();
|
||||
vm.runInContext(source, ctx, { filename: "index.html-inline-script" });
|
||||
|
||||
// --- industryTop: reduces YC's "Top -> Sub" string to the top-level category ---
|
||||
assert.equal(ctx.__test.industryTop("B2B -> Analytics"), "B2B");
|
||||
assert.equal(ctx.__test.industryTop("Consumer"), "Consumer");
|
||||
assert.equal(ctx.__test.industryTop(""), "");
|
||||
assert.equal(ctx.__test.industryTop(undefined), "");
|
||||
assert.equal(ctx.__test.industryTop(" Fintech -> Payments "), "Fintech");
|
||||
console.log("PASS: industryTop reduces 'Top -> Sub' industry strings to their top-level category.");
|
||||
|
||||
// --- populateIndustries: builds the dropdown from the batch's own distinct top-level industries ---
|
||||
ctx.__test.setAll([
|
||||
{ industry: "B2B -> Analytics" },
|
||||
{ industry: "B2B -> Sales" },
|
||||
{ industry: "Fintech -> Payments" },
|
||||
{ industry: "" },
|
||||
{ industry: undefined },
|
||||
]);
|
||||
ctx.__test.populateIndustries();
|
||||
const indSelect = ctx.document.getElementById("ind");
|
||||
assert.match(indSelect.innerHTML, /All industries/);
|
||||
assert.match(indSelect.innerHTML, /value="B2B">B2B</);
|
||||
assert.match(indSelect.innerHTML, /value="Fintech">Fintech</);
|
||||
// No duplicate "B2B" option despite two B2B companies, and no empty-string option.
|
||||
assert.equal((indSelect.innerHTML.match(/value="B2B"/g) || []).length, 1);
|
||||
assert.doesNotMatch(indSelect.innerHTML, /value=""><\/option>/);
|
||||
console.log("PASS: populateIndustries lists each distinct top-level industry once, skipping blanks.");
|
||||
|
||||
// --- filter(): the industry dropdown actually narrows the visible list ---
|
||||
const b2bRow = makeDetailsEl({ ind: "B2B", k: "acme corp" });
|
||||
const fintechRow = makeDetailsEl({ ind: "Fintech", k: "payco" });
|
||||
ctx.__test.setData([{}, {}]); // only length matters for the "shown" summary text
|
||||
ctx.document.querySelectorAll("details"); // sanity: registry exists
|
||||
ctx.__detailsRegistry.push(b2bRow, fintechRow);
|
||||
|
||||
ctx.document.getElementById("ind").value = "B2B";
|
||||
ctx.__test.filter();
|
||||
assert.equal(b2bRow.style.display, "", "the B2B row must stay visible when 'B2B' is selected");
|
||||
assert.equal(fintechRow.style.display, "none", "the Fintech row must be hidden when 'B2B' is selected");
|
||||
assert.match(ctx.document.getElementById("shown").textContent, /^1 of 2 shown/);
|
||||
|
||||
ctx.document.getElementById("ind").value = "";
|
||||
ctx.__test.filter();
|
||||
assert.equal(b2bRow.style.display, "", "clearing the industry filter must show every row again");
|
||||
assert.equal(fintechRow.style.display, "");
|
||||
assert.match(ctx.document.getElementById("shown").textContent, /^2 of 2 shown/);
|
||||
|
||||
console.log("PASS: the industry filter narrows (and un-narrows) the visible company list.");
|
||||
@ -1,11 +1,7 @@
|
||||
// Exercises the real index.html <script> inside a sandboxed VM context to prove that
|
||||
// marking one company's pipeline stage does not affect a different company that happens
|
||||
// to share the same display name (YC has many name collisions across/within batches, e.g.
|
||||
// two distinct "Palisade" companies both appear in Summer 2026 with slugs palisade/palisade-2).
|
||||
//
|
||||
// Pipeline state moved from a boolean "sent" Set (commit bfca064) to a per-slug stage enum
|
||||
// (not_sent/sent/followed_up/replied/interview/rejected/closed, each with a timestamp) --
|
||||
// this test now drives that stage select instead of the old checkbox, same slug-isolation intent.
|
||||
// marking one company "sent" does not affect a different company that happens to share
|
||||
// the same display name (YC has many name collisions across/within batches, e.g. two
|
||||
// distinct "Palisade" companies both appear in Summer 2026 with slugs palisade/palisade-2).
|
||||
//
|
||||
// No npm dependencies: node:vm + node:assert only, matching this repo's stdlib-only policy.
|
||||
// Run: node tests/test_sent_tracking.mjs
|
||||
@ -27,7 +23,7 @@ assert.ok(scriptMatch, "index.html must contain a single inline <script> block")
|
||||
const glue = `
|
||||
;globalThis.__test = {
|
||||
setData: (v) => { DATA = v; },
|
||||
getStages: () => stages,
|
||||
getSent: () => sent,
|
||||
};
|
||||
`;
|
||||
const source = scriptMatch[1] + glue;
|
||||
@ -69,7 +65,7 @@ function buildSandbox() {
|
||||
return elements.get(id);
|
||||
},
|
||||
querySelectorAll(sel) {
|
||||
if (sel === "details" || sel === "#list details") return detailsRegistry;
|
||||
if (sel === "details") return detailsRegistry;
|
||||
if (sel === "[data-k]") return dataKFields;
|
||||
return [];
|
||||
},
|
||||
@ -83,26 +79,12 @@ function buildSandbox() {
|
||||
const localStorage = {
|
||||
getItem(k) { return storageMap.has(k) ? storageMap.get(k) : null; },
|
||||
setItem(k, v) { storageMap.set(k, String(v)); },
|
||||
removeItem(k) { storageMap.delete(k); },
|
||||
};
|
||||
// The real script also reads/writes sessionStorage (Gmail OAuth token) and uses
|
||||
// setInterval (queue countdown refresh) at the top level -- stub both so the whole
|
||||
// inline script can run unmodified inside this sandbox.
|
||||
const sessionMap = new Map();
|
||||
const sessionStorage = {
|
||||
getItem(k) { return sessionMap.has(k) ? sessionMap.get(k) : null; },
|
||||
setItem(k, v) { sessionMap.set(k, String(v)); },
|
||||
removeItem(k) { sessionMap.delete(k); },
|
||||
};
|
||||
|
||||
const sandbox = {
|
||||
document, localStorage, sessionStorage,
|
||||
document, localStorage,
|
||||
fetch: async () => { throw new Error("network disabled in test"); },
|
||||
setTimeout, clearTimeout,
|
||||
// unref so the one real interval the script starts (the queue countdown ticker)
|
||||
// can't keep this short-lived test process alive after the assertions run.
|
||||
setInterval: (fn, ms) => { const t = setInterval(fn, ms); t.unref?.(); return t; },
|
||||
clearInterval, URLSearchParams, console,
|
||||
setTimeout, clearTimeout, URLSearchParams, console,
|
||||
__detailsRegistry: detailsRegistry,
|
||||
};
|
||||
return vm.createContext(sandbox);
|
||||
@ -127,17 +109,17 @@ function run(companyA, companyB) {
|
||||
ctx.__test.setData([companyA, companyB]);
|
||||
|
||||
const listEl = ctx.document.getElementById("list");
|
||||
const changeHandler = listEl._listeners.change[0];
|
||||
const clickHandler = listEl._listeners.click[0];
|
||||
|
||||
// Simulate picking "Sent" in company A's (index 0) pipeline-stage <select>.
|
||||
const stageSelect = makeEl();
|
||||
stageSelect.dataset.a = "stage";
|
||||
stageSelect.value = "sent";
|
||||
stageSelect.closest = (sel) => (sel === '[data-a="stage"]' ? stageSelect : sel === "details" ? detailsA : null);
|
||||
// Simulate checking the "sent" checkbox on company A (index 0).
|
||||
const checkbox = makeEl();
|
||||
checkbox.dataset.a = "sent";
|
||||
checkbox.checked = true;
|
||||
checkbox.closest = (sel) => (sel === "[data-a]" ? checkbox : sel === "details" ? detailsA : null);
|
||||
|
||||
changeHandler({ target: stageSelect });
|
||||
clickHandler({ target: checkbox });
|
||||
|
||||
return { stages: ctx.__test.getStages(), detailsA, detailsB };
|
||||
return { sent: ctx.__test.getSent(), detailsA, detailsB };
|
||||
}
|
||||
|
||||
// Two distinct real YC companies that share a display name but have different slugs
|
||||
@ -145,26 +127,28 @@ function run(companyA, companyB) {
|
||||
const companyA = { name: "Palisade", slug: "palisade" };
|
||||
const companyB = { name: "Palisade", slug: "palisade-2" };
|
||||
|
||||
const { stages } = run(companyA, companyB);
|
||||
const { sent, detailsA, detailsB } = run(companyA, companyB);
|
||||
|
||||
// The bug this guards against: stage tracking keyed by company *name* would mark both
|
||||
// same-named companies as sent, even though only the first one was ever actually marked.
|
||||
const keyedByNameWouldCollide = stages[companyA.name] !== undefined || stages[companyB.name] !== undefined;
|
||||
// The bug: "sent" tracking keyed by company *name* marks both same-named companies as
|
||||
// sent, even though only the first one was ever actually marked.
|
||||
const keyedByName = sent.has(companyA.name) && sent.has(companyB.name);
|
||||
// The fix: keyed by slug, marking A must not affect B.
|
||||
const keyedBySlugCorrectly = stages[companyA.slug]?.stage === "sent" && stages[companyB.slug] === undefined;
|
||||
const keyedBySlugCorrectly = sent.has(companyA.slug) && !sent.has(companyB.slug);
|
||||
|
||||
assert.equal(detailsA.classList.contains("sent"), true, "company A's own row should be marked sent");
|
||||
|
||||
assert.equal(
|
||||
keyedBySlugCorrectly,
|
||||
true,
|
||||
`Expected pipeline stage to be tracked by the unique company slug, not the (possibly duplicate) name. ` +
|
||||
`stages=${JSON.stringify(stages)} -- marking "${companyA.name}" (slug ${companyA.slug}) as sent must not ` +
|
||||
`Expected "sent" to be tracked by the unique company slug, not the (possibly duplicate) name. ` +
|
||||
`sent=${JSON.stringify([...sent])} -- marking "${companyA.name}" (slug ${companyA.slug}) as sent must not ` +
|
||||
`also mark the unrelated company "${companyB.name}" (slug ${companyB.slug}) as sent.`
|
||||
);
|
||||
assert.equal(
|
||||
keyedByNameWouldCollide,
|
||||
keyedByName,
|
||||
false,
|
||||
"pipeline-stage tracking must not use the non-unique company name as its key (YC has real name collisions, " +
|
||||
"sent-tracking must not use the non-unique company name as its key (YC has real name collisions, " +
|
||||
'e.g. two distinct "Palisade" companies both in Summer 2026: slugs palisade / palisade-2)'
|
||||
);
|
||||
|
||||
console.log("PASS: pipeline-stage tracking is keyed by unique company slug, not by the collidable display name.");
|
||||
console.log("PASS: sent-tracking is keyed by unique company slug, not by the collidable display name.");
|
||||
|
||||
@ -13,7 +13,6 @@ import urllib.parse, urllib.request
|
||||
|
||||
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128 Safari/537.36"
|
||||
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
|
||||
CF_EMAIL_RE = re.compile(r'data-cfemail="([0-9a-fA-F]+)"') # Cloudflare's "email protection" obfuscation
|
||||
BAD_EMAIL = re.compile(r"\.(png|jpe?g|gif|svg|webp|css|js)$|sentry|wixpress|example\.|@2x|u00|domain\.com|email\.com", re.I)
|
||||
CONTACT_PATHS = ["", "/contact", "/about", "/team", "/contact-us", "/about-us"]
|
||||
CTX = ssl.create_default_context()
|
||||
@ -69,37 +68,21 @@ def domain_of(website):
|
||||
return host.removeprefix("www.").lower()
|
||||
|
||||
|
||||
def cf_decode(hexstr):
|
||||
# Cloudflare's "email protection" shows "[email protected]" on the page and stashes the real
|
||||
# address XOR-masked in a data-cfemail="<hex>" attribute: byte 0 is the key, every later byte
|
||||
# is a masked character. Very common on small-business sites (Webflow/WordPress + Cloudflare);
|
||||
# EMAIL_RE alone never sees these addresses, so without this they silently fall back to a guess.
|
||||
try:
|
||||
key, rest = int(hexstr[:2], 16), hexstr[2:]
|
||||
if len(rest) < 2 or len(rest) % 2:
|
||||
return None
|
||||
return bytes(int(rest[i : i + 2], 16) ^ key for i in range(0, len(rest), 2)).decode("ascii")
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def site_emails(website, domain):
|
||||
if not website:
|
||||
return []
|
||||
base = website.rstrip("/")
|
||||
found = set()
|
||||
for path in CONTACT_PATHS:
|
||||
raw = get(base + path, timeout=10)
|
||||
if not raw:
|
||||
body = get(base + path, timeout=10)
|
||||
if not body:
|
||||
continue
|
||||
unescaped = urllib.parse.unquote(html.unescape(raw))
|
||||
candidates = EMAIL_RE.findall(unescaped)
|
||||
candidates += filter(None, (cf_decode(h) for h in CF_EMAIL_RE.findall(raw)))
|
||||
for e in candidates:
|
||||
body = urllib.parse.unquote(html.unescape(body))
|
||||
for e in EMAIL_RE.findall(body):
|
||||
e = e.lower().strip(".")
|
||||
# Only keep emails on the company's own domain (drops form placeholders like you@company.com)
|
||||
host = e.split("@")[-1]
|
||||
if EMAIL_RE.fullmatch(e) and not BAD_EMAIL.search(e) and (host == domain or host.endswith("." + domain)):
|
||||
host = e.split("@")[1]
|
||||
if not BAD_EMAIL.search(e) and (host == domain or host.endswith("." + domain)):
|
||||
found.add(e)
|
||||
return sorted(found)
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user