@synthient/synthient 1.0.1 → 2.0.0

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.
package/dist/client.d.ts CHANGED
@@ -1,42 +1,101 @@
1
- import { LookupResponse, VisitResponse, DeleteResponse } from './models';
1
+ import type { AnonymizerEvent, HeliosADBEvent, HeliosDNSEvent, HeliosHTTPEvent, HeliosHTTPSEvent, JA4TEvent, ProxyEvent, TorrentEvent } from "./events.ts";
2
+ import { Feed } from "./feed.ts";
3
+ import { type Fetch, type RequestOptions, type ResponseMetadata } from "./transport.ts";
4
+ import type { Account, DomainInfo, IPInfo } from "./types.ts";
5
+ export declare const DEFAULT_BASE_URL = "https://api.synthient.com/api/v4";
6
+ export interface ClientOptions {
7
+ /** The API key. Defaults to the SYNTHIENT_API_KEY environment variable. */
8
+ apiKey?: string | undefined;
9
+ /** The API base URL, including the version path. Defaults to {@link DEFAULT_BASE_URL}. */
10
+ baseURL?: string | undefined;
11
+ /** How many times a failed request is retried. Defaults to 2; 0 disables retries. */
12
+ maxRetries?: number | undefined;
13
+ /**
14
+ * The longest time in milliseconds to wait for response headers or for the next part
15
+ * of a body, including streams and downloads. Defaults to 60,000. It does not limit a
16
+ * whole call; see {@link RequestOptions.signal}.
17
+ */
18
+ timeout?: number | undefined;
19
+ /**
20
+ * The fetch implementation. Defaults to the global `fetch`. A custom fetch must honor
21
+ * `init.signal` and must not follow redirects or replay requests itself; the client
22
+ * handles each redirect to keep the API key away from other hosts.
23
+ */
24
+ fetch?: Fetch | undefined;
25
+ /** Appended to the User-Agent header, such as "my-app/1.2". */
26
+ userAgent?: string | undefined;
27
+ /**
28
+ * Called synchronously when each API response's headers arrive, including retries,
29
+ * pages, stream handshakes, and responses that fail to decode. Storage download
30
+ * responses are excluded. It must not be async. If it throws, the error is reported
31
+ * with `process.emitWarning` and the call continues.
32
+ */
33
+ onResponse?: ((metadata: ResponseMetadata) => void) | undefined;
34
+ }
35
+ export interface LookupDomainOptions extends RequestOptions {
36
+ /** Caps the number of recent events returned. The API default is 50, and it clamps values above 1000. */
37
+ limit?: number | undefined;
38
+ }
2
39
  /**
3
- * Async client for interacting with the Synthient API.
40
+ * A Synthient API client. Creating one does no network I/O. Reuse one client for every
41
+ * request.
42
+ *
43
+ * Account and feed requests to the API are retried on 500, 502, 503, and 504 responses,
44
+ * on rate limits, and on timeouts and connection failures. Lookups and health are
45
+ * retried only on rate limits, which the API returns before doing any work. A
46
+ * download's request to the storage host is not retried. A rate limit is a 429 with
47
+ * Retry-After; a 429 without it means the key's monthly budget or concurrent stream
48
+ * limit is spent, and is not retried. Retries back off exponentially with jitter and
49
+ * honor Retry-After.
4
50
  */
5
- declare class Client {
6
- private _http;
7
- default_timeout: number;
8
- /**
9
- * Initializes the client with an API key, default timeout, and optional proxy.
10
- *
11
- * @param api_key - The API key for authorization.
12
- * @param default_timeout - The default timeout for requests.
13
- * @param proxy - Optional proxy configuration.
14
- * @param port - Optional port for the proxy.
15
- */
16
- constructor(api_key: string, default_timeout?: number, proxy?: string, port?: number);
17
- /**
18
- * Lookup a token and return its corresponding data.
19
- *
20
- * @param token - Token to lookup.
21
- * @throws ErrorResponse | InternalServerError - If the server returns a 401, 404, 409, or 500 status code.
22
- * @returns LookupResponse - The token data.
23
- */
24
- lookup(token: string): Promise<LookupResponse>;
25
- /**
26
- * Lookup a session and return its corresponding visit data.
27
- *
28
- * @param session - Session to lookup.
29
- * @throws ErrorResponse | InternalServerError - If the server returns a 401, 409, or 500 status code.
30
- * @returns VisitResponse - The session data.
31
- */
32
- visits(session: string): Promise<VisitResponse>;
33
- /**
34
- * Delete a token.
35
- *
36
- * @param token - Token to delete.
37
- * @throws InternalServerError - If the server returns a 500 status code.
38
- * @returns DeleteResponse - The response from the server.
39
- */
40
- delete(token: string): Promise<DeleteResponse>;
51
+ export declare class Synthient {
52
+ #private;
53
+ /** The residential, mobile, and datacenter proxy feed. Streaming needs the PROXY_FIREHOSE scope and exports need PROXY_FEEDS. */
54
+ readonly proxies: Feed<ProxyEvent>;
55
+ /** The VPN and anonymizer IP range feed. Streaming needs the ANONYMIZERS_STREAM scope and exports need ANONYMIZERS_FEED. */
56
+ readonly anonymizers: Feed<AnonymizerEvent>;
57
+ /** The BitTorrent DHT and tracker feed. Streaming needs the TORRENTS_STREAM scope and exports need TORRENTS_FEED. */
58
+ readonly torrents: Feed<TorrentEvent>;
59
+ /** The JA4T TCP fingerprint feed. Streaming needs the JA4T_STREAM scope and exports need JA4T_FEED. */
60
+ readonly ja4t: Feed<JA4TEvent>;
61
+ /** The Helios honeypot HTTP capture feed. Streaming needs the HONEYPOT_HTTP_STREAM scope and exports need HONEYPOT_HTTP_FEED. */
62
+ readonly heliosHTTP: Feed<HeliosHTTPEvent>;
63
+ /** The Helios honeypot TLS ClientHello capture feed. Streaming needs the HONEYPOT_HTTPS_STREAM scope and exports need HONEYPOT_HTTPS_FEED. */
64
+ readonly heliosHTTPS: Feed<HeliosHTTPSEvent>;
65
+ /** The Helios honeypot DNS tunnel feed. Streaming needs the HONEYPOT_DNS_STREAM scope and exports need HONEYPOT_DNS_FEED. */
66
+ readonly heliosDNS: Feed<HeliosDNSEvent>;
67
+ /** The Helios honeypot Android Debug Bridge command feed. Streaming needs the HONEYPOT_ADB_STREAM scope and exports need HONEYPOT_ADB_FEED. */
68
+ readonly heliosADB: Feed<HeliosADBEvent>;
69
+ /** Throws a TypeError or RangeError if the API key is missing or an option is invalid. */
70
+ constructor(options?: ClientOptions);
71
+ /**
72
+ * Returns intelligence for an IPv4 or IPv6 address. Each lookup costs one credit;
73
+ * failed lookups are not billed. A private or reserved address rejects with an
74
+ * APIError with status 422.
75
+ */
76
+ lookupIP(ip: string, options?: RequestOptions): Promise<IPInfo>;
77
+ /**
78
+ * Looks up as many as 1000 addresses in one request, billed as ceil(n × 0.9) credits
79
+ * for the n distinct usable addresses. Private and reserved addresses are skipped and
80
+ * duplicates collapse, so match results by their canonical `ip`, not by position.
81
+ * Results follow the order each address first appears. A batch with no usable address
82
+ * rejects with an APIError with status 422. An empty list returns [] without a request.
83
+ */
84
+ lookupIPs(ips: Iterable<string>, options?: RequestOptions): Promise<IPInfo[]>;
85
+ /**
86
+ * Returns the honeypot traffic observed for a domain. A domain that was never observed
87
+ * resolves with status "inactive" and zeroed stats. Internationalized names must be
88
+ * sent in Punycode. Each lookup costs one credit.
89
+ */
90
+ lookupDomain(domain: string, options?: LookupDomainOptions): Promise<DomainInfo>;
91
+ /**
92
+ * Returns the account that owns the API key, including its scopes and remaining
93
+ * lookup credits. It costs no credits.
94
+ */
95
+ account(options?: RequestOptions): Promise<Account>;
96
+ /**
97
+ * Resolves if the API and its dependencies are healthy. An unhealthy API rejects at
98
+ * once with an APIError with status 503.
99
+ */
100
+ health(options?: RequestOptions): Promise<void>;
41
101
  }
42
- export { Client };
package/dist/client.js CHANGED
@@ -1,106 +1,157 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.Client = void 0;
16
- const axios_1 = __importDefault(require("axios"));
17
- const constants_1 = require("./constants");
18
- const exceptions_1 = require("./exceptions");
19
- const models_1 = require("./models");
1
+ import { isIP } from "node:net";
2
+ import { SynthientError } from "./errors.js";
3
+ import { Feed, exactTunnelID } from "./feed.js";
4
+ import { checkTimeout, limitQuery, resolveAPIKey } from "./options.js";
5
+ import { Transport, isHTTP, kWait, wait, } from "./transport.js";
6
+ import { VERSION } from "./version.js";
7
+ export const DEFAULT_BASE_URL = "https://api.synthient.com/api/v4";
20
8
  /**
21
- * Async client for interacting with the Synthient API.
9
+ * A Synthient API client. Creating one does no network I/O. Reuse one client for every
10
+ * request.
11
+ *
12
+ * Account and feed requests to the API are retried on 500, 502, 503, and 504 responses,
13
+ * on rate limits, and on timeouts and connection failures. Lookups and health are
14
+ * retried only on rate limits, which the API returns before doing any work. A
15
+ * download's request to the storage host is not retried. A rate limit is a 429 with
16
+ * Retry-After; a 429 without it means the key's monthly budget or concurrent stream
17
+ * limit is spent, and is not retried. Retries back off exponentially with jitter and
18
+ * honor Retry-After.
22
19
  */
23
- class Client {
20
+ export class Synthient {
21
+ /** The residential, mobile, and datacenter proxy feed. Streaming needs the PROXY_FIREHOSE scope and exports need PROXY_FEEDS. */
22
+ proxies;
23
+ /** The VPN and anonymizer IP range feed. Streaming needs the ANONYMIZERS_STREAM scope and exports need ANONYMIZERS_FEED. */
24
+ anonymizers;
25
+ /** The BitTorrent DHT and tracker feed. Streaming needs the TORRENTS_STREAM scope and exports need TORRENTS_FEED. */
26
+ torrents;
27
+ /** The JA4T TCP fingerprint feed. Streaming needs the JA4T_STREAM scope and exports need JA4T_FEED. */
28
+ ja4t;
29
+ /** The Helios honeypot HTTP capture feed. Streaming needs the HONEYPOT_HTTP_STREAM scope and exports need HONEYPOT_HTTP_FEED. */
30
+ heliosHTTP;
31
+ /** The Helios honeypot TLS ClientHello capture feed. Streaming needs the HONEYPOT_HTTPS_STREAM scope and exports need HONEYPOT_HTTPS_FEED. */
32
+ heliosHTTPS;
33
+ /** The Helios honeypot DNS tunnel feed. Streaming needs the HONEYPOT_DNS_STREAM scope and exports need HONEYPOT_DNS_FEED. */
34
+ heliosDNS;
35
+ /** The Helios honeypot Android Debug Bridge command feed. Streaming needs the HONEYPOT_ADB_STREAM scope and exports need HONEYPOT_ADB_FEED. */
36
+ heliosADB;
37
+ #transport;
38
+ /** Throws a TypeError or RangeError if the API key is missing or an option is invalid. */
39
+ constructor(options = {}) {
40
+ const apiKey = resolveAPIKey(options.apiKey);
41
+ if (apiKey === "") {
42
+ throw new TypeError("missing API key: pass apiKey or set SYNTHIENT_API_KEY");
43
+ }
44
+ const baseURL = URL.parse(options.baseURL ?? DEFAULT_BASE_URL);
45
+ if (!isHTTP(baseURL) ||
46
+ baseURL.search ||
47
+ baseURL.hash ||
48
+ baseURL.username ||
49
+ baseURL.password) {
50
+ throw new TypeError("invalid baseURL: use an http(s) URL without credentials, query, or fragment");
51
+ }
52
+ const maxRetries = options.maxRetries ?? 2;
53
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) {
54
+ throw new RangeError("maxRetries must be a non-negative integer");
55
+ }
56
+ const timeout = options.timeout ?? 60_000;
57
+ checkTimeout(timeout);
58
+ this.#transport = new Transport({
59
+ apiKey,
60
+ baseURL,
61
+ maxRetries,
62
+ timeout,
63
+ fetch: options.fetch ?? fetch,
64
+ userAgent: options.userAgent
65
+ ? `synthient-node/${VERSION} ${options.userAgent}`
66
+ : `synthient-node/${VERSION}`,
67
+ onResponse: options.onResponse,
68
+ wait: options[kWait] ?? wait,
69
+ });
70
+ this.proxies = new Feed(this.#transport, "/feeds/proxies");
71
+ this.anonymizers = new Feed(this.#transport, "/feeds/anonymizers");
72
+ this.torrents = new Feed(this.#transport, "/feeds/torrents");
73
+ this.ja4t = new Feed(this.#transport, "/feeds/ja4t");
74
+ this.heliosHTTP = new Feed(this.#transport, "/feeds/helio/http", exactTunnelID);
75
+ this.heliosHTTPS = new Feed(this.#transport, "/feeds/helio/https", exactTunnelID);
76
+ this.heliosDNS = new Feed(this.#transport, "/feeds/helio/dns", exactTunnelID);
77
+ this.heliosADB = new Feed(this.#transport, "/feeds/helio/adb");
78
+ }
24
79
  /**
25
- * Initializes the client with an API key, default timeout, and optional proxy.
26
- *
27
- * @param api_key - The API key for authorization.
28
- * @param default_timeout - The default timeout for requests.
29
- * @param proxy - Optional proxy configuration.
30
- * @param port - Optional port for the proxy.
80
+ * Returns intelligence for an IPv4 or IPv6 address. Each lookup costs one credit;
81
+ * failed lookups are not billed. A private or reserved address rejects with an
82
+ * APIError with status 422.
31
83
  */
32
- constructor(api_key, default_timeout = constants_1.DEFAULT_TIMEOUT, proxy, port) {
33
- const proxyConfig = proxy
34
- ? {
35
- host: proxy,
36
- port: port ? port : 8000, // Use provided port or default to 8000
37
- }
38
- : undefined;
39
- this._http = axios_1.default.create({
40
- headers: { Authorization: api_key },
41
- proxy: proxyConfig,
42
- timeout: default_timeout,
43
- validateStatus: () => true,
44
- });
45
- this.default_timeout = default_timeout;
84
+ async lookupIP(ip, options) {
85
+ if (typeof ip !== "string" || isIP(ip) === 0) {
86
+ throw new TypeError("invalid IP address");
87
+ }
88
+ return this.#transport.json({ path: `/lookup/ip/${pathSegment(ip)}`, policy: "rateLimit" }, options?.signal);
46
89
  }
47
90
  /**
48
- * Lookup a token and return its corresponding data.
49
- *
50
- * @param token - Token to lookup.
51
- * @throws ErrorResponse | InternalServerError - If the server returns a 401, 404, 409, or 500 status code.
52
- * @returns LookupResponse - The token data.
91
+ * Looks up as many as 1000 addresses in one request, billed as ceil(n × 0.9) credits
92
+ * for the n distinct usable addresses. Private and reserved addresses are skipped and
93
+ * duplicates collapse, so match results by their canonical `ip`, not by position.
94
+ * Results follow the order each address first appears. A batch with no usable address
95
+ * rejects with an APIError with status 422. An empty list returns [] without a request.
53
96
  */
54
- lookup(token) {
55
- return __awaiter(this, void 0, void 0, function* () {
56
- const resp = yield this._http.get(`${constants_1.API_URL}lookup/${token}`);
57
- if (resp.status === 200) {
58
- return new models_1.LookupResponse(resp.data.token, resp.data.token_type, resp.data.session, resp.data.device, resp.data.browser, resp.data.ip, resp.data.ip_data, resp.data.location, resp.data.page, resp.data.risk_score, resp.data.is_incognito, resp.data.is_bot, resp.data.is_vm, resp.data.solved, resp.data.consumed);
59
- }
60
- else if ([401, 404, 409].includes(resp.status)) {
61
- throw new exceptions_1.ErrorResponse(resp.data.message);
97
+ async lookupIPs(ips, options) {
98
+ const addresses = Array.from(ips);
99
+ for (const [index, ip] of addresses.entries()) {
100
+ if (typeof ip !== "string" || isIP(ip) === 0) {
101
+ throw new TypeError(`invalid IP address at index ${index}`);
62
102
  }
63
- else {
64
- throw new exceptions_1.InternalServerError("Server failed to lookup token.");
65
- }
66
- });
103
+ }
104
+ if (addresses.length === 0) {
105
+ options?.signal?.throwIfAborted();
106
+ return [];
107
+ }
108
+ const batch = await this.#transport.json({
109
+ method: "POST",
110
+ path: "/lookup/ips",
111
+ body: JSON.stringify({ ips: addresses }),
112
+ policy: "rateLimit",
113
+ }, options?.signal);
114
+ if (!Array.isArray(batch.results)) {
115
+ throw new SynthientError("batch response has no results array");
116
+ }
117
+ return batch.results;
67
118
  }
68
119
  /**
69
- * Lookup a session and return its corresponding visit data.
70
- *
71
- * @param session - Session to lookup.
72
- * @throws ErrorResponse | InternalServerError - If the server returns a 401, 409, or 500 status code.
73
- * @returns VisitResponse - The session data.
120
+ * Returns the honeypot traffic observed for a domain. A domain that was never observed
121
+ * resolves with status "inactive" and zeroed stats. Internationalized names must be
122
+ * sent in Punycode. Each lookup costs one credit.
74
123
  */
75
- visits(session) {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- const resp = yield this._http.get(`${constants_1.API_URL}visits/${session}`);
78
- if (resp.status === 200) {
79
- return new models_1.VisitResponse(resp.data.session, resp.data.visits, resp.data.has_next);
80
- }
81
- else if ([401, 409].includes(resp.status)) {
82
- throw new exceptions_1.ErrorResponse(resp.data.message);
83
- }
84
- else {
85
- throw new exceptions_1.InternalServerError("Server failed to lookup token.");
86
- }
87
- });
124
+ async lookupDomain(domain, options) {
125
+ if (typeof domain !== "string" ||
126
+ domain === "" ||
127
+ domain === "." ||
128
+ domain === ".." ||
129
+ !domain.isWellFormed()) {
130
+ throw new TypeError("invalid domain");
131
+ }
132
+ return this.#transport.json({
133
+ path: `/lookup/domain/${pathSegment(domain)}`,
134
+ query: limitQuery(options?.limit),
135
+ policy: "rateLimit",
136
+ }, options?.signal);
88
137
  }
89
138
  /**
90
- * Delete a token.
91
- *
92
- * @param token - Token to delete.
93
- * @throws InternalServerError - If the server returns a 500 status code.
94
- * @returns DeleteResponse - The response from the server.
139
+ * Returns the account that owns the API key, including its scopes and remaining
140
+ * lookup credits. It costs no credits.
95
141
  */
96
- delete(token) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- const resp = yield this._http.delete(`${constants_1.API_URL}delete/${token}`);
99
- if (resp.status === 500) {
100
- throw new exceptions_1.InternalServerError("Server failed to delete token.");
101
- }
102
- return new models_1.DeleteResponse(resp.data.message);
103
- });
142
+ async account(options) {
143
+ return this.#transport.json({ path: "/account/me", policy: "transient" }, options?.signal);
104
144
  }
145
+ /**
146
+ * Resolves if the API and its dependencies are healthy. An unhealthy API rejects at
147
+ * once with an APIError with status 503.
148
+ */
149
+ async health(options) {
150
+ await this.#transport.json({ path: "/health", policy: "rateLimit" }, options?.signal);
151
+ }
152
+ }
153
+ // Escapes a path segment like Go's url.PathEscape, which the other Synthient SDKs use:
154
+ // "/", "?", "#", and "%" are escaped and IPv6 colons are kept.
155
+ function pathSegment(value) {
156
+ return encodeURIComponent(value).replaceAll("%3A", ":");
105
157
  }
106
- exports.Client = Client;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Base class of the errors the SDK throws for failed requests and invalid responses.
3
+ * Invalid arguments and configuration throw `TypeError` or `RangeError` instead, and a
4
+ * canceled request rejects with its `AbortSignal`'s reason.
5
+ */
6
+ export declare class SynthientError extends Error {
7
+ name: string;
8
+ }
9
+ /**
10
+ * The connection failed before a response arrived or while its body was being read, such
11
+ * as a DNS, connection, or TLS failure or a dropped stream. The underlying error is
12
+ * `cause`, except for storage host failures during a download, where it is omitted to
13
+ * keep presigned URLs out of errors.
14
+ */
15
+ export declare class APIConnectionError extends SynthientError {
16
+ name: string;
17
+ }
18
+ /**
19
+ * No data arrived for the client's `timeout` while waiting for a response or reading
20
+ * its body.
21
+ */
22
+ export declare class APITimeoutError extends APIConnectionError {
23
+ name: string;
24
+ }
25
+ export interface APIErrorInit {
26
+ status: number;
27
+ type?: string | undefined;
28
+ title?: string | undefined;
29
+ detail?: string | undefined;
30
+ errors?: Record<string, string[]> | undefined;
31
+ requestID?: string | undefined;
32
+ retryAfter?: number | undefined;
33
+ }
34
+ /**
35
+ * The API answered with a non-success HTTP status.
36
+ *
37
+ * `message` contains only the HTTP status, so it is safe to log. The other fields come
38
+ * from the server's problem details and can contain sensitive data.
39
+ */
40
+ export declare class APIError extends SynthientError {
41
+ name: string;
42
+ /** The HTTP status code, such as 402 when the account is out of credits. */
43
+ readonly status: number;
44
+ /** The problem type URI, such as "https://docs.synthient.com/errors/unauthorized", or "". */
45
+ readonly type: string;
46
+ /** A short summary of the problem type, or "". */
47
+ readonly title: string;
48
+ /**
49
+ * An explanation of this occurrence of the problem, or "". For a plain-text error,
50
+ * such as the edge's 401 for a malformed key, it is the response body.
51
+ */
52
+ readonly detail: string;
53
+ /** Validation messages by request field, set on 422 responses. */
54
+ readonly errors: Record<string, string[]>;
55
+ /** Identifies the request when contacting Synthient support, or "". */
56
+ readonly requestID: string;
57
+ /** Milliseconds the server asked the caller to wait before retrying, if it said. */
58
+ readonly retryAfter: number | undefined;
59
+ constructor(init: APIErrorInit, options?: ErrorOptions);
60
+ }
61
+ /**
62
+ * Plain text, HTML, and malformed problem details still keep the status, request ID, and
63
+ * Retry-After.
64
+ */
65
+ export declare function apiError(response: Response, body: Uint8Array, cause?: unknown): APIError;
66
+ /**
67
+ * Parses a Retry-After header as whole seconds or an IMF-fixdate and returns
68
+ * milliseconds. Negative and past values become 0; absent and malformed values return
69
+ * undefined.
70
+ */
71
+ export declare function parseRetryAfter(header: string | null): number | undefined;
72
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
package/dist/errors.js ADDED
@@ -0,0 +1,122 @@
1
+ import { STATUS_CODES } from "node:http";
2
+ const IMF_FIXDATE = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/;
3
+ /**
4
+ * Base class of the errors the SDK throws for failed requests and invalid responses.
5
+ * Invalid arguments and configuration throw `TypeError` or `RangeError` instead, and a
6
+ * canceled request rejects with its `AbortSignal`'s reason.
7
+ */
8
+ export class SynthientError extends Error {
9
+ name = "SynthientError";
10
+ }
11
+ /**
12
+ * The connection failed before a response arrived or while its body was being read, such
13
+ * as a DNS, connection, or TLS failure or a dropped stream. The underlying error is
14
+ * `cause`, except for storage host failures during a download, where it is omitted to
15
+ * keep presigned URLs out of errors.
16
+ */
17
+ export class APIConnectionError extends SynthientError {
18
+ name = "APIConnectionError";
19
+ }
20
+ /**
21
+ * No data arrived for the client's `timeout` while waiting for a response or reading
22
+ * its body.
23
+ */
24
+ export class APITimeoutError extends APIConnectionError {
25
+ name = "APITimeoutError";
26
+ }
27
+ /**
28
+ * The API answered with a non-success HTTP status.
29
+ *
30
+ * `message` contains only the HTTP status, so it is safe to log. The other fields come
31
+ * from the server's problem details and can contain sensitive data.
32
+ */
33
+ export class APIError extends SynthientError {
34
+ name = "APIError";
35
+ /** The HTTP status code, such as 402 when the account is out of credits. */
36
+ status;
37
+ /** The problem type URI, such as "https://docs.synthient.com/errors/unauthorized", or "". */
38
+ type;
39
+ /** A short summary of the problem type, or "". */
40
+ title;
41
+ /**
42
+ * An explanation of this occurrence of the problem, or "". For a plain-text error,
43
+ * such as the edge's 401 for a malformed key, it is the response body.
44
+ */
45
+ detail;
46
+ /** Validation messages by request field, set on 422 responses. */
47
+ errors;
48
+ /** Identifies the request when contacting Synthient support, or "". */
49
+ requestID;
50
+ /** Milliseconds the server asked the caller to wait before retrying, if it said. */
51
+ retryAfter;
52
+ constructor(init, options) {
53
+ const text = STATUS_CODES[init.status];
54
+ super(text === undefined ? String(init.status) : `${init.status} ${text}`, options);
55
+ this.status = init.status;
56
+ this.type = init.type ?? "";
57
+ this.title = init.title ?? "";
58
+ this.detail = init.detail ?? "";
59
+ this.errors = init.errors ?? {};
60
+ this.requestID = init.requestID ?? "";
61
+ this.retryAfter = init.retryAfter;
62
+ }
63
+ }
64
+ /**
65
+ * Plain text, HTML, and malformed problem details still keep the status, request ID, and
66
+ * Retry-After.
67
+ */
68
+ export function apiError(response, body, cause) {
69
+ const decoded = new TextDecoder().decode(body);
70
+ let problem;
71
+ try {
72
+ const parsed = JSON.parse(decoded);
73
+ if (isObject(parsed)) {
74
+ problem = parsed;
75
+ }
76
+ }
77
+ catch {
78
+ // Not problem details; the status and headers still describe the failure.
79
+ }
80
+ const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
81
+ const plainText = problem === undefined && mediaType === "text/plain" ? decoded.trim() : "";
82
+ problem ??= {};
83
+ const text = (value) => (typeof value === "string" ? value : "");
84
+ let errors = {};
85
+ if (isObject(problem.errors)) {
86
+ const entries = Object.entries(problem.errors);
87
+ const valid = entries.every(([, messages]) => {
88
+ return Array.isArray(messages) && messages.every((message) => typeof message === "string");
89
+ });
90
+ if (valid) {
91
+ errors = Object.fromEntries(entries);
92
+ }
93
+ }
94
+ return new APIError({
95
+ status: response.status,
96
+ type: text(problem.type),
97
+ title: text(problem.title),
98
+ detail: plainText || text(problem.detail),
99
+ errors,
100
+ requestID: response.headers.get("x-request-id") ?? text(problem.instance),
101
+ retryAfter: parseRetryAfter(response.headers.get("retry-after")),
102
+ }, cause === undefined ? undefined : { cause });
103
+ }
104
+ /**
105
+ * Parses a Retry-After header as whole seconds or an IMF-fixdate and returns
106
+ * milliseconds. Negative and past values become 0; absent and malformed values return
107
+ * undefined.
108
+ */
109
+ export function parseRetryAfter(header) {
110
+ const value = header?.trim() ?? "";
111
+ if (/^-?\d+$/.test(value)) {
112
+ return Math.min(Math.max(Number(value), 0), 2 ** 31) * 1000;
113
+ }
114
+ if (!IMF_FIXDATE.test(value)) {
115
+ return undefined;
116
+ }
117
+ const at = Date.parse(value);
118
+ return Number.isFinite(at) ? Math.max(at - Date.now(), 0) : undefined;
119
+ }
120
+ export function isObject(value) {
121
+ return typeof value === "object" && value !== null && !Array.isArray(value);
122
+ }