@naturalcycles/js-lib 15.102.0 → 15.104.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.
@@ -0,0 +1,43 @@
1
+ /// <reference lib="dom" preserve="true" />
2
+ import type { HttpRequestErrorData } from '../error/error.model.js';
3
+ import type { NumberOfMilliseconds } from '../types.js';
4
+ import type { HttpMethod } from './http.model.js';
5
+ /**
6
+ * Minimal wrapper around native `fetch`:
7
+ *
8
+ * - returns json output via Promise
9
+ * - throws FetchError (a plain Error with `cause` and `data`) if anything goes wrong
10
+ * - retries 2 times with simple non-configurable exponential back-off
11
+ *
12
+ * For anything more complex - use the Fetcher.
13
+ * Use this wrapper for the simplest use cases, and where bundle size matters.
14
+ */
15
+ export declare function _fetch<T = unknown>(url: string, opt?: FetchOptions): Promise<T>;
16
+ /**
17
+ * Accepts the commonly used RequestInit options.
18
+ * `signal` is replaced by `timeout`.
19
+ */
20
+ export interface FetchOptions extends Pick<RequestInit, 'body' | 'cache' | 'credentials' | 'keepalive' | 'redirect'> {
21
+ /**
22
+ * Defaults to GET
23
+ */
24
+ method?: HttpMethod;
25
+ headers?: Record<string, string>;
26
+ /**
27
+ * Request body. It's JSON.stringified, and the Content-Type header is set to `application/json`.
28
+ * Takes precedence over `body`.
29
+ */
30
+ json?: any;
31
+ /**
32
+ * Defaults to 30 seconds. 0 disables the timeout.
33
+ * Covers the whole request, including reading the body.
34
+ */
35
+ timeout?: NumberOfMilliseconds;
36
+ }
37
+ /**
38
+ * Thrown by `_fetch`: a plain Error, with the response body text (or the underlying error)
39
+ * as `cause`, and a subset of HttpRequestErrorData as `data`.
40
+ */
41
+ export interface FetchError extends Error {
42
+ data: Pick<HttpRequestErrorData, 'responseStatusCode' | 'requestUrl' | 'requestMethod'>;
43
+ }
@@ -0,0 +1,57 @@
1
+ /// <reference lib="dom" preserve="true" />
2
+ /**
3
+ * Minimal wrapper around native `fetch`:
4
+ *
5
+ * - returns json output via Promise
6
+ * - throws FetchError (a plain Error with `cause` and `data`) if anything goes wrong
7
+ * - retries 2 times with simple non-configurable exponential back-off
8
+ *
9
+ * For anything more complex - use the Fetcher.
10
+ * Use this wrapper for the simplest use cases, and where bundle size matters.
11
+ */
12
+ export async function _fetch(url, opt = {}) {
13
+ const { method = 'GET', timeout = 30_000, json, ...init } = opt;
14
+ if (json !== undefined) {
15
+ init.body = JSON.stringify(json);
16
+ init.headers = { 'content-type': 'application/json', ...init.headers };
17
+ }
18
+ let res;
19
+ let cause;
20
+ for (let attempt = 0;; attempt++) {
21
+ res = undefined;
22
+ try {
23
+ res = await fetch(url, {
24
+ ...init,
25
+ method,
26
+ // A fresh signal per attempt, as a timed-out signal stays aborted
27
+ signal: timeout ? AbortSignal.timeout(timeout) : undefined,
28
+ });
29
+ if (res.ok) {
30
+ const text = await res.text();
31
+ return (text ? JSON.parse(text) : {});
32
+ }
33
+ cause = await res.text();
34
+ }
35
+ catch (err) {
36
+ // Network failure, timeout, or failure to read/parse the body
37
+ cause = err;
38
+ }
39
+ if (attempt === 2 || !shouldRetry(method, res))
40
+ break;
41
+ await pDelay(1000 * 2 ** attempt); // 1s, then 2s
42
+ }
43
+ const err = Object.assign(
44
+ // E.g `503 GET https://example.com/api`, or `GET https://example.com/api` on a network failure
45
+ new Error([res?.status, method, url].filter(Boolean).join(' '), { cause }), { data: { responseStatusCode: res?.status || 0, requestUrl: url, requestMethod: method } });
46
+ throw err;
47
+ }
48
+ /**
49
+ * Retries network failures (including timeouts), 5xx, 408 and 429.
50
+ * Never retries a POST.
51
+ */
52
+ function shouldRetry(method, res) {
53
+ return (method !== 'POST' && (!res || res.status >= 500 || res.status === 408 || res.status === 429));
54
+ }
55
+ async function pDelay(ms) {
56
+ await new Promise(resolve => setTimeout(resolve, ms));
57
+ }
@@ -50,17 +50,24 @@ export declare class Fetcher {
50
50
  put: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>;
51
51
  patch: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>;
52
52
  delete: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>;
53
+ /**
54
+ * HTTP QUERY method: like GET (safe and idempotent, hence retried by default),
55
+ * but with a request body (e.g `json`).
56
+ */
57
+ query: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>;
53
58
  getText: (url: string, opt?: FetcherOptions) => Promise<string>;
54
59
  postText: (url: string, opt?: FetcherOptions) => Promise<string>;
55
60
  putText: (url: string, opt?: FetcherOptions) => Promise<string>;
56
61
  patchText: (url: string, opt?: FetcherOptions) => Promise<string>;
57
62
  deleteText: (url: string, opt?: FetcherOptions) => Promise<string>;
63
+ queryText: (url: string, opt?: FetcherOptions) => Promise<string>;
58
64
  getVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
59
65
  postVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
60
66
  putVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
61
67
  patchVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
62
68
  deleteVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
63
69
  headVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
70
+ queryVoid: (url: string, opt?: FetcherOptions) => Promise<void>;
64
71
  /**
65
72
  * Small convenience wrapper that allows to issue GraphQL queries.
66
73
  * In practice, all it does is:
@@ -122,12 +122,18 @@ export class Fetcher {
122
122
  put;
123
123
  patch;
124
124
  delete;
125
+ /**
126
+ * HTTP QUERY method: like GET (safe and idempotent, hence retried by default),
127
+ * but with a request body (e.g `json`).
128
+ */
129
+ query;
125
130
  // responseType=text
126
131
  getText;
127
132
  postText;
128
133
  putText;
129
134
  patchText;
130
135
  deleteText;
136
+ queryText;
131
137
  // responseType=void (no body fetching/parsing)
132
138
  getVoid;
133
139
  postVoid;
@@ -135,6 +141,7 @@ export class Fetcher {
135
141
  patchVoid;
136
142
  deleteVoid;
137
143
  headVoid;
144
+ queryVoid;
138
145
  /**
139
146
  * Small convenience wrapper that allows to issue GraphQL queries.
140
147
  * In practice, all it does is:
@@ -1,4 +1,4 @@
1
- export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD';
1
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'QUERY';
2
2
  export type HttpStatusFamily = 5 | 4 | 3 | 2 | 1;
3
3
  /**
4
4
  * Number, representing a valid Http status code (e.g 401, 500, etc)
@@ -1 +1,9 @@
1
- export const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'];
1
+ export const HTTP_METHODS = [
2
+ 'GET',
3
+ 'POST',
4
+ 'PUT',
5
+ 'PATCH',
6
+ 'DELETE',
7
+ 'HEAD',
8
+ 'QUERY',
9
+ ];
@@ -1,3 +1,4 @@
1
1
  export * from './fetcher.js';
2
2
  export type * from './fetcher.model.js';
3
3
  export * from './http.model.js';
4
+ export * from './fetch.js';
@@ -1,2 +1,3 @@
1
1
  export * from './fetcher.js';
2
2
  export * from './http.model.js';
3
+ export * from './fetch.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
3
  "type": "module",
4
- "version": "15.102.0",
4
+ "version": "15.104.0",
5
5
  "dependencies": {
6
6
  "tslib": "^2"
7
7
  },
@@ -14,7 +14,7 @@
14
14
  }
15
15
  },
16
16
  "devDependencies": {
17
- "@naturalcycles/dev-lib": "20.72.0",
17
+ "@naturalcycles/dev-lib": "0.0.0",
18
18
  "@types/node": "^26",
19
19
  "@types/semver": "^7",
20
20
  "rolldown": "^1",
@@ -40,6 +40,7 @@
40
40
  "./error": "./dist/error/index.js",
41
41
  "./error/*.js": "./dist/error/*.js",
42
42
  "./http": "./dist/http/index.js",
43
+ "./http/*.js": "./dist/http/*.js",
43
44
  "./intl": "./dist/intl/intl.js",
44
45
  "./log": "./dist/log/commonLogger.js",
45
46
  "./math": "./dist/math/index.js",
@@ -0,0 +1,102 @@
1
+ /// <reference lib="dom" preserve="true" />
2
+
3
+ import type { HttpRequestErrorData } from '../error/error.model.js'
4
+ import type { NumberOfMilliseconds } from '../types.js'
5
+ import type { HttpMethod } from './http.model.js'
6
+
7
+ /**
8
+ * Minimal wrapper around native `fetch`:
9
+ *
10
+ * - returns json output via Promise
11
+ * - throws FetchError (a plain Error with `cause` and `data`) if anything goes wrong
12
+ * - retries 2 times with simple non-configurable exponential back-off
13
+ *
14
+ * For anything more complex - use the Fetcher.
15
+ * Use this wrapper for the simplest use cases, and where bundle size matters.
16
+ */
17
+ export async function _fetch<T = unknown>(url: string, opt: FetchOptions = {}): Promise<T> {
18
+ const { method = 'GET', timeout = 30_000, json, ...init } = opt
19
+ if (json !== undefined) {
20
+ init.body = JSON.stringify(json)
21
+ init.headers = { 'content-type': 'application/json', ...init.headers }
22
+ }
23
+ let res: Response | undefined
24
+ let cause: unknown
25
+
26
+ for (let attempt = 0; ; attempt++) {
27
+ res = undefined
28
+ try {
29
+ res = await fetch(url, {
30
+ ...init,
31
+ method,
32
+ // A fresh signal per attempt, as a timed-out signal stays aborted
33
+ signal: timeout ? AbortSignal.timeout(timeout) : undefined,
34
+ })
35
+ if (res.ok) {
36
+ const text = await res.text()
37
+ return (text ? JSON.parse(text) : {}) as T
38
+ }
39
+ cause = await res.text()
40
+ } catch (err) {
41
+ // Network failure, timeout, or failure to read/parse the body
42
+ cause = err
43
+ }
44
+
45
+ if (attempt === 2 || !shouldRetry(method, res)) break
46
+ await pDelay(1000 * 2 ** attempt) // 1s, then 2s
47
+ }
48
+
49
+ const err: FetchError = Object.assign(
50
+ // E.g `503 GET https://example.com/api`, or `GET https://example.com/api` on a network failure
51
+ new Error([res?.status, method, url].filter(Boolean).join(' '), { cause }),
52
+ { data: { responseStatusCode: res?.status || 0, requestUrl: url, requestMethod: method } },
53
+ )
54
+ throw err
55
+ }
56
+
57
+ /**
58
+ * Retries network failures (including timeouts), 5xx, 408 and 429.
59
+ * Never retries a POST.
60
+ */
61
+ function shouldRetry(method: HttpMethod, res?: Response): boolean {
62
+ return (
63
+ method !== 'POST' && (!res || res.status >= 500 || res.status === 408 || res.status === 429)
64
+ )
65
+ }
66
+
67
+ /**
68
+ * Accepts the commonly used RequestInit options.
69
+ * `signal` is replaced by `timeout`.
70
+ */
71
+ export interface FetchOptions extends Pick<
72
+ RequestInit,
73
+ 'body' | 'cache' | 'credentials' | 'keepalive' | 'redirect'
74
+ > {
75
+ /**
76
+ * Defaults to GET
77
+ */
78
+ method?: HttpMethod
79
+ headers?: Record<string, string>
80
+ /**
81
+ * Request body. It's JSON.stringified, and the Content-Type header is set to `application/json`.
82
+ * Takes precedence over `body`.
83
+ */
84
+ json?: any
85
+ /**
86
+ * Defaults to 30 seconds. 0 disables the timeout.
87
+ * Covers the whole request, including reading the body.
88
+ */
89
+ timeout?: NumberOfMilliseconds
90
+ }
91
+
92
+ /**
93
+ * Thrown by `_fetch`: a plain Error, with the response body text (or the underlying error)
94
+ * as `cause`, and a subset of HttpRequestErrorData as `data`.
95
+ */
96
+ export interface FetchError extends Error {
97
+ data: Pick<HttpRequestErrorData, 'responseStatusCode' | 'requestUrl' | 'requestMethod'>
98
+ }
99
+
100
+ async function pDelay<T>(ms: NumberOfMilliseconds): Promise<void> {
101
+ await new Promise<T>(resolve => setTimeout(resolve, ms))
102
+ }
@@ -175,6 +175,11 @@ export class Fetcher {
175
175
  put!: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>
176
176
  patch!: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>
177
177
  delete!: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>
178
+ /**
179
+ * HTTP QUERY method: like GET (safe and idempotent, hence retried by default),
180
+ * but with a request body (e.g `json`).
181
+ */
182
+ query!: <T = unknown>(url: string, opt?: FetcherOptions) => Promise<T>
178
183
 
179
184
  // responseType=text
180
185
  getText!: (url: string, opt?: FetcherOptions) => Promise<string>
@@ -182,6 +187,7 @@ export class Fetcher {
182
187
  putText!: (url: string, opt?: FetcherOptions) => Promise<string>
183
188
  patchText!: (url: string, opt?: FetcherOptions) => Promise<string>
184
189
  deleteText!: (url: string, opt?: FetcherOptions) => Promise<string>
190
+ queryText!: (url: string, opt?: FetcherOptions) => Promise<string>
185
191
 
186
192
  // responseType=void (no body fetching/parsing)
187
193
  getVoid!: (url: string, opt?: FetcherOptions) => Promise<void>
@@ -190,6 +196,7 @@ export class Fetcher {
190
196
  patchVoid!: (url: string, opt?: FetcherOptions) => Promise<void>
191
197
  deleteVoid!: (url: string, opt?: FetcherOptions) => Promise<void>
192
198
  headVoid!: (url: string, opt?: FetcherOptions) => Promise<void>
199
+ queryVoid!: (url: string, opt?: FetcherOptions) => Promise<void>
193
200
 
194
201
  /**
195
202
  * Small convenience wrapper that allows to issue GraphQL queries.
@@ -1,5 +1,6 @@
1
1
  // Should be uppercase, because e.g this browser issue: https://github.com/axios/axios/issues/26
2
- export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'
2
+ // QUERY is like GET (safe and idempotent), but with a request body: https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/
3
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'QUERY'
3
4
 
4
5
  export type HttpStatusFamily = 5 | 4 | 3 | 2 | 1
5
6
 
@@ -8,4 +9,12 @@ export type HttpStatusFamily = 5 | 4 | 3 | 2 | 1
8
9
  */
9
10
  export type HttpStatusCode = number
10
11
 
11
- export const HTTP_METHODS: readonly HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD']
12
+ export const HTTP_METHODS: readonly HttpMethod[] = [
13
+ 'GET',
14
+ 'POST',
15
+ 'PUT',
16
+ 'PATCH',
17
+ 'DELETE',
18
+ 'HEAD',
19
+ 'QUERY',
20
+ ]
package/src/http/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './fetcher.js'
2
2
  export type * from './fetcher.model.js'
3
3
  export * from './http.model.js'
4
+ export * from './fetch.js'