Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SPIDER — Universal Web Intelligence Engine8 * File : sdk/typescript/test/client.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// Retries, idempotency, pagination, events, artifacts and error mapping against a local mock HTTP server.44import assert from "node:assert/strict";45import { createHash } from "node:crypto";46import { createServer } from "node:net";47import { test } from "node:test";48import { inspect } from "node:util";4950import * as sdk from "../dist/index.js";51import { API_KEY, apiError, drain, json, reset, sse, withServer } from "./helpers.mjs";5253const JOB = { job_id: "j1", status: "queued", status_url: "/v1/jobs/j1", results_url: "/v1/jobs/j1/results", events_url: "/v1/jobs/j1/events" };54const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;5556test("a submission is retried with the same Idempotency-Key", () =>57 withServer([apiError(503, "unavailable"), reset, json(202, JOB)], async (s) => {58 const job = await s.client().scrape({ url: "https://example.org/" });59 assert.equal(job.job_id, "j1");60 assert.equal(s.requests.length, 3);61 const keys = new Set(s.requests.map((r) => r.headers["idempotency-key"]));62 assert.equal(keys.size, 1);63 assert.match([...keys][0], UUID);64 assert.equal(new Set(s.requests.map((r) => r.raw)).size, 1); // same body every time65 assert.equal(s.sleeps.length, 2);66 assert.ok(s.sleeps[0] >= 250 && s.sleeps[0] <= 500, "first backoff: base with jitter");67 assert.ok(s.sleeps[1] >= 500 && s.sleeps[1] <= 1000, "second backoff: doubled");68 }));6970test("each logical call has its own key; a caller's key is kept", () =>71 withServer([json(202, JOB), json(202, JOB), json(202, JOB)], async (s) => {72 const c = s.client();73 await c.scrape({ url: "https://example.org/" });74 await c.scrape({ url: "https://example.org/" });75 await c.crawl({ url: "https://example.org/" }, { idempotencyKey: "order-42" });76 const k = s.requests.map((r) => r.headers["idempotency-key"]);77 assert.notEqual(k[0], k[1]);78 assert.equal(k[2], "order-42");79 }));8081test("retries are bounded", () =>82 withServer([1, 2, 3].map(() => apiError(503, "unavailable")), async (s) => {83 await assert.rejects(s.client({ maxRetries: 2 }).getJob("j1"), (e) => e instanceof sdk.ServerError && e.status === 503);84 assert.equal(s.requests.length, 3);85 }));8687for (const status of [502, 503, 504]) {88 test(`${status} is retried on reads`, () =>89 withServer([apiError(status, "upstream"), json(200, JOB)], async (s) => {90 assert.equal((await s.client().getJob("j1")).job_id, "j1");91 assert.equal(s.requests.length, 2);92 }));93}9495test("500 is not retried", () =>96 withServer([apiError(500, "internal_error")], async (s) => {97 await assert.rejects(s.client().getJob("j1"), sdk.ServerError);98 assert.equal(s.requests.length, 1);99 }));100101test("429 honours Retry-After, then details.retry_after_s", () =>102 withServer([apiError(429, "rate_limited", null, { "Retry-After": "7" }), apiError(429, "rate_limited", { retry_after_s: 3 }), json(200, JOB)], async (s) => {103 await s.client().getJob("j1");104 assert.deepEqual(s.sleeps, [7000, 3000]);105 }));106107test("429 is retried without a key, and ends as a typed RateLimitError", async () => {108 await withServer([apiError(429, "rate_limited", { retry_after_s: 1 }), json(201, { id: "m1" })], async (s) => {109 assert.equal((await s.client().createMonitor({ name: "m", request: { url: "https://example.org/" } })).id, "m1");110 });111 await withServer([1, 2].map(() => apiError(429, "rate_limited", { retry_after_s: 1 })), async (s) => {112 await assert.rejects(s.client({ maxRetries: 1 }).getJob("j1"), (e) =>113 e instanceof sdk.RateLimitError && e.retryAfterSeconds === 1 && e.code === "rate_limited");114 assert.deepEqual(s.sleeps, [1000]);115 });116});117118test("a quota without Retry-After and an excessive Retry-After are not retried", async () => {119 await withServer([apiError(429, "quota_exceeded", { quota: "max_jobs_per_day", limit: 5 })], async (s) => {120 await assert.rejects(s.client().scrape({ url: "https://example.org/" }), (e) =>121 e instanceof sdk.QuotaExceededError && e instanceof sdk.RateLimitError && e.details.quota === "max_jobs_per_day");122 assert.equal(s.requests.length, 1);123 });124 await withServer([apiError(429, "rate_limited", null, { "Retry-After": "3600" })], async (s) => {125 await assert.rejects(s.client().getJob("j1"), sdk.RateLimitError);126 assert.deepEqual(s.sleeps, []);127 });128});129130test("a POST without Idempotency-Key is not retried after an ambiguous failure", async () => {131 for (const step of [apiError(503, "unavailable"), reset]) {132 await withServer([step], async (s) => {133 await assert.rejects(s.client().createMonitor({ name: "m", request: { url: "https://example.org/" } }),134 (e) => e instanceof sdk.ServerError || e instanceof sdk.TransportError);135 assert.equal(s.requests.length, 1);136 assert.equal(s.requests[0].headers["idempotency-key"], undefined);137 });138 }139 await withServer([apiError(503, "unavailable")], async (s) => {140 await assert.rejects(s.client().request("POST", "/v1/scrape", { body: { url: "https://example.org/" } }), sdk.ServerError);141 assert.equal(s.requests.length, 1);142 });143});144145test("a connection that was never established is retried, even without a key", async () => {146 const probe = createServer();147 await new Promise((r) => probe.listen(0, "127.0.0.1", r));148 const port = probe.address().port;149 await new Promise((r) => probe.close(r)); // nothing listens on this port any more150 const sleeps = [];151 const c = new sdk.Spider({ baseUrl: `http://127.0.0.1:${port}`, apiKey: API_KEY, maxRetries: 2, sleep: async (ms) => void sleeps.push(ms) });152 await assert.rejects(c.createMonitor({ name: "m", request: { url: "https://example.org/" } }), (e) =>153 e instanceof sdk.TransportError && /ECONNREFUSED/.test(e.message) && !e.message.includes(API_KEY));154 assert.equal(sleeps.length, 2);155});156157test("the low-level request is retried when it carries a key", () =>158 withServer([apiError(502, "bad_gateway"), json(202, JOB)], async (s) => {159 const out = await s.client().request("POST", "/v1/scrape", { body: { url: "https://example.org/" }, idempotencyKey: "k1" });160 assert.equal(out.job_id, "j1");161 assert.deepEqual(s.requests.map((r) => r.headers["idempotency-key"]), ["k1", "k1"]);162 }));163164test("a request that exceeds the timeout is a TransportError", () =>165 withServer([() => new Promise((r) => setTimeout(() => r(json(200, JOB)), 300))], async (s) => {166 await assert.rejects(s.client({ timeoutMs: 40, maxRetries: 0 }).getJob("j1"), (e) => e instanceof sdk.TransportError && /timeout/.test(e.message));167 }));168169const ERRORS = [170 [400, "invalid_cursor", "ValidationError"], [401, "unauthorized", "AuthenticationError"],171 [403, "forbidden", "PermissionDeniedError"], [404, "not_found", "NotFoundError"],172 [409, "idempotency_conflict", "IdempotencyConflictError"], [409, "connector_inactive", "ConflictError"],173 [422, "validation_error", "ValidationError"], [422, "mandatory_policy", "MandatoryPolicyError"],174 [501, "not_implemented", "ServerError"],175];176for (const [status, code, cls] of ERRORS) {177 test(`${status} ${code} is a ${cls} and is not retried`, () =>178 withServer([apiError(status, code, [{ loc: "policy.respect_robots_txt", msg: "…" }])], async (s) => {179 const e = await s.client().scrape({ url: "https://example.org/" }).then(() => null, (x) => x);180 assert.equal(e.constructor.name, cls);181 assert.equal(e.name, cls);182 assert.ok(e instanceof sdk.ApiError && e instanceof sdk.SpiderError && e instanceof Error);183 assert.deepEqual([e.status, e.code, e.message, e.requestId], [status, code, "explained", "rid-1"]);184 assert.deepEqual(e.details, [{ loc: "policy.respect_robots_txt", msg: "…" }]);185 if (status === 401 || status === 403) assert.ok(e instanceof sdk.AuthError);186 if (code === "mandatory_policy") assert.ok(e instanceof sdk.ValidationError);187 assert.equal(s.requests.length, 1);188 assert.deepEqual(s.sleeps, []);189 }));190}191192test("a non-JSON error body still gives a typed error", () =>193 withServer([{ status: 404, body: "<html>nginx</html>", headers: { "X-Request-Id": "edge-9" } }], async (s) => {194 await assert.rejects(s.client().getJob("j1"), (e) =>195 e instanceof sdk.NotFoundError && e.code === "http_error" && e.requestId === "edge-9" && e.message.includes("nginx"));196 }));197198test("the key travels only in the Authorization header", () =>199 withServer([json(200, JOB), json(200, { url: "u", items: [] }), { status: 302, body: "", headers: { Location: "http://elsewhere.invalid/steal" } }], async (s) => {200 const c = s.client({ userAgent: "marge/1.0" });201 await c.getJob("a/b?c");202 await c.snapshotHistory("https://example.org/?q=1");203 await c.request("GET", "/v1/health"); // a redirect is returned, not followed204 assert.equal(s.requests.length, 3);205 const r = s.requests[0];206 assert.equal(r.headers.authorization, `Bearer ${API_KEY}`);207 assert.equal(r.headers["user-agent"], `spider-sdk-typescript/${sdk.VERSION} marge/1.0`);208 assert.equal(r.rawPath, "/v1/jobs/a%2Fb%3Fc"); // identifiers cannot escape their path segment209 assert.equal(s.requests[1].query.url, "https://example.org/?q=1");210 for (const text of [JSON.stringify(c), inspect(c, { depth: 5, showHidden: true }), String(c), ...s.requests.map((q) => q.path + JSON.stringify(q.query))]) {211 assert.ok(!text.includes(API_KEY));212 }213 }));214215test("unsafe configuration is refused", () => {216 for (const [baseUrl, apiKey] of [["ftp://x", "k"], ["https://user:pw@x", "k"], ["https://x?key=1", "k"], ["https://x", ""], ["https://x", "a b"], ["nonsense", "k"]]) {217 assert.throws(() => new sdk.Spider({ baseUrl, apiKey }), TypeError);218 }219});220221test("typed requests cannot disable a mandatory policy; the low-level request reaches the server", () =>222 withServer([apiError(422, "mandatory_policy")], async (s) => {223 const c = s.client();224 for (const name of ["respect_robots_txt", "stop_on_access_denied"]) {225 const policy = { [name]: false };226 await assert.rejects(c.scrape({ url: "https://example.org/", policy }), /mandatory policy/);227 await assert.rejects(c.createMonitor({ name: "m", request: { url: "https://example.org/", policy } }), /mandatory policy/);228 await assert.rejects(c.batch([{ kind: "scrape", request: { url: "https://example.org/", policy } }]), /mandatory policy/);229 }230 assert.equal(s.requests.length, 0);231 await assert.rejects(c.request("POST", "/v1/scrape", { body: { url: "https://example.org/", policy: { respect_robots_txt: false } } }), sdk.MandatoryPolicyError);232 assert.equal(s.requests.length, 1);233 }));234235// ----------------------------------------------------------------------------- pagination and waiting236test("iterResults follows next_cursor", () =>237 withServer([238 json(200, { items: [{ url: "a" }, { url: "b" }], next_cursor: "c1" }),239 json(200, { items: [{ url: "c" }], next_cursor: "c2" }),240 json(200, { items: [], next_cursor: null }),241 ], async (s) => {242 const items = await drain(s.client().iterResults("j1", { pageSize: 2, includeContent: false }));243 assert.deepEqual(items.map((i) => i.url), ["a", "b", "c"]);244 assert.deepEqual(s.requests.map((r) => r.query.cursor), [undefined, "c1", "c2"]);245 assert.ok(s.requests.every((r) => r.query.limit === "2" && r.query.include_content === "false" && r.path === "/v1/jobs/j1/results"));246 }));247248test("iterJobs and iterSearch follow next_cursor", () =>249 withServer([250 json(200, { items: [{ job_id: "1" }], next_cursor: "n" }), json(200, { items: [{ job_id: "2" }] }),251 json(200, { items: [{ url: "u1" }], next_cursor: "o" }), json(200, { items: [{ url: "u2" }], next_cursor: null }),252 ], async (s) => {253 const c = s.client();254 assert.deepEqual((await drain(c.iterJobs({ kind: "crawl" }))).map((j) => j.job_id), ["1", "2"]);255 assert.deepEqual((await drain(c.iterSearch({ query: "harbour" }))).map((h) => h.url), ["u1", "u2"]);256 assert.deepEqual(s.requests[1].query, { kind: "crawl", cursor: "n" });257 assert.deepEqual(s.requests.slice(2).map((r) => r.body), [{ query: "harbour" }, { query: "harbour", cursor: "o" }]);258 }));259260test("waitForJob polls with a growing interval until a terminal state", () =>261 withServer([json(200, JOB), json(200, { ...JOB, status: "running" }), json(200, { ...JOB, status: "running" }), json(200, { ...JOB, status: "partial" })], async (s) => {262 const job = await s.client().waitForJob("j1", { pollIntervalMs: 200, maxPollIntervalMs: 400 });263 assert.equal(job.status, "partial");264 assert.deepEqual(s.sleeps.map(Math.round), [200, 300, 400]);265 }));266267test("terminal states", () => {268 for (const status of sdk.JOB_STATES) assert.equal(sdk.isTerminal({ status }), !["queued", "running"].includes(status));269});270271test("waitForJob times out without cancelling the job", () =>272 withServer([json(200, { ...JOB, status: "running" })], async (s) => {273 await assert.rejects(s.client().waitForJob("j1", { timeoutMs: 0 }), (e) => e instanceof sdk.JobTimeoutError && e.lastStatus === "running");274 assert.deepEqual(s.requests.map((r) => r.method), ["GET"]);275 }));276277test("scrapeAndWait returns the job and every result", () =>278 withServer([279 json(202, JOB), json(200, { ...JOB, status: "succeeded" }),280 json(200, { items: [{ url: "a" }], not_collected: [{ url: "x", status: "blocked" }], next_cursor: "n" }),281 json(200, { items: [{ url: "b" }], not_collected: [], next_cursor: null }),282 ], async (s) => {283 const out = await s.client().scrapeAndWait({ url: "https://example.org/", render: "http" });284 assert.equal(out.job.status, "succeeded");285 assert.deepEqual(out.results.map((i) => i.url), ["a", "b"]);286 assert.equal(out.notCollected.length, 1);287 assert.deepEqual(s.requests[0].body, { url: "https://example.org/", render: "http" });288 }));289290// ----------------------------------------------------------------------------- events291const EVENTS = [292 ": keep-alive\n\n",293 'id: 1\nevent: job.progress\ndata: {"pa', 'ges": 1}\n\nid: 2\r', '\nevent: url.fetched\r\ndata: {"url":\r\ndata: "https://example.org/é"}\r\n\r\n',294 "event: note\ndata: not json\n\n",295 'id: 3\nevent: job.finished\ndata: {"status": "succeeded"}\n\n',296 "id: 4\nevent: never\ndata: {}\n\n",297];298299test("streamEvents parses SSE across chunk boundaries and stops at job.finished", () =>300 withServer([sse(...EVENTS)], async (s) => {301 const events = await drain(s.client().streamEvents("j1"));302 assert.deepEqual(events.map((e) => [e.id, e.type]), [["1", "job.progress"], ["2", "url.fetched"], ["2", "note"], ["3", "job.finished"]]);303 assert.deepEqual(events[0].data, { pages: 1 });304 assert.deepEqual(events[1].data, { url: "https://example.org/é" });305 assert.equal(events[2].data, "not json");306 assert.equal(s.requests[0].headers.accept, "text/event-stream");307 assert.equal(s.requests[0].headers["last-event-id"], undefined);308 }));309310test("a multi-byte character split between two chunks is decoded once", () =>311 withServer([sse(Buffer.from('id: 1\nevent: job.finished\ndata: {"t": "caf\xc3', "latin1"), Buffer.from('\xa9"}\n\n', "latin1"))], async (s) => {312 const [ev] = await drain(s.client().streamEvents("j1"));313 assert.deepEqual(ev.data, { t: "café" });314 }));315316test("streamEvents resumes with Last-Event-ID", () =>317 withServer([sse("id: 7\nevent: job.progress\ndata: {}\n\n"), sse("id: 8\nevent: job.finished\ndata: {}\n\n")], async (s) => {318 const events = await drain(s.client().streamEvents("j1", { lastEventId: "5" }));319 assert.deepEqual(events.map((e) => e.id), ["7", "8"]);320 assert.deepEqual(s.requests.map((r) => r.headers["last-event-id"]), ["5", "7"]);321 }));322323test("streamEvents gives up on a stream that never delivers", () =>324 withServer([sse(""), sse(""), sse("")], async (s) => {325 await assert.rejects(drain(s.client({ maxRetries: 2 }).streamEvents("j1")), sdk.TransportError);326 assert.equal(s.requests.length, 3);327 }));328329test("waitForJob can follow the event stream", () =>330 withServer([sse(...EVENTS), json(200, { ...JOB, status: "succeeded" })], async (s) => {331 const job = await s.client().waitForJob("j1", { useEvents: true });332 assert.equal(job.status, "succeeded");333 assert.deepEqual(s.requests.map((r) => r.path), ["/v1/jobs/j1/events", "/v1/jobs/j1"]);334 }));335336test("waitForJob over events honours its timeout", () =>337 withServer([() => new Promise((r) => setTimeout(() => r(sse("id: 1\nevent: job.progress\ndata: {}\n\n")), 500))], async (s) => {338 await assert.rejects(s.client({ maxRetries: 0 }).waitForJob("j1", { useEvents: true, timeoutMs: 50 }), sdk.JobTimeoutError);339 }));340341test("waitForJob over events times out on an open, silent stream", () =>342 withServer([{ ...sse("id: 1\nevent: job.progress\ndata: {}\n\n"), hold: true }], async (s) => {343 const t0 = Date.now();344 await assert.rejects(s.client().waitForJob("j1", { useEvents: true, timeoutMs: 80 }), sdk.JobTimeoutError);345 assert.ok(Date.now() - t0 < 2000);346 assert.equal(s.requests.length, 1);347 }));348349test("an aborted event stream stops", () =>350 withServer([{ ...sse("id: 1\nevent: job.progress\ndata: {}\n\n"), hold: true }], async (s) => {351 const ctl = new AbortController();352 const seen = [];353 await assert.rejects((async () => {354 for await (const ev of s.client().streamEvents("j1", { signal: ctl.signal })) {355 seen.push(ev.id);356 ctl.abort(new Error("enough"));357 }358 })(), /enough/);359 assert.deepEqual(seen, ["1"]);360 }));361362test("SSEParser ignores comments, retry fields and empty data", () => {363 const p = new sdk.SSEParser();364 const events = p.feed("retry: 10\nid: 9\ndata: 1\ndata: 2\n\n\n: c\ndata\n\n");365 assert.deepEqual(events, [{ id: "9", type: "message", data: "1\n2" }]);366 assert.equal(p.lastEventId, "9");367});368369// ----------------------------------------------------------------------------- artifacts and export370test("getArtifact verifies the announced hash", async () => {371 const data = Buffer.from("\x89PNG fixture bytes", "latin1");372 const good = createHash("sha256").update(data).digest("hex");373 const resp = (sha) => ({ status: 200, body: data, headers: sha ? { "X-Spider-Sha256": sha } : {} });374 await withServer([resp(good), resp(good.toUpperCase()), resp("0".repeat(64)), resp(null), resp(good)], async (s) => {375 const c = s.client();376 assert.deepEqual(Buffer.from(await c.getArtifact("a1")), data);377 assert.deepEqual(Buffer.from(await c.getArtifact("a1", { expectedSha256: good })), data);378 await assert.rejects(c.getArtifact("a1"), (e) => e instanceof sdk.ArtifactIntegrityError && e.expected === "0".repeat(64) && e.actual === good);379 await assert.rejects(c.getArtifact("a1"), sdk.ArtifactIntegrityError); // no header: integrity cannot be established380 await assert.rejects(c.getArtifact("a1", { expectedSha256: "1".repeat(64) }), sdk.ArtifactIntegrityError);381 assert.equal(s.requests[0].path, "/v1/artifacts/a1");382 assert.deepEqual(s.requests[0].query, {});383 });384});385386test("export returns bytes", () =>387 withServer([{ status: 200, body: Buffer.from('{"url":"a"}\n') }], async (s) => {388 const out = await s.client().export("j1", { maskPii: true });389 assert.deepEqual(JSON.parse(new TextDecoder().decode(out)), { url: "a" });390 assert.deepEqual(s.requests[0].query, { format: "jsonl", mask: "pii" });391 }));392393test("an aborted call stops without retrying", () =>394 withServer([() => new Promise((r) => setTimeout(() => r(json(200, JOB)), 300))], async (s) => {395 const ctl = new AbortController();396 setTimeout(() => ctl.abort(new Error("stop")), 30);397 await assert.rejects(s.client().getJob("j1", { signal: ctl.signal }), /stop/);398 assert.deepEqual(s.sleeps, []);399 }));400