@argos-ci/api-client 0.20.0 → 0.20.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.mts CHANGED
@@ -1643,6 +1643,11 @@ interface operations {
1643
1643
  };
1644
1644
  }
1645
1645
  //#endregion
1646
+ //#region src/fetch.d.ts
1647
+ declare class APIError extends Error {
1648
+ constructor(message: string);
1649
+ }
1650
+ //#endregion
1646
1651
  //#region src/index.d.ts
1647
1652
  type ArgosAPIClient = ReturnType<typeof createClient>;
1648
1653
  /**
@@ -1652,9 +1657,6 @@ declare function createClient(options?: {
1652
1657
  baseUrl?: string;
1653
1658
  authToken?: string;
1654
1659
  }): _$openapi_fetch0.Client<paths, `${string}/${string}`>;
1655
- declare class APIError extends Error {
1656
- constructor(message: string);
1657
- }
1658
1660
  /**
1659
1661
  * Handle API errors.
1660
1662
  */
package/dist/index.mjs CHANGED
@@ -1,193 +1,52 @@
1
1
  import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
2
2
  import createFetchClient from "openapi-fetch";
3
3
  import createDebug from "debug";
4
- //#region ../../node_modules/.pnpm/is-network-error@1.3.2/node_modules/is-network-error/index.js
5
- const objectToString = Object.prototype.toString;
6
- const isError = (value) => objectToString.call(value) === "[object Error]";
7
- const errorMessages = new Set([
8
- "network error",
9
- "NetworkError when attempting to fetch resource.",
10
- "The Internet connection appears to be offline.",
11
- "Network request failed",
12
- "fetch failed",
13
- "terminated",
14
- " A network error occurred.",
15
- "Network connection lost"
16
- ]);
17
- function isNetworkError(error) {
18
- if (!(error && isError(error) && error.name === "TypeError" && typeof error.message === "string")) return false;
19
- const { message, stack } = error;
20
- if (message === "Load failed" || message.startsWith("Load failed (") && message.endsWith(")")) return stack === void 0 || "__sentry_captured__" in error;
21
- if (message.startsWith("error sending request for url")) return true;
22
- if (message === "Failed to fetch" || message.startsWith("Failed to fetch (") && message.endsWith(")")) return true;
23
- return errorMessages.has(message);
24
- }
4
+ import pRetry from "p-retry";
5
+ const debug = createDebug("@argos-ci/api-client");
25
6
  //#endregion
26
- //#region ../../node_modules/.pnpm/p-retry@8.0.0/node_modules/p-retry/index.js
27
- function validateRetries(retries) {
28
- if (typeof retries === "number") {
29
- if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number.");
30
- if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
31
- } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity.");
32
- }
33
- function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
34
- if (value === void 0) return;
35
- if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
36
- if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`);
37
- if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`);
38
- }
39
- function validateFunctionOption(name, value) {
40
- if (value === void 0) return;
41
- if (typeof value !== "function") throw new TypeError(`Expected \`${name}\` to be a function.`);
42
- }
43
- var AbortError = class extends Error {
7
+ //#region src/fetch.ts
8
+ const DEFAULT_TIMEOUT = 3e4;
9
+ var APIError = class extends Error {
44
10
  constructor(message) {
45
- super();
46
- if (message instanceof Error) {
47
- this.originalError = message;
48
- ({message} = message);
49
- } else {
50
- this.originalError = new Error(message);
51
- this.originalError.stack = this.stack;
52
- }
53
- this.name = "AbortError";
54
- this.message = message;
11
+ super(message);
55
12
  }
56
13
  };
57
- function calculateDelay(retriesConsumed, options) {
58
- const attempt = Math.max(1, retriesConsumed + 1);
59
- const random = options.randomize ? Math.random() + 1 : 1;
60
- let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
61
- timeout = Math.min(timeout, options.maxTimeout);
62
- return timeout;
63
- }
64
- function calculateRemainingTime(start, max) {
65
- if (!Number.isFinite(max)) return max;
66
- return max - (performance.now() - start);
67
- }
68
- async function delayForRetry(delay, options) {
69
- if (delay <= 0) return;
70
- await new Promise((resolve, reject) => {
71
- const onAbort = () => {
72
- clearTimeout(timeoutToken);
73
- options.signal?.removeEventListener("abort", onAbort);
74
- reject(options.signal.reason);
75
- };
76
- const timeoutToken = setTimeout(() => {
77
- options.signal?.removeEventListener("abort", onAbort);
78
- resolve();
79
- }, delay);
80
- if (options.unref) timeoutToken.unref?.();
81
- options.signal?.addEventListener("abort", onAbort, { once: true });
82
- });
83
- }
84
- async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) {
85
- const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
86
- if (normalizedError instanceof AbortError) throw normalizedError.originalError;
87
- const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
88
- const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
89
- const delayTime = calculateDelay(retriesConsumed, options);
90
- if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {
91
- const context = Object.freeze({
92
- error: normalizedError,
93
- attemptNumber,
94
- retriesLeft,
95
- retriesConsumed,
96
- retryDelay: 0
97
- });
98
- await options.onFailedAttempt(context);
99
- throw normalizedError;
100
- }
101
- const consumeRetryContext = Object.freeze({
102
- error: normalizedError,
103
- attemptNumber,
104
- retriesLeft,
105
- retriesConsumed,
106
- retryDelay: retriesLeft > 0 ? delayTime : 0
107
- });
108
- const consumeRetry = await options.shouldConsumeRetry(consumeRetryContext);
109
- const effectiveDelay = consumeRetry && retriesLeft > 0 ? delayTime : 0;
110
- const context = Object.freeze({
111
- error: normalizedError,
112
- attemptNumber,
113
- retriesLeft,
114
- retriesConsumed,
115
- retryDelay: effectiveDelay
14
+ async function createRequestFactory(request, timeout) {
15
+ const body = request.body ? await request.arrayBuffer() : void 0;
16
+ const headers = new Headers(request.headers);
17
+ return () => new Request(request.url, {
18
+ body,
19
+ cache: request.cache,
20
+ credentials: request.credentials,
21
+ headers,
22
+ integrity: request.integrity,
23
+ keepalive: request.keepalive,
24
+ method: request.method,
25
+ mode: request.mode,
26
+ redirect: request.redirect,
27
+ referrer: request.referrer,
28
+ referrerPolicy: request.referrerPolicy,
29
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(timeout)])
116
30
  });
117
- await options.onFailedAttempt(context);
118
- if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError;
119
- if (calculateRemainingTime(startTime, maxRetryTime) <= 0 || retriesLeft <= 0) throw normalizedError;
120
- if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) throw normalizedError;
121
- if (!await options.shouldRetry(context)) throw normalizedError;
122
- const remainingTimeAfterShouldRetry = calculateRemainingTime(startTime, maxRetryTime);
123
- if (remainingTimeAfterShouldRetry <= 0) throw normalizedError;
124
- if (!consumeRetry) {
125
- options.signal?.throwIfAborted();
126
- return false;
127
- }
128
- const finalDelay = Math.min(effectiveDelay, remainingTimeAfterShouldRetry);
129
- options.signal?.throwIfAborted();
130
- await delayForRetry(finalDelay, options);
131
- options.signal?.throwIfAborted();
132
- return true;
133
31
  }
134
- async function pRetry(input, options = {}) {
135
- options = { ...options };
136
- validateRetries(options.retries);
137
- if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
138
- options.retries ??= 10;
139
- options.factor ??= 2;
140
- options.minTimeout ??= 1e3;
141
- options.maxTimeout ??= Number.POSITIVE_INFINITY;
142
- options.maxRetryTime ??= Number.POSITIVE_INFINITY;
143
- options.randomize ??= false;
144
- options.onFailedAttempt ??= () => {};
145
- options.shouldRetry ??= () => true;
146
- options.shouldConsumeRetry ??= () => true;
147
- validateFunctionOption("onFailedAttempt", options.onFailedAttempt);
148
- validateFunctionOption("shouldRetry", options.shouldRetry);
149
- validateFunctionOption("shouldConsumeRetry", options.shouldConsumeRetry);
150
- validateNumberOption("factor", options.factor, {
151
- min: 0,
152
- allowInfinity: false
153
- });
154
- validateNumberOption("minTimeout", options.minTimeout, {
155
- min: 0,
156
- allowInfinity: false
157
- });
158
- validateNumberOption("maxTimeout", options.maxTimeout, {
159
- min: 0,
160
- allowInfinity: true
161
- });
162
- validateNumberOption("maxRetryTime", options.maxRetryTime, {
163
- min: 0,
164
- allowInfinity: true
165
- });
166
- if (!(options.factor > 0)) options.factor = 1;
167
- options.signal?.throwIfAborted();
168
- let attemptNumber = 0;
169
- let retriesConsumed = 0;
170
- const startTime = performance.now();
171
- while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
172
- attemptNumber++;
173
- try {
174
- options.signal?.throwIfAborted();
175
- const result = await input(attemptNumber);
176
- options.signal?.throwIfAborted();
177
- return result;
178
- } catch (error) {
179
- if (await onAttemptFailure({
180
- error,
181
- attemptNumber,
182
- retriesConsumed,
183
- startTime,
184
- options
185
- })) retriesConsumed++;
32
+ async function apiFetch(input, options = {}) {
33
+ input.signal.throwIfAborted();
34
+ const fetchImpl = options.fetch ?? fetch;
35
+ const createRequest = await createRequestFactory(input, options.timeout ?? DEFAULT_TIMEOUT);
36
+ return pRetry(async () => {
37
+ const response = await fetchImpl(createRequest());
38
+ if (response.status >= 500) throw new APIError(`Internal Server Error (${response.status})`);
39
+ return response;
40
+ }, {
41
+ minTimeout: options.minTimeout,
42
+ retries: options.retries ?? 3,
43
+ shouldRetry: () => !input.signal.aborted,
44
+ onFailedAttempt: (context) => {
45
+ debug("API request failed", context.error.message);
46
+ if (context.retriesLeft > 0) debug(`Retrying API request... (${context.retriesLeft} left)`);
186
47
  }
187
- }
188
- throw new Error("Retry attempts exhausted without throwing an error.");
48
+ });
189
49
  }
190
- const debug = createDebug("@argos-ci/api-client");
191
50
  //#endregion
192
51
  //#region src/schema.ts
193
52
  var schema_exports = /* @__PURE__ */ __exportAll({});
@@ -201,26 +60,9 @@ function createClient(options) {
201
60
  return createFetchClient({
202
61
  baseUrl: baseUrl || "https://api.argos-ci.com/v2/",
203
62
  headers: { Authorization: authToken ? `Bearer ${authToken}` : void 0 },
204
- fetch: (input) => {
205
- return pRetry(async () => {
206
- const response = await fetch(input.clone());
207
- if (response.status >= 500) throw new APIError("Internal Server Error");
208
- return response;
209
- }, {
210
- retries: 3,
211
- onFailedAttempt: (context) => {
212
- debug("API request failed", context.error.message);
213
- if (context.retriesLeft > 0) debug(`Retrying API request... (${context.retriesLeft} left)`);
214
- }
215
- });
216
- }
63
+ fetch: apiFetch
217
64
  });
218
65
  }
219
- var APIError = class extends Error {
220
- constructor(message) {
221
- super(message);
222
- }
223
- };
224
66
  /**
225
67
  * Handle API errors.
226
68
  */
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.20.0",
4
+ "version": "0.20.1",
5
5
  "author": "Smooth Code",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -40,17 +40,19 @@
40
40
  "build": "tsdown",
41
41
  "check-types": "tsc",
42
42
  "check-format": "prettier --check --ignore-unknown --ignore-path=../../.gitignore --ignore-path=../../.prettierignore .",
43
- "lint": "eslint ."
43
+ "lint": "eslint .",
44
+ "test": "vitest"
44
45
  },
45
46
  "devDependencies": {
46
47
  "@types/debug": "^4.1.13",
47
48
  "@types/node": "catalog:",
48
49
  "openapi-typescript": "^7.13.0",
49
- "p-retry": "^8.0.0"
50
+ "vitest": "catalog:"
50
51
  },
51
52
  "dependencies": {
52
53
  "debug": "^4.4.3",
53
- "openapi-fetch": "^0.17.0"
54
+ "openapi-fetch": "^0.17.0",
55
+ "p-retry": "^8.0.0"
54
56
  },
55
- "gitHead": "357c71173989a18d98767bb8811272cb46ecf937"
57
+ "gitHead": "75892460d881beaf87ae6a6c62c2c82d5df8fba4"
56
58
  }