@zayne-labs/callapi 1.10.6 → 1.11.1

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.
@@ -16,6 +16,7 @@ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) =>
16
16
  type UnmaskType<TValue> = {
17
17
  _: TValue;
18
18
  }["_"];
19
+ type RemovePrefix<TPrefix extends "dedupe" | "retry", TKey extends string> = TKey extends `${TPrefix}${infer TRest}` ? Uncapitalize<TRest> : TKey;
19
20
  type Awaitable<TValue> = Promise<TValue> | TValue;
20
21
  type CommonRequestHeaders = "Access-Control-Allow-Credentials" | "Access-Control-Allow-Headers" | "Access-Control-Allow-Methods" | "Access-Control-Allow-Origin" | "Access-Control-Expose-Headers" | "Access-Control-Max-Age" | "Age" | "Allow" | "Cache-Control" | "Clear-Site-Data" | "Content-Disposition" | "Content-Encoding" | "Content-Language" | "Content-Length" | "Content-Location" | "Content-Range" | "Content-Security-Policy-Report-Only" | "Content-Security-Policy" | "Cookie" | "Cross-Origin-Embedder-Policy" | "Cross-Origin-Opener-Policy" | "Cross-Origin-Resource-Policy" | "Date" | "ETag" | "Expires" | "Last-Modified" | "Location" | "Permissions-Policy" | "Pragma" | "Retry-After" | "Save-Data" | "Sec-CH-Prefers-Color-Scheme" | "Sec-CH-Prefers-Reduced-Motion" | "Sec-CH-UA-Arch" | "Sec-CH-UA-Bitness" | "Sec-CH-UA-Form-Factor" | "Sec-CH-UA-Full-Version-List" | "Sec-CH-UA-Full-Version" | "Sec-CH-UA-Mobile" | "Sec-CH-UA-Model" | "Sec-CH-UA-Platform-Version" | "Sec-CH-UA-Platform" | "Sec-CH-UA-WoW64" | "Sec-CH-UA" | "Sec-Fetch-Dest" | "Sec-Fetch-Mode" | "Sec-Fetch-Site" | "Sec-Fetch-User" | "Sec-GPC" | "Server-Timing" | "Server" | "Service-Worker-Navigation-Preload" | "Set-Cookie" | "Strict-Transport-Security" | "Timing-Allow-Origin" | "Trailer" | "Transfer-Encoding" | "Upgrade" | "Vary" | "Warning" | "WWW-Authenticate" | "X-Content-Type-Options" | "X-DNS-Prefetch-Control" | "X-Frame-Options" | "X-Permitted-Cross-Domain-Policies" | "X-Powered-By" | "X-Robots-Tag" | "X-XSS-Protection" | AnyString;
21
22
  type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
@@ -61,7 +62,7 @@ type CustomAuth = {
61
62
  type Auth = PossibleAuthValueOrGetter | BearerOrTokenAuth | BasicAuth | CustomAuth;
62
63
  //#endregion
63
64
  //#region src/constants/common.d.ts
64
- declare const fetchSpecificKeys: (keyof RequestInit | "duplex")[];
65
+ declare const fetchSpecificKeys: readonly (keyof RequestInit | "duplex")[];
65
66
  //#endregion
66
67
  //#region src/types/standard-schema.d.ts
67
68
  /**
@@ -356,7 +357,7 @@ interface CallApiSchema {
356
357
  */
357
358
  query?: StandardSchemaV1<Query | undefined> | ((query: Query) => Awaitable<Query | undefined>);
358
359
  }
359
- declare const routeKeyMethods: ["delete", "get", "patch", "post", "put"];
360
+ declare const routeKeyMethods: readonly ["delete", "get", "patch", "post", "put"];
360
361
  type RouteKeyMethods = (typeof routeKeyMethods)[number];
361
362
  type RouteKeyMethodsURLUnion = `@${RouteKeyMethods}/`;
362
363
  type BaseCallApiSchemaRoutes = Partial<Record<AnyString | RouteKeyMethodsURLUnion, CallApiSchema>>;
@@ -417,6 +418,43 @@ declare class ValidationError extends Error {
417
418
  static isError(error: unknown): error is ValidationError;
418
419
  }
419
420
  //#endregion
421
+ //#region src/middlewares.d.ts
422
+ type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
423
+ interface Middlewares {
424
+ /**
425
+ * Wraps the fetch implementation to intercept requests at the network layer.
426
+ *
427
+ * Takes the current fetch function and returns a new one. Use it to cache responses,
428
+ * add logging, handle offline mode, or short-circuit requests etc. Multiple middleware
429
+ * compose in order: plugins → base config → per-request.
430
+ *
431
+ * Unlike `customFetchImpl`, middleware can call through to the original fetch.
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * // Cache responses
436
+ * const cache = new Map();
437
+ * fetchMiddleware: (fetchImpl) => async (input, init) => {
438
+ * const key = input.toString();
439
+ * if (cache.has(key)) return cache.get(key).clone();
440
+ *
441
+ * const response = await fetchImpl(input, init);
442
+ * cache.set(key, response.clone());
443
+ * return response;
444
+ * }
445
+ *
446
+ * // Handle offline
447
+ * fetchMiddleware: (fetchImpl) => async (input, init) => {
448
+ * if (!navigator.onLine) {
449
+ * return new Response('{"error": "offline"}', { status: 503 });
450
+ * }
451
+ * return fetchImpl(input, init);
452
+ * }
453
+ * ```
454
+ */
455
+ fetchMiddleware?: (fetchImpl: FetchImpl) => FetchImpl;
456
+ }
457
+ //#endregion
420
458
  //#region src/plugins.d.ts
421
459
  type PluginSetupContext<TPluginExtraOptions = unknown> = RequestContext & PluginExtraOptions<TPluginExtraOptions> & {
422
460
  initURL: string;
@@ -437,13 +475,17 @@ interface CallApiPlugin {
437
475
  */
438
476
  description?: string;
439
477
  /**
440
- * Hooks / Interceptors for the plugin
478
+ * Hooks for the plugin
441
479
  */
442
- hooks?: PluginHooks;
480
+ hooks?: PluginHooks | ((context: PluginSetupContext) => Awaitable<PluginHooks>);
443
481
  /**
444
482
  * A unique id for the plugin
445
483
  */
446
484
  id: string;
485
+ /**
486
+ * Middlewares that for the plugin
487
+ */
488
+ middlewares?: Middlewares | ((context: PluginSetupContext) => Awaitable<Middlewares>);
447
489
  /**
448
490
  * A name for the plugin
449
491
  */
@@ -571,7 +613,7 @@ interface Hooks<TData = DefaultDataType, TErrorData = DefaultDataType, TPluginOp
571
613
  */
572
614
  onError?: (context: ErrorContext<TErrorData> & PluginExtraOptions<TPluginOptions>) => Awaitable<unknown>;
573
615
  /**
574
- * Hook called before the HTTP request is sent and before any internal processing begins.
616
+ * Hook called before the HTTP request is sent and before any internal processing of the request object begins.
575
617
  *
576
618
  * This is the ideal place to modify request headers, add authentication,
577
619
  * implement request logging, or perform any setup before the network call.
@@ -692,8 +734,6 @@ interface HookConfigOptions {
692
734
  *
693
735
  * This affects how ALL hooks execute together, regardless of their source (main or plugin).
694
736
  *
695
- * Use `hookRegistrationOrder` to control the registration order of main vs plugin hooks.
696
- *
697
737
  * @default "parallel"
698
738
  *
699
739
  * @example
@@ -707,7 +747,6 @@ interface HookConfigOptions {
707
747
  * // Use case: Hooks have dependencies and must run in order
708
748
  * const client = callApi.create({
709
749
  * hooksExecutionMode: "sequential",
710
- * hookRegistrationOrder: "mainFirst",
711
750
  * plugins: [transformPlugin],
712
751
  * onRequest: (ctx) => {
713
752
  * // This runs first, then transform plugin runs
@@ -737,62 +776,6 @@ interface HookConfigOptions {
737
776
  * ```
738
777
  */
739
778
  hooksExecutionMode?: "parallel" | "sequential";
740
- /**
741
- * Controls the registration order of main hooks relative to plugin hooks.
742
- *
743
- * - **"pluginsFirst"**: Plugin hooks register first, then main hooks (default)
744
- * - **"mainFirst"**: Main hooks register first, then plugin hooks
745
- *
746
- * This determines the order hooks are added to the registry, which affects
747
- * their execution sequence when using sequential execution mode.
748
- *
749
- * @default "pluginsFirst"
750
- *
751
- * @example
752
- * ```ts
753
- * // Plugin hooks register first (default behavior)
754
- * hookRegistrationOrder: "pluginsFirst"
755
- *
756
- * // Main hooks register first
757
- * hookRegistrationOrder: "mainFirst"
758
- *
759
- * // Use case: Main validation before plugin processing
760
- * const client = callApi.create({
761
- * hookRegistrationOrder: "mainFirst",
762
- * hooksExecutionMode: "sequential",
763
- * plugins: [transformPlugin],
764
- * onRequest: (ctx) => {
765
- * // This main hook runs first in sequential mode
766
- * if (!ctx.request.headers.authorization) {
767
- * throw new Error("Authorization required");
768
- * }
769
- * }
770
- * });
771
- *
772
- * // Use case: Plugin setup before main logic (default)
773
- * const client = callApi.create({
774
- * hookRegistrationOrder: "pluginsFirst", // Default
775
- * hooksExecutionMode: "sequential",
776
- * plugins: [setupPlugin],
777
- * onRequest: (ctx) => {
778
- * // Plugin runs first, then this main hook
779
- * console.log("Request prepared:", ctx.request.url);
780
- * }
781
- * });
782
- *
783
- * // Use case: Parallel mode (registration order less important)
784
- * const client = callApi.create({
785
- * hookRegistrationOrder: "pluginsFirst",
786
- * hooksExecutionMode: "parallel", // All run simultaneously
787
- * plugins: [metricsPlugin, cachePlugin],
788
- * onRequest: (ctx) => {
789
- * // All hooks run in parallel regardless of registration order
790
- * addRequestId(ctx.request);
791
- * }
792
- * });
793
- * ```
794
- */
795
- hooksRegistrationOrder?: "mainFirst" | "pluginsFirst";
796
779
  }
797
780
  type RequestContext = {
798
781
  /**
@@ -880,7 +863,13 @@ type ResponseStreamContext = UnmaskType<RequestContext & {
880
863
  //#endregion
881
864
  //#region src/dedupe.d.ts
882
865
  type DedupeStrategyUnion = UnmaskType<"cancel" | "defer" | "none">;
866
+ type DedupeOptionKeys = Exclude<keyof DedupeOptions, "dedupe">;
867
+ type InnerDedupeOptions = { [Key in DedupeOptionKeys as RemovePrefix<"dedupe", Key>]?: DedupeOptions[Key] };
883
868
  type DedupeOptions = {
869
+ /**
870
+ * All dedupe options in a single object instead of separate properties
871
+ */
872
+ dedupe?: InnerDedupeOptions;
884
873
  /**
885
874
  * Controls the scope of request deduplication caching.
886
875
  *
@@ -1089,7 +1078,7 @@ type DedupeOptions = {
1089
1078
  };
1090
1079
  //#endregion
1091
1080
  //#region src/retry.d.ts
1092
- declare const defaultRetryStatusCodesLookup: () => {
1081
+ declare const defaultRetryStatusCodesLookup: () => Readonly<{
1093
1082
  408: "Request Timeout";
1094
1083
  409: "Conflict";
1095
1084
  425: "Too Early";
@@ -1098,13 +1087,11 @@ declare const defaultRetryStatusCodesLookup: () => {
1098
1087
  502: "Bad Gateway";
1099
1088
  503: "Service Unavailable";
1100
1089
  504: "Gateway Timeout";
1101
- };
1090
+ }>;
1102
1091
  type RetryStatusCodes = UnmaskType<AnyNumber | keyof ReturnType<typeof defaultRetryStatusCodesLookup>>;
1103
1092
  type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;
1104
- type InnerRetryKeys<TErrorData> = Exclude<keyof RetryOptions<TErrorData>, "~retryAttemptCount" | "retry">;
1105
- type InnerRetryOptions<TErrorData> = { [Key in InnerRetryKeys<TErrorData> as Key extends `retry${infer TRest}` ? Uncapitalize<TRest> extends "attempts" ? never : Uncapitalize<TRest> : Key]?: RetryOptions<TErrorData>[Key] } & {
1106
- attempts: NonNullable<RetryOptions<TErrorData>["retryAttempts"]>;
1107
- };
1093
+ type RetryOptionKeys<TErrorData> = Exclude<keyof RetryOptions<TErrorData>, "~retryAttemptCount" | "retry">;
1094
+ type InnerRetryOptions<TErrorData> = { [Key in RetryOptionKeys<TErrorData> as RemovePrefix<"retry", Key>]?: RetryOptions<TErrorData>[Key] };
1108
1095
  interface RetryOptions<TErrorData> {
1109
1096
  /**
1110
1097
  * Keeps track of the number of times the request has already been retried
@@ -1287,8 +1274,7 @@ type CallApiRequestOptions = Prettify<{
1287
1274
  type CallApiRequestOptionsForHooks = Omit<CallApiRequestOptions, "headers"> & {
1288
1275
  headers: Record<string, string | undefined>;
1289
1276
  };
1290
- type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
1291
- type SharedExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = DedupeOptions & HookConfigOptions & HooksOrHooksArray<TData, TErrorData, Partial<InferPluginOptions<TPluginArray>>> & Partial<InferPluginOptions<TPluginArray>> & ResultModeOption<TErrorData, TResultMode> & RetryOptions<TErrorData> & ThrowOnErrorOption<TErrorData, TThrowOnError> & URLOptions & {
1277
+ type SharedExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = DedupeOptions & HookConfigOptions & HooksOrHooksArray<TData, TErrorData, Partial<InferPluginOptions<TPluginArray>>> & Middlewares & Partial<InferPluginOptions<TPluginArray>> & ResultModeOption<TErrorData, TResultMode> & RetryOptions<TErrorData> & ThrowOnErrorOption<TErrorData, TThrowOnError> & URLOptions & {
1292
1278
  /**
1293
1279
  * Automatically add an Authorization header value.
1294
1280
  *
@@ -1808,4 +1794,4 @@ type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TR
1808
1794
  type CallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion, TResponseType extends ResponseTypeUnion> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;
1809
1795
  //#endregion
1810
1796
  export { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaOutputResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey };
1811
- //# sourceMappingURL=common-0nTMuN7U.d.ts.map
1797
+ //# sourceMappingURL=common-BMWVqV15.d.ts.map
@@ -1,4 +1,4 @@
1
- import { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaOutputResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey } from "./common-0nTMuN7U.js";
1
+ import { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaOutputResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey } from "./common-BMWVqV15.js";
2
2
 
3
3
  //#region src/createFetchClient.d.ts
4
4