Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/connectors/firecrawl.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Client Firecrawl v2 (scrape / search / map) : timeouts, réessais, rythme par44 * domaine, hachage du contenu. Clé côté serveur uniquement (FIRECRAWL_API_KEY).45 * Aucun appel n'est fait depuis le chemin utilisateur.46 */47import { createHash } from "crypto";4849const API = "https://api.firecrawl.dev/v2";5051export interface ScrapeResult {52 markdown: string;53 metadata: Record<string, unknown>;54 statusCode: number | null;55 links: string[];56}5758export interface SearchHit {59 url: string;60 title: string;61 description: string;62}6364export class FirecrawlError extends Error {65 constructor(message: string, public readonly status: number | null, public readonly url: string) {66 super(message);67 this.name = "FirecrawlError";68 }69}7071/* --------------------------------------------------------- rythme par domaine */7273const lastCall = new Map<string, number>();74const inflight = new Map<string, number>();7576function domainOf(url: string): string {77 try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return "unknown"; }78}7980const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));8182/** Attend le créneau libre pour un domaine (rythme minimal + concurrence). */83export async function throttle(domain: string, minGapMs: number, concurrency: number): Promise<() => void> {84 for (;;) {85 const now = Date.now();86 const last = lastCall.get(domain) ?? 0;87 const busy = inflight.get(domain) ?? 0;88 if (busy < concurrency && now - last >= minGapMs) {89 lastCall.set(domain, now);90 inflight.set(domain, busy + 1);91 return () => inflight.set(domain, Math.max(0, (inflight.get(domain) ?? 1) - 1));92 }93 await sleep(Math.max(50, minGapMs - (now - last)));94 }95}9697/* ------------------------------------------------------------------ client */9899export function firecrawlKey(): string {100 const k = process.env.FIRECRAWL_API_KEY;101 if (!k) throw new FirecrawlError("FIRECRAWL_API_KEY manquante (serveur)", null, API);102 return k;103}104105async function post<T>(path: string, body: unknown, timeoutMs: number, retries: number): Promise<T> {106 let lastErr: unknown = null;107 for (let attempt = 0; attempt <= retries; attempt++) {108 const ctrl = new AbortController();109 const t = setTimeout(() => ctrl.abort(), timeoutMs);110 try {111 const res = await fetch(`${API}${path}`, { method: "POST", headers: { Authorization: `Bearer ${firecrawlKey()}`, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: ctrl.signal });112 const json = (await res.json().catch(() => ({}))) as { success?: boolean; error?: string; data?: T };113 if (res.status === 429 || res.status >= 500) throw new FirecrawlError(`HTTP ${res.status} ${json.error ?? ""}`.trim(), res.status, path);114 if (!res.ok || json.success === false) throw new FirecrawlError(json.error ?? `HTTP ${res.status}`, res.status, path);115 return json.data as T;116 } catch (e) {117 lastErr = e;118 const status = e instanceof FirecrawlError ? e.status : null;119 const retriable = status == null || status === 429 || status >= 500;120 if (!retriable || attempt === retries) break;121 await sleep(1500 * 2 ** attempt);122 } finally {123 clearTimeout(t);124 }125 }126 if (lastErr instanceof Error && lastErr.name === "AbortError") throw new FirecrawlError("délai dépassé", null, path);127 throw lastErr instanceof Error ? lastErr : new FirecrawlError(String(lastErr), null, path);128}129130export interface ScrapeOptions { timeoutMs?: number; retries?: number; rateLimitMs?: number; concurrency?: number; links?: boolean }131132export async function scrape(url: string, o: ScrapeOptions = {}): Promise<ScrapeResult> {133 const release = await throttle(domainOf(url), o.rateLimitMs ?? 1000, o.concurrency ?? 2);134 try {135 const formats = o.links ? ["markdown", "links"] : ["markdown"];136 const data = await post<{ markdown?: string; metadata?: Record<string, unknown>; links?: string[] }>("/scrape", { url, formats, onlyMainContent: true }, o.timeoutMs ?? 90_000, o.retries ?? 2);137 const md = data?.metadata ?? {};138 const sc = typeof md.statusCode === "number" ? md.statusCode : null;139 return { markdown: data?.markdown ?? "", metadata: md, statusCode: sc, links: data?.links ?? [] };140 } finally {141 release();142 }143}144145export async function search(query: string, limit = 5, o: ScrapeOptions = {}): Promise<SearchHit[]> {146 const release = await throttle("api.firecrawl.dev/search", o.rateLimitMs ?? 1000, o.concurrency ?? 2);147 try {148 const data = await post<{ web?: { url: string; title?: string; description?: string }[] }>("/search", { query, limit }, o.timeoutMs ?? 60_000, o.retries ?? 2);149 return (data?.web ?? []).map((h) => ({ url: h.url, title: h.title ?? "", description: h.description ?? "" }));150 } finally {151 release();152 }153}154155export async function mapSite(url: string, searchTerm?: string, limit = 50, o: ScrapeOptions = {}): Promise<string[]> {156 const release = await throttle(domainOf(url), o.rateLimitMs ?? 1000, o.concurrency ?? 1);157 try {158 const data = await post<{ links?: { url: string }[] | string[] }>("/map", { url, search: searchTerm, limit }, o.timeoutMs ?? 60_000, o.retries ?? 1);159 return (data?.links ?? []).map((l) => (typeof l === "string" ? l : l.url));160 } finally {161 release();162 }163}164165/** Hachage stable du contenu utile (markdown normalisé) pour la détection de changement. */166export function contentHash(markdown: string, extra: Record<string, unknown> = {}): string {167 const norm = markdown.replace(/\s+/g, " ").trim();168 return createHash("sha256").update(norm).update(JSON.stringify(extra)).digest("hex");169}170171/** Parse « 5,98 $ », « $6.98 », « 1 234,50 » → nombre ; null si impossible. */172export function parseMoney(s: unknown): number | null {173 if (typeof s === "number") return Number.isFinite(s) ? s : null;174 if (typeof s !== "string") return null;175 const m = s.replace(/ /g, " ").match(/-?\d[\d\s]*(?:[.,]\d+)?/);176 if (!m) return null;177 const v = Number(m[0].replace(/\s/g, "").replace(",", "."));178 return Number.isFinite(v) ? v : null;179}180