@agentproto/collect-cli 0.0.0-stage → 0.1.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 +202 -0
- package/README.md +173 -2
- package/dist/cli.mjs +1253 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.mjs +1238 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -3
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,1253 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'util';
|
|
3
|
+
import { lstat, realpath, mkdir, rm, open as open$1, readFile } from 'fs/promises';
|
|
4
|
+
import { dirname, resolve, join, basename, sep } from 'path';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'url';
|
|
6
|
+
import { readAll, CollectTask, CollectRunError, StoreLockedError, StoreVersionError, ConnectorDeclaration, listConnectors, createConnectorRegistry, canonicalUrl, itemIdFromUrl, textFingerprint, CollectItem, Observation, Pickup, Actor, seenKey, itemSeenKeys, stableStringify, recordSecrets, createCollector, Recipe, TransportError, sha256Hex } from '@agentproto/collect';
|
|
7
|
+
import { shippedConnectors } from '@agentproto/collect/connectors';
|
|
8
|
+
import { initStore, StoreNotFoundError, StoreMigrationError, openStore, browserProfile, createMcpClient, createBrowserTransport, requiredTools, createHttpTransport, createApiTransport } from '@agentproto/collect/node';
|
|
9
|
+
import { parse as parse$1 } from 'yaml';
|
|
10
|
+
import { Writable, Readable } from 'stream';
|
|
11
|
+
import { pipeline } from 'stream/promises';
|
|
12
|
+
import { readFileSync } from 'fs';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @agentproto/collect-cli
|
|
16
|
+
* The `collect` binary: a command-line tool for collecting public posts and articles with provenance.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
// src/io.ts
|
|
20
|
+
var UsageError = class extends Error {
|
|
21
|
+
code = "USAGE";
|
|
22
|
+
constructor(message2) {
|
|
23
|
+
super(message2);
|
|
24
|
+
this.name = "UsageError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
function out(io, text) {
|
|
28
|
+
io.stdout.write(text.endsWith("\n") ? text : `${text}
|
|
29
|
+
`);
|
|
30
|
+
}
|
|
31
|
+
function err(io, text) {
|
|
32
|
+
io.stderr.write(text.endsWith("\n") ? text : `${text}
|
|
33
|
+
`);
|
|
34
|
+
}
|
|
35
|
+
function outJson(io, value) {
|
|
36
|
+
out(io, JSON.stringify(value));
|
|
37
|
+
}
|
|
38
|
+
function table(rows) {
|
|
39
|
+
if (rows.length === 0) return "";
|
|
40
|
+
const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
|
|
41
|
+
return rows.map((r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i])).join(" ").trimEnd()).join("\n");
|
|
42
|
+
}
|
|
43
|
+
var COMMON_OPTIONS = {
|
|
44
|
+
json: { type: "boolean" },
|
|
45
|
+
help: { type: "boolean", short: "h" },
|
|
46
|
+
quiet: { type: "boolean", short: "q" }
|
|
47
|
+
};
|
|
48
|
+
function parse(argv, spec) {
|
|
49
|
+
try {
|
|
50
|
+
const { values, positionals } = parseArgs({ args: argv, options: { ...COMMON_OPTIONS, ...spec }, allowPositionals: true, strict: true });
|
|
51
|
+
return { values, positionals };
|
|
52
|
+
} catch (e) {
|
|
53
|
+
throw new UsageError(e instanceof Error ? e.message : String(e));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function positional(p, name, count = 1) {
|
|
57
|
+
if (p.length < count) throw new UsageError(`missing argument <${name}>`);
|
|
58
|
+
if (p.length > count) throw new UsageError(`unexpected argument "${p[count]}"`);
|
|
59
|
+
return p;
|
|
60
|
+
}
|
|
61
|
+
function intOption(name, value) {
|
|
62
|
+
if (value === void 0) return void 0;
|
|
63
|
+
if (!/^\d+$/.test(value) || Number(value) < 1) throw new UsageError(`--${name} must be a positive integer, got "${value}"`);
|
|
64
|
+
return Number(value);
|
|
65
|
+
}
|
|
66
|
+
function looksLikeConnector(v) {
|
|
67
|
+
if (!v || typeof v !== "object") return false;
|
|
68
|
+
const c = v;
|
|
69
|
+
return typeof c.plan === "function" && typeof c.fetch === "function" && typeof c.parse === "function";
|
|
70
|
+
}
|
|
71
|
+
function issuePath(path) {
|
|
72
|
+
return path.map((p, i) => typeof p === "number" ? `[${p}]` : i === 0 ? String(p) : `.${String(p)}`).join("") || "(root)";
|
|
73
|
+
}
|
|
74
|
+
function formatIssues(error) {
|
|
75
|
+
return error.issues.map((i) => ` ${issuePath(i.path)}: ${i.message}`).join("\n");
|
|
76
|
+
}
|
|
77
|
+
function validateRecipe(input, label) {
|
|
78
|
+
const parsed = Recipe.safeParse(input);
|
|
79
|
+
if (!parsed.success) throw new UsageError(`invalid recipe ${label}:
|
|
80
|
+
${formatIssues(parsed.error)}`);
|
|
81
|
+
return parsed.data;
|
|
82
|
+
}
|
|
83
|
+
function announce(io, loaded) {
|
|
84
|
+
for (const line of loaded.overrides) err(io, `info: ${line}`);
|
|
85
|
+
}
|
|
86
|
+
async function loadConnectors(paths, cwd) {
|
|
87
|
+
const found = new Map(shippedConnectors.map((c) => [c.id, c]));
|
|
88
|
+
const overrides = [];
|
|
89
|
+
const apiAuth = /* @__PURE__ */ new Map();
|
|
90
|
+
const merged = /* @__PURE__ */ new Map();
|
|
91
|
+
const add = (c, where) => {
|
|
92
|
+
const existing = found.get(c.id);
|
|
93
|
+
if (existing && existing !== c && shippedConnectors.includes(existing)) {
|
|
94
|
+
overrides.push(`connector "${c.id}" from ${where.replace(/^connector module /, "")} replaces the shipped one`);
|
|
95
|
+
found.set(c.id, c);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (existing && existing !== c) throw new UsageError(`${where}: connector "${c.id}" is defined twice`);
|
|
99
|
+
found.set(c.id, c);
|
|
100
|
+
};
|
|
101
|
+
for (const p of paths) {
|
|
102
|
+
const file = resolve(cwd, p);
|
|
103
|
+
let mod;
|
|
104
|
+
try {
|
|
105
|
+
mod = await import(pathToFileURL(file).href);
|
|
106
|
+
} catch (e) {
|
|
107
|
+
throw new UsageError(`cannot load connector module ${p}: ${e instanceof Error ? e.message : String(e)}`);
|
|
108
|
+
}
|
|
109
|
+
const here = [];
|
|
110
|
+
for (const [name, value] of Object.entries(mod)) {
|
|
111
|
+
if (name === "apiAuth") continue;
|
|
112
|
+
for (const v of Array.isArray(value) ? value : [value]) {
|
|
113
|
+
if (!looksLikeConnector(v)) continue;
|
|
114
|
+
const { id, version, transports, access, capabilities, counters, pace, sessionCheck } = v;
|
|
115
|
+
const declared = ConnectorDeclaration.safeParse({ id, version, transports, access, capabilities, counters, pace, sessionCheck });
|
|
116
|
+
if (!declared.success) throw new UsageError(`connector module ${p}: export "${name}" is not a valid connector:
|
|
117
|
+
${formatIssues(declared.error)}`);
|
|
118
|
+
let copy = merged.get(v);
|
|
119
|
+
if (!copy) merged.set(v, copy = Object.freeze({ ...v, ...declared.data }));
|
|
120
|
+
if (!here.includes(copy)) here.push(copy);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (here.length === 0) throw new UsageError(`connector module ${p} exports no connector`);
|
|
124
|
+
for (const c of here) {
|
|
125
|
+
add(c, `connector module ${p}`);
|
|
126
|
+
if (mod.apiAuth && typeof mod.apiAuth === "object") apiAuth.set(c.id, mod.apiAuth);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const c of listConnectors()) if (!merged.has(c)) add(c, "registry");
|
|
130
|
+
return { registry: createConnectorRegistry([...found.values()]), apiAuth, overrides };
|
|
131
|
+
}
|
|
132
|
+
function envSecrets(env) {
|
|
133
|
+
return { get: async (name) => env[name] || void 0 };
|
|
134
|
+
}
|
|
135
|
+
function secretNameOf(c) {
|
|
136
|
+
return c.access.level === "key" ? c.access.secret : void 0;
|
|
137
|
+
}
|
|
138
|
+
function buildTransports(loaded, secrets, rateMs, browser) {
|
|
139
|
+
const http = createHttpTransport(rateMs === void 0 ? {} : { minIntervalMs: rateMs });
|
|
140
|
+
return {
|
|
141
|
+
http,
|
|
142
|
+
...browser ? { browser } : {},
|
|
143
|
+
api: (connector) => {
|
|
144
|
+
if (connector.access.level !== "key") return http;
|
|
145
|
+
const secret = connector.access.secret;
|
|
146
|
+
const auth = loaded.apiAuth.get(connector.id) ?? { type: "bearer", secret };
|
|
147
|
+
return createApiTransport({ http, secrets, auth: { ...auth, secret } });
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
async function loadRecipe(file, cwd) {
|
|
152
|
+
const abs = resolve(cwd, file);
|
|
153
|
+
let text;
|
|
154
|
+
try {
|
|
155
|
+
text = await readFile(abs, "utf8");
|
|
156
|
+
} catch {
|
|
157
|
+
throw new UsageError(`cannot read recipe ${file}`);
|
|
158
|
+
}
|
|
159
|
+
let doc;
|
|
160
|
+
try {
|
|
161
|
+
doc = parse$1(text);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
throw new UsageError(`invalid YAML in ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
164
|
+
}
|
|
165
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new UsageError(`${file}: the recipe must be a mapping`);
|
|
166
|
+
const { connectors, ...rest } = doc;
|
|
167
|
+
if (connectors !== void 0 && (!Array.isArray(connectors) || connectors.some((c) => typeof c !== "string"))) {
|
|
168
|
+
throw new UsageError(`${file}: connectors: must be a list of module paths`);
|
|
169
|
+
}
|
|
170
|
+
const recipe = validateRecipe(rest, file);
|
|
171
|
+
return { recipe, connectors: (connectors ?? []).map((c) => resolve(dirname(abs), c)) };
|
|
172
|
+
}
|
|
173
|
+
function storePathOf(io, option) {
|
|
174
|
+
return resolve(io.cwd, option ?? io.env.COLLECT_STORE ?? "collect-store");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/commands/connectors.ts
|
|
178
|
+
var CONNECTOR_OPTION = { connector: { type: "string", multiple: true } };
|
|
179
|
+
async function runConnectors(argv, io) {
|
|
180
|
+
const { values, positionals } = parse(argv, CONNECTOR_OPTION);
|
|
181
|
+
positional(positionals, "none", 0);
|
|
182
|
+
const loadedAll = await loadConnectors(values.connector ?? [], io.cwd);
|
|
183
|
+
announce(io, loadedAll);
|
|
184
|
+
const { registry } = loadedAll;
|
|
185
|
+
const list = registry.list().map((c) => ({
|
|
186
|
+
id: c.id,
|
|
187
|
+
version: c.version,
|
|
188
|
+
transports: [...c.transports],
|
|
189
|
+
access: c.access,
|
|
190
|
+
capabilities: [...c.capabilities]
|
|
191
|
+
}));
|
|
192
|
+
if (values.json) {
|
|
193
|
+
outJson(io, list);
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
if (list.length === 0) {
|
|
197
|
+
out(io, "no connectors registered (load one with --connector <module>)");
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
const rows = [["id", "version", "transports", "access", "capabilities"]];
|
|
201
|
+
for (const c of list) {
|
|
202
|
+
const access = c.access.level === "key" ? `key (${c.access.secret})` : c.access.level === "session" ? `session (${c.access.site})` : "none";
|
|
203
|
+
rows.push([c.id, c.version, c.transports.join(","), access, c.capabilities.join(",")]);
|
|
204
|
+
}
|
|
205
|
+
out(io, table(rows));
|
|
206
|
+
return 0;
|
|
207
|
+
}
|
|
208
|
+
var BROWSER_OPTIONS = {
|
|
209
|
+
"browser-mcp": { type: "string" },
|
|
210
|
+
"browser-profile": { type: "string" },
|
|
211
|
+
"browser-proxy-tool": { type: "string" },
|
|
212
|
+
"browser-alias": { type: "string" },
|
|
213
|
+
"browser-instance": { type: "string" },
|
|
214
|
+
"browser-header": { type: "string", multiple: true },
|
|
215
|
+
"browser-pace": { type: "string" }
|
|
216
|
+
};
|
|
217
|
+
function envHeaders(env) {
|
|
218
|
+
return (env.COLLECT_BROWSER_HEADER ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
219
|
+
}
|
|
220
|
+
function parseHeader(line) {
|
|
221
|
+
const i = line.indexOf(":");
|
|
222
|
+
const name = line.slice(0, i).trim();
|
|
223
|
+
if (i <= 0 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new UsageError("--browser-header must look like 'Name: value'");
|
|
224
|
+
return [name, line.slice(i + 1).trim()];
|
|
225
|
+
}
|
|
226
|
+
function browserConfig(values, env) {
|
|
227
|
+
const endpoint = values["browser-mcp"] ?? (env.COLLECT_BROWSER_MCP || void 0);
|
|
228
|
+
const profileName = values["browser-profile"] ?? (env.COLLECT_BROWSER_PROFILE || void 0);
|
|
229
|
+
const proxyTool = values["browser-proxy-tool"] ?? (env.COLLECT_BROWSER_PROXY_TOOL || void 0);
|
|
230
|
+
const alias = values["browser-alias"] ?? (env.COLLECT_BROWSER_ALIAS || void 0);
|
|
231
|
+
const instance = values["browser-instance"] ?? (env.COLLECT_BROWSER_INSTANCE || void 0);
|
|
232
|
+
const paceText = values["browser-pace"] ?? (env.COLLECT_BROWSER_PACE || void 0);
|
|
233
|
+
const headerLines = [...envHeaders(env), ...values["browser-header"] ?? []];
|
|
234
|
+
if (!endpoint) {
|
|
235
|
+
const orphan = ["browser-profile", "browser-proxy-tool", "browser-alias", "browser-instance", "browser-header", "browser-pace"].find((k) => values[k] !== void 0);
|
|
236
|
+
if (orphan) throw new UsageError(`--${orphan} needs --browser-mcp <url>`);
|
|
237
|
+
return void 0;
|
|
238
|
+
}
|
|
239
|
+
let url;
|
|
240
|
+
try {
|
|
241
|
+
url = new URL(endpoint);
|
|
242
|
+
} catch {
|
|
243
|
+
throw new UsageError("--browser-mcp must be an http(s) URL");
|
|
244
|
+
}
|
|
245
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new UsageError("--browser-mcp must be an http(s) URL");
|
|
246
|
+
if (Boolean(proxyTool) !== Boolean(alias)) throw new UsageError("--browser-proxy-tool and --browser-alias go together");
|
|
247
|
+
let profile;
|
|
248
|
+
try {
|
|
249
|
+
profile = browserProfile(profileName ?? "chrome-devtools");
|
|
250
|
+
} catch (e) {
|
|
251
|
+
throw new UsageError(e instanceof Error ? e.message : String(e));
|
|
252
|
+
}
|
|
253
|
+
const headers = {};
|
|
254
|
+
for (const line of headerLines) {
|
|
255
|
+
const [k, v] = parseHeader(line);
|
|
256
|
+
headers[k] = v;
|
|
257
|
+
}
|
|
258
|
+
let pace;
|
|
259
|
+
if (paceText !== void 0) {
|
|
260
|
+
const m = /^(\d+)-(\d+)$/.exec(paceText);
|
|
261
|
+
if (!m || Number(m[1]) > Number(m[2])) throw new UsageError("--browser-pace must look like 2000-6000 (min-max milliseconds)");
|
|
262
|
+
pace = { minMs: Number(m[1]), maxMs: Number(m[2]) };
|
|
263
|
+
}
|
|
264
|
+
return { endpoint, profile, ...pace ? { pace } : {}, ...proxyTool && alias ? { proxy: { tool: proxyTool, alias } } : {}, ...instance ? { instance } : {}, headers };
|
|
265
|
+
}
|
|
266
|
+
function displayEndpoint(endpoint) {
|
|
267
|
+
const u = new URL(endpoint);
|
|
268
|
+
return `${u.protocol}//${u.host}${u.pathname}`;
|
|
269
|
+
}
|
|
270
|
+
function redactBrowser(io, config) {
|
|
271
|
+
const values = [...Object.values(config.headers)];
|
|
272
|
+
const u = new URL(config.endpoint);
|
|
273
|
+
if (u.password) values.push(u.password);
|
|
274
|
+
if (u.username) values.push(u.username);
|
|
275
|
+
for (const v of u.searchParams.values()) values.push(v);
|
|
276
|
+
const secrets = values.filter((v) => v.length >= 4).sort((x, y) => y.length - x.length);
|
|
277
|
+
if (secrets.length === 0) return;
|
|
278
|
+
io.addRedactor?.((text) => secrets.reduce((t, v) => t.split(v).join("[redacted]"), text));
|
|
279
|
+
}
|
|
280
|
+
function createBrowser(config, io, defaultPace) {
|
|
281
|
+
const pace = config.pace ?? defaultPace;
|
|
282
|
+
const client = createMcpClient({
|
|
283
|
+
endpoint: config.endpoint,
|
|
284
|
+
headers: config.headers,
|
|
285
|
+
signal: io.signal,
|
|
286
|
+
clientInfo: { name: "collect", version: "0" }
|
|
287
|
+
});
|
|
288
|
+
const transport = createBrowserTransport({
|
|
289
|
+
client,
|
|
290
|
+
profile: config.profile,
|
|
291
|
+
...config.proxy ? { proxy: config.proxy } : {},
|
|
292
|
+
...config.instance ? { instance: config.instance } : {},
|
|
293
|
+
...pace ? { pace } : {},
|
|
294
|
+
// Stops paced waits when the run is cancelled; the cleanup calls do not depend on it.
|
|
295
|
+
signal: io.signal
|
|
296
|
+
});
|
|
297
|
+
return {
|
|
298
|
+
client,
|
|
299
|
+
transport,
|
|
300
|
+
async dispose() {
|
|
301
|
+
await transport.closeAll();
|
|
302
|
+
const left = transport.leftOpen();
|
|
303
|
+
if (left.length > 0) err(io, `collect: ${left.length} browser tab${left.length === 1 ? "" : "s"} could not be closed safely and ${left.length === 1 ? "was" : "were"} left open`);
|
|
304
|
+
await client.close();
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/commands/doctor.ts
|
|
310
|
+
var message = (e) => e instanceof Error ? e.message : String(e);
|
|
311
|
+
async function checkBrowser(config, io, browser) {
|
|
312
|
+
if (!config || !browser) return { configured: false, ok: false, missingTools: [] };
|
|
313
|
+
const report = {
|
|
314
|
+
configured: true,
|
|
315
|
+
endpoint: displayEndpoint(config.endpoint),
|
|
316
|
+
profile: config.profile.name,
|
|
317
|
+
proxy: Boolean(config.proxy),
|
|
318
|
+
ok: false,
|
|
319
|
+
missingTools: []
|
|
320
|
+
};
|
|
321
|
+
try {
|
|
322
|
+
const toolList = await browser.client.listTools({ signal: io.signal });
|
|
323
|
+
const tools = new Set(toolList.map((t) => t.name));
|
|
324
|
+
if (config.proxy) {
|
|
325
|
+
if (!tools.has(config.proxy.tool)) report.missingTools = [config.proxy.tool];
|
|
326
|
+
} else {
|
|
327
|
+
report.missingTools = requiredTools(config.profile).filter((t) => !tools.has(t));
|
|
328
|
+
const schemaOf = (name) => (toolList.find((t) => t.name === name)?.inputSchema ?? {}).properties ?? {};
|
|
329
|
+
const closeProps = schemaOf(config.profile.tools.closeTab);
|
|
330
|
+
if (config.profile.name === "chrome-devtools" && "pageIdx" in closeProps && !("pageId" in closeProps)) {
|
|
331
|
+
report.error = "this server names pages by index (pageIdx): use --browser-profile chrome-devtools-index (a fallback that needs a browser session no other client drives)";
|
|
332
|
+
return report;
|
|
333
|
+
}
|
|
334
|
+
if (config.profile.name === "chrome-devtools-index" && "pageId" in closeProps) {
|
|
335
|
+
report.error = "this server names pages by stable id (pageId): use --browser-profile chrome-devtools";
|
|
336
|
+
return report;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (report.missingTools.length) {
|
|
340
|
+
report.error = `missing tools: ${report.missingTools.join(", ")}`;
|
|
341
|
+
return report;
|
|
342
|
+
}
|
|
343
|
+
const sum = await browser.transport.probe();
|
|
344
|
+
report.blankTab = true;
|
|
345
|
+
report.evaluate = sum === 2;
|
|
346
|
+
if (!report.evaluate) report.error = "the probe evaluation did not return 2";
|
|
347
|
+
report.probeClosed = true;
|
|
348
|
+
report.listing = await browser.transport.canList();
|
|
349
|
+
report.ok = report.evaluate === true;
|
|
350
|
+
} catch (e) {
|
|
351
|
+
report.error = message(e);
|
|
352
|
+
if (/probe tab could not be closed/.test(report.error)) {
|
|
353
|
+
report.probeClosed = false;
|
|
354
|
+
}
|
|
355
|
+
if (report.blankTab === void 0 && report.missingTools.length === 0 && report.error) report.blankTab = false;
|
|
356
|
+
}
|
|
357
|
+
return report;
|
|
358
|
+
}
|
|
359
|
+
function sessionCheckScript(body) {
|
|
360
|
+
return `try {
|
|
361
|
+
const __answer = await (async () => {
|
|
362
|
+
${body}
|
|
363
|
+
})();
|
|
364
|
+
return __answer === true ? "open" : "none";
|
|
365
|
+
} catch (__e) {
|
|
366
|
+
return "error";
|
|
367
|
+
}`;
|
|
368
|
+
}
|
|
369
|
+
async function checkSession(check, browser) {
|
|
370
|
+
let page;
|
|
371
|
+
try {
|
|
372
|
+
page = await browser.transport.open(check.url);
|
|
373
|
+
const code = await browser.transport.evaluate(page, sessionCheckScript(check.evaluate));
|
|
374
|
+
if (code === "open") return { state: "open" };
|
|
375
|
+
if (code === "none") return { state: "none" };
|
|
376
|
+
if (code === "error") return { state: "error", note: "the check could not run" };
|
|
377
|
+
return { state: "unknown", note: "the check gave no answer" };
|
|
378
|
+
} catch (e) {
|
|
379
|
+
if (e instanceof TransportError && e.cause === "challenge") return { state: "unknown", note: "the site showed a verification page; nothing was bypassed" };
|
|
380
|
+
return { state: "error", note: "the check could not run" };
|
|
381
|
+
} finally {
|
|
382
|
+
if (page) await browser.transport.close(page).catch(() => void 0);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
async function runDoctor(argv, io) {
|
|
386
|
+
const { values, positionals } = parse(argv, { ...CONNECTOR_OPTION, ...BROWSER_OPTIONS, source: { type: "string", multiple: true } });
|
|
387
|
+
if (positionals.length > 1) positional(positionals, "recipe", 1);
|
|
388
|
+
const config = browserConfig(values, io.env);
|
|
389
|
+
if (config) redactBrowser(io, config);
|
|
390
|
+
const modules = [...values.connector ?? []];
|
|
391
|
+
let wanted = values.source ?? [];
|
|
392
|
+
if (positionals[0]) {
|
|
393
|
+
const loaded = await loadRecipe(positionals[0], io.cwd);
|
|
394
|
+
modules.push(...loaded.connectors);
|
|
395
|
+
if (wanted.length === 0) wanted = [...new Set(loaded.recipe.sources.map((s) => s.connector))];
|
|
396
|
+
}
|
|
397
|
+
const loadedAll = await loadConnectors(modules, io.cwd);
|
|
398
|
+
announce(io, loadedAll);
|
|
399
|
+
const { registry } = loadedAll;
|
|
400
|
+
const ids = wanted.length > 0 ? wanted : registry.list().map((c) => c.id);
|
|
401
|
+
const browser = config ? createBrowser(config, io, { minMs: 500, maxMs: 1500 }) : void 0;
|
|
402
|
+
try {
|
|
403
|
+
const browserReport = await checkBrowser(config, io, browser);
|
|
404
|
+
let unusable = 0;
|
|
405
|
+
const reports = [];
|
|
406
|
+
for (const id of ids) {
|
|
407
|
+
const c = registry.get(id);
|
|
408
|
+
if (!c) {
|
|
409
|
+
unusable++;
|
|
410
|
+
reports.push({ id, registered: false, usable: false, problems: [`connector "${id}" is not registered`] });
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const secret = secretNameOf(c);
|
|
414
|
+
const secretPresent = secret ? Boolean(io.env[secret]) : void 0;
|
|
415
|
+
const transports = {};
|
|
416
|
+
for (const t of c.transports) {
|
|
417
|
+
if (t === "http") transports[t] = { available: true };
|
|
418
|
+
else if (t === "api") transports[t] = secret ? { available: Boolean(secretPresent), note: secretPresent ? void 0 : `${secret} is not set` } : { available: false, note: "the connector declares no secret" };
|
|
419
|
+
else if (!browserReport.configured) transports[t] = { available: false, note: "no browser: use --browser-mcp <url>" };
|
|
420
|
+
else transports[t] = browserReport.ok ? { available: true } : { available: false, note: browserReport.error ?? "the browser is not usable" };
|
|
421
|
+
}
|
|
422
|
+
const problems = [];
|
|
423
|
+
if (secret && !secretPresent) problems.push(`secret ${secret} is not set`);
|
|
424
|
+
let session;
|
|
425
|
+
if (c.access.level === "session") {
|
|
426
|
+
const site = c.access.site;
|
|
427
|
+
if (!browserReport.ok || !browser) {
|
|
428
|
+
session = { site, state: "unknown", note: "no usable browser" };
|
|
429
|
+
problems.push(`needs a logged-in session on ${site}, and no usable browser is configured`);
|
|
430
|
+
} else if (!c.sessionCheck) {
|
|
431
|
+
session = { site, state: "unknown", note: "the connector declares no session check" };
|
|
432
|
+
} else {
|
|
433
|
+
session = { site, ...await checkSession(c.sessionCheck, browser) };
|
|
434
|
+
if (session.state === "none") problems.push(`no open session on ${site}: log in with the browser first`);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const usable = problems.length === 0 && Object.values(transports).some((t) => t.available);
|
|
438
|
+
if (!usable && problems.length === 0) problems.push("no usable transport");
|
|
439
|
+
if (!usable) unusable++;
|
|
440
|
+
reports.push({ id, registered: true, version: c.version, access: c.access, secret, secretPresent, transports, ...session ? { session } : {}, usable, problems });
|
|
441
|
+
}
|
|
442
|
+
const ok = unusable === 0 && !(browserReport.configured && !browserReport.ok);
|
|
443
|
+
if (values.json) outJson(io, { browser: browserReport, connectors: reports, ok });
|
|
444
|
+
else {
|
|
445
|
+
if (browserReport.configured) {
|
|
446
|
+
const detail = browserReport.ok ? "ok" : `FAILED (${browserReport.error})`;
|
|
447
|
+
out(io, `browser: ${browserReport.endpoint} profile ${browserReport.profile}${browserReport.proxy ? " (through a proxy tool)" : ""}: ${detail}`);
|
|
448
|
+
if (browserReport.ok) out(io, "browser: listed the tools, opened a probe tab, navigated it to a safe data: URL, evaluated 1+1 in it and closed it");
|
|
449
|
+
if (browserReport.ok && browserReport.listing === false) {
|
|
450
|
+
out(io, "browser: cannot list tabs: a tab whose creation times out cannot be found and closed afterwards");
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (reports.length === 0) out(io, "no connectors to check");
|
|
454
|
+
else {
|
|
455
|
+
const rows = [["connector", "access", "secret", "transports", "session", "usable"]];
|
|
456
|
+
for (const r of reports) {
|
|
457
|
+
if (!r.registered) {
|
|
458
|
+
rows.push([r.id, "-", "-", "-", "-", "no (not registered)"]);
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
const t = Object.entries(r.transports).map(([n, a]) => `${n}:${a.available ? "yes" : `no${a.note ? ` (${a.note})` : ""}`}`).join(" ");
|
|
462
|
+
const secret = r.secret ? `${r.secret}: ${r.secretPresent ? "set" : "missing"}` : "-";
|
|
463
|
+
const session = r.session ? `${r.session.state} (${r.session.site})` : "-";
|
|
464
|
+
rows.push([r.id, r.access.level, secret, t, session, r.usable ? "yes" : "no"]);
|
|
465
|
+
}
|
|
466
|
+
out(io, table(rows));
|
|
467
|
+
for (const r of reports) {
|
|
468
|
+
for (const p of r.problems) out(io, `${r.id}: ${p}`);
|
|
469
|
+
if ((r.session?.state === "unknown" || r.session?.state === "error") && r.session.note) out(io, `${r.id}: session ${r.session.state}: ${r.session.note}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return ok ? 0 : 1;
|
|
474
|
+
} finally {
|
|
475
|
+
await browser?.dispose().catch(() => void 0);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function classify(e) {
|
|
479
|
+
const cause = e instanceof CollectRunError ? e.cause : e;
|
|
480
|
+
if (!(e instanceof CollectRunError) && cause instanceof Error && (cause.name === "ZodError" || cause instanceof SyntaxError)) {
|
|
481
|
+
return { code: 3, message: `store data is unreadable: ${cause.message.split("\n")[0]}` };
|
|
482
|
+
}
|
|
483
|
+
if (cause instanceof UsageError) return { code: 2, message: cause.message };
|
|
484
|
+
if (cause instanceof StoreLockedError) {
|
|
485
|
+
const h = cause.holder;
|
|
486
|
+
return { code: 3, message: `store is locked${h ? ` by pid ${h.pid} since ${h.at}` : ""}; wait for the other run to end` };
|
|
487
|
+
}
|
|
488
|
+
if (cause instanceof StoreNotFoundError) return { code: 3, message: `${cause.message}; create it with: collect init <path>` };
|
|
489
|
+
if (cause instanceof StoreVersionError || cause instanceof StoreMigrationError) return { code: 3, message: cause.message };
|
|
490
|
+
if (cause && typeof cause === "object" && "code" in cause && ["EACCES", "EPERM", "ENOENT", "EISDIR", "ENOTDIR"].includes(String(cause.code))) {
|
|
491
|
+
return { code: 3, message: `store unreadable: ${String(cause.message)}` };
|
|
492
|
+
}
|
|
493
|
+
return void 0;
|
|
494
|
+
}
|
|
495
|
+
async function open(path) {
|
|
496
|
+
return openStore(path);
|
|
497
|
+
}
|
|
498
|
+
function progress(io, json, quiet) {
|
|
499
|
+
return (event) => {
|
|
500
|
+
if (quiet) return;
|
|
501
|
+
if (json) return err(io, JSON.stringify(event));
|
|
502
|
+
const d = event.data ? ` ${Object.entries(event.data).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ")}` : "";
|
|
503
|
+
err(io, `[${event.type}]${d}`);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function reportExit(report, interrupted, unexpectedSkips) {
|
|
507
|
+
if (interrupted || unexpectedSkips > 0) return 1;
|
|
508
|
+
const bad = report.connectors.some((c) => c.status === "failed" || c.status === "skipped" || c.tasks.failed > 0);
|
|
509
|
+
return bad ? 1 : 0;
|
|
510
|
+
}
|
|
511
|
+
async function countUnexpectedSkips(store, runId) {
|
|
512
|
+
const latest = /* @__PURE__ */ new Map();
|
|
513
|
+
for await (const t of store.tasks(runId)) latest.set(`${t.connector}/${t.taskId}`, t);
|
|
514
|
+
let n = 0;
|
|
515
|
+
for (const t of latest.values()) {
|
|
516
|
+
if (t.status === "pending" || t.status === "started") n++;
|
|
517
|
+
else if (t.status === "skipped" && !/cap reached/.test(t.reason ?? "")) n++;
|
|
518
|
+
}
|
|
519
|
+
return n;
|
|
520
|
+
}
|
|
521
|
+
function renderReport(report) {
|
|
522
|
+
const rows = [["connector", "status", "tasks done/failed/skipped", "new", "obs", "dup"]];
|
|
523
|
+
for (const c of report.connectors) {
|
|
524
|
+
rows.push([c.connector, c.status, `${c.tasks.done}/${c.tasks.failed}/${c.tasks.skipped} of ${c.tasks.planned}`, String(c.newItems), String(c.observations), String(c.duplicates)]);
|
|
525
|
+
}
|
|
526
|
+
const lines = [`run ${report.runId}`, table(rows)];
|
|
527
|
+
for (const c of report.connectors) {
|
|
528
|
+
const why = [c.skippedReason, c.reason].filter(Boolean).join("; ");
|
|
529
|
+
if (why) lines.push(`${c.connector}: ${why}`);
|
|
530
|
+
const f = Object.entries(c.failures).map(([k, v]) => `${k}=${v}`).join(" ");
|
|
531
|
+
if (f) lines.push(`${c.connector}: failures ${f}`);
|
|
532
|
+
for (const e of c.escalations) lines.push(`${c.connector}: escalated ${e.from} -> ${e.to} (${e.count})`);
|
|
533
|
+
}
|
|
534
|
+
return lines.join("\n");
|
|
535
|
+
}
|
|
536
|
+
async function execute(io, opts) {
|
|
537
|
+
const store = await open(opts.storePath);
|
|
538
|
+
const secrets = recordSecrets(envSecrets(io.env));
|
|
539
|
+
io.addRedactor?.(secrets.redact);
|
|
540
|
+
if (opts.browser) redactBrowser(io, opts.browser);
|
|
541
|
+
const browser = opts.browser ? createBrowser(opts.browser, io) : void 0;
|
|
542
|
+
const collector = createCollector({
|
|
543
|
+
store,
|
|
544
|
+
transports: buildTransports(opts.loaded, secrets, opts.rateMs, browser?.transport),
|
|
545
|
+
secrets,
|
|
546
|
+
connectors: opts.loaded.registry
|
|
547
|
+
});
|
|
548
|
+
let report;
|
|
549
|
+
try {
|
|
550
|
+
report = await opts.start(collector, progress(io, opts.json, opts.quiet));
|
|
551
|
+
} finally {
|
|
552
|
+
await browser?.dispose();
|
|
553
|
+
}
|
|
554
|
+
const interrupted = io.signal?.aborted === true;
|
|
555
|
+
if (opts.json) outJson(io, { ...report, interrupted });
|
|
556
|
+
else {
|
|
557
|
+
out(io, renderReport(report));
|
|
558
|
+
if (interrupted) out(io, `interrupted: continue with: collect resume ${report.runId}`);
|
|
559
|
+
}
|
|
560
|
+
return reportExit(report, interrupted, await countUnexpectedSkips(store, report.runId));
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// src/commands/export.ts
|
|
564
|
+
var CSV_COLUMNS = [
|
|
565
|
+
"id",
|
|
566
|
+
"source",
|
|
567
|
+
"sourceInstance",
|
|
568
|
+
"kind",
|
|
569
|
+
"url",
|
|
570
|
+
"canonicalUrl",
|
|
571
|
+
"contentId",
|
|
572
|
+
"contentGroupId",
|
|
573
|
+
"title",
|
|
574
|
+
"text",
|
|
575
|
+
"textTruncated",
|
|
576
|
+
"language",
|
|
577
|
+
"wordCount",
|
|
578
|
+
"format",
|
|
579
|
+
"authorRef",
|
|
580
|
+
"submitterRef",
|
|
581
|
+
"publishedAt",
|
|
582
|
+
"postedAt",
|
|
583
|
+
"firstSeenAt",
|
|
584
|
+
"hasMedia",
|
|
585
|
+
"query",
|
|
586
|
+
"runId",
|
|
587
|
+
"subjects",
|
|
588
|
+
"tags",
|
|
589
|
+
"links",
|
|
590
|
+
"outboundLinks",
|
|
591
|
+
"parts",
|
|
592
|
+
"rawRefs",
|
|
593
|
+
"ext"
|
|
594
|
+
];
|
|
595
|
+
function cell(value) {
|
|
596
|
+
if (value === void 0 || value === null) return "";
|
|
597
|
+
const text = typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
598
|
+
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
|
599
|
+
}
|
|
600
|
+
function csvRow(item) {
|
|
601
|
+
const r = item;
|
|
602
|
+
return CSV_COLUMNS.map((c) => cell(r[c])).join(",");
|
|
603
|
+
}
|
|
604
|
+
async function outputPath(io, out2, storePath) {
|
|
605
|
+
const wanted = resolve(io.cwd, out2);
|
|
606
|
+
let dir;
|
|
607
|
+
try {
|
|
608
|
+
dir = await realpath(dirname(wanted));
|
|
609
|
+
} catch {
|
|
610
|
+
throw new UsageError(`--out ${out2}: the directory does not exist`);
|
|
611
|
+
}
|
|
612
|
+
const real = join(dir, basename(wanted));
|
|
613
|
+
const store = await realpath(storePath);
|
|
614
|
+
if (real === store || real.startsWith(store + sep)) throw new UsageError(`--out ${out2} is inside the store directory; choose a path outside it`);
|
|
615
|
+
return real;
|
|
616
|
+
}
|
|
617
|
+
async function runExport(argv, io) {
|
|
618
|
+
const { values, positionals } = parse(argv, {
|
|
619
|
+
store: { type: "string" },
|
|
620
|
+
format: { type: "string" },
|
|
621
|
+
source: { type: "string" },
|
|
622
|
+
out: { type: "string" },
|
|
623
|
+
view: { type: "string" }
|
|
624
|
+
});
|
|
625
|
+
positional(positionals, "none", 0);
|
|
626
|
+
if (values.view !== void 0) {
|
|
627
|
+
if (values.view === "flat") {
|
|
628
|
+
err(io, "collect: --view flat is not available yet");
|
|
629
|
+
return 2;
|
|
630
|
+
}
|
|
631
|
+
throw new UsageError(`unknown view "${values.view}"`);
|
|
632
|
+
}
|
|
633
|
+
if (values.json && !values.out) throw new UsageError("export --json needs --out <file>: without it, items stream to stdout as JSONL");
|
|
634
|
+
const format = values.format ?? "jsonl";
|
|
635
|
+
if (format !== "jsonl" && format !== "csv") throw new UsageError(`--format must be jsonl or csv, got "${format}"`);
|
|
636
|
+
const storePath = storePathOf(io, values.store);
|
|
637
|
+
const store = await open(storePath);
|
|
638
|
+
let file;
|
|
639
|
+
let outPath;
|
|
640
|
+
if (values.out) {
|
|
641
|
+
outPath = await outputPath(io, values.out, storePath);
|
|
642
|
+
try {
|
|
643
|
+
file = await open$1(outPath, "wx");
|
|
644
|
+
} catch (e) {
|
|
645
|
+
if (e.code === "EEXIST") throw new UsageError(`--out ${values.out} already exists; it is never overwritten`);
|
|
646
|
+
throw e;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
let count = 0;
|
|
650
|
+
const items = store.items(values.source);
|
|
651
|
+
async function* lines() {
|
|
652
|
+
if (format === "csv") yield `${CSV_COLUMNS.join(",")}
|
|
653
|
+
`;
|
|
654
|
+
for await (const item of items) {
|
|
655
|
+
count++;
|
|
656
|
+
yield `${format === "csv" ? csvRow(item) : JSON.stringify(item)}
|
|
657
|
+
`;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const sink = file ? file.createWriteStream() : new Writable({
|
|
661
|
+
write(chunk, _enc, cb) {
|
|
662
|
+
try {
|
|
663
|
+
const ok = io.stdout.write(chunk.toString("utf8"));
|
|
664
|
+
if (ok === false && io.stdout.once) io.stdout.once("drain", () => cb());
|
|
665
|
+
else cb();
|
|
666
|
+
} catch (e) {
|
|
667
|
+
cb(e);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
try {
|
|
672
|
+
await pipeline(Readable.from(lines()), sink);
|
|
673
|
+
} catch (e) {
|
|
674
|
+
if (outPath) await rm(outPath, { force: true });
|
|
675
|
+
throw e;
|
|
676
|
+
}
|
|
677
|
+
const skipped = items.skipped;
|
|
678
|
+
if (skipped > 0) err(io, `warning: ${skipped} unreadable line(s) skipped; the export is incomplete`);
|
|
679
|
+
if (outPath && values.json) outJson(io, { out: outPath, format, items: count, skipped });
|
|
680
|
+
else if (outPath) err(io, `${count} item(s) written to ${values.out}`);
|
|
681
|
+
return skipped > 0 ? 1 : 0;
|
|
682
|
+
}
|
|
683
|
+
async function runInit(argv, io) {
|
|
684
|
+
const { values, positionals } = parse(argv, {});
|
|
685
|
+
const [path] = positional(positionals, "store");
|
|
686
|
+
const root = resolve(io.cwd, path);
|
|
687
|
+
const store = await initStore(root);
|
|
688
|
+
const schemaVersion = await store.schemaVersion();
|
|
689
|
+
if (values.json) outJson(io, { store: root, schemaVersion });
|
|
690
|
+
else out(io, `store ready at ${root} (schema version ${schemaVersion})`);
|
|
691
|
+
return 0;
|
|
692
|
+
}
|
|
693
|
+
var STORE_OPTION = { store: { type: "string" } };
|
|
694
|
+
async function runRuns(argv, io) {
|
|
695
|
+
const { values, positionals } = parse(argv, STORE_OPTION);
|
|
696
|
+
positional(positionals, "none", 0);
|
|
697
|
+
const store = await open(storePathOf(io, values.store));
|
|
698
|
+
const rows = [];
|
|
699
|
+
for (const id of (await store.listRuns()).sort()) {
|
|
700
|
+
const run = await store.getRun(id);
|
|
701
|
+
const report = await store.readReport(id);
|
|
702
|
+
rows.push({
|
|
703
|
+
runId: id,
|
|
704
|
+
name: run?.recipe.name,
|
|
705
|
+
createdAt: run?.createdAt,
|
|
706
|
+
state: run?.origin === "reparse" ? "reparsed" : report?.finishedAt ? "finished" : "unfinished",
|
|
707
|
+
connectors: (report?.connectors ?? []).map((c) => ({ connector: c.connector, status: c.status }))
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
if (values.json) outJson(io, rows);
|
|
711
|
+
else if (rows.length === 0) out(io, "no runs yet");
|
|
712
|
+
else {
|
|
713
|
+
out(io, table([["run", "name", "created", "state"], ...rows.map((r) => [r.runId, r.name ?? "", r.createdAt ?? "", r.state])]));
|
|
714
|
+
}
|
|
715
|
+
return 0;
|
|
716
|
+
}
|
|
717
|
+
async function runStatus(argv, io) {
|
|
718
|
+
const { values, positionals } = parse(argv, STORE_OPTION);
|
|
719
|
+
const [runId] = positional(positionals, "runId");
|
|
720
|
+
const store = await open(storePathOf(io, values.store));
|
|
721
|
+
const run = await store.getRun(runId);
|
|
722
|
+
if (!run) throw new UsageError(`unknown run ${runId}`);
|
|
723
|
+
const report = await store.readReport(runId);
|
|
724
|
+
const latest = /* @__PURE__ */ new Map();
|
|
725
|
+
for (const t of (await readAll(store.tasks(runId))).records) latest.set(`${t.connector}/${t.taskId}`, t);
|
|
726
|
+
const byStatus = {};
|
|
727
|
+
const failures = {};
|
|
728
|
+
for (const t of latest.values()) {
|
|
729
|
+
byStatus[t.status] = (byStatus[t.status] ?? 0) + 1;
|
|
730
|
+
if (t.status === "failed") failures[t.cause ?? "other"] = (failures[t.cause ?? "other"] ?? 0) + 1;
|
|
731
|
+
}
|
|
732
|
+
const state = run.origin === "reparse" ? "reparsed" : report?.finishedAt ? "finished" : "unfinished";
|
|
733
|
+
if (values.json) {
|
|
734
|
+
outJson(io, { runId, name: run.recipe.name, createdAt: run.createdAt, state, tasks: byStatus, failures, report: report ?? null });
|
|
735
|
+
return 0;
|
|
736
|
+
}
|
|
737
|
+
out(io, `run ${runId}${run.recipe.name ? ` (${run.recipe.name})` : ""}: ${state}`);
|
|
738
|
+
out(io, `tasks: ${Object.entries(byStatus).map(([k, v]) => `${k}=${v}`).join(" ") || "none"}`);
|
|
739
|
+
if (Object.keys(failures).length) out(io, `failures: ${Object.entries(failures).map(([k, v]) => `${k}=${v}`).join(" ")}`);
|
|
740
|
+
if (report) {
|
|
741
|
+
out(io, table([["connector", "status", "new", "obs", "dup"], ...report.connectors.map((c) => [c.connector, c.status, String(c.newItems), String(c.observations), String(c.duplicates)])]));
|
|
742
|
+
}
|
|
743
|
+
if (state === "unfinished") out(io, `continue with: collect resume ${runId}`);
|
|
744
|
+
if (state === "reparsed") out(io, "this is a copy kept by reparse: it can be reparsed again but not resumed");
|
|
745
|
+
return 0;
|
|
746
|
+
}
|
|
747
|
+
async function ingestRaw(target, connector, entry, position, bytes, task, writtenActors, totals) {
|
|
748
|
+
const parsed = await connector.parse({
|
|
749
|
+
connector: connector.id,
|
|
750
|
+
task: CollectTask.parse(task),
|
|
751
|
+
raw: { ref: entry.ref, url: entry.url, ext: entry.ext, bytes, httpStatus: entry.httpStatus, contentType: entry.contentType, fetchedAt: entry.fetchedAt, transport: entry.transport }
|
|
752
|
+
});
|
|
753
|
+
const keyOf = (kind, i) => sha256Hex(JSON.stringify([entry.runId ?? "", "reparse", position, entry.hash, kind, i]));
|
|
754
|
+
const items = [];
|
|
755
|
+
for (const p of parsed.items ?? []) {
|
|
756
|
+
const canonical = p.canonicalUrl ?? (p.url ? canonicalUrl(p.url) : void 0);
|
|
757
|
+
const id = p.id ?? (canonical ? await itemIdFromUrl(p.source, canonical) : void 0);
|
|
758
|
+
if (!id) throw new Error("an item needs an id or a url");
|
|
759
|
+
const contentId = p.contentId ?? (p.text ? await textFingerprint(p.text) : void 0);
|
|
760
|
+
const item = CollectItem.parse({
|
|
761
|
+
...p,
|
|
762
|
+
id,
|
|
763
|
+
canonicalUrl: canonical,
|
|
764
|
+
contentId,
|
|
765
|
+
firstSeenAt: p.firstSeenAt ?? entry.fetchedAt,
|
|
766
|
+
runId: entry.runId,
|
|
767
|
+
rawRefs: [.../* @__PURE__ */ new Set([...p.rawRefs ?? [], entry.ref])]
|
|
768
|
+
});
|
|
769
|
+
if (connector.ext && item.ext !== void 0) connector.ext.parse(item.ext);
|
|
770
|
+
items.push(item);
|
|
771
|
+
}
|
|
772
|
+
const observations = [];
|
|
773
|
+
for (const [i, o] of (parsed.observations ?? []).entries()) {
|
|
774
|
+
observations.push(
|
|
775
|
+
Observation.parse({ measuredAt: entry.fetchedAt, transport: entry.transport, rawRef: entry.ref, ...o, runId: entry.runId, taskId: "reparse", recordKey: await keyOf("observation", i) })
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
const pickups = [];
|
|
779
|
+
for (const [i, p] of (parsed.pickups ?? []).entries()) {
|
|
780
|
+
pickups.push(
|
|
781
|
+
Pickup.parse({
|
|
782
|
+
firstSeenAt: entry.fetchedAt,
|
|
783
|
+
measuredAt: entry.fetchedAt,
|
|
784
|
+
...p,
|
|
785
|
+
runId: entry.runId,
|
|
786
|
+
taskId: "reparse",
|
|
787
|
+
recordKey: await keyOf("pickup", i),
|
|
788
|
+
evidence: { rawRef: entry.ref, ...p.evidence }
|
|
789
|
+
})
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
const actors = (parsed.actors ?? []).map((a) => Actor.parse(a));
|
|
793
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
794
|
+
const resolveId = async (id) => idMap.get(id) ?? await target.seenGet(seenKey("id", id)) ?? id;
|
|
795
|
+
const created = [];
|
|
796
|
+
for (const item of items) {
|
|
797
|
+
const idKey = seenKey("id", item.id);
|
|
798
|
+
let owner = await target.seenGet(idKey);
|
|
799
|
+
if (owner === void 0 && await target.seenHas(idKey)) owner = item.id;
|
|
800
|
+
let level = owner ? 1 : 0;
|
|
801
|
+
if (!owner && item.canonicalUrl) {
|
|
802
|
+
owner = await target.seenGet(seenKey("url", item.canonicalUrl));
|
|
803
|
+
if (owner) level = 2;
|
|
804
|
+
}
|
|
805
|
+
if (owner) {
|
|
806
|
+
idMap.set(item.id, owner);
|
|
807
|
+
if (level === 2) await target.seenAdd(idKey, owner);
|
|
808
|
+
totals.duplicates++;
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
await target.upsertItem(item);
|
|
812
|
+
for (const k of itemSeenKeys(item)) await target.seenAdd(k, item.id);
|
|
813
|
+
created.push(item);
|
|
814
|
+
totals.items++;
|
|
815
|
+
}
|
|
816
|
+
for (const item of created) {
|
|
817
|
+
if (!item.links) continue;
|
|
818
|
+
const links = { ...item.links };
|
|
819
|
+
let changed = false;
|
|
820
|
+
for (const name of ["target", "parent", "root", "quoted"]) {
|
|
821
|
+
const v = links[name];
|
|
822
|
+
if (v === void 0) continue;
|
|
823
|
+
const r = await resolveId(v);
|
|
824
|
+
if (r !== v) {
|
|
825
|
+
links[name] = r;
|
|
826
|
+
changed = true;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
if (changed) await target.upsertItem({ ...item, links });
|
|
830
|
+
}
|
|
831
|
+
for (const o of observations) {
|
|
832
|
+
await target.appendObservation({ ...o, itemId: await resolveId(o.itemId) });
|
|
833
|
+
totals.observations++;
|
|
834
|
+
}
|
|
835
|
+
for (const a of actors) {
|
|
836
|
+
const k = stableStringify(a);
|
|
837
|
+
if (writtenActors.has(k)) continue;
|
|
838
|
+
writtenActors.add(k);
|
|
839
|
+
await target.appendActor(a);
|
|
840
|
+
totals.actors++;
|
|
841
|
+
}
|
|
842
|
+
for (const p of pickups) {
|
|
843
|
+
await target.appendPickup({ ...p, itemId: await resolveId(p.itemId), ...p.pickupItemId ? { pickupItemId: await resolveId(p.pickupItemId) } : {} });
|
|
844
|
+
totals.pickups++;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
async function realTarget(path) {
|
|
848
|
+
const rest = [];
|
|
849
|
+
let cur = path;
|
|
850
|
+
for (; ; ) {
|
|
851
|
+
try {
|
|
852
|
+
return join(await realpath(cur), ...rest.reverse());
|
|
853
|
+
} catch (e) {
|
|
854
|
+
if (e.code !== "ENOENT") throw e;
|
|
855
|
+
const parent = dirname(cur);
|
|
856
|
+
if (parent === cur) throw e;
|
|
857
|
+
rest.push(basename(cur));
|
|
858
|
+
cur = parent;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
var inside = (child, parent) => child === parent || child.startsWith(parent + sep);
|
|
863
|
+
async function copyRuns(source, target, referenced, problems) {
|
|
864
|
+
for (const [runId, taskIds] of referenced) {
|
|
865
|
+
const run = await source.getRun(runId);
|
|
866
|
+
if (!run) continue;
|
|
867
|
+
await target.createRun(runId, run.recipe, { ...run.connectorModules ? { connectorModules: run.connectorModules } : {}, origin: "reparse" });
|
|
868
|
+
const plan = (await source.readPlan(runId))?.filter((e) => taskIds.has(e.taskId));
|
|
869
|
+
if (plan?.length) await target.writePlan(runId, plan);
|
|
870
|
+
const log = source.tasks(runId);
|
|
871
|
+
for await (const t of log) if (taskIds.has(t.taskId)) await target.appendTask(runId, t);
|
|
872
|
+
if (log.skipped) problems.push(`run ${runId}: ${log.skipped} unreadable line(s) in its task log were not copied`);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
async function originalTask(source, cache, entry) {
|
|
876
|
+
if (!entry.runId || !entry.taskId) return void 0;
|
|
877
|
+
let tasks = cache.get(entry.runId);
|
|
878
|
+
if (!tasks) {
|
|
879
|
+
tasks = /* @__PURE__ */ new Map();
|
|
880
|
+
for await (const t of source.tasks(entry.runId)) {
|
|
881
|
+
const p = t.payload;
|
|
882
|
+
if (p && typeof p.id === "string") tasks.set(t.taskId, { id: p.id, ...p.kind ? { kind: p.kind } : {}, params: p.params ?? {} });
|
|
883
|
+
}
|
|
884
|
+
cache.set(entry.runId, tasks);
|
|
885
|
+
}
|
|
886
|
+
return tasks.get(entry.taskId);
|
|
887
|
+
}
|
|
888
|
+
async function runReparse(argv, io) {
|
|
889
|
+
const { values, positionals } = parse(argv, { ...CONNECTOR_OPTION, store: { type: "string" }, into: { type: "string" } });
|
|
890
|
+
positional(positionals, "none", 0);
|
|
891
|
+
if (!values.into) throw new UsageError("reparse needs --into <new store path>: the source store is never rewritten in place");
|
|
892
|
+
const sourcePath = storePathOf(io, values.store);
|
|
893
|
+
const wanted = resolve(io.cwd, values.into);
|
|
894
|
+
const loadedAll = await loadConnectors(values.connector ?? [], io.cwd);
|
|
895
|
+
announce(io, loadedAll);
|
|
896
|
+
const { registry } = loadedAll;
|
|
897
|
+
const source = await open(sourcePath);
|
|
898
|
+
const exists = await lstat(wanted).then(
|
|
899
|
+
() => true,
|
|
900
|
+
(e) => {
|
|
901
|
+
if (e.code === "ENOENT") return false;
|
|
902
|
+
throw new UsageError(`--into ${values.into} cannot be used: ${e.message}`);
|
|
903
|
+
}
|
|
904
|
+
);
|
|
905
|
+
if (exists) throw new UsageError(`--into ${values.into} already exists; reparse writes a new store and never reuses a path`);
|
|
906
|
+
const target = await realTarget(wanted);
|
|
907
|
+
const realSource = await realpath(sourcePath);
|
|
908
|
+
if (inside(target, realSource) || inside(realSource, target)) {
|
|
909
|
+
throw new UsageError("--into and the source store must not contain each other (symlinks resolved)");
|
|
910
|
+
}
|
|
911
|
+
await mkdir(dirname(target), { recursive: true });
|
|
912
|
+
try {
|
|
913
|
+
await mkdir(target);
|
|
914
|
+
} catch (e) {
|
|
915
|
+
if (e.code === "EEXIST") throw new UsageError(`--into ${values.into} was taken by another process`);
|
|
916
|
+
throw e;
|
|
917
|
+
}
|
|
918
|
+
const totals = {
|
|
919
|
+
raws: 0,
|
|
920
|
+
parsed: 0,
|
|
921
|
+
failedRaws: 0,
|
|
922
|
+
legacyTaskFallbacks: 0,
|
|
923
|
+
skippedIndexLines: 0,
|
|
924
|
+
interrupted: false,
|
|
925
|
+
items: 0,
|
|
926
|
+
duplicates: 0,
|
|
927
|
+
observations: 0,
|
|
928
|
+
actors: 0,
|
|
929
|
+
pickups: 0,
|
|
930
|
+
problems: []
|
|
931
|
+
};
|
|
932
|
+
let sourceLock;
|
|
933
|
+
let targetLock;
|
|
934
|
+
try {
|
|
935
|
+
sourceLock = await source.acquireLock();
|
|
936
|
+
const out2 = await initStore(target);
|
|
937
|
+
targetLock = await out2.acquireLock();
|
|
938
|
+
const writtenActors = /* @__PURE__ */ new Set();
|
|
939
|
+
const taskCache = /* @__PURE__ */ new Map();
|
|
940
|
+
const referenced = /* @__PURE__ */ new Map();
|
|
941
|
+
let position = 0;
|
|
942
|
+
const index = source.rawIndex();
|
|
943
|
+
for await (const entry of index) {
|
|
944
|
+
if (io.signal?.aborted) {
|
|
945
|
+
totals.interrupted = true;
|
|
946
|
+
break;
|
|
947
|
+
}
|
|
948
|
+
totals.raws++;
|
|
949
|
+
if (!values.quiet && (totals.raws === 1 || totals.raws % 25 === 0)) err(io, `[reparse] ${totals.raws} raw(s)`);
|
|
950
|
+
const bytes = await source.getRaw(entry.ref);
|
|
951
|
+
if (!bytes) {
|
|
952
|
+
totals.problems.push(`${entry.ref}: raw body is missing`);
|
|
953
|
+
position++;
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
if (entry.runId && entry.taskId) {
|
|
957
|
+
const ids = referenced.get(entry.runId) ?? /* @__PURE__ */ new Set();
|
|
958
|
+
ids.add(entry.taskId);
|
|
959
|
+
referenced.set(entry.runId, ids);
|
|
960
|
+
}
|
|
961
|
+
await out2.putRaw({
|
|
962
|
+
connector: entry.connector,
|
|
963
|
+
ext: entry.ext,
|
|
964
|
+
bytes,
|
|
965
|
+
url: entry.url,
|
|
966
|
+
fetchedAt: entry.fetchedAt,
|
|
967
|
+
httpStatus: entry.httpStatus,
|
|
968
|
+
contentType: entry.contentType,
|
|
969
|
+
transport: entry.transport,
|
|
970
|
+
runId: entry.runId,
|
|
971
|
+
taskId: entry.taskId,
|
|
972
|
+
failure: entry.failure
|
|
973
|
+
});
|
|
974
|
+
if (entry.failure) {
|
|
975
|
+
totals.failedRaws++;
|
|
976
|
+
position++;
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
979
|
+
const connector = registry.get(entry.connector);
|
|
980
|
+
if (!connector) {
|
|
981
|
+
const msg = `connector "${entry.connector}" is not registered (load it with --connector <module>)`;
|
|
982
|
+
if (!totals.problems.includes(msg)) totals.problems.push(msg);
|
|
983
|
+
position++;
|
|
984
|
+
continue;
|
|
985
|
+
}
|
|
986
|
+
let task = await originalTask(source, taskCache, entry);
|
|
987
|
+
if (!task) {
|
|
988
|
+
totals.legacyTaskFallbacks++;
|
|
989
|
+
task = { id: `reparse:${entry.hash.slice(0, 12)}`, params: {} };
|
|
990
|
+
}
|
|
991
|
+
try {
|
|
992
|
+
await ingestRaw(out2, connector, entry, position, bytes, task, writtenActors, totals);
|
|
993
|
+
totals.parsed++;
|
|
994
|
+
} catch (e) {
|
|
995
|
+
totals.problems.push(`${entry.ref}: ${e instanceof Error ? e.message : String(e)}`);
|
|
996
|
+
}
|
|
997
|
+
position++;
|
|
998
|
+
}
|
|
999
|
+
totals.skippedIndexLines = index.skipped;
|
|
1000
|
+
await copyRuns(source, out2, referenced, totals.problems);
|
|
1001
|
+
} catch (e) {
|
|
1002
|
+
if (!targetLock) await rm(target, { recursive: true, force: true }).catch(() => void 0);
|
|
1003
|
+
throw e;
|
|
1004
|
+
} finally {
|
|
1005
|
+
await targetLock?.release().catch(() => void 0);
|
|
1006
|
+
await sourceLock?.release().catch(() => void 0);
|
|
1007
|
+
}
|
|
1008
|
+
if (values.json) outJson(io, { into: target, ...totals });
|
|
1009
|
+
else {
|
|
1010
|
+
out(io, `reparsed ${totals.parsed} of ${totals.raws} raw(s) into ${target}`);
|
|
1011
|
+
out(io, `items=${totals.items} duplicates=${totals.duplicates} observations=${totals.observations} actors=${totals.actors} pickups=${totals.pickups} failedRaws=${totals.failedRaws}`);
|
|
1012
|
+
if (totals.legacyTaskFallbacks) err(io, `warning: ${totals.legacyTaskFallbacks} raw(s) have no recorded task; parsed with a synthetic task, results may differ`);
|
|
1013
|
+
if (totals.skippedIndexLines) err(io, `warning: ${totals.skippedIndexLines} unreadable line(s) in the raw index were skipped`);
|
|
1014
|
+
if (totals.interrupted) err(io, "interrupted: the new store is incomplete");
|
|
1015
|
+
for (const p of totals.problems) err(io, `problem: ${p}`);
|
|
1016
|
+
}
|
|
1017
|
+
const clean = totals.problems.length === 0 && totals.legacyTaskFallbacks === 0 && totals.skippedIndexLines === 0 && !totals.interrupted;
|
|
1018
|
+
return clean ? 0 : 1;
|
|
1019
|
+
}
|
|
1020
|
+
var RUN_OPTIONS = {
|
|
1021
|
+
...CONNECTOR_OPTION,
|
|
1022
|
+
store: { type: "string" },
|
|
1023
|
+
"rate-ms": { type: "string" },
|
|
1024
|
+
...BROWSER_OPTIONS
|
|
1025
|
+
};
|
|
1026
|
+
function rateOf(value) {
|
|
1027
|
+
if (value === void 0) return void 0;
|
|
1028
|
+
if (!/^\d+$/.test(value)) throw new UsageError(`--rate-ms must be a non-negative integer, got "${value}"`);
|
|
1029
|
+
return Number(value);
|
|
1030
|
+
}
|
|
1031
|
+
async function runRun(argv, io) {
|
|
1032
|
+
const { values, positionals } = parse(argv, {
|
|
1033
|
+
...RUN_OPTIONS,
|
|
1034
|
+
source: { type: "string", multiple: true },
|
|
1035
|
+
query: { type: "string", multiple: true },
|
|
1036
|
+
subject: { type: "string" },
|
|
1037
|
+
max: { type: "string" },
|
|
1038
|
+
"dry-run": { type: "boolean" }
|
|
1039
|
+
});
|
|
1040
|
+
if (positionals.length > 1) positional(positionals, "recipe", 1);
|
|
1041
|
+
const max = intOption("max", values.max);
|
|
1042
|
+
const rateMs = rateOf(values["rate-ms"]);
|
|
1043
|
+
const browser = browserConfig(values, io.env);
|
|
1044
|
+
const modules = [...values.connector ?? []];
|
|
1045
|
+
let recipe;
|
|
1046
|
+
if (positionals[0]) {
|
|
1047
|
+
const loaded = await loadRecipe(positionals[0], io.cwd);
|
|
1048
|
+
modules.push(...loaded.connectors);
|
|
1049
|
+
recipe = loaded.recipe;
|
|
1050
|
+
if (values.source?.length) {
|
|
1051
|
+
const unknown = values.source.filter((s) => !recipe.sources.some((r) => r.connector === s));
|
|
1052
|
+
if (unknown.length) throw new UsageError(`--source ${unknown.join(", ")} is not in the recipe`);
|
|
1053
|
+
recipe = { ...recipe, sources: recipe.sources.filter((s) => values.source.includes(s.connector)) };
|
|
1054
|
+
}
|
|
1055
|
+
if (values.query?.length) {
|
|
1056
|
+
if (!values.subject) throw new UsageError("--query needs --subject");
|
|
1057
|
+
const queries = values.query.map((text) => ({ text, subject: values.subject }));
|
|
1058
|
+
recipe = { ...recipe, sources: recipe.sources.map((s) => ({ ...s, queries })) };
|
|
1059
|
+
}
|
|
1060
|
+
} else {
|
|
1061
|
+
if (!values.source?.length) throw new UsageError("give a recipe file, or --source <connector> for a trial run");
|
|
1062
|
+
if (values.query?.length && !values.subject) throw new UsageError("--query needs --subject");
|
|
1063
|
+
const queries = (values.query ?? []).map((text) => ({ text, subject: values.subject }));
|
|
1064
|
+
recipe = validateRecipe({ name: "trial", sources: values.source.map((connector) => ({ connector, queries })) }, "built from the command line");
|
|
1065
|
+
}
|
|
1066
|
+
if (max !== void 0) recipe = { ...recipe, caps: { ...recipe.caps, total: max } };
|
|
1067
|
+
recipe = validateRecipe(recipe, "after applying the command-line options");
|
|
1068
|
+
const moduleFiles = [...new Set(modules.map((m) => resolve(io.cwd, m)))];
|
|
1069
|
+
const loadedConnectors = await loadConnectors(moduleFiles, io.cwd);
|
|
1070
|
+
announce(io, loadedConnectors);
|
|
1071
|
+
if (values["dry-run"]) {
|
|
1072
|
+
const tasks = [];
|
|
1073
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1074
|
+
for (const id of new Set(recipe.sources.map((s) => s.connector))) {
|
|
1075
|
+
const c = loadedConnectors.registry.get(id);
|
|
1076
|
+
if (!c) throw new UsageError(`connector "${id}" is not registered (load it with --connector <module>)`);
|
|
1077
|
+
const sources = recipe.sources.filter((s) => s.connector === id);
|
|
1078
|
+
for (const t of c.plan(recipe, sources)) {
|
|
1079
|
+
const task = CollectTask.parse(t);
|
|
1080
|
+
if (seen.has(`${id}/${task.id}`)) continue;
|
|
1081
|
+
seen.add(`${id}/${task.id}`);
|
|
1082
|
+
tasks.push({ connector: id, id: task.id, ...task.kind ? { kind: task.kind } : {}, params: task.params });
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if (values.json) outJson(io, { dryRun: true, tasks, sampling: recipe.sampling ?? null, lookahead: recipe.lookahead ?? null });
|
|
1086
|
+
else {
|
|
1087
|
+
out(io, `dry run: ${tasks.length} planned task${tasks.length === 1 ? "" : "s"}, nothing fetched or written`);
|
|
1088
|
+
if (recipe.sampling) out(io, "sampling (bands, quotas, caps) applies to what the tasks return and is not simulated");
|
|
1089
|
+
if (recipe.lookahead !== void 0) out(io, `lookahead: ${recipe.lookahead}`);
|
|
1090
|
+
if (tasks.length) out(io, table(tasks.map((t) => [t.connector, t.id, t.kind ?? "", JSON.stringify(t.params)])));
|
|
1091
|
+
}
|
|
1092
|
+
return 0;
|
|
1093
|
+
}
|
|
1094
|
+
return execute(io, {
|
|
1095
|
+
storePath: storePathOf(io, values.store),
|
|
1096
|
+
json: Boolean(values.json),
|
|
1097
|
+
quiet: Boolean(values.quiet),
|
|
1098
|
+
loaded: loadedConnectors,
|
|
1099
|
+
rateMs,
|
|
1100
|
+
browser,
|
|
1101
|
+
start: (collector, onEvent) => collector.run(recipe, { signal: io.signal, onEvent, connectorModules: moduleFiles })
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
async function runResume(argv, io) {
|
|
1105
|
+
const { values, positionals } = parse(argv, RUN_OPTIONS);
|
|
1106
|
+
const [runId] = positional(positionals, "runId");
|
|
1107
|
+
const rateMs = rateOf(values["rate-ms"]);
|
|
1108
|
+
const storePath = storePathOf(io, values.store);
|
|
1109
|
+
const run = await (await open(storePath)).getRun(runId);
|
|
1110
|
+
if (!run) throw new UsageError(`unknown run ${runId}`);
|
|
1111
|
+
if (run.origin === "reparse") throw new UsageError(`run ${runId} is a copy kept by reparse and cannot be resumed; run its recipe again instead`);
|
|
1112
|
+
const modules = [.../* @__PURE__ */ new Set([...run.connectorModules ?? [], ...(values.connector ?? []).map((m) => resolve(io.cwd, m))])];
|
|
1113
|
+
const loaded = await loadConnectors(modules, io.cwd);
|
|
1114
|
+
announce(io, loaded);
|
|
1115
|
+
return execute(io, {
|
|
1116
|
+
storePath,
|
|
1117
|
+
json: Boolean(values.json),
|
|
1118
|
+
quiet: Boolean(values.quiet),
|
|
1119
|
+
loaded,
|
|
1120
|
+
rateMs,
|
|
1121
|
+
browser: browserConfig(values, io.env),
|
|
1122
|
+
start: (collector, onEvent) => collector.resume(runId, { signal: io.signal, onEvent })
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
function readVersion() {
|
|
1126
|
+
try {
|
|
1127
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
1128
|
+
const pkg = JSON.parse(readFileSync(resolve(here, "../package.json"), "utf8"));
|
|
1129
|
+
return pkg.version ?? "0.0.0";
|
|
1130
|
+
} catch {
|
|
1131
|
+
return "0.0.0";
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
var VERSION = readVersion();
|
|
1135
|
+
|
|
1136
|
+
// src/main.ts
|
|
1137
|
+
function defaultIo() {
|
|
1138
|
+
return { stdout: process.stdout, stderr: process.stderr, env: process.env, cwd: process.cwd() };
|
|
1139
|
+
}
|
|
1140
|
+
var HELP = `collect: collect public posts and articles with provenance (v${VERSION})
|
|
1141
|
+
|
|
1142
|
+
Commands:
|
|
1143
|
+
init <store> Create a store
|
|
1144
|
+
connectors List the connectors that are registered or loaded
|
|
1145
|
+
doctor [recipe.yaml] Check connectors: access level, secret (name only), transports, browser session
|
|
1146
|
+
[--source id]... (default: every registered connector)
|
|
1147
|
+
With a browser configured: lists its tools, opens and closes a blank tab,
|
|
1148
|
+
and asks each session connector whether its site has an open session.
|
|
1149
|
+
run [recipe.yaml] Run a recipe
|
|
1150
|
+
[--source id]... [--query text]... [--subject label] [--max n]
|
|
1151
|
+
[--dry-run] [--store path]
|
|
1152
|
+
Without a recipe, --source (and --query with --subject) makes a trial run.
|
|
1153
|
+
resume <runId> Continue an interrupted run (done tasks are not fetched again)
|
|
1154
|
+
runs List the runs of a store
|
|
1155
|
+
status <runId> Task states and report of one run
|
|
1156
|
+
export Items as JSONL (default) or --format csv
|
|
1157
|
+
[--source id] [--out file]
|
|
1158
|
+
reparse --into <new store> Rebuild items, observations, actors and pickups from stored raws.
|
|
1159
|
+
No network; the source store is never modified. The copy keeps the run
|
|
1160
|
+
records of its raws for reparsing again; it is not meant for resume.
|
|
1161
|
+
|
|
1162
|
+
Browser (run, resume, doctor), over an MCP server for an already-connected browser:
|
|
1163
|
+
--browser-mcp url streamable-HTTP endpoint ($COLLECT_BROWSER_MCP)
|
|
1164
|
+
--browser-profile name chrome-devtools (default, stable page ids), chrome-devtools-index (older
|
|
1165
|
+
servers that name pages by index; exclusive mode) or tab-tools
|
|
1166
|
+
($COLLECT_BROWSER_PROFILE)
|
|
1167
|
+
--browser-proxy-tool name reach the browser tools through one tool taking { alias, toolName, args }
|
|
1168
|
+
--browser-alias name alias sent to the proxy tool (both go together)
|
|
1169
|
+
--browser-instance name browser instance sent with every call (tab-tools)
|
|
1170
|
+
--browser-pace min-max wait between page actions in ms, e.g. 2000-6000 (default; $COLLECT_BROWSER_PACE)
|
|
1171
|
+
--browser-header 'Name: v' extra header, e.g. authorisation (repeatable; $COLLECT_BROWSER_HEADER, one
|
|
1172
|
+
per line). Values never appear in output.
|
|
1173
|
+
The browser only reads pages: no clicks, no typing, no forms.
|
|
1174
|
+
|
|
1175
|
+
Options on every command:
|
|
1176
|
+
--json machine output on stdout (progress stays on stderr)
|
|
1177
|
+
--store path store to use (default: $COLLECT_STORE or ./collect-store)
|
|
1178
|
+
--connector f load connector modules from a file (repeatable; also "connectors:" in a recipe)
|
|
1179
|
+
-q, --quiet no progress on stderr
|
|
1180
|
+
-h, --help this help
|
|
1181
|
+
|
|
1182
|
+
Exit codes: 0 success, 1 partial failure, 2 usage error, 3 store locked or unreadable.
|
|
1183
|
+
`;
|
|
1184
|
+
var COMMANDS = {
|
|
1185
|
+
init: runInit,
|
|
1186
|
+
connectors: runConnectors,
|
|
1187
|
+
doctor: runDoctor,
|
|
1188
|
+
run: runRun,
|
|
1189
|
+
resume: runResume,
|
|
1190
|
+
runs: runRuns,
|
|
1191
|
+
status: runStatus,
|
|
1192
|
+
export: runExport,
|
|
1193
|
+
reparse: runReparse
|
|
1194
|
+
};
|
|
1195
|
+
function guarded(io) {
|
|
1196
|
+
const redactors = [];
|
|
1197
|
+
const scrub = (text) => redactors.reduce((t, r) => r(t), text);
|
|
1198
|
+
const wrap = (s) => ({
|
|
1199
|
+
write: (chunk) => s.write(redactors.length ? scrub(chunk) : chunk),
|
|
1200
|
+
once: s.once ? s.once.bind(s) : void 0
|
|
1201
|
+
});
|
|
1202
|
+
return { ...io, stdout: wrap(io.stdout), stderr: wrap(io.stderr), addRedactor: (r) => void redactors.push(r) };
|
|
1203
|
+
}
|
|
1204
|
+
async function main(argv, io = defaultIo()) {
|
|
1205
|
+
const [cmd, ...rest] = argv;
|
|
1206
|
+
if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") {
|
|
1207
|
+
out(io, HELP);
|
|
1208
|
+
return cmd ? 0 : 2;
|
|
1209
|
+
}
|
|
1210
|
+
if (cmd === "--version" || cmd === "-v") {
|
|
1211
|
+
out(io, VERSION);
|
|
1212
|
+
return 0;
|
|
1213
|
+
}
|
|
1214
|
+
const run = Object.hasOwn(COMMANDS, cmd) ? COMMANDS[cmd] : void 0;
|
|
1215
|
+
if (!run) {
|
|
1216
|
+
err(io, `collect: unknown command "${cmd}". Try --help.`);
|
|
1217
|
+
return 2;
|
|
1218
|
+
}
|
|
1219
|
+
if (rest.includes("--help") || rest.includes("-h")) {
|
|
1220
|
+
out(io, HELP);
|
|
1221
|
+
return 0;
|
|
1222
|
+
}
|
|
1223
|
+
const safe = guarded(io);
|
|
1224
|
+
try {
|
|
1225
|
+
return await run(rest, safe);
|
|
1226
|
+
} catch (e) {
|
|
1227
|
+
const c = classify(e);
|
|
1228
|
+
if (c) {
|
|
1229
|
+
err(safe, `collect: ${c.message}`);
|
|
1230
|
+
return c.code;
|
|
1231
|
+
}
|
|
1232
|
+
err(safe, `collect: ${e instanceof Error ? e.message : String(e)}`);
|
|
1233
|
+
return 1;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
// src/cli.ts
|
|
1238
|
+
process.exitCode = 1;
|
|
1239
|
+
process.stdout.on("error", () => process.exit(1));
|
|
1240
|
+
var controller = new AbortController();
|
|
1241
|
+
process.once("SIGINT", () => controller.abort());
|
|
1242
|
+
process.once("SIGTERM", () => controller.abort());
|
|
1243
|
+
main(process.argv.slice(2), { ...defaultIo(), signal: controller.signal }).then((code) => {
|
|
1244
|
+
process.exitCode = code;
|
|
1245
|
+
process.stdout.write("", () => void 0);
|
|
1246
|
+
setTimeout(() => process.exit(code), 5e3).unref();
|
|
1247
|
+
}).catch((err2) => {
|
|
1248
|
+
process.stderr.write(`collect: unhandled error: ${err2 instanceof Error ? err2.message : String(err2)}
|
|
1249
|
+
`);
|
|
1250
|
+
process.exit(1);
|
|
1251
|
+
});
|
|
1252
|
+
//# sourceMappingURL=cli.mjs.map
|
|
1253
|
+
//# sourceMappingURL=cli.mjs.map
|