/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * `bxc extract --schema ` — typed records from pages via * learned CSS selectors, cached per registrable domain (see docs/EXTRACT.md). */ import { existsSync } from "node:fs"; import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { EXIT, type CommonOptions, logger, parseCommonArgs } from "./shared.ts"; import type { ExtractUrlResult, FetchProfile, LlmFallback } from "../extract/index.ts"; interface ExtractCliOptions extends CommonOptions { schema: string; urls: string[]; profile: FetchProfile; format: "json" | "jsonl"; cache: boolean; cachePath?: string; concurrency: number; llm?: "gemini"; escalate: boolean; selectors: boolean; baseUrl?: string; minConfidence?: number; } const PROFILES: ReadonlySet = new Set(["static", "http", "fast", "stealth", "max"]); function printUsage(): void { Bun.stdout.write( `bxc extract — typed JSON records from pages (learned selectors, no LLM by default) Usage: bxc extract --schema [options] Schema: JSON Schema subset ({type:"object",properties} or {type:"array",items:{...}}) or shorthand: '[{"title":"string","price":"number?","url":"uri"}]' (array = record list) Options: --schema schema file path or inline JSON (required) --profile http (default) | static | fast | stealth | max --format json (default, array) | jsonl (one object per line) --concurrency URLs processed in parallel (default 8) --no-cache do not read or write the per-domain selector cache --cache-path selector cache SQLite file (default: domain memory database) --no-escalate do not escalate profiles when the page looks blocked --llm gemini fill unresolved required fields with Gemini (cookie session) --min-confidence locator confidence below which a field is unresolved (default 0.3) --base-url base URL for local files (link resolution + cache key) --selectors include the learned extraction plan in the output --help, -h this help Output (per URL): {"url","source","confidence","data","missingFields"} `, ); } function parseArgs(argv: readonly string[], base: CommonOptions): ExtractCliOptions | null { const opts: ExtractCliOptions = { ...base, schema: "", urls: [], profile: "http", format: "json", cache: true, concurrency: 8, escalate: true, selectors: false, }; for (let i = 0; i < argv.length; i++) { const arg = argv[i] as string; const value = () => argv[++i] ?? ""; switch (arg) { case "--schema": opts.schema = value(); break; case "--profile": { const profile = value(); if (!PROFILES.has(profile)) { logger.error(`Invalid profile: ${profile}`); return null; } opts.profile = profile as FetchProfile; break; } case "--format": { const format = value(); if (format !== "json" && format !== "jsonl") { logger.error(`Invalid format: ${format}`); return null; } opts.format = format; break; } case "--concurrency": opts.concurrency = Math.max(1, Number.parseInt(value(), 10) || 8); break; case "--no-cache": opts.cache = false; break; case "--cache-path": opts.cachePath = value(); break; case "--no-escalate": opts.escalate = false; break; case "--llm": { const provider = value(); if (provider !== "gemini") { logger.error(`Unsupported --llm provider: ${provider} (available: gemini)`); return null; } opts.llm = provider; break; } case "--min-confidence": opts.minConfidence = Number(value()); break; case "--base-url": opts.baseUrl = value(); break; case "--selectors": opts.selectors = true; break; case "--help": case "-h": return null; default: if (arg.startsWith("-")) { logger.error(`Unknown option: ${arg}`); return null; } opts.urls.push(arg); } } if (!opts.schema) { logger.error("--schema is required"); return null; } if (opts.urls.length === 0) { logger.error("requires at least one "); return null; } return opts; } async function loadSchema(value: string): Promise { const trimmed = value.trim(); if (trimmed.startsWith("{") || trimmed.startsWith("[")) return JSON.parse(trimmed); return JSON.parse(await Bun.file(resolve(trimmed)).text()); } function toTarget(input: string): string { if (/^[a-z][a-z0-9+.-]*:\/\//i.test(input)) return input; if (existsSync(input)) return pathToFileURL(resolve(input)).href; return `https://${input}`; } /** LLM fallback backed by the Gemini toolbox (signed-in cookie session). */ async function geminiFallback(): Promise { const { defaultGeminiToolbox } = await import("../gemini/index.ts"); return { async complete(prompt, jsonSchema) { const response = await defaultGeminiToolbox.ask(`${prompt}\n\nJSON schema:\n${JSON.stringify(jsonSchema)}`, { model: "flash", }); return response.text; }, }; } export async function main(argv: readonly string[], base: CommonOptions): Promise { const opts = parseArgs(argv, base); if (!opts) { printUsage(); process.exit(EXIT.MISUSE); } const extract = await import("../extract/index.ts"); let schema: unknown; try { schema = extract.normalizeSchema(await loadSchema(opts.schema)); } catch (err) { logger.error(`Invalid schema: ${err instanceof Error ? err.message : String(err)}`); process.exit(EXIT.MISUSE); } const cache = opts.cache ? new extract.SelectorCache(opts.cachePath ? { path: opts.cachePath } : {}) : false; const llm = opts.llm === "gemini" ? await geminiFallback() : undefined; const targets = opts.urls.map(toTarget); const results: Array> = Array.from({ length: targets.length }); let failures = 0; let next = 0; const emit = (row: Record) => { if (opts.format === "jsonl") Bun.stdout.write(`${JSON.stringify(row)}\n`); }; const worker = async () => { while (next < targets.length) { const index = next++; const url = targets[index] as string; let row: Record; try { const result: ExtractUrlResult = await extract.extractUrlWithSchema(url, schema, { profile: opts.profile, escalate: opts.escalate, cache, llm, ...(opts.minConfidence !== undefined && Number.isFinite(opts.minConfidence) ? { minConfidence: opts.minConfidence } : {}), ...(opts.baseUrl ? { baseUrl: opts.baseUrl } : {}), }); row = { url, source: result.source, confidence: result.confidence, data: result.records ?? result.record ?? null, missingFields: result.missingFields, profile: result.profile, status: result.status, ...(opts.selectors ? { selectors: result.selectors } : {}), }; } catch (err) { failures++; row = { url, error: err instanceof Error ? err.message : String(err) }; logger.warn(`${url}: ${row.error}`, opts); } results[index] = row; emit(row); } }; try { await Promise.all(Array.from({ length: Math.min(opts.concurrency, targets.length) }, worker)); if (opts.format === "json") Bun.stdout.write(`${JSON.stringify(results, null, 2)}\n`); } finally { if (cache) cache.close(); if (targets.some((t) => !t.startsWith("file://"))) { const { Browser } = await import("../api/browser.ts"); await Browser.close().catch(() => {}); } } if (failures === targets.length) process.exit(EXIT.DATA_ERR); } if (import.meta.main) { const { opts, remaining } = parseCommonArgs(process.argv.slice(2)); main(remaining, opts).catch((err) => { logger.error(err instanceof Error ? err.message : String(err)); process.exit(EXIT.SOFTWARE); }); }