@argos-ci/api-client 0.10.0 → 0.11.1

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/index.d.ts CHANGED
@@ -631,11 +631,6 @@ declare class APIError extends Error {
631
631
  /**
632
632
  * Handle API errors.
633
633
  */
634
- declare function throwAPIError(error: {
635
- error: string;
636
- details?: {
637
- message: string;
638
- }[];
639
- }): never;
634
+ declare function throwAPIError(error: components["schemas"]["Error"]): never;
640
635
 
641
636
  export { APIError, type ArgosAPIClient, schema as ArgosAPISchema, createClient, throwAPIError };
package/dist/index.js CHANGED
@@ -1,6 +1,181 @@
1
1
  // src/index.ts
2
2
  import createFetchClient from "openapi-fetch";
3
3
 
4
+ // ../../node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js
5
+ var objectToString = Object.prototype.toString;
6
+ var isError = (value) => objectToString.call(value) === "[object Error]";
7
+ var errorMessages = /* @__PURE__ */ new Set([
8
+ "network error",
9
+ // Chrome
10
+ "Failed to fetch",
11
+ // Chrome
12
+ "NetworkError when attempting to fetch resource.",
13
+ // Firefox
14
+ "The Internet connection appears to be offline.",
15
+ // Safari 16
16
+ "Network request failed",
17
+ // `cross-fetch`
18
+ "fetch failed",
19
+ // Undici (Node.js)
20
+ "terminated",
21
+ // Undici (Node.js)
22
+ " A network error occurred.",
23
+ // Bun (WebKit)
24
+ "Network connection lost"
25
+ // Cloudflare Workers (fetch)
26
+ ]);
27
+ function isNetworkError(error) {
28
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
29
+ if (!isValid) {
30
+ return false;
31
+ }
32
+ const { message, stack } = error;
33
+ if (message === "Load failed") {
34
+ return stack === void 0 || "__sentry_captured__" in error;
35
+ }
36
+ if (message.startsWith("error sending request for url")) {
37
+ return true;
38
+ }
39
+ return errorMessages.has(message);
40
+ }
41
+
42
+ // ../../node_modules/.pnpm/p-retry@7.0.0/node_modules/p-retry/index.js
43
+ function validateRetries(retries) {
44
+ if (typeof retries === "number") {
45
+ if (retries < 0) {
46
+ throw new TypeError("Expected `retries` to be a non-negative number.");
47
+ }
48
+ if (Number.isNaN(retries)) {
49
+ throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
50
+ }
51
+ } else if (retries !== void 0) {
52
+ throw new TypeError("Expected `retries` to be a number or Infinity.");
53
+ }
54
+ }
55
+ function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
56
+ if (value === void 0) {
57
+ return;
58
+ }
59
+ if (typeof value !== "number" || Number.isNaN(value)) {
60
+ throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
61
+ }
62
+ if (!allowInfinity && !Number.isFinite(value)) {
63
+ throw new TypeError(`Expected \`${name}\` to be a finite number.`);
64
+ }
65
+ if (value < min) {
66
+ throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`);
67
+ }
68
+ }
69
+ var AbortError = class extends Error {
70
+ constructor(message) {
71
+ super();
72
+ if (message instanceof Error) {
73
+ this.originalError = message;
74
+ ({ message } = message);
75
+ } else {
76
+ this.originalError = new Error(message);
77
+ this.originalError.stack = this.stack;
78
+ }
79
+ this.name = "AbortError";
80
+ this.message = message;
81
+ }
82
+ };
83
+ var createRetryContext = (error, attemptNumber, options) => {
84
+ const retriesLeft = options.retries - (attemptNumber - 1);
85
+ return Object.freeze({
86
+ error,
87
+ attemptNumber,
88
+ retriesLeft
89
+ });
90
+ };
91
+ function calculateDelay(attempt, options) {
92
+ const random = options.randomize ? Math.random() + 1 : 1;
93
+ let timeout = Math.round(random * Math.max(options.minTimeout, 1) * options.factor ** (attempt - 1));
94
+ timeout = Math.min(timeout, options.maxTimeout);
95
+ return timeout;
96
+ }
97
+ async function onAttemptFailure(error, attemptNumber, options, startTime, maxRetryTime) {
98
+ let normalizedError = error;
99
+ if (!(normalizedError instanceof Error)) {
100
+ normalizedError = new TypeError(`Non-error was thrown: "${normalizedError}". You should only throw errors.`);
101
+ }
102
+ if (normalizedError instanceof AbortError) {
103
+ throw normalizedError.originalError;
104
+ }
105
+ if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {
106
+ throw normalizedError;
107
+ }
108
+ const context = createRetryContext(normalizedError, attemptNumber, options);
109
+ await options.onFailedAttempt(context);
110
+ const currentTime = Date.now();
111
+ if (currentTime - startTime >= maxRetryTime || attemptNumber >= options.retries + 1 || !await options.shouldRetry(context)) {
112
+ throw normalizedError;
113
+ }
114
+ const delayTime = calculateDelay(attemptNumber, options);
115
+ const timeLeft = maxRetryTime - (currentTime - startTime);
116
+ if (timeLeft <= 0) {
117
+ throw normalizedError;
118
+ }
119
+ const finalDelay = Math.min(delayTime, timeLeft);
120
+ if (finalDelay > 0) {
121
+ await new Promise((resolve, reject) => {
122
+ const onAbort = () => {
123
+ clearTimeout(timeoutToken);
124
+ options.signal?.removeEventListener("abort", onAbort);
125
+ reject(options.signal.reason);
126
+ };
127
+ const timeoutToken = setTimeout(() => {
128
+ options.signal?.removeEventListener("abort", onAbort);
129
+ resolve();
130
+ }, finalDelay);
131
+ if (options.unref) {
132
+ timeoutToken.unref?.();
133
+ }
134
+ options.signal?.addEventListener("abort", onAbort, { once: true });
135
+ });
136
+ }
137
+ options.signal?.throwIfAborted();
138
+ }
139
+ async function pRetry(input, options = {}) {
140
+ options = { ...options };
141
+ validateRetries(options.retries);
142
+ if (Object.hasOwn(options, "forever")) {
143
+ throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
144
+ }
145
+ options.retries ??= 10;
146
+ options.factor ??= 2;
147
+ options.minTimeout ??= 1e3;
148
+ options.maxTimeout ??= Number.POSITIVE_INFINITY;
149
+ options.randomize ??= false;
150
+ options.onFailedAttempt ??= () => {
151
+ };
152
+ options.shouldRetry ??= () => true;
153
+ validateNumberOption("factor", options.factor, { min: 0, allowInfinity: false });
154
+ validateNumberOption("minTimeout", options.minTimeout, { min: 0, allowInfinity: false });
155
+ validateNumberOption("maxTimeout", options.maxTimeout, { min: 0, allowInfinity: true });
156
+ const resolvedMaxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
157
+ validateNumberOption("maxRetryTime", resolvedMaxRetryTime, { min: 0, allowInfinity: true });
158
+ if (!(options.factor > 0)) {
159
+ options.factor = 1;
160
+ }
161
+ options.signal?.throwIfAborted();
162
+ let attemptNumber = 0;
163
+ const startTime = Date.now();
164
+ const maxRetryTime = resolvedMaxRetryTime;
165
+ while (attemptNumber < options.retries + 1) {
166
+ attemptNumber++;
167
+ try {
168
+ options.signal?.throwIfAborted();
169
+ const result = await input(attemptNumber);
170
+ options.signal?.throwIfAborted();
171
+ return result;
172
+ } catch (error) {
173
+ await onAttemptFailure(error, attemptNumber, options, startTime, maxRetryTime);
174
+ }
175
+ }
176
+ throw new Error("Retry attempts exhausted without throwing an error.");
177
+ }
178
+
4
179
  // src/debug.ts
5
180
  import createDebug from "debug";
6
181
  var KEY = "@argos-ci/api-client";
@@ -16,6 +191,26 @@ function createClient(options) {
16
191
  baseUrl: baseUrl || "https://api.argos-ci.com/v2/",
17
192
  headers: {
18
193
  Authorization: `Bearer ${options.authToken}`
194
+ },
195
+ fetch: (input) => {
196
+ return pRetry(
197
+ async () => {
198
+ const response = await fetch(input.clone());
199
+ if (response.status >= 500) {
200
+ throw new APIError("Internal Server Error");
201
+ }
202
+ return response;
203
+ },
204
+ {
205
+ retries: 3,
206
+ onFailedAttempt: (context) => {
207
+ debug("API request failed", context.error.message);
208
+ if (context.retriesLeft > 0) {
209
+ debug(`Retrying API request... (${context.retriesLeft} left)`);
210
+ }
211
+ }
212
+ }
213
+ );
19
214
  }
20
215
  });
21
216
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@argos-ci/api-client",
3
3
  "description": "Argos API Client library.",
4
- "version": "0.10.0",
4
+ "version": "0.11.1",
5
5
  "author": "Smooth Code",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -45,11 +45,12 @@
45
45
  "devDependencies": {
46
46
  "@types/debug": "^4.1.12",
47
47
  "@types/node": "catalog:",
48
- "openapi-typescript": "^7.8.0"
48
+ "openapi-typescript": "^7.9.1",
49
+ "p-retry": "^7.0.0"
49
50
  },
50
51
  "dependencies": {
51
- "debug": "^4.4.0",
52
+ "debug": "^4.4.3",
52
53
  "openapi-fetch": "^0.14.0"
53
54
  },
54
- "gitHead": "dfad527145f58037c1991c2a85ad8cdc0d8a1a3f"
55
+ "gitHead": "00f28041a847158e437aaab5fc9e816f6b609021"
55
56
  }