1000fetches 0.1.6 → 0.1.7
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.cjs.js +1 -1
- package/dist/index.d.ts +3 -28
- package/dist/index.es.js +0 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class e extends Error{name="HttpError";status;statusText;data;response;url;method;cause;constructor(e,t,r,a,s,n,o,i){super(`HTTP ${t} ${r}: ${e} (${o} ${n})`,{cause:i}),this.status=t,this.statusText=r,this.data=a,this.response=s,this.url=n,this.method=o}}class t extends Error{name="NetworkError";cause;constructor(e,t){super(e,{cause:t})}}class r extends Error{name="SchemaValidationError";schema;data;cause;constructor(e,t,r,a){super(e,{cause:a}),this.schema=t,this.data=r}}class a extends Error{name="TimeoutError";cause;constructor(e,t){super(e,{cause:t})}}class s extends Error{name="PathParameterError";url;requiredParams;providedParams;cause;constructor(e,t,r,a,s){super(e,{cause:s}),this.url=t,this.requiredParams=r,this.providedParams=a}}class n extends Error{name="MiddlewareError";interceptorType;url;method;cause;constructor(e,t,r,a,s){super(e,{cause:s}),this.interceptorType=t,this.url=r,this.method=a}}class o extends Error{name="SerializationError";cause;constructor(e,t){super(e,{cause:t})}}class i extends Error{name="InvalidSchemaError";schema;cause;constructor(e,t,r){super(e,{cause:r}),this.schema=t}}class c extends Error{name="AsyncSchemaValidationError";schema;cause;constructor(e,t,r){super(e,{cause:r}),this.schema=t}}class d extends Error{name="InvalidBaseUrlError";baseUrl;cause;constructor(e,t,r){super(e,{cause:r}),this.baseUrl=t}}function u(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"~standard"in e&&"object"==typeof e["~standard"]&&null!==e["~standard"]&&"validate"in e["~standard"]&&"function"==typeof e["~standard"].validate&&"version"in e["~standard"]&&"number"==typeof e["~standard"].version&&"vendor"in e["~standard"]&&"string"==typeof e["~standard"].vendor}function l(){return{validate(e,t){if(!u(e))throw new i("Schema must implement the Standard Schema interface",e);const a=e["~standard"].validate(t);if(a instanceof Promise)throw new c("Async Standard Schema validation is not supported in this context",e);if(a.issues)throw new r(JSON.stringify(a.issues),e,t);return a.value},isSchema:e=>u(e)}}function h(e,t,r){let a=0;return new ReadableStream({async start(s){try{for(;;){const{done:n,value:o}=await e.read();if(n)break;a+=o.length,t(o,r,a),s.enqueue(o)}}finally{e.releaseLock(),s.close()}}})}async function f(e,t){if(!t||!e.body)return e;const r=h(e.body.getReader(),(e,r,a)=>{t({chunk:e,totalBytes:r,transferredBytes:a})},e.headers.get("content-length")?parseInt(e.headers.get("content-length")||"0",10):0);return new Request(e.url,{method:e.method,headers:e.headers,body:r,signal:e.signal,credentials:e.credentials,cache:e.cache,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,integrity:e.integrity,keepalive:e.keepalive,duplex:"half"})}async function m(e,t){if(!t||!e.body)return e;const r=h(e.body.getReader(),(e,r,a)=>{t({chunk:e,totalBytes:r,transferredBytes:a})},e.headers.get("content-length")?parseInt(e.headers.get("content-length")||"0",10):void 0);return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}const p={maxRetries:3,retryDelay:300,backoffFactor:2,retryStatusCodes:[429,500,502,503,504],retryNetworkErrors:!0,maxRetryDelay:3e4,shouldRetry:()=>!0};function y(e={}){const{baseUrl:t="",headers:r={},timeout:o=3e4,schemaValidator:i=l(),fetch:c=fetch,serializeBody:d,serializeParams:u,onRequestMiddleware:h,onResponseMiddleware:y}=e;return async function(l,T={}){const{method:v="GET",headers:R={},params:P,pathParams:U,body:O,schema:$,timeout:k=o,signal:q,credentials:A,cache:j,mode:B,redirect:L,onUploadStreaming:M,onDownloadStreaming:N,validateStatus:H,responseType:C,retryOptions:D}=T;let
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class e extends Error{name="HttpError";status;statusText;data;response;url;method;cause;constructor(e,t,r,a,s,n,o,i){super(`HTTP ${t} ${r}: ${e} (${o} ${n})`,{cause:i}),this.status=t,this.statusText=r,this.data=a,this.response=s,this.url=n,this.method=o}}class t extends Error{name="NetworkError";cause;constructor(e,t){super(e,{cause:t})}}class r extends Error{name="SchemaValidationError";schema;data;cause;constructor(e,t,r,a){super(e,{cause:a}),this.schema=t,this.data=r}}class a extends Error{name="TimeoutError";cause;constructor(e,t){super(e,{cause:t})}}class s extends Error{name="PathParameterError";url;requiredParams;providedParams;cause;constructor(e,t,r,a,s){super(e,{cause:s}),this.url=t,this.requiredParams=r,this.providedParams=a}}class n extends Error{name="MiddlewareError";interceptorType;url;method;cause;constructor(e,t,r,a,s){super(e,{cause:s}),this.interceptorType=t,this.url=r,this.method=a}}class o extends Error{name="SerializationError";cause;constructor(e,t){super(e,{cause:t})}}class i extends Error{name="InvalidSchemaError";schema;cause;constructor(e,t,r){super(e,{cause:r}),this.schema=t}}class c extends Error{name="AsyncSchemaValidationError";schema;cause;constructor(e,t,r){super(e,{cause:r}),this.schema=t}}class d extends Error{name="InvalidBaseUrlError";baseUrl;cause;constructor(e,t,r){super(e,{cause:r}),this.baseUrl=t}}function u(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"~standard"in e&&"object"==typeof e["~standard"]&&null!==e["~standard"]&&"validate"in e["~standard"]&&"function"==typeof e["~standard"].validate&&"version"in e["~standard"]&&"number"==typeof e["~standard"].version&&"vendor"in e["~standard"]&&"string"==typeof e["~standard"].vendor}function l(){return{validate(e,t){if(!u(e))throw new i("Schema must implement the Standard Schema interface",e);const a=e["~standard"].validate(t);if(a instanceof Promise)throw new c("Async Standard Schema validation is not supported in this context",e);if(a.issues)throw new r(JSON.stringify(a.issues),e,t);return a.value},isSchema:e=>u(e)}}function h(e,t,r){let a=0;return new ReadableStream({async start(s){try{for(;;){const{done:n,value:o}=await e.read();if(n)break;a+=o.length,t(o,r,a),s.enqueue(o)}}finally{e.releaseLock(),s.close()}}})}async function f(e,t){if(!t||!e.body)return e;const r=h(e.body.getReader(),(e,r,a)=>{t({chunk:e,totalBytes:r,transferredBytes:a})},e.headers.get("content-length")?parseInt(e.headers.get("content-length")||"0",10):0);return new Request(e.url,{method:e.method,headers:e.headers,body:r,signal:e.signal,credentials:e.credentials,cache:e.cache,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,integrity:e.integrity,keepalive:e.keepalive,duplex:"half"})}async function m(e,t){if(!t||!e.body)return e;const r=h(e.body.getReader(),(e,r,a)=>{t({chunk:e,totalBytes:r,transferredBytes:a})},e.headers.get("content-length")?parseInt(e.headers.get("content-length")||"0",10):void 0);return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}const p={maxRetries:3,retryDelay:300,backoffFactor:2,retryStatusCodes:[429,500,502,503,504],retryNetworkErrors:!0,maxRetryDelay:3e4,shouldRetry:()=>!0};function y(e={}){const{baseUrl:t="",headers:r={},timeout:o=3e4,schemaValidator:i=l(),fetch:c=fetch,serializeBody:d,serializeParams:u,onRequestMiddleware:h,onResponseMiddleware:y}=e;return async function(l,T={}){const{method:v="GET",headers:R={},params:P,pathParams:U,body:O,schema:$,timeout:k=o,signal:q,credentials:A,cache:j,mode:B,redirect:L,onUploadStreaming:M,onDownloadStreaming:N,validateStatus:H,responseType:C,retryOptions:D}=T;let z=function(e,t={}){return e.replace(/:([a-zA-Z0-9_]+)/g,(r,a)=>{if(void 0===t[a])throw new s(`Missing required path parameter: ${a}`,e,[a],Object.keys(t));return String(t[a])})}(l,U);t&&(z=new URL(z,t).toString());let I={url:z,method:v,params:P,headers:new Headers({...r,...R}),body:O,signal:q,fetchOptions:{credentials:A,cache:j,mode:B,redirect:L}};if(h)try{I=await h(I)}catch(_){throw new n(x("Request middleware failed",_),"request",I.url,I.method,_ instanceof Error?_:void 0)}if(I.params){const e=new URL(I.url),t=u?u(I.params):new URLSearchParams(JSON.parse(JSON.stringify(I.params))).toString();if(t){const r=u&&t.startsWith("?")?t.slice(1):t;e.search=r}I.url=e.toString()}const J={method:I.method,headers:I.headers,...I.fetchOptions};if(void 0!==I.body&&("POST"===I.method||"PUT"===I.method||"PATCH"===I.method)){let e,t;if(d){const r=d(I.body);null==r?e="":(e=r,E(I.body)&&"string"==typeof r&&!I.headers.has("content-type")&&(t="application/json"))}else{const r=function(e){if("string"==typeof e||e instanceof FormData||e instanceof URLSearchParams||e instanceof ArrayBuffer||e instanceof Blob||e instanceof ReadableStream)return{body:e};if(E(e))return{body:JSON.stringify(e),contentType:"application/json"};return{body:e}}(I.body);e=r.body,t=r.contentType}J.body=e,t&&I.headers.set("content-type",t),J.duplex="half"}const V={...p,...e.retryOptions,...D},F=V.maxRetries;let W;for(let e=0;e<=F;e+=1){const t=new AbortController,r=setTimeout(()=>t.abort(),k),s=I.signal?(()=>{if(I.signal&&I.signal.aborted)return I.signal;const e=new AbortController,a=()=>{clearTimeout(r),e.abort()};return I.signal?.addEventListener("abort",a),t.signal.addEventListener("abort",a),e.signal})():t.signal;try{const e=new Request(I.url,J),t=M?await f(e,M):e,r=await c(t.url,{method:t.method,headers:t.headers,body:t.body,signal:s,...I.fetchOptions,...t.body&&{duplex:"half"}}),a=N?await m(r,N):r,o=await w(a,{validateStatus:H,schema:$,responseType:C},v,I.url,i);if(y)try{return await y(o)}catch(_){throw new n(x("Response middleware failed",_),"response",I.url,v,_ instanceof Error?_:void 0)}return o}catch(_){if(clearTimeout(r),W=_ instanceof Error?_:new Error(String(_)),"AbortError"===W.name&&(W=new a(`Request timeout after ${k}ms`,W)),e<F&&await b(W,e,V)){const t=g(e,V);await S(t);continue}throw W}}throw W||new Error("Request failed")}}async function w(t,a,s,n,i){const c=Object.fromEntries(t.headers.entries()),d=a.validateStatus||(e=>e>=200&&e<300);let u;try{if("text"===a.responseType)u=await t.text();else if("blob"===a.responseType)u=await t.blob();else if("arrayBuffer"===a.responseType)u=await t.arrayBuffer();else{const e=t.headers.get("content-type");u=e?.includes("application/json")?await t.json():e?.includes("text/")?await t.text():await t.arrayBuffer()}}catch(h){throw new o(x("Failed to parse response body",h),h instanceof Error?h:void 0)}if(!d(t.status))throw new e(`HTTP ${t.status} ${t.statusText}`,t.status,t.statusText,u,t,n,s);const l={data:u,status:t.status,statusText:t.statusText,headers:c,method:s,url:n,raw:t};if(a.schema)try{l.data=i.validate(a.schema,l.data)}catch(h){throw new r(`Schema validation failed: ${h instanceof Error?h.message:String(h)}`,a.schema,l.data,h instanceof Error?h:void 0)}return l}async function b(r,a,s){return!!s&&(s.shouldRetry?await s.shouldRetry(r,a):r instanceof e?s.retryStatusCodes?.includes(r.status)??!1:(r instanceof t||"TypeError"===r.name)&&(s.retryNetworkErrors??!1))}function g(e,t){if(!t)return 0;const r=t.retryDelay??300,a=t.backoffFactor??2,s=t.maxRetryDelay??3e4,n=r*Math.pow(a,e);return Math.min(n,s)}function E(e){return e&&"object"==typeof e&&"Object"===e.constructor?.name||Array.isArray(e)||"function"==typeof e?.toJSON}function x(e,t){return`${e}: ${t instanceof Error?t.message:String(t)}`}function S(e){return new Promise(t=>setTimeout(t,e))}function T(e){const t="undefined"!=typeof window&&void 0!==window.location&&"null"!==window.location.origin;if(!e)return t?window.location.origin:"";if(e.startsWith("/"))return t?new URL(e,window.location.origin).href.replace(/\/$/,""):e.replace(/\/$/,"");try{new URL(e)}catch{throw new d(`Invalid baseUrl: "${e}". Must be a valid absolute URL or relative path starting with "/".`,e)}return e.endsWith("/")?e.slice(0,-1):e}function v(e){const t=e;return t.data=async()=>(await e).data,t}function R(e={}){const t=y({...e,baseUrl:T(e.baseUrl)});return{get:function(e,...r){return v(t(e,{...r[0],method:"GET"}))},post:(e,r,...a)=>v(t(e,{...a[0],method:"POST",body:r})),put:(e,r,...a)=>v(t(e,{...a[0],method:"PUT",body:r})),patch:(e,r,...a)=>v(t(e,{...a[0],method:"PATCH",body:r})),delete:(e,...r)=>v(t(e,{...r[0],method:"DELETE"})),request:(e,r)=>v(t(e,r))}}const P=R();exports.AsyncSchemaValidationError=c,exports.HttpError=e,exports.MiddlewareError=n,exports.NetworkError=t,exports.PathParameterError=s,exports.SchemaValidationError=r,exports.SerializationError=o,exports.TimeoutError=a,exports.createHttpClient=R,exports.default=P,exports.http=P;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -33,29 +33,6 @@ export declare function createHttpClient(config?: HttpClientConfig): {
|
|
|
33
33
|
request: <Path extends string = string, TResponse = unknown, TBody = unknown, TParams extends RequestParamsType = RequestParamsType>(url: Path, options?: HttpRequestOptions<TBody, TResponse, TParams>) => ResponsePromise<TResponse>;
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
-
/**
|
|
37
|
-
* Create a default schema validator that supports Standard Schema.
|
|
38
|
-
*
|
|
39
|
-
* This validator only works with schemas that implement the Standard Schema
|
|
40
|
-
* interface. For full support of Zod, Valibot, and Arktype, use the
|
|
41
|
-
* appropriate validator from their respective packages.
|
|
42
|
-
*
|
|
43
|
-
* @returns A schema validator instance
|
|
44
|
-
*
|
|
45
|
-
* @example
|
|
46
|
-
* ```ts
|
|
47
|
-
* import { createSchemaValidator } from '1000fetches'
|
|
48
|
-
*
|
|
49
|
-
* const validator = createSchemaValidator();
|
|
50
|
-
*
|
|
51
|
-
* // Use with HttpClient
|
|
52
|
-
* const client = new HttpClient({
|
|
53
|
-
* schemaValidator: validator
|
|
54
|
-
* });
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
export declare function createSchemaValidator(): SchemaValidator;
|
|
58
|
-
|
|
59
36
|
declare type CustomFetch = typeof fetch;
|
|
60
37
|
|
|
61
38
|
declare interface DownloadStreamingEvent {
|
|
@@ -181,15 +158,13 @@ export declare interface HttpRequestOptions<TBody = unknown, TResponse = unknown
|
|
|
181
158
|
|
|
182
159
|
/**
|
|
183
160
|
* Infer the output type from a Schema
|
|
184
|
-
* For Zod schemas
|
|
161
|
+
* For Zod schemas, we use z.infer (same as schemaOf)
|
|
185
162
|
* For other StandardSchemaV1 schemas, we use StandardSchemaV1.InferOutput
|
|
186
163
|
*/
|
|
187
|
-
declare type InferSchemaOutput<ResponseSchema extends StandardSchemaV1> =
|
|
188
|
-
ResponseSchema
|
|
189
|
-
] extends [{
|
|
164
|
+
declare type InferSchemaOutput<ResponseSchema extends StandardSchemaV1> = ResponseSchema extends {
|
|
190
165
|
_def: any;
|
|
191
166
|
parse: (data: any) => infer T;
|
|
192
|
-
}
|
|
167
|
+
} ? T : StandardSchemaV1.InferOutput<ResponseSchema>;
|
|
193
168
|
|
|
194
169
|
export declare class MiddlewareError extends Error implements HttpClientError {
|
|
195
170
|
readonly name = "MiddlewareError";
|
package/dist/index.es.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "1000fetches",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "A type-first HTTP client with compile-time path validation, schema validation, middleware, retries, and real-time streaming — powered by native fetch. Supports Zod, Valibot, ArkType, and any Standard Schema-compatible library.",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"module": "dist/index.es.js",
|