Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ You should see Markdown or parsed JSON within seconds. If you see an auth error,
| `decodo map <url>` | List a site's URLs, one per line (`--limit`, `--sitemap`, `--full`) |
| `decodo crawl <url>` | Start a crawl and print its id; `--wait` prints pages as NDJSON |
| `decodo screenshot <url>` | Capture a PNG screenshot (`-o` file or directory) |
| `decodo task status\|results <id>` | Check or collect a task started with `--async` |
| `decodo targets` | List all scrape targets by group |
| `decodo setup` | Save your API key or auth token interactively |
| `decodo whoami` | Show configured auth source |
Expand All @@ -177,7 +178,7 @@ decodo crawl results <id> --wait -o pages.ndjson
decodo crawl cancel <id>
```

`crawl results --wait` lets an agent start a crawl, keep working, and collect the pages later. With `--wait`, the CLI polls every `--poll-interval` seconds (default `5`) and gives up after `--timeout` seconds (default `3600`, exit code `6`); the crawl keeps running until you cancel it. The crawl id goes to stderr as soon as the crawl starts. A `truncated` or `cancelled` crawl prints a warning; a `faulted` crawl still prints its pages, then exits `7`.
`crawl results --wait` lets an agent start a crawl, keep working, and collect the pages later. With `--wait`, the CLI polls every `--poll-interval` seconds and gives up after `--timeout` seconds (default `3600`, exit code `6`); the crawl keeps running until you cancel it. The crawl id goes to stderr as soon as the crawl starts. A `truncated` or `cancelled` crawl prints a warning; a `faulted` crawl still prints its pages, then exits `7`.

> **Upgrading from 1.x:** `decodo search` used the `google_search` scrape target. Use `decodo google-search` or `decodo bing-search` for the previous behaviour.

Expand All @@ -193,6 +194,25 @@ decodo universal --help

Use `decodo <target> --help` for target-specific flags (`--parse`, `--geo`, and others from the schema).

### Async tasks

Add `--async` to any target command to create an async task instead of waiting for the scrape. The command prints the task as JSON, including its `id`, and returns right away:

```bash
decodo google-search "decodo web data api" --async
decodo task status <id>
decodo task results <id>
decodo task results <id> --wait
```

Add `--wait` to create the task and print its result in one command:

```bash
decodo google-search "decodo web data api" --async --wait
```

With `--wait`, the CLI polls every `--poll-interval` seconds (default `5`) and gives up after `--timeout` seconds (default `600`, exit code `6`); the task keeps running. The task id goes to stderr as soon as the task is created. A `faulted` task exits `7`. `task results` without `--wait` exits `1` when the task has no results yet. `--async` and the `task` commands need an API key; a basic auth token cannot use them.

## Output modes

By default, scrape commands print the first result's `content` (parsed JSON when the target supports `--parse`, Markdown for `decodo scrape`).
Expand Down
13 changes: 11 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,17 @@ Command assembly is two-layered:
dynamically generated scrape commands, then sorts them with `sortCommandsByOrder` so
help output has a stable, curated order (`ROOT_COMMAND_ORDER`).
- `scrape/register.ts` loads the schema once and builds the scrape-family commands:
`scrape`, `screenshot`, `targets` (list), plus one generated command per API
target from `codegen-target-commands.ts`.
`scrape`, `screenshot`, `targets` (list), plus one generated command per API target from
`codegen-target-commands.ts` and the job commands from `codegen-job-commands.ts`.
- `codegen-job-commands.ts` reads the schema's `cli` surface: every tool with a `status`,
`results` or `cancel` step of a job flow becomes `decodo <flow> <step> <id>` (today
`task status|results`). A schema without that surface, such as an older bundled one,
yields no job commands.
- Every generated target command takes `--async`, which creates an async task through the
SDK's `task` flow instead of a real-time scrape (`scrape/services/run-async-scrape.ts`);
`--wait` polls the task and prints its result. Endpoints, statuses and the poll interval
come from the schema through `webScrapingApi.flows`. Like the job commands, which run
through `cli/services/run-data-action.ts`, `--async` requires an API key.
- The Data API commands `search`, `map`, and `crawl` (with `crawl status|results|cancel`)
live in their own modules and are registered directly in `cli/register.ts`. They don't
use the schema; each runs through `cli/services/run-data-action.ts`, which requires an
Expand Down
8 changes: 6 additions & 2 deletions src/cli/services/run-data-action.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { DecodoSchema } from "@decodo/sdk-ts";
import type { Command } from "commander";
import { AUTH_TYPE } from "../../auth/constants.js";
import { ApiKeyRequiredError } from "../../auth/errors/api-key-required-error.js";
Expand All @@ -9,7 +10,10 @@ import type { DataActionHandler } from "../types/data-action.js";
import { getRootOpts } from "./global-opts.js";
import { verboseLog } from "./verbose-log.js";

export function createDataAction<Options>(handler: DataActionHandler<Options>) {
export function createDataAction<Options>(
handler: DataActionHandler<Options>,
schema?: DecodoSchema
) {
return async (
input: string,
_localOptions: unknown,
Expand All @@ -32,7 +36,7 @@ export function createDataAction<Options>(handler: DataActionHandler<Options>) {
throw new ApiKeyRequiredError();
}

const { webScrapingApi } = createDecodoClient(auth.credential);
const { webScrapingApi } = createDecodoClient(auth.credential, schema);
await handler({ api: webScrapingApi, input, options, verbose });
} catch (err) {
handleCliError(err, { fallbackMessage: "Request failed." });
Expand Down
1 change: 1 addition & 0 deletions src/cli/services/sort-commands-by-order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const ROOT_COMMAND_ORDER = [
"map",
"crawl",
"screenshot",
"task",
"setup",
"reset",
"whoami",
Expand Down
7 changes: 6 additions & 1 deletion src/platform/services/handle-cli-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { ApiKeyRequiredError } from "../../auth/errors/api-key-required-error.js
import { AuthRequiredError } from "../../auth/errors/auth-required-error.js";
import { CrawlFailedError } from "../../crawl/errors/crawl-failed-error.js";
import { ScrapeFailedError } from "../../output/errors/scrape-failed-error.js";
import { TaskFailedError } from "../../scrape/errors/task-failed-error.js";
import { EXIT } from "../constants.js";
import { CliUsageError } from "../errors/cli-usage-error.js";

Expand Down Expand Up @@ -70,7 +71,11 @@ export function resolveCliExitCode(err: unknown): number {
return EXIT.TIMEOUT;
}

if (err instanceof ScrapeFailedError || err instanceof CrawlFailedError) {
if (
err instanceof ScrapeFailedError ||
err instanceof CrawlFailedError ||
err instanceof TaskFailedError
) {
return EXIT.NETWORK;
}

Expand Down
14 changes: 14 additions & 0 deletions src/scrape/commands/attach-async-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Command } from "commander";
import { attachTaskWaitOptions } from "./attach-task-wait-options.js";

export function attachAsyncOptions(command: Command): Command {
command.option(
"--async",
"Create an async task and print it with its id instead of waiting for the result"
);

return attachTaskWaitOptions(
command,
"Wait for the task to finish and print the result (with --async)"
);
}
22 changes: 22 additions & 0 deletions src/scrape/commands/attach-task-wait-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { Command } from "commander";
import { parsePositiveInt } from "../../cli/services/parse-positive-int.js";
import { parsePollInterval } from "../../crawl/services/parse-poll-interval.js";
import { DEFAULT_TASK_TIMEOUT_SECONDS } from "../constants.js";

export function attachTaskWaitOptions(
command: Command,
waitHelp: string
): Command {
return command
.option("--wait", waitHelp)
.option(
"--poll-interval <seconds>",
"Seconds between status checks (with --wait)",
parsePollInterval
)
.option(
"--timeout <seconds>",
`Give up waiting after this many seconds (with --wait, default: ${DEFAULT_TASK_TIMEOUT_SECONDS})`,
parsePositiveInt
);
}
92 changes: 92 additions & 0 deletions src/scrape/commands/codegen-job-commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import type {
DecodoSchema,
FlowSchema,
IrJobFlow,
IrSurfaceTool,
} from "@decodo/sdk-ts";
import { Command } from "commander";
import { createDataAction } from "../../cli/services/run-data-action.js";
import { attachScrapeOutputOptions } from "../../output/commands/attach-output-options.js";
import { writeJsonOutput } from "../../output/services/write-json-output.js";
import { writeScrapeResponse } from "../../output/services/write-scrape-response.js";
import { INTEGRATION_HEADER } from "../constants.js";
import { assertTaskWaitFlags } from "../services/assert-task-wait-flags.js";
import { getTaskResults } from "../services/get-task-results.js";
import { snakeToKebab } from "../services/naming.js";
import { settleTask } from "../services/settle-task.js";
import type {
TaskResultsOptions,
TaskStatusOptions,
} from "../types/task-command.js";
import { attachTaskWaitOptions } from "./attach-task-wait-options.js";

function createJobResultsCommand(
command: Command,
tool: IrSurfaceTool,
schema: DecodoSchema
): Command {
attachScrapeOutputOptions(command);

return attachTaskWaitOptions(
command,
`Wait for the ${tool.flow} to finish before printing its result`
).action(
createDataAction<TaskResultsOptions>(async ({ api, input, options }) => {
assertTaskWaitFlags(options);
if (options.wait) {
await settleTask(api, tool.flow, input, options);
}

writeScrapeResponse(await getTaskResults(api, tool.flow, input), {
options,
});
}, schema)
);
}

function createJobStepCommand(
tool: IrSurfaceTool,
flow: IrJobFlow,
schema: DecodoSchema
): Command {
const command = new Command(tool.step)
.description(tool.description)
.argument("<id>", tool.descriptions?.[flow.idField] ?? `${tool.flow} id`);

if (tool.step === "results") {
return createJobResultsCommand(command, tool, schema);
}

return command.option("--pretty", "Pretty-print JSON on stdout").action(
createDataAction<TaskStatusOptions>(async ({ api, input, options }) => {
const job =
tool.step === "cancel"
? await api.flows.cancel(tool.flow, input)
: await api.flows.status(tool.flow, input);
writeJsonOutput(job, options);
}, schema)
);
}

export function createCodegenJobCommands(schema: DecodoSchema): Command[] {
const flowSchema = schema as Partial<FlowSchema>;
const tools = flowSchema.getSurface?.(INTEGRATION_HEADER)?.tools ?? [];
const commands = new Map<string, Command>();

for (const tool of tools) {
const flow = flowSchema.getFlow?.(tool.flow);
if (flow?.pattern !== "job" || !tool.step || tool.step === "start") {
continue;
}

const command =
commands.get(tool.flow) ??
new Command(snakeToKebab(tool.flow)).description(
`Follow up on a ${tool.flow} started earlier`
);
commands.set(tool.flow, command);
command.addCommand(createJobStepCommand(tool, flow, schema));
}

return [...commands.values()];
}
9 changes: 9 additions & 0 deletions src/scrape/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ export const INTEGRATION_HEADER = "cli";

export const SCHEMA_TTL_MS = 3_600_000;

export const TASK_FLOW = "task";

export const DEFAULT_TASK_TIMEOUT_SECONDS = 600;

export const TASK_WAIT_ONLY_FLAGS = {
pollInterval: "--poll-interval",
timeout: "--timeout",
} as const;

export const PRIMARY_INPUT_FIELDS = [
"query",
"url",
Expand Down
13 changes: 13 additions & 0 deletions src/scrape/errors/task-failed-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class TaskFailedError extends Error {
readonly flow: string;
readonly status: string;
readonly taskId: string;

constructor(flow: string, taskId: string, status: string) {
super(`${flow} ${taskId} ended with status ${status}.`);
this.name = "TaskFailedError";
this.flow = flow;
this.taskId = taskId;
this.status = status;
}
}
13 changes: 13 additions & 0 deletions src/scrape/errors/task-results-not-ready-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class TaskResultsNotReadyError extends Error {
readonly flow: string;
readonly taskId: string;

constructor(flow: string, taskId: string) {
super(
`${flow} ${taskId} has no results yet. Run \`decodo ${flow} results ${taskId} --wait\` to wait for them.`
);
this.name = "TaskResultsNotReadyError";
this.flow = flow;
this.taskId = taskId;
}
}
2 changes: 2 additions & 0 deletions src/scrape/register.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Command } from "commander";
import { createCodegenJobCommands } from "./commands/codegen-job-commands.js";
import { createCodegenTargetCommands } from "./commands/codegen-target-commands.js";
import { createListTargetsCommand } from "./commands/list-targets.js";
import { createScrapeCommand } from "./commands/scrape.js";
Expand All @@ -11,6 +12,7 @@ export async function createScrapeCommands(): Promise<Command[]> {
return [
createScrapeCommand(schema),
createScreenshotCommand(schema),
...createCodegenJobCommands(schema),
createListTargetsCommand(schema),
...createCodegenTargetCommands(schema),
];
Expand Down
11 changes: 11 additions & 0 deletions src/scrape/services/assert-async-flags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { CliUsageError } from "../../platform/errors/cli-usage-error.js";
import type { AsyncOptions } from "../types/async-options.js";
import { assertTaskWaitFlags } from "./assert-task-wait-flags.js";

export function assertAsyncFlags(options: AsyncOptions): void {
if (options.wait && !options.async) {
throw new CliUsageError("--wait requires --async.");
}

assertTaskWaitFlags(options);
}
15 changes: 15 additions & 0 deletions src/scrape/services/assert-task-wait-flags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { CliUsageError } from "../../platform/errors/cli-usage-error.js";
import { TASK_WAIT_ONLY_FLAGS } from "../constants.js";
import type { TaskWaitOptions } from "../types/async-options.js";

export function assertTaskWaitFlags(options: TaskWaitOptions): void {
if (options.wait) {
return;
}

for (const [key, flag] of Object.entries(TASK_WAIT_ONLY_FLAGS)) {
if (options[key as keyof TaskWaitOptions] !== undefined) {
throw new CliUsageError(`${flag} requires --wait.`);
}
}
}
2 changes: 2 additions & 0 deletions src/scrape/services/command-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { type Command, InvalidArgumentError, Option } from "commander";
import type { JSONSchema4 } from "json-schema";
import { attachScrapeOutputOptions } from "../../output/commands/attach-output-options.js";
import { applyRequestDefaults } from "../../output/services/apply-request-defaults.js";
import { attachAsyncOptions } from "../commands/attach-async-options.js";
import type { TargetCommandConfig } from "../types/target-command.js";
import { snakeToCamel, snakeToKebab } from "./naming.js";
import { getPrimaryInputField } from "./primary-input.js";
Expand Down Expand Up @@ -120,6 +121,7 @@ export function configureTargetCommand(
}

attachScrapeOutputOptions(command);
attachAsyncOptions(command);

return { target, primaryField, optionFields };
}
Expand Down
14 changes: 14 additions & 0 deletions src/scrape/services/get-task-results.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { SyncResponse, WebScrapingApi } from "@decodo/sdk-ts";
import { TaskResultsNotReadyError } from "../errors/task-results-not-ready-error.js";

export async function getTaskResults(
api: WebScrapingApi,
flow: string,
taskId: string
): Promise<SyncResponse> {
const results = await api.flows.results(flow, taskId);
if (results === undefined || results === null) {
throw new TaskResultsNotReadyError(flow, taskId);
}
return results as SyncResponse;
}
Loading
Loading