@superutils/fetch 1.5.16 → 1.5.18

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.ts CHANGED
@@ -1,8 +1,6 @@
1
- import * as _superutils_core from '@superutils/core';
2
- import { ValueOrPromise, DropFirst } from '@superutils/core';
3
- import * as _superutils_promise from '@superutils/promise';
4
1
  import { RetryOptions, RetryIfFunc, TimeoutOptions, IPromisE_Timeout, DeferredAsyncOptions } from '@superutils/promise';
5
2
  export { DeferredAsyncOptions, OnEarlyFinalize, OnFinalize, ResolveError, ResolveIgnored, RetryIfFunc, RetryOptions, TIMEOUT_FALLBACK, TIMEOUT_MAX, TimeoutOptions, TimeoutPromise } from '@superutils/promise';
3
+ import { ValueOrPromise, DropFirst } from '@superutils/core';
6
4
 
7
5
  /** Commonly used content types for easier access */
8
6
  declare const ContentType: {
@@ -279,6 +277,13 @@ type FetchCustomOptions = {
279
277
  abortCtrl?: AbortController;
280
278
  body?: PostArgs[1];
281
279
  errMsgs?: FetchErrMsgs;
280
+ /**
281
+ * If set to `true`, the global `fetch.defaults` (including global headers, interceptors,
282
+ * and timeout settings) will not be merged into the options for this request.
283
+ *
284
+ * Default: `false`
285
+ */
286
+ ignoreGlobalDefaults?: boolean;
282
287
  /**
283
288
  * Custom fetch function to use instead of the global `fetch`.
284
289
  * Useful for testing or using a different fetch implementation (e.g. `node-fetch` in older Node versions).
@@ -314,7 +319,7 @@ type FetchFunc = (...args: FetchArgs) => Promise<Response>;
314
319
  */
315
320
  type FetchOptions = Omit<RequestInit, 'body'> & FetchCustomOptions;
316
321
  /** Default fetch options */
317
- type FetchOptionsDefault = Omit<FetchOptionsInterceptor, 'abortCtrl' | 'as' | 'body' | 'method' | 'signal' | 'timeout' | 'headers'> & {
322
+ type FetchOptionsDefault = Omit<FetchOptionsInterceptor, 'abortCtrl' | 'as' | 'body' | 'ignoreGlobalDefaults' | 'method' | 'signal' | 'timeout' | 'headers'> & {
318
323
  /**
319
324
  * Request headers.
320
325
  *
@@ -645,6 +650,75 @@ commonOptions?: PostOptions & CommonOptions, commonDeferOptions?: DeferredAsyncO
645
650
  deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ExcludePostOptions<FixedOptions> | undefined = ExcludePostOptions<FixedOptions> | undefined, Delay extends CommonDelay | number = number>(deferOptions?: DeferredAsyncOptions<ThisArg, Delay>, defaultUrl?: DefaultUrl, defaultData?: DefaultData, defaultOptions?: DefaultOptions): <T extends ClientData<FixedOptions> = never, Options_1 extends ExcludePostOptions<FixedOptions> | undefined = ExcludePostOptions<FixedOptions> | undefined, TReturn = GetFetchResult<[FixedOptions, Options_1, DefaultOptions, CommonOptions], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options_1>) => IPromise_Fetch<TReturn>;
646
651
  };
647
652
 
653
+ /**
654
+ * Configuration for the ApiClient instance.
655
+ */
656
+ type ApiClientConfig<
657
+ /** Options that are enforced for every request and cannot be overridden. */
658
+ FixedOptions extends ApiClientFetchOptions,
659
+ /** Default options that can be overridden by individual request calls. */
660
+ CommonOptions extends ExcludeOptions<FixedOptions, ApiClientFetchOptions>, CommonDelay extends number> = {
661
+ commonOptions?: CommonOptions;
662
+ commonDeferOptions?: DeferredAsyncOptions<unknown, CommonDelay>;
663
+ errorPrefix?: string;
664
+ fixedOptions?: FixedOptions;
665
+ withBaseClients?: boolean;
666
+ };
667
+ type ApiClientFetchOptions = Omit<FetchOptions, 'method'>;
668
+ /**
669
+ * A fully encapsulated and isolated API client factory.
670
+ *
671
+ * ApiClient creates a sandboxed environment for a specific API service. It provides
672
+ * complete isolation by ignoring global `fetch.defaults` by default, ensuring that instance-specific
673
+ * configurations remain clean and predictable. It bundles RESTful methods and execution
674
+ * controls (like debounce/throttle) into a single, cohesive unit.
675
+ *
676
+ * ### Key Features:
677
+ * - **Isolation**: Instance-specific options are scoped to this client and isolated from other instances.
678
+ * - **Base Resolution**: Automatic path joining when `apiBaseUrl` is provided.
679
+ * - **Unified Error Handling**: Optional `errorPrefix` to namespace errors for easier debugging.
680
+ * - **Method Suite**: Integrated `delete`, `get`, `head`, `options`, `patch`, `post` and `put` methods.
681
+ *
682
+ * ### Precedence & Merging Nuances
683
+ * - **Options follow a strict hierarchy**: `fixedOptions` > `call options` > `commonOptions`.
684
+ * - Global `fetch.defaults` are ignored by default.
685
+ * - **Headers**: Merged by key. Specifying headers in a call overrides common headers with the
686
+ * same name, but does NOT remove or replace the entire header set.
687
+ * - **Interceptors**: Cumulative. Interceptors from all levels are concatenated and executed
688
+ * sequentially (Common -> Call -> Fixed). They cannot be overridden or replaced.
689
+ * - **Error Messages**: Merged by key, allowing per-service or per-call customization of
690
+ * specific error strings without losing the rest of the global message set.
691
+ */
692
+ declare class ApiClient<FixedOptions extends ApiClientFetchOptions = {}, // "{}" is required to correct infer common options
693
+ CommonOptions extends ExcludeOptions<FixedOptions, ApiClientFetchOptions> = ExcludeOptions<FixedOptions, ApiClientFetchOptions>, CommonDelay extends number = number> {
694
+ apiBaseUrl?: string | undefined;
695
+ /** The base GET-style client. Defaults to GET method. */
696
+ readonly client: ReturnType<typeof createClient<FixedOptions, CommonOptions, CommonDelay>>;
697
+ /** The base POST-style client. Defaults to POST method and supports request bodies. */
698
+ readonly postClient: ReturnType<typeof createPostClient<FixedOptions, CommonOptions, CommonDelay>>;
699
+ /** Alias for postClient with DELETE method. */
700
+ readonly delete: typeof this.postClient;
701
+ /** Alias for client with GET method. */
702
+ readonly get: typeof this.client;
703
+ /** Alias for client with HEAD method. */
704
+ readonly head: typeof this.client;
705
+ /** Alias for client with OPTIONS method. */
706
+ readonly options: typeof this.client;
707
+ /** Alias for postClient with POST method. */
708
+ readonly post: typeof this.postClient;
709
+ /** Alias for postClient with PUT method. */
710
+ readonly put: typeof this.postClient;
711
+ /** Alias for postClient with PATCH method. */
712
+ readonly patch: typeof this.postClient;
713
+ /**
714
+ * Creates a new ApiClient instance.
715
+ *
716
+ * @param apiBaseUrl - The base URL for the API. Relative paths passed to methods will be appended to this.
717
+ * @param config - Optional configuration for headers, interceptors, and default behavior.
718
+ */
719
+ constructor(apiBaseUrl?: string | undefined, config?: ApiClientConfig<FixedOptions, CommonOptions, CommonDelay>);
720
+ }
721
+
648
722
  /**
649
723
  * Gracefully executes interceptors and returns the processed value.
650
724
  * If the value is not transformed (by returning a new value) by the interceptors,
@@ -662,9 +736,11 @@ commonOptions?: PostOptions & CommonOptions, commonDeferOptions?: DeferredAsyncO
662
736
  */
663
737
  declare const executeInterceptors: <T, TArgs extends unknown[]>(value: T, signal?: AbortSignal, interceptors?: Interceptor<T, TArgs>[], ...args: TArgs) => Promise<T>;
664
738
 
739
+ declare const defaultErrorMsgs: Required<FetchErrMsgs>;
740
+ declare const POST_METHODS: string[];
665
741
  declare const fetch$1: {
666
742
  <T = unknown, TOptions extends FetchOptions = FetchOptions, TAs extends FetchAs = TOptions["as"] extends FetchAs ? TOptions["as"] : FetchAs.response, TReturn = FetchResult<T>[TAs]>(url: FetchArgs[0], options?: FetchOptions & TOptions): IPromise_Fetch<TReturn>;
667
- /** Default fetch options */
743
+ /** Global default fetch options */
668
744
  defaults: FetchOptionsDefault;
669
745
  };
670
746
 
@@ -683,183 +759,6 @@ declare const fetch$1: {
683
759
  */
684
760
  declare const mergeOptions: (...allOptions: (FetchOptions | undefined)[]) => FetchOptionsInterceptor;
685
761
 
686
- declare const methods: {
687
- /** Make HTTP requests with method GET */
688
- get: {
689
- <T extends unknown = never, TOptions extends ({
690
- headers?: HeadersInit | undefined;
691
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
692
- headers?: HeadersInit | undefined;
693
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
694
- method: string;
695
- }, TOptions, ({
696
- headers?: HeadersInit | undefined;
697
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: FetchArgs[0], options?: TOptions | undefined): IPromise_Fetch<Result>;
698
- deferred<ThisArg, Delay extends number, DefaultUrl extends FetchArgs[0] | undefined = URL | RequestInfo | undefined, DefaultOptions extends ({
699
- headers?: HeadersInit | undefined;
700
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
701
- headers?: HeadersInit | undefined;
702
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, TOptions extends ({
703
- headers?: HeadersInit | undefined;
704
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
705
- headers?: HeadersInit | undefined;
706
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
707
- method: string;
708
- }, TOptions, DefaultOptions, ({
709
- headers?: HeadersInit | undefined;
710
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: DefaultUrl extends undefined ? [url: URL | RequestInfo, options?: TOptions | undefined] : [options?: TOptions | undefined]) => IPromise_Fetch<Result>;
711
- };
712
- /** Make HTTP requests with method HEAD */
713
- head: {
714
- <T extends unknown = never, TOptions extends ({
715
- headers?: HeadersInit | undefined;
716
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
717
- headers?: HeadersInit | undefined;
718
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
719
- method: string;
720
- }, TOptions, ({
721
- headers?: HeadersInit | undefined;
722
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: FetchArgs[0], options?: TOptions | undefined): IPromise_Fetch<Result>;
723
- deferred<ThisArg, Delay extends number, DefaultUrl extends FetchArgs[0] | undefined = URL | RequestInfo | undefined, DefaultOptions extends ({
724
- headers?: HeadersInit | undefined;
725
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
726
- headers?: HeadersInit | undefined;
727
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, TOptions extends ({
728
- headers?: HeadersInit | undefined;
729
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
730
- headers?: HeadersInit | undefined;
731
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
732
- method: string;
733
- }, TOptions, DefaultOptions, ({
734
- headers?: HeadersInit | undefined;
735
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: DefaultUrl extends undefined ? [url: URL | RequestInfo, options?: TOptions | undefined] : [options?: TOptions | undefined]) => IPromise_Fetch<Result>;
736
- };
737
- /** Make HTTP requests with method OPTIONS */
738
- options: {
739
- <T extends unknown = never, TOptions extends ({
740
- headers?: HeadersInit | undefined;
741
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
742
- headers?: HeadersInit | undefined;
743
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
744
- method: string;
745
- }, TOptions, ({
746
- headers?: HeadersInit | undefined;
747
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: FetchArgs[0], options?: TOptions | undefined): IPromise_Fetch<Result>;
748
- deferred<ThisArg, Delay extends number, DefaultUrl extends FetchArgs[0] | undefined = URL | RequestInfo | undefined, DefaultOptions extends ({
749
- headers?: HeadersInit | undefined;
750
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
751
- headers?: HeadersInit | undefined;
752
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, TOptions extends ({
753
- headers?: HeadersInit | undefined;
754
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
755
- headers?: HeadersInit | undefined;
756
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
757
- method: string;
758
- }, TOptions, DefaultOptions, ({
759
- headers?: HeadersInit | undefined;
760
- } & Omit<FetchOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: DefaultUrl extends undefined ? [url: URL | RequestInfo, options?: TOptions | undefined] : [options?: TOptions | undefined]) => IPromise_Fetch<Result>;
761
- };
762
- /** Make HTTP requests with method DELETE */
763
- delete: {
764
- <T extends unknown = never, Options extends ({
765
- headers?: HeadersInit | undefined;
766
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
767
- headers?: HeadersInit | undefined;
768
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
769
- method: "delete";
770
- }, Options, ({
771
- headers?: HeadersInit | undefined;
772
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
773
- deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
774
- headers?: HeadersInit | undefined;
775
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
776
- headers?: HeadersInit | undefined;
777
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
778
- headers?: HeadersInit | undefined;
779
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
780
- headers?: HeadersInit | undefined;
781
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
782
- method: "delete";
783
- }, Options, DefaultOptions, ({
784
- headers?: HeadersInit | undefined;
785
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: URL | RequestInfo, data: PostBody | (() => _superutils_core.ValueOrPromise<PostBody>), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
786
- };
787
- /** Make HTTP requests with method PATCH */
788
- patch: {
789
- <T extends unknown = never, Options extends ({
790
- headers?: HeadersInit | undefined;
791
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
792
- headers?: HeadersInit | undefined;
793
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
794
- method: "patch";
795
- }, Options, ({
796
- headers?: HeadersInit | undefined;
797
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
798
- deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
799
- headers?: HeadersInit | undefined;
800
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
801
- headers?: HeadersInit | undefined;
802
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
803
- headers?: HeadersInit | undefined;
804
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
805
- headers?: HeadersInit | undefined;
806
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
807
- method: "patch";
808
- }, Options, DefaultOptions, ({
809
- headers?: HeadersInit | undefined;
810
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: URL | RequestInfo, data: PostBody | (() => _superutils_core.ValueOrPromise<PostBody>), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
811
- };
812
- /** Make HTTP requests with method POST */
813
- post: {
814
- <T extends unknown = never, Options extends ({
815
- headers?: HeadersInit | undefined;
816
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
817
- headers?: HeadersInit | undefined;
818
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
819
- method: "post";
820
- }, Options, ({
821
- headers?: HeadersInit | undefined;
822
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
823
- deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
824
- headers?: HeadersInit | undefined;
825
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
826
- headers?: HeadersInit | undefined;
827
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
828
- headers?: HeadersInit | undefined;
829
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
830
- headers?: HeadersInit | undefined;
831
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
832
- method: "post";
833
- }, Options, DefaultOptions, ({
834
- headers?: HeadersInit | undefined;
835
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: URL | RequestInfo, data: PostBody | (() => _superutils_core.ValueOrPromise<PostBody>), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
836
- };
837
- /** Make HTTP requests with method PUT */
838
- put: {
839
- <T extends unknown = never, Options extends ({
840
- headers?: HeadersInit | undefined;
841
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
842
- headers?: HeadersInit | undefined;
843
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Result = GetFetchResult<[{
844
- method: "put";
845
- }, Options, ({
846
- headers?: HeadersInit | undefined;
847
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(url: PostArgs[0], data?: PostArgs[1], options?: Options | undefined): IPromise_Fetch<Result>;
848
- deferred<ThisArg, DefaultUrl extends PostArgs[0] | undefined, DefaultData extends PostArgs[1] | undefined, DefaultOptions extends ({
849
- headers?: HeadersInit | undefined;
850
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
851
- headers?: HeadersInit | undefined;
852
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, Delay extends number = number>(deferOptions?: _superutils_promise.DeferredAsyncOptions<ThisArg, Delay> | undefined, defaultUrl?: DefaultUrl | undefined, defaultData?: DefaultData | undefined, defaultOptions?: DefaultOptions | undefined): <T extends unknown = never, Options extends ({
853
- headers?: HeadersInit | undefined;
854
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined = ({
855
- headers?: HeadersInit | undefined;
856
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined, TReturn = GetFetchResult<[{
857
- method: "put";
858
- }, Options, DefaultOptions, ({
859
- headers?: HeadersInit | undefined;
860
- } & Omit<PostOptions, "headers" | "method"> & Partial<Record<"method", never>>) | undefined], T>>(...args: PostDeferredCbArgs<DefaultUrl, DefaultData, Options, [url: URL | RequestInfo, data: PostBody | (() => _superutils_core.ValueOrPromise<PostBody>), options: PostOptions], undefined extends DefaultUrl ? DefaultUrl & undefined : DefaultUrl, undefined extends DefaultData ? DefaultData & undefined : DefaultData>) => IPromise_Fetch<TReturn>;
861
- };
862
- };
863
762
  /**
864
763
  * A `fetch()` replacement that simplifies data fetching with automatic JSON parsing, request timeouts, retries,
865
764
  * and handy interceptors that also work as transformers. It also includes deferred and throttled request
@@ -982,6 +881,6 @@ declare const methods: {
982
881
  * })
983
882
  * ```
984
883
  */
985
- declare const fetch: typeof fetch$1 & typeof methods;
884
+ declare const fetch: typeof fetch$1 & ApiClient;
986
885
 
987
- export { type ClientData, ContentType, type ExcludeOptions, type ExcludePostOptions, type ExtractAs, type FetchArgs, type FetchArgsInterceptor, FetchAs, type FetchCustomOptions, type FetchErrMsgs, FetchError, type FetchFunc, type FetchInterceptorError, type FetchInterceptorRequest, type FetchInterceptorResponse, type FetchInterceptorResult, type FetchInterceptors, type FetchInterceptorsMerged, type FetchOptions, type FetchOptionsDefault, type FetchOptionsInterceptor, type FetchResult, type FetchRetryOptions, type GetFetchResult, type IPromise_Fetch, type Interceptor, type OnDownloadProgress, type PostArgs, type PostBody, type PostDeferredCbArgs, type PostOptions, createClient, createPostClient, fetch as default, executeInterceptors, fetch, mergeOptions };
886
+ export { ApiClient, type ApiClientConfig, type ApiClientFetchOptions, type ClientData, ContentType, type ExcludeOptions, type ExcludePostOptions, type ExtractAs, type FetchArgs, type FetchArgsInterceptor, FetchAs, type FetchCustomOptions, type FetchErrMsgs, FetchError, type FetchFunc, type FetchInterceptorError, type FetchInterceptorRequest, type FetchInterceptorResponse, type FetchInterceptorResult, type FetchInterceptors, type FetchInterceptorsMerged, type FetchOptions, type FetchOptionsDefault, type FetchOptionsInterceptor, type FetchResult, type FetchRetryOptions, type GetFetchResult, type IPromise_Fetch, type Interceptor, type OnDownloadProgress, POST_METHODS, type PostArgs, type PostBody, type PostDeferredCbArgs, type PostOptions, createClient, createPostClient, fetch as default, defaultErrorMsgs, executeInterceptors, fetch, mergeOptions };
package/dist/index.js CHANGED
@@ -7,6 +7,9 @@ import {
7
7
  TimeoutPromise
8
8
  } from "@superutils/promise";
9
9
 
10
+ // src/ApiClient.ts
11
+ import { isStr } from "@superutils/core";
12
+
10
13
  // src/createClient.ts
11
14
  import { deferredCallback } from "@superutils/promise";
12
15
 
@@ -310,18 +313,19 @@ var defaultErrorMsgs = Object.freeze({
310
313
  timedout: "Request timed out",
311
314
  requestFailed: "Request failed with status code:"
312
315
  });
316
+ var POST_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
313
317
  var fetch = (url, options = {}) => {
314
318
  var _a, _b, _c;
315
319
  if (!isObj2(options)) options = {};
316
320
  let response;
317
321
  const opts = mergeOptions_default(
318
322
  { errMsgs: defaultErrorMsgs },
319
- fetch.defaults,
323
+ options.ignoreGlobalDefaults ? void 0 : fetch.defaults,
320
324
  options
321
325
  );
322
326
  opts.abortCtrl = opts.abortCtrl instanceof AbortController ? opts.abortCtrl : new AbortController();
323
327
  (_a = opts.as) != null ? _a : opts.as = "response" /* response */;
324
- (_b = opts.method) != null ? _b : opts.method = "get";
328
+ (_b = opts.method) != null ? _b : opts.method = "GET";
325
329
  (_c = opts.signal) != null ? _c : opts.signal = opts.abortCtrl.signal;
326
330
  const { abortCtrl, as: parseAs, headers, onAbort, onTimeout } = opts;
327
331
  opts.onAbort = async () => {
@@ -343,7 +347,7 @@ var fetch = (url, options = {}) => {
343
347
  );
344
348
  };
345
349
  return PromisE_timeout(opts, async () => {
346
- var _a2, _b2, _c2, _d;
350
+ var _a2, _b2, _c2, _d, _e;
347
351
  try {
348
352
  opts.body = await fallbackIfFails4(
349
353
  opts.body,
@@ -360,9 +364,7 @@ var fetch = (url, options = {}) => {
360
364
  (_b2 = opts.signal) != null ? _b2 : opts.signal = abortCtrl.signal;
361
365
  if (validateUrl && !isUrlValid(url, false))
362
366
  throw new Error(errMsgs.invalidUrl);
363
- const stringify = ["delete", "patch", "post", "put"].includes(
364
- `${opts.method}`.toLowerCase()
365
- ) && !["undefined", "string"].includes(typeof body) && isObj2(body, true) && headers.get("content-type") === ContentType.APPLICATION_JSON;
367
+ const stringify = POST_METHODS.includes(`${opts.method}`.toUpperCase()) && !["undefined", "string"].includes(typeof body) && isObj2(body, true) && headers.get("content-type") === ContentType.APPLICATION_JSON;
366
368
  if (stringify) opts.body = JSON.stringify(opts.body);
367
369
  response = await getResponse_default(url, opts);
368
370
  response = await executeInterceptors_default(
@@ -384,7 +386,9 @@ var fetch = (url, options = {}) => {
384
386
  [],
385
387
  void 0
386
388
  );
387
- throw new Error(jsonError, { cause: jsonError });
389
+ throw new Error((_d = jsonError == null ? void 0 : jsonError.message) != null ? _d : jsonError, {
390
+ cause: jsonError
391
+ });
388
392
  }
389
393
  let result = getResult_default(
390
394
  response,
@@ -404,7 +408,7 @@ var fetch = (url, options = {}) => {
404
408
  result = await executeInterceptors_default(
405
409
  result,
406
410
  abortCtrl.signal,
407
- (_d = opts.interceptors) == null ? void 0 : _d.result,
411
+ (_e = opts.interceptors) == null ? void 0 : _e.result,
408
412
  url,
409
413
  opts
410
414
  );
@@ -457,7 +461,6 @@ var createClient = (fixedOptions, commonOptions, commonDeferOptions) => {
457
461
  function client(url, options) {
458
462
  var _a;
459
463
  const mergedOptions = mergeOptions_default(
460
- fetch_default.defaults,
461
464
  commonOptions,
462
465
  options,
463
466
  fixedOptions
@@ -471,7 +474,6 @@ var createClient = (fixedOptions, commonOptions, commonDeferOptions) => {
471
474
  const fetchCb = (...args) => {
472
475
  var _a, _b;
473
476
  const mergedOptions = mergeOptions_default(
474
- fetch_default.defaults,
475
477
  commonOptions,
476
478
  defaultOptions,
477
479
  defaultUrl === void 0 ? args[1] : args[0],
@@ -510,7 +512,7 @@ var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
510
512
  );
511
513
  (_a = mergedOptions.as) != null ? _a : mergedOptions.as = "json" /* json */;
512
514
  mergedOptions.body = data != null ? data : mergedOptions.body;
513
- (_b = mergedOptions.method) != null ? _b : mergedOptions.method = "post";
515
+ (_b = mergedOptions.method) != null ? _b : mergedOptions.method = "POST";
514
516
  const headers = mergedOptions.headers;
515
517
  if (!headers.get("content-type")) {
516
518
  headers.set("content-type", ContentType.APPLICATION_JSON);
@@ -524,7 +526,6 @@ var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
524
526
  if (defaultUrl !== void 0) args.splice(0, 0, defaultUrl);
525
527
  if (defaultData !== void 0) args.splice(1, 0, defaultData);
526
528
  const mergedOptions = mergeOptions_default(
527
- fetch_default.defaults,
528
529
  commonOptions,
529
530
  defaultOptions,
530
531
  args[2],
@@ -549,36 +550,107 @@ var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
549
550
  };
550
551
  var createPostClient_default = createPostClient;
551
552
 
552
- // src/index.ts
553
- var methods = {
554
- /** Make HTTP requests with method GET */
555
- get: createClient_default({ method: "get" }),
556
- /** Make HTTP requests with method HEAD */
557
- head: createClient_default({ method: "head" }),
558
- /** Make HTTP requests with method OPTIONS */
559
- options: createClient_default({ method: "options" }),
560
- /** Make HTTP requests with method DELETE */
561
- delete: createPostClient_default({ method: "delete" }),
562
- /** Make HTTP requests with method PATCH */
563
- patch: createPostClient_default({ method: "patch" }),
564
- /** Make HTTP requests with method POST */
565
- post: createPostClient_default({ method: "post" }),
566
- /** Make HTTP requests with method PUT */
567
- put: createPostClient_default({ method: "put" })
553
+ // src/ApiClient.ts
554
+ var ApiClient = class {
555
+ /**
556
+ * Creates a new ApiClient instance.
557
+ *
558
+ * @param apiBaseUrl - The base URL for the API. Relative paths passed to methods will be appended to this.
559
+ * @param config - Optional configuration for headers, interceptors, and default behavior.
560
+ */
561
+ constructor(apiBaseUrl, config = {}) {
562
+ this.apiBaseUrl = apiBaseUrl;
563
+ const {
564
+ errorPrefix,
565
+ fixedOptions = {},
566
+ commonOptions = {},
567
+ commonDeferOptions = {},
568
+ withBaseClients = true
569
+ } = config;
570
+ const interceptors = {};
571
+ if (errorPrefix)
572
+ interceptors.error = [
573
+ (err) => {
574
+ err.message = `${errorPrefix} ${err.message}`;
575
+ return err;
576
+ }
577
+ ];
578
+ if (isStr(this.apiBaseUrl)) {
579
+ interceptors.request = [
580
+ (url) => {
581
+ const useBaseUrl = isStr(url) && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith(this.apiBaseUrl);
582
+ if (useBaseUrl) url = `${this.apiBaseUrl}${url}`;
583
+ return url;
584
+ }
585
+ ];
586
+ }
587
+ const getMethods = [
588
+ withBaseClients ? "client" : "",
589
+ "get",
590
+ "head",
591
+ "options"
592
+ ].filter(Boolean);
593
+ const postMethods = [
594
+ withBaseClients ? "postClient" : "",
595
+ "delete",
596
+ "patch",
597
+ "post",
598
+ "put"
599
+ ].filter(Boolean);
600
+ const methods = [...getMethods, ...postMethods].reduce(
601
+ (obj, method) => {
602
+ const isBaseClient = method.toLowerCase().includes("client");
603
+ const _createClient = getMethods.includes(method) ? createClient_default : createPostClient_default;
604
+ return {
605
+ [method]: {
606
+ enumerable: false,
607
+ value: _createClient(
608
+ mergeOptions_default(fixedOptions, {
609
+ interceptors,
610
+ method: isBaseClient ? void 0 : method.toUpperCase()
611
+ }),
612
+ { ignoreGlobalDefaults: true, ...commonOptions },
613
+ commonDeferOptions
614
+ ),
615
+ writable: false
616
+ },
617
+ ...obj
618
+ };
619
+ },
620
+ {}
621
+ );
622
+ Object.defineProperties(this, methods);
623
+ }
568
624
  };
625
+ var ApiClient_default = ApiClient;
626
+
627
+ // src/index.ts
569
628
  var fetch2 = fetch_default;
570
- fetch2.delete = methods.delete;
571
- fetch2.get = methods.get;
572
- fetch2.head = methods.head;
573
- fetch2.options = methods.options;
574
- fetch2.patch = methods.patch;
575
- fetch2.post = methods.post;
576
- fetch2.put = methods.put;
629
+ var globalClient = new ApiClient_default(void 0, {
630
+ commonOptions: { ignoreGlobalDefaults: false },
631
+ withBaseClients: false
632
+ });
633
+ Object.defineProperties(
634
+ fetch2,
635
+ ["delete", "get", "head", "options", "patch", "post", "put"].reduce(
636
+ (obj, method) => ({
637
+ [method]: {
638
+ enumerable: false,
639
+ value: globalClient[method],
640
+ writable: false
641
+ },
642
+ ...obj
643
+ }),
644
+ {}
645
+ )
646
+ );
577
647
  var index_default = fetch2;
578
648
  export {
649
+ ApiClient,
579
650
  ContentType,
580
651
  FetchAs,
581
652
  FetchError,
653
+ POST_METHODS,
582
654
  ResolveError,
583
655
  ResolveIgnored,
584
656
  TIMEOUT_FALLBACK,
@@ -587,6 +659,7 @@ export {
587
659
  createClient,
588
660
  createPostClient,
589
661
  index_default as default,
662
+ defaultErrorMsgs,
590
663
  executeInterceptors,
591
664
  fetch2 as fetch,
592
665
  mergeOptions
package/package.json CHANGED
@@ -5,8 +5,8 @@
5
5
  },
6
6
  "description": "A lightweight `fetch` wrapper for browsers and Node.js, designed to simplify data fetching and reduce boilerplate.",
7
7
  "dependencies": {
8
- "@superutils/core": "^1.2.15",
9
- "@superutils/promise": "^1.3.14"
8
+ "@superutils/core": "^1.2.16",
9
+ "@superutils/promise": "^1.3.15"
10
10
  },
11
11
  "files": [
12
12
  "dist",
@@ -53,6 +53,6 @@
53
53
  "module": "./dist/index.js",
54
54
  "type": "module",
55
55
  "types": "./dist/index.d.ts",
56
- "version": "1.5.16",
57
- "gitHead": "7be3be6fb4a8cb1955ee5f704fc49bbb792bd961"
56
+ "version": "1.5.18",
57
+ "gitHead": "5bf3601096002f3ff4913a967dd77ed9798ea2e9"
58
58
  }