1
2
3
4
5
6
7
8
9
10import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11import { dirname, join } from 'node:path';
12import { setTimeout as sleep } from 'node:timers/promises';
13import { URL, fileURLToPath } from 'node:url';
14
15import { Parser } from 'htmlparser2';
16
17import { MAX_JOBS_PER_BOARD } from '../dist/adapters/board.js';
18import { smartRecruitersAdapter } from '../dist/adapters/smartrecruiters/index.js';
19import { SafeFetchError, safeFetch } from '../dist/http/safe-fetch.js';
20
21const API = 'https://api.smartrecruiters.com/v1/companies';
22const PAGES = 'https://jobs.smartrecruiters.com';
23const PAGE_HOST = 'jobs.smartrecruiters.com';
24const PAGE_SIZE = 100;
25
26const MAX_LIST_PAGES = 150;
27
28const PAGES_PER_BOARD = 3;
29
30const PAGE_GAP_MS = 1_000;
31const PAGE_MAX_BYTES = 2 * 1024 * 1024;
32
33const root = join(dirname(fileURLToPath(import.meta.url)), '..');
34
35function slugsFromLabels() {
36 const { companies } = JSON.parse(readFileSync(join(root, 'tests', 'eval', 'companies.json'), 'utf8'));
37 const slugs = companies
38 .filter((c) => c.expected?.ats === 'smartrecruiters')
39 .map((c) => c.expected.slug.toLowerCase());
40 return [...new Set(slugs)];
41}
42
43const blankToNull = (s) => (typeof s === 'string' && s.trim() !== '' ? s.trim() : null);
44const squash = (s) => s.replace(/\s+/g, ' ').trim();
45
46
47async function fetchRaw(slug) {
48 const byId = new Map();
49 for (let page = 0; page < MAX_LIST_PAGES; page++) {
50 const url = `${API}/${encodeURIComponent(slug)}/postings?limit=${PAGE_SIZE}&offset=${page * PAGE_SIZE}`;
51 const res = await safeFetch(url);
52 if (res.status !== 200) throw new Error(`list ${url} answered ${res.status}`);
53 const data = JSON.parse(res.body.toString('utf8'));
54 for (const posting of data.content) if (!byId.has(posting.id)) byId.set(posting.id, posting);
55 if (data.content.length === 0 || (page + 1) * PAGE_SIZE >= data.totalFound) return byId;
56 }
57 throw new Error(`board ${slug} has more than ${MAX_LIST_PAGES} list pages`);
58}
59
60
61
62
63
64function expectedFromRaw(posting) {
65 return {
66 title: posting.name.trim(),
67 country: blankToNull(posting.location?.country),
68 remote: posting.location?.remote === true,
69 posted: blankToNull(posting.releasedDate)?.slice(0, 10) ?? null,
70 };
71}
72
73function fromAdapter(job) {
74 return {
75 title: job.title,
76 country: job.country,
77 remote: job.workplaceType === 'remote',
78 posted: job.postedAt?.slice(0, 10) ?? null,
79 };
80}
81
82
83async function compareWithRaw(slug, board) {
84 const ours = new Map(board.jobs.map((j) => [j.atsJobId, j]));
85 const raw = await fetchRaw(slug);
86 const capped = raw.size > MAX_JOBS_PER_BOARD;
87 let extra = [...ours.keys()].filter((id) => !raw.has(id));
88 let missing = capped ? [] : [...raw.keys()].filter((id) => !ours.has(id));
89 if (extra.length > 0 || missing.length > 0) {
90 const again = await fetchRaw(slug);
91 for (const [id, posting] of again) if (!raw.has(id)) raw.set(id, posting);
92 extra = extra.filter((id) => !again.has(id));
93 missing = missing.filter((id) => again.has(id));
94 }
95 const mismatches = [
96 ...extra.map((id) => ({ id, field: 'job', ours: 'present', theirs: 'absent' })),
97 ...missing.map((id) => ({ id, field: 'job', ours: 'absent', theirs: 'present' })),
98 ];
99 if (capped && (board.truncated !== true || ours.size > MAX_JOBS_PER_BOARD)) {
100 mismatches.push({
101 id: '-',
102 field: 'cap',
103 ours: `${ours.size} jobs, truncated ${board.truncated}`,
104 theirs: raw.size,
105 });
106 }
107 for (const [id, job] of ours) {
108 const posting = raw.get(id);
109 if (posting === undefined) continue;
110 const want = expectedFromRaw(posting);
111 const got = fromAdapter(job);
112 for (const field of Object.keys(want)) {
113 if (got[field] !== want[field]) mismatches.push({ id, field, ours: got[field], theirs: want[field] });
114 }
115 }
116 return { raw: raw.size, mismatches };
117}
118
119
120
121
122
123
124function pageFacts(html) {
125 const facts = {};
126 const keep = (key, value) => {
127 if (value !== undefined && facts[key] === undefined) facts[key] = value;
128 };
129 const parser = new Parser({
130 onopentag(name, a) {
131 if (name === 'html') keep('lang', a.lang);
132 if (name === 'spl-job-location') keep('place', a.formattedaddress);
133 if (name !== 'meta') return;
134 if (a.property === 'og:title') keep('title', a.content);
135 if (a.itemprop === 'datePosted') keep('posted', a.content);
136 },
137 });
138 parser.write(html);
139 parser.end();
140 return facts;
141}
142
143
144function refusal(res) {
145 if (res.status === 429 || res.status === 403) return `status ${res.status}`;
146 const mitigated = res.headers.get('cf-mitigated');
147 return mitigated === null ? null : `cf-mitigated: ${mitigated}`;
148}
149
150let pagesRefused = null;
151
152
153async function compareWithPages(slug, board) {
154 const newest = [...board.jobs]
155 .sort((a, b) => (Date.parse(b.postedAt ?? '') || 0) - (Date.parse(a.postedAt ?? '') || 0))
156 .slice(0, PAGES_PER_BOARD);
157 const mismatches = [];
158 let read = 0;
159 for (const job of newest) {
160 if (pagesRefused !== null) break;
161 await sleep(PAGE_GAP_MS);
162 const url = `${PAGES}/${encodeURIComponent(slug)}/${encodeURIComponent(job.atsJobId)}`;
163 let res;
164 try {
165 res = await safeFetch(url, { maxRetries: 0, maxBytes: PAGE_MAX_BYTES });
166 } catch (err) {
167 if (!(err instanceof SafeFetchError)) throw err;
168 mismatches.push({
169 id: job.atsJobId,
170 field: 'page',
171 ours: 'present',
172 theirs: `fetch failed: ${err.code}`,
173 });
174 continue;
175 }
176 const why = refusal(res);
177 if (why !== null) {
178 pagesRefused = { slug, reason: why };
179 break;
180 }
181 if (res.status === 404 || new URL(res.url).hostname.toLowerCase() !== PAGE_HOST) continue;
182 if (res.status !== 200) {
183 mismatches.push({ id: job.atsJobId, field: 'page', ours: 'present', theirs: `status ${res.status}` });
184 continue;
185 }
186 read++;
187 const facts = pageFacts(res.body.toString('utf8'));
188
189
190 const city = blankToNull((job.location ?? '').split(',')[0]);
191
192 const place = facts.lang?.toLowerCase().startsWith('en') === true ? blankToNull(facts.place) : null;
193 const checks = [
194 ['title', squash(job.title), facts.title === undefined ? undefined : squash(facts.title)],
195 ['posted', job.postedAt?.slice(0, 10) ?? null, facts.posted?.slice(0, 10)],
196 ];
197 for (const [field, got, want] of checks) {
198 if (want === undefined || want === '') continue;
199 if (got !== want)
200 mismatches.push({ id: job.atsJobId, field: `page ${field}`, ours: got, theirs: want });
201 }
202 if (city !== null && place !== null && !place.toLowerCase().includes(city.toLowerCase())) {
203 mismatches.push({ id: job.atsJobId, field: 'page place', ours: job.location, theirs: place });
204 }
205 }
206 return { read, mismatches };
207}
208
209async function checkBoard(slug) {
210 const board = await smartRecruitersAdapter.fetchJobs(slug, safeFetch);
211 if (board === null) return { slug, ok: false, problem: 'adapter found no board' };
212 const raw = await compareWithRaw(slug, board);
213 const pages = await compareWithPages(slug, board);
214 const mismatches = [...raw.mismatches, ...pages.mismatches];
215 return {
216 slug,
217 ok: mismatches.length === 0,
218 jobs: { adapter: board.jobs.length, raw: raw.raw, pages: pages.read },
219 mismatches,
220 };
221}
222
223const slugs = process.argv.length > 2 ? process.argv.slice(2).map((s) => s.toLowerCase()) : slugsFromLabels();
224const results = [];
225for (const slug of slugs) {
226 try {
227 results.push(await checkBoard(slug));
228 } catch (err) {
229 results.push({ slug, ok: false, problem: err instanceof Error ? err.message : 'throw' });
230 }
231}
232
233for (const r of results) {
234 const detail =
235 r.problem ??
236 `${r.jobs.adapter}/${r.jobs.raw} jobs, ${r.jobs.pages} pages, ${r.mismatches.length} mismatches`;
237 console.log(`${r.ok ? 'agree ' : 'DISAGREE'} ${r.slug.padEnd(28)} ${detail}`);
238 for (const m of (r.mismatches ?? []).slice(0, 5)) {
239 console.log(` ${m.id} ${m.field}: ours ${JSON.stringify(m.ours)} vs ${JSON.stringify(m.theirs)}`);
240 }
241}
242const agreeing = results.filter((r) => r.ok).length;
243const pagesRead = results.reduce((n, r) => n + (r.jobs?.pages ?? 0), 0);
244console.log(`crosscheck: ${agreeing}/${results.length} boards agree, ${pagesRead} posting pages read`);
245if (pagesRefused !== null) {
246 console.log(
247 `crosscheck: posting pages REFUSED at ${pagesRefused.slug} (${pagesRefused.reason}); none read after it`,
248 );
249}
250
251const out = join(root, 'storage', 'smartrecruiters-crosscheck.json');
252mkdirSync(dirname(out), { recursive: true });
253writeFileSync(
254 out,
255 `${JSON.stringify({ agreeing, total: results.length, pagesRead, pagesRefused, results }, null, 2)}\n`,
256);
257console.log(`crosscheck: report → ${out}`);
258process.exit(agreeing === results.length && pagesRefused === null ? 0 : 1);