fetch-layers 0.0.0-stage → 1.0.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/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +262 -2
- package/README.ru.md +263 -0
- package/dist/classify-body-DOG6Vbf_.mjs +1 -0
- package/dist/errors-CSZuncD0.d.mts +119 -0
- package/dist/index.d.mts +74 -0
- package/dist/index.mjs +1 -0
- package/dist/layer-C9nwqcxP.d.mts +69 -0
- package/dist/layer-D1S2Wlu1.d.mts +238 -0
- package/dist/layer-DRRyGTne.d.mts +99 -0
- package/dist/layer-Db25lSAX.d.mts +132 -0
- package/dist/layer-Dhb1y_u6.mjs +1 -0
- package/dist/layers/auth/index.d.mts +12 -0
- package/dist/layers/auth/index.mjs +1 -0
- package/dist/layers/idempotency/index.d.mts +55 -0
- package/dist/layers/idempotency/index.mjs +1 -0
- package/dist/layers/index.d.mts +38 -0
- package/dist/layers/index.mjs +1 -0
- package/dist/layers/retry/index.d.mts +2 -0
- package/dist/layers/retry/index.mjs +1 -0
- package/dist/reset-registry-CQPiZVBB.mjs +1 -0
- package/dist/session-Dm-H-5hJ.mjs +1 -0
- package/dist/shared/storage.d.mts +2 -0
- package/dist/shared/storage.mjs +1 -0
- package/dist/signals-DQjF6ojU.mjs +1 -0
- package/dist/storage-C0XsVkz-.d.mts +44 -0
- package/package.json +100 -4
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
//#region src/core/errors.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* All library errors are normalized to ApiError: the app handles
|
|
4
|
+
* them in one place instead of parsing Response in every catch.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Error category. Affects handling strategy.
|
|
8
|
+
*
|
|
9
|
+
* - network: no connection (network, DNS, CORS);
|
|
10
|
+
* - timeout: request did not finish in time, including token refresh;
|
|
11
|
+
* - http: status outside 2xx;
|
|
12
|
+
* - parse: response body could not be parsed;
|
|
13
|
+
* - abort: cancelled via AbortSignal;
|
|
14
|
+
* - serialize: body or fingerprint could not be serialized,
|
|
15
|
+
* or idempotency key is invalid (IDEMPOTENCY_KEY_INVALID);
|
|
16
|
+
* - storage: idempotency key was not saved;
|
|
17
|
+
* - unknown: everything else, including AUTH_PROVIDER_ERROR,
|
|
18
|
+
* REFRESH_CIRCUIT_OPEN and INVALID_REQUEST_CONFIG.
|
|
19
|
+
*/
|
|
20
|
+
type ApiErrorKind = 'network' | 'timeout' | 'http' | 'parse' | 'abort' | 'serialize' | 'storage' | 'unknown';
|
|
21
|
+
/**
|
|
22
|
+
* Single error class for the library.
|
|
23
|
+
*
|
|
24
|
+
* Library codes:
|
|
25
|
+
*
|
|
26
|
+
* - ABORTED, TIMEOUT, NETWORK_ERROR, PARSE_ERROR,
|
|
27
|
+
* BODY_SERIALIZATION_ERROR - transport;
|
|
28
|
+
* - AUTH_PROVIDER_ERROR, REFRESH_TIMEOUT, REFRESH_CIRCUIT_OPEN - auth;
|
|
29
|
+
* - IDEMPOTENCY_STORAGE_ERROR, IDEMPOTENCY_KEY_INVALID - idempotency;
|
|
30
|
+
* - INVALID_REQUEST_CONFIG - request config failed validation
|
|
31
|
+
* (empty path, timeoutMs < 100).
|
|
32
|
+
*
|
|
33
|
+
* Other codes come from server response body.
|
|
34
|
+
*/
|
|
35
|
+
declare class ApiError extends Error {
|
|
36
|
+
readonly kind: ApiErrorKind;
|
|
37
|
+
/** HTTP status. 0 if no response (network, timeout, abort). */
|
|
38
|
+
readonly status: number;
|
|
39
|
+
/** Code: server-side or from the list above. */
|
|
40
|
+
readonly code: string;
|
|
41
|
+
/**
|
|
42
|
+
* Form field errors. Key is field name, value is error text.
|
|
43
|
+
* Non-string values are dropped, full original stays in rawBody.
|
|
44
|
+
*/
|
|
45
|
+
readonly fields?: Record<string, string>;
|
|
46
|
+
/** X-Request-Id, if server returned one. */
|
|
47
|
+
readonly requestId?: string;
|
|
48
|
+
/** Retry-After in milliseconds, if present. */
|
|
49
|
+
readonly retryAfterMs?: number;
|
|
50
|
+
/** Response body as is. Useful for non-standard formats. */
|
|
51
|
+
readonly rawBody?: unknown;
|
|
52
|
+
/** Details from error parser. undefined for flat shape. */
|
|
53
|
+
readonly details?: unknown;
|
|
54
|
+
/**
|
|
55
|
+
* true if server-side operation state is unknown.
|
|
56
|
+
*
|
|
57
|
+
* - network, timeout: request may not have arrived or response
|
|
58
|
+
* may be lost;
|
|
59
|
+
* - 5xx: server may have partially applied operation before failing;
|
|
60
|
+
* - parse on 2xx or 5xx: response body is unknown;
|
|
61
|
+
* - 408/429: false, server explicitly did not accept operation;
|
|
62
|
+
* - parse on 4xx: false, server explicitly rejected operation.
|
|
63
|
+
*
|
|
64
|
+
* For safe retry decisions use isRetryable.
|
|
65
|
+
*/
|
|
66
|
+
readonly isUncertain: boolean;
|
|
67
|
+
constructor(params: {
|
|
68
|
+
kind: ApiErrorKind;
|
|
69
|
+
message: string;
|
|
70
|
+
status?: number;
|
|
71
|
+
code?: string;
|
|
72
|
+
fields?: Record<string, string>;
|
|
73
|
+
requestId?: string;
|
|
74
|
+
retryAfterMs?: number;
|
|
75
|
+
rawBody?: unknown;
|
|
76
|
+
details?: unknown;
|
|
77
|
+
isUncertain?: boolean;
|
|
78
|
+
cause?: unknown;
|
|
79
|
+
});
|
|
80
|
+
/** true for kind network and timeout. No response from server. */
|
|
81
|
+
get isNetwork(): boolean;
|
|
82
|
+
/** true for kind abort: cancelled by the app via AbortSignal. */
|
|
83
|
+
get isCancelled(): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Auth-related: status 401 or 403, or code AUTH_PROVIDER_ERROR,
|
|
86
|
+
* REFRESH_TIMEOUT or REFRESH_CIRCUIT_OPEN.
|
|
87
|
+
*/
|
|
88
|
+
get isAuthError(): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* true for network, timeout, 408, 429 and 5xx.
|
|
91
|
+
*
|
|
92
|
+
* false for abort, auth errors (401, 403, AUTH_PROVIDER_ERROR,
|
|
93
|
+
* REFRESH_TIMEOUT, REFRESH_CIRCUIT_OPEN) and other 4xx.
|
|
94
|
+
*/
|
|
95
|
+
get isRetryable(): boolean;
|
|
96
|
+
/**
|
|
97
|
+
* 4xx. Overlaps with isAuthError: 401 and 403 match both. To
|
|
98
|
+
* separate auth, check isAuthError first.
|
|
99
|
+
*/
|
|
100
|
+
get isClientError(): boolean;
|
|
101
|
+
/** 5xx. Retry after some time may help. */
|
|
102
|
+
get isServerError(): boolean;
|
|
103
|
+
/** status === 409. */
|
|
104
|
+
get isConflict(): boolean;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Normalizes any exception to ApiError. Returns the same object if
|
|
108
|
+
* input is already an ApiError.
|
|
109
|
+
*
|
|
110
|
+
* AbortError, TimeoutError and SyntaxError are detected by name,
|
|
111
|
+
* not via instanceof: an error from another realm (iframe, worker)
|
|
112
|
+
* has a different constructor.
|
|
113
|
+
*
|
|
114
|
+
* TypeError becomes unknown here: source is unknown. classifyFetchError
|
|
115
|
+
* classifies it as a network error.
|
|
116
|
+
*/
|
|
117
|
+
declare function toApiError(error: unknown): ApiError;
|
|
118
|
+
//#endregion
|
|
119
|
+
export { ApiErrorKind as n, toApiError as r, ApiError as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { _ as ResponseWithMeta, a as QueryArrayFormat, c as QueryParamPrimitive, d as RequestConfig, f as RequestFn, g as ResponseType, h as ResponseMeta, i as HttpMethod, l as QueryParamValue, m as ResolvedRequestConfig, n as LayerContext, o as QueryObjectFormat, p as RequestOptions, r as Client, s as QueryParamObject, t as Layer, u as QueryParams } from "./layer-D1S2Wlu1.mjs";
|
|
2
|
+
import { n as ApiErrorKind, r as toApiError, t as ApiError } from "./errors-CSZuncD0.mjs";
|
|
3
|
+
import { n as createMemoryStorage, r as fromWebStorage, t as StorageLike } from "./storage-C0XsVkz-.mjs";
|
|
4
|
+
//#region src/core/error-body.d.ts
|
|
5
|
+
/** Fields extracted by error parser. */
|
|
6
|
+
type ErrorBodyContent = {
|
|
7
|
+
code?: string;
|
|
8
|
+
message?: string;
|
|
9
|
+
fields?: Record<string, string>;
|
|
10
|
+
details?: unknown;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Error body parser. Passed to ClientOptions.parseErrorBody when
|
|
14
|
+
* server returns errors in a format other than flat. What is not
|
|
15
|
+
* extracted stays undefined, full body is in ApiError.rawBody.
|
|
16
|
+
*/
|
|
17
|
+
type ErrorBodyParser = (raw: unknown) => ErrorBodyContent;
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/transport/transport.d.ts
|
|
20
|
+
/**
|
|
21
|
+
* ClientOptions fields for the base transport. createClient passes
|
|
22
|
+
* options here without layers and warn.
|
|
23
|
+
*
|
|
24
|
+
* @internal
|
|
25
|
+
*/
|
|
26
|
+
interface TransportOptions {
|
|
27
|
+
/** Base address. */
|
|
28
|
+
baseUrl: string;
|
|
29
|
+
/** Request timeout in milliseconds. Defaults to 10000. */
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
/** fetch function. Defaults to the global one. */
|
|
32
|
+
fetch?: typeof fetch;
|
|
33
|
+
/** Cookie mode. */
|
|
34
|
+
credentials?: RequestCredentials;
|
|
35
|
+
/**
|
|
36
|
+
* Headers for all requests. Merged with per-request headers at the
|
|
37
|
+
* bottom of the pipeline; per-request headers and headers from
|
|
38
|
+
* layers override defaultHeaders.
|
|
39
|
+
*/
|
|
40
|
+
defaultHeaders?: HeadersInit;
|
|
41
|
+
/** Query array format. */
|
|
42
|
+
queryArrayFormat?: QueryArrayFormat;
|
|
43
|
+
/** Query object format. */
|
|
44
|
+
queryObjectFormat?: QueryObjectFormat;
|
|
45
|
+
/**
|
|
46
|
+
* Custom error body parser. Defaults to flat shape:
|
|
47
|
+
* { code, message, fields } or a plain-text string as message.
|
|
48
|
+
*/
|
|
49
|
+
parseErrorBody?: ErrorBodyParser;
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/client.d.ts
|
|
53
|
+
/** Client options: TransportOptions plus warn and layers. */
|
|
54
|
+
interface ClientOptions extends TransportOptions {
|
|
55
|
+
/**
|
|
56
|
+
* Where misuse warnings go. Defaults to console.warn, null disables.
|
|
57
|
+
*/
|
|
58
|
+
warn?: ((message: string) => void) | null;
|
|
59
|
+
/**
|
|
60
|
+
* Client layers. Empty by default. Order and stage are described
|
|
61
|
+
* in Layer.
|
|
62
|
+
*/
|
|
63
|
+
layers?: readonly Layer[];
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Builds the pipeline from base transport and layers, validates
|
|
67
|
+
* order.
|
|
68
|
+
*
|
|
69
|
+
* @throws Error on invalid config: empty baseUrl, invalid or too
|
|
70
|
+
* small timeoutMs, unavailable fetch, layer order violation.
|
|
71
|
+
*/
|
|
72
|
+
declare function createClient(options: ClientOptions): Client;
|
|
73
|
+
//#endregion
|
|
74
|
+
export { ApiError, type ApiErrorKind, type Client, type ClientOptions, type ErrorBodyParser, type HttpMethod, type Layer, type LayerContext, type QueryArrayFormat, type QueryObjectFormat, type QueryParamObject, type QueryParamPrimitive, type QueryParamValue, type QueryParams, type RequestConfig, type RequestFn, type RequestOptions, type ResolvedRequestConfig, type ResponseMeta, type ResponseType, type ResponseWithMeta, type StorageLike, createClient, createMemoryStorage, fromWebStorage, toApiError };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,c as t,f as n,h as r,i,n as a,o,p as s,t as c}from"./classify-body-DOG6Vbf_.mjs";import{a as l,o as u,r as d,s as f,t as p}from"./signals-DQjF6ojU.mjs";import{createMemoryStorage as m,fromWebStorage as h}from"./shared/storage.mjs";function g(e){let t=new Set,n=new Map,r=1/0,i;for(let a of e){if(t.has(a.name))throw Error(`createClient: layer "${a.name}" is passed more than once. Each layer must have a unique name.`);if(t.add(a.name),a.stage===void 0)continue;if(!Number.isFinite(a.stage))throw Error(`createClient: layer "${a.name}" has invalid stage ${String(a.stage)}. Stage must be a finite number.`);if(a.stage>r)throw Error(`createClient: layer "${a.name}" (stage ${a.stage}) breaks the order after "${i}" (stage ${r}). Expected descending stage. Built-in stages: withIdempotency=3, withRetry=2, withAuth=1. For a custom layer between withIdempotency and withRetry use stage 2.5, between withRetry and withAuth use stage 1.5.`);let e=n.get(a.stage);if(e!==void 0)throw Error(`createClient: layers "${e}" and "${a.name}" have the same stage ${a.stage}. Order between them would be determined by position in the layers array, which is ambiguous. Use fractional stages (for example 2.5) to make the order explicit.`);n.set(a.stage,a.name),r=a.stage,i=a.name}}function _(e,t,n){let r=Array(t.length),i=e;for(let e=t.length-1;e>=0;e--){let a=t[e].wrap(i,n);i=a.fn,r[e]=a.state}return{pipeline:i,states:r}}function v(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];try{i.attach?.(n,t[r])}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`createClient: layer "${i.name}" attach threw: ${t}`,{cause:e})}}}function y(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t={},n=!1;for(let[r,i]of Object.entries(e))typeof i==`string`&&(t[r]=i,n=!0);return n?t:void 0}function b(e){if(typeof e==`string`&&e.length>0)return{message:e};if(e&&typeof e==`object`){let t=e;return{code:typeof t.code==`string`?t.code:void 0,message:typeof t.message==`string`?t.message:void 0,fields:y(t.fields)}}return{}}var x=class extends TypeError{typeName;constructor(e){super(`Unsupported body type`),this.typeName=e}};function S(e){return new n({kind:`serialize`,code:`BODY_SERIALIZATION_ERROR`,message:`Unsupported value in request body: ${e}. Convert it to a plain object or an array before sending.`})}function C(e){let t=c(e);if(o(t))throw S(a(e));switch(t){case`undefined`:return{body:void 0,contentType:void 0};case`form-data`:return{body:e,contentType:void 0};case`blob`:return{body:e,contentType:e.type||`application/octet-stream`};case`binary`:return{body:e,contentType:`application/octet-stream`};case`stream`:return{body:e,contentType:void 0};case`url-search-params`:return{body:e,contentType:`application/x-www-form-urlencoded;charset=UTF-8`};case`string`:return{body:e,contentType:void 0};case`json`:return w(e)}}function w(e){try{let t=JSON.stringify(e,(e,t)=>{let n=c(t);if(!i(n))throw new x(a(t));return t});if(t===void 0)throw TypeError(`JSON.stringify returned undefined`);return{body:t,contentType:`application/json`}}catch(e){throw e instanceof x?S(e.typeName):new n({kind:`serialize`,code:`BODY_SERIALIZATION_ERROR`,message:`Failed to serialize request body to JSON`,cause:e})}}async function T(e,t,i){if(i?.aborted)throw r(i.reason);try{switch(t){case`json`:{let t=await e.text();return t===``?void 0:JSON.parse(t)}case`text`:return await e.text();case`blob`:return await e.blob();case`arrayBuffer`:return await e.arrayBuffer();case`stream`:return e.body}}catch(a){if(i?.aborted)throw r(i.reason);let o=e.headers.get(`content-type`);throw new n({kind:`parse`,code:`PARSE_ERROR`,message:o?`Failed to parse response body as ${t} (content-type: ${o})`:`Failed to parse response body as ${t}`,status:e.status,isUncertain:e.status<400||e.status>=500,cause:a})}}async function E(e,t){try{let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}catch{if(t?.aborted)throw r(t.reason);return null}}const D=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/;function O(e){if(!e)return;let t=e.trim();if(/^\d+$/.test(t))return Math.max(0,Number(t)*1e3);if(!D.test(t))return;let n=Date.parse(t);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function k(e){return encodeURIComponent(e).replace(/%5B/g,`[`).replace(/%5D/g,`]`)}function A(e){return encodeURIComponent(e)}function j(e){return e.split(`/`).map(e=>{if(e===``)return``;try{return encodeURIComponent(decodeURIComponent(e))}catch{return encodeURIComponent(e)}}).join(`/`)}function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e,t,n,r){if(t==null)return[];if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return[`${k(e)}=${A(String(t))}`];if(Array.isArray(t)){let r=t.filter(e=>e!=null);if(r.length===0)return[];switch(n){case`repeat`:return r.map(t=>`${k(e)}=${A(String(t))}`);case`brackets`:return r.map(t=>`${k(`${e}[]`)}=${A(String(t))}`);case`comma`:return[`${k(e)}=${r.map(e=>A(String(e))).join(`,`)}`]}}if(M(t)){let i=Object.entries(t).sort(([e],[t])=>Number(e>t)-Number(e<t));switch(r){case`brackets`:{let t=[];for(let[a,o]of i)t.push(...N(`${e}[${a}]`,o,n,r));return t}case`dots`:{let t=[];for(let[a,o]of i)t.push(...N(`${e}.${a}`,o,n,r));return t}}}return[]}function P(e,t,n,r=`repeat`,i=`brackets`){let a=`${e.replace(/\/+$/,``)}/${j(t.replace(/^\//,``))}`;if(!n)return a;let o=[];for(let e of Object.keys(n).sort()){let t=N(e,n[e],r,i);for(let e of t)o.push(e)}return o.length>0?`${a}?${o.join(`&`)}`:a}function F(e){return e===`json`?`application/json`:e===`text`?`text/plain`:`*/*`}function I(t){let{baseUrl:i,timeoutMs:a=1e4,fetch:o=globalThis.fetch,credentials:c,defaultHeaders:m,queryArrayFormat:h=`repeat`,queryObjectFormat:g=`brackets`}=t,_=t.parseErrorBody??b;return async function(t){d(t.signal);let v=t.method??`GET`,y=t.timeoutMs??a,b=p(y),x=t.signal?AbortSignal.any([t.signal,b.signal]):b.signal;try{let r=P(i,t.path,t.query,t.queryArrayFormat??h,t.queryObjectFormat??g),a=v===`HEAD`||v===`OPTIONS`?`text`:`json`,d=t.responseType??a,p=t.includeResponseMeta===!0,y=F(d),b=u({Accept:y},m,t.headers),{body:S,contentType:w}=C(t.body);w!==void 0&&l(b,`Content-Type`)===void 0&&f(b,`Content-Type`,w);let D={...t.fetchOptions,method:v,headers:b,body:S,signal:x},k=t.credentials??c;k!==void 0&&(D.credentials=k),e(S)&&(D.duplex=`half`);let A;try{A=await o(r,D)}catch(e){throw s(e)}let j={status:A.status,headers:A.headers,requestId:A.headers.get(`X-Request-Id`)??void 0,retryAfterMs:O(A.headers.get(`Retry-After`))};if(A.status===204||A.status===304)return p?{data:void 0,meta:j}:void 0;if(!A.ok){let e=await E(A,x),t=_(e);throw new n({kind:`http`,status:A.status,code:t.code??`HTTP_${A.status}`,message:t.message??`HTTP ${A.status}`,fields:t.fields,requestId:j.requestId,retryAfterMs:j.retryAfterMs,rawBody:e,details:t.details,isUncertain:A.status>=500})}if(!A.body||v===`HEAD`||v===`OPTIONS`)return p?{data:void 0,meta:j}:void 0;let M=await T(A,d,x);return p?{data:M,meta:j}:M}catch(e){throw r(e)}finally{b.clear()}}}function L(e){return{...e,headers:e.headers?u(e.headers):void 0}}function R(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<100)throw Error(`${t}: timeoutMs must be a number >= 100 ms, got ${String(e)}`)}function z(e){if(e===void 0)return e=>console.warn(e);if(e!==null)return e}function B(e){V(e);let i=e.layers??[];g(i);let a={warn:z(e.warn)},{pipeline:o,states:s}=_(I(e),i,a),c=G(async e=>{let i=L(e),a;try{t(i.path,`client: path`),i.timeoutMs!==void 0&&R(i.timeoutMs,`client`),a={...i,method:(i.method??`GET`).toUpperCase()}}catch(e){throw new n({kind:`unknown`,code:`INVALID_REQUEST_CONFIG`,message:e instanceof Error?e.message:String(e),cause:e})}try{return await o(a)}catch(e){throw r(e)}});return v(i,s,c),c}function V(e){if(t(e.baseUrl,`createClient: baseUrl`),e.timeoutMs!==void 0&&R(e.timeoutMs,`createClient`),typeof(e.fetch??globalThis.fetch)!=`function`)throw Error(`createClient: fetch is not available. Pass it via the fetch option or use an environment with a global fetch (Node >= 20, modern browser).`)}function H(e,t){return(n,r)=>e({...r,path:n,method:t})}function U(e,t){return(n,r,i)=>e({...i,path:n,method:t,body:r})}function W(e,t){return(n,r)=>e({...r,path:n,method:t,includeResponseMeta:!0})}function G(e){return{request:t=>e(t),requestWithMeta:t=>e({...t,includeResponseMeta:!0}),get:H(e,`GET`),post:U(e,`POST`),put:U(e,`PUT`),patch:U(e,`PATCH`),delete:U(e,`DELETE`),head:W(e,`HEAD`),options:W(e,`OPTIONS`)}}export{n as ApiError,B as createClient,m as createMemoryStorage,h as fromWebStorage,r as toApiError};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { i as HttpMethod, t as Layer, u as QueryParams } from "./layer-D1S2Wlu1.mjs";
|
|
2
|
+
//#region src/layers/idempotency/types.d.ts
|
|
3
|
+
/** Input for the source: decide between a new key and the old one. */
|
|
4
|
+
interface IdempotencyContext {
|
|
5
|
+
path: string;
|
|
6
|
+
method: HttpMethod;
|
|
7
|
+
/** Feeds the fingerprint. */
|
|
8
|
+
body: unknown;
|
|
9
|
+
/**
|
|
10
|
+
* Feeds the fingerprint: POST /orders?type=a and POST /orders?type=b
|
|
11
|
+
* with the same body get different keys.
|
|
12
|
+
*/
|
|
13
|
+
query?: QueryParams;
|
|
14
|
+
/** Explicit scope. Defaults to "${method} ${path}". */
|
|
15
|
+
scope?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* - success: server confirmed, the key is no longer needed;
|
|
19
|
+
* - definite-failure: 4xx except 408 and 429. The key can be released;
|
|
20
|
+
* - indefinite-failure: network, timeout, 5xx, 408, 429, cancel.
|
|
21
|
+
* The key must be kept.
|
|
22
|
+
*/
|
|
23
|
+
type IdempotencyOutcome = 'success' | 'definite-failure' | 'indefinite-failure';
|
|
24
|
+
/**
|
|
25
|
+
* Idempotency key source. Implemented by the app or taken from
|
|
26
|
+
* createSessionSource.
|
|
27
|
+
*
|
|
28
|
+
* Methods are synchronous: two parallel nextKey calls for the same
|
|
29
|
+
* (scope, fingerprint) pair cannot both see that the key is missing.
|
|
30
|
+
*/
|
|
31
|
+
interface IdempotencySource {
|
|
32
|
+
/**
|
|
33
|
+
* Key for the request: new or stored.
|
|
34
|
+
*
|
|
35
|
+
* @throws On storage error. The client wraps the exception in
|
|
36
|
+
* ApiError and does not send the request.
|
|
37
|
+
*/
|
|
38
|
+
nextKey(context: IdempotencyContext): string;
|
|
39
|
+
/**
|
|
40
|
+
* Operation outcome. Releases the key on success and
|
|
41
|
+
* definite-failure, keeps it on indefinite-failure. Exceptions
|
|
42
|
+
* are ignored.
|
|
43
|
+
*/
|
|
44
|
+
resolve?(context: IdempotencyContext, outcome: IdempotencyOutcome): void;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/layers/idempotency/layer.d.ts
|
|
48
|
+
interface IdempotencyOptions {
|
|
49
|
+
/**
|
|
50
|
+
* Header name. Defaults to Idempotency-Key. Some servers use
|
|
51
|
+
* X-Idempotency-Key.
|
|
52
|
+
*/
|
|
53
|
+
headerName?: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* For mutating methods adds the idempotency header with the value
|
|
57
|
+
* from the source. If the app set the header itself, the layer does
|
|
58
|
+
* not interfere. After completion reports the outcome to the source.
|
|
59
|
+
*
|
|
60
|
+
* Sits outside the retry layer: the key is generated once for the
|
|
61
|
+
* whole operation, including retries, resolve is called once.
|
|
62
|
+
*
|
|
63
|
+
* Marks the config with an idempotency marker so withRetry does not
|
|
64
|
+
* emit a false unsafe retry warning. The marker is set both for a
|
|
65
|
+
* generated key and for a manual one.
|
|
66
|
+
*/
|
|
67
|
+
declare function withIdempotency(source: IdempotencySource, options?: IdempotencyOptions): Layer;
|
|
68
|
+
//#endregion
|
|
69
|
+
export { IdempotencySource as a, IdempotencyOutcome as i, withIdempotency as n, IdempotencyContext as r, IdempotencyOptions as t };
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
//#region src/core/types.d.ts
|
|
2
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
|
|
3
|
+
/**
|
|
4
|
+
* Format for parsing successful responses. Defaults to json.
|
|
5
|
+
*
|
|
6
|
+
* - json: empty body returns undefined, not an error;
|
|
7
|
+
* - text: CSV, HTML, plain text;
|
|
8
|
+
* - blob: binary data with a MIME type;
|
|
9
|
+
* - arrayBuffer: binary data without a MIME type;
|
|
10
|
+
* - stream: ReadableStream<Uint8Array>.
|
|
11
|
+
*/
|
|
12
|
+
type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream';
|
|
13
|
+
/** Numbers and booleans are stringified automatically. */
|
|
14
|
+
type QueryParamPrimitive = string | number | boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Primitive, array of primitives, or nested object. undefined and
|
|
17
|
+
* null are skipped.
|
|
18
|
+
*/
|
|
19
|
+
type QueryParamValue = QueryParamPrimitive | undefined | null | Array<QueryParamPrimitive | undefined | null> | QueryParamObject;
|
|
20
|
+
interface QueryParamObject {
|
|
21
|
+
[key: string]: QueryParamValue;
|
|
22
|
+
}
|
|
23
|
+
type QueryParams = Record<string, QueryParamValue>;
|
|
24
|
+
/**
|
|
25
|
+
* - repeat: ?ids=1&ids=2. Default.
|
|
26
|
+
* - brackets: ?ids[]=1&ids[]=2.
|
|
27
|
+
* - comma: ?ids=1,2.
|
|
28
|
+
*/
|
|
29
|
+
type QueryArrayFormat = 'repeat' | 'brackets' | 'comma';
|
|
30
|
+
/**
|
|
31
|
+
* - brackets: ?filter[status]=active. Default.
|
|
32
|
+
* - dots: ?filter.status=active.
|
|
33
|
+
*/
|
|
34
|
+
type QueryObjectFormat = 'brackets' | 'dots';
|
|
35
|
+
/**
|
|
36
|
+
* HTTP response metadata. Returned by requestWithMeta, head and
|
|
37
|
+
* options.
|
|
38
|
+
*/
|
|
39
|
+
interface ResponseMeta {
|
|
40
|
+
status: number;
|
|
41
|
+
headers: Headers;
|
|
42
|
+
/** X-Request-Id, if server returned one. */
|
|
43
|
+
requestId?: string;
|
|
44
|
+
/** Retry-After in milliseconds, uncapped. */
|
|
45
|
+
retryAfterMs?: number;
|
|
46
|
+
}
|
|
47
|
+
interface ResponseWithMeta<T> {
|
|
48
|
+
data: T;
|
|
49
|
+
meta: ResponseMeta;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Request configuration. In shorthand methods like client.get,
|
|
53
|
+
* path, method and body are set by the method and are not part
|
|
54
|
+
* of RequestOptions.
|
|
55
|
+
*/
|
|
56
|
+
interface RequestConfig {
|
|
57
|
+
/**
|
|
58
|
+
* Path relative to baseUrl, e.g. `/orders`. Without a query
|
|
59
|
+
* string: pass params via query.
|
|
60
|
+
*
|
|
61
|
+
* Segments are encoded automatically: `/users/John Doe` goes out
|
|
62
|
+
* as `/users/John%20Doe`.
|
|
63
|
+
*/
|
|
64
|
+
path: string;
|
|
65
|
+
/** Defaults to GET. */
|
|
66
|
+
method?: HttpMethod;
|
|
67
|
+
/**
|
|
68
|
+
* Body format is inferred from the type: JSON object and array
|
|
69
|
+
* are sent as JSON, FormData as multipart, Blob and File as
|
|
70
|
+
* binary data, ArrayBuffer and TypedArray as
|
|
71
|
+
* application/octet-stream, ReadableStream as a stream,
|
|
72
|
+
* URLSearchParams as form-urlencoded, string as is.
|
|
73
|
+
*
|
|
74
|
+
* An explicit Content-Type is not overwritten.
|
|
75
|
+
*/
|
|
76
|
+
body?: unknown;
|
|
77
|
+
/**
|
|
78
|
+
* Request headers: Record, Headers or an array of pairs. Header
|
|
79
|
+
* names are case-insensitive.
|
|
80
|
+
*/
|
|
81
|
+
headers?: HeadersInit;
|
|
82
|
+
query?: QueryParams;
|
|
83
|
+
/**
|
|
84
|
+
* Abort signal. Merged with the internal timeout: whichever fires
|
|
85
|
+
* first wins, the reason is preserved.
|
|
86
|
+
*/
|
|
87
|
+
signal?: AbortSignal;
|
|
88
|
+
/**
|
|
89
|
+
* Request timeout in ms. Overrides the client's timeoutMs for this
|
|
90
|
+
* request. Must be >= 100.
|
|
91
|
+
*/
|
|
92
|
+
timeoutMs?: number;
|
|
93
|
+
/**
|
|
94
|
+
* Skip auth and 401 handling. For requests that create a session.
|
|
95
|
+
*/
|
|
96
|
+
skipAuth?: boolean;
|
|
97
|
+
/** Skip automatic retries. */
|
|
98
|
+
skipRetry?: boolean;
|
|
99
|
+
/** Skip adding idempotency header. */
|
|
100
|
+
skipIdempotency?: boolean;
|
|
101
|
+
/** Explicit idempotency scope. Defaults to "${method} ${path}". */
|
|
102
|
+
idempotencyScope?: string;
|
|
103
|
+
/** Format for parsing response body. Defaults to json. */
|
|
104
|
+
responseType?: ResponseType;
|
|
105
|
+
/** Cookie mode: omit, same-origin or include. */
|
|
106
|
+
credentials?: RequestCredentials;
|
|
107
|
+
/** Query array format. Overrides the client setting. */
|
|
108
|
+
queryArrayFormat?: QueryArrayFormat;
|
|
109
|
+
/** Query object format. Overrides the client setting. */
|
|
110
|
+
queryObjectFormat?: QueryObjectFormat;
|
|
111
|
+
/**
|
|
112
|
+
* Extra fetch options. method, headers, body, signal, credentials
|
|
113
|
+
* and duplex are ignored.
|
|
114
|
+
*/
|
|
115
|
+
fetchOptions?: Partial<Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal' | 'credentials' | 'duplex'>>;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Config with response metadata flag. Used inside requestWithMeta,
|
|
119
|
+
* head and options: the public RequestConfig does not expose it,
|
|
120
|
+
* otherwise a stray call from JS could get ResponseWithMeta instead
|
|
121
|
+
* of a plain body.
|
|
122
|
+
*
|
|
123
|
+
* @internal
|
|
124
|
+
*/
|
|
125
|
+
interface InternalRequestConfig extends RequestConfig {
|
|
126
|
+
includeResponseMeta?: true;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Internal config: headers are normalized to Record. Layers and
|
|
130
|
+
* transport receive this type after client.ts called mergeHeaders
|
|
131
|
+
* on the public RequestConfig.
|
|
132
|
+
*/
|
|
133
|
+
interface ResolvedRequestConfig extends Omit<InternalRequestConfig, 'headers'> {
|
|
134
|
+
headers?: Record<string, string>;
|
|
135
|
+
/**
|
|
136
|
+
* Set by withIdempotency. withRetry reads the marker to decide
|
|
137
|
+
* whether retrying a mutating method is safe.
|
|
138
|
+
*
|
|
139
|
+
* The field is set both when withIdempotency generated a key and
|
|
140
|
+
* when the app sets it manually. headerName is for debugging,
|
|
141
|
+
* withRetry does not rely on it.
|
|
142
|
+
*
|
|
143
|
+
* @internal
|
|
144
|
+
*/
|
|
145
|
+
idempotency?: {
|
|
146
|
+
headerName: string;
|
|
147
|
+
key: string;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* RequestConfig without path, method and body. Used in shorthand
|
|
152
|
+
* methods like client.get.
|
|
153
|
+
*/
|
|
154
|
+
type RequestOptions = Omit<RequestConfig, 'path' | 'method' | 'body'>;
|
|
155
|
+
/** Low-level request function that the pipeline is built from. */
|
|
156
|
+
type RequestFn = <T = unknown>(config: ResolvedRequestConfig) => Promise<T>;
|
|
157
|
+
/**
|
|
158
|
+
* HTTP client. Created by createClient.
|
|
159
|
+
*
|
|
160
|
+
* get, post, put, patch, delete return parsed body. head and
|
|
161
|
+
* options return { data, meta }: no body, metadata is the main
|
|
162
|
+
* result. requestWithMeta exposes metadata for any HTTP method.
|
|
163
|
+
*/
|
|
164
|
+
interface Client {
|
|
165
|
+
/** Request with any HTTP method. */
|
|
166
|
+
request: <T = unknown>(config: RequestConfig) => Promise<T>;
|
|
167
|
+
/** Request with response metadata: { data, meta }. */
|
|
168
|
+
requestWithMeta: <T = unknown>(config: RequestConfig) => Promise<ResponseWithMeta<T>>;
|
|
169
|
+
get: <T = unknown>(path: string, options?: RequestOptions) => Promise<T>;
|
|
170
|
+
post: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
|
|
171
|
+
put: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
|
|
172
|
+
patch: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
|
|
173
|
+
/**
|
|
174
|
+
* Accepts an optional body. HTTP spec leaves DELETE body semantics
|
|
175
|
+
* undefined, but many APIs support it.
|
|
176
|
+
*/
|
|
177
|
+
delete: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
|
|
178
|
+
/** Headers only. data is always undefined. */
|
|
179
|
+
head: (path: string, options?: RequestOptions) => Promise<ResponseWithMeta<undefined>>;
|
|
180
|
+
/** Allowed methods for a resource. data is always undefined. */
|
|
181
|
+
options: (path: string, options?: RequestOptions) => Promise<ResponseWithMeta<undefined>>;
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
184
|
+
//#region src/core/layer.d.ts
|
|
185
|
+
/**
|
|
186
|
+
* Context that createClient passes to every layer when building the
|
|
187
|
+
* pipeline. Shared by all client layers.
|
|
188
|
+
*/
|
|
189
|
+
interface LayerContext {
|
|
190
|
+
readonly warn?: (message: string) => void;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* fn is the request function produced by this layer. state - a value
|
|
194
|
+
* the layer saves until attach: this is how a layer ties its state
|
|
195
|
+
* to a specific client, even if the same Layer is used across
|
|
196
|
+
* several clients.
|
|
197
|
+
*/
|
|
198
|
+
interface LayerWrapResult {
|
|
199
|
+
fn: RequestFn;
|
|
200
|
+
state?: unknown;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Layer. Passed to ClientOptions.layers from the outside in: the
|
|
204
|
+
* first in the array wraps all subsequent layers, the last receives
|
|
205
|
+
* the base transport.
|
|
206
|
+
*/
|
|
207
|
+
interface Layer {
|
|
208
|
+
/**
|
|
209
|
+
* Name used in validation error messages. Must be unique: a
|
|
210
|
+
* duplicate fails client creation. For built-ins it matches the
|
|
211
|
+
* factory name.
|
|
212
|
+
*/
|
|
213
|
+
readonly name: string;
|
|
214
|
+
/**
|
|
215
|
+
* Priority: higher means further outside. Layers must go in
|
|
216
|
+
* descending stage order. If omitted, the layer skips order
|
|
217
|
+
* validation. Built-ins: withIdempotency: 3, withRetry: 2,
|
|
218
|
+
* withAuth: 1. To insert between built-ins: 2.5 - between
|
|
219
|
+
* withIdempotency and withRetry, 1.5 - between withRetry
|
|
220
|
+
* and withAuth.
|
|
221
|
+
*/
|
|
222
|
+
readonly stage?: number;
|
|
223
|
+
/**
|
|
224
|
+
* Wraps the next function in the pipeline. Called from the inside
|
|
225
|
+
* out: the last layer in the array receives the base transport.
|
|
226
|
+
* state is passed back to the same layer's attach.
|
|
227
|
+
*/
|
|
228
|
+
wrap(next: RequestFn, context: LayerContext): LayerWrapResult;
|
|
229
|
+
/**
|
|
230
|
+
* Called after client creation. For service functions that need
|
|
231
|
+
* the client itself (resetRefreshCircuit). state is what wrap
|
|
232
|
+
* returned for this client. An exception aborts createClient;
|
|
233
|
+
* the message includes the layer name.
|
|
234
|
+
*/
|
|
235
|
+
attach?(client: Client, state: unknown): void;
|
|
236
|
+
}
|
|
237
|
+
//#endregion
|
|
238
|
+
export { ResponseWithMeta as _, QueryArrayFormat as a, QueryParamPrimitive as c, RequestConfig as d, RequestFn as f, ResponseType as g, ResponseMeta as h, HttpMethod as i, QueryParamValue as l, ResolvedRequestConfig as m, LayerContext as n, QueryObjectFormat as o, RequestOptions as p, Client as r, QueryParamObject as s, Layer as t, QueryParams as u };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { m as ResolvedRequestConfig, t as Layer } from "./layer-D1S2Wlu1.mjs";
|
|
2
|
+
import { t as ApiError } from "./errors-CSZuncD0.mjs";
|
|
3
|
+
//#region src/layers/retry/layer.d.ts
|
|
4
|
+
interface RetryOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Max attempts, including the first one. Defaults to 3, minimum 1.
|
|
7
|
+
*/
|
|
8
|
+
maxAttempts?: number;
|
|
9
|
+
/**
|
|
10
|
+
* Initial delay in milliseconds. Defaults to 300. Values below
|
|
11
|
+
* MIN_RETRY_MS are raised to the minimum.
|
|
12
|
+
*/
|
|
13
|
+
baseDelayMs?: number;
|
|
14
|
+
/**
|
|
15
|
+
* Upper bound of the delay. Defaults to 10000. Caps the computed
|
|
16
|
+
* delay and acts as threshold for Retry-After: if the server asked
|
|
17
|
+
* for more, the retry is skipped.
|
|
18
|
+
*
|
|
19
|
+
* Must be >= baseDelayMs after it was raised to MIN_RETRY_MS,
|
|
20
|
+
* otherwise withRetry throws.
|
|
21
|
+
*/
|
|
22
|
+
maxDelayMs?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Spread around the computed delay, defaults to 0.15 (+-15%).
|
|
25
|
+
* 0 disables the spread, 1 gives +-100%. Not applied to
|
|
26
|
+
* Retry-After. Value in [0, 1].
|
|
27
|
+
*/
|
|
28
|
+
jitterRatio?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Warn about a mutating retry without idempotency header. Defaults
|
|
31
|
+
* to true.
|
|
32
|
+
*
|
|
33
|
+
* No warning when withIdempotency applied a key, the app set
|
|
34
|
+
* Idempotency-Key itself, or passed skipIdempotency: true. Once per
|
|
35
|
+
* method and root path segment: for DELETE /sessions/123 the root
|
|
36
|
+
* segment is sessions.
|
|
37
|
+
*/
|
|
38
|
+
warnOnUnsafeRetry?: boolean;
|
|
39
|
+
/** Retry network errors (kind network). Defaults to true. */
|
|
40
|
+
retryOnNetwork?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Retry timeouts (kind timeout). Defaults to true. For unsafe
|
|
43
|
+
* methods a retry without Idempotency-Key may create a duplicate.
|
|
44
|
+
*/
|
|
45
|
+
retryOnTimeout?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Retry policy. Defaults to isRetryable, adjusted by retryOnNetwork
|
|
48
|
+
* and retryOnTimeout. Cancel and auth errors are not retried even
|
|
49
|
+
* if the function returns true.
|
|
50
|
+
*
|
|
51
|
+
* On callback failure the default policy is used, the error goes
|
|
52
|
+
* to warn.
|
|
53
|
+
*
|
|
54
|
+
* @param attempt - failed attempt number, 1-based.
|
|
55
|
+
*/
|
|
56
|
+
shouldRetry?: (error: ApiError, attempt: number) => boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Delay before retry. Not applied when the server sent Retry-After.
|
|
59
|
+
* Result is clamped to [MIN_RETRY_MS, maxDelayMs].
|
|
60
|
+
*
|
|
61
|
+
* On callback failure the default delay is used, the error goes
|
|
62
|
+
* to warn.
|
|
63
|
+
*
|
|
64
|
+
* @param attempt - failed attempt number, 1-based.
|
|
65
|
+
*/
|
|
66
|
+
computeDelay?: (attempt: number, error: ApiError) => number;
|
|
67
|
+
/**
|
|
68
|
+
* Before each retry. May return a new config (e.g. replace
|
|
69
|
+
* Idempotency-Key on 409) or stop retries by returning
|
|
70
|
+
* skipRetry: true - the error is rethrown at once.
|
|
71
|
+
*
|
|
72
|
+
* @param attempt - attempt number from 1. First retry: attempt === 1.
|
|
73
|
+
*/
|
|
74
|
+
onBeforeRetry?: (config: ResolvedRequestConfig, attempt: number, error: ApiError) => ResolvedRequestConfig | void;
|
|
75
|
+
/** Pause between attempts. Defaults to setTimeout with abort. */
|
|
76
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Automatic retry layer.
|
|
80
|
+
*
|
|
81
|
+
* Retries network errors, timeouts, 5xx, 408 and 429. Does not retry
|
|
82
|
+
* cancel, auth errors and other 4xx.
|
|
83
|
+
*
|
|
84
|
+
* Delays are exponential with +-15% spread (300, 600, 1200 ms), upper
|
|
85
|
+
* bound is maxDelayMs.
|
|
86
|
+
*
|
|
87
|
+
* Retry-After from the response replaces the computed delay. If the
|
|
88
|
+
* value is above maxDelayMs, the retry is skipped: the server asks to
|
|
89
|
+
* wait longer than the app is ready to.
|
|
90
|
+
*
|
|
91
|
+
* Retries are disabled for streaming bodies: a stream is single-use,
|
|
92
|
+
* a second fetch throws TypeError, which transport takes for a
|
|
93
|
+
* network error.
|
|
94
|
+
*
|
|
95
|
+
* @throws Error on invalid options.
|
|
96
|
+
*/
|
|
97
|
+
declare function withRetry(options?: RetryOptions): Layer;
|
|
98
|
+
//#endregion
|
|
99
|
+
export { withRetry as n, RetryOptions as t };
|