screenshotone-api-sdk 1.1.23 → 1.1.25

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/README.md CHANGED
@@ -36,7 +36,7 @@ const url = client.generateTakeURL(options);
36
36
  console.log(url);
37
37
  // expected output: https://api.screenshotone.com/take?url=https%3A%2F%2Fexample.com&delay=3&block_ads=true&access_key=%3Caccess+key%3E&signature=7f3419ece2c53ed2c7923c7d5deef290d662c3643822bf69ec8259ce10b3ea61
38
38
 
39
- // download the screenshot and handle potential API errors
39
+ // download the screenshot and handle potential errors
40
40
  try {
41
41
  const imageBlob = await client.take(options);
42
42
 
@@ -49,6 +49,15 @@ try {
49
49
  // Error Code: error.errorCode
50
50
  // Error Message: error.errorMessage
51
51
  // Documentation URL: error.documentationUrl
52
+ } else if (error instanceof screenshotone.ConnectionError) {
53
+ // The connection to the API failed, for example with ECONNRESET.
54
+ // error.message explains what happened and what usually causes it.
55
+ // Code: error.code, for example "ECONNRESET"
56
+ // Phase: error.phase, "request" (before the API responded) or "response" (while downloading)
57
+ // Attempts: error.attempts
58
+ // Time from the last attempt's start to the failure: error.lastElapsedMs
59
+ // Time from the first attempt's start, retry waits included: error.totalElapsedMs
60
+ console.error(error.message);
52
61
  } else {
53
62
  // An unexpected error occurred
54
63
  console.error("An unexpected error occurred:", error.message);
@@ -56,6 +65,27 @@ try {
56
65
  }
57
66
  ```
58
67
 
68
+ ### Connection errors and retries
69
+
70
+ A request can fail on the network between your server and the API, for example with `ECONNRESET` when a proxy, NAT gateway or firewall closes the connection. The SDK then throws a `ConnectionError` that says:
71
+
72
+ - whether the connection broke before the API responded (`phase: "request"`) or while the result was downloading (`phase: "response"`, with `httpStatusCode`)
73
+ - how many attempts were made (`attempts`)
74
+ - how long after the last attempt started (`lastElapsedMs`), and how long after the first one started, waits between retries included (`totalElapsedMs`)
75
+ - what usually causes it
76
+
77
+ To retry connection resets automatically, set `maxRetries`. It's 0 by default, so the SDK doesn't retry unless you set it:
78
+
79
+ ```javascript
80
+ const client = new screenshotone.Client("<access key>", "<secret key>", {
81
+ maxRetries: 3,
82
+ });
83
+ ```
84
+
85
+ Retries apply only to `ECONNRESET` and wait with exponential backoff. A retry sends the request again. If the API had already finished the first one, the retry renders the screenshot again and counts toward your usage again, unless the result is served from the cache.
86
+
87
+ Many requests starting at once make connection resets more likely. If you take screenshots in large batches, limit how many requests run at the same time.
88
+
59
89
  ## Build and publish (a manual for SDK developers)
60
90
 
61
91
  To build and publish the SDK:
@@ -5,3 +5,40 @@ export default class APIError extends Error {
5
5
  readonly documentationUrl?: string;
6
6
  constructor(message: string, httpStatusCode?: number, errorCode?: string, errorMessage?: string, documentationUrl?: string);
7
7
  }
8
+ /**
9
+ * Where the connection failed: before the API responded ("request") or while
10
+ * the response was downloading ("response").
11
+ */
12
+ export declare type ConnectionErrorPhase = "request" | "response";
13
+ /**
14
+ * The connection to the API failed, for example with ECONNRESET. The message
15
+ * explains what happened and what usually causes it.
16
+ */
17
+ export declare class ConnectionError extends Error {
18
+ /** The system error code, for example "ECONNRESET". */
19
+ readonly code: string;
20
+ /** Whether the connection failed before the API responded or while the response was downloading. */
21
+ readonly phase: ConnectionErrorPhase;
22
+ /** Milliseconds from the start of the last attempt to the failure. */
23
+ readonly lastElapsedMs: number;
24
+ /**
25
+ * Milliseconds from the start of the first attempt to the failure, waits
26
+ * between retries included. Equals lastElapsedMs when there was one attempt.
27
+ */
28
+ readonly totalElapsedMs: number;
29
+ /** How many times the request was sent, retries included. */
30
+ readonly attempts: number;
31
+ /** The HTTP status of the response that was downloading, when the phase is "response". */
32
+ readonly httpStatusCode?: number;
33
+ /** The underlying error message. */
34
+ readonly reason?: string;
35
+ constructor(message: string, details: {
36
+ code: string;
37
+ phase: ConnectionErrorPhase;
38
+ lastElapsedMs: number;
39
+ totalElapsedMs: number;
40
+ attempts: number;
41
+ httpStatusCode?: number;
42
+ reason?: string;
43
+ });
44
+ }
@@ -1,5 +1,16 @@
1
- import APIError from "./errors";
2
- export { APIError };
1
+ import APIError, { ConnectionError, ConnectionErrorPhase } from "./errors";
2
+ export { APIError, ConnectionError };
3
+ export type { ConnectionErrorPhase };
4
+ export interface ClientOptions {
5
+ /** API base URL. Defaults to https://api.screenshotone.com. */
6
+ apiBaseUrl?: string;
7
+ /**
8
+ * Additional attempts for ECONNRESET errors, including response download
9
+ * failures. Defaults to 0 (disabled); set a positive value to enable retries.
10
+ * Retries use exponential backoff with jitter and may start another render.
11
+ */
12
+ maxRetries?: number;
13
+ }
3
14
  /**
4
15
  * Represents an API client for the ScreenshotOne.com API.
5
16
  */
@@ -7,7 +18,16 @@ export declare class Client {
7
18
  private readonly accessKey;
8
19
  private readonly secretKey;
9
20
  private readonly apiBaseUrl;
10
- constructor(accessKey: string, secretKey: string, apiBaseUrl?: string);
21
+ private readonly maxRetries;
22
+ /**
23
+ * @param options Client configuration. An API base URL string is also
24
+ * accepted for compatibility with existing constructor calls.
25
+ */
26
+ constructor(accessKey: string, secretKey: string, options?: ClientOptions | string);
27
+ private withConnectionResetRetries;
28
+ private send;
29
+ private read;
30
+ private connectionError;
11
31
  /**
12
32
  * Generates an URL that can be used to send GET requests for taking screenshots.
13
33
  *
package/dist/errors.js CHANGED
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConnectionError = void 0;
3
4
  class APIError extends Error {
4
5
  constructor(message, httpStatusCode, errorCode, errorMessage, documentationUrl) {
5
6
  super(message);
@@ -10,3 +11,21 @@ class APIError extends Error {
10
11
  }
11
12
  }
12
13
  exports.default = APIError;
14
+ /**
15
+ * The connection to the API failed, for example with ECONNRESET. The message
16
+ * explains what happened and what usually causes it.
17
+ */
18
+ class ConnectionError extends Error {
19
+ constructor(message, details) {
20
+ super(message);
21
+ this.name = "ConnectionError";
22
+ this.code = details.code;
23
+ this.phase = details.phase;
24
+ this.lastElapsedMs = details.lastElapsedMs;
25
+ this.totalElapsedMs = details.totalElapsedMs;
26
+ this.attempts = details.attempts;
27
+ this.httpStatusCode = details.httpStatusCode;
28
+ this.reason = details.reason;
29
+ }
30
+ }
31
+ exports.ConnectionError = ConnectionError;
package/dist/main.js CHANGED
@@ -1,28 +1,225 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
27
  };
5
28
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AnimateOptions = exports.TakeOptions = exports.Client = exports.APIError = void 0;
29
+ exports.AnimateOptions = exports.TakeOptions = exports.Client = exports.ConnectionError = exports.APIError = void 0;
7
30
  const big_js_1 = __importDefault(require("big.js"));
8
31
  const cross_fetch_1 = __importDefault(require("cross-fetch"));
9
32
  const signature_1 = require("./signature");
10
- const errors_1 = __importDefault(require("./errors"));
33
+ const errors_1 = __importStar(require("./errors"));
11
34
  exports.APIError = errors_1.default;
35
+ Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_1.ConnectionError; } });
12
36
  const API_BASE_URL = "https://api.screenshotone.com";
13
37
  const API_TAKE_PATH = "/take";
14
38
  const API_ANIMATE_PATH = "/animate";
39
+ // the only error code the client retries
40
+ const RETRYABLE_CODE = "ECONNRESET";
41
+ function isConnectionReset(error) {
42
+ return (typeof error === "object" &&
43
+ error !== null &&
44
+ error.code === RETRYABLE_CODE);
45
+ }
46
+ const CONNECTION_FAILURES = {
47
+ ECONNRESET: "the connection was reset",
48
+ EPIPE: "the connection was closed while the request was being sent",
49
+ ERR_STREAM_PREMATURE_CLOSE: "the connection closed before the whole response arrived",
50
+ ECONNREFUSED: "the connection was refused",
51
+ ETIMEDOUT: "the connection timed out",
52
+ EHOSTUNREACH: "the API host is unreachable",
53
+ ENETUNREACH: "the network is unreachable",
54
+ ENOTFOUND: "the API host name couldn't be resolved",
55
+ EAI_AGAIN: "the API host name couldn't be resolved",
56
+ };
57
+ // an open connection that broke, rather than one that couldn't be opened
58
+ const DROPPED_CONNECTION_CODES = [
59
+ "ECONNRESET",
60
+ "EPIPE",
61
+ "ERR_STREAM_PREMATURE_CLOSE",
62
+ ];
63
+ // The code of a network failure, or undefined for any other error. node-fetch,
64
+ // which cross-fetch uses in Node, rejects with a FetchError of type "system";
65
+ // fetch built on undici rejects with a TypeError caused by the system error.
66
+ function networkFailureCode(error) {
67
+ if (typeof error !== "object" || error === null) {
68
+ return undefined;
69
+ }
70
+ const { type, code, cause } = error;
71
+ if (type === "system" && typeof code === "string") {
72
+ return code;
73
+ }
74
+ if (error instanceof TypeError && typeof cause === "object" && cause) {
75
+ const causeCode = cause.code;
76
+ if (typeof causeCode === "string") {
77
+ return causeCode;
78
+ }
79
+ }
80
+ return undefined;
81
+ }
82
+ // the request URL without its query and fragment, which hold the access key
83
+ // and the signature, whatever the URL's form
84
+ function withoutQuery(url) {
85
+ return url.split(/[?#]/, 1)[0];
86
+ }
87
+ // The text without the request's query: exactly as sent, in any URL the text
88
+ // mentions (whatever its scheme spelling, or none), and any credential left.
89
+ function redact(text, url) {
90
+ const query = url.slice(withoutQuery(url).length);
91
+ return (query ? text.split(query).join("") : text)
92
+ .replace(/((?:[a-z][a-z0-9+.-]*:)?\/\/[^\s?#]+)[?#]\S*?(?=:?(?:\s|$))/gi, "$1")
93
+ .replace(/\b(access_key|signature)=[^&\s]+/gi, "$1=[redacted]");
94
+ }
95
+ function formatDuration(ms) {
96
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
97
+ }
98
+ function reasonOf(error, url) {
99
+ if (!(error instanceof Error)) {
100
+ return undefined;
101
+ }
102
+ const cause = error.cause;
103
+ const message = error instanceof TypeError && cause instanceof Error
104
+ ? cause.message
105
+ : error.message;
106
+ return redact(message, url);
107
+ }
15
108
  /**
16
109
  * Represents an API client for the ScreenshotOne.com API.
17
110
  */
18
111
  class Client {
19
- constructor(accessKey, secretKey, apiBaseUrl) {
112
+ /**
113
+ * @param options Client configuration. An API base URL string is also
114
+ * accepted for compatibility with existing constructor calls.
115
+ */
116
+ constructor(accessKey, secretKey, options = {}) {
20
117
  if (!accessKey || !secretKey) {
21
118
  throw new Error("Both non-empty access and secret keys are required");
22
119
  }
120
+ const { apiBaseUrl, maxRetries = 0 } = typeof options === "string" ? { apiBaseUrl: options } : options;
121
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) {
122
+ throw new RangeError("maxRetries must be a non-negative safe integer");
123
+ }
23
124
  this.accessKey = accessKey;
24
125
  this.secretKey = secretKey;
25
126
  this.apiBaseUrl = apiBaseUrl ? apiBaseUrl : API_BASE_URL;
127
+ this.maxRetries = maxRetries;
128
+ }
129
+ async withConnectionResetRetries(operation) {
130
+ const attempts = { current: 0 };
131
+ for (let retry = 0;; retry++) {
132
+ attempts.current = retry + 1;
133
+ try {
134
+ return await operation(attempts);
135
+ }
136
+ catch (error) {
137
+ if (!isConnectionReset(error) || retry >= this.maxRetries) {
138
+ throw error;
139
+ }
140
+ const delay = Math.min(1000 * 2 ** retry, 30000) + Math.random() * 250;
141
+ await new Promise((resolve) => setTimeout(resolve, delay));
142
+ }
143
+ }
144
+ }
145
+ // Sends the request. A network failure becomes a ConnectionError.
146
+ async send(url, attempts) {
147
+ const startedAt = Date.now();
148
+ attempts.firstStartedAt ??= startedAt;
149
+ const request = {
150
+ url,
151
+ attempt: attempts.current,
152
+ startedAt,
153
+ firstStartedAt: attempts.firstStartedAt,
154
+ };
155
+ try {
156
+ return { ...request, response: await (0, cross_fetch_1.default)(url) };
157
+ }
158
+ catch (error) {
159
+ throw this.connectionError(error, request, "request") ?? error;
160
+ }
161
+ }
162
+ // Reads the response body. A network failure becomes a ConnectionError.
163
+ async read(request, body) {
164
+ try {
165
+ return await body(request.response);
166
+ }
167
+ catch (error) {
168
+ throw (this.connectionError(error, request, "response", request.response.status) ?? error);
169
+ }
170
+ }
171
+ // A ConnectionError that explains a network failure, or undefined for any
172
+ // other error
173
+ connectionError(error, request, phase, httpStatusCode) {
174
+ const code = networkFailureCode(error);
175
+ if (!code) {
176
+ return undefined;
177
+ }
178
+ const now = Date.now();
179
+ const lastElapsedMs = now - request.startedAt;
180
+ const totalElapsedMs = now - request.firstStartedAt;
181
+ const endpoint = withoutQuery(request.url);
182
+ const when = request.attempt > 1
183
+ ? `${formatDuration(lastElapsedMs)} after the last of ${request.attempt} attempts to ${endpoint} started, ${formatDuration(totalElapsedMs)} after the first`
184
+ : `${formatDuration(lastElapsedMs)} after the request to ${endpoint} started`;
185
+ const failure = `${CONNECTION_FAILURES[code] ?? "the connection failed"} (${code}) ${when}`;
186
+ const dropped = DROPPED_CONNECTION_CODES.includes(code);
187
+ const sentences = phase === "request"
188
+ ? [
189
+ `The connection to the ScreenshotOne API failed before a response arrived: ${failure}.`,
190
+ ]
191
+ : [
192
+ `The connection to the ScreenshotOne API failed while downloading the response (HTTP ${httpStatusCode}): ${failure}.`,
193
+ httpStatusCode !== undefined && httpStatusCode < 400
194
+ ? "The API had already finished the request. Unless the result came from the cache, it counts toward your usage."
195
+ : "The API had responded with an error, but its details couldn't be read.",
196
+ ];
197
+ if (dropped) {
198
+ if (phase === "request") {
199
+ sentences.push("The API might not have received the request, or the connection broke while the API was working on it.");
200
+ }
201
+ sentences.push("This usually happens on the network between your server and the API: a proxy, NAT gateway or firewall closed the connection, or an idle kept-alive connection was reused after the network had closed it. It's more likely when many requests start at once.");
202
+ sentences.push(request.attempt > 1
203
+ ? `It failed on all ${request.attempt} attempts. Limit how many requests run at once.`
204
+ : code === RETRYABLE_CODE && this.maxRetries === 0
205
+ ? "Limit how many requests run at once, or set the maxRetries client option to retry automatically."
206
+ : "Limit how many requests run at once.");
207
+ }
208
+ else if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
209
+ sentences.push("Check your server's DNS settings.");
210
+ }
211
+ else {
212
+ sentences.push("Check that your server can reach the API, including firewall and proxy settings.");
213
+ }
214
+ return new errors_1.ConnectionError(sentences.join(" "), {
215
+ code,
216
+ phase,
217
+ lastElapsedMs,
218
+ totalElapsedMs,
219
+ attempts: request.attempt,
220
+ httpStatusCode,
221
+ reason: reasonOf(error, request.url),
222
+ });
26
223
  }
27
224
  /**
28
225
  * Generates an URL that can be used to send GET requests for taking screenshots.
@@ -76,20 +273,23 @@ class Client {
76
273
  */
77
274
  async take(options) {
78
275
  const url = await this.generateSignedTakeURL(options);
79
- const response = await (0, cross_fetch_1.default)(url);
80
- if (response.ok) {
81
- return await response.blob();
82
- }
83
- try {
84
- const data = await response.json();
85
- throw new errors_1.default(`Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
86
- }
87
- catch (e) {
88
- if (e instanceof errors_1.default) {
89
- throw e;
276
+ return this.withConnectionResetRetries(async (attempts) => {
277
+ const request = await this.send(url, attempts);
278
+ const response = request.response;
279
+ if (response.ok) {
280
+ return await this.read(request, (r) => r.blob());
90
281
  }
91
- throw new Error(`failed to take screenshot, response returned ${response.status} ${response.statusText}`);
92
- }
282
+ try {
283
+ const data = await this.read(request, (r) => r.json());
284
+ throw new errors_1.default(`Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
285
+ }
286
+ catch (e) {
287
+ if (e instanceof errors_1.default || e instanceof errors_1.ConnectionError) {
288
+ throw e;
289
+ }
290
+ throw new Error(`failed to take screenshot, response returned ${response.status} ${response.statusText}`);
291
+ }
292
+ });
93
293
  }
94
294
  /**
95
295
  * Generates an animated screenshot and return the image blob.
@@ -99,20 +299,23 @@ class Client {
99
299
  */
100
300
  async animate(options) {
101
301
  const url = await this.generateSignedAnimateURL(options);
102
- const response = await (0, cross_fetch_1.default)(url);
103
- if (response.ok) {
104
- return await response.blob();
105
- }
106
- try {
107
- const data = await response.json();
108
- throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
109
- }
110
- catch (e) {
111
- if (e instanceof errors_1.default) {
112
- throw e;
302
+ return this.withConnectionResetRetries(async (attempts) => {
303
+ const request = await this.send(url, attempts);
304
+ const response = request.response;
305
+ if (response.ok) {
306
+ return await this.read(request, (r) => r.blob());
113
307
  }
114
- throw new Error(`Failed to generate animation, response returned ${response.status} (${response.statusText})`);
115
- }
308
+ try {
309
+ const data = await this.read(request, (r) => r.json());
310
+ throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
311
+ }
312
+ catch (e) {
313
+ if (e instanceof errors_1.default || e instanceof errors_1.ConnectionError) {
314
+ throw e;
315
+ }
316
+ throw new Error(`Failed to generate animation, response returned ${response.status} (${response.statusText})`);
317
+ }
318
+ });
116
319
  }
117
320
  /**
118
321
  * Generates an animated screenshot and return the image blob.
@@ -140,15 +343,18 @@ class Client {
140
343
  const url = options instanceof TakeOptions
141
344
  ? await this.generateSignedTakeURL(options)
142
345
  : await this.generateSignedAnimateURL(options);
143
- const response = await (0, cross_fetch_1.default)(url);
144
- if (response.ok) {
145
- return {
146
- key: response.headers.get("X-ScreenshotOne-Store-Key"),
147
- bucket: response.headers.get("X-ScreenshotOne-Store-Bucket"),
148
- };
149
- }
150
- const data = await response.json();
151
- throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
346
+ return this.withConnectionResetRetries(async (attempts) => {
347
+ const request = await this.send(url, attempts);
348
+ const response = request.response;
349
+ if (response.ok) {
350
+ return {
351
+ key: response.headers.get("X-ScreenshotOne-Store-Key"),
352
+ bucket: response.headers.get("X-ScreenshotOne-Store-Bucket"),
353
+ };
354
+ }
355
+ const data = await this.read(request, (r) => r.json());
356
+ throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
357
+ });
152
358
  }
153
359
  }
154
360
  exports.Client = Client;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "screenshotone-api-sdk",
3
3
  "homepage": "https://screenshotone.com",
4
- "version": "1.1.23",
4
+ "version": "1.1.25",
5
5
  "description": "Use ScreenshotOne.com API to generate screenshots of any website.",
6
6
  "repository": {
7
7
  "type": "git",
package/src/errors.ts CHANGED
@@ -13,4 +13,58 @@ export default class APIError extends Error {
13
13
  this.errorMessage = errorMessage;
14
14
  this.documentationUrl = documentationUrl;
15
15
  }
16
+ }
17
+
18
+ /**
19
+ * Where the connection failed: before the API responded ("request") or while
20
+ * the response was downloading ("response").
21
+ */
22
+ export type ConnectionErrorPhase = "request" | "response";
23
+
24
+ /**
25
+ * The connection to the API failed, for example with ECONNRESET. The message
26
+ * explains what happened and what usually causes it.
27
+ */
28
+ export class ConnectionError extends Error {
29
+ /** The system error code, for example "ECONNRESET". */
30
+ public readonly code: string;
31
+ /** Whether the connection failed before the API responded or while the response was downloading. */
32
+ public readonly phase: ConnectionErrorPhase;
33
+ /** Milliseconds from the start of the last attempt to the failure. */
34
+ public readonly lastElapsedMs: number;
35
+ /**
36
+ * Milliseconds from the start of the first attempt to the failure, waits
37
+ * between retries included. Equals lastElapsedMs when there was one attempt.
38
+ */
39
+ public readonly totalElapsedMs: number;
40
+ /** How many times the request was sent, retries included. */
41
+ public readonly attempts: number;
42
+ /** The HTTP status of the response that was downloading, when the phase is "response". */
43
+ public readonly httpStatusCode?: number;
44
+ /** The underlying error message. */
45
+ public readonly reason?: string;
46
+
47
+ constructor(
48
+ message: string,
49
+ details: {
50
+ code: string;
51
+ phase: ConnectionErrorPhase;
52
+ lastElapsedMs: number;
53
+ totalElapsedMs: number;
54
+ attempts: number;
55
+ httpStatusCode?: number;
56
+ reason?: string;
57
+ }
58
+ ) {
59
+ super(message);
60
+
61
+ this.name = "ConnectionError";
62
+ this.code = details.code;
63
+ this.phase = details.phase;
64
+ this.lastElapsedMs = details.lastElapsedMs;
65
+ this.totalElapsedMs = details.totalElapsedMs;
66
+ this.attempts = details.attempts;
67
+ this.httpStatusCode = details.httpStatusCode;
68
+ this.reason = details.reason;
69
+ }
16
70
  }
package/src/main.ts CHANGED
@@ -1,13 +1,136 @@
1
1
  import Big from "big.js";
2
2
  import fetch from "cross-fetch";
3
3
  import { signQueryString } from "./signature";
4
- import APIError from "./errors";
4
+ import APIError, { ConnectionError, ConnectionErrorPhase } from "./errors";
5
5
 
6
6
  const API_BASE_URL = "https://api.screenshotone.com";
7
7
  const API_TAKE_PATH = "/take";
8
8
  const API_ANIMATE_PATH = "/animate";
9
9
 
10
- export { APIError };
10
+ export { APIError, ConnectionError };
11
+ export type { ConnectionErrorPhase };
12
+
13
+ export interface ClientOptions {
14
+ /** API base URL. Defaults to https://api.screenshotone.com. */
15
+ apiBaseUrl?: string;
16
+ /**
17
+ * Additional attempts for ECONNRESET errors, including response download
18
+ * failures. Defaults to 0 (disabled); set a positive value to enable retries.
19
+ * Retries use exponential backoff with jitter and may start another render.
20
+ */
21
+ maxRetries?: number;
22
+ }
23
+
24
+ // the only error code the client retries
25
+ const RETRYABLE_CODE = "ECONNRESET";
26
+
27
+ function isConnectionReset(error: unknown): boolean {
28
+ return (
29
+ typeof error === "object" &&
30
+ error !== null &&
31
+ (error as { code?: unknown }).code === RETRYABLE_CODE
32
+ );
33
+ }
34
+
35
+ type FetchResponse = Awaited<ReturnType<typeof fetch>>;
36
+
37
+ // one call's attempts: the current one, and when the first one started
38
+ interface Attempts {
39
+ current: number;
40
+ firstStartedAt?: number;
41
+ }
42
+
43
+ // what a ConnectionError reports about the request that failed
44
+ interface SentRequest {
45
+ url: string;
46
+ attempt: number;
47
+ startedAt: number;
48
+ firstStartedAt: number;
49
+ }
50
+
51
+ const CONNECTION_FAILURES: Record<string, string> = {
52
+ ECONNRESET: "the connection was reset",
53
+ EPIPE: "the connection was closed while the request was being sent",
54
+ ERR_STREAM_PREMATURE_CLOSE:
55
+ "the connection closed before the whole response arrived",
56
+ ECONNREFUSED: "the connection was refused",
57
+ ETIMEDOUT: "the connection timed out",
58
+ EHOSTUNREACH: "the API host is unreachable",
59
+ ENETUNREACH: "the network is unreachable",
60
+ ENOTFOUND: "the API host name couldn't be resolved",
61
+ EAI_AGAIN: "the API host name couldn't be resolved",
62
+ };
63
+
64
+ // an open connection that broke, rather than one that couldn't be opened
65
+ const DROPPED_CONNECTION_CODES = [
66
+ "ECONNRESET",
67
+ "EPIPE",
68
+ "ERR_STREAM_PREMATURE_CLOSE",
69
+ ];
70
+
71
+ // The code of a network failure, or undefined for any other error. node-fetch,
72
+ // which cross-fetch uses in Node, rejects with a FetchError of type "system";
73
+ // fetch built on undici rejects with a TypeError caused by the system error.
74
+ function networkFailureCode(error: unknown): string | undefined {
75
+ if (typeof error !== "object" || error === null) {
76
+ return undefined;
77
+ }
78
+
79
+ const { type, code, cause } = error as {
80
+ type?: unknown;
81
+ code?: unknown;
82
+ cause?: unknown;
83
+ };
84
+ if (type === "system" && typeof code === "string") {
85
+ return code;
86
+ }
87
+
88
+ if (error instanceof TypeError && typeof cause === "object" && cause) {
89
+ const causeCode = (cause as { code?: unknown }).code;
90
+ if (typeof causeCode === "string") {
91
+ return causeCode;
92
+ }
93
+ }
94
+
95
+ return undefined;
96
+ }
97
+
98
+ // the request URL without its query and fragment, which hold the access key
99
+ // and the signature, whatever the URL's form
100
+ function withoutQuery(url: string): string {
101
+ return url.split(/[?#]/, 1)[0];
102
+ }
103
+
104
+ // The text without the request's query: exactly as sent, in any URL the text
105
+ // mentions (whatever its scheme spelling, or none), and any credential left.
106
+ function redact(text: string, url: string): string {
107
+ const query = url.slice(withoutQuery(url).length);
108
+
109
+ return (query ? text.split(query).join("") : text)
110
+ .replace(
111
+ /((?:[a-z][a-z0-9+.-]*:)?\/\/[^\s?#]+)[?#]\S*?(?=:?(?:\s|$))/gi,
112
+ "$1"
113
+ )
114
+ .replace(/\b(access_key|signature)=[^&\s]+/gi, "$1=[redacted]");
115
+ }
116
+
117
+ function formatDuration(ms: number): string {
118
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
119
+ }
120
+
121
+ function reasonOf(error: unknown, url: string): string | undefined {
122
+ if (!(error instanceof Error)) {
123
+ return undefined;
124
+ }
125
+
126
+ const cause = (error as { cause?: unknown }).cause;
127
+ const message =
128
+ error instanceof TypeError && cause instanceof Error
129
+ ? cause.message
130
+ : error.message;
131
+
132
+ return redact(message, url);
133
+ }
11
134
 
12
135
  /**
13
136
  * Represents an API client for the ScreenshotOne.com API.
@@ -16,17 +139,166 @@ export class Client {
16
139
  private readonly accessKey: string;
17
140
  private readonly secretKey: string;
18
141
  private readonly apiBaseUrl: string;
142
+ private readonly maxRetries: number;
19
143
 
20
- constructor(accessKey: string, secretKey: string, apiBaseUrl?: string) {
144
+ /**
145
+ * @param options Client configuration. An API base URL string is also
146
+ * accepted for compatibility with existing constructor calls.
147
+ */
148
+ constructor(
149
+ accessKey: string,
150
+ secretKey: string,
151
+ options: ClientOptions | string = {}
152
+ ) {
21
153
  if (!accessKey || !secretKey) {
22
154
  throw new Error(
23
155
  "Both non-empty access and secret keys are required"
24
156
  );
25
157
  }
26
158
 
159
+ const { apiBaseUrl, maxRetries = 0 } =
160
+ typeof options === "string" ? { apiBaseUrl: options } : options;
161
+
162
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) {
163
+ throw new RangeError("maxRetries must be a non-negative safe integer");
164
+ }
165
+
27
166
  this.accessKey = accessKey;
28
167
  this.secretKey = secretKey;
29
168
  this.apiBaseUrl = apiBaseUrl ? apiBaseUrl : API_BASE_URL;
169
+ this.maxRetries = maxRetries;
170
+ }
171
+
172
+ private async withConnectionResetRetries<T>(
173
+ operation: (attempts: Attempts) => Promise<T>
174
+ ): Promise<T> {
175
+ const attempts: Attempts = { current: 0 };
176
+ for (let retry = 0; ; retry++) {
177
+ attempts.current = retry + 1;
178
+ try {
179
+ return await operation(attempts);
180
+ } catch (error) {
181
+ if (!isConnectionReset(error) || retry >= this.maxRetries) {
182
+ throw error;
183
+ }
184
+
185
+ const delay =
186
+ Math.min(1000 * 2 ** retry, 30000) + Math.random() * 250;
187
+ await new Promise((resolve) => setTimeout(resolve, delay));
188
+ }
189
+ }
190
+ }
191
+
192
+ // Sends the request. A network failure becomes a ConnectionError.
193
+ private async send(
194
+ url: string,
195
+ attempts: Attempts
196
+ ): Promise<SentRequest & { response: FetchResponse }> {
197
+ const startedAt = Date.now();
198
+ attempts.firstStartedAt ??= startedAt;
199
+ const request = {
200
+ url,
201
+ attempt: attempts.current,
202
+ startedAt,
203
+ firstStartedAt: attempts.firstStartedAt,
204
+ };
205
+ try {
206
+ return { ...request, response: await fetch(url) };
207
+ } catch (error) {
208
+ throw this.connectionError(error, request, "request") ?? error;
209
+ }
210
+ }
211
+
212
+ // Reads the response body. A network failure becomes a ConnectionError.
213
+ private async read<T>(
214
+ request: SentRequest & { response: FetchResponse },
215
+ body: (response: FetchResponse) => Promise<T>
216
+ ): Promise<T> {
217
+ try {
218
+ return await body(request.response);
219
+ } catch (error) {
220
+ throw (
221
+ this.connectionError(
222
+ error,
223
+ request,
224
+ "response",
225
+ request.response.status
226
+ ) ?? error
227
+ );
228
+ }
229
+ }
230
+
231
+ // A ConnectionError that explains a network failure, or undefined for any
232
+ // other error
233
+ private connectionError(
234
+ error: unknown,
235
+ request: SentRequest,
236
+ phase: ConnectionErrorPhase,
237
+ httpStatusCode?: number
238
+ ): ConnectionError | undefined {
239
+ const code = networkFailureCode(error);
240
+ if (!code) {
241
+ return undefined;
242
+ }
243
+
244
+ const now = Date.now();
245
+ const lastElapsedMs = now - request.startedAt;
246
+ const totalElapsedMs = now - request.firstStartedAt;
247
+ const endpoint = withoutQuery(request.url);
248
+ const when =
249
+ request.attempt > 1
250
+ ? `${formatDuration(lastElapsedMs)} after the last of ${request.attempt} attempts to ${endpoint} started, ${formatDuration(totalElapsedMs)} after the first`
251
+ : `${formatDuration(lastElapsedMs)} after the request to ${endpoint} started`;
252
+ const failure = `${
253
+ CONNECTION_FAILURES[code] ?? "the connection failed"
254
+ } (${code}) ${when}`;
255
+ const dropped = DROPPED_CONNECTION_CODES.includes(code);
256
+
257
+ const sentences =
258
+ phase === "request"
259
+ ? [
260
+ `The connection to the ScreenshotOne API failed before a response arrived: ${failure}.`,
261
+ ]
262
+ : [
263
+ `The connection to the ScreenshotOne API failed while downloading the response (HTTP ${httpStatusCode}): ${failure}.`,
264
+ httpStatusCode !== undefined && httpStatusCode < 400
265
+ ? "The API had already finished the request. Unless the result came from the cache, it counts toward your usage."
266
+ : "The API had responded with an error, but its details couldn't be read.",
267
+ ];
268
+
269
+ if (dropped) {
270
+ if (phase === "request") {
271
+ sentences.push(
272
+ "The API might not have received the request, or the connection broke while the API was working on it."
273
+ );
274
+ }
275
+ sentences.push(
276
+ "This usually happens on the network between your server and the API: a proxy, NAT gateway or firewall closed the connection, or an idle kept-alive connection was reused after the network had closed it. It's more likely when many requests start at once."
277
+ );
278
+ sentences.push(
279
+ request.attempt > 1
280
+ ? `It failed on all ${request.attempt} attempts. Limit how many requests run at once.`
281
+ : code === RETRYABLE_CODE && this.maxRetries === 0
282
+ ? "Limit how many requests run at once, or set the maxRetries client option to retry automatically."
283
+ : "Limit how many requests run at once."
284
+ );
285
+ } else if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
286
+ sentences.push("Check your server's DNS settings.");
287
+ } else {
288
+ sentences.push(
289
+ "Check that your server can reach the API, including firewall and proxy settings."
290
+ );
291
+ }
292
+
293
+ return new ConnectionError(sentences.join(" "), {
294
+ code,
295
+ phase,
296
+ lastElapsedMs,
297
+ totalElapsedMs,
298
+ attempts: request.attempt,
299
+ httpStatusCode,
300
+ reason: reasonOf(error, request.url),
301
+ });
30
302
  }
31
303
 
32
304
  /**
@@ -89,30 +361,33 @@ export class Client {
89
361
  */
90
362
  async take(options: TakeOptions): Promise<Blob> {
91
363
  const url = await this.generateSignedTakeURL(options);
92
- const response = await fetch(url);
93
- if (response.ok) {
94
- return await response.blob();
95
- }
96
-
97
- try {
98
- const data = await response.json();
99
-
100
- throw new APIError(
101
- `Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
102
- response.status,
103
- data?.error_code,
104
- data?.error_message,
105
- data?.documentation_url
106
- );
107
- } catch (e) {
108
- if (e instanceof APIError) {
109
- throw e;
364
+ return this.withConnectionResetRetries(async (attempts) => {
365
+ const request = await this.send(url, attempts);
366
+ const response = request.response;
367
+ if (response.ok) {
368
+ return await this.read(request, (r) => r.blob());
110
369
  }
111
370
 
112
- throw new Error(
113
- `failed to take screenshot, response returned ${response.status} ${response.statusText}`
114
- );
115
- }
371
+ try {
372
+ const data = await this.read(request, (r) => r.json());
373
+
374
+ throw new APIError(
375
+ `Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
376
+ response.status,
377
+ data?.error_code,
378
+ data?.error_message,
379
+ data?.documentation_url
380
+ );
381
+ } catch (e) {
382
+ if (e instanceof APIError || e instanceof ConnectionError) {
383
+ throw e;
384
+ }
385
+
386
+ throw new Error(
387
+ `failed to take screenshot, response returned ${response.status} ${response.statusText}`
388
+ );
389
+ }
390
+ });
116
391
  }
117
392
 
118
393
  /**
@@ -123,30 +398,33 @@ export class Client {
123
398
  */
124
399
  async animate(options: AnimateOptions): Promise<Blob> {
125
400
  const url = await this.generateSignedAnimateURL(options);
126
- const response = await fetch(url);
127
- if (response.ok) {
128
- return await response.blob();
129
- }
130
-
131
- try {
132
- const data = await response.json();
133
-
134
- throw new APIError(
135
- `Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
136
- response.status,
137
- data?.error_code,
138
- data?.error_message,
139
- data?.documentation_url
140
- );
141
- } catch (e) {
142
- if (e instanceof APIError) {
143
- throw e;
401
+ return this.withConnectionResetRetries(async (attempts) => {
402
+ const request = await this.send(url, attempts);
403
+ const response = request.response;
404
+ if (response.ok) {
405
+ return await this.read(request, (r) => r.blob());
144
406
  }
145
407
 
146
- throw new Error(
147
- `Failed to generate animation, response returned ${response.status} (${response.statusText})`
148
- );
149
- }
408
+ try {
409
+ const data = await this.read(request, (r) => r.json());
410
+
411
+ throw new APIError(
412
+ `Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
413
+ response.status,
414
+ data?.error_code,
415
+ data?.error_message,
416
+ data?.documentation_url
417
+ );
418
+ } catch (e) {
419
+ if (e instanceof APIError || e instanceof ConnectionError) {
420
+ throw e;
421
+ }
422
+
423
+ throw new Error(
424
+ `Failed to generate animation, response returned ${response.status} (${response.statusText})`
425
+ );
426
+ }
427
+ });
150
428
  }
151
429
 
152
430
  /**
@@ -187,23 +465,26 @@ export class Client {
187
465
  ? await this.generateSignedTakeURL(options)
188
466
  : await this.generateSignedAnimateURL(options);
189
467
 
190
- const response = await fetch(url);
191
- if (response.ok) {
192
- return {
193
- key: response.headers.get("X-ScreenshotOne-Store-Key"),
194
- bucket: response.headers.get("X-ScreenshotOne-Store-Bucket"),
195
- };
196
- }
468
+ return this.withConnectionResetRetries(async (attempts) => {
469
+ const request = await this.send(url, attempts);
470
+ const response = request.response;
471
+ if (response.ok) {
472
+ return {
473
+ key: response.headers.get("X-ScreenshotOne-Store-Key"),
474
+ bucket: response.headers.get("X-ScreenshotOne-Store-Bucket"),
475
+ };
476
+ }
197
477
 
198
- const data = await response.json();
478
+ const data = await this.read(request, (r) => r.json());
199
479
 
200
- throw new APIError(
201
- `Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
202
- response.status,
203
- data?.error_code,
204
- data?.error_message,
205
- data?.documentation_url
206
- );
480
+ throw new APIError(
481
+ `Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
482
+ response.status,
483
+ data?.error_code,
484
+ data?.error_message,
485
+ data?.documentation_url
486
+ );
487
+ });
207
488
  }
208
489
  }
209
490