@argos-ci/api-client 0.20.0 → 0.21.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/index.d.mts CHANGED
@@ -1,6 +1,3 @@
1
- import * as _$openapi_fetch0 from "openapi-fetch";
2
-
3
- //#region src/schema.d.ts
4
1
  declare namespace schema_d_exports {
5
2
  export { $defs, components, operations, paths, webhooks };
6
3
  }
@@ -1643,6 +1640,11 @@ interface operations {
1643
1640
  };
1644
1641
  }
1645
1642
  //#endregion
1643
+ //#region src/fetch.d.ts
1644
+ declare class APIError extends Error {
1645
+ constructor(message: string);
1646
+ }
1647
+ //#endregion
1646
1648
  //#region src/index.d.ts
1647
1649
  type ArgosAPIClient = ReturnType<typeof createClient>;
1648
1650
  /**
@@ -1651,10 +1653,7 @@ type ArgosAPIClient = ReturnType<typeof createClient>;
1651
1653
  declare function createClient(options?: {
1652
1654
  baseUrl?: string;
1653
1655
  authToken?: string;
1654
- }): _$openapi_fetch0.Client<paths, `${string}/${string}`>;
1655
- declare class APIError extends Error {
1656
- constructor(message: string);
1657
- }
1656
+ }): import("openapi-fetch").Client<paths, `${string}/${string}`>;
1658
1657
  /**
1659
1658
  * Handle API errors.
1660
1659
  */
package/dist/index.mjs CHANGED
@@ -1,193 +1,58 @@
1
- import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
1
+ import { t as __exportAll } from "./chunk-D7D4PA-g.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
14
+ async function createRequestFactory(request, timeout) {
15
+ const body = request.body ? await request.arrayBuffer() : void 0;
16
+ const headers = new Headers(request.headers);
17
+ const requestId = headers.get("x-argos-request-id")?.trim() || globalThis.crypto.randomUUID();
18
+ return (retryAttempt) => {
19
+ const requestHeaders = new Headers(headers);
20
+ requestHeaders.set("x-argos-request-id", requestId);
21
+ requestHeaders.set("x-argos-retry-attempt", String(retryAttempt));
22
+ return new Request(request.url, {
23
+ body,
24
+ cache: request.cache,
25
+ credentials: request.credentials,
26
+ headers: requestHeaders,
27
+ integrity: request.integrity,
28
+ keepalive: request.keepalive,
29
+ method: request.method,
30
+ mode: request.mode,
31
+ redirect: request.redirect,
32
+ referrer: request.referrer,
33
+ referrerPolicy: request.referrerPolicy,
34
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(timeout)])
97
35
  });
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
116
- });
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;
36
+ };
133
37
  }
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++;
38
+ async function apiFetch(input, options = {}) {
39
+ input.signal.throwIfAborted();
40
+ const fetchImpl = options.fetch ?? fetch;
41
+ const createRequest = await createRequestFactory(input, options.timeout ?? DEFAULT_TIMEOUT);
42
+ return pRetry(async (attemptNumber) => {
43
+ const response = await fetchImpl(createRequest(attemptNumber - 1));
44
+ if (response.status >= 500) throw new APIError(`Internal Server Error (${response.status})`);
45
+ return response;
46
+ }, {
47
+ minTimeout: options.minTimeout,
48
+ retries: options.retries ?? 3,
49
+ shouldRetry: () => !input.signal.aborted,
50
+ onFailedAttempt: (context) => {
51
+ debug("API request failed", context.error.message);
52
+ if (context.retriesLeft > 0) debug(`Retrying API request... (${context.retriesLeft} left)`);
186
53
  }
187
- }
188
- throw new Error("Retry attempts exhausted without throwing an error.");
54
+ });
189
55
  }
190
- const debug = createDebug("@argos-ci/api-client");
191
56
  //#endregion
192
57
  //#region src/schema.ts
193
58
  var schema_exports = /* @__PURE__ */ __exportAll({});
@@ -201,26 +66,9 @@ function createClient(options) {
201
66
  return createFetchClient({
202
67
  baseUrl: baseUrl || "https://api.argos-ci.com/v2/",
203
68
  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
- }
69
+ fetch: apiFetch
217
70
  });
218
71
  }
219
- var APIError = class extends Error {
220
- constructor(message) {
221
- super(message);
222
- }
223
- };
224
72
  /**
225
73
  * Handle API errors.
226
74
  */
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.21.0",
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": "fa5a1d192b0782602f9a415ddfc82c0f696eec7b"
56
58
  }
File without changes