@profullstack/gov-contracts 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/profile.js ADDED
@@ -0,0 +1,308 @@
1
+ /**
2
+ * The bidder's niche profile, derived from its own website.
3
+ *
4
+ * crawl (spider.js, c0mpute crawl.fetch first) -> index the pages (SQLite
5
+ * FTS5) -> a model names the niches, keywords, NAICS and non-fits from what
6
+ * the pages say (c0mpute first, OpenAI/Claude fallback) -> save as the active
7
+ * profile -> re-screen every open solicitation against it.
8
+ *
9
+ * Without a model, niches come from NICHE_LIBRARY: a niche is kept when the
10
+ * site's own text uses its keywords. An operator can edit the result.
11
+ */
12
+ import { z } from 'zod';
13
+ import { makeAi } from './ai.js';
14
+ import { DEFAULT_PROFILE, NICHE_LIBRARY, BASE_NEGATIVE, activeProfile, compile, keywordFragment, nicheMatch, normalizeProfile, setActiveProfile } from './niche.js';
15
+ import { crawlSite } from './spider.js';
16
+ import { logRun, now, openDb } from './store.js';
17
+
18
+ /* ------------------------------------------------------------------ storage -- */
19
+
20
+ let ready = false;
21
+ function db() {
22
+ const d = openDb();
23
+ if (ready) return d;
24
+ d.exec(`
25
+ CREATE TABLE IF NOT EXISTS profile (
26
+ id TEXT PRIMARY KEY, -- 'active'
27
+ domain TEXT,
28
+ data TEXT NOT NULL, -- JSON profile (niche.js normalizeProfile)
29
+ updated_at TEXT NOT NULL
30
+ );
31
+ CREATE TABLE IF NOT EXISTS profile_pages (
32
+ url TEXT PRIMARY KEY,
33
+ domain TEXT NOT NULL,
34
+ title TEXT,
35
+ description TEXT,
36
+ headings TEXT, -- JSON array
37
+ text TEXT,
38
+ via TEXT, -- c0mpute:bridge | c0mpute:cli | direct | pushed
39
+ fetched_at TEXT NOT NULL
40
+ );
41
+ CREATE INDEX IF NOT EXISTS pp_domain ON profile_pages(domain);
42
+ CREATE VIRTUAL TABLE IF NOT EXISTS profile_pages_fts USING fts5(url UNINDEXED, title, headings, text, tokenize = 'porter');
43
+ `);
44
+ ready = true;
45
+ return d;
46
+ }
47
+
48
+ const pj = (v, d) => { try { return JSON.parse(v); } catch { return d; } };
49
+ const hostOf = (domain) => String(domain).replace(/^https?:\/\//i, '').replace(/\/.*$/, '').replace(/^www\./, '').toLowerCase();
50
+
51
+ /** Load the saved profile into niche.js. Called at start. */
52
+ export function loadProfile() {
53
+ const r = db().prepare("SELECT data FROM profile WHERE id = 'active'").get();
54
+ return setActiveProfile(r ? pj(r.data, null) : null);
55
+ }
56
+
57
+ export function saveProfile(p) {
58
+ const n = normalizeProfile(p);
59
+ db().prepare("INSERT INTO profile (id, domain, data, updated_at) VALUES ('active', ?, ?, ?) ON CONFLICT (id) DO UPDATE SET domain = excluded.domain, data = excluded.data, updated_at = excluded.updated_at")
60
+ .run(n.domain ?? null, JSON.stringify(n), now());
61
+ return setActiveProfile(n);
62
+ }
63
+
64
+ export function getProfile() {
65
+ const p = activeProfile();
66
+ const pages = db().prepare('SELECT COUNT(*) AS n FROM profile_pages WHERE domain = ?').get(hostOf(p.domain || '')).n;
67
+ return { ...p, indexed_pages: pages };
68
+ }
69
+
70
+ /** Replace a domain's indexed pages. */
71
+ export function indexPages(domain, pages) {
72
+ const d = db();
73
+ const host = hostOf(domain);
74
+ const old = d.prepare('SELECT url FROM profile_pages WHERE domain = ?').all(host).map((r) => r.url);
75
+ const delFts = d.prepare('DELETE FROM profile_pages_fts WHERE url = ?');
76
+ for (const u of old) delFts.run(u);
77
+ d.prepare('DELETE FROM profile_pages WHERE domain = ?').run(host);
78
+ const ins = d.prepare('INSERT OR REPLACE INTO profile_pages (url, domain, title, description, headings, text, via, fetched_at) VALUES (?,?,?,?,?,?,?,?)');
79
+ const fts = d.prepare('INSERT INTO profile_pages_fts (url, title, headings, text) VALUES (?,?,?,?)');
80
+ const t = now();
81
+ for (const p of pages) {
82
+ const headings = Array.isArray(p.headings) ? p.headings.slice(0, 30).map((x) => String(x).slice(0, 200)) : [];
83
+ const text = String(p.text || '').slice(0, 12_000);
84
+ ins.run(String(p.url).slice(0, 2000), host, String(p.title || '').slice(0, 200), String(p.description || '').slice(0, 500), JSON.stringify(headings), text, String(p.via || 'pushed').slice(0, 40), t);
85
+ fts.run(String(p.url).slice(0, 2000), String(p.title || ''), headings.join('\n'), text);
86
+ }
87
+ return pages.length;
88
+ }
89
+
90
+ export function pagesFor(domain, { withText = false } = {}) {
91
+ const cols = withText ? '*' : 'url, title, description, via, fetched_at, length(text) AS text_chars';
92
+ return db().prepare(`SELECT ${cols} FROM profile_pages WHERE domain = ? ORDER BY url`).all(hostOf(domain)).map((r) => (r.headings ? { ...r, headings: pj(r.headings, []) } : r));
93
+ }
94
+
95
+ /** Full-text search over the indexed site (FTS5 query built from plain words). */
96
+ export function searchPages(q, { limit = 10 } = {}) {
97
+ const words = String(q || '').toLowerCase().match(/[a-z0-9]{2,}/g) || [];
98
+ if (!words.length) return [];
99
+ const match = words.slice(0, 8).map((w) => `"${w}"`).join(' OR ');
100
+ return db().prepare(`SELECT url, title, snippet(profile_pages_fts, 3, '[', ']', ' ... ', 16) AS snippet, bm25(profile_pages_fts) AS rank
101
+ FROM profile_pages_fts WHERE profile_pages_fts MATCH ? ORDER BY rank LIMIT ?`).all(match, Math.min(Number(limit) || 10, 50));
102
+ }
103
+
104
+ /* ----------------------------------------------------------------- deriving -- */
105
+
106
+ const siteText = (pages) => pages.map((p) => [p.title, p.description, ...(p.headings || []), p.text].join('\n')).join('\n\n');
107
+
108
+ /** Niches from the library whose keywords the site uses, strongest first. */
109
+ export function libraryNiches(pages) {
110
+ const text = siteText(pages);
111
+ const head = pages.map((p) => [p.title, p.description, ...(p.headings || [])].join('\n')).join('\n');
112
+ const out = [];
113
+ for (const n of NICHE_LIBRARY) {
114
+ let hits = 0;
115
+ const used = [];
116
+ for (const k of n.keywords) {
117
+ const r = new RegExp(`(?<![\\w-])${k}(?![\\w-])`, 'gi');
118
+ const c = (text.match(r) || []).length + 2 * (head.match(r) || []).length;
119
+ if (c) { hits += c; used.push(k); }
120
+ }
121
+ if (hits >= 3) out.push({ ...n, hits, evidence: `site uses: ${used.slice(0, 6).join(', ')}` });
122
+ }
123
+ return out.sort((a, b) => b.hits - a.hits).map(({ hits, ...n }) => ({ ...n, enabled: true }));
124
+ }
125
+
126
+ const squash = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
127
+
128
+ /**
129
+ * A library niche with the same name as a model niche ("Cybersecurity" and
130
+ * "Cyber security") is folded into it, keywords added. Every other library
131
+ * niche the site supports is kept under its own name, so a well-known niche
132
+ * ("Software consulting", "Agentic engineering") is never renamed after a
133
+ * model's wording; two niches covering the same bid only add a second label.
134
+ */
135
+ export function mergeLibrary(modelNiches, lib) {
136
+ const out = modelNiches.map((n) => ({ ...n, keywords: [...n.keywords] }));
137
+ for (const l of lib) {
138
+ const twin = out.find((n) => { const a = squash(n.name); const b = squash(l.name); return a === b || (a.length > 6 && b.includes(a)) || (b.length > 6 && a.includes(b)); });
139
+ if (twin) {
140
+ twin.keywords = [...new Set([...twin.keywords, ...l.keywords])];
141
+ twin.libName = l.name;
142
+ } else out.push(l);
143
+ }
144
+ return out;
145
+ }
146
+
147
+ export const DerivedSchema = z.object({
148
+ company: z.string(),
149
+ summary: z.string(),
150
+ niches: z.array(z.object({
151
+ name: z.string(),
152
+ keywords: z.array(z.string()).default([]),
153
+ evidence: z.string().default(''),
154
+ })).default([]),
155
+ capabilities: z.array(z.string()).default([]),
156
+ naics: z.array(z.string()).default([]),
157
+ not_a_fit: z.array(z.string()).default([]),
158
+ });
159
+
160
+ const SYSTEM = `You read a company's own website and write its government-contracting niche profile.
161
+ Name 3 to 8 niches the company clearly sells (for example "Software consulting", "Agentic engineering", "Cybersecurity"), each with 4 to 12 short keywords or phrases a government solicitation TITLE would use for that work (lowercase, 1 to 4 words; "case management system", "penetration testing", "ai agents").
162
+ Only niches the pages actually support; quote the evidence briefly. List capabilities as short sentences, the 6-digit NAICS codes that fit (541511, 541512, 541519, 518210 and the like), and what the company should never bid on.
163
+ Answer with JSON only.`;
164
+
165
+ const clip = (s, n) => (s && s.length > n ? `${s.slice(0, n)}\n[...]` : s || '');
166
+
167
+ export function derivePrompt(domain, pages) {
168
+ const ranked = [...pages].sort((a, b) => (/(service|about|solution|capabilit|consult|agentic|\bai\b)/i.test(b.url) ? 1 : 0) - (/(service|about|solution|capabilit|consult|agentic|\bai\b)/i.test(a.url) ? 1 : 0));
169
+ let budget = 9000;
170
+ const parts = [];
171
+ for (const p of ranked) {
172
+ const block = `--- ${p.url}\n${p.title}\n${p.description || ''}\n${(p.headings || []).join(' | ')}\n${clip(p.text, 900)}`;
173
+ if (block.length > budget) break;
174
+ budget -= block.length;
175
+ parts.push(block);
176
+ }
177
+ return `Website: ${domain}\nPages read: ${pages.length}\n\n${parts.join('\n\n')}`;
178
+ }
179
+
180
+ /**
181
+ * Pages -> profile. A model answer is checked against the site text: a niche
182
+ * whose keywords never appear on the site is dropped. Library niches the site
183
+ * uses heavily are added when the model missed them.
184
+ */
185
+ export async function deriveProfile(domain, pages, { ai = makeAi() } = {}) {
186
+ const host = hostOf(domain);
187
+ const lib = libraryNiches(pages);
188
+ const text = siteText(pages).toLowerCase();
189
+ let derived = null;
190
+ let method = 'library';
191
+ let provider = null;
192
+ let aiError = null;
193
+ if (ai && pages.length) {
194
+ try {
195
+ const r = await ai.generateObject({
196
+ system: SYSTEM, user: derivePrompt(host, pages), schema: DerivedSchema, jsonSchema: z.toJSONSchema(DerivedSchema),
197
+ name: 'profile', feature: 'gov-contracts:profile', maxTokens: 2000, temperature: 0.2,
198
+ });
199
+ derived = r.object;
200
+ method = 'ai';
201
+ provider = r.provider;
202
+ } catch (e) {
203
+ aiError = String(e?.message || e).slice(0, 300);
204
+ }
205
+ }
206
+ let niches = lib;
207
+ if (derived) {
208
+ const grounded = derived.niches
209
+ .map((n) => {
210
+ const kws = [...new Set(n.keywords.map((k) => String(k).toLowerCase().trim()).filter((k) => k.length >= 2 && k.length <= 60))];
211
+ const onSite = kws.filter((k) => new RegExp(`(?<![\\w-])${keywordFragment(k)}(?![\\w-])`, 'i').test(text));
212
+ const libTwin = NICHE_LIBRARY.find((l) => l.name.toLowerCase() === n.name.toLowerCase());
213
+ return { name: n.name, keywords: [...new Set([...kws, ...(libTwin?.keywords || [])])], evidence: n.evidence, enabled: true, grounded: onSite.length };
214
+ })
215
+ .filter((n) => n.grounded > 0 && n.keywords.length)
216
+ .map(({ grounded, ...n }) => n);
217
+ niches = mergeLibrary(grounded, lib);
218
+ }
219
+ const libNaics = niches.flatMap((n) => NICHE_LIBRARY.find((l) => l.name === n.libName || l.name === n.name)?.naics || []);
220
+ const naics = [...new Set([...(derived?.naics || []).map((c) => String(c).replace(/\D/g, '')).filter((c) => /^\d{6}$/.test(c)), ...libNaics])];
221
+ return normalizeProfile({
222
+ company: derived?.company || pages.find((p) => p.title)?.title?.split(/[|\-:]/)[0]?.trim() || host,
223
+ domain: host,
224
+ summary: derived?.summary || pages.find((p) => p.description)?.description || `Read from ${host}.`,
225
+ capabilities: derived?.capabilities?.length ? derived.capabilities : niches.map((n) => n.name),
226
+ niches: niches.length ? niches : DEFAULT_PROFILE.niches,
227
+ negative_keywords: BASE_NEGATIVE,
228
+ naics: naics.length ? naics : DEFAULT_PROFILE.naics,
229
+ not_a_fit: derived?.not_a_fit?.length ? derived.not_a_fit : DEFAULT_PROFILE.not_a_fit,
230
+ source: `site:${host}`,
231
+ method: method === 'ai' ? `ai${provider ? `:${provider}` : ''}` : 'library',
232
+ crawled_at: now(),
233
+ pages: pages.length,
234
+ ...(aiError ? { ai_error: aiError } : {}),
235
+ });
236
+ }
237
+
238
+ /* --------------------------------------------------------------- re-screen -- */
239
+
240
+ /**
241
+ * Score every open solicitation against the active profile. Bids that left
242
+ * the niche stop at 'skipped' (if not read yet) and their open bid/no-bid
243
+ * card is hidden by the niche filter; bids that entered it go back to 'new'
244
+ * so they are read and scored. Scored, drafted and resolved work is kept.
245
+ */
246
+ export function rescreen(profile = activeProfile()) {
247
+ compile(profile);
248
+ const d = openDb();
249
+ const rows = d.prepare("SELECT id, title, description, naics, status FROM solicitations WHERE due_at IS NULL OR due_at >= ?").all(now().slice(0, 10));
250
+ const upd = d.prepare('UPDATE solicitations SET prefilter = ?, niche_score = ?, niches = ?, status = ? WHERE id = ?');
251
+ const counts = { checked: rows.length, in_niche: 0, entered: 0, left: 0 };
252
+ d.exec('BEGIN');
253
+ try {
254
+ for (const r of rows) {
255
+ const m = nicheMatch(r, profile);
256
+ let status = r.status;
257
+ if (m.score > 0 && r.status === 'skipped') { status = 'new'; counts.entered++; }
258
+ else if (m.score === 0 && (r.status === 'new' || r.status === 'read')) { status = 'skipped'; counts.left++; }
259
+ if (m.score > 0) counts.in_niche++;
260
+ upd.run(m.score, m.score, JSON.stringify(m.niches), status, r.id);
261
+ }
262
+ d.exec('COMMIT');
263
+ } catch (e) {
264
+ d.exec('ROLLBACK');
265
+ throw e;
266
+ }
267
+ logRun('rescreen', true, counts);
268
+ return counts;
269
+ }
270
+
271
+ /* ----------------------------------------------------------------- the job -- */
272
+
273
+ let running = null;
274
+ export const crawlRunning = () => running;
275
+
276
+ /** Crawl a domain, index it, derive the profile, make it active, re-screen. One at a time. */
277
+ export async function buildProfile(domain, { maxPages, fetchPage, fetchSitemap, ai } = {}) {
278
+ if (running) return { status: 'already running', domain: running };
279
+ const host = hostOf(domain || activeProfile().domain || DEFAULT_PROFILE.domain);
280
+ running = host;
281
+ try {
282
+ const crawl = await crawlSite(host, { maxPages, ...(fetchPage ? { fetchPage } : {}), ...(fetchSitemap ? { fetchSitemap } : {}) });
283
+ if (!crawl.pages.length) throw new Error(`no readable pages on ${host}: ${crawl.errors.map((e) => e.error).slice(0, 3).join('; ') || 'nothing fetched'}`);
284
+ return await applyPages(host, crawl.pages, { ai, crawl });
285
+ } catch (e) {
286
+ logRun('profile', false, String(e?.message || e).slice(0, 300));
287
+ throw e;
288
+ } finally {
289
+ running = null;
290
+ }
291
+ }
292
+
293
+ /** Pages read elsewhere (the CLI's local c0mpute spider) -> index, derive, activate, re-screen. */
294
+ export async function applyPages(domain, pages, { ai = makeAi(), crawl = null } = {}) {
295
+ const host = hostOf(domain);
296
+ indexPages(host, pages);
297
+ const prev = activeProfile();
298
+ const derived = await deriveProfile(host, pages, { ai });
299
+ // Operator edits survive a re-crawl: niches they switched off stay off.
300
+ const off = new Set(prev.niches.filter((n) => n.enabled === false).map((n) => n.name.toLowerCase()));
301
+ derived.niches = derived.niches.map((n) => (off.has(n.name.toLowerCase()) ? { ...n, enabled: false } : n));
302
+ const profile = saveProfile(derived);
303
+ const screened = rescreen(profile);
304
+ const via = crawl?.via || pages.reduce((a, p) => ({ ...a, [p.via || 'pushed']: (a[p.via || 'pushed'] || 0) + 1 }), {});
305
+ const result = { domain: host, pages: pages.length, via, method: profile.method, niches: profile.niches.map((n) => n.name), screened, notes: crawl?.notes || [] };
306
+ logRun('profile', true, result);
307
+ return result;
308
+ }
package/src/propose.js CHANGED
@@ -25,7 +25,7 @@ export const ProposalSchema = z.object({
25
25
  questions_for_buyer: z.array(z.string()).default([]),
26
26
  });
27
27
 
28
- const SYSTEM = `You write government proposal DRAFTS for ${PROFILE.company} for a person to review. ${PROFILE.summary}
28
+ const system = () => `You write government proposal DRAFTS for ${PROFILE.company} for a person to review. ${PROFILE.summary}
29
29
  Rules:
30
30
  - Respond to the buyer's actual requirements; reuse their section names and requirement wording in the compliance matrix.
31
31
  - NEVER state a price, rate, discount or total. Pricing is only the structure (line items and units); a person fills in numbers.
@@ -151,7 +151,7 @@ export async function draftProposal(sol, docs, { ai, timeoutMs } = {}) {
151
151
  for (const part of PARTS) {
152
152
  try {
153
153
  const r = await ai.generateObject({
154
- system: SYSTEM,
154
+ system: system(),
155
155
  user: `${context}\n\n${part.ask}`,
156
156
  schema: part.schema,
157
157
  jsonSchema: z.toJSONSchema(part.schema),
package/src/server.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { serve } from '@hono/node-server';
2
2
  import { app } from './app.js';
3
+ import { bootProfile } from './pipeline.js';
3
4
  import { startDaemon, getDaemon } from './pipeline.js';
4
5
 
5
6
  const port = Number(process.env.PORT || 8080);
6
7
  const hostname = process.env.HOST || '0.0.0.0';
7
8
 
9
+ bootProfile();
8
10
  serve({ fetch: app.fetch, port, hostname }, () => {
9
11
  console.log(`gov-contracts listening on http://${hostname}:${port}`);
10
12
  startDaemon();
package/src/spider.js ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Spider: read a bidder's own website so the niche profile comes from what the
3
+ * company says it does, not a hand-written list.
4
+ *
5
+ * Pages are fetched through c0mpute's `crawl.fetch` workload first (house
6
+ * rule), either through a `c0mpute jobs serve` bridge (C0MPUTE_JOBS_URL +
7
+ * C0MPUTE_JOBS_TOKEN) or the local `c0mpute crawl fetch` CLI
8
+ * (C0MPUTE_CRAWL_CLI=1). When the network has no free crawl worker, or neither
9
+ * is configured, the page is read directly with the polite fetcher (robots.txt,
10
+ * public addresses only, one request at a time per host). Every page records
11
+ * which path read it.
12
+ *
13
+ * Same host only, sitemap first, then links, service/about pages first.
14
+ */
15
+ import { execFile } from 'node:child_process';
16
+ import { promisify } from 'node:util';
17
+ import { http, htmlToText } from './http.js';
18
+
19
+ const run = promisify(execFile);
20
+
21
+ export const DEFAULT_MAX_PAGES = 40;
22
+ const SKIP_EXT = /\.(png|jpe?g|gif|webp|avif|svg|ico|css|js|mjs|json|xml|rss|atom|pdf|zip|gz|tgz|mp3|mp4|webm|mov|woff2?|ttf|eot|txt|wasm)$/i;
23
+ const SKIP_PATH = /\/(api|auth|login|signin|signup|register|logout|signout|cart|checkout|account|admin|wp-admin|wp-json|feed|tag|tags|cdn-cgi)(\/|$)/i;
24
+ const PRIORITY = /(service|solution|about|capabilit|expertise|what-we-do|work|case-stud|portfolio|industr|consult|agentic|\bai\b|security|automation|product|offering|stack|team|company|government|public-sector|hire)/i;
25
+
26
+ /** "profullstack.com", "https://profullstack.com/x" -> https://profullstack.com/ */
27
+ export function siteRoot(domain) {
28
+ const raw = String(domain || '').trim();
29
+ if (!raw) throw new Error('domain required');
30
+ const u = new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`);
31
+ if (!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(u.hostname)) throw new Error(`not a public domain: ${u.hostname}`);
32
+ return new URL(`${u.protocol}//${u.host}/`);
33
+ }
34
+
35
+ const sameSite = (a, b) => a.replace(/^www\./, '') === b.replace(/^www\./, '');
36
+
37
+ /** Canonical form for de-duplication: no hash, no tracking query, no trailing slash. */
38
+ export function canonical(url) {
39
+ const u = new URL(url);
40
+ u.hash = '';
41
+ for (const k of [...u.searchParams.keys()]) if (/^(utm_|ref$|fbclid|gclid|mc_)/i.test(k)) u.searchParams.delete(k);
42
+ let s = u.toString();
43
+ if (s.endsWith('/') && u.pathname !== '/') s = s.slice(0, -1);
44
+ return s;
45
+ }
46
+
47
+ /** Same-site page links in an HTML document. */
48
+ export function extractLinks(html, base) {
49
+ const root = new URL(base);
50
+ const out = new Set();
51
+ for (const m of String(html || '').matchAll(/<a\b[^>]*?\bhref\s*=\s*(["'])(.*?)\1/gi)) {
52
+ const href = m[2].trim();
53
+ if (!href || /^(mailto|tel|javascript|data):/i.test(href) || href.startsWith('#')) continue;
54
+ let u;
55
+ try { u = new URL(href, root); } catch { continue; }
56
+ if (!/^https?:$/.test(u.protocol) || !sameSite(u.hostname, root.hostname)) continue;
57
+ if (SKIP_EXT.test(u.pathname) || SKIP_PATH.test(u.pathname)) continue;
58
+ if ([...u.searchParams.keys()].length > 2) continue;
59
+ out.add(canonical(u.toString()));
60
+ }
61
+ return [...out];
62
+ }
63
+
64
+ /** <loc> entries of a sitemap (or sitemap index). */
65
+ export function parseSitemap(xml) {
66
+ return [...String(xml || '').matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/gi)].map((m) => m[1].replace(/&amp;/g, '&'));
67
+ }
68
+
69
+ const tag = (html, re) => (re.exec(html)?.[1] || '').replace(/\s+/g, ' ').trim();
70
+
71
+ /** What the profile step needs from a page: title, description, headings, text. */
72
+ export function pageSummary(url, html) {
73
+ const title = htmlToText(tag(html, /<title[^>]*>([\s\S]*?)<\/title>/i)).slice(0, 200);
74
+ const description = htmlToText(
75
+ tag(html, /<meta[^>]+name=["']description["'][^>]+content=["']([^"']*)["']/i) || tag(html, /<meta[^>]+property=["']og:description["'][^>]+content=["']([^"']*)["']/i),
76
+ ).slice(0, 500);
77
+ const headings = [...String(html).matchAll(/<h[1-3][^>]*>([\s\S]*?)<\/h[1-3]>/gi)].map((m) => htmlToText(m[1]).replace(/\s+/g, ' ').trim()).filter(Boolean).slice(0, 30);
78
+ const main = /<main[\s\S]*?<\/main>/i.exec(html)?.[0] || String(html).replace(/<(nav|header|footer)[\s\S]*?<\/\1>/gi, ' ');
79
+ const text = htmlToText(main).slice(0, 12_000);
80
+ return { url, title, description, headings, text };
81
+ }
82
+
83
+ /* ------------------------------------------------------------ page fetchers -- */
84
+
85
+ /** crawl.fetch through a `c0mpute jobs serve` bridge. */
86
+ async function viaBridge(url, env) {
87
+ const timeoutMs = Number(env.C0MPUTE_CRAWL_TIMEOUT_MS || 25_000);
88
+ const r = await fetch(`${env.C0MPUTE_JOBS_URL.replace(/\/$/, '')}/v1/jobs`, {
89
+ method: 'POST',
90
+ headers: { authorization: `Bearer ${env.C0MPUTE_JOBS_TOKEN}`, 'content-type': 'application/json' },
91
+ body: JSON.stringify({ workload: 'crawl.fetch', spec: { v: 1, url, timeout_ms: Math.min(timeoutMs, 20_000) }, max_price: Number(env.C0MPUTE_CRAWL_MAX_PRICE || 0.01), timeout_ms: timeoutMs }),
92
+ signal: AbortSignal.timeout(timeoutMs + 5_000),
93
+ });
94
+ const j = await r.json().catch(() => ({}));
95
+ if (!r.ok) throw Object.assign(new Error(j.error || `bridge HTTP ${r.status}`), { busy: j.error === 'network_busy' || r.status === 503 });
96
+ const res = j.result || {};
97
+ if (!res.ok) throw new Error(res.error || 'crawl.fetch failed');
98
+ return { status: res.output?.status, body: typeof res.output?.body === 'string' ? res.output.body : '', worker: j.worker };
99
+ }
100
+
101
+ /** crawl.fetch through the local c0mpute CLI. */
102
+ async function viaCli(url, env) {
103
+ const secs = Math.ceil(Number(env.C0MPUTE_CRAWL_TIMEOUT_MS || 25_000) / 1000);
104
+ try {
105
+ const { stdout } = await run(env.C0MPUTE_BIN || 'c0mpute', ['crawl', 'fetch', url, '--max-price', String(env.C0MPUTE_CRAWL_MAX_PRICE || 0.01), '--timeout-secs', String(secs)], {
106
+ timeout: (secs + 15) * 1000, maxBuffer: 8_000_000, env: { ...process.env, RUST_LOG: 'error' },
107
+ });
108
+ const j = JSON.parse(stdout);
109
+ if (!j.ok) throw new Error(j.error || 'crawl.fetch failed');
110
+ return { status: j.output?.status, body: typeof j.output?.body === 'string' ? j.output.body : '' };
111
+ } catch (e) {
112
+ const msg = String(e?.stderr || e?.message || e);
113
+ throw Object.assign(new Error(/network_busy/.test(msg) ? 'network_busy' : msg.split('\n').filter(Boolean).pop()?.slice(0, 200) || 'c0mpute crawl failed'), { busy: /network_busy|NoPeers/.test(msg) });
114
+ }
115
+ }
116
+
117
+ export function c0mputeCrawlMode(env = process.env) {
118
+ if (env.C0MPUTE_CRAWL === '0') return null;
119
+ if (env.C0MPUTE_JOBS_URL && env.C0MPUTE_JOBS_TOKEN) return 'bridge';
120
+ if (env.C0MPUTE_CRAWL_CLI === '1') return 'cli';
121
+ return null;
122
+ }
123
+
124
+ /**
125
+ * A page fetcher that tries c0mpute, then reads directly. After the network
126
+ * says it is busy twice, the rest of this crawl goes direct (each busy answer
127
+ * costs ~45 s).
128
+ */
129
+ export function makePageFetcher(env = process.env) {
130
+ const mode = c0mputeCrawlMode(env);
131
+ let busy = 0;
132
+ const notes = [];
133
+ async function fetchPage(url) {
134
+ if (mode && busy < 2) {
135
+ try {
136
+ const r = mode === 'bridge' ? await viaBridge(url, env) : await viaCli(url, env);
137
+ if (r.status && r.status >= 400) throw new Error(`HTTP ${r.status}`);
138
+ busy = 0;
139
+ return { html: r.body, via: `c0mpute:${mode}` };
140
+ } catch (e) {
141
+ if (e.busy) busy++;
142
+ if (notes.length < 5) notes.push(`c0mpute ${mode}: ${String(e.message).slice(0, 160)}`);
143
+ }
144
+ }
145
+ const r = await http().text(url, { accept: 'text/html,application/xhtml+xml' });
146
+ if (r.status >= 400) throw new Error(`HTTP ${r.status}`);
147
+ return { html: r.text, via: 'direct' };
148
+ }
149
+ fetchPage.mode = mode;
150
+ fetchPage.notes = notes;
151
+ return fetchPage;
152
+ }
153
+
154
+ /**
155
+ * Crawl one site. Returns { root, pages: [{url, title, description, headings, text, via}], errors, via, notes }.
156
+ * `fetchPage(url) -> {html, via}` can be passed in (tests, the CLI).
157
+ */
158
+ const sitemapText = async (url) => {
159
+ const r = await http().text(url, { accept: 'application/xml,text/xml' });
160
+ return r.status < 400 ? r.text : '';
161
+ };
162
+
163
+ export async function crawlSite(domain, { maxPages = DEFAULT_MAX_PAGES, fetchPage = makePageFetcher(), fetchSitemap = sitemapText, onPage } = {}) {
164
+ const root = siteRoot(domain);
165
+ const cap = Math.max(1, Math.min(Number(maxPages) || DEFAULT_MAX_PAGES, 200));
166
+ const queue = [canonical(root.toString())];
167
+ const seen = new Set(queue);
168
+ const pages = [];
169
+ const errors = [];
170
+ const push = (u) => {
171
+ if (seen.has(u) || seen.size > cap * 6) return;
172
+ seen.add(u);
173
+ queue.push(u);
174
+ };
175
+
176
+ // Sitemap first: it lists the pages the owner thinks matter.
177
+ try {
178
+ const sm = await fetchSitemap(new URL('/sitemap.xml', root).toString());
179
+ if (sm) {
180
+ let locs = parseSitemap(sm);
181
+ const nested = locs.filter((l) => /\.xml(\?|$)/i.test(l)).slice(0, 3);
182
+ for (const n of nested) {
183
+ try { locs = locs.concat(parseSitemap(await fetchSitemap(n))); } catch { /* a missing child sitemap is fine */ }
184
+ }
185
+ for (const l of locs) {
186
+ try {
187
+ const u = new URL(l);
188
+ if (sameSite(u.hostname, root.hostname) && !SKIP_EXT.test(u.pathname) && !SKIP_PATH.test(u.pathname)) push(canonical(u.toString()));
189
+ } catch { /* skip bad loc */ }
190
+ }
191
+ }
192
+ } catch { /* no sitemap */ }
193
+
194
+ const next = () => {
195
+ // Service and about pages before blog posts.
196
+ const i = queue.findIndex((u) => PRIORITY.test(new URL(u).pathname));
197
+ return queue.splice(i >= 0 && pages.length > 0 ? i : 0, 1)[0];
198
+ };
199
+
200
+ while (queue.length && pages.length < cap) {
201
+ const url = next();
202
+ try {
203
+ const { html, via } = await fetchPage(url);
204
+ if (!/<html|<body|<title|<h1/i.test(html)) continue;
205
+ const p = { ...pageSummary(url, html), via };
206
+ if (p.text.length < 40 && !p.title) continue;
207
+ pages.push(p);
208
+ onPage?.(p);
209
+ for (const l of extractLinks(html, url)) push(l);
210
+ } catch (e) {
211
+ errors.push({ url, error: String(e?.message || e).slice(0, 200) });
212
+ if (errors.length > cap) break;
213
+ }
214
+ }
215
+ const via = {};
216
+ for (const p of pages) via[p.via] = (via[p.via] || 0) + 1;
217
+ return { root: root.toString(), pages, errors: errors.slice(0, 20), via, notes: fetchPage.notes || [] };
218
+ }