SPB Git

Repository Public

README.md 8.0 KB 188 lines markdown

1# SPIDER SDK for TypeScript23Client of the SPIDER web-intelligence API. Promise-based, strict types, ESM, **zero runtime4dependencies** (Node's built-in `fetch` and `node:crypto`), Node 20 or later.56Package name: `@spboucher/spider-sdk` (private; nothing is published to a registry).78## Install from the repository910```bash11cd sdk/typescript12pnpm install          # dev dependencies only: typescript, @types/node13pnpm run build        # tsc → dist/ (ESM + .d.ts)14pnpm test             # build, then node --test test/15```1617Use it from another project with a path dependency:1819```jsonc20// package.json of your project21{ "dependencies": { "@spboucher/spider-sdk": "file:../spider/sdk/typescript" } }22```2324## Quickstart2526```ts27import { Spider } from "@spboucher/spider-sdk";2829const spider = new Spider({30  baseUrl: "https://spider.example.org",31  apiKey: process.env.SPIDER_API_KEY!,     // sent only in the Authorization header32  userAgent: "my-app/1.0",                 // → "spider-sdk-typescript/0.1.0 my-app/1.0"33  timeoutMs: 30_000,34});3536const { job, results, notCollected } = await spider.scrapeAndWait(37  { url: "https://example.org/about", extract: { formats: ["markdown", "json"] } },38  { timeoutMs: 120_000 },39);40console.log(job.status, results[0]?.content?.markdown);41```4243Job endpoints answer immediately with an accepted job (`job_id`, `status_url`, `results_url`,44`events_url`); the work is asynchronous:4546```ts47const job = await spider.crawl({ url: "https://example.org/", budgets: { max_pages: 200, max_depth: 3 } });48const final = await spider.waitForJob(job.job_id, { timeoutMs: 900_000 });   // polling with backoff49// states: queued, running → partial | succeeded | failed | cancelled | blocked50```5152Collect only sources you are authorised to collect.5354### Methods5556| Area | Methods |57|---|---|58| Submit (202) | `scrape`, `crawl`, `map`, `screenshot`, `deepCapture`, `extract`, `ocr`, `vision`, `batch` |59| Convenience | `scrapeAndWait`, `crawlAndWait`, `extractAndWait`, `collect(job)` → `{ job, results, notCollected }` |60| Jobs | `getJob`, `listJobs`, `iterJobs`, `cancelJob`, `pauseJob`, `resumeJob`, `retryJob`, `waitForJob`, `streamEvents` |61| Results | `getResults` (one page), `iterResults` (all), `export` (bytes: jsonl, csv, markdown, html, zip) |62| Artifacts, snapshots | `getArtifact` (hash-verified bytes), `getSnapshot`, `snapshotHistory` |63| Watch, search | `createMonitor`, `listMonitors`, `monitorAction`, `listChanges`, `diff`, `search`, `iterSearch` |64| Sites, system | `listSites`, `siteGraph`, `siteCoverage`, `health`, `me`, `webhookSecret` |65| Low level | `request(method, path, { body, query, headers, idempotencyKey })` |6667## Mandatory policies6869SPIDER always honours `robots.txt` and always stops on an access denial (login wall, CAPTCHA,70paywall, 401/403). These are enforced by the server and **the SDK offers no option to disable71them**: `PolicyOptions` has no `respect_robots_txt` or `stop_on_access_denied` field, and a typed72call that smuggles one in as `false` is refused locally with a `TypeError`. Through the low-level73`request` the server answers `422 mandatory_policy`, surfaced as `MandatoryPolicyError`.7475## Pagination7677List endpoints return `{ items, next_cursor }`. Use the one-page methods to drive it yourself, or the78`AsyncIterable` helpers, which follow `next_cursor` until it is `null`:7980```ts81const page = await spider.getResults(job.job_id, { limit: 50 });            // one page82for await (const item of spider.iterResults(job.job_id, { pageSize: 50 })) { // every result83  console.log(item.url, item.record?.status);84}85for await (const j of spider.iterJobs({ kind: "crawl" })) console.log(j.job_id, j.status);86for await (const hit of spider.iterSearch({ query: "installation" })) console.log(hit.url);87```8889Results are available while a job is running.9091## Events (SSE)9293```ts94for await (const ev of spider.streamEvents(job.job_id)) {95  console.log(ev.id, ev.type, ev.data);          // ends after "job.finished"96}97const final = await spider.waitForJob(job.job_id, { useEvents: true });98```99100A dropped stream is resumed with `Last-Event-ID`, so no event is lost or repeated. Pass101`{ signal }` (an `AbortSignal`) to stop early.102103## Errors104105Every API error (`{"error": {code, message, details, request_id}}`) is an `ApiError` with `status`,106`code`, `message`, `details`, `requestId` and `retryAfterSeconds`:107108| Class | When |109|---|---|110| `AuthenticationError`, `PermissionDeniedError` (both `AuthError`) | 401, 403 |111| `ValidationError` | 400, 422 |112| `MandatoryPolicyError` (a `ValidationError`) | 422 `mandatory_policy` |113| `NotFoundError` | 404 |114| `ConflictError`, `IdempotencyConflictError` | 409, 409 `idempotency_conflict` |115| `RateLimitError`, `QuotaExceededError` | 429 `rate_limited`, 429 `quota_exceeded` |116| `ServerError` | 5xx |117118Outside the API: `TransportError` (connection or timeout after the allowed retries),119`JobTimeoutError` (`waitForJob` gave up; the job keeps running), `ArtifactIntegrityError`,120`WebhookVerificationError`. All extend `SpiderError`.121122```ts123try {124  await spider.getJob(id);125} catch (e) {126  if (e instanceof NotFoundError) console.error(e.code, e.requestId);127  else throw e;128}129```130131## Retries and idempotency132133- Retried: connection errors, `429` (waiting `Retry-After`, else `details.retry_after_s`) and134  `502/503/504`, with exponential backoff and jitter, at most `maxRetries` times (default 3).135- Never retried: any other `4xx`, `500`, and a `429 quota_exceeded` that carries no delay.136- **Job submissions are retried only because they are idempotent**: the SDK generates one137  `Idempotency-Key` (UUID) per call and reuses it for every retry of that call, so a submission whose138  answer was lost returns the same job (`idempotent_replay: true`) instead of creating a second one.139  Pass `{ idempotencyKey }` to make your own retries (after a crash, for instance) just as safe.140- `createMonitor`, `retryJob` and `monitorAction` take no idempotency key in the API: they are141  retried only when the request provably did not reach the application (connection never142  established, or `429`).143- `request("POST", …)` follows the same rule: retried on `5xx`/transport errors only with an144  `idempotencyKey`.145- Redirects are not followed, so the API key is never sent to another origin.146147## Webhook verification148149SPIDER signs `<X-Spider-Timestamp>.<X-Spider-Delivery>.<raw body>` with HMAC-SHA256 and sends150`X-Spider-Signature: v1=<hex>`. The secret is per tenant (`await spider.webhookSecret()`, admin scope).151152```ts153import { createServer } from "node:http";154import { WebhookVerificationError, parseWebhook } from "@spboucher/spider-sdk";155156const seen = new Set<string>();157createServer((req, res) => {158  const chunks: Buffer[] = [];159  req.on("data", (c) => chunks.push(c));160  req.on("end", () => {161    try {162      // the raw bytes, exactly as received; default tolerance 300 s163      const payload = parseWebhook(process.env.SPIDER_WEBHOOK_SECRET!, req.headers, Buffer.concat(chunks));164      const delivery = String(req.headers["x-spider-delivery"]);165      if (!seen.has(delivery)) { seen.add(delivery); handle(payload); }   // process a delivery id once166      res.writeHead(204).end();167    } catch (e) {168      res.writeHead(e instanceof WebhookVerificationError ? 401 : 500).end();169    }170  });171}).listen(8787);172```173174`verifyWebhook(secret, headers, rawBody, toleranceSeconds = 300)` compares in constant time, rejects175timestamps outside the tolerance and returns the delivery id; it throws `WebhookVerificationError`176with a `reason` (`missing_header`, `bad_timestamp`, `timestamp_out_of_tolerance`,177`unsupported_version`, `bad_signature`).178179## Tests180181- `test/client.test.mjs`: retries, idempotency reuse, pagination, SSE parsing, artifacts, error182  mapping, against a local mock HTTP server.183- `test/webhooks.test.mjs`: vectors computed with `openssl dgst -sha256 -hmac`.184- `test/contract.test.mjs`: loads `../../docs/openapi.json`; every route exists, every method's real185  requests (path, query parameters, `Idempotency-Key`, JSON body) match the operation described.186- `tests/integration/test_sdk_typescript.py` (repository root) runs `scripts/live.mjs` against the187  in-process test stack.188
Files main
Menu

Theme