SPB Git

Repository Public

contract.test.mjs 15.2 KB 242 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPIDER — Universal Web Intelligence Engine8 * File             : sdk/typescript/test/contract.test.mjs9 * Module           : Tests10 * Repository       : https://git.spboucher.ai/spider11 * Project Website  : Not specified12 * Created          : 2026-12-0413 * Last Modified    : 2026-12-0414 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : ISC34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// The TypeScript SDK against the contract, docs/openapi.json: every route exists with that method,44// every public method is exercised and its real requests (path, query parameters, Idempotency-Key,45// JSON body) match the operation the document describes, and every public operation is covered.46import assert from "node:assert/strict";47import { createHash } from "node:crypto";48import { test } from "node:test";4950import { ROUTES, Spider } from "../dist/index.js";51import { OPENAPI, drain, withServer } from "./helpers.mjs";5253const METHODS = ["get", "post", "put", "delete", "patch"];54const OPERATIONS = new Map();55for (const [path, ops] of Object.entries(OPENAPI.paths)) {56  for (const [m, op] of Object.entries(ops)) if (METHODS.includes(m)) OPERATIONS.set(`${m.toUpperCase()} ${path}`, op);57}58const UUID = "00000000-0000-4000-8000-000000000001";59const SCHEMA = { type: "object", properties: { name: { type: "string" }, price: { type: "number" } } };60const PUBLIC_TAGS = ["collect", "capture", "extract", "watch", "search", "jobs", "artifacts", "sites"];61const MANDATE = [62  "POST /v1/scrape", "POST /v1/crawl", "POST /v1/map", "POST /v1/screenshot", "POST /v1/deep-capture",63  "POST /v1/extract", "POST /v1/ocr", "POST /v1/vision", "POST /v1/batch", "POST /v1/monitor", "POST /v1/diff",64  "POST /v1/search", "GET /v1/jobs", "GET /v1/jobs/{job_id}", "POST /v1/jobs/{job_id}/cancel",65  "GET /v1/jobs/{job_id}/results", "GET /v1/jobs/{job_id}/events", "GET /v1/jobs/{job_id}/export",66  "GET /v1/artifacts/{artifact_id}", "GET /v1/snapshots/{snapshot_id}", "GET /v1/snapshots",67  "GET /v1/sites/{site_id}/graph", "GET /v1/sites/{site_id}/coverage", "GET /v1/health", "GET /v1/monitors",68  "GET /v1/changes", "GET /v1/webhook-secret",69];7071/** A small JSON Schema validator covering the keywords the document uses for request bodies. */72function validate(schema, value, path = "$", errors = []) {73  if (schema.$ref) return validate(schema.$ref.split("/").slice(1).reduce((o, k) => o[k], OPENAPI), value, path, errors);74  if (schema.anyOf) {75    if (!schema.anyOf.some((s) => validate(s, value, path, []).length === 0)) errors.push(`${path}: matches no alternative`);76    return errors;77  }78  const type = Array.isArray(value) ? "array" : value === null ? "null" : Number.isInteger(value) ? "integer" : typeof value;79  if (schema.type && !(schema.type === type || (schema.type === "number" && type === "integer"))) {80    errors.push(`${path}: expected ${schema.type}, got ${type}`);81    return errors;82  }83  if (schema.enum && !schema.enum.includes(value)) errors.push(`${path}: ${JSON.stringify(value)} not in enum`);84  if (schema.const !== undefined && schema.const !== value) errors.push(`${path}: not the constant`);85  if (typeof value === "number") {86    if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path}: below minimum`);87    if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path}: above maximum`);88  }89  if (typeof value === "string") {90    if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path}: too short`);91    if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path}: too long`);92  }93  if (type === "array") {94    if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${path}: too few items`);95    if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${path}: too many items`);96    if (schema.items) value.forEach((v, i) => validate(schema.items, v, `${path}[${i}]`, errors));97  }98  if (type === "object") {99    for (const name of schema.required ?? []) if (!(name in value)) errors.push(`${path}: missing ${name}`);100    for (const [k, v] of Object.entries(value)) {101      const sub = schema.properties?.[k];102      if (sub) validate(sub, v, `${path}.${k}`, errors);103      else if (schema.additionalProperties === false) errors.push(`${path}: unknown property ${k}`);104      else if (schema.additionalProperties && typeof schema.additionalProperties === "object") validate(schema.additionalProperties, v, `${path}.${k}`, errors);105    }106  }107  return errors;108}109110const bodySchema = (op) => op.requestBody?.content?.["application/json"]?.schema;111112function match(method, path) {113  const hits = [...OPERATIONS.keys()].filter((key) => {114    const [m, template] = key.split(" ");115    return m === method && new RegExp(`^${template.replace(/\{[^}]+\}/g, "[^/]+")}$`).test(path);116  });117  const exact = hits.filter((k) => k === `${method} ${path}`);118  assert.ok(exact.length === 1 || hits.length === 1, `${method} ${path} matches ${hits.length ? hits : "no operation of the document"}`);119  return exact[0] ?? hits[0];120}121122const POLICY = { same_origin_only: true, include_subdomains: false, allow_domains: ["example.org"], exclude_paths: ["^/private"], include_paths: ["^/blog"], min_delay_ms: 1500 };123const CAPTURE = { viewport: true, full_page: true, tiles: true, tile_height: 1200, tile_width: 1280, tile_overlap: 100, elements: ["#price"], sections: true, interactive_states: true, profiles: ["desktop", "mobile"], engine: "chromium", device_scale_factor: 2, locale: "fr-CA", timezone: "America/Toronto", webp_derivatives: false, pdf: true };124const EXTRACT = { formats: ["markdown", "json", "text"], ocr: true, ocr_languages: ["fr-CA"], vision: "on_conflict", include_evidence: true, schema: SCHEMA, rules: { price: { css: "#price" } } };125const BUDGETS = { max_pages: 10, max_depth: 2, max_states_per_page: 5, max_actions_per_page: 10, max_bytes: 10_000_000, max_duration_s: 600, max_urls_per_pattern: 20 };126const COMMON = { policy: POLICY, webhook: { url: "https://hooks.example.org/spider", events: ["job.finished", "change.detected"] }, priority: 7, metadata: { team: "pricing" } };127const URL_ = "https://example.org/";128129// public method -> [routes it must land on (in order of first use), call]130const CALLS = {131  scrape: [["scrape"], (c) => c.scrape({ url: URL_, render: "browser", capture: CAPTURE, extract: EXTRACT, timeout_s: 90, ...COMMON })],132  crawl: [["crawl"], (c) => c.crawl({ urls: [URL_], sitemap: `${URL_}sitemap.xml`, strategy: "priority", render: "http", max_depth: 2, max_pages: 50, max_states_per_page: 3, budgets: BUDGETS, capture: CAPTURE, extract: EXTRACT, use_sitemaps: true, ...COMMON })],133  map: [["map"], (c) => c.map({ url: URL_, budgets: BUDGETS, use_sitemaps: false, render: "browser", ...COMMON })],134  screenshot: [["screenshot"], (c) => c.screenshot({ url: URL_, capture: CAPTURE, timeout_s: 30, ...COMMON })],135  deepCapture: [["deepCapture"], (c) => c.deepCapture({ url: URL_, capture: CAPTURE, budgets: BUDGETS, extract: EXTRACT, timeout_s: 300, ...COMMON })],136  extract: [["extract"], (c) => c.extract({ url: URL_, render: "auto", extract: EXTRACT, ...COMMON })],137  ocr: [["ocr"], (c) => c.ocr({ artifact_id: UUID, languages: ["fr-CA"], fast: true })],138  vision: [["vision"], (c) => c.vision({ artifact_ids: [UUID, UUID], task: "fields", schema: SCHEMA, model: "local-default" })],139  batch: [["batch"], (c) => c.batch([{ kind: "scrape", request: { url: URL_ } }, { kind: "extract", request: { url: URL_, extract: { schema: SCHEMA } } }])],140  createMonitor: [["createMonitor"], (c) => c.createMonitor({ name: "price", request: { url: URL_, extract: EXTRACT, webhook: COMMON.webhook }, interval_s: 3600, watch: ["content", "fields"], ignore_selectors: [".ad"], cooldown_s: 0, enabled: true })],141  diff: [["diff"], (c) => c.diff({ snapshot_a: UUID, snapshot_b: UUID, visual: false, ignore_selectors: [".ad"] })],142  search: [["search"], (c) => c.search({ query: "harbour", site_id: UUID, domain: "example.org", since: "2026-01-01T00:00:00Z", until: "2026-12-31T00:00:00Z", limit: 5, cursor: "abc" })],143  iterSearch: [["search"], (c) => drain(c.iterSearch({ query: "harbour", limit: 5 }))],144  getJob: [["getJob"], (c) => c.getJob(UUID)],145  listJobs: [["listJobs"], (c) => c.listJobs({ status: "running", kind: "crawl", limit: 10, cursor: "abc" })],146  iterJobs: [["listJobs"], (c) => drain(c.iterJobs({ status: "running", pageSize: 10 }))],147  cancelJob: [["cancelJob"], (c) => c.cancelJob(UUID)],148  pauseJob: [["pauseJob"], (c) => c.pauseJob(UUID)],149  resumeJob: [["pauseJob"], (c) => c.resumeJob(UUID)],150  retryJob: [["retryJob"], (c) => c.retryJob(UUID)],151  getResults: [["getResults"], (c) => c.getResults(UUID, { limit: 5, cursor: "abc", includeEvidence: false, includeContent: true, maskPii: true })],152  iterResults: [["getResults"], (c) => drain(c.iterResults(UUID, { pageSize: 5 }))],153  streamEvents: [["streamEvents"], (c) => drain(c.streamEvents(UUID, { lastEventId: "3" }))],154  waitForJob: [["getJob"], (c) => c.waitForJob(UUID)],155  collect: [["getJob", "getResults"], (c) => c.collect(UUID)],156  scrapeAndWait: [["scrape", "getJob", "getResults"], (c) => c.scrapeAndWait({ url: URL_ })],157  crawlAndWait: [["crawl", "getJob", "getResults"], (c) => c.crawlAndWait({ url: URL_ })],158  extractAndWait: [["extract", "getJob", "getResults"], (c) => c.extractAndWait({ url: URL_, extract: { schema_id: UUID } })],159  export: [["export"], (c) => c.export(UUID, { format: "csv", maskPii: true })],160  getArtifact: [["getArtifact"], (c) => c.getArtifact(UUID)],161  getSnapshot: [["getSnapshot"], (c) => c.getSnapshot(UUID)],162  snapshotHistory: [["snapshotHistory"], (c) => c.snapshotHistory(URL_, { limit: 5 })],163  listSites: [["listSites"], (c) => c.listSites()],164  siteGraph: [["siteGraph"], (c) => c.siteGraph(UUID, { jobId: UUID, limit: 10, cursor: "abc" })],165  siteCoverage: [["siteCoverage"], (c) => c.siteCoverage(UUID, { jobId: UUID })],166  health: [["health"], (c) => c.health()],167  me: [["me"], (c) => c.me()],168  listMonitors: [["listMonitors"], (c) => c.listMonitors()],169  monitorAction: [["monitorAction"], (c) => c.monitorAction(UUID, "run-now")],170  listChanges: [["listChanges"], (c) => c.listChanges({ scheduleId: UUID, limit: 5 })],171  webhookSecret: [["webhookSecret"], (c) => c.webhookSecret()],172};173174const ARTIFACT = Buffer.from("artifact-bytes");175function fallback(request) {176  if (request.path.endsWith("/events")) {177    return { status: 200, headers: { "Content-Type": "text/event-stream" }, chunks: ['id: 4\nevent: job.finished\ndata: {"status":"succeeded"}\n\n'] };178  }179  if (request.path.startsWith("/v1/artifacts/")) {180    return { status: 200, body: ARTIFACT, headers: { "X-Spider-Sha256": createHash("sha256").update(ARTIFACT).digest("hex") } };181  }182  return { status: 200, body: { job_id: UUID, status: "succeeded", items: [], not_collected: [], next_cursor: null, secret: "whsec" } };183}184185test("every SDK route exists in docs/openapi.json", () => {186  const missing = Object.entries(ROUTES).filter(([, r]) => !OPERATIONS.has(`${r.method} ${r.path}`)).map(([name]) => name);187  assert.deepEqual(missing, []);188  assert.ok(OPERATIONS.size >= 50);189});190191test("the mandate and every public operation are covered by a method", () => {192  const used = new Set(Object.values(ROUTES).map((r) => `${r.method} ${r.path}`));193  assert.deepEqual(MANDATE.filter((op) => !OPERATIONS.has(op)), [], "mandate list out of date with the document");194  assert.deepEqual(MANDATE.filter((op) => !used.has(op)), []);195  const publicOps = [...OPERATIONS].filter(([, op]) => (op.tags ?? []).some((t) => PUBLIC_TAGS.includes(t))).map(([key]) => key);196  assert.ok(publicOps.length >= 25);197  assert.deepEqual(publicOps.filter((op) => !used.has(op)), []);198});199200test("every public method of the client is exercised, every route is reached", () => {201  const methods = Object.getOwnPropertyNames(Spider.prototype).filter((n) => !["constructor", "toJSON", "request"].includes(n));202  assert.deepEqual(methods.sort(), Object.keys(CALLS).sort());203  assert.deepEqual([...new Set(Object.values(CALLS).flatMap(([routes]) => routes))].sort(), Object.keys(ROUTES).sort());204});205206for (const [name, [routes, call]] of Object.entries(CALLS)) {207  test(`${name} sends requests the document describes`, () =>208    withServer([], async (s) => {209      await call(s.client());210      assert.ok(s.requests.length > 0, "no request was sent");211      const landed = [];212      for (const req of s.requests) {213        const key = match(req.method, req.path);214        if (!landed.includes(key)) landed.push(key);215        const op = OPERATIONS.get(key);216        const declared = (op.parameters ?? []).filter((p) => p.in === "query").map((p) => p.name);217        assert.deepEqual(Object.keys(req.query).filter((q) => !declared.includes(q)), [], `undeclared query parameters on ${key}`);218        const takesKey = (op.parameters ?? []).some((p) => p.in === "header" && p.name === "idempotency-key");219        assert.equal("idempotency-key" in req.headers, takesKey, `Idempotency-Key on ${key}`);220        const schema = bodySchema(op);221        if (schema) assert.deepEqual(validate(schema, req.body), [], `body of ${key}`);222        else assert.equal(req.raw, "", `${key} takes no body`);223        assert.equal(req.headers.authorization, "Bearer sk_test_unit_0123456789");224      }225      assert.deepEqual(landed, routes.map((r) => `${ROUTES[r].method} ${ROUTES[r].path}`));226    }, fallback));227}228229test("the body validator is not vacuous", () => {230  const scrape = bodySchema(OPERATIONS.get("POST /v1/scrape"));231  assert.deepEqual(validate(scrape, { url: URL_ }), []);232  assert.equal(validate(scrape, { url: URL_, no_such_option: 1 }).length, 1);233  assert.equal(validate(scrape, { url: 3 }).length, 1);234  assert.equal(validate(scrape, { url: URL_, priority: 12 }).length, 1);235  assert.equal(validate(scrape, { url: URL_, render: "fast" }).length, 1);236  assert.equal(validate(scrape, { url: URL_, policy: { min_delay: 1 } }).length, 1);237  assert.equal(validate(bodySchema(OPERATIONS.get("POST /v1/monitor")), { name: "x", request: { render: "http" } }).length, 1);238  // the two mandatory policies exist in the contract; the SDK types simply do not expose them239  const policy = OPENAPI.components.schemas.PolicyOptions.properties;240  assert.ok("respect_robots_txt" in policy && "stop_on_access_denied" in policy);241});242
Files main
Menu

Theme