@profullstack/gov-contracts 0.0.0-stage → 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/LICENSE +9 -0
- package/README.md +78 -2
- package/bin/gov-contracts.js +225 -0
- package/package.json +50 -4
- package/src/ai.js +46 -0
- package/src/app.js +337 -0
- package/src/auth.js +109 -0
- package/src/fit.js +127 -0
- package/src/http.js +86 -0
- package/src/index.js +12 -0
- package/src/mcp.js +159 -0
- package/src/niche.js +196 -0
- package/src/pages.js +380 -0
- package/src/pipeline.js +141 -0
- package/src/profile.js +308 -0
- package/src/propose.js +260 -0
- package/src/safety.js +48 -0
- package/src/server.js +17 -0
- package/src/service.js +27 -0
- package/src/sources/digest.js +119 -0
- package/src/sources/index.js +59 -0
- package/src/sources/lacounty.js +100 -0
- package/src/sources/sam.js +178 -0
- package/src/spider.js +218 -0
- package/src/store.js +390 -0
- package/src/version.js +3 -0
package/src/app.js
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { descriptor } from '@profullstack/footer';
|
|
3
|
+
import { throttle } from '@profullstack/throttle/hono';
|
|
4
|
+
import { createGateway } from '@profullstack/x402-gateway';
|
|
5
|
+
import { SITE, me, mountAuth, operator } from './auth.js';
|
|
6
|
+
import { aiStatus } from './ai.js';
|
|
7
|
+
import { handleMcp, TOOL_NAMES } from './mcp.js';
|
|
8
|
+
import {
|
|
9
|
+
ICON, MANIFEST, SW, docsPage, homePage, messagePage, profilePage, proposalPage, queuePage, solicitationPage, solicitationsPage,
|
|
10
|
+
} from './pages.js';
|
|
11
|
+
import { applyPages, buildProfile, crawlRunning, getProfile, pagesFor, rescreen, saveProfile, searchPages } from './profile.js';
|
|
12
|
+
import { NICHE_LIBRARY } from './niche.js';
|
|
13
|
+
import { getDaemon, ingestDigest, ingestSource, workTick } from './pipeline.js';
|
|
14
|
+
import { publicSolicitation, startDraft } from './service.js';
|
|
15
|
+
import { listSources } from './sources/index.js';
|
|
16
|
+
import {
|
|
17
|
+
documentsFor, getIntervention, getProposal, getSolicitation, latestProposal, listInterventions, logRun, nicheCounts, openDb, resolveIntervention, searchSolicitations, stats,
|
|
18
|
+
} from './store.js';
|
|
19
|
+
import { HUMAN_ONLY } from './safety.js';
|
|
20
|
+
import { VERSION } from './version.js';
|
|
21
|
+
|
|
22
|
+
openDb();
|
|
23
|
+
export const app = new Hono();
|
|
24
|
+
|
|
25
|
+
/** The caller behind the pit.world relay and the c0mpute gateway: first X-Forwarded-For hop. */
|
|
26
|
+
function identify(request) {
|
|
27
|
+
const first = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
|
|
28
|
+
return first || 'local';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** $1 USDC day pass (CoinPay / x402) once a caller passes the free rate. Off until the CoinPay keys are set. */
|
|
32
|
+
function paywall(env = process.env) {
|
|
33
|
+
if (!env.COINPAY_X402_KEY || !env.CRAWL_PAY_TO) return null;
|
|
34
|
+
return createGateway({
|
|
35
|
+
siteUrl: SITE.replace(/\/$/, ''),
|
|
36
|
+
coinpay: { apiKey: env.COINPAY_X402_KEY },
|
|
37
|
+
payTo: env.CRAWL_PAY_TO,
|
|
38
|
+
priceCents: Number(env.PASS_PRICE_CENTS || 100),
|
|
39
|
+
passMinutes: 1440,
|
|
40
|
+
contact: 'mailto:hello@profullstack.com',
|
|
41
|
+
appPaths: ['/health', '/docs', '/llms.txt'],
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const gateway = paywall();
|
|
46
|
+
const limiter = throttle({
|
|
47
|
+
gateway: gateway || undefined,
|
|
48
|
+
limit: Number(process.env.RATE_LIMIT_PER_MIN || 60),
|
|
49
|
+
headroom: 1,
|
|
50
|
+
identify,
|
|
51
|
+
rules: [
|
|
52
|
+
{ path: '/health', open: true },
|
|
53
|
+
{ path: '/robots.txt', open: true },
|
|
54
|
+
{ path: '/llms.txt', open: true },
|
|
55
|
+
{ path: '/hooks/', open: true },
|
|
56
|
+
{ path: '/auth/', open: true },
|
|
57
|
+
{ path: '/sw.js', open: true },
|
|
58
|
+
{ path: '/icon.svg', open: true },
|
|
59
|
+
{ path: '/manifest.webmanifest', open: true },
|
|
60
|
+
],
|
|
61
|
+
});
|
|
62
|
+
// Operators are never metered.
|
|
63
|
+
app.use('*', (c, next) => (operator(c) ? next() : limiter(c, next)));
|
|
64
|
+
|
|
65
|
+
app.use('*', async (c, next) => {
|
|
66
|
+
await next();
|
|
67
|
+
c.header('x-content-type-options', 'nosniff');
|
|
68
|
+
c.header('referrer-policy', 'strict-origin-when-cross-origin');
|
|
69
|
+
if (c.req.path.startsWith('/api/') || c.req.path === '/mcp') {
|
|
70
|
+
c.header('access-control-allow-origin', '*');
|
|
71
|
+
c.header('access-control-allow-headers', 'content-type, authorization, mcp-session-id, mcp-protocol-version');
|
|
72
|
+
c.header('access-control-allow-methods', 'GET, POST, OPTIONS');
|
|
73
|
+
c.header('access-control-expose-headers', 'mcp-session-id');
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
app.options('/api/*', (c) => c.body(null, 204));
|
|
77
|
+
app.options('/mcp', (c) => c.body(null, 204));
|
|
78
|
+
|
|
79
|
+
mountAuth(app);
|
|
80
|
+
|
|
81
|
+
const html = async (c, p, status = 200) => {
|
|
82
|
+
c.header('cache-control', 'no-store');
|
|
83
|
+
return c.html(await p, status);
|
|
84
|
+
};
|
|
85
|
+
const needOperatorPage = async (c) => {
|
|
86
|
+
if (!me(c)) return c.redirect(`/signin?next=${encodeURIComponent(c.req.path)}`, 302);
|
|
87
|
+
const m = await messagePage({ title: 'Operators only', message: 'You are signed in with CoinPay, but this queue belongs to the bidder\'s operators. Ask an operator to add your CoinPay account.', signedIn: me(c), status: 403 });
|
|
88
|
+
return c.html(m.html, 403);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/* ------------------------------------------------------------------- pages -- */
|
|
92
|
+
|
|
93
|
+
app.get('/', (c) => {
|
|
94
|
+
const isOp = !!operator(c);
|
|
95
|
+
const top = searchSolicitations({ order: isOp ? 'fit' : 'new', niche: 'in', limit: 12 }).map((s) => publicSolicitation(s, isOp));
|
|
96
|
+
return html(c, homePage({ stats: stats(), top, signedIn: me(c), isOperator: isOp, error: c.req.query('signin_error') }));
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
app.get('/solicitations', (c) => {
|
|
100
|
+
const isOp = !!operator(c);
|
|
101
|
+
const { q, level, source } = c.req.query();
|
|
102
|
+
const niche = c.req.query('niche') ?? 'in';
|
|
103
|
+
const rows = searchSolicitations({ q, level, source, niche, order: isOp ? 'fit' : 'due', limit: 200 }).map((s) => publicSolicitation(s, isOp));
|
|
104
|
+
return html(c, solicitationsPage({ rows, q, level, source, niche, niches: nicheCounts(), profile: getProfile(), signedIn: me(c), isOperator: isOp }));
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
app.get('/s/:id', async (c) => {
|
|
108
|
+
const s = getSolicitation(c.req.param('id'));
|
|
109
|
+
if (!s) { const m = await messagePage({ title: 'Not found', message: 'No such solicitation.', status: 404 }); return c.html(m.html, 404); }
|
|
110
|
+
const isOp = !!operator(c);
|
|
111
|
+
return html(c, solicitationPage({ s: publicSolicitation(s, isOp), docs: documentsFor(s.id, { withText: false }), proposal: isOp ? latestProposal(s.id) : null, isOperator: isOp, signedIn: me(c) }));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
app.post('/s/:id/draft', async (c) => {
|
|
115
|
+
if (!operator(c)) return needOperatorPage(c);
|
|
116
|
+
try { startDraft(c.req.param('id')); } catch { return c.redirect('/queue', 303); }
|
|
117
|
+
return c.redirect(`/s/${encodeURIComponent(c.req.param('id'))}?drafting=1`, 303);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
app.get('/queue', (c) => {
|
|
121
|
+
const op = operator(c);
|
|
122
|
+
if (!op) return needOperatorPage(c);
|
|
123
|
+
const status = ['open', 'done', 'dismissed', 'all'].includes(c.req.query('status')) ? c.req.query('status') : 'open';
|
|
124
|
+
const niche = c.req.query('niche') || 'in';
|
|
125
|
+
const all = listInterventions({ status: 'all', niche, limit: 500 });
|
|
126
|
+
const counts = { open: 0, done: 0, dismissed: 0, all: all.length };
|
|
127
|
+
for (const i of all) counts[i.status]++;
|
|
128
|
+
const hidden = niche === 'all' ? 0 : listInterventions({ status, niche: 'all', limit: 500 }).length - (status === 'all' ? all.length : counts[status]);
|
|
129
|
+
return html(c, queuePage({ items: status === 'all' ? all : all.filter((i) => i.status === status), status, counts, niche, hidden, niches: nicheCounts(), profile: getProfile(), account: op }));
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
app.post('/queue/:id', async (c) => {
|
|
133
|
+
const op = operator(c);
|
|
134
|
+
if (!op) return needOperatorPage(c);
|
|
135
|
+
const form = await c.req.parseBody();
|
|
136
|
+
const r = resolveIntervention(c.req.param('id'), { status: String(form.status || ''), note: String(form.note || ''), by: op.coinpay_sub || op.id });
|
|
137
|
+
if (!r) return c.redirect('/queue', 303);
|
|
138
|
+
return c.redirect(`/queue#iv-${r.id}`, 303);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
app.get('/p/:id', async (c) => {
|
|
142
|
+
const op = operator(c);
|
|
143
|
+
if (!op) return needOperatorPage(c);
|
|
144
|
+
const raw = c.req.param('id');
|
|
145
|
+
const md = raw.endsWith('.md');
|
|
146
|
+
const p = getProposal(md ? raw.slice(0, -3) : raw);
|
|
147
|
+
if (!p) { const m = await messagePage({ title: 'Not found', message: 'No such proposal.', status: 404 }); return c.html(m.html, 404); }
|
|
148
|
+
if (md) {
|
|
149
|
+
c.header('content-type', 'text/markdown; charset=utf-8');
|
|
150
|
+
c.header('content-disposition', `attachment; filename="proposal-${p.id}-v${p.version}.md"`);
|
|
151
|
+
return c.body(p.markdown);
|
|
152
|
+
}
|
|
153
|
+
return html(c, proposalPage({ p, s: getSolicitation(p.solicitation_id), account: op }));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
app.get('/profile', (c) => {
|
|
157
|
+
const isOp = !!operator(c);
|
|
158
|
+
const p = getProfile();
|
|
159
|
+
return html(c, profilePage({ p, pages: pagesFor(p.domain || ''), running: crawlRunning(), library: NICHE_LIBRARY, isOperator: isOp, signedIn: me(c), notice: c.req.query('notice') }));
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
/** Start a crawl in the background; the page shows "reading" until it finishes. */
|
|
163
|
+
function startCrawl(domain, maxPages) {
|
|
164
|
+
if (crawlRunning()) return { status: 'already running', domain: crawlRunning() };
|
|
165
|
+
buildProfile(domain, { maxPages }).catch((e) => console.error('profile crawl failed', String(e?.message || e).slice(0, 200)));
|
|
166
|
+
return { status: 'crawling', domain, note: 'Reading the site, then deriving niches (1-5 minutes). GET /api/v1/profile for the result.' };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
app.post('/profile', async (c) => {
|
|
170
|
+
if (!operator(c)) return needOperatorPage(c);
|
|
171
|
+
const f = await c.req.parseBody({ all: true });
|
|
172
|
+
const one = (k) => (Array.isArray(f[k]) ? f[k][0] : f[k]);
|
|
173
|
+
if (one('action') === 'crawl') {
|
|
174
|
+
try { startCrawl(String(one('domain') || getProfile().domain || ''), Number(one('max_pages') || 40)); } catch (e) { return c.redirect(`/profile?notice=${encodeURIComponent(e.message)}`, 303); }
|
|
175
|
+
return c.redirect('/profile?notice=Reading+the+site', 303);
|
|
176
|
+
}
|
|
177
|
+
const cur = getProfile();
|
|
178
|
+
const on = new Set([].concat(f.enabled || []).map(String));
|
|
179
|
+
const niches = cur.niches.map((n, i) => ({ ...n, enabled: on.has(String(i)), keywords: String(one(`kw_${i}`) ?? n.keywords.join(', ')).split(',').map((x) => x.trim()).filter(Boolean) }));
|
|
180
|
+
const addName = String(one('new_name') || '').trim();
|
|
181
|
+
const addKw = String(one('new_keywords') || '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
182
|
+
const lib = NICHE_LIBRARY.find((l) => l.name === addName);
|
|
183
|
+
if (addName && (addKw.length || lib)) niches.push({ name: addName, keywords: addKw.length ? addKw : lib.keywords, enabled: true });
|
|
184
|
+
const p = saveProfile({
|
|
185
|
+
...cur, niches, source: cur.source?.startsWith('site:') ? `${cur.source}+edited` : cur.source,
|
|
186
|
+
naics: String(one('naics') ?? cur.naics.join(', ')).split(/[,\s]+/).filter(Boolean),
|
|
187
|
+
negative_keywords: String(one('negative') ?? cur.negative_keywords.join(', ')).split(',').map((x) => x.trim()).filter(Boolean),
|
|
188
|
+
});
|
|
189
|
+
const r = rescreen(p);
|
|
190
|
+
return c.redirect(`/profile?notice=${encodeURIComponent(`Saved. ${r.in_niche} of ${r.checked} open bids are in your niches (${r.entered} added, ${r.left} filtered out).`)}`, 303);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
app.get('/docs', (c) => html(c, docsPage({ signedIn: me(c) })));
|
|
194
|
+
|
|
195
|
+
/* --------------------------------------------------------------------- API -- */
|
|
196
|
+
|
|
197
|
+
const json = (c, data, status = 200) => c.json(data, status);
|
|
198
|
+
const needOp = (c) => json(c, { error: { code: 'operator_only', message: 'Send Authorization: Bearer <operator key>, or sign in as an operator.' } }, 401);
|
|
199
|
+
|
|
200
|
+
app.get('/api/v1/solicitations', (c) => {
|
|
201
|
+
const isOp = !!operator(c);
|
|
202
|
+
const { q, level, source, order, limit, offset, status, min_fit, niche } = c.req.query();
|
|
203
|
+
const rows = searchSolicitations({ q, level, source, niche, order: order || (isOp ? 'fit' : 'due'), limit, offset, status: isOp ? status : undefined, minFit: isOp && min_fit ? Number(min_fit) : null });
|
|
204
|
+
return json(c, { data: rows.map((s) => publicSolicitation(s, isOp)), meta: { count: rows.length, version: VERSION } });
|
|
205
|
+
});
|
|
206
|
+
app.get('/api/v1/solicitations/:id', (c) => {
|
|
207
|
+
const isOp = !!operator(c);
|
|
208
|
+
const s = getSolicitation(c.req.param('id'));
|
|
209
|
+
if (!s) return json(c, { error: { code: 'not_found' } }, 404);
|
|
210
|
+
const p = isOp ? latestProposal(s.id) : null;
|
|
211
|
+
return json(c, { data: { ...publicSolicitation(s, isOp), documents: documentsFor(s.id, { withText: false }), ...(p ? { proposal: { id: p.id, version: p.version, status: p.status } } : {}) } });
|
|
212
|
+
});
|
|
213
|
+
app.get('/api/v1/profile', (c) => {
|
|
214
|
+
const p = getProfile();
|
|
215
|
+
return json(c, { data: { ...p, crawling: crawlRunning(), niche_counts: nicheCounts(), ...(operator(c) ? { pages: pagesFor(p.domain || '') } : {}) } });
|
|
216
|
+
});
|
|
217
|
+
app.get('/api/v1/profile/search', (c) => json(c, { data: searchPages(c.req.query('q'), { limit: c.req.query('limit') }) }));
|
|
218
|
+
app.post('/api/v1/profile/crawl', async (c) => {
|
|
219
|
+
if (!operator(c)) return needOp(c);
|
|
220
|
+
const b = await c.req.json().catch(() => ({}));
|
|
221
|
+
try { return json(c, { data: startCrawl(String(b.domain || getProfile().domain || ''), Number(b.max_pages || 40)) }, 202); } catch (e) { return json(c, { error: { code: 'bad_request', message: e.message } }, 400); }
|
|
222
|
+
});
|
|
223
|
+
/** Pages read elsewhere (the CLI's local c0mpute spider): {domain, pages: [{url, title, description, headings, text, via}]}. */
|
|
224
|
+
app.post('/api/v1/profile/pages', async (c) => {
|
|
225
|
+
if (!operator(c)) return needOp(c);
|
|
226
|
+
const b = await c.req.json().catch(() => ({}));
|
|
227
|
+
const pages = Array.isArray(b.pages) ? b.pages.filter((p) => p && typeof p.url === 'string').slice(0, 200) : [];
|
|
228
|
+
if (!b.domain || !pages.length) return json(c, { error: { code: 'bad_request', message: 'Send {"domain": "...", "pages": [{"url", "title", "text", ...}]}' } }, 400);
|
|
229
|
+
if (crawlRunning()) return json(c, { error: { code: 'busy', message: `already reading ${crawlRunning()}` } }, 409);
|
|
230
|
+
try { return json(c, { data: await applyPages(String(b.domain), pages) }); } catch (e) { logRun('profile', false, String(e?.message || e).slice(0, 300)); return json(c, { error: { code: 'failed', message: String(e?.message || e).slice(0, 300) } }, 502); }
|
|
231
|
+
});
|
|
232
|
+
/** Edit: {niches?, naics?, negative_keywords?, not_a_fit?, summary?}. Re-screens open bids. */
|
|
233
|
+
app.put('/api/v1/profile', async (c) => {
|
|
234
|
+
if (!operator(c)) return needOp(c);
|
|
235
|
+
const b = await c.req.json().catch(() => ({}));
|
|
236
|
+
const cur = getProfile();
|
|
237
|
+
const p = saveProfile({ ...cur, ...['niches', 'naics', 'negative_keywords', 'not_a_fit', 'summary', 'capabilities', 'company'].reduce((a, k) => (b[k] !== undefined ? { ...a, [k]: b[k] } : a), {}), source: cur.source?.startsWith('site:') && !cur.source.endsWith('+edited') ? `${cur.source}+edited` : cur.source });
|
|
238
|
+
return json(c, { data: { profile: p, screened: rescreen(p) } });
|
|
239
|
+
});
|
|
240
|
+
app.get('/api/v1/sources', async (c) => json(c, { data: await listSources() }));
|
|
241
|
+
app.get('/api/v1/stats', (c) => json(c, { data: stats() }));
|
|
242
|
+
app.get('/api/v1/rules', (c) => json(c, { data: { human_only: HUMAN_ONLY } }));
|
|
243
|
+
|
|
244
|
+
app.get('/api/v1/interventions', (c) => {
|
|
245
|
+
if (!operator(c)) return needOp(c);
|
|
246
|
+
return json(c, { data: listInterventions({ status: c.req.query('status') || 'open', kind: c.req.query('kind'), niche: c.req.query('niche') || 'all' }) });
|
|
247
|
+
});
|
|
248
|
+
app.get('/api/v1/interventions/:id', (c) => {
|
|
249
|
+
if (!operator(c)) return needOp(c);
|
|
250
|
+
const iv = getIntervention(c.req.param('id'));
|
|
251
|
+
return iv ? json(c, { data: iv }) : json(c, { error: { code: 'not_found' } }, 404);
|
|
252
|
+
});
|
|
253
|
+
app.post('/api/v1/interventions/:id', async (c) => {
|
|
254
|
+
const op = operator(c);
|
|
255
|
+
if (!op) return needOp(c);
|
|
256
|
+
const body = await c.req.json().catch(() => ({}));
|
|
257
|
+
try {
|
|
258
|
+
const r = resolveIntervention(c.req.param('id'), { status: body.status, note: body.note, by: op.coinpay_sub || op.id });
|
|
259
|
+
return r ? json(c, { data: r }) : json(c, { error: { code: 'not_found' } }, 404);
|
|
260
|
+
} catch (e) {
|
|
261
|
+
return json(c, { error: { code: 'bad_request', message: e.message } }, 400);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
app.get('/api/v1/proposals/:id', (c) => {
|
|
265
|
+
if (!operator(c)) return needOp(c);
|
|
266
|
+
const p = getProposal(c.req.param('id')) || latestProposal(c.req.param('id'));
|
|
267
|
+
if (!p) return json(c, { error: { code: 'not_found' } }, 404);
|
|
268
|
+
if (c.req.query('format') === 'md') return c.body(p.markdown, 200, { 'content-type': 'text/markdown; charset=utf-8' });
|
|
269
|
+
return json(c, { data: p });
|
|
270
|
+
});
|
|
271
|
+
app.post('/api/v1/solicitations/:id/draft', (c) => {
|
|
272
|
+
if (!operator(c)) return needOp(c);
|
|
273
|
+
try { return json(c, { data: startDraft(c.req.param('id')) }, 202); } catch { return json(c, { error: { code: 'not_found' } }, 404); }
|
|
274
|
+
});
|
|
275
|
+
app.post('/api/v1/ingest/digest', async (c) => {
|
|
276
|
+
if (!operator(c)) return needOp(c);
|
|
277
|
+
const ct = c.req.header('content-type') || '';
|
|
278
|
+
const text = ct.includes('json') ? (await c.req.json().catch(() => ({}))).text : await c.req.text();
|
|
279
|
+
if (!text || String(text).length > 200_000) return json(c, { error: { code: 'bad_request', message: 'Send the digest body as {"text": "..."} or text/plain (max 200 KB).' } }, 400);
|
|
280
|
+
return json(c, { data: await ingestDigest(String(text)) });
|
|
281
|
+
});
|
|
282
|
+
app.post('/api/v1/run/:job', async (c) => {
|
|
283
|
+
if (!operator(c)) return needOp(c);
|
|
284
|
+
const job = c.req.param('job');
|
|
285
|
+
try {
|
|
286
|
+
if (job === 'work') return json(c, { data: await workTick() });
|
|
287
|
+
const m = /^ingest-(\w+)$/.exec(job);
|
|
288
|
+
if (m) return json(c, { data: await ingestSource(m[1]) });
|
|
289
|
+
if (job === 'profile') return json(c, { data: startCrawl(getProfile().domain || process.env.PROFILE_DOMAIN || 'profullstack.com', Number(process.env.PROFILE_MAX_PAGES || 40)) }, 202);
|
|
290
|
+
if (job === 'rescreen') return json(c, { data: rescreen() });
|
|
291
|
+
return json(c, { error: { code: 'not_found', message: 'jobs: ingest-sam, ingest-lacounty, work, profile, rescreen' } }, 404);
|
|
292
|
+
} catch (e) {
|
|
293
|
+
return json(c, { error: { code: 'job_failed', message: String(e?.message || e).slice(0, 300) } }, 502);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
app.get('/api/v1/daemon', async (c) => {
|
|
297
|
+
if (!operator(c)) return needOp(c);
|
|
298
|
+
const d = getDaemon();
|
|
299
|
+
return json(c, { data: d ? await d.status() : null, ai: aiStatus() });
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
app.all('/mcp', (c) => handleMcp(c.req.raw));
|
|
303
|
+
|
|
304
|
+
// CoinPay business webhook (payments are settled by the x402 gateway; this only acknowledges).
|
|
305
|
+
app.post('/hooks/coinpay', (c) => c.body(null, 204));
|
|
306
|
+
|
|
307
|
+
app.all('/api/*', (c) => json(c, { error: { code: 'not_found', message: 'See /docs#api' } }, 404));
|
|
308
|
+
|
|
309
|
+
/* ---------------------------------------------------------------- plumbing -- */
|
|
310
|
+
|
|
311
|
+
app.get('/health', (c) => c.json({ ok: true, version: VERSION }));
|
|
312
|
+
app.get('/manifest.webmanifest', (c) => c.body(JSON.stringify(MANIFEST), 200, { 'content-type': 'application/manifest+json' }));
|
|
313
|
+
app.get('/sw.js', (c) => c.body(SW, 200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache' }));
|
|
314
|
+
app.get('/icon.svg', (c) => c.body(ICON, 200, { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=86400' }));
|
|
315
|
+
app.get('/robots.txt', (c) => c.text('User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /queue\nDisallow: /p/\n'));
|
|
316
|
+
app.get('/.well-known/openwebring.json', (c) => c.json(descriptor({ site: SITE, name: 'gov.procurement', madeBy: 'both' })));
|
|
317
|
+
app.get('/llms.txt', (c) => c.text(`# gov.procurement
|
|
318
|
+
|
|
319
|
+
> Government contract opportunities (SAM.gov, County of Los Angeles, forwarded bid digests), read and scored for fit, with proposal drafts. Every submission, registration, signature, price and agency contact is a human step; the system never does them.
|
|
320
|
+
|
|
321
|
+
- API: ${SITE}api/v1/solicitations, ${SITE}api/v1/sources, ${SITE}api/v1/stats
|
|
322
|
+
- MCP: ${SITE}mcp (tools: ${TOOL_NAMES.join(', ')})
|
|
323
|
+
- CLI: npx @profullstack/gov-contracts
|
|
324
|
+
- Docs: ${SITE}docs
|
|
325
|
+
`));
|
|
326
|
+
app.get('/install.sh', (c) => c.body(`#!/bin/sh
|
|
327
|
+
# gov-contracts CLI + TUI. Needs Node 24+.
|
|
328
|
+
set -eu
|
|
329
|
+
if ! command -v node >/dev/null 2>&1; then echo "gov-contracts needs Node.js 24 or newer: https://nodejs.org" >&2; exit 1; fi
|
|
330
|
+
npm install -g @profullstack/gov-contracts@latest
|
|
331
|
+
echo "Installed. Try: gov-contracts search software"
|
|
332
|
+
`, 200, { 'content-type': 'text/x-shellscript; charset=utf-8' }));
|
|
333
|
+
|
|
334
|
+
app.notFound(async (c) => {
|
|
335
|
+
const m = await messagePage({ title: 'Not found', message: 'Nothing here. <a href="/">Home</a>', status: 404 });
|
|
336
|
+
return c.html(m.html, 404);
|
|
337
|
+
});
|
package/src/auth.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign in with CoinPay (OAuth 2.1, PKCE). Login = signup. Accounts bind to the
|
|
3
|
+
* CoinPay `sub` only, never the email (CoinPay never verifies it). Who may work
|
|
4
|
+
* the intervention queue is an allowlist of CoinPay subs (OPERATOR_SUBS), and
|
|
5
|
+
* scripts/CLI/MCP use the operator API key (OPERATOR_API_KEY) as a Bearer.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
8
|
+
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
|
9
|
+
import {
|
|
10
|
+
exchangeCoinPayCode, fetchCoinPayUserinfo, generateCoinPayPkcePair, generateCoinPayState, getCoinPayAuthorizeUrl, validateCoinPayState,
|
|
11
|
+
} from '@profullstack/stack/coinpay';
|
|
12
|
+
import { accountBySession, accountBySub, createAccount, createSession, deleteSession } from './store.js';
|
|
13
|
+
|
|
14
|
+
export const SITE = (process.env.SITE_URL || 'https://gov.procurement.pit.world').replace(/\/$/, '') + '/';
|
|
15
|
+
const COOKIE = 'gc_session';
|
|
16
|
+
const STATE_COOKIE = 'gc_oauth';
|
|
17
|
+
|
|
18
|
+
const oauthReady = () => !!(process.env.COINPAY_OAUTH_CLIENT_ID && process.env.COINPAY_OAUTH_CLIENT_SECRET);
|
|
19
|
+
const issuer = () => (process.env.COINPAY_OAUTH_ISSUER || 'https://coinpayportal.com').replace(/\/$/, '');
|
|
20
|
+
const redirectUri = () => `${SITE}auth/coinpay/callback`;
|
|
21
|
+
const operatorSubs = () => new Set(String(process.env.OPERATOR_SUBS || '').split(',').map((s) => s.trim()).filter(Boolean));
|
|
22
|
+
/** Same-site paths only, so `next` can never send someone off-site. */
|
|
23
|
+
export const safeNext = (n) => (typeof n === 'string' && /^\/(?!\/)[^\s\\]*$/.test(n) ? n : '/queue');
|
|
24
|
+
const withParam = (path, k, v) => `${path}${path.includes('?') ? '&' : '?'}${k}=${encodeURIComponent(v)}`;
|
|
25
|
+
|
|
26
|
+
const sameKey = (a, b) => {
|
|
27
|
+
const x = createHash('sha256').update(String(a)).digest();
|
|
28
|
+
const y = createHash('sha256').update(String(b)).digest();
|
|
29
|
+
return timingSafeEqual(x, y);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** The signed-in person (session cookie), or null. */
|
|
33
|
+
export function me(c) {
|
|
34
|
+
return accountBySession(getCookie(c, COOKIE));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Operator = the API key as Bearer, or a signed-in CoinPay sub on the allowlist. */
|
|
38
|
+
export function operator(c) {
|
|
39
|
+
const key = process.env.OPERATOR_API_KEY;
|
|
40
|
+
const m = /^Bearer\s+(\S+)$/i.exec(c.req.header('authorization') || '');
|
|
41
|
+
if (key && m && sameKey(m[1], key)) return { id: 'api-key', name: 'operator key', via: 'key' };
|
|
42
|
+
const a = me(c);
|
|
43
|
+
if (a && operatorSubs().has(a.coinpay_sub)) return { ...a, via: 'coinpay' };
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function bearerIsOperator(authHeader) {
|
|
48
|
+
const key = process.env.OPERATOR_API_KEY;
|
|
49
|
+
const m = /^Bearer\s+(\S+)$/i.exec(authHeader || '');
|
|
50
|
+
return !!(key && m && sameKey(m[1], key));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function mountAuth(app, { fetch: fetchImpl } = {}) {
|
|
54
|
+
app.get('/signin', (c) => c.redirect(`/auth/coinpay?next=${encodeURIComponent(safeNext(c.req.query('next')))}`, 302));
|
|
55
|
+
|
|
56
|
+
app.get('/auth/coinpay', (c) => {
|
|
57
|
+
const next = safeNext(c.req.query('next'));
|
|
58
|
+
if (!oauthReady()) return c.redirect(withParam('/', 'signin_error', 'Sign-in with CoinPay is not set up yet.'), 302);
|
|
59
|
+
const state = generateCoinPayState();
|
|
60
|
+
const { codeVerifier, codeChallenge } = generateCoinPayPkcePair();
|
|
61
|
+
setCookie(c, STATE_COOKIE, Buffer.from(JSON.stringify({ state, codeVerifier, next })).toString('base64url'), {
|
|
62
|
+
path: '/auth/coinpay', httpOnly: true, secure: SITE.startsWith('https:'), sameSite: 'Lax', maxAge: 600,
|
|
63
|
+
});
|
|
64
|
+
c.header('cache-control', 'no-store');
|
|
65
|
+
return c.redirect(getCoinPayAuthorizeUrl({
|
|
66
|
+
clientId: process.env.COINPAY_OAUTH_CLIENT_ID, redirectUri: redirectUri(), state, codeChallenge, issuer: issuer(), scopes: ['openid', 'profile'],
|
|
67
|
+
}), 302);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
app.get('/auth/coinpay/callback', async (c) => {
|
|
71
|
+
let saved = {};
|
|
72
|
+
try { saved = JSON.parse(Buffer.from(getCookie(c, STATE_COOKIE) || '', 'base64url').toString()); } catch { saved = {}; }
|
|
73
|
+
deleteCookie(c, STATE_COOKIE, { path: '/auth/coinpay' });
|
|
74
|
+
c.header('cache-control', 'no-store');
|
|
75
|
+
const next = safeNext(saved.next);
|
|
76
|
+
const fail = (msg) => c.redirect(withParam('/', 'signin_error', msg), 302);
|
|
77
|
+
if (!oauthReady()) return fail('Sign-in with CoinPay is not set up yet.');
|
|
78
|
+
if (c.req.query('error')) return fail('CoinPay sign-in was cancelled.');
|
|
79
|
+
const code = c.req.query('code');
|
|
80
|
+
if (!code || !validateCoinPayState(c.req.query('state'), saved.state)) return fail('That sign-in link expired. Please try again.');
|
|
81
|
+
let claims;
|
|
82
|
+
try {
|
|
83
|
+
const tokens = await exchangeCoinPayCode({
|
|
84
|
+
code, redirectUri: redirectUri(), clientId: process.env.COINPAY_OAUTH_CLIENT_ID, clientSecret: process.env.COINPAY_OAUTH_CLIENT_SECRET,
|
|
85
|
+
codeVerifier: saved.codeVerifier, issuer: issuer(), ...(fetchImpl ? { fetch: fetchImpl } : {}),
|
|
86
|
+
});
|
|
87
|
+
claims = await fetchCoinPayUserinfo({ accessToken: tokens.access_token, issuer: issuer(), ...(fetchImpl ? { fetch: fetchImpl } : {}) });
|
|
88
|
+
} catch (e) {
|
|
89
|
+
console.error('coinpay sign-in failed', String(e?.message || e).slice(0, 200));
|
|
90
|
+
return fail('CoinPay sign-in did not finish. Please try again.');
|
|
91
|
+
}
|
|
92
|
+
const sub = String(claims?.sub || '');
|
|
93
|
+
if (!sub) return fail('CoinPay did not say who you are. Please try again.');
|
|
94
|
+
// Bind by sub only; the email is never looked at.
|
|
95
|
+
const account = accountBySub(sub) || createAccount(sub, String(claims.name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60) || 'CoinPay user');
|
|
96
|
+
deleteSession(getCookie(c, COOKIE));
|
|
97
|
+
setCookie(c, COOKIE, createSession(account.id), { path: '/', httpOnly: true, secure: SITE.startsWith('https:'), sameSite: 'Lax', maxAge: 90 * 86400 });
|
|
98
|
+
return c.redirect(next, 302);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const signout = (c) => {
|
|
102
|
+
deleteSession(getCookie(c, COOKIE));
|
|
103
|
+
deleteCookie(c, COOKIE, { path: '/' });
|
|
104
|
+
c.header('cache-control', 'no-store');
|
|
105
|
+
return c.req.method === 'GET' ? c.redirect('/', 302) : c.json({ ok: true });
|
|
106
|
+
};
|
|
107
|
+
app.get('/signout', signout);
|
|
108
|
+
app.post('/signout', signout);
|
|
109
|
+
}
|
package/src/fit.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fit: how well a solicitation matches what the bidder actually does.
|
|
3
|
+
*
|
|
4
|
+
* Two passes. `prefilter` is a free keyword pass over the title and summary so
|
|
5
|
+
* a county's 200 gift-card and janitorial bids never reach a model. Anything
|
|
6
|
+
* that passes goes to `scoreFit`, where the model reads the notice and the RFP
|
|
7
|
+
* documents and answers in a fixed JSON shape; without a model the keyword
|
|
8
|
+
* score stands in, marked as such.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
import { activeProfile, nicheMatch, profileBrief } from './niche.js';
|
|
12
|
+
|
|
13
|
+
/** The active niche profile (niche.js; derived from the bidder's website by profile.js). */
|
|
14
|
+
export const PROFILE = new Proxy({}, { get: (_, k) => activeProfile()[k] });
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 0 = skip, higher = more likely a fit. Cheap and deterministic, whole words
|
|
18
|
+
* only, against the active niche profile. Nothing passes without a niche
|
|
19
|
+
* keyword in the title or one of our NAICS codes.
|
|
20
|
+
*/
|
|
21
|
+
export function prefilter(sol = {}, profile = activeProfile()) {
|
|
22
|
+
return nicheMatch(sol, profile).score;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const FitSchema = z.object({
|
|
26
|
+
score: z.number().min(0).max(100),
|
|
27
|
+
verdict: z.enum(['bid', 'maybe', 'no_bid']),
|
|
28
|
+
summary: z.string(),
|
|
29
|
+
why: z.array(z.string()).default([]),
|
|
30
|
+
risks: z.array(z.string()).default([]),
|
|
31
|
+
requirements: z.array(z.string()).default([]),
|
|
32
|
+
forms: z.array(z.string()).default([]),
|
|
33
|
+
vendor_registration: z.array(z.string()).default([]),
|
|
34
|
+
set_aside_ok: z.boolean().nullable().default(null),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const system = () => `You are a capture manager deciding whether a small company should bid on a government solicitation.
|
|
38
|
+
${profileBrief()}
|
|
39
|
+
Read the solicitation and documents. Be strict. Renewing or reselling a named product's licenses or maintenance needs an authorized reseller: score those under 40. Score 70+ only when the work is clearly something the company does and it can legally bid (set-asides, reseller authorizations, clearances, on-site requirements).
|
|
40
|
+
List the mandatory requirements, every form or certification the buyer requires (ONLY names written in the text; never invent form names or numbers), and any vendor registration needed to bid (for example SAM.gov UEI, Cal eProcure supplier ID, the county's own vendor portal).
|
|
41
|
+
Answer with JSON only.`;
|
|
42
|
+
|
|
43
|
+
const clip = (s, n) => (s && s.length > n ? `${s.slice(0, n)}\n[...truncated]` : s || '');
|
|
44
|
+
|
|
45
|
+
export function fitPrompt(sol, docs = []) {
|
|
46
|
+
const docText = docs
|
|
47
|
+
.filter((d) => d.text)
|
|
48
|
+
.map((d) => `--- ${d.kind === 'notice' ? 'Notice' : 'Document'}: ${d.name || d.url}\n${clip(d.text, 3000)}`)
|
|
49
|
+
.join('\n\n');
|
|
50
|
+
return clip(
|
|
51
|
+
`Solicitation: ${sol.title}
|
|
52
|
+
Number: ${sol.number || 'n/a'}
|
|
53
|
+
Buyer: ${sol.agency || 'n/a'} (${sol.level || 'n/a'}${sol.region ? ', ' + sol.region : ''})
|
|
54
|
+
Type: ${sol.notice_type || 'n/a'}
|
|
55
|
+
Due: ${sol.due_at || 'n/a'}
|
|
56
|
+
NAICS: ${sol.naics || 'n/a'} Set-aside: ${sol.set_aside || 'none stated'}
|
|
57
|
+
Link: ${sol.url || 'n/a'}
|
|
58
|
+
|
|
59
|
+
${clip(sol.description, 2500)}
|
|
60
|
+
|
|
61
|
+
${docText}`,
|
|
62
|
+
7000,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const RESALE = /\b(renewal|subscriptions?|maintenance|licens(e|es|ing)|brand[ -](only|specific|name)|support renewal|accelerators?)\b/i;
|
|
67
|
+
const SERVICE_WORK = /\b(develop\w*|implement\w*|integrat\w*|moderniz\w*|replacement|solution|configuration|enhancement|services? (rfp|request)|case management|on-call it|consult\w*|sustainment|operations)\b/i;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Buying a named product's licenses, renewal or maintenance needs an authorized
|
|
71
|
+
* reseller, which the bidder is not by default: cap the score and say why.
|
|
72
|
+
* Small models rate these as "software, so a fit" every time.
|
|
73
|
+
*/
|
|
74
|
+
export function capResale(sol, fit) {
|
|
75
|
+
const t = String(sol.title || '');
|
|
76
|
+
if (!RESALE.test(t) || SERVICE_WORK.test(t)) return fit;
|
|
77
|
+
if (fit.score <= 45) return fit;
|
|
78
|
+
return {
|
|
79
|
+
...fit,
|
|
80
|
+
score: 45,
|
|
81
|
+
verdict: fit.verdict === 'bid' ? 'maybe' : fit.verdict,
|
|
82
|
+
risks: [...(fit.risks || []), 'Looks like a license/renewal/maintenance buy of a named product: usually needs an authorized reseller agreement. Capped at 45.'],
|
|
83
|
+
capped: 'resale',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Keyword-only fit, used when no model answered. */
|
|
88
|
+
export function keywordFit(sol) {
|
|
89
|
+
const p = sol.prefilter ?? prefilter(sol);
|
|
90
|
+
const score = Math.min(60, p * 4);
|
|
91
|
+
return {
|
|
92
|
+
score,
|
|
93
|
+
verdict: score >= 40 ? 'maybe' : 'no_bid',
|
|
94
|
+
summary: 'Keyword match only (no AI read yet). Read the solicitation before deciding.',
|
|
95
|
+
why: [],
|
|
96
|
+
risks: ['Not read by a model; score is keyword based.'],
|
|
97
|
+
requirements: [],
|
|
98
|
+
forms: [],
|
|
99
|
+
vendor_registration: [],
|
|
100
|
+
set_aside_ok: null,
|
|
101
|
+
method: 'keywords',
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Score one solicitation. `ai` is an object with generateObject (an AiRouter or
|
|
107
|
+
* the module); without it, or when every provider fails, the keyword fit is used.
|
|
108
|
+
*/
|
|
109
|
+
export async function scoreFit(sol, docs, { ai, timeoutMs } = {}) {
|
|
110
|
+
if (!ai) return keywordFit(sol);
|
|
111
|
+
try {
|
|
112
|
+
const r = await ai.generateObject({
|
|
113
|
+
system: system(),
|
|
114
|
+
user: fitPrompt(sol, docs),
|
|
115
|
+
schema: FitSchema,
|
|
116
|
+
jsonSchema: z.toJSONSchema(FitSchema),
|
|
117
|
+
name: 'fit',
|
|
118
|
+
feature: 'gov-contracts:fit',
|
|
119
|
+
maxTokens: 1800,
|
|
120
|
+
temperature: 0.2,
|
|
121
|
+
...(timeoutMs ? { timeoutMs } : {}),
|
|
122
|
+
});
|
|
123
|
+
return capResale(sol, { ...r.object, score: Math.round(r.object.score), method: 'ai', provider: r.provider, model: r.model });
|
|
124
|
+
} catch (e) {
|
|
125
|
+
return { ...keywordFit(sol), ai_error: String(e?.message || e).slice(0, 300) };
|
|
126
|
+
}
|
|
127
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Polite, read-only fetching. Page and JSON reads go through
|
|
3
|
+
* @profullstack/scraper-daemon's fetcher (robots.txt, one request at a time per
|
|
4
|
+
* host with a delay, 429 hold-back, public addresses only, size and time caps).
|
|
5
|
+
* Binary RFP files (PDFs) need bytes, which that fetcher does not return, so
|
|
6
|
+
* `fetchBytes` reads them under the same rules, from READ_ONLY_HOSTS only.
|
|
7
|
+
*/
|
|
8
|
+
import { createFetcher, hostGate, isPublicAddress } from '@profullstack/scraper-daemon';
|
|
9
|
+
import { lookup } from 'node:dns/promises';
|
|
10
|
+
import { READ_ONLY_HOSTS } from './safety.js';
|
|
11
|
+
import { VERSION } from './version.js';
|
|
12
|
+
|
|
13
|
+
export const USER_AGENT = `gov-contracts/${VERSION} (+https://gov.procurement.pit.world; read-only)`;
|
|
14
|
+
|
|
15
|
+
const gate = hostGate({ delayMs: Number(process.env.FETCH_DELAY_MS || 2000) });
|
|
16
|
+
let fetcher;
|
|
17
|
+
export function http() {
|
|
18
|
+
fetcher ??= createFetcher({ userAgent: USER_AGENT, gate, timeoutMs: 30_000, maxBytes: 4_000_000 });
|
|
19
|
+
return fetcher;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const allowedHost = (host) => READ_ONLY_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
|
|
23
|
+
|
|
24
|
+
/** GET a file's bytes. Follows redirects (re-checking each hop), 4 MB and 45 s caps. */
|
|
25
|
+
export async function fetchBytes(url, { maxBytes = 4_000_000, timeoutMs = 45_000 } = {}) {
|
|
26
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
27
|
+
let at = url;
|
|
28
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
29
|
+
const u = new URL(at);
|
|
30
|
+
if (u.protocol !== 'https:' || !allowedHost(u.hostname)) throw new Error(`not a read-only source host: ${u.hostname}`);
|
|
31
|
+
const addrs = await lookup(u.hostname, { all: true });
|
|
32
|
+
if (!addrs.length || !addrs.every((a) => isPublicAddress(a.address))) throw new Error(`refusing non-public address for ${u.hostname}`);
|
|
33
|
+
const res = await gate.run(u.host, () => fetch(u, { redirect: 'manual', signal: deadline, headers: { 'user-agent': USER_AGENT } }));
|
|
34
|
+
if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
|
|
35
|
+
res.body?.cancel().catch(() => {});
|
|
36
|
+
at = new URL(res.headers.get('location'), u).toString();
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!res.ok) {
|
|
40
|
+
res.body?.cancel().catch(() => {});
|
|
41
|
+
throw new Error(`${res.status} from ${u.hostname}`);
|
|
42
|
+
}
|
|
43
|
+
const len = Number(res.headers.get('content-length') || 0);
|
|
44
|
+
if (len > maxBytes) {
|
|
45
|
+
res.body?.cancel().catch(() => {});
|
|
46
|
+
throw new Error(`file too large (${len} bytes)`);
|
|
47
|
+
}
|
|
48
|
+
const chunks = [];
|
|
49
|
+
let total = 0;
|
|
50
|
+
for await (const chunk of res.body) {
|
|
51
|
+
total += chunk.length;
|
|
52
|
+
if (total > maxBytes) throw new Error('file too large');
|
|
53
|
+
chunks.push(chunk);
|
|
54
|
+
}
|
|
55
|
+
return { bytes: Buffer.concat(chunks), type: res.headers.get('content-type') || '', url: at };
|
|
56
|
+
}
|
|
57
|
+
throw new Error('too many redirects');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Plain text from HTML: drop scripts/styles/tags, decode the common entities, squeeze whitespace. */
|
|
61
|
+
export function htmlToText(html) {
|
|
62
|
+
return String(html || '')
|
|
63
|
+
.replace(/<(script|style)[\s\S]*?<\/\1>/gi, ' ')
|
|
64
|
+
.replace(/<br\s*\/?>|<\/p>|<\/li>|<\/h\d>/gi, '\n')
|
|
65
|
+
.replace(/<[^>]+>/g, ' ')
|
|
66
|
+
.replace(/ /g, ' ')
|
|
67
|
+
.replace(/&/g, '&')
|
|
68
|
+
.replace(/</g, '<')
|
|
69
|
+
.replace(/>/g, '>')
|
|
70
|
+
.replace(/"/g, '"')
|
|
71
|
+
.replace(/'|’|‘/g, "'")
|
|
72
|
+
.replace(/“|”/g, '"')
|
|
73
|
+
.replace(/–|—/g, '-')
|
|
74
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)))
|
|
75
|
+
.replace(/[ \t\f\v]+/g, ' ')
|
|
76
|
+
.replace(/\s*\n\s*/g, '\n')
|
|
77
|
+
.trim();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Text from a PDF (unpdf, pure JS). Returns '' for scanned PDFs with no text layer. */
|
|
81
|
+
export async function pdfText(bytes, maxChars = 60_000) {
|
|
82
|
+
const { extractText, getDocumentProxy } = await import('unpdf');
|
|
83
|
+
const pdf = await getDocumentProxy(new Uint8Array(bytes));
|
|
84
|
+
const { text } = await extractText(pdf, { mergePages: true });
|
|
85
|
+
return String(text || '').replace(/[ \t]+/g, ' ').slice(0, maxChars);
|
|
86
|
+
}
|