@zimic/fetch 0.2.1-canary.0 → 0.2.1-canary.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.
- package/dist/index.d.ts +81 -77
- package/dist/index.js.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
- package/src/client/FetchClient.ts +2 -9
- package/src/client/types/public.ts +70 -71
- package/src/client/types/requests.ts +28 -23
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HttpSchema, HttpSchemaMethod, HttpSchemaPath, HttpRequestSchema, HttpHeaders, HttpSearchParams, JSONValue, HttpMethod, HttpHeadersSchema, HttpSearchParamsSchema, HttpMethodSchema, HttpStatusCode, HttpResponseSchemaStatusCode, HttpResponse, HttpResponseBodySchema, HttpResponseHeadersSchema,
|
|
1
|
+
import { HttpSchema, HttpSchemaMethod, HttpSchemaPath, HttpRequestSchema, HttpHeaders, HttpSearchParams, JSONValue, HttpMethod, HttpHeadersSchema, HttpSearchParamsSchema, HttpRequest, HttpMethodSchema, HttpRequestHeadersSchema, AllowAnyStringInPathParams, HttpStatusCode, HttpResponseSchemaStatusCode, HttpResponse, HttpResponseBodySchema, HttpResponseHeadersSchema, LiteralHttpSchemaPathFromNonLiteral } from '@zimic/http';
|
|
2
2
|
|
|
3
3
|
declare const value: unique symbol;
|
|
4
4
|
/**
|
|
@@ -25,24 +25,26 @@ type ReplaceBy<Type, Source, Target> = Type extends Source ? Target : Type;
|
|
|
25
25
|
type RequiredByKey<Type, Key extends keyof Type> = Omit<Type, Key> & Required<Pick<Type, Key>>;
|
|
26
26
|
|
|
27
27
|
type FetchRequestInitHeaders<RequestSchema extends HttpRequestSchema> = RequestSchema['headers'] | HttpHeaders<Default<RequestSchema['headers']>>;
|
|
28
|
-
type FetchRequestInitWithHeaders<RequestSchema extends HttpRequestSchema> = [RequestSchema['headers']] extends [never] ? {
|
|
28
|
+
type FetchRequestInitWithHeaders<RequestSchema extends HttpRequestSchema> = 'headers' extends keyof RequestSchema ? [RequestSchema['headers']] extends [never] ? {
|
|
29
29
|
headers?: undefined;
|
|
30
30
|
} : undefined extends RequestSchema['headers'] ? {
|
|
31
31
|
headers?: FetchRequestInitHeaders<RequestSchema>;
|
|
32
32
|
} : {
|
|
33
33
|
headers: FetchRequestInitHeaders<RequestSchema>;
|
|
34
|
+
} : {
|
|
35
|
+
headers?: undefined;
|
|
34
36
|
};
|
|
35
37
|
type FetchRequestInitSearchParams<RequestSchema extends HttpRequestSchema> = RequestSchema['searchParams'] | HttpSearchParams<Default<RequestSchema['searchParams']>>;
|
|
36
|
-
type FetchRequestInitWithSearchParams<RequestSchema extends HttpRequestSchema> = [
|
|
37
|
-
RequestSchema['searchParams']
|
|
38
|
-
] extends [never] ? {
|
|
38
|
+
type FetchRequestInitWithSearchParams<RequestSchema extends HttpRequestSchema> = 'searchParams' extends keyof RequestSchema ? [RequestSchema['searchParams']] extends [never] ? {
|
|
39
39
|
searchParams?: undefined;
|
|
40
40
|
} : undefined extends RequestSchema['searchParams'] ? {
|
|
41
41
|
searchParams?: FetchRequestInitSearchParams<RequestSchema>;
|
|
42
42
|
} : {
|
|
43
43
|
searchParams: FetchRequestInitSearchParams<RequestSchema>;
|
|
44
|
+
} : {
|
|
45
|
+
searchParams?: undefined;
|
|
44
46
|
};
|
|
45
|
-
type FetchRequestInitWithBody<RequestSchema extends HttpRequestSchema> = [RequestSchema['body']] extends [never] ? {
|
|
47
|
+
type FetchRequestInitWithBody<RequestSchema extends HttpRequestSchema> = 'body' extends keyof RequestSchema ? [RequestSchema['body']] extends [never] ? {
|
|
46
48
|
body?: null;
|
|
47
49
|
} : RequestSchema['body'] extends string ? undefined extends RequestSchema['body'] ? {
|
|
48
50
|
body?: ReplaceBy<RequestSchema['body'], undefined, null>;
|
|
@@ -56,6 +58,8 @@ type FetchRequestInitWithBody<RequestSchema extends HttpRequestSchema> = [Reques
|
|
|
56
58
|
body?: ReplaceBy<RequestSchema['body'], undefined, null>;
|
|
57
59
|
} : {
|
|
58
60
|
body: RequestSchema['body'];
|
|
61
|
+
} : {
|
|
62
|
+
body?: null;
|
|
59
63
|
};
|
|
60
64
|
type FetchRequestInitPerPath<RequestSchema extends HttpRequestSchema> = FetchRequestInitWithHeaders<RequestSchema> & FetchRequestInitWithSearchParams<RequestSchema> & FetchRequestInitWithBody<RequestSchema>;
|
|
61
65
|
/**
|
|
@@ -438,11 +442,78 @@ type AnyFetchRequestError = FetchResponseError<any, any, any>;
|
|
|
438
442
|
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}
|
|
439
443
|
*/
|
|
440
444
|
type FetchInput<Schema extends HttpSchema, Method extends HttpSchemaMethod<Schema>, Path extends HttpSchemaPath.NonLiteral<Schema, Method>> = Path | URL | FetchRequest<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>;
|
|
441
|
-
|
|
445
|
+
/**
|
|
446
|
+
* A fetch instance typed with an HTTP schema, closely compatible with the
|
|
447
|
+
* {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All requests and responses are typed by
|
|
448
|
+
* default with the schema, including methods, paths, status codes, parameters, and bodies.
|
|
449
|
+
*
|
|
450
|
+
* Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance. Default
|
|
451
|
+
* options are also applied to the requests, if present in the instance.
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* import { type HttpSchema } from '@zimic/http';
|
|
455
|
+
* import { createFetch } from '@zimic/fetch';
|
|
456
|
+
*
|
|
457
|
+
* interface User {
|
|
458
|
+
* id: string;
|
|
459
|
+
* username: string;
|
|
460
|
+
* }
|
|
461
|
+
*
|
|
462
|
+
* type Schema = HttpSchema<{
|
|
463
|
+
* '/users': {
|
|
464
|
+
* GET: {
|
|
465
|
+
* request: {
|
|
466
|
+
* searchParams: { query?: string };
|
|
467
|
+
* };
|
|
468
|
+
* response: {
|
|
469
|
+
* 200: { body: User[] };
|
|
470
|
+
* 404: { body: { message: string } };
|
|
471
|
+
* 500: { body: { message: string } };
|
|
472
|
+
* };
|
|
473
|
+
* };
|
|
474
|
+
* };
|
|
475
|
+
* }>;
|
|
476
|
+
*
|
|
477
|
+
* const fetch = createFetch<Schema>({
|
|
478
|
+
* baseURL: 'http://localhost:3000',
|
|
479
|
+
* headers: { 'accept-language': 'en' },
|
|
480
|
+
* });
|
|
481
|
+
*
|
|
482
|
+
* const response = await fetch('/users', {
|
|
483
|
+
* method: 'GET',
|
|
484
|
+
* searchParams: { query: 'u' },
|
|
485
|
+
* });
|
|
486
|
+
*
|
|
487
|
+
* if (response.status === 404) {
|
|
488
|
+
* return null; // User not found
|
|
489
|
+
* }
|
|
490
|
+
*
|
|
491
|
+
* if (!response.ok) {
|
|
492
|
+
* throw response.error;
|
|
493
|
+
* }
|
|
494
|
+
*
|
|
495
|
+
* const users = await response.json();
|
|
496
|
+
* return users; // User[]
|
|
497
|
+
*
|
|
498
|
+
* @param input The resource to fetch, either a path, a URL, or a {@link FetchRequest request}. If a path is provided, it
|
|
499
|
+
* is automatically prefixed with the base URL of the fetch instance when the request is sent. If a URL or a request
|
|
500
|
+
* is provided, it is used as is.
|
|
501
|
+
* @param init The request options. If a path or a URL is provided as the first argument, this argument is required and
|
|
502
|
+
* should contain at least the method of the request. If the first argument is a {@link FetchRequest request}, this
|
|
503
|
+
* argument is optional.
|
|
504
|
+
* @returns A promise that resolves to the response to the request.
|
|
505
|
+
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}
|
|
506
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/Fetch_API}
|
|
507
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/Request}
|
|
508
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/RequestInit}
|
|
509
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/Response}
|
|
510
|
+
*/
|
|
511
|
+
interface Fetch<Schema extends HttpSchema> extends FetchClient<Schema> {
|
|
442
512
|
<Method extends HttpSchemaMethod<Schema>, Path extends HttpSchemaPath.NonLiteral<Schema, Method>, Redirect extends RequestRedirect = 'follow'>(input: Path | URL, init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>, Redirect>): Promise<FetchResponse<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>, false, Redirect>>;
|
|
443
513
|
<Method extends HttpSchemaMethod<Schema>, Path extends HttpSchemaPath.NonLiteral<Schema, Method>, Redirect extends RequestRedirect = 'follow'>(input: FetchRequest<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>, init?: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>, Redirect>): Promise<FetchResponse<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>, false, Redirect>>;
|
|
444
514
|
}
|
|
445
|
-
declare namespace
|
|
515
|
+
declare namespace Fetch {
|
|
516
|
+
/** A loosely-typed version of {@link Fetch `fetch`}. This can be useful to make requests with fewer type constraints, */
|
|
446
517
|
type Loose = (input: string | URL | FetchRequest.Loose, init?: FetchRequestInit.Loose) => Promise<FetchResponse.Loose>;
|
|
447
518
|
}
|
|
448
519
|
/**
|
|
@@ -698,7 +769,7 @@ interface FetchClient<Schema extends HttpSchema> extends Pick<FetchOptions<Schem
|
|
|
698
769
|
* @see {@link https://developer.mozilla.org/docs/Web/API/RequestInit}
|
|
699
770
|
* @see {@link https://developer.mozilla.org/docs/Web/API/Response}
|
|
700
771
|
*/
|
|
701
|
-
loose:
|
|
772
|
+
loose: Fetch.Loose;
|
|
702
773
|
/**
|
|
703
774
|
* A constructor for creating
|
|
704
775
|
* {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchrequest-1 `FetchRequest`}, closely compatible with
|
|
@@ -903,73 +974,6 @@ interface FetchClient<Schema extends HttpSchema> extends Pick<FetchOptions<Schem
|
|
|
903
974
|
*/
|
|
904
975
|
isResponseError: <Method extends HttpSchemaMethod<Schema>, Path extends HttpSchemaPath.Literal<Schema, Method>>(error: unknown, method: Method, path: Path) => error is FetchResponseError<Schema, Method, Path>;
|
|
905
976
|
}
|
|
906
|
-
/**
|
|
907
|
-
* A fetch instance typed with an HTTP schema, closely compatible with the
|
|
908
|
-
* {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All requests and responses are typed by
|
|
909
|
-
* default with the schema, including methods, paths, status codes, parameters, and bodies.
|
|
910
|
-
*
|
|
911
|
-
* Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance. Default
|
|
912
|
-
* options are also applied to the requests, if present in the instance.
|
|
913
|
-
*
|
|
914
|
-
* @example
|
|
915
|
-
* import { type HttpSchema } from '@zimic/http';
|
|
916
|
-
* import { createFetch } from '@zimic/fetch';
|
|
917
|
-
*
|
|
918
|
-
* interface User {
|
|
919
|
-
* id: string;
|
|
920
|
-
* username: string;
|
|
921
|
-
* }
|
|
922
|
-
*
|
|
923
|
-
* type Schema = HttpSchema<{
|
|
924
|
-
* '/users': {
|
|
925
|
-
* GET: {
|
|
926
|
-
* request: {
|
|
927
|
-
* searchParams: { query?: string };
|
|
928
|
-
* };
|
|
929
|
-
* response: {
|
|
930
|
-
* 200: { body: User[] };
|
|
931
|
-
* 404: { body: { message: string } };
|
|
932
|
-
* 500: { body: { message: string } };
|
|
933
|
-
* };
|
|
934
|
-
* };
|
|
935
|
-
* };
|
|
936
|
-
* }>;
|
|
937
|
-
*
|
|
938
|
-
* const fetch = createFetch<Schema>({
|
|
939
|
-
* baseURL: 'http://localhost:3000',
|
|
940
|
-
* headers: { 'accept-language': 'en' },
|
|
941
|
-
* });
|
|
942
|
-
*
|
|
943
|
-
* const response = await fetch('/users', {
|
|
944
|
-
* method: 'GET',
|
|
945
|
-
* searchParams: { query: 'u' },
|
|
946
|
-
* });
|
|
947
|
-
*
|
|
948
|
-
* if (response.status === 404) {
|
|
949
|
-
* return null; // User not found
|
|
950
|
-
* }
|
|
951
|
-
*
|
|
952
|
-
* if (!response.ok) {
|
|
953
|
-
* throw response.error;
|
|
954
|
-
* }
|
|
955
|
-
*
|
|
956
|
-
* const users = await response.json();
|
|
957
|
-
* return users; // User[]
|
|
958
|
-
*
|
|
959
|
-
* @param input The resource to fetch, either a path, a URL, or a {@link FetchRequest request}. If a path is provided, it
|
|
960
|
-
* is automatically prefixed with the base URL of the fetch instance when the request is sent. If a URL or a request
|
|
961
|
-
* is provided, it is used as is.
|
|
962
|
-
* @param init The request options. If a path or a URL is provided as the first argument, this argument is required and
|
|
963
|
-
* should contain at least the method of the request. If the first argument is a {@link FetchRequest request}, this
|
|
964
|
-
* argument is optional.
|
|
965
|
-
* @returns A promise that resolves to the response to the request.
|
|
966
|
-
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}
|
|
967
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/Fetch_API}
|
|
968
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/Request}
|
|
969
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/RequestInit}
|
|
970
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/Response}
|
|
971
|
-
*/
|
|
972
|
-
type Fetch<Schema extends HttpSchema> = FetchFunction<Schema> & FetchClient<Schema>;
|
|
973
977
|
/**
|
|
974
978
|
* Infers the schema of a {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch fetch instance}.
|
|
975
979
|
*
|
|
@@ -1054,4 +1058,4 @@ type InferFetchSchema<FetchInstance> = FetchInstance extends Fetch<infer Schema>
|
|
|
1054
1058
|
*/
|
|
1055
1059
|
declare function createFetch<Schema extends HttpSchema>(options: FetchOptions<Schema>): Fetch<Schema>;
|
|
1056
1060
|
|
|
1057
|
-
export {
|
|
1061
|
+
export { Fetch, type FetchDefaults, type FetchInput, type FetchOptions, FetchRequest, type FetchRequestConstructor, FetchRequestInit, type FetchRequestObject, FetchResponse, FetchResponseError, type FetchResponseErrorObject, FetchResponseErrorObjectOptions, type FetchResponseObject, type InferFetchSchema, type JSONStringified, createFetch };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/errors/FetchResponseError.ts","../../zimic-utils/dist/chunk-PAWJFY3S.mjs","../../zimic-utils/src/url/createRegExpFromURL.ts","../../zimic-utils/src/url/excludeURLParams.ts","../../zimic-utils/src/url/joinURL.ts","../src/client/FetchClient.ts","../src/client/factory.ts"],"names":["HttpHeaders","__defProp","__name","Request","HttpSearchParams"],"mappings":";;;;;;AAmGA,IAAM,kBAAA,GAAN,cAIU,KAAM,CAAA;AAAA,EACd,WAAA,CACS,SACA,QACP,EAAA;AACA,IAAA,KAAA,CAAM,CAAG,EAAA,OAAA,CAAQ,MAAM,CAAA,CAAA,EAAI,OAAQ,CAAA,GAAG,CAAuB,oBAAA,EAAA,QAAA,CAAS,MAAM,CAAA,EAAA,EAAK,QAAS,CAAA,UAAU,CAAE,CAAA,CAAA;AAH/F,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAGP,IAAA,IAAA,CAAK,IAAO,GAAA,oBAAA;AAAA;AACd,EA9GF;AAuGgB,IAAA,MAAA,CAAA,IAAA,EAAA,oBAAA,CAAA;AAAA;AAAA,EAqCd,SAAS,OAAyG,EAAA;AAChH,IAAM,MAAA,kBAAA,GAAqB,SAAS,kBAAsB,IAAA,KAAA;AAC1D,IAAM,MAAA,mBAAA,GAAsB,SAAS,mBAAuB,IAAA,KAAA;AAE5D,IAAA,MAAM,aAAgB,GAAA;AAAA,MACpB,MAAM,IAAK,CAAA,IAAA;AAAA,MACX,SAAS,IAAK,CAAA;AAAA,KAChB;AAEA,IAAI,IAAA,CAAC,kBAAsB,IAAA,CAAC,mBAAqB,EAAA;AAC/C,MAAA,MAAM,UAAU,IAAK,CAAA,sB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ACV,SAAS,KAAU,KAAA,IAAA,IAAQ,SAAS,KAAiB,YAAA,0BAAA,CAAA;AAAA;AAE1D,EAEA,eAAA,CACE,KACA,EAAA,MAAA,EACA,IACmD,EAAA;AACnD,IAAA,OACE,KAAiB,YAAA,0BAAA,IACjB,IAAK,CAAA,SAAA,CAAU,MAAM,OAAS,EAAA,MAAA,EAAQ,IAAI,CAAA,IAC1C,IAAK,CAAA,UAAA,CAAW,KAAM,CAAA,QAAA,EAAU,QAAQ,IAAI,CAAA;AAAA;AAGlD,CAAA;AAEA,IAAO,mBAAQ,GAAA,WAAA;;;AC9Nf,SAAS,YAAuC,OAA8C,EAAA;AAC5F,EAAA,MAAM,EAAE,KAAA,EAAU,GAAA,IAAI,oBAAoB,OAAO,CAAA;AACjD,EAAO,OAAA,KAAA;AACT;AAHS,MAAA,CAAA,WAAA,EAAA,aAAA,CAAA;AAKT,IAAO,eAAQ,GAAA","file":"index.js","sourcesContent":["import { HttpHeaders, HttpHeadersSchema, HttpSchema, HttpSchemaMethod, HttpSchemaPath } from '@zimic/http';\n\nimport { FetchRequest, FetchRequestObject, FetchResponse, FetchResponseObject } from '../types/requests';\n\n/**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObjectOptions {\n /**\n * Whether to include the body of the request in the plain object.\n *\n * @default false\n */\n includeRequestBody?: boolean;\n\n /**\n * Whether to include the body of the response in the plain object.\n *\n * @default false\n */\n includeResponseBody?: boolean;\n}\n\nexport namespace FetchResponseErrorObjectOptions {\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, including the body of\n * the request and/or response.\n */\n export type WithBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody: true } | { includeResponseBody: true });\n\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, excluding the body of\n * the request and/or response.\n */\n export type WithoutBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody?: false } | { includeResponseBody?: false });\n}\n\n/**\n * A plain object representation of a {@link FetchResponseError `FetchResponseError`}, compatible with JSON. It is useful\n * for serialization, debugging, and logging purposes.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObject {\n name: string;\n message: string;\n request: FetchRequestObject;\n response: FetchResponseObject;\n}\n\n/**\n * An error representing a response with a failure status code (4XX or 5XX).\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users/:userId': {\n * GET: {\n * response: {\n * 200: { body: User };\n * 404: { body: { message: string } };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * console.log(response.status); // 404\n *\n * console.log(response.error); // FetchResponseError<Schema, 'GET', '/users'>\n * console.log(response.error.request); // FetchRequest<Schema, 'GET', '/users'>\n * console.log(response.error.response); // FetchResponse<Schema, 'GET', '/users'>\n *\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerror `FetchResponseError` API reference}\n */\nclass FetchResponseError<\n Schema extends HttpSchema,\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n> extends Error {\n constructor(\n public request: FetchRequest<Schema, Method, Path>,\n public response: FetchResponse<Schema, Method, Path, true, 'manual'>,\n ) {\n super(`${request.method} ${request.url} failed with status ${response.status}: ${response.statusText}`);\n this.name = 'FetchResponseError';\n }\n\n /**\n * Converts this error into a plain object. This method is useful for serialization, debugging, and logging purposes.\n *\n * @example\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @param options Options for converting this error into a plain object. By default, the body of the request and\n * response will not be included.\n * @returns A plain object representing this error. If `options.includeRequestBody` or `options.includeResponseBody`\n * is `true`, the body of the request and response will be included, respectively, and the return is a `Promise`.\n * Otherwise, the return is the plain object itself without the bodies.\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\n toObject(options: FetchResponseErrorObjectOptions.WithBody): Promise<FetchResponseErrorObject>;\n toObject(options: FetchResponseErrorObjectOptions.WithoutBody): FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {\n const includeRequestBody = options?.includeRequestBody ?? false;\n const includeResponseBody = options?.includeResponseBody ?? false;\n\n const partialObject = {\n name: this.name,\n message: this.message,\n } satisfies Partial<FetchResponseErrorObject>;\n\n if (!includeRequestBody && !includeResponseBody) {\n const request = this.convertRequestToObject({ includeBody: false });\n const response = this.convertResponseToObject({ includeBody: false });\n return { ...partialObject, request, response };\n }\n\n return Promise.all([\n this.convertRequestToObject({ includeBody: includeRequestBody }),\n this.convertResponseToObject({ includeBody: includeResponseBody }),\n ]).then(([request, response]) => ({ ...partialObject, request, response }));\n }\n\n private convertRequestToObject(options: { includeBody: true }): Promise<FetchRequestObject>;\n private convertRequestToObject(options: { includeBody: false }): FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject {\n const requestObject: FetchRequestObject = {\n url: this.request.url,\n path: this.request.path,\n method: this.request.method,\n headers: HttpHeaders.prototype.toObject.call(this.request.headers) as HttpHeadersSchema,\n cache: this.request.cache,\n destination: this.request.destination,\n credentials: this.request.credentials,\n integrity: this.request.integrity,\n keepalive: this.request.keepalive,\n mode: this.request.mode,\n redirect: this.request.redirect,\n referrer: this.request.referrer,\n referrerPolicy: this.request.referrerPolicy,\n };\n\n if (!options.includeBody) {\n return requestObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.request.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return requestObject;\n });\n }\n\n private convertResponseToObject(options: { includeBody: true }): Promise<FetchResponseObject>;\n private convertResponseToObject(options: { includeBody: false }): FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject {\n const responseObject: FetchResponseObject = {\n url: this.response.url,\n type: this.response.type,\n status: this.response.status,\n statusText: this.response.statusText,\n ok: this.response.ok,\n headers: HttpHeaders.prototype.toObject.call(this.response.headers) as HttpHeadersSchema,\n redirected: this.response.redirected,\n };\n\n if (!options.includeBody) {\n return responseObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.response.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return responseObject;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFetchRequestError = FetchResponseError<any, any, any>;\n\nexport default FetchResponseError;\n","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\nexport { __name };\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map","export const URL_PATH_PARAM_REGEX = /\\/:([^/]+)/g;\n\nfunction createRegExpFromURL(url: string) {\n URL_PATH_PARAM_REGEX.lastIndex = 0;\n\n const urlWithReplacedPathParams = encodeURI(url)\n .replace(/([.()*?+$\\\\])/g, '\\\\$1')\n .replace(URL_PATH_PARAM_REGEX, '/(?<$1>[^/]+)')\n .replace(/^(\\/)|(\\/)$/g, '');\n\n return new RegExp(`^(?:/)?${urlWithReplacedPathParams}(?:/)?$`);\n}\n\nexport default createRegExpFromURL;\n","function excludeURLParams(url: URL) {\n url.hash = '';\n url.search = '';\n url.username = '';\n url.password = '';\n return url;\n}\n\nexport default excludeURLParams;\n","function joinURL(...parts: (URL | string)[]) {\n return parts\n .map((part, index) => {\n const isFirstPart = index === 0;\n const isLastPart = index === parts.length - 1;\n\n let partAsString = part.toString();\n\n if (!isFirstPart) {\n partAsString = partAsString.replace(/^\\//, '');\n }\n if (!isLastPart) {\n partAsString = partAsString.replace(/\\/$/, '');\n }\n\n return partAsString;\n })\n .filter((part) => part.length > 0)\n .join('/');\n}\n\nexport default joinURL;\n","import {\n HttpSchemaPath,\n HttpSchemaMethod,\n HttpSearchParams,\n LiteralHttpSchemaPathFromNonLiteral,\n HttpSchema,\n HttpHeaders,\n} from '@zimic/http';\nimport createRegexFromURL from '@zimic/utils/url/createRegExpFromURL';\nimport excludeURLParams from '@zimic/utils/url/excludeURLParams';\nimport joinURL from '@zimic/utils/url/joinURL';\n\nimport FetchResponseError from './errors/FetchResponseError';\nimport {\n FetchInput,\n FetchOptions,\n Fetch,\n FetchClient as PublicFetchClient,\n FetchDefaults,\n FetchFunction,\n} from './types/public';\nimport { FetchRequestConstructor, FetchRequestInit, FetchRequest, FetchResponse } from './types/requests';\n\nclass FetchClient<Schema extends HttpSchema>\n implements Omit<PublicFetchClient<Schema>, 'defaults' | 'loose' | 'Request'>\n{\n fetch: Fetch<Schema>;\n\n constructor({ onRequest, onResponse, ...defaults }: FetchOptions<Schema>) {\n this.fetch = this.createFetchFunction();\n\n this.fetch.defaults = {\n ...defaults,\n headers: defaults.headers ?? {},\n searchParams: defaults.searchParams ?? {},\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.fetch.loose = this.fetch as Fetch<any> as FetchFunction.Loose;\n\n this.fetch.Request = this.createRequestClass(this.fetch.defaults);\n this.fetch.onRequest = onRequest;\n this.fetch.onResponse = onResponse;\n }\n\n private createFetchFunction() {\n const fetch = async <\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) => {\n const request = await this.createFetchRequest<Method, Path>(input, init);\n const requestClone = request.clone();\n\n const rawResponse = await globalThis.fetch(\n // Optimize type checking by narrowing the type of request\n requestClone as Request,\n );\n const response = await this.createFetchResponse<\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >(request, rawResponse);\n\n return response;\n };\n\n Object.setPrototypeOf(fetch, this);\n\n return fetch as Fetch<Schema>;\n }\n\n private async createFetchRequest<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n let request = input instanceof Request ? input : new this.fetch.Request(input, init);\n\n if (this.fetch.onRequest) {\n const requestAfterInterceptor = await this.fetch.onRequest(\n // Optimize type checking by narrowing the type of request\n request as FetchRequest.Loose,\n );\n\n if (requestAfterInterceptor !== request) {\n const isFetchRequest = requestAfterInterceptor instanceof this.fetch.Request;\n\n request = isFetchRequest\n ? (requestAfterInterceptor as Request as typeof request)\n : new this.fetch.Request(requestAfterInterceptor as FetchInput<Schema, Method, Path>, init);\n }\n }\n\n return request;\n }\n\n private async createFetchResponse<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, rawResponse: Response) {\n let response = this.defineFetchResponseProperties<Method, Path>(fetchRequest, rawResponse);\n\n if (this.fetch.onResponse) {\n const responseAfterInterceptor = await this.fetch.onResponse(\n // Optimize type checking by narrowing the type of response\n response as FetchResponse.Loose,\n );\n\n const isFetchResponse =\n responseAfterInterceptor instanceof Response &&\n 'request' in responseAfterInterceptor &&\n responseAfterInterceptor.request instanceof this.fetch.Request;\n\n response = isFetchResponse\n ? (responseAfterInterceptor as typeof response)\n : this.defineFetchResponseProperties<Method, Path>(fetchRequest, responseAfterInterceptor);\n }\n\n return response;\n }\n\n private defineFetchResponseProperties<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, response: Response) {\n const fetchResponse = response as FetchResponse<Schema, Method, Path>;\n\n Object.defineProperty(fetchResponse, 'request', {\n value: fetchRequest satisfies FetchResponse.Loose['request'],\n writable: false,\n enumerable: true,\n configurable: false,\n });\n\n let responseError: FetchResponse.Loose['error'] | undefined;\n\n Object.defineProperty(fetchResponse, 'error', {\n get() {\n if (responseError === undefined) {\n responseError = fetchResponse.ok\n ? null\n : new FetchResponseError(\n fetchRequest,\n fetchResponse as FetchResponse<Schema, Method, Path, true, 'manual'>,\n );\n }\n return responseError;\n },\n enumerable: true,\n configurable: false,\n });\n\n return fetchResponse;\n }\n\n private createRequestClass(defaults: FetchDefaults) {\n class Request<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n > extends globalThis.Request {\n path: LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n\n constructor(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n const initWithDefaults = { ...defaults, ...init };\n\n const headersFromDefaults = new HttpHeaders(defaults.headers);\n const headersFromInit = new HttpHeaders((init satisfies RequestInit as RequestInit).headers);\n\n let url: URL;\n const baseURL = new URL(initWithDefaults.baseURL);\n\n if (input instanceof globalThis.Request) {\n // Optimize type checking by narrowing the type of input\n const request = input as globalThis.Request;\n\n // Optimize type checking by narrowing the type of headers\n const headersFromRequest = new HttpHeaders(input.headers as Headers);\n\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromRequest.toObject(),\n ...headersFromInit.toObject(),\n };\n\n super(request, initWithDefaults);\n\n url = new URL(input.url);\n } else {\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromInit.toObject(),\n };\n\n url = input instanceof URL ? new URL(input) : new URL(joinURL(baseURL, input));\n\n const searchParamsFromDefaults = new HttpSearchParams(defaults.searchParams);\n const searchParamsFromInit = new HttpSearchParams(initWithDefaults.searchParams);\n\n initWithDefaults.searchParams = {\n ...searchParamsFromDefaults.toObject(),\n ...searchParamsFromInit.toObject(),\n };\n\n url.search = new HttpSearchParams(initWithDefaults.searchParams).toString();\n\n super(url, initWithDefaults);\n }\n\n const baseURLWithoutTrailingSlash = baseURL.toString().replace(/\\/$/, '');\n\n this.path = excludeURLParams(url)\n .toString()\n .replace(baseURLWithoutTrailingSlash, '') as LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n }\n\n clone(): Request<Method, Path> {\n const rawClone = super.clone();\n\n return new Request<Method, Path>(\n rawClone as unknown as FetchInput<Schema, Method, Path>,\n rawClone as unknown as FetchRequestInit<\n Schema,\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >,\n );\n }\n }\n\n return Request as FetchRequestConstructor<Schema>;\n }\n\n isRequest<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n request: unknown,\n method: Method,\n path: Path,\n ): request is FetchRequest<Schema, Method, Path> {\n return (\n request instanceof Request &&\n request.method === method &&\n 'path' in request &&\n typeof request.path === 'string' &&\n createRegexFromURL(path).test(request.path)\n );\n }\n\n isResponse<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n response: unknown,\n method: Method,\n path: Path,\n ): response is FetchResponse<Schema, Method, Path> {\n return (\n response instanceof Response &&\n 'request' in response &&\n this.isRequest(response.request, method, path) &&\n 'error' in response &&\n (response.error === null || response.error instanceof FetchResponseError)\n );\n }\n\n isResponseError<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n error: unknown,\n method: Method,\n path: Path,\n ): error is FetchResponseError<Schema, Method, Path> {\n return (\n error instanceof FetchResponseError &&\n this.isRequest(error.request, method, path) &&\n this.isResponse(error.response, method, path)\n );\n }\n}\n\nexport default FetchClient;\n","import { HttpSchema } from '@zimic/http';\n\nimport FetchClient from './FetchClient';\nimport { FetchOptions, Fetch } from './types/public';\n\n/**\n * Creates a {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch fetch instance} typed with an HTTP\n * schema, closely compatible with the {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All\n * requests and responses are typed by default with the schema, including methods, paths, status codes, parameters, and\n * bodies.\n *\n * Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance.\n * {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch.defaults Default options} are also applied to the\n * requests, if provided.\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users': {\n * POST: {\n * request: {\n * headers: { 'content-type': 'application/json' };\n * body: { username: string };\n * };\n * response: {\n * 201: { body: User };\n * };\n * };\n *\n * GET: {\n * request: {\n * searchParams: {\n * query?: string;\n * page?: number;\n * limit?: number;\n * };\n * };\n * response: {\n * 200: { body: User[] };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#createfetch `createFetch(options)` API reference}\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}\n */\nfunction createFetch<Schema extends HttpSchema>(options: FetchOptions<Schema>): Fetch<Schema> {\n const { fetch } = new FetchClient<Schema>(options);\n return fetch;\n}\n\nexport default createFetch;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/errors/FetchResponseError.ts","../../zimic-utils/dist/chunk-PAWJFY3S.mjs","../../zimic-utils/src/url/createRegExpFromURL.ts","../../zimic-utils/src/url/excludeURLParams.ts","../../zimic-utils/src/url/joinURL.ts","../src/client/FetchClient.ts","../src/client/factory.ts"],"names":["HttpHeaders","__defProp","__name","Request","HttpSearchParams"],"mappings":";;;;;;AAmGA,IAAM,kBAAA,GAAN,cAIU,KAAM,CAAA;AAAA,EACd,WAAA,CACS,SACA,QACP,EAAA;AACA,IAAA,KAAA,CAAM,CAAG,EAAA,OAAA,CAAQ,MAAM,CAAA,CAAA,EAAI,OAAQ,CAAA,GAAG,CAAuB,oBAAA,EAAA,QAAA,CAAS,MAAM,CAAA,EAAA,EAAK,QAAS,CAAA,UAAU,CAAE,CAAA,CAAA;AAH/F,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAGP,IAAA,IAAA,CAAK,IAAO,GAAA,oBAAA;AAAA;AACd,EA9GF;AAuGgB,IAAA,MAAA,CAAA,IAAA,EAAA,oBAAA,CAAA;AAAA;AAAA,EAqCd,SAAS,OAAyG,EAAA;AAChH,IAAM,MAAA,kBAAA,GAAqB,SAAS,kBAAsB,IAAA,KAAA;AAC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AA,IAAI,CAAE,CAAA,IAAA,CAAK,QAAQ,IAAI,CAAA;AAAA;AAE9C,EAEA,UAAA,CACE,QACA,EAAA,MAAA,EACA,IACiD,EAAA;AACjD,IAAA,OACE,oBAAoB,QACpB,IAAA,SAAA,IAAa,QACb,IAAA,IAAA,CAAK,UAAU,QAAS,CAAA,OAAA,EAAS,MAAQ,EAAA,IAAI,KAC7C,OAAW,IAAA,QAAA,KACV,SAAS,KAAU,KAAA,IAAA,IAAQ,SAAS,KAAiB,YAAA,0BAAA,CAAA;AAAA;AAE1D,EAEA,eAAA,CACE,KACA,EAAA,MAAA,EACA,IACmD,EAAA;AACnD,IAAA,OACE,KAAiB,YAAA,0BAAA,IACjB,IAAK,CAAA,SAAA,CAAU,MAAM,OAAS,EAAA,MAAA,EAAQ,IAAI,CAAA,IAC1C,IAAK,CAAA,UAAA,CAAW,KAAM,CAAA,QAAA,EAAU,QAAQ,IAAI,CAAA;AAAA;AAGlD,CAAA;AAEA,IAAO,mBAAQ,GAAA,WAAA;;;ACvNf,SAAS,YAAuC,OAA8C,EAAA;AAC5F,EAAA,MAAM,EAAE,KAAA,EAAU,GAAA,IAAI,oBAAoB,OAAO,CAAA;AACjD,EAAO,OAAA,KAAA;AACT;AAHS,MAAA,CAAA,WAAA,EAAA,aAAA,CAAA;AAKT,IAAO,eAAQ,GAAA","file":"index.js","sourcesContent":["import { HttpHeaders, HttpHeadersSchema, HttpSchema, HttpSchemaMethod, HttpSchemaPath } from '@zimic/http';\n\nimport { FetchRequest, FetchRequestObject, FetchResponse, FetchResponseObject } from '../types/requests';\n\n/**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObjectOptions {\n /**\n * Whether to include the body of the request in the plain object.\n *\n * @default false\n */\n includeRequestBody?: boolean;\n\n /**\n * Whether to include the body of the response in the plain object.\n *\n * @default false\n */\n includeResponseBody?: boolean;\n}\n\nexport namespace FetchResponseErrorObjectOptions {\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, including the body of\n * the request and/or response.\n */\n export type WithBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody: true } | { includeResponseBody: true });\n\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, excluding the body of\n * the request and/or response.\n */\n export type WithoutBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody?: false } | { includeResponseBody?: false });\n}\n\n/**\n * A plain object representation of a {@link FetchResponseError `FetchResponseError`}, compatible with JSON. It is useful\n * for serialization, debugging, and logging purposes.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObject {\n name: string;\n message: string;\n request: FetchRequestObject;\n response: FetchResponseObject;\n}\n\n/**\n * An error representing a response with a failure status code (4XX or 5XX).\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users/:userId': {\n * GET: {\n * response: {\n * 200: { body: User };\n * 404: { body: { message: string } };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * console.log(response.status); // 404\n *\n * console.log(response.error); // FetchResponseError<Schema, 'GET', '/users'>\n * console.log(response.error.request); // FetchRequest<Schema, 'GET', '/users'>\n * console.log(response.error.response); // FetchResponse<Schema, 'GET', '/users'>\n *\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerror `FetchResponseError` API reference}\n */\nclass FetchResponseError<\n Schema extends HttpSchema,\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n> extends Error {\n constructor(\n public request: FetchRequest<Schema, Method, Path>,\n public response: FetchResponse<Schema, Method, Path, true, 'manual'>,\n ) {\n super(`${request.method} ${request.url} failed with status ${response.status}: ${response.statusText}`);\n this.name = 'FetchResponseError';\n }\n\n /**\n * Converts this error into a plain object. This method is useful for serialization, debugging, and logging purposes.\n *\n * @example\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @param options Options for converting this error into a plain object. By default, the body of the request and\n * response will not be included.\n * @returns A plain object representing this error. If `options.includeRequestBody` or `options.includeResponseBody`\n * is `true`, the body of the request and response will be included, respectively, and the return is a `Promise`.\n * Otherwise, the return is the plain object itself without the bodies.\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\n toObject(options: FetchResponseErrorObjectOptions.WithBody): Promise<FetchResponseErrorObject>;\n toObject(options: FetchResponseErrorObjectOptions.WithoutBody): FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {\n const includeRequestBody = options?.includeRequestBody ?? false;\n const includeResponseBody = options?.includeResponseBody ?? false;\n\n const partialObject = {\n name: this.name,\n message: this.message,\n } satisfies Partial<FetchResponseErrorObject>;\n\n if (!includeRequestBody && !includeResponseBody) {\n const request = this.convertRequestToObject({ includeBody: false });\n const response = this.convertResponseToObject({ includeBody: false });\n return { ...partialObject, request, response };\n }\n\n return Promise.all([\n this.convertRequestToObject({ includeBody: includeRequestBody }),\n this.convertResponseToObject({ includeBody: includeResponseBody }),\n ]).then(([request, response]) => ({ ...partialObject, request, response }));\n }\n\n private convertRequestToObject(options: { includeBody: true }): Promise<FetchRequestObject>;\n private convertRequestToObject(options: { includeBody: false }): FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject {\n const requestObject: FetchRequestObject = {\n url: this.request.url,\n path: this.request.path,\n method: this.request.method,\n headers: HttpHeaders.prototype.toObject.call(this.request.headers) as HttpHeadersSchema,\n cache: this.request.cache,\n destination: this.request.destination,\n credentials: this.request.credentials,\n integrity: this.request.integrity,\n keepalive: this.request.keepalive,\n mode: this.request.mode,\n redirect: this.request.redirect,\n referrer: this.request.referrer,\n referrerPolicy: this.request.referrerPolicy,\n };\n\n if (!options.includeBody) {\n return requestObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.request.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return requestObject;\n });\n }\n\n private convertResponseToObject(options: { includeBody: true }): Promise<FetchResponseObject>;\n private convertResponseToObject(options: { includeBody: false }): FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject {\n const responseObject: FetchResponseObject = {\n url: this.response.url,\n type: this.response.type,\n status: this.response.status,\n statusText: this.response.statusText,\n ok: this.response.ok,\n headers: HttpHeaders.prototype.toObject.call(this.response.headers) as HttpHeadersSchema,\n redirected: this.response.redirected,\n };\n\n if (!options.includeBody) {\n return responseObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.response.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return responseObject;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFetchRequestError = FetchResponseError<any, any, any>;\n\nexport default FetchResponseError;\n","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\nexport { __name };\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map","export const URL_PATH_PARAM_REGEX = /\\/:([^/]+)/g;\n\nfunction createRegExpFromURL(url: string) {\n URL_PATH_PARAM_REGEX.lastIndex = 0;\n\n const urlWithReplacedPathParams = encodeURI(url)\n .replace(/([.()*?+$\\\\])/g, '\\\\$1')\n .replace(URL_PATH_PARAM_REGEX, '/(?<$1>[^/]+)')\n .replace(/^(\\/)|(\\/)$/g, '');\n\n return new RegExp(`^(?:/)?${urlWithReplacedPathParams}(?:/)?$`);\n}\n\nexport default createRegExpFromURL;\n","function excludeURLParams(url: URL) {\n url.hash = '';\n url.search = '';\n url.username = '';\n url.password = '';\n return url;\n}\n\nexport default excludeURLParams;\n","function joinURL(...parts: (URL | string)[]) {\n return parts\n .map((part, index) => {\n const isFirstPart = index === 0;\n const isLastPart = index === parts.length - 1;\n\n let partAsString = part.toString();\n\n if (!isFirstPart) {\n partAsString = partAsString.replace(/^\\//, '');\n }\n if (!isLastPart) {\n partAsString = partAsString.replace(/\\/$/, '');\n }\n\n return partAsString;\n })\n .filter((part) => part.length > 0)\n .join('/');\n}\n\nexport default joinURL;\n","import {\n HttpSchemaPath,\n HttpSchemaMethod,\n HttpSearchParams,\n LiteralHttpSchemaPathFromNonLiteral,\n HttpSchema,\n HttpHeaders,\n} from '@zimic/http';\nimport createRegexFromURL from '@zimic/utils/url/createRegExpFromURL';\nimport excludeURLParams from '@zimic/utils/url/excludeURLParams';\nimport joinURL from '@zimic/utils/url/joinURL';\n\nimport FetchResponseError from './errors/FetchResponseError';\nimport { FetchInput, FetchOptions, Fetch, FetchClient as PublicFetchClient, FetchDefaults } from './types/public';\nimport { FetchRequestConstructor, FetchRequestInit, FetchRequest, FetchResponse } from './types/requests';\n\nclass FetchClient<Schema extends HttpSchema>\n implements Omit<PublicFetchClient<Schema>, 'defaults' | 'loose' | 'Request'>\n{\n fetch: Fetch<Schema>;\n\n constructor({ onRequest, onResponse, ...defaults }: FetchOptions<Schema>) {\n this.fetch = this.createFetchFunction();\n\n this.fetch.defaults = {\n ...defaults,\n headers: defaults.headers ?? {},\n searchParams: defaults.searchParams ?? {},\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.fetch.loose = this.fetch as Fetch<any> as Fetch.Loose;\n\n this.fetch.Request = this.createRequestClass(this.fetch.defaults);\n this.fetch.onRequest = onRequest;\n this.fetch.onResponse = onResponse;\n }\n\n private createFetchFunction() {\n const fetch = async <\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) => {\n const request = await this.createFetchRequest<Method, Path>(input, init);\n const requestClone = request.clone();\n\n const rawResponse = await globalThis.fetch(\n // Optimize type checking by narrowing the type of request\n requestClone as Request,\n );\n const response = await this.createFetchResponse<\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >(request, rawResponse);\n\n return response;\n };\n\n Object.setPrototypeOf(fetch, this);\n\n return fetch as Fetch<Schema>;\n }\n\n private async createFetchRequest<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n let request = input instanceof Request ? input : new this.fetch.Request(input, init);\n\n if (this.fetch.onRequest) {\n const requestAfterInterceptor = await this.fetch.onRequest(\n // Optimize type checking by narrowing the type of request\n request as FetchRequest.Loose,\n );\n\n if (requestAfterInterceptor !== request) {\n const isFetchRequest = requestAfterInterceptor instanceof this.fetch.Request;\n\n request = isFetchRequest\n ? (requestAfterInterceptor as Request as typeof request)\n : new this.fetch.Request(requestAfterInterceptor as FetchInput<Schema, Method, Path>, init);\n }\n }\n\n return request;\n }\n\n private async createFetchResponse<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, rawResponse: Response) {\n let response = this.defineFetchResponseProperties<Method, Path>(fetchRequest, rawResponse);\n\n if (this.fetch.onResponse) {\n const responseAfterInterceptor = await this.fetch.onResponse(\n // Optimize type checking by narrowing the type of response\n response as FetchResponse.Loose,\n );\n\n const isFetchResponse =\n responseAfterInterceptor instanceof Response &&\n 'request' in responseAfterInterceptor &&\n responseAfterInterceptor.request instanceof this.fetch.Request;\n\n response = isFetchResponse\n ? (responseAfterInterceptor as typeof response)\n : this.defineFetchResponseProperties<Method, Path>(fetchRequest, responseAfterInterceptor);\n }\n\n return response;\n }\n\n private defineFetchResponseProperties<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, response: Response) {\n const fetchResponse = response as FetchResponse<Schema, Method, Path>;\n\n Object.defineProperty(fetchResponse, 'request', {\n value: fetchRequest satisfies FetchResponse.Loose['request'],\n writable: false,\n enumerable: true,\n configurable: false,\n });\n\n let responseError: FetchResponse.Loose['error'] | undefined;\n\n Object.defineProperty(fetchResponse, 'error', {\n get() {\n if (responseError === undefined) {\n responseError = fetchResponse.ok\n ? null\n : new FetchResponseError(\n fetchRequest,\n fetchResponse as FetchResponse<Schema, Method, Path, true, 'manual'>,\n );\n }\n return responseError;\n },\n enumerable: true,\n configurable: false,\n });\n\n return fetchResponse;\n }\n\n private createRequestClass(defaults: FetchDefaults) {\n class Request<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n > extends globalThis.Request {\n path: LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n\n constructor(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n const initWithDefaults = { ...defaults, ...init };\n\n const headersFromDefaults = new HttpHeaders(defaults.headers);\n const headersFromInit = new HttpHeaders((init satisfies RequestInit as RequestInit).headers);\n\n let url: URL;\n const baseURL = new URL(initWithDefaults.baseURL);\n\n if (input instanceof globalThis.Request) {\n // Optimize type checking by narrowing the type of input\n const request = input as globalThis.Request;\n\n // Optimize type checking by narrowing the type of headers\n const headersFromRequest = new HttpHeaders(input.headers as Headers);\n\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromRequest.toObject(),\n ...headersFromInit.toObject(),\n };\n\n super(request, initWithDefaults);\n\n url = new URL(input.url);\n } else {\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromInit.toObject(),\n };\n\n url = input instanceof URL ? new URL(input) : new URL(joinURL(baseURL, input));\n\n const searchParamsFromDefaults = new HttpSearchParams(defaults.searchParams);\n const searchParamsFromInit = new HttpSearchParams(initWithDefaults.searchParams);\n\n initWithDefaults.searchParams = {\n ...searchParamsFromDefaults.toObject(),\n ...searchParamsFromInit.toObject(),\n };\n\n url.search = new HttpSearchParams(initWithDefaults.searchParams).toString();\n\n super(url, initWithDefaults);\n }\n\n const baseURLWithoutTrailingSlash = baseURL.toString().replace(/\\/$/, '');\n\n this.path = excludeURLParams(url)\n .toString()\n .replace(baseURLWithoutTrailingSlash, '') as LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n }\n\n clone(): Request<Method, Path> {\n const rawClone = super.clone();\n\n return new Request<Method, Path>(\n rawClone as unknown as FetchInput<Schema, Method, Path>,\n rawClone as unknown as FetchRequestInit<\n Schema,\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >,\n );\n }\n }\n\n return Request as FetchRequestConstructor<Schema>;\n }\n\n isRequest<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n request: unknown,\n method: Method,\n path: Path,\n ): request is FetchRequest<Schema, Method, Path> {\n return (\n request instanceof Request &&\n request.method === method &&\n 'path' in request &&\n typeof request.path === 'string' &&\n createRegexFromURL(path).test(request.path)\n );\n }\n\n isResponse<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n response: unknown,\n method: Method,\n path: Path,\n ): response is FetchResponse<Schema, Method, Path> {\n return (\n response instanceof Response &&\n 'request' in response &&\n this.isRequest(response.request, method, path) &&\n 'error' in response &&\n (response.error === null || response.error instanceof FetchResponseError)\n );\n }\n\n isResponseError<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n error: unknown,\n method: Method,\n path: Path,\n ): error is FetchResponseError<Schema, Method, Path> {\n return (\n error instanceof FetchResponseError &&\n this.isRequest(error.request, method, path) &&\n this.isResponse(error.response, method, path)\n );\n }\n}\n\nexport default FetchClient;\n","import { HttpSchema } from '@zimic/http';\n\nimport FetchClient from './FetchClient';\nimport { FetchOptions, Fetch } from './types/public';\n\n/**\n * Creates a {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch fetch instance} typed with an HTTP\n * schema, closely compatible with the {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All\n * requests and responses are typed by default with the schema, including methods, paths, status codes, parameters, and\n * bodies.\n *\n * Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance.\n * {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch.defaults Default options} are also applied to the\n * requests, if provided.\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users': {\n * POST: {\n * request: {\n * headers: { 'content-type': 'application/json' };\n * body: { username: string };\n * };\n * response: {\n * 201: { body: User };\n * };\n * };\n *\n * GET: {\n * request: {\n * searchParams: {\n * query?: string;\n * page?: number;\n * limit?: number;\n * };\n * };\n * response: {\n * 200: { body: User[] };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#createfetch `createFetch(options)` API reference}\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}\n */\nfunction createFetch<Schema extends HttpSchema>(options: FetchOptions<Schema>): Fetch<Schema> {\n const { fetch } = new FetchClient<Schema>(options);\n return fetch;\n}\n\nexport default createFetch;\n"]}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/errors/FetchResponseError.ts","../../zimic-utils/dist/chunk-PAWJFY3S.mjs","../../zimic-utils/src/url/createRegExpFromURL.ts","../../zimic-utils/src/url/excludeURLParams.ts","../../zimic-utils/src/url/joinURL.ts","../src/client/FetchClient.ts","../src/client/factory.ts"],"names":["__defProp","__name","Request","HttpHeaders"],"mappings":";;;;AAmGA,IAAM,kBAAA,GAAN,cAIU,KAAM,CAAA;AAAA,EACd,WAAA,CACS,SACA,QACP,EAAA;AACA,IAAA,KAAA,CAAM,CAAG,EAAA,OAAA,CAAQ,MAAM,CAAA,CAAA,EAAI,OAAQ,CAAA,GAAG,CAAuB,oBAAA,EAAA,QAAA,CAAS,MAAM,CAAA,EAAA,EAAK,QAAS,CAAA,UAAU,CAAE,CAAA,CAAA;AAH/F,IAAA,IAAA,CAAA,OAAA,G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ACA;AAAA,SAKF;AAAA;AACF;AAGF,IAAOA,OAAAA,QAAAA;AAAA;AACT,EAEA,SAAA,CACE,OACA,EAAA,MAAA,EACA,IAC+C,EAAA;AAC/C,IAAA,OACE,mBAAmB,OACnB,IAAA,OAAA,CAAQ,MAAW,KAAA,MAAA,IACnB,UAAU,OACV,IAAA,OAAO,OAAQ,CAAA,IAAA,KAAS,YACxB,2BAAmB,CAAA,IAAI,CAAE,CAAA,IAAA,CAAK,QAAQ,IAAI,CAAA;AAAA;AAE9C,EAEA,UAAA,CACE,QACA,EAAA,MAAA,EACA,IACiD,EAAA;AACjD,IAAA,OACE,oBAAoB,QACpB,IAAA,SAAA,IAAa,QACb,IAAA,IAAA,CAAK,UAAU,QAAS,CAAA,OAAA,EAAS,MAAQ,EAAA,IAAI,KAC7C,OAAW,IAAA,QAAA,KACV,SAAS,KAAU,KAAA,IAAA,IAAQ,SAAS,KAAiB,YAAA,0BAAA,CAAA;AAAA;AAE1D,EAEA,eAAA,CACE,KACA,EAAA,MAAA,EACA,IACmD,EAAA;AACnD,IAAA,OACE,KAAiB,YAAA,0BAAA,IACjB,IAAK,CAAA,SAAA,CAAU,MAAM,OAAS,EAAA,MAAA,EAAQ,IAAI,CAAA,IAC1C,IAAK,CAAA,UAAA,CAAW,KAAM,CAAA,QAAA,EAAU,QAAQ,IAAI,CAAA;AAAA;AAGlD,CAAA;AAEA,IAAO,mBAAQ,GAAA,WAAA;;;AC9Nf,SAAS,YAAuC,OAA8C,EAAA;AAC5F,EAAA,MAAM,EAAE,KAAA,EAAU,GAAA,IAAI,oBAAoB,OAAO,CAAA;AACjD,EAAO,OAAA,KAAA;AACT;AAHS,MAAA,CAAA,WAAA,EAAA,aAAA,CAAA;AAKT,IAAO,eAAQ,GAAA","file":"index.mjs","sourcesContent":["import { HttpHeaders, HttpHeadersSchema, HttpSchema, HttpSchemaMethod, HttpSchemaPath } from '@zimic/http';\n\nimport { FetchRequest, FetchRequestObject, FetchResponse, FetchResponseObject } from '../types/requests';\n\n/**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObjectOptions {\n /**\n * Whether to include the body of the request in the plain object.\n *\n * @default false\n */\n includeRequestBody?: boolean;\n\n /**\n * Whether to include the body of the response in the plain object.\n *\n * @default false\n */\n includeResponseBody?: boolean;\n}\n\nexport namespace FetchResponseErrorObjectOptions {\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, including the body of\n * the request and/or response.\n */\n export type WithBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody: true } | { includeResponseBody: true });\n\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, excluding the body of\n * the request and/or response.\n */\n export type WithoutBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody?: false } | { includeResponseBody?: false });\n}\n\n/**\n * A plain object representation of a {@link FetchResponseError `FetchResponseError`}, compatible with JSON. It is useful\n * for serialization, debugging, and logging purposes.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObject {\n name: string;\n message: string;\n request: FetchRequestObject;\n response: FetchResponseObject;\n}\n\n/**\n * An error representing a response with a failure status code (4XX or 5XX).\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users/:userId': {\n * GET: {\n * response: {\n * 200: { body: User };\n * 404: { body: { message: string } };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * console.log(response.status); // 404\n *\n * console.log(response.error); // FetchResponseError<Schema, 'GET', '/users'>\n * console.log(response.error.request); // FetchRequest<Schema, 'GET', '/users'>\n * console.log(response.error.response); // FetchResponse<Schema, 'GET', '/users'>\n *\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerror `FetchResponseError` API reference}\n */\nclass FetchResponseError<\n Schema extends HttpSchema,\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n> extends Error {\n constructor(\n public request: FetchRequest<Schema, Method, Path>,\n public response: FetchResponse<Schema, Method, Path, true, 'manual'>,\n ) {\n super(`${request.method} ${request.url} failed with status ${response.status}: ${response.statusText}`);\n this.name = 'FetchResponseError';\n }\n\n /**\n * Converts this error into a plain object. This method is useful for serialization, debugging, and logging purposes.\n *\n * @example\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @param options Options for converting this error into a plain object. By default, the body of the request and\n * response will not be included.\n * @returns A plain object representing this error. If `options.includeRequestBody` or `options.includeResponseBody`\n * is `true`, the body of the request and response will be included, respectively, and the return is a `Promise`.\n * Otherwise, the return is the plain object itself without the bodies.\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\n toObject(options: FetchResponseErrorObjectOptions.WithBody): Promise<FetchResponseErrorObject>;\n toObject(options: FetchResponseErrorObjectOptions.WithoutBody): FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {\n const includeRequestBody = options?.includeRequestBody ?? false;\n const includeResponseBody = options?.includeResponseBody ?? false;\n\n const partialObject = {\n name: this.name,\n message: this.message,\n } satisfies Partial<FetchResponseErrorObject>;\n\n if (!includeRequestBody && !includeResponseBody) {\n const request = this.convertRequestToObject({ includeBody: false });\n const response = this.convertResponseToObject({ includeBody: false });\n return { ...partialObject, request, response };\n }\n\n return Promise.all([\n this.convertRequestToObject({ includeBody: includeRequestBody }),\n this.convertResponseToObject({ includeBody: includeResponseBody }),\n ]).then(([request, response]) => ({ ...partialObject, request, response }));\n }\n\n private convertRequestToObject(options: { includeBody: true }): Promise<FetchRequestObject>;\n private convertRequestToObject(options: { includeBody: false }): FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject {\n const requestObject: FetchRequestObject = {\n url: this.request.url,\n path: this.request.path,\n method: this.request.method,\n headers: HttpHeaders.prototype.toObject.call(this.request.headers) as HttpHeadersSchema,\n cache: this.request.cache,\n destination: this.request.destination,\n credentials: this.request.credentials,\n integrity: this.request.integrity,\n keepalive: this.request.keepalive,\n mode: this.request.mode,\n redirect: this.request.redirect,\n referrer: this.request.referrer,\n referrerPolicy: this.request.referrerPolicy,\n };\n\n if (!options.includeBody) {\n return requestObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.request.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return requestObject;\n });\n }\n\n private convertResponseToObject(options: { includeBody: true }): Promise<FetchResponseObject>;\n private convertResponseToObject(options: { includeBody: false }): FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject {\n const responseObject: FetchResponseObject = {\n url: this.response.url,\n type: this.response.type,\n status: this.response.status,\n statusText: this.response.statusText,\n ok: this.response.ok,\n headers: HttpHeaders.prototype.toObject.call(this.response.headers) as HttpHeadersSchema,\n redirected: this.response.redirected,\n };\n\n if (!options.includeBody) {\n return responseObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.response.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return responseObject;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFetchRequestError = FetchResponseError<any, any, any>;\n\nexport default FetchResponseError;\n","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\nexport { __name };\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map","export const URL_PATH_PARAM_REGEX = /\\/:([^/]+)/g;\n\nfunction createRegExpFromURL(url: string) {\n URL_PATH_PARAM_REGEX.lastIndex = 0;\n\n const urlWithReplacedPathParams = encodeURI(url)\n .replace(/([.()*?+$\\\\])/g, '\\\\$1')\n .replace(URL_PATH_PARAM_REGEX, '/(?<$1>[^/]+)')\n .replace(/^(\\/)|(\\/)$/g, '');\n\n return new RegExp(`^(?:/)?${urlWithReplacedPathParams}(?:/)?$`);\n}\n\nexport default createRegExpFromURL;\n","function excludeURLParams(url: URL) {\n url.hash = '';\n url.search = '';\n url.username = '';\n url.password = '';\n return url;\n}\n\nexport default excludeURLParams;\n","function joinURL(...parts: (URL | string)[]) {\n return parts\n .map((part, index) => {\n const isFirstPart = index === 0;\n const isLastPart = index === parts.length - 1;\n\n let partAsString = part.toString();\n\n if (!isFirstPart) {\n partAsString = partAsString.replace(/^\\//, '');\n }\n if (!isLastPart) {\n partAsString = partAsString.replace(/\\/$/, '');\n }\n\n return partAsString;\n })\n .filter((part) => part.length > 0)\n .join('/');\n}\n\nexport default joinURL;\n","import {\n HttpSchemaPath,\n HttpSchemaMethod,\n HttpSearchParams,\n LiteralHttpSchemaPathFromNonLiteral,\n HttpSchema,\n HttpHeaders,\n} from '@zimic/http';\nimport createRegexFromURL from '@zimic/utils/url/createRegExpFromURL';\nimport excludeURLParams from '@zimic/utils/url/excludeURLParams';\nimport joinURL from '@zimic/utils/url/joinURL';\n\nimport FetchResponseError from './errors/FetchResponseError';\nimport {\n FetchInput,\n FetchOptions,\n Fetch,\n FetchClient as PublicFetchClient,\n FetchDefaults,\n FetchFunction,\n} from './types/public';\nimport { FetchRequestConstructor, FetchRequestInit, FetchRequest, FetchResponse } from './types/requests';\n\nclass FetchClient<Schema extends HttpSchema>\n implements Omit<PublicFetchClient<Schema>, 'defaults' | 'loose' | 'Request'>\n{\n fetch: Fetch<Schema>;\n\n constructor({ onRequest, onResponse, ...defaults }: FetchOptions<Schema>) {\n this.fetch = this.createFetchFunction();\n\n this.fetch.defaults = {\n ...defaults,\n headers: defaults.headers ?? {},\n searchParams: defaults.searchParams ?? {},\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.fetch.loose = this.fetch as Fetch<any> as FetchFunction.Loose;\n\n this.fetch.Request = this.createRequestClass(this.fetch.defaults);\n this.fetch.onRequest = onRequest;\n this.fetch.onResponse = onResponse;\n }\n\n private createFetchFunction() {\n const fetch = async <\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) => {\n const request = await this.createFetchRequest<Method, Path>(input, init);\n const requestClone = request.clone();\n\n const rawResponse = await globalThis.fetch(\n // Optimize type checking by narrowing the type of request\n requestClone as Request,\n );\n const response = await this.createFetchResponse<\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >(request, rawResponse);\n\n return response;\n };\n\n Object.setPrototypeOf(fetch, this);\n\n return fetch as Fetch<Schema>;\n }\n\n private async createFetchRequest<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n let request = input instanceof Request ? input : new this.fetch.Request(input, init);\n\n if (this.fetch.onRequest) {\n const requestAfterInterceptor = await this.fetch.onRequest(\n // Optimize type checking by narrowing the type of request\n request as FetchRequest.Loose,\n );\n\n if (requestAfterInterceptor !== request) {\n const isFetchRequest = requestAfterInterceptor instanceof this.fetch.Request;\n\n request = isFetchRequest\n ? (requestAfterInterceptor as Request as typeof request)\n : new this.fetch.Request(requestAfterInterceptor as FetchInput<Schema, Method, Path>, init);\n }\n }\n\n return request;\n }\n\n private async createFetchResponse<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, rawResponse: Response) {\n let response = this.defineFetchResponseProperties<Method, Path>(fetchRequest, rawResponse);\n\n if (this.fetch.onResponse) {\n const responseAfterInterceptor = await this.fetch.onResponse(\n // Optimize type checking by narrowing the type of response\n response as FetchResponse.Loose,\n );\n\n const isFetchResponse =\n responseAfterInterceptor instanceof Response &&\n 'request' in responseAfterInterceptor &&\n responseAfterInterceptor.request instanceof this.fetch.Request;\n\n response = isFetchResponse\n ? (responseAfterInterceptor as typeof response)\n : this.defineFetchResponseProperties<Method, Path>(fetchRequest, responseAfterInterceptor);\n }\n\n return response;\n }\n\n private defineFetchResponseProperties<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, response: Response) {\n const fetchResponse = response as FetchResponse<Schema, Method, Path>;\n\n Object.defineProperty(fetchResponse, 'request', {\n value: fetchRequest satisfies FetchResponse.Loose['request'],\n writable: false,\n enumerable: true,\n configurable: false,\n });\n\n let responseError: FetchResponse.Loose['error'] | undefined;\n\n Object.defineProperty(fetchResponse, 'error', {\n get() {\n if (responseError === undefined) {\n responseError = fetchResponse.ok\n ? null\n : new FetchResponseError(\n fetchRequest,\n fetchResponse as FetchResponse<Schema, Method, Path, true, 'manual'>,\n );\n }\n return responseError;\n },\n enumerable: true,\n configurable: false,\n });\n\n return fetchResponse;\n }\n\n private createRequestClass(defaults: FetchDefaults) {\n class Request<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n > extends globalThis.Request {\n path: LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n\n constructor(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n const initWithDefaults = { ...defaults, ...init };\n\n const headersFromDefaults = new HttpHeaders(defaults.headers);\n const headersFromInit = new HttpHeaders((init satisfies RequestInit as RequestInit).headers);\n\n let url: URL;\n const baseURL = new URL(initWithDefaults.baseURL);\n\n if (input instanceof globalThis.Request) {\n // Optimize type checking by narrowing the type of input\n const request = input as globalThis.Request;\n\n // Optimize type checking by narrowing the type of headers\n const headersFromRequest = new HttpHeaders(input.headers as Headers);\n\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromRequest.toObject(),\n ...headersFromInit.toObject(),\n };\n\n super(request, initWithDefaults);\n\n url = new URL(input.url);\n } else {\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromInit.toObject(),\n };\n\n url = input instanceof URL ? new URL(input) : new URL(joinURL(baseURL, input));\n\n const searchParamsFromDefaults = new HttpSearchParams(defaults.searchParams);\n const searchParamsFromInit = new HttpSearchParams(initWithDefaults.searchParams);\n\n initWithDefaults.searchParams = {\n ...searchParamsFromDefaults.toObject(),\n ...searchParamsFromInit.toObject(),\n };\n\n url.search = new HttpSearchParams(initWithDefaults.searchParams).toString();\n\n super(url, initWithDefaults);\n }\n\n const baseURLWithoutTrailingSlash = baseURL.toString().replace(/\\/$/, '');\n\n this.path = excludeURLParams(url)\n .toString()\n .replace(baseURLWithoutTrailingSlash, '') as LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n }\n\n clone(): Request<Method, Path> {\n const rawClone = super.clone();\n\n return new Request<Method, Path>(\n rawClone as unknown as FetchInput<Schema, Method, Path>,\n rawClone as unknown as FetchRequestInit<\n Schema,\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >,\n );\n }\n }\n\n return Request as FetchRequestConstructor<Schema>;\n }\n\n isRequest<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n request: unknown,\n method: Method,\n path: Path,\n ): request is FetchRequest<Schema, Method, Path> {\n return (\n request instanceof Request &&\n request.method === method &&\n 'path' in request &&\n typeof request.path === 'string' &&\n createRegexFromURL(path).test(request.path)\n );\n }\n\n isResponse<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n response: unknown,\n method: Method,\n path: Path,\n ): response is FetchResponse<Schema, Method, Path> {\n return (\n response instanceof Response &&\n 'request' in response &&\n this.isRequest(response.request, method, path) &&\n 'error' in response &&\n (response.error === null || response.error instanceof FetchResponseError)\n );\n }\n\n isResponseError<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n error: unknown,\n method: Method,\n path: Path,\n ): error is FetchResponseError<Schema, Method, Path> {\n return (\n error instanceof FetchResponseError &&\n this.isRequest(error.request, method, path) &&\n this.isResponse(error.response, method, path)\n );\n }\n}\n\nexport default FetchClient;\n","import { HttpSchema } from '@zimic/http';\n\nimport FetchClient from './FetchClient';\nimport { FetchOptions, Fetch } from './types/public';\n\n/**\n * Creates a {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch fetch instance} typed with an HTTP\n * schema, closely compatible with the {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All\n * requests and responses are typed by default with the schema, including methods, paths, status codes, parameters, and\n * bodies.\n *\n * Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance.\n * {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch.defaults Default options} are also applied to the\n * requests, if provided.\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users': {\n * POST: {\n * request: {\n * headers: { 'content-type': 'application/json' };\n * body: { username: string };\n * };\n * response: {\n * 201: { body: User };\n * };\n * };\n *\n * GET: {\n * request: {\n * searchParams: {\n * query?: string;\n * page?: number;\n * limit?: number;\n * };\n * };\n * response: {\n * 200: { body: User[] };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#createfetch `createFetch(options)` API reference}\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}\n */\nfunction createFetch<Schema extends HttpSchema>(options: FetchOptions<Schema>): Fetch<Schema> {\n const { fetch } = new FetchClient<Schema>(options);\n return fetch;\n}\n\nexport default createFetch;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/errors/FetchResponseError.ts","../../zimic-utils/dist/chunk-PAWJFY3S.mjs","../../zimic-utils/src/url/createRegExpFromURL.ts","../../zimic-utils/src/url/excludeURLParams.ts","../../zimic-utils/src/url/joinURL.ts","../src/client/FetchClient.ts","../src/client/factory.ts"],"names":["__defProp","__name","Request","HttpHeaders"],"mappings":";;;;AAmGA,IAAM,kBAAA,GAAN,cAIU,KAAM,CAAA;AAAA,EAC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AO,CAAA;AACjD,EAAO,OAAA,KAAA;AACT;AAHS,MAAA,CAAA,WAAA,EAAA,aAAA,CAAA;AAKT,IAAO,eAAQ,GAAA","file":"index.mjs","sourcesContent":["import { HttpHeaders, HttpHeadersSchema, HttpSchema, HttpSchemaMethod, HttpSchemaPath } from '@zimic/http';\n\nimport { FetchRequest, FetchRequestObject, FetchResponse, FetchResponseObject } from '../types/requests';\n\n/**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObjectOptions {\n /**\n * Whether to include the body of the request in the plain object.\n *\n * @default false\n */\n includeRequestBody?: boolean;\n\n /**\n * Whether to include the body of the response in the plain object.\n *\n * @default false\n */\n includeResponseBody?: boolean;\n}\n\nexport namespace FetchResponseErrorObjectOptions {\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, including the body of\n * the request and/or response.\n */\n export type WithBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody: true } | { includeResponseBody: true });\n\n /**\n * Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, excluding the body of\n * the request and/or response.\n */\n export type WithoutBody = FetchResponseErrorObjectOptions &\n ({ includeRequestBody?: false } | { includeResponseBody?: false });\n}\n\n/**\n * A plain object representation of a {@link FetchResponseError `FetchResponseError`}, compatible with JSON. It is useful\n * for serialization, debugging, and logging purposes.\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\nexport interface FetchResponseErrorObject {\n name: string;\n message: string;\n request: FetchRequestObject;\n response: FetchResponseObject;\n}\n\n/**\n * An error representing a response with a failure status code (4XX or 5XX).\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users/:userId': {\n * GET: {\n * response: {\n * 200: { body: User };\n * 404: { body: { message: string } };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * console.log(response.status); // 404\n *\n * console.log(response.error); // FetchResponseError<Schema, 'GET', '/users'>\n * console.log(response.error.request); // FetchRequest<Schema, 'GET', '/users'>\n * console.log(response.error.response); // FetchResponse<Schema, 'GET', '/users'>\n *\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerror `FetchResponseError` API reference}\n */\nclass FetchResponseError<\n Schema extends HttpSchema,\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n> extends Error {\n constructor(\n public request: FetchRequest<Schema, Method, Path>,\n public response: FetchResponse<Schema, Method, Path, true, 'manual'>,\n ) {\n super(`${request.method} ${request.url} failed with status ${response.status}: ${response.statusText}`);\n this.name = 'FetchResponseError';\n }\n\n /**\n * Converts this error into a plain object. This method is useful for serialization, debugging, and logging purposes.\n *\n * @example\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * const response = await fetch(`/users/${userId}`, {\n * method: 'GET',\n * });\n *\n * if (!response.ok) {\n * const plainError = response.error.toObject();\n * console.log(JSON.stringify(plainError));\n * // {\"name\":\"FetchResponseError\",\"message\":\"...\",\"request\":{...},\"response\":{...}}\n * }\n *\n * @param options Options for converting this error into a plain object. By default, the body of the request and\n * response will not be included.\n * @returns A plain object representing this error. If `options.includeRequestBody` or `options.includeResponseBody`\n * is `true`, the body of the request and response will be included, respectively, and the return is a `Promise`.\n * Otherwise, the return is the plain object itself without the bodies.\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\n toObject(options: FetchResponseErrorObjectOptions.WithBody): Promise<FetchResponseErrorObject>;\n toObject(options: FetchResponseErrorObjectOptions.WithoutBody): FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {\n const includeRequestBody = options?.includeRequestBody ?? false;\n const includeResponseBody = options?.includeResponseBody ?? false;\n\n const partialObject = {\n name: this.name,\n message: this.message,\n } satisfies Partial<FetchResponseErrorObject>;\n\n if (!includeRequestBody && !includeResponseBody) {\n const request = this.convertRequestToObject({ includeBody: false });\n const response = this.convertResponseToObject({ includeBody: false });\n return { ...partialObject, request, response };\n }\n\n return Promise.all([\n this.convertRequestToObject({ includeBody: includeRequestBody }),\n this.convertResponseToObject({ includeBody: includeResponseBody }),\n ]).then(([request, response]) => ({ ...partialObject, request, response }));\n }\n\n private convertRequestToObject(options: { includeBody: true }): Promise<FetchRequestObject>;\n private convertRequestToObject(options: { includeBody: false }): FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject;\n private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject {\n const requestObject: FetchRequestObject = {\n url: this.request.url,\n path: this.request.path,\n method: this.request.method,\n headers: HttpHeaders.prototype.toObject.call(this.request.headers) as HttpHeadersSchema,\n cache: this.request.cache,\n destination: this.request.destination,\n credentials: this.request.credentials,\n integrity: this.request.integrity,\n keepalive: this.request.keepalive,\n mode: this.request.mode,\n redirect: this.request.redirect,\n referrer: this.request.referrer,\n referrerPolicy: this.request.referrerPolicy,\n };\n\n if (!options.includeBody) {\n return requestObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.request.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return requestObject;\n });\n }\n\n private convertResponseToObject(options: { includeBody: true }): Promise<FetchResponseObject>;\n private convertResponseToObject(options: { includeBody: false }): FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject;\n private convertResponseToObject(options: {\n includeBody: boolean;\n }): Promise<FetchResponseObject> | FetchResponseObject {\n const responseObject: FetchResponseObject = {\n url: this.response.url,\n type: this.response.type,\n status: this.response.status,\n statusText: this.response.statusText,\n ok: this.response.ok,\n headers: HttpHeaders.prototype.toObject.call(this.response.headers) as HttpHeadersSchema,\n redirected: this.response.redirected,\n };\n\n if (!options.includeBody) {\n return responseObject;\n }\n\n // Optimize type checking by narrowing the type of the body\n const bodyAsTextPromise = this.response.text() as Promise<string>;\n\n return bodyAsTextPromise.then((bodyAsText) => {\n responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;\n return responseObject;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFetchRequestError = FetchResponseError<any, any, any>;\n\nexport default FetchResponseError;\n","var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: true });\n\nexport { __name };\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map\n//# sourceMappingURL=chunk-PAWJFY3S.mjs.map","export const URL_PATH_PARAM_REGEX = /\\/:([^/]+)/g;\n\nfunction createRegExpFromURL(url: string) {\n URL_PATH_PARAM_REGEX.lastIndex = 0;\n\n const urlWithReplacedPathParams = encodeURI(url)\n .replace(/([.()*?+$\\\\])/g, '\\\\$1')\n .replace(URL_PATH_PARAM_REGEX, '/(?<$1>[^/]+)')\n .replace(/^(\\/)|(\\/)$/g, '');\n\n return new RegExp(`^(?:/)?${urlWithReplacedPathParams}(?:/)?$`);\n}\n\nexport default createRegExpFromURL;\n","function excludeURLParams(url: URL) {\n url.hash = '';\n url.search = '';\n url.username = '';\n url.password = '';\n return url;\n}\n\nexport default excludeURLParams;\n","function joinURL(...parts: (URL | string)[]) {\n return parts\n .map((part, index) => {\n const isFirstPart = index === 0;\n const isLastPart = index === parts.length - 1;\n\n let partAsString = part.toString();\n\n if (!isFirstPart) {\n partAsString = partAsString.replace(/^\\//, '');\n }\n if (!isLastPart) {\n partAsString = partAsString.replace(/\\/$/, '');\n }\n\n return partAsString;\n })\n .filter((part) => part.length > 0)\n .join('/');\n}\n\nexport default joinURL;\n","import {\n HttpSchemaPath,\n HttpSchemaMethod,\n HttpSearchParams,\n LiteralHttpSchemaPathFromNonLiteral,\n HttpSchema,\n HttpHeaders,\n} from '@zimic/http';\nimport createRegexFromURL from '@zimic/utils/url/createRegExpFromURL';\nimport excludeURLParams from '@zimic/utils/url/excludeURLParams';\nimport joinURL from '@zimic/utils/url/joinURL';\n\nimport FetchResponseError from './errors/FetchResponseError';\nimport { FetchInput, FetchOptions, Fetch, FetchClient as PublicFetchClient, FetchDefaults } from './types/public';\nimport { FetchRequestConstructor, FetchRequestInit, FetchRequest, FetchResponse } from './types/requests';\n\nclass FetchClient<Schema extends HttpSchema>\n implements Omit<PublicFetchClient<Schema>, 'defaults' | 'loose' | 'Request'>\n{\n fetch: Fetch<Schema>;\n\n constructor({ onRequest, onResponse, ...defaults }: FetchOptions<Schema>) {\n this.fetch = this.createFetchFunction();\n\n this.fetch.defaults = {\n ...defaults,\n headers: defaults.headers ?? {},\n searchParams: defaults.searchParams ?? {},\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.fetch.loose = this.fetch as Fetch<any> as Fetch.Loose;\n\n this.fetch.Request = this.createRequestClass(this.fetch.defaults);\n this.fetch.onRequest = onRequest;\n this.fetch.onResponse = onResponse;\n }\n\n private createFetchFunction() {\n const fetch = async <\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) => {\n const request = await this.createFetchRequest<Method, Path>(input, init);\n const requestClone = request.clone();\n\n const rawResponse = await globalThis.fetch(\n // Optimize type checking by narrowing the type of request\n requestClone as Request,\n );\n const response = await this.createFetchResponse<\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >(request, rawResponse);\n\n return response;\n };\n\n Object.setPrototypeOf(fetch, this);\n\n return fetch as Fetch<Schema>;\n }\n\n private async createFetchRequest<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n >(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n let request = input instanceof Request ? input : new this.fetch.Request(input, init);\n\n if (this.fetch.onRequest) {\n const requestAfterInterceptor = await this.fetch.onRequest(\n // Optimize type checking by narrowing the type of request\n request as FetchRequest.Loose,\n );\n\n if (requestAfterInterceptor !== request) {\n const isFetchRequest = requestAfterInterceptor instanceof this.fetch.Request;\n\n request = isFetchRequest\n ? (requestAfterInterceptor as Request as typeof request)\n : new this.fetch.Request(requestAfterInterceptor as FetchInput<Schema, Method, Path>, init);\n }\n }\n\n return request;\n }\n\n private async createFetchResponse<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, rawResponse: Response) {\n let response = this.defineFetchResponseProperties<Method, Path>(fetchRequest, rawResponse);\n\n if (this.fetch.onResponse) {\n const responseAfterInterceptor = await this.fetch.onResponse(\n // Optimize type checking by narrowing the type of response\n response as FetchResponse.Loose,\n );\n\n const isFetchResponse =\n responseAfterInterceptor instanceof Response &&\n 'request' in responseAfterInterceptor &&\n responseAfterInterceptor.request instanceof this.fetch.Request;\n\n response = isFetchResponse\n ? (responseAfterInterceptor as typeof response)\n : this.defineFetchResponseProperties<Method, Path>(fetchRequest, responseAfterInterceptor);\n }\n\n return response;\n }\n\n private defineFetchResponseProperties<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.Literal<Schema, Method>,\n >(fetchRequest: FetchRequest<Schema, Method, Path>, response: Response) {\n const fetchResponse = response as FetchResponse<Schema, Method, Path>;\n\n Object.defineProperty(fetchResponse, 'request', {\n value: fetchRequest satisfies FetchResponse.Loose['request'],\n writable: false,\n enumerable: true,\n configurable: false,\n });\n\n let responseError: FetchResponse.Loose['error'] | undefined;\n\n Object.defineProperty(fetchResponse, 'error', {\n get() {\n if (responseError === undefined) {\n responseError = fetchResponse.ok\n ? null\n : new FetchResponseError(\n fetchRequest,\n fetchResponse as FetchResponse<Schema, Method, Path, true, 'manual'>,\n );\n }\n return responseError;\n },\n enumerable: true,\n configurable: false,\n });\n\n return fetchResponse;\n }\n\n private createRequestClass(defaults: FetchDefaults) {\n class Request<\n Method extends HttpSchemaMethod<Schema>,\n Path extends HttpSchemaPath.NonLiteral<Schema, Method>,\n > extends globalThis.Request {\n path: LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n\n constructor(\n input: FetchInput<Schema, Method, Path>,\n init: FetchRequestInit<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>,\n ) {\n const initWithDefaults = { ...defaults, ...init };\n\n const headersFromDefaults = new HttpHeaders(defaults.headers);\n const headersFromInit = new HttpHeaders((init satisfies RequestInit as RequestInit).headers);\n\n let url: URL;\n const baseURL = new URL(initWithDefaults.baseURL);\n\n if (input instanceof globalThis.Request) {\n // Optimize type checking by narrowing the type of input\n const request = input as globalThis.Request;\n\n // Optimize type checking by narrowing the type of headers\n const headersFromRequest = new HttpHeaders(input.headers as Headers);\n\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromRequest.toObject(),\n ...headersFromInit.toObject(),\n };\n\n super(request, initWithDefaults);\n\n url = new URL(input.url);\n } else {\n initWithDefaults.headers = {\n ...headersFromDefaults.toObject(),\n ...headersFromInit.toObject(),\n };\n\n url = input instanceof URL ? new URL(input) : new URL(joinURL(baseURL, input));\n\n const searchParamsFromDefaults = new HttpSearchParams(defaults.searchParams);\n const searchParamsFromInit = new HttpSearchParams(initWithDefaults.searchParams);\n\n initWithDefaults.searchParams = {\n ...searchParamsFromDefaults.toObject(),\n ...searchParamsFromInit.toObject(),\n };\n\n url.search = new HttpSearchParams(initWithDefaults.searchParams).toString();\n\n super(url, initWithDefaults);\n }\n\n const baseURLWithoutTrailingSlash = baseURL.toString().replace(/\\/$/, '');\n\n this.path = excludeURLParams(url)\n .toString()\n .replace(baseURLWithoutTrailingSlash, '') as LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>;\n }\n\n clone(): Request<Method, Path> {\n const rawClone = super.clone();\n\n return new Request<Method, Path>(\n rawClone as unknown as FetchInput<Schema, Method, Path>,\n rawClone as unknown as FetchRequestInit<\n Schema,\n Method,\n LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>\n >,\n );\n }\n }\n\n return Request as FetchRequestConstructor<Schema>;\n }\n\n isRequest<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n request: unknown,\n method: Method,\n path: Path,\n ): request is FetchRequest<Schema, Method, Path> {\n return (\n request instanceof Request &&\n request.method === method &&\n 'path' in request &&\n typeof request.path === 'string' &&\n createRegexFromURL(path).test(request.path)\n );\n }\n\n isResponse<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n response: unknown,\n method: Method,\n path: Path,\n ): response is FetchResponse<Schema, Method, Path> {\n return (\n response instanceof Response &&\n 'request' in response &&\n this.isRequest(response.request, method, path) &&\n 'error' in response &&\n (response.error === null || response.error instanceof FetchResponseError)\n );\n }\n\n isResponseError<Path extends HttpSchemaPath.Literal<Schema, Method>, Method extends HttpSchemaMethod<Schema>>(\n error: unknown,\n method: Method,\n path: Path,\n ): error is FetchResponseError<Schema, Method, Path> {\n return (\n error instanceof FetchResponseError &&\n this.isRequest(error.request, method, path) &&\n this.isResponse(error.response, method, path)\n );\n }\n}\n\nexport default FetchClient;\n","import { HttpSchema } from '@zimic/http';\n\nimport FetchClient from './FetchClient';\nimport { FetchOptions, Fetch } from './types/public';\n\n/**\n * Creates a {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch fetch instance} typed with an HTTP\n * schema, closely compatible with the {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All\n * requests and responses are typed by default with the schema, including methods, paths, status codes, parameters, and\n * bodies.\n *\n * Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance.\n * {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch.defaults Default options} are also applied to the\n * requests, if provided.\n *\n * @example\n * import { type HttpSchema } from '@zimic/http';\n * import { createFetch } from '@zimic/fetch';\n *\n * interface User {\n * id: string;\n * username: string;\n * }\n *\n * type Schema = HttpSchema<{\n * '/users': {\n * POST: {\n * request: {\n * headers: { 'content-type': 'application/json' };\n * body: { username: string };\n * };\n * response: {\n * 201: { body: User };\n * };\n * };\n *\n * GET: {\n * request: {\n * searchParams: {\n * query?: string;\n * page?: number;\n * limit?: number;\n * };\n * };\n * response: {\n * 200: { body: User[] };\n * };\n * };\n * };\n * }>;\n *\n * const fetch = createFetch<Schema>({\n * baseURL: 'http://localhost:3000',\n * });\n *\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#createfetch `createFetch(options)` API reference}\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}\n */\nfunction createFetch<Schema extends HttpSchema>(options: FetchOptions<Schema>): Fetch<Schema> {\n const { fetch } = new FetchClient<Schema>(options);\n return fetch;\n}\n\nexport default createFetch;\n"]}
|
package/package.json
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"api",
|
|
14
14
|
"static"
|
|
15
15
|
],
|
|
16
|
-
"version": "0.2.1-canary.
|
|
16
|
+
"version": "0.2.1-canary.1",
|
|
17
17
|
"repository": {
|
|
18
18
|
"type": "git",
|
|
19
19
|
"url": "https://github.com/zimicjs/zimic.git",
|
|
@@ -67,10 +67,10 @@
|
|
|
67
67
|
"typescript": "^5.8.2",
|
|
68
68
|
"vitest": "^3.0.9",
|
|
69
69
|
"@zimic/interceptor": "0.17.0-canary.2",
|
|
70
|
-
"@zimic/tsconfig": "0.0.0",
|
|
71
70
|
"@zimic/lint-staged-config": "0.0.0",
|
|
72
|
-
"@zimic/
|
|
73
|
-
"@zimic/
|
|
71
|
+
"@zimic/eslint-config-node": "0.0.0",
|
|
72
|
+
"@zimic/tsconfig": "0.0.0",
|
|
73
|
+
"@zimic/utils": "0.0.0"
|
|
74
74
|
},
|
|
75
75
|
"peerDependencies": {
|
|
76
76
|
"@zimic/http": "^0.3.0 || ^0.3.0-canary.0",
|
|
@@ -11,14 +11,7 @@ import excludeURLParams from '@zimic/utils/url/excludeURLParams';
|
|
|
11
11
|
import joinURL from '@zimic/utils/url/joinURL';
|
|
12
12
|
|
|
13
13
|
import FetchResponseError from './errors/FetchResponseError';
|
|
14
|
-
import {
|
|
15
|
-
FetchInput,
|
|
16
|
-
FetchOptions,
|
|
17
|
-
Fetch,
|
|
18
|
-
FetchClient as PublicFetchClient,
|
|
19
|
-
FetchDefaults,
|
|
20
|
-
FetchFunction,
|
|
21
|
-
} from './types/public';
|
|
14
|
+
import { FetchInput, FetchOptions, Fetch, FetchClient as PublicFetchClient, FetchDefaults } from './types/public';
|
|
22
15
|
import { FetchRequestConstructor, FetchRequestInit, FetchRequest, FetchResponse } from './types/requests';
|
|
23
16
|
|
|
24
17
|
class FetchClient<Schema extends HttpSchema>
|
|
@@ -36,7 +29,7 @@ class FetchClient<Schema extends HttpSchema>
|
|
|
36
29
|
};
|
|
37
30
|
|
|
38
31
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
39
|
-
this.fetch.loose = this.fetch as Fetch<any> as
|
|
32
|
+
this.fetch.loose = this.fetch as Fetch<any> as Fetch.Loose;
|
|
40
33
|
|
|
41
34
|
this.fetch.Request = this.createRequestClass(this.fetch.defaults);
|
|
42
35
|
this.fetch.onRequest = onRequest;
|
|
@@ -15,7 +15,73 @@ export type FetchInput<
|
|
|
15
15
|
Path extends HttpSchemaPath.NonLiteral<Schema, Method>,
|
|
16
16
|
> = Path | URL | FetchRequest<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>>;
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
/**
|
|
19
|
+
* A fetch instance typed with an HTTP schema, closely compatible with the
|
|
20
|
+
* {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All requests and responses are typed by
|
|
21
|
+
* default with the schema, including methods, paths, status codes, parameters, and bodies.
|
|
22
|
+
*
|
|
23
|
+
* Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance. Default
|
|
24
|
+
* options are also applied to the requests, if present in the instance.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* import { type HttpSchema } from '@zimic/http';
|
|
28
|
+
* import { createFetch } from '@zimic/fetch';
|
|
29
|
+
*
|
|
30
|
+
* interface User {
|
|
31
|
+
* id: string;
|
|
32
|
+
* username: string;
|
|
33
|
+
* }
|
|
34
|
+
*
|
|
35
|
+
* type Schema = HttpSchema<{
|
|
36
|
+
* '/users': {
|
|
37
|
+
* GET: {
|
|
38
|
+
* request: {
|
|
39
|
+
* searchParams: { query?: string };
|
|
40
|
+
* };
|
|
41
|
+
* response: {
|
|
42
|
+
* 200: { body: User[] };
|
|
43
|
+
* 404: { body: { message: string } };
|
|
44
|
+
* 500: { body: { message: string } };
|
|
45
|
+
* };
|
|
46
|
+
* };
|
|
47
|
+
* };
|
|
48
|
+
* }>;
|
|
49
|
+
*
|
|
50
|
+
* const fetch = createFetch<Schema>({
|
|
51
|
+
* baseURL: 'http://localhost:3000',
|
|
52
|
+
* headers: { 'accept-language': 'en' },
|
|
53
|
+
* });
|
|
54
|
+
*
|
|
55
|
+
* const response = await fetch('/users', {
|
|
56
|
+
* method: 'GET',
|
|
57
|
+
* searchParams: { query: 'u' },
|
|
58
|
+
* });
|
|
59
|
+
*
|
|
60
|
+
* if (response.status === 404) {
|
|
61
|
+
* return null; // User not found
|
|
62
|
+
* }
|
|
63
|
+
*
|
|
64
|
+
* if (!response.ok) {
|
|
65
|
+
* throw response.error;
|
|
66
|
+
* }
|
|
67
|
+
*
|
|
68
|
+
* const users = await response.json();
|
|
69
|
+
* return users; // User[]
|
|
70
|
+
*
|
|
71
|
+
* @param input The resource to fetch, either a path, a URL, or a {@link FetchRequest request}. If a path is provided, it
|
|
72
|
+
* is automatically prefixed with the base URL of the fetch instance when the request is sent. If a URL or a request
|
|
73
|
+
* is provided, it is used as is.
|
|
74
|
+
* @param init The request options. If a path or a URL is provided as the first argument, this argument is required and
|
|
75
|
+
* should contain at least the method of the request. If the first argument is a {@link FetchRequest request}, this
|
|
76
|
+
* argument is optional.
|
|
77
|
+
* @returns A promise that resolves to the response to the request.
|
|
78
|
+
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}
|
|
79
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/Fetch_API}
|
|
80
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/Request}
|
|
81
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/RequestInit}
|
|
82
|
+
* @see {@link https://developer.mozilla.org/docs/Web/API/Response}
|
|
83
|
+
*/
|
|
84
|
+
export interface Fetch<Schema extends HttpSchema> extends FetchClient<Schema> {
|
|
19
85
|
<
|
|
20
86
|
Method extends HttpSchemaMethod<Schema>,
|
|
21
87
|
Path extends HttpSchemaPath.NonLiteral<Schema, Method>,
|
|
@@ -35,7 +101,8 @@ export interface FetchFunction<Schema extends HttpSchema> {
|
|
|
35
101
|
): Promise<FetchResponse<Schema, Method, LiteralHttpSchemaPathFromNonLiteral<Schema, Method, Path>, false, Redirect>>;
|
|
36
102
|
}
|
|
37
103
|
|
|
38
|
-
export namespace
|
|
104
|
+
export namespace Fetch {
|
|
105
|
+
/** A loosely-typed version of {@link Fetch `fetch`}. This can be useful to make requests with fewer type constraints, */
|
|
39
106
|
export type Loose = (
|
|
40
107
|
input: string | URL | FetchRequest.Loose,
|
|
41
108
|
init?: FetchRequestInit.Loose,
|
|
@@ -299,7 +366,7 @@ export interface FetchClient<Schema extends HttpSchema> extends Pick<FetchOption
|
|
|
299
366
|
* @see {@link https://developer.mozilla.org/docs/Web/API/RequestInit}
|
|
300
367
|
* @see {@link https://developer.mozilla.org/docs/Web/API/Response}
|
|
301
368
|
*/
|
|
302
|
-
loose:
|
|
369
|
+
loose: Fetch.Loose;
|
|
303
370
|
|
|
304
371
|
/**
|
|
305
372
|
* A constructor for creating
|
|
@@ -521,74 +588,6 @@ export interface FetchClient<Schema extends HttpSchema> extends Pick<FetchOption
|
|
|
521
588
|
) => error is FetchResponseError<Schema, Method, Path>;
|
|
522
589
|
}
|
|
523
590
|
|
|
524
|
-
/**
|
|
525
|
-
* A fetch instance typed with an HTTP schema, closely compatible with the
|
|
526
|
-
* {@link https://developer.mozilla.org/docs/Web/API/Fetch_API native Fetch API}. All requests and responses are typed by
|
|
527
|
-
* default with the schema, including methods, paths, status codes, parameters, and bodies.
|
|
528
|
-
*
|
|
529
|
-
* Requests sent by the fetch instance have their URL automatically prefixed with the base URL of the instance. Default
|
|
530
|
-
* options are also applied to the requests, if present in the instance.
|
|
531
|
-
*
|
|
532
|
-
* @example
|
|
533
|
-
* import { type HttpSchema } from '@zimic/http';
|
|
534
|
-
* import { createFetch } from '@zimic/fetch';
|
|
535
|
-
*
|
|
536
|
-
* interface User {
|
|
537
|
-
* id: string;
|
|
538
|
-
* username: string;
|
|
539
|
-
* }
|
|
540
|
-
*
|
|
541
|
-
* type Schema = HttpSchema<{
|
|
542
|
-
* '/users': {
|
|
543
|
-
* GET: {
|
|
544
|
-
* request: {
|
|
545
|
-
* searchParams: { query?: string };
|
|
546
|
-
* };
|
|
547
|
-
* response: {
|
|
548
|
-
* 200: { body: User[] };
|
|
549
|
-
* 404: { body: { message: string } };
|
|
550
|
-
* 500: { body: { message: string } };
|
|
551
|
-
* };
|
|
552
|
-
* };
|
|
553
|
-
* };
|
|
554
|
-
* }>;
|
|
555
|
-
*
|
|
556
|
-
* const fetch = createFetch<Schema>({
|
|
557
|
-
* baseURL: 'http://localhost:3000',
|
|
558
|
-
* headers: { 'accept-language': 'en' },
|
|
559
|
-
* });
|
|
560
|
-
*
|
|
561
|
-
* const response = await fetch('/users', {
|
|
562
|
-
* method: 'GET',
|
|
563
|
-
* searchParams: { query: 'u' },
|
|
564
|
-
* });
|
|
565
|
-
*
|
|
566
|
-
* if (response.status === 404) {
|
|
567
|
-
* return null; // User not found
|
|
568
|
-
* }
|
|
569
|
-
*
|
|
570
|
-
* if (!response.ok) {
|
|
571
|
-
* throw response.error;
|
|
572
|
-
* }
|
|
573
|
-
*
|
|
574
|
-
* const users = await response.json();
|
|
575
|
-
* return users; // User[]
|
|
576
|
-
*
|
|
577
|
-
* @param input The resource to fetch, either a path, a URL, or a {@link FetchRequest request}. If a path is provided, it
|
|
578
|
-
* is automatically prefixed with the base URL of the fetch instance when the request is sent. If a URL or a request
|
|
579
|
-
* is provided, it is used as is.
|
|
580
|
-
* @param init The request options. If a path or a URL is provided as the first argument, this argument is required and
|
|
581
|
-
* should contain at least the method of the request. If the first argument is a {@link FetchRequest request}, this
|
|
582
|
-
* argument is optional.
|
|
583
|
-
* @returns A promise that resolves to the response to the request.
|
|
584
|
-
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch `fetch` API reference}
|
|
585
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/Fetch_API}
|
|
586
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/Request}
|
|
587
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/RequestInit}
|
|
588
|
-
* @see {@link https://developer.mozilla.org/docs/Web/API/Response}
|
|
589
|
-
*/
|
|
590
|
-
export type Fetch<Schema extends HttpSchema> = FetchFunction<Schema> & FetchClient<Schema>;
|
|
591
|
-
|
|
592
591
|
/**
|
|
593
592
|
* Infers the schema of a {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetch fetch instance}.
|
|
594
593
|
*
|
|
@@ -30,37 +30,42 @@ type FetchRequestInitHeaders<RequestSchema extends HttpRequestSchema> =
|
|
|
30
30
|
| RequestSchema['headers']
|
|
31
31
|
| HttpHeaders<Default<RequestSchema['headers']>>;
|
|
32
32
|
|
|
33
|
-
type FetchRequestInitWithHeaders<RequestSchema extends HttpRequestSchema> =
|
|
34
|
-
?
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
type FetchRequestInitWithHeaders<RequestSchema extends HttpRequestSchema> = 'headers' extends keyof RequestSchema
|
|
34
|
+
? [RequestSchema['headers']] extends [never]
|
|
35
|
+
? { headers?: undefined }
|
|
36
|
+
: undefined extends RequestSchema['headers']
|
|
37
|
+
? { headers?: FetchRequestInitHeaders<RequestSchema> }
|
|
38
|
+
: { headers: FetchRequestInitHeaders<RequestSchema> }
|
|
39
|
+
: { headers?: undefined };
|
|
38
40
|
|
|
39
41
|
type FetchRequestInitSearchParams<RequestSchema extends HttpRequestSchema> =
|
|
40
42
|
| RequestSchema['searchParams']
|
|
41
43
|
| HttpSearchParams<Default<RequestSchema['searchParams']>>;
|
|
42
44
|
|
|
43
|
-
type FetchRequestInitWithSearchParams<RequestSchema extends HttpRequestSchema> =
|
|
44
|
-
|
|
45
|
-
] extends [never]
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
45
|
+
type FetchRequestInitWithSearchParams<RequestSchema extends HttpRequestSchema> =
|
|
46
|
+
'searchParams' extends keyof RequestSchema
|
|
47
|
+
? [RequestSchema['searchParams']] extends [never]
|
|
48
|
+
? { searchParams?: undefined }
|
|
49
|
+
: undefined extends RequestSchema['searchParams']
|
|
50
|
+
? { searchParams?: FetchRequestInitSearchParams<RequestSchema> }
|
|
51
|
+
: { searchParams: FetchRequestInitSearchParams<RequestSchema> }
|
|
52
|
+
: { searchParams?: undefined };
|
|
50
53
|
|
|
51
|
-
type FetchRequestInitWithBody<RequestSchema extends HttpRequestSchema> =
|
|
52
|
-
?
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
? { body?: ReplaceBy<RequestSchema['body'], undefined, null> }
|
|
56
|
-
: { body: RequestSchema['body'] }
|
|
57
|
-
: RequestSchema['body'] extends JSONValue
|
|
54
|
+
type FetchRequestInitWithBody<RequestSchema extends HttpRequestSchema> = 'body' extends keyof RequestSchema
|
|
55
|
+
? [RequestSchema['body']] extends [never]
|
|
56
|
+
? { body?: null }
|
|
57
|
+
: RequestSchema['body'] extends string
|
|
58
58
|
? undefined extends RequestSchema['body']
|
|
59
|
-
? { body?: JSONStringified<ReplaceBy<RequestSchema['body'], undefined, null>> }
|
|
60
|
-
: { body: JSONStringified<RequestSchema['body']> }
|
|
61
|
-
: undefined extends RequestSchema['body']
|
|
62
59
|
? { body?: ReplaceBy<RequestSchema['body'], undefined, null> }
|
|
63
|
-
: { body: RequestSchema['body'] }
|
|
60
|
+
: { body: RequestSchema['body'] }
|
|
61
|
+
: RequestSchema['body'] extends JSONValue
|
|
62
|
+
? undefined extends RequestSchema['body']
|
|
63
|
+
? { body?: JSONStringified<ReplaceBy<RequestSchema['body'], undefined, null>> }
|
|
64
|
+
: { body: JSONStringified<RequestSchema['body']> }
|
|
65
|
+
: undefined extends RequestSchema['body']
|
|
66
|
+
? { body?: ReplaceBy<RequestSchema['body'], undefined, null> }
|
|
67
|
+
: { body: RequestSchema['body'] }
|
|
68
|
+
: { body?: null };
|
|
64
69
|
|
|
65
70
|
type FetchRequestInitPerPath<RequestSchema extends HttpRequestSchema> = FetchRequestInitWithHeaders<RequestSchema> &
|
|
66
71
|
FetchRequestInitWithSearchParams<RequestSchema> &
|