@b3os/cli 0.0.1 → 0.1.3

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.
Files changed (76) hide show
  1. package/README.md +71 -34
  2. package/bin/b3os.js +13 -3
  3. package/dist/commands/_common.d.ts +49 -0
  4. package/dist/commands/_common.js +174 -0
  5. package/dist/commands/_common.js.map +1 -0
  6. package/dist/commands/actions.d.ts +43 -0
  7. package/dist/commands/actions.js +184 -0
  8. package/dist/commands/actions.js.map +1 -0
  9. package/dist/commands/api.d.ts +24 -0
  10. package/dist/commands/api.js +14 -8
  11. package/dist/commands/api.js.map +1 -1
  12. package/dist/commands/auth.d.ts +58 -0
  13. package/dist/commands/auth.js +215 -19
  14. package/dist/commands/auth.js.map +1 -1
  15. package/dist/commands/bench.d.ts +22 -0
  16. package/dist/commands/bench.js +19 -7
  17. package/dist/commands/bench.js.map +1 -1
  18. package/dist/commands/connect.d.ts +52 -0
  19. package/dist/commands/connect.js +221 -0
  20. package/dist/commands/connect.js.map +1 -0
  21. package/dist/commands/infer.d.ts +47 -0
  22. package/dist/commands/infer.js +152 -0
  23. package/dist/commands/infer.js.map +1 -0
  24. package/dist/commands/init.d.ts +45 -0
  25. package/dist/commands/init.js +267 -0
  26. package/dist/commands/init.js.map +1 -0
  27. package/dist/commands/keys.d.ts +42 -0
  28. package/dist/commands/keys.js +70 -38
  29. package/dist/commands/keys.js.map +1 -1
  30. package/dist/commands/manifest.d.ts +13 -0
  31. package/dist/commands/manifest.js +117 -0
  32. package/dist/commands/manifest.js.map +1 -0
  33. package/dist/commands/mcp.d.ts +65 -0
  34. package/dist/commands/mcp.js +167 -50
  35. package/dist/commands/mcp.js.map +1 -1
  36. package/dist/commands/render.d.ts +119 -0
  37. package/dist/commands/render.js +294 -0
  38. package/dist/commands/render.js.map +1 -0
  39. package/dist/commands/requests.d.ts +34 -0
  40. package/dist/commands/requests.js +63 -0
  41. package/dist/commands/requests.js.map +1 -0
  42. package/dist/commands/routine.d.ts +53 -1
  43. package/dist/commands/routine.js +246 -110
  44. package/dist/commands/routine.js.map +1 -1
  45. package/dist/commands/sandbox.d.ts +130 -0
  46. package/dist/commands/sandbox.js +327 -55
  47. package/dist/commands/sandbox.js.map +1 -1
  48. package/dist/commands/vision.d.ts +196 -0
  49. package/dist/commands/vision.js +478 -0
  50. package/dist/commands/vision.js.map +1 -0
  51. package/dist/commands/webhooks.d.ts +20 -0
  52. package/dist/commands/webhooks.js +76 -0
  53. package/dist/commands/webhooks.js.map +1 -0
  54. package/dist/ctx.d.ts +80 -6
  55. package/dist/ctx.js +233 -24
  56. package/dist/ctx.js.map +1 -1
  57. package/dist/main.d.ts +4 -1
  58. package/dist/main.js +72 -40
  59. package/dist/main.js.map +1 -1
  60. package/dist/manifest/load.d.ts +143 -0
  61. package/dist/manifest/load.js +279 -0
  62. package/dist/manifest/load.js.map +1 -0
  63. package/dist/manifest/plan.d.ts +52 -0
  64. package/dist/manifest/plan.js +628 -0
  65. package/dist/manifest/plan.js.map +1 -0
  66. package/dist/registry.d.ts +19 -0
  67. package/dist/registry.js +52 -0
  68. package/dist/registry.js.map +1 -0
  69. package/dist/suggest.d.ts +9 -0
  70. package/dist/suggest.js +51 -0
  71. package/dist/suggest.js.map +1 -0
  72. package/package.json +12 -9
  73. package/schemas/b3os.v0.schema.json +244 -0
  74. package/dist/commands/web.d.ts +0 -4
  75. package/dist/commands/web.js +0 -205
  76. package/dist/commands/web.js.map +0 -1
@@ -0,0 +1,196 @@
1
+ import { type Ctx } from "../ctx.ts";
2
+ import type { CliCommand } from "../registry.ts";
3
+ /** `b3os scrape`'s options. One named after a request field sets that field (ctx.ts CliOption). */
4
+ export declare const SCRAPE_OPTIONS: {
5
+ readonly format: {
6
+ readonly type: "string";
7
+ readonly short: "f";
8
+ readonly multiple: true;
9
+ readonly fields: readonly ["visionScrape:formats"];
10
+ };
11
+ readonly "all-content": {
12
+ readonly type: "boolean";
13
+ readonly fields: readonly ["visionScrape:only_main_content"];
14
+ readonly rename: "--all-content sends only_main_content: false";
15
+ };
16
+ readonly engine: {
17
+ readonly type: "string";
18
+ readonly fields: readonly ["visionScrape:engine"];
19
+ };
20
+ readonly "wait-for-ms": {
21
+ readonly type: "string";
22
+ readonly alias: readonly ["wait-for"];
23
+ readonly fields: readonly ["visionScrape:wait_for_ms"];
24
+ };
25
+ readonly "max-age-ms": {
26
+ readonly type: "string";
27
+ readonly alias: readonly ["max-age"];
28
+ readonly fields: readonly ["visionScrape:max_age_ms"];
29
+ };
30
+ readonly "no-cache": {
31
+ readonly type: "boolean";
32
+ readonly fields: readonly ["visionScrape:max_age_ms"];
33
+ readonly rename: "--no-cache sends max_age_ms: 0";
34
+ };
35
+ readonly header: {
36
+ readonly type: "string";
37
+ readonly multiple: true;
38
+ readonly fields: readonly ["visionScrape:headers"];
39
+ };
40
+ readonly profile: {
41
+ readonly type: "string";
42
+ readonly fields: readonly ["visionScrape:profile"];
43
+ };
44
+ readonly out: {
45
+ readonly type: "string";
46
+ readonly short: "o";
47
+ };
48
+ readonly "max-concurrency": {
49
+ readonly type: "string";
50
+ readonly alias: readonly ["concurrency"];
51
+ readonly fields: readonly ["visionCreateBatch:max_concurrency"];
52
+ };
53
+ readonly "no-wait": {
54
+ readonly type: "boolean";
55
+ };
56
+ readonly "respect-robots": {
57
+ readonly type: "boolean";
58
+ readonly fields: readonly ["visionScrape:respect_robots"];
59
+ };
60
+ readonly screenshot: {
61
+ readonly type: "string";
62
+ };
63
+ readonly mobile: {
64
+ readonly type: "boolean";
65
+ readonly fields: readonly ["visionScrape:mobile"];
66
+ };
67
+ readonly schema: {
68
+ readonly type: "string";
69
+ readonly fields: readonly ["visionScrape:json.schema"];
70
+ };
71
+ readonly action: {
72
+ readonly type: "string";
73
+ readonly multiple: true;
74
+ readonly fields: readonly ["visionScrape:actions"];
75
+ };
76
+ readonly browser: {
77
+ readonly type: "string";
78
+ readonly fields: readonly ["visionScrape:browser"];
79
+ };
80
+ };
81
+ export declare function scrape(ctx: Ctx, argv: string[]): Promise<number>;
82
+ /** `b3os map`'s options. */
83
+ export declare const MAP_OPTIONS: {
84
+ readonly search: {
85
+ readonly type: "string";
86
+ readonly fields: readonly ["visionMap:search"];
87
+ };
88
+ readonly limit: {
89
+ readonly type: "string";
90
+ readonly fields: readonly ["visionMap:limit"];
91
+ };
92
+ readonly sitemap: {
93
+ readonly type: "string";
94
+ readonly fields: readonly ["visionMap:sitemap"];
95
+ };
96
+ readonly "include-subdomains": {
97
+ readonly type: "boolean";
98
+ readonly alias: readonly ["subdomains"];
99
+ readonly fields: readonly ["visionMap:include_subdomains"];
100
+ };
101
+ readonly "no-include-subdomains": {
102
+ readonly type: "boolean";
103
+ readonly fields: readonly ["visionMap:include_subdomains"];
104
+ };
105
+ readonly "respect-robots": {
106
+ readonly type: "boolean";
107
+ readonly fields: readonly ["visionMap:respect_robots"];
108
+ };
109
+ };
110
+ export declare function map(ctx: Ctx, argv: string[]): Promise<number>;
111
+ /** `b3os crawl`'s options. */
112
+ export declare const CRAWL_OPTIONS: {
113
+ readonly limit: {
114
+ readonly type: "string";
115
+ readonly fields: readonly ["visionCreateCrawl:limit", "visionListCrawlPages:limit"];
116
+ };
117
+ readonly "max-depth": {
118
+ readonly type: "string";
119
+ readonly alias: readonly ["depth"];
120
+ readonly fields: readonly ["visionCreateCrawl:max_depth"];
121
+ };
122
+ readonly "include-paths": {
123
+ readonly type: "string";
124
+ readonly multiple: true;
125
+ readonly alias: readonly ["include"];
126
+ readonly fields: readonly ["visionCreateCrawl:include_paths"];
127
+ };
128
+ readonly "exclude-paths": {
129
+ readonly type: "string";
130
+ readonly multiple: true;
131
+ readonly alias: readonly ["exclude"];
132
+ readonly fields: readonly ["visionCreateCrawl:exclude_paths"];
133
+ };
134
+ readonly "include-subdomains": {
135
+ readonly type: "boolean";
136
+ readonly fields: readonly ["visionCreateCrawl:allow_subdomains"];
137
+ readonly rename: "crawl calls map's include_subdomains allow_subdomains; the API takes the one name on both later (B5)";
138
+ };
139
+ readonly out: {
140
+ readonly type: "string";
141
+ };
142
+ readonly "no-wait": {
143
+ readonly type: "boolean";
144
+ };
145
+ readonly "respect-robots": {
146
+ readonly type: "boolean";
147
+ readonly fields: readonly ["visionCreateCrawl:respect_robots"];
148
+ };
149
+ };
150
+ export declare function crawl(ctx: Ctx, argv: string[]): Promise<number>;
151
+ /** `b3os session`'s options. */
152
+ export declare const SESSION_OPTIONS: {
153
+ readonly profile: {
154
+ readonly type: "string";
155
+ readonly fields: readonly ["visionCreateSession:profile"];
156
+ };
157
+ readonly "persist-profile": {
158
+ readonly type: "boolean";
159
+ readonly fields: readonly ["visionCreateSession:persist_profile"];
160
+ };
161
+ readonly "timeout-s": {
162
+ readonly type: "string";
163
+ readonly fields: readonly ["visionCreateSession:timeout_s"];
164
+ };
165
+ readonly actions: {
166
+ readonly type: "string";
167
+ readonly fields: readonly ["visionAct:actions"];
168
+ };
169
+ readonly "continue-on-error": {
170
+ readonly type: "boolean";
171
+ readonly fields: readonly ["visionAct:continue_on_error"];
172
+ };
173
+ readonly limit: {
174
+ readonly type: "string";
175
+ readonly fields: readonly ["visionListSessions:limit"];
176
+ };
177
+ readonly name: {
178
+ readonly type: "string";
179
+ readonly fields: readonly ["visionSaveSessionProfile:name"];
180
+ };
181
+ readonly overwrite: {
182
+ readonly type: "boolean";
183
+ readonly fields: readonly ["visionSaveSessionProfile:overwrite"];
184
+ };
185
+ };
186
+ export declare function session(ctx: Ctx, argv: string[]): Promise<number>;
187
+ /** `b3os profile`'s options. */
188
+ export declare const PROFILE_OPTIONS: {
189
+ readonly limit: {
190
+ readonly type: "string";
191
+ readonly fields: readonly ["visionListProfiles:limit"];
192
+ };
193
+ };
194
+ export declare function profile(ctx: Ctx, argv: string[]): Promise<number>;
195
+ /** This module's commands, found by main.ts (src/registry.ts). */
196
+ export declare const commands: CliCommand[];
@@ -0,0 +1,478 @@
1
+ // b3os scrape | map | crawl | session | profile (vision): vision.scrape and its batch form, map, crawl, browser
2
+ // sessions and saved profiles. Thin verbs over the SDK, with --json for scripts.
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
+ import { EXIT, intFlag, jsonFlag, pairs, parse, splitSub, UsageError } from "../ctx.js";
5
+ import { imageFormat, showUsage, unknownSub, usage, usageOf } from "./_common.js";
6
+ const FORMATS = ["markdown", "html", "raw_html", "text", "links", "metadata", "screenshot", "json"];
7
+ /** `b3os scrape`'s options. One named after a request field sets that field (ctx.ts CliOption). */
8
+ export const SCRAPE_OPTIONS = {
9
+ format: { type: "string", short: "f", multiple: true, fields: ["visionScrape:formats"] },
10
+ "all-content": {
11
+ type: "boolean",
12
+ fields: ["visionScrape:only_main_content"],
13
+ rename: "--all-content sends only_main_content: false",
14
+ },
15
+ engine: { type: "string", fields: ["visionScrape:engine"] },
16
+ "wait-for-ms": { type: "string", alias: ["wait-for"], fields: ["visionScrape:wait_for_ms"] },
17
+ "max-age-ms": { type: "string", alias: ["max-age"], fields: ["visionScrape:max_age_ms"] },
18
+ "no-cache": { type: "boolean", fields: ["visionScrape:max_age_ms"], rename: "--no-cache sends max_age_ms: 0" },
19
+ header: { type: "string", multiple: true, fields: ["visionScrape:headers"] },
20
+ profile: { type: "string", fields: ["visionScrape:profile"] },
21
+ out: { type: "string", short: "o" },
22
+ "max-concurrency": { type: "string", alias: ["concurrency"], fields: ["visionCreateBatch:max_concurrency"] },
23
+ "no-wait": { type: "boolean" },
24
+ "respect-robots": { type: "boolean", fields: ["visionScrape:respect_robots"] },
25
+ screenshot: { type: "string" },
26
+ mobile: { type: "boolean", fields: ["visionScrape:mobile"] },
27
+ schema: { type: "string", fields: ["visionScrape:json.schema"] },
28
+ action: { type: "string", multiple: true, fields: ["visionScrape:actions"] },
29
+ browser: { type: "string", fields: ["visionScrape:browser"] },
30
+ };
31
+ export async function scrape(ctx, argv) {
32
+ const a = parse(argv, SCRAPE_OPTIONS);
33
+ ctx.applyGlobals(a.values);
34
+ const url = a.positionals[0];
35
+ if (!url || a.values.help) {
36
+ ctx.out("usage: b3os scrape <url> [--format markdown|html|raw_html|text|links|json ...] [--all-content]\n" +
37
+ " [--engine auto|fetch|browser] [--browser chrome|headless-shell] [--wait-for-ms MS]\n" +
38
+ " [--max-age-ms MS|--no-cache] [--header K=V ...] [--profile NAME] [--mobile]\n" +
39
+ " [--screenshot FILE] [--schema FILE] [--action JSON|@file ...] [--respect-robots]\n" +
40
+ " [--out FILE] [--json]\n" +
41
+ " b3os scrape <url> <url> ... [--max-concurrency N] [--no-wait] [options above]\n" +
42
+ "--screenshot writes the page's image to FILE (.webp, .png or .jpg; without an extension, WebP). --schema\n" +
43
+ "adds the json format with the JSON Schema in FILE. --action adds browser actions run before the capture: a\n" +
44
+ "step or a list of steps, as JSON or @file, and may repeat. Several URLs are one batch job: it waits and\n" +
45
+ "prints each page as Markdown (--out or --json: JSON lines of the pages; --no-wait prints the batch_ id).\n" +
46
+ "--respect-robots checks robots.txt first (off by default: a disallowed URL is 403 robots_disallowed).");
47
+ return a.values.help ? EXIT.OK : EXIT.USAGE;
48
+ }
49
+ const formats = (a.values.format ?? ["markdown"]).flatMap((f) => f.split(","));
50
+ for (const f of formats) {
51
+ if (!FORMATS.includes(f))
52
+ throw new UsageError(`unknown format "${f}" (${FORMATS.join(", ")})`);
53
+ }
54
+ const shotFile = typeof a.values.screenshot === "string" ? a.values.screenshot : undefined;
55
+ if (shotFile !== undefined && !shotFile)
56
+ throw new UsageError("--screenshot needs a file name");
57
+ if (shotFile && !formats.includes("screenshot"))
58
+ formats.push("screenshot");
59
+ const schemaFile = typeof a.values.schema === "string" ? a.values.schema : undefined;
60
+ if (schemaFile && !formats.includes("json"))
61
+ formats.push("json");
62
+ const body = { url, formats: formats };
63
+ if (shotFile)
64
+ body.screenshot = { format: imageFormat(shotFile, undefined, "--screenshot") };
65
+ if (schemaFile) {
66
+ const schema = jsonFlag(readFileSync(schemaFile, "utf8"), "--schema");
67
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
68
+ throw new UsageError("--schema: the file must hold a JSON Schema object");
69
+ body.json = { schema: schema };
70
+ }
71
+ if (a.values.mobile)
72
+ body.mobile = true;
73
+ if (typeof a.values.browser === "string") {
74
+ if (a.values.browser !== "chrome" && a.values.browser !== "headless-shell")
75
+ throw new UsageError(`unknown browser "${a.values.browser}" (chrome, headless-shell)`);
76
+ body.browser = a.values.browser;
77
+ }
78
+ const actions = (a.values.action ?? []).flatMap((v) => {
79
+ const parsed = jsonFlag(v.startsWith("@") ? readFileSync(v.slice(1), "utf8") : v, "--action");
80
+ const steps = Array.isArray(parsed) ? parsed : [parsed];
81
+ for (const st of steps)
82
+ if (!st || typeof st !== "object" || typeof st.kind !== "string")
83
+ throw new UsageError('--action: each step is an object with a kind, such as {"kind": "click", ...}');
84
+ return steps;
85
+ });
86
+ if (actions.length)
87
+ body.actions = actions;
88
+ if (a.values["respect-robots"])
89
+ body.respect_robots = true;
90
+ if (a.values["all-content"])
91
+ body.only_main_content = false;
92
+ if (typeof a.values.engine === "string")
93
+ body.engine = a.values.engine;
94
+ const wait = intFlag(a.values["wait-for-ms"], "--wait-for-ms");
95
+ if (wait !== undefined)
96
+ body.wait_for_ms = wait;
97
+ if (a.values["no-cache"] && a.values["max-age-ms"] !== undefined)
98
+ throw new UsageError("--no-cache is --max-age-ms 0: give one of them");
99
+ const maxAge = a.values["no-cache"] ? 0 : intFlag(a.values["max-age-ms"], "--max-age-ms");
100
+ if (maxAge !== undefined)
101
+ body.max_age_ms = maxAge;
102
+ if (a.values.header)
103
+ body.headers = pairs(a.values.header, "--header");
104
+ if (typeof a.values.profile === "string")
105
+ body.profile = a.values.profile;
106
+ if (a.positionals.length > 1) {
107
+ if (shotFile)
108
+ throw new UsageError("--screenshot writes one file: give one URL");
109
+ return batch(ctx, a.positionals, body, a.values);
110
+ }
111
+ const { data: page, response } = await ctx.client().vision.scrape(body).withResponse();
112
+ if (shotFile) {
113
+ const shot = page.screenshot;
114
+ if (!shot?.data_base64)
115
+ throw new UsageError("the scrape returned no screenshot");
116
+ writeFileSync(shotFile, Buffer.from(shot.data_base64, "base64"));
117
+ ctx.info(`Wrote ${shotFile} (${shot.format}, ${shot.width}x${shot.height})`);
118
+ page.screenshot = { ...shot, data_base64: `(written to ${shotFile})` };
119
+ }
120
+ // The image goes to its file: what is printed is the other formats.
121
+ const shown = formats.filter((f) => !(shotFile && f === "screenshot"));
122
+ const single = shown.length === 1 ? shown[0] : undefined;
123
+ let text;
124
+ if (single === "markdown" || single === "html" || single === "raw_html" || single === "text") {
125
+ text = page[single] ?? "";
126
+ }
127
+ else if (single === "links") {
128
+ text = (page.links ?? []).join("\n");
129
+ }
130
+ else if (single === "json" && page.json !== undefined) {
131
+ text = JSON.stringify(page.json, null, 2);
132
+ }
133
+ if (typeof a.values.out === "string") {
134
+ writeFileSync(a.values.out, ctx.json || text === undefined ? JSON.stringify(page, null, 2) : text);
135
+ ctx.info(`Wrote ${a.values.out}`);
136
+ }
137
+ else if (ctx.json || text === undefined) {
138
+ ctx.printJson(page);
139
+ }
140
+ else {
141
+ ctx.out(text);
142
+ }
143
+ const t = response.timing.total_ms;
144
+ ctx.info(`${page.status_code} ${page.final_url} via ${page.tier} (cache ${page.cache.state})${t === null ? "" : `, server ${t} ms`}`);
145
+ return EXIT.OK;
146
+ }
147
+ /** The screenshot format a file name asks for: `.png`, `.webp`, else JPEG. */
148
+ /** `b3os scrape <url> <url> ...`: one batch job with the same scrape options for every page. */
149
+ async function batch(ctx, urls, one, flags) {
150
+ const { url: _first, ...scrapeOptions } = one;
151
+ const body = { urls, scrape: scrapeOptions };
152
+ const conc = intFlag(flags["max-concurrency"], "--max-concurrency");
153
+ if (conc !== undefined)
154
+ body.max_concurrency = conc;
155
+ const b3 = ctx.client();
156
+ if (flags["no-wait"]) {
157
+ const job = await b3.vision.createBatch(body);
158
+ ctx.result(job, () => ctx.out(job.id));
159
+ return EXIT.OK;
160
+ }
161
+ const job = await b3.vision.createBatch(body).wait({ throwOnFailure: false });
162
+ if (job.status !== "succeeded") {
163
+ ctx.warn(`batch ${job.id} ${job.status}${job.error ? `: ${job.error.code}: ${job.error.detail}` : ""}`);
164
+ return EXIT.FAILED;
165
+ }
166
+ const lines = [];
167
+ let n = 0;
168
+ for await (const p of b3.vision.listBatchPages(job.id, { limit: 100 })) {
169
+ n++;
170
+ if (typeof flags.out === "string" || ctx.json)
171
+ lines.push(JSON.stringify(p));
172
+ else
173
+ ctx.out(`## ${p.url}\n\n${p.scrape?.markdown ?? (p.error ? `failed: ${p.error.detail}` : "")}\n\n`);
174
+ }
175
+ if (typeof flags.out === "string") {
176
+ writeFileSync(flags.out, lines.length ? `${lines.join("\n")}\n` : "");
177
+ ctx.info(`${n} pages of ${job.id} written to ${flags.out}`);
178
+ }
179
+ else if (ctx.json)
180
+ for (const l of lines)
181
+ ctx.io.stdout.write(`${l}\n`);
182
+ const r = job.result;
183
+ ctx.info(`${job.id}: ${r?.pages_succeeded ?? n} succeeded, ${r?.pages_failed ?? 0} failed` +
184
+ (r?.invalid_urls?.length ? `, invalid: ${r.invalid_urls.join(" ")}` : ""));
185
+ return EXIT.OK;
186
+ }
187
+ const MAP_USAGE = `usage: b3os map <url> [--search WORDS] [--limit N] [--sitemap include|skip|only] [--no-include-subdomains]
188
+ [--respect-robots]
189
+ Prints the site's URLs, one per line (most relevant first with --search). Subdomains are included unless
190
+ --no-include-subdomains. --respect-robots refuses a start URL robots.txt disallows (off by default).`;
191
+ /** `b3os map`'s options. */
192
+ export const MAP_OPTIONS = {
193
+ search: { type: "string", fields: ["visionMap:search"] },
194
+ limit: { type: "string", fields: ["visionMap:limit"] },
195
+ sitemap: { type: "string", fields: ["visionMap:sitemap"] },
196
+ "include-subdomains": { type: "boolean", alias: ["subdomains"], fields: ["visionMap:include_subdomains"] },
197
+ "no-include-subdomains": { type: "boolean", fields: ["visionMap:include_subdomains"] },
198
+ "respect-robots": { type: "boolean", fields: ["visionMap:respect_robots"] },
199
+ };
200
+ export async function map(ctx, argv) {
201
+ const a = parse(argv, MAP_OPTIONS);
202
+ ctx.applyGlobals(a.values);
203
+ const url = a.positionals[0];
204
+ const u = usage(ctx, MAP_USAGE, url, a.values.help);
205
+ if (u !== undefined)
206
+ return u;
207
+ if (a.values["include-subdomains"] && a.values["no-include-subdomains"])
208
+ throw new UsageError("--include-subdomains and --no-include-subdomains: give one of them");
209
+ const r = await ctx.client().vision.map({
210
+ ...(a.values["respect-robots"] ? { respect_robots: true } : {}),
211
+ url: url,
212
+ ...(typeof a.values.search === "string" ? { search: a.values.search } : {}),
213
+ ...(a.values.limit ? { limit: intFlag(a.values.limit, "--limit") } : {}),
214
+ ...(typeof a.values.sitemap === "string" ? { sitemap: a.values.sitemap } : {}),
215
+ ...(a.values["include-subdomains"] ? { include_subdomains: true } : {}),
216
+ ...(a.values["no-include-subdomains"] ? { include_subdomains: false } : {}),
217
+ });
218
+ ctx.result(r, () => {
219
+ for (const l of r.links)
220
+ ctx.out(l.url);
221
+ ctx.info(`${r.links.length} URLs`);
222
+ });
223
+ return EXIT.OK;
224
+ }
225
+ const CRAWL_USAGE = `usage: b3os crawl <url> [--limit N] [--max-depth N] [--include-paths REGEX ...] [--exclude-paths REGEX ...]
226
+ [--include-subdomains] [--respect-robots] [--no-wait] [--out FILE]
227
+ b3os crawl <crawl_id> [--out FILE] pages of an earlier crawl
228
+ Waits for the crawl and prints each page as Markdown (--out writes JSON lines of the pages; --no-wait prints the
229
+ crawl id). --respect-robots skips pages robots.txt disallows and uses its Crawl-delay (off by default).`;
230
+ /** `b3os crawl`'s options. */
231
+ export const CRAWL_OPTIONS = {
232
+ limit: { type: "string", fields: ["visionCreateCrawl:limit", "visionListCrawlPages:limit"] },
233
+ "max-depth": { type: "string", alias: ["depth"], fields: ["visionCreateCrawl:max_depth"] },
234
+ "include-paths": { type: "string", multiple: true, alias: ["include"], fields: ["visionCreateCrawl:include_paths"] },
235
+ "exclude-paths": { type: "string", multiple: true, alias: ["exclude"], fields: ["visionCreateCrawl:exclude_paths"] },
236
+ "include-subdomains": {
237
+ type: "boolean",
238
+ fields: ["visionCreateCrawl:allow_subdomains"],
239
+ rename: "crawl calls map's include_subdomains allow_subdomains; the API takes the one name on both later (B5)",
240
+ },
241
+ out: { type: "string" },
242
+ "no-wait": { type: "boolean" },
243
+ "respect-robots": { type: "boolean", fields: ["visionCreateCrawl:respect_robots"] },
244
+ };
245
+ export async function crawl(ctx, argv) {
246
+ const a = parse(argv, CRAWL_OPTIONS);
247
+ ctx.applyGlobals(a.values);
248
+ const target = a.positionals[0];
249
+ const u = usage(ctx, CRAWL_USAGE, target, a.values.help);
250
+ if (u !== undefined)
251
+ return u;
252
+ const b3 = ctx.client();
253
+ let id = target;
254
+ if (!id.startsWith("crawl_")) {
255
+ const body = { url: id, scrape: { formats: ["markdown"] } };
256
+ if (a.values["respect-robots"])
257
+ body.respect_robots = true;
258
+ const limit = intFlag(a.values.limit, "--limit");
259
+ if (limit !== undefined)
260
+ body.limit = limit;
261
+ const depth = intFlag(a.values["max-depth"], "--max-depth");
262
+ if (depth !== undefined)
263
+ body.max_depth = depth;
264
+ if (a.values["include-paths"])
265
+ body.include_paths = a.values["include-paths"];
266
+ if (a.values["exclude-paths"])
267
+ body.exclude_paths = a.values["exclude-paths"];
268
+ if (a.values["include-subdomains"])
269
+ body.allow_subdomains = true;
270
+ if (a.values["no-wait"]) {
271
+ const job = await b3.vision.createCrawl(body);
272
+ ctx.result(job, () => ctx.out(job.id));
273
+ return EXIT.OK;
274
+ }
275
+ const job = await b3.vision.createCrawl(body).wait({ throwOnFailure: false });
276
+ id = job.id;
277
+ if (job.status !== "succeeded") {
278
+ ctx.warn(`crawl ${job.id} ${job.status}${job.error ? `: ${job.error.code}: ${job.error.detail}` : ""}`);
279
+ return EXIT.FAILED;
280
+ }
281
+ }
282
+ const lines = [];
283
+ let n = 0;
284
+ for await (const p of b3.vision.listCrawlPages(id, { limit: 100 })) {
285
+ n++;
286
+ if (typeof a.values.out === "string" || ctx.json)
287
+ lines.push(JSON.stringify(p));
288
+ else
289
+ ctx.out(`## ${p.url}\n\n${p.scrape?.markdown ?? (p.error ? `failed: ${p.error.detail}` : "")}\n\n`);
290
+ }
291
+ if (typeof a.values.out === "string") {
292
+ writeFileSync(a.values.out, lines.length ? `${lines.join("\n")}\n` : "");
293
+ ctx.info(`${n} pages of ${id} written to ${a.values.out}`);
294
+ }
295
+ else if (ctx.json)
296
+ for (const l of lines)
297
+ ctx.io.stdout.write(`${l}\n`);
298
+ else
299
+ ctx.info(`${n} pages (${id})`);
300
+ return EXIT.OK;
301
+ }
302
+ const SESSION_USAGE = `usage: b3os session <command>
303
+ create [--profile NAME] [--persist-profile] [--timeout-s S] prints the brs_ id
304
+ act <brs_id> --actions JSON|@file [--continue-on-error] browser actions, results as JSON
305
+ cdp <brs_id> a CDP URL for Playwright/Puppeteer (30 s)
306
+ save-profile <brs_id> --name NAME [--overwrite] save its sign-ins as a profile now
307
+ ls [--limit N]
308
+ close <brs_id>`;
309
+ /** `b3os session`'s options. */
310
+ export const SESSION_OPTIONS = {
311
+ profile: { type: "string", fields: ["visionCreateSession:profile"] },
312
+ "persist-profile": { type: "boolean", fields: ["visionCreateSession:persist_profile"] },
313
+ "timeout-s": { type: "string", fields: ["visionCreateSession:timeout_s"] },
314
+ actions: { type: "string", fields: ["visionAct:actions"] },
315
+ "continue-on-error": { type: "boolean", fields: ["visionAct:continue_on_error"] },
316
+ limit: { type: "string", fields: ["visionListSessions:limit"] },
317
+ name: { type: "string", fields: ["visionSaveSessionProfile:name"] },
318
+ overwrite: { type: "boolean", fields: ["visionSaveSessionProfile:overwrite"] },
319
+ };
320
+ export async function session(ctx, argv) {
321
+ const [sub, rest] = splitSub(argv);
322
+ const a = parse(rest, SESSION_OPTIONS);
323
+ ctx.applyGlobals(a.values);
324
+ if (!sub || a.values.help)
325
+ return showUsage(ctx, SESSION_USAGE, sub, a.values.help);
326
+ const b3 = ctx.client();
327
+ const id = a.positionals[0];
328
+ const need = () => {
329
+ if (!id)
330
+ throw new UsageError(`session ${sub} needs a brs_ id\n${usageOf(SESSION_USAGE, sub)}`);
331
+ return id;
332
+ };
333
+ switch (sub) {
334
+ case "create": {
335
+ const body = {};
336
+ if (typeof a.values.profile === "string")
337
+ body.profile = a.values.profile;
338
+ if (a.values["persist-profile"])
339
+ body.persist_profile = true;
340
+ const t = intFlag(a.values["timeout-s"], "--timeout-s");
341
+ if (t !== undefined)
342
+ body.timeout_s = t;
343
+ const s = await b3.vision.createSession(body);
344
+ ctx.result(s, () => ctx.out(s.id));
345
+ return EXIT.OK;
346
+ }
347
+ case "act": {
348
+ const sid = need();
349
+ if (typeof a.values.actions !== "string")
350
+ throw new UsageError("session act needs --actions JSON|@file");
351
+ const raw = a.values.actions.startsWith("@") ? readFileSync(a.values.actions.slice(1), "utf8") : a.values.actions;
352
+ const actions = jsonFlag(raw, "--actions");
353
+ if (!Array.isArray(actions))
354
+ throw new UsageError("--actions must be a JSON array of actions");
355
+ const r = await b3.vision.act(sid, {
356
+ actions: actions,
357
+ continue_on_error: !!a.values["continue-on-error"],
358
+ });
359
+ ctx.printJson(r);
360
+ return r.ok ? EXIT.OK : EXIT.FAILED;
361
+ }
362
+ case "cdp": {
363
+ const ep = await b3.vision.connectCdp(need());
364
+ ctx.result(ep, () => ctx.out(ep.url));
365
+ return EXIT.OK;
366
+ }
367
+ case "save-profile": {
368
+ const sid = need();
369
+ if (typeof a.values.name !== "string")
370
+ throw new UsageError("session save-profile needs --name NAME");
371
+ const p = await b3.vision.saveSessionProfile(sid, {
372
+ name: a.values.name,
373
+ ...(a.values.overwrite ? { overwrite: true } : {}),
374
+ });
375
+ ctx.result(p, () => ctx.out(`${p.id} ${p.name}`));
376
+ return EXIT.OK;
377
+ }
378
+ case "ls":
379
+ case "list": {
380
+ const page = await b3.vision.listSessions({ limit: intFlag(a.values.limit, "--limit") });
381
+ ctx.result(page, () => ctx.table(page.data, ["id", "status", "created_at", "expires_at"]));
382
+ return EXIT.OK;
383
+ }
384
+ case "close":
385
+ case "rm": {
386
+ const s = await b3.vision.closeSession(need());
387
+ ctx.result(s, () => ctx.out(`${s.id} ${s.status}`));
388
+ return EXIT.OK;
389
+ }
390
+ default:
391
+ throw unknownSub("session", sub, SESSION_USAGE);
392
+ }
393
+ }
394
+ const PROFILE_USAGE = `usage: b3os profile <command>
395
+ ls [--limit N] saved browser profiles (sign-ins sessions and scrapes reuse with --profile NAME)
396
+ get <prof_id|name>
397
+ rm <prof_id> [--yes]
398
+ Save one from a session with: b3os session create --profile NAME --persist-profile (saved when it closes), or
399
+ b3os session save-profile <brs_id> --name NAME (saved now).`;
400
+ /** `b3os profile`'s options. */
401
+ export const PROFILE_OPTIONS = {
402
+ limit: { type: "string", fields: ["visionListProfiles:limit"] },
403
+ };
404
+ export async function profile(ctx, argv) {
405
+ const [sub, rest] = splitSub(argv);
406
+ const a = parse(rest, PROFILE_OPTIONS);
407
+ ctx.applyGlobals(a.values);
408
+ if (!sub || a.values.help)
409
+ return showUsage(ctx, PROFILE_USAGE, sub, a.values.help);
410
+ const b3 = ctx.client();
411
+ const id = a.positionals[0];
412
+ const need = () => {
413
+ if (!id)
414
+ throw new UsageError(`profile ${sub} needs a profile\n${usageOf(PROFILE_USAGE, sub)}`);
415
+ return id;
416
+ };
417
+ const row = (p) => ({ ...p, domains: p.domains.join(",") });
418
+ const columns = ["id", "name", "status", "domains", "last_used_at"];
419
+ switch (sub) {
420
+ case "ls":
421
+ case "list": {
422
+ const page = await b3.vision.listProfiles({ limit: intFlag(a.values.limit, "--limit") });
423
+ ctx.result(page, () => ctx.table(page.data.map(row), columns));
424
+ return EXIT.OK;
425
+ }
426
+ case "get": {
427
+ const p = await b3.vision.getProfile(need());
428
+ ctx.result(p, () => ctx.table([row(p)], columns));
429
+ return EXIT.OK;
430
+ }
431
+ case "rm":
432
+ case "delete": {
433
+ const pid = need();
434
+ if (!(await ctx.confirm(`Delete profile ${pid} and its saved sign-ins?`)))
435
+ return EXIT.OK;
436
+ const d = await b3.vision.deleteProfile(pid);
437
+ ctx.result(d, () => ctx.out(`${d.id} deleted`));
438
+ return EXIT.OK;
439
+ }
440
+ default:
441
+ throw unknownSub("profile", sub, PROFILE_USAGE);
442
+ }
443
+ }
444
+ /** This module's commands, found by main.ts (src/registry.ts). */
445
+ export const commands = [
446
+ {
447
+ name: "scrape",
448
+ summary: "Read a page as Markdown (or HTML, text, links, JSON)",
449
+ order: 50,
450
+ run: scrape,
451
+ options: SCRAPE_OPTIONS,
452
+ },
453
+ { name: "map", summary: "List a site's URLs (from links and sitemaps)", order: 60, run: map, options: MAP_OPTIONS },
454
+ {
455
+ name: "crawl",
456
+ summary: "Crawl a site and print its pages as Markdown",
457
+ order: 70,
458
+ run: crawl,
459
+ options: CRAWL_OPTIONS,
460
+ },
461
+ {
462
+ name: "session",
463
+ summary: "Browser sessions: create, act, a CDP URL, save a profile, list and close",
464
+ order: 80,
465
+ run: session,
466
+ options: SESSION_OPTIONS,
467
+ oldSubcommands: { list: "ls", rm: "close" },
468
+ },
469
+ {
470
+ name: "profile",
471
+ summary: "Saved browser profiles (sign-ins): ls, get and rm",
472
+ order: 90,
473
+ run: profile,
474
+ options: PROFILE_OPTIONS,
475
+ oldSubcommands: { list: "ls", delete: "rm" },
476
+ },
477
+ ];
478
+ //# sourceMappingURL=vision.js.map