@zimic/fetch 0.2.0-canary.1 → 0.2.0-canary.3
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 +40 -14
- package/dist/index.js +22 -22
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +22 -22
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -3
- package/src/client/FetchClient.ts +3 -1
- package/src/client/errors/FetchResponseError.ts +67 -34
package/dist/index.d.ts
CHANGED
|
@@ -305,7 +305,38 @@ type FetchRequestConstructor<Schema extends HttpSchema> = new <Method extends Ht
|
|
|
305
305
|
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}
|
|
306
306
|
*/
|
|
307
307
|
interface FetchResponseErrorObjectOptions {
|
|
308
|
-
|
|
308
|
+
/**
|
|
309
|
+
* Whether to include the body of the request in the plain object.
|
|
310
|
+
*
|
|
311
|
+
* @default false
|
|
312
|
+
*/
|
|
313
|
+
includeRequestBody?: boolean;
|
|
314
|
+
/**
|
|
315
|
+
* Whether to include the body of the response in the plain object.
|
|
316
|
+
*
|
|
317
|
+
* @default false
|
|
318
|
+
*/
|
|
319
|
+
includeResponseBody?: boolean;
|
|
320
|
+
}
|
|
321
|
+
declare namespace FetchResponseErrorObjectOptions {
|
|
322
|
+
/**
|
|
323
|
+
* Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, including the body of
|
|
324
|
+
* the request and/or response.
|
|
325
|
+
*/
|
|
326
|
+
type WithBody = FetchResponseErrorObjectOptions & ({
|
|
327
|
+
includeRequestBody: true;
|
|
328
|
+
} | {
|
|
329
|
+
includeResponseBody: true;
|
|
330
|
+
});
|
|
331
|
+
/**
|
|
332
|
+
* Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, excluding the body of
|
|
333
|
+
* the request and/or response.
|
|
334
|
+
*/
|
|
335
|
+
type WithoutBody = FetchResponseErrorObjectOptions & ({
|
|
336
|
+
includeRequestBody?: false;
|
|
337
|
+
} | {
|
|
338
|
+
includeResponseBody?: false;
|
|
339
|
+
});
|
|
309
340
|
}
|
|
310
341
|
/**
|
|
311
342
|
* A plain object representation of a {@link FetchResponseError `FetchResponseError`}, compatible with JSON. It is useful
|
|
@@ -386,23 +417,18 @@ declare class FetchResponseError<Schema extends HttpSchema, Method extends HttpS
|
|
|
386
417
|
* // {"name":"FetchResponseError","message":"...","request":{...},"response":{...}}
|
|
387
418
|
* }
|
|
388
419
|
*
|
|
389
|
-
* @param options
|
|
390
|
-
*
|
|
391
|
-
* @returns A plain object representing this error. If `options.
|
|
392
|
-
*
|
|
393
|
-
* plain object itself without the
|
|
420
|
+
* @param options Options for converting this error into a plain object. By default, the body of the request and
|
|
421
|
+
* response will not be included.
|
|
422
|
+
* @returns A plain object representing this error. If `options.includeRequestBody` or `options.includeResponseBody`
|
|
423
|
+
* is `true`, the body of the request and response will be included, respectively, and the return is a `Promise`.
|
|
424
|
+
* Otherwise, the return is the plain object itself without the bodies.
|
|
394
425
|
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}
|
|
395
426
|
*/
|
|
396
|
-
toObject(options:
|
|
397
|
-
|
|
398
|
-
}): Promise<FetchResponseErrorObject>;
|
|
399
|
-
toObject(options?: {
|
|
400
|
-
includeBody?: false;
|
|
401
|
-
}): FetchResponseErrorObject;
|
|
427
|
+
toObject(options: FetchResponseErrorObjectOptions.WithBody): Promise<FetchResponseErrorObject>;
|
|
428
|
+
toObject(options: FetchResponseErrorObjectOptions.WithoutBody): FetchResponseErrorObject;
|
|
402
429
|
toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;
|
|
403
430
|
private convertRequestToObject;
|
|
404
431
|
private convertResponseToObject;
|
|
405
|
-
private convertHeadersToObject;
|
|
406
432
|
}
|
|
407
433
|
type AnyFetchRequestError = FetchResponseError<any, any, any>;
|
|
408
434
|
|
|
@@ -1028,4 +1054,4 @@ type InferFetchSchema<FetchInstance> = FetchInstance extends Fetch<infer Schema>
|
|
|
1028
1054
|
*/
|
|
1029
1055
|
declare function createFetch<Schema extends HttpSchema>(options: FetchOptions<Schema>): Fetch<Schema>;
|
|
1030
1056
|
|
|
1031
|
-
export { type Fetch, type FetchDefaults, type FetchInput, type FetchOptions, FetchRequest, type FetchRequestConstructor, FetchRequestInit, type FetchRequestObject, FetchResponse, FetchResponseError, type FetchResponseErrorObject,
|
|
1057
|
+
export { type 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
CHANGED
|
@@ -14,28 +14,29 @@ var FetchResponseError = class extends Error {
|
|
|
14
14
|
static {
|
|
15
15
|
__name(this, "FetchResponseError");
|
|
16
16
|
}
|
|
17
|
-
toObject(options
|
|
18
|
-
const
|
|
17
|
+
toObject(options) {
|
|
18
|
+
const includeRequestBody = options?.includeRequestBody ?? false;
|
|
19
|
+
const includeResponseBody = options?.includeResponseBody ?? false;
|
|
19
20
|
const partialObject = {
|
|
20
21
|
name: this.name,
|
|
21
22
|
message: this.message
|
|
22
23
|
};
|
|
23
|
-
if (!
|
|
24
|
+
if (!includeRequestBody && !includeResponseBody) {
|
|
24
25
|
const request = this.convertRequestToObject({ includeBody: false });
|
|
25
26
|
const response = this.convertResponseToObject({ includeBody: false });
|
|
26
27
|
return { ...partialObject, request, response };
|
|
27
28
|
}
|
|
28
29
|
return Promise.all([
|
|
29
|
-
this.convertRequestToObject({ includeBody:
|
|
30
|
-
this.convertResponseToObject({ includeBody:
|
|
30
|
+
this.convertRequestToObject({ includeBody: includeRequestBody }),
|
|
31
|
+
this.convertResponseToObject({ includeBody: includeResponseBody })
|
|
31
32
|
]).then(([request, response]) => ({ ...partialObject, request, response }));
|
|
32
33
|
}
|
|
33
34
|
convertRequestToObject(options) {
|
|
34
|
-
const
|
|
35
|
+
const requestObject = {
|
|
35
36
|
url: this.request.url,
|
|
36
37
|
path: this.request.path,
|
|
37
38
|
method: this.request.method,
|
|
38
|
-
headers:
|
|
39
|
+
headers: http.HttpHeaders.prototype.toObject.call(this.request.headers),
|
|
39
40
|
cache: this.request.cache,
|
|
40
41
|
destination: this.request.destination,
|
|
41
42
|
credentials: this.request.credentials,
|
|
@@ -47,33 +48,32 @@ var FetchResponseError = class extends Error {
|
|
|
47
48
|
referrerPolicy: this.request.referrerPolicy
|
|
48
49
|
};
|
|
49
50
|
if (!options.includeBody) {
|
|
50
|
-
return
|
|
51
|
+
return requestObject;
|
|
51
52
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
body
|
|
55
|
-
|
|
53
|
+
const bodyAsTextPromise = this.request.text();
|
|
54
|
+
return bodyAsTextPromise.then((bodyAsText) => {
|
|
55
|
+
requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;
|
|
56
|
+
return requestObject;
|
|
57
|
+
});
|
|
56
58
|
}
|
|
57
59
|
convertResponseToObject(options) {
|
|
58
|
-
const
|
|
60
|
+
const responseObject = {
|
|
59
61
|
url: this.response.url,
|
|
60
62
|
type: this.response.type,
|
|
61
63
|
status: this.response.status,
|
|
62
64
|
statusText: this.response.statusText,
|
|
63
65
|
ok: this.response.ok,
|
|
64
|
-
headers:
|
|
66
|
+
headers: http.HttpHeaders.prototype.toObject.call(this.response.headers),
|
|
65
67
|
redirected: this.response.redirected
|
|
66
68
|
};
|
|
67
69
|
if (!options.includeBody) {
|
|
68
|
-
return
|
|
70
|
+
return responseObject;
|
|
69
71
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
body
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
convertHeadersToObject(headers) {
|
|
76
|
-
return http.HttpHeaders.prototype.toObject.call(headers);
|
|
72
|
+
const bodyAsTextPromise = this.response.text();
|
|
73
|
+
return bodyAsTextPromise.then((bodyAsText) => {
|
|
74
|
+
responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;
|
|
75
|
+
return responseObject;
|
|
76
|
+
});
|
|
77
77
|
}
|
|
78
78
|
};
|
|
79
79
|
var FetchResponseError_default = FetchResponseError;
|
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":";;;;;;AAuEA,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,EAlFF;AA2EgB,IAAA,MAAA,CAAA,IAAA,EAAA,oBAAA,CAAA;AAAA;AAAA,EAqCd,QAAA,CACE,OAA2C,GAAA,EACmB,EAAA;AAC9D,IAAM,MAAA,EAAE,WAAc,GAAA,KAAA,EAAU,GAAA,OAAA;AAEhC,IAAA,MAAM,aAAgB,GAAA;AAAA,MACpB,MAAM,IAAK,CAAA,IAAA;AAAA,MACX,SAAS,IAAK,CAAA;AAAA,KAChB;AAEA,IAAA,IAAI,CAAC,WAA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,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;;;AC5Nf,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 includeBody?: boolean;\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.includeBody Whether to include the body of the request and response in the output. Defaults to\n * `false`.\n * @returns A plain object representing this error. If `options.includeBody` is `true`, the body of the request and\n * response will be included and the return of this method will be a `Promise`. Otherwise, the return will be the\n * plain object itself without the body.\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\n toObject(options: { includeBody: true }): Promise<FetchResponseErrorObject>;\n toObject(options?: { includeBody?: false }): FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;\n toObject(\n options: FetchResponseErrorObjectOptions = {},\n ): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {\n const { includeBody = false } = options;\n\n const partialObject = {\n name: this.name,\n message: this.message,\n } satisfies Partial<FetchResponseErrorObject>;\n\n if (!includeBody) {\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: true }),\n this.convertResponseToObject({ includeBody: true }),\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 const partialObject = {\n url: this.request.url,\n path: this.request.path,\n method: this.request.method,\n headers: this.convertHeadersToObject(this.request.headers),\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 } satisfies Partial<FetchRequestObject>;\n\n if (!options.includeBody) {\n return partialObject;\n }\n\n return this.request.text().then((bodyAsText: string) => ({\n ...partialObject,\n body: bodyAsText.length > 0 ? bodyAsText : null,\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 const partialObject = {\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: this.convertHeadersToObject(this.response.headers),\n redirected: this.response.redirected,\n } satisfies Partial<FetchResponseObject>;\n\n if (!options.includeBody) {\n return partialObject;\n }\n\n return this.response.text().then((bodyAsText: string) => ({\n ...partialObject,\n body: bodyAsText.length > 0 ? bodyAsText : null,\n }));\n }\n\n private convertHeadersToObject(headers: Headers) {\n return HttpHeaders.prototype.toObject.call(headers) as HttpHeadersSchema;\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 const headersFromRequest = new HttpHeaders(input.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,SAC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AA;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"]}
|
package/dist/index.mjs
CHANGED
|
@@ -12,28 +12,29 @@ var FetchResponseError = class extends Error {
|
|
|
12
12
|
static {
|
|
13
13
|
__name(this, "FetchResponseError");
|
|
14
14
|
}
|
|
15
|
-
toObject(options
|
|
16
|
-
const
|
|
15
|
+
toObject(options) {
|
|
16
|
+
const includeRequestBody = options?.includeRequestBody ?? false;
|
|
17
|
+
const includeResponseBody = options?.includeResponseBody ?? false;
|
|
17
18
|
const partialObject = {
|
|
18
19
|
name: this.name,
|
|
19
20
|
message: this.message
|
|
20
21
|
};
|
|
21
|
-
if (!
|
|
22
|
+
if (!includeRequestBody && !includeResponseBody) {
|
|
22
23
|
const request = this.convertRequestToObject({ includeBody: false });
|
|
23
24
|
const response = this.convertResponseToObject({ includeBody: false });
|
|
24
25
|
return { ...partialObject, request, response };
|
|
25
26
|
}
|
|
26
27
|
return Promise.all([
|
|
27
|
-
this.convertRequestToObject({ includeBody:
|
|
28
|
-
this.convertResponseToObject({ includeBody:
|
|
28
|
+
this.convertRequestToObject({ includeBody: includeRequestBody }),
|
|
29
|
+
this.convertResponseToObject({ includeBody: includeResponseBody })
|
|
29
30
|
]).then(([request, response]) => ({ ...partialObject, request, response }));
|
|
30
31
|
}
|
|
31
32
|
convertRequestToObject(options) {
|
|
32
|
-
const
|
|
33
|
+
const requestObject = {
|
|
33
34
|
url: this.request.url,
|
|
34
35
|
path: this.request.path,
|
|
35
36
|
method: this.request.method,
|
|
36
|
-
headers:
|
|
37
|
+
headers: HttpHeaders.prototype.toObject.call(this.request.headers),
|
|
37
38
|
cache: this.request.cache,
|
|
38
39
|
destination: this.request.destination,
|
|
39
40
|
credentials: this.request.credentials,
|
|
@@ -45,33 +46,32 @@ var FetchResponseError = class extends Error {
|
|
|
45
46
|
referrerPolicy: this.request.referrerPolicy
|
|
46
47
|
};
|
|
47
48
|
if (!options.includeBody) {
|
|
48
|
-
return
|
|
49
|
+
return requestObject;
|
|
49
50
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
body
|
|
53
|
-
|
|
51
|
+
const bodyAsTextPromise = this.request.text();
|
|
52
|
+
return bodyAsTextPromise.then((bodyAsText) => {
|
|
53
|
+
requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;
|
|
54
|
+
return requestObject;
|
|
55
|
+
});
|
|
54
56
|
}
|
|
55
57
|
convertResponseToObject(options) {
|
|
56
|
-
const
|
|
58
|
+
const responseObject = {
|
|
57
59
|
url: this.response.url,
|
|
58
60
|
type: this.response.type,
|
|
59
61
|
status: this.response.status,
|
|
60
62
|
statusText: this.response.statusText,
|
|
61
63
|
ok: this.response.ok,
|
|
62
|
-
headers:
|
|
64
|
+
headers: HttpHeaders.prototype.toObject.call(this.response.headers),
|
|
63
65
|
redirected: this.response.redirected
|
|
64
66
|
};
|
|
65
67
|
if (!options.includeBody) {
|
|
66
|
-
return
|
|
68
|
+
return responseObject;
|
|
67
69
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
body
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
convertHeadersToObject(headers) {
|
|
74
|
-
return HttpHeaders.prototype.toObject.call(headers);
|
|
70
|
+
const bodyAsTextPromise = this.response.text();
|
|
71
|
+
return bodyAsTextPromise.then((bodyAsText) => {
|
|
72
|
+
responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;
|
|
73
|
+
return responseObject;
|
|
74
|
+
});
|
|
75
75
|
}
|
|
76
76
|
};
|
|
77
77
|
var FetchResponseError_default = FetchResponseError;
|
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":";;;;AAuEA,IAAM,kBAAA,GAAN,cAIU,KAAM,CAAA;AAAA,EACd,WAAA,CACS,SACA,QACP,EAAA;AACA,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":["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 includeBody?: boolean;\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.includeBody Whether to include the body of the request and response in the output. Defaults to\n * `false`.\n * @returns A plain object representing this error. If `options.includeBody` is `true`, the body of the request and\n * response will be included and the return of this method will be a `Promise`. Otherwise, the return will be the\n * plain object itself without the body.\n * @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}\n */\n toObject(options: { includeBody: true }): Promise<FetchResponseErrorObject>;\n toObject(options?: { includeBody?: false }): FetchResponseErrorObject;\n toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;\n toObject(\n options: FetchResponseErrorObjectOptions = {},\n ): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {\n const { includeBody = false } = options;\n\n const partialObject = {\n name: this.name,\n message: this.message,\n } satisfies Partial<FetchResponseErrorObject>;\n\n if (!includeBody) {\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: true }),\n this.convertResponseToObject({ includeBody: true }),\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 const partialObject = {\n url: this.request.url,\n path: this.request.path,\n method: this.request.method,\n headers: this.convertHeadersToObject(this.request.headers),\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 } satisfies Partial<FetchRequestObject>;\n\n if (!options.includeBody) {\n return partialObject;\n }\n\n return this.request.text().then((bodyAsText: string) => ({\n ...partialObject,\n body: bodyAsText.length > 0 ? bodyAsText : null,\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 const partialObject = {\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: this.convertHeadersToObject(this.response.headers),\n redirected: this.response.redirected,\n } satisfies Partial<FetchResponseObject>;\n\n if (!options.includeBody) {\n return partialObject;\n }\n\n return this.response.text().then((bodyAsText: string) => ({\n ...partialObject,\n body: bodyAsText.length > 0 ? bodyAsText : null,\n }));\n }\n\n private convertHeadersToObject(headers: Headers) {\n return HttpHeaders.prototype.toObject.call(headers) as HttpHeadersSchema;\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 const headersFromRequest = new HttpHeaders(input.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,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;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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"]}
|
package/package.json
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"api",
|
|
14
14
|
"static"
|
|
15
15
|
],
|
|
16
|
-
"version": "0.2.0-canary.
|
|
16
|
+
"version": "0.2.0-canary.3",
|
|
17
17
|
"repository": {
|
|
18
18
|
"type": "git",
|
|
19
19
|
"url": "https://github.com/zimicjs/zimic.git",
|
|
@@ -43,6 +43,7 @@
|
|
|
43
43
|
"dist",
|
|
44
44
|
"index.d.ts"
|
|
45
45
|
],
|
|
46
|
+
"sideEffects": false,
|
|
46
47
|
"main": "./dist/index.js",
|
|
47
48
|
"module": "./dist/index.mjs",
|
|
48
49
|
"types": "index.d.ts",
|
|
@@ -67,9 +68,9 @@
|
|
|
67
68
|
"vitest": "^3.0.9",
|
|
68
69
|
"@zimic/eslint-config-node": "0.0.0",
|
|
69
70
|
"@zimic/interceptor": "0.16.0",
|
|
71
|
+
"@zimic/lint-staged-config": "0.0.0",
|
|
70
72
|
"@zimic/tsconfig": "0.0.0",
|
|
71
|
-
"@zimic/utils": "0.0.0"
|
|
72
|
-
"@zimic/lint-staged-config": "0.0.0"
|
|
73
|
+
"@zimic/utils": "0.0.0"
|
|
73
74
|
},
|
|
74
75
|
"peerDependencies": {
|
|
75
76
|
"@zimic/http": "^0.2.0 || ^0.2.0-canary.0",
|
|
@@ -179,7 +179,9 @@ class FetchClient<Schema extends HttpSchema>
|
|
|
179
179
|
if (input instanceof globalThis.Request) {
|
|
180
180
|
// Optimize type checking by narrowing the type of input
|
|
181
181
|
const request = input as globalThis.Request;
|
|
182
|
-
|
|
182
|
+
|
|
183
|
+
// Optimize type checking by narrowing the type of headers
|
|
184
|
+
const headersFromRequest = new HttpHeaders(input.headers as Headers);
|
|
183
185
|
|
|
184
186
|
initWithDefaults.headers = {
|
|
185
187
|
...headersFromDefaults.toObject(),
|
|
@@ -8,7 +8,35 @@ import { FetchRequest, FetchRequestObject, FetchResponse, FetchResponseObject }
|
|
|
8
8
|
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}
|
|
9
9
|
*/
|
|
10
10
|
export interface FetchResponseErrorObjectOptions {
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Whether to include the body of the request in the plain object.
|
|
13
|
+
*
|
|
14
|
+
* @default false
|
|
15
|
+
*/
|
|
16
|
+
includeRequestBody?: boolean;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Whether to include the body of the response in the plain object.
|
|
20
|
+
*
|
|
21
|
+
* @default false
|
|
22
|
+
*/
|
|
23
|
+
includeResponseBody?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export namespace FetchResponseErrorObjectOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, including the body of
|
|
29
|
+
* the request and/or response.
|
|
30
|
+
*/
|
|
31
|
+
export type WithBody = FetchResponseErrorObjectOptions &
|
|
32
|
+
({ includeRequestBody: true } | { includeResponseBody: true });
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Options for converting a {@link FetchResponseError `FetchResponseError`} into a plain object, excluding the body of
|
|
36
|
+
* the request and/or response.
|
|
37
|
+
*/
|
|
38
|
+
export type WithoutBody = FetchResponseErrorObjectOptions &
|
|
39
|
+
({ includeRequestBody?: false } | { includeResponseBody?: false });
|
|
12
40
|
}
|
|
13
41
|
|
|
14
42
|
/**
|
|
@@ -100,46 +128,46 @@ class FetchResponseError<
|
|
|
100
128
|
* // {"name":"FetchResponseError","message":"...","request":{...},"response":{...}}
|
|
101
129
|
* }
|
|
102
130
|
*
|
|
103
|
-
* @param options
|
|
104
|
-
*
|
|
105
|
-
* @returns A plain object representing this error. If `options.
|
|
106
|
-
*
|
|
107
|
-
* plain object itself without the
|
|
131
|
+
* @param options Options for converting this error into a plain object. By default, the body of the request and
|
|
132
|
+
* response will not be included.
|
|
133
|
+
* @returns A plain object representing this error. If `options.includeRequestBody` or `options.includeResponseBody`
|
|
134
|
+
* is `true`, the body of the request and response will be included, respectively, and the return is a `Promise`.
|
|
135
|
+
* Otherwise, the return is the plain object itself without the bodies.
|
|
108
136
|
* @see {@link https://github.com/zimicjs/zimic/wiki/api‐zimic‐fetch#fetchresponseerrortoobject `FetchResponseError#toObject` API reference}
|
|
109
137
|
*/
|
|
110
|
-
toObject(options:
|
|
111
|
-
toObject(options
|
|
138
|
+
toObject(options: FetchResponseErrorObjectOptions.WithBody): Promise<FetchResponseErrorObject>;
|
|
139
|
+
toObject(options: FetchResponseErrorObjectOptions.WithoutBody): FetchResponseErrorObject;
|
|
112
140
|
toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject;
|
|
113
|
-
toObject(
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const { includeBody = false } = options;
|
|
141
|
+
toObject(options?: FetchResponseErrorObjectOptions): Promise<FetchResponseErrorObject> | FetchResponseErrorObject {
|
|
142
|
+
const includeRequestBody = options?.includeRequestBody ?? false;
|
|
143
|
+
const includeResponseBody = options?.includeResponseBody ?? false;
|
|
117
144
|
|
|
118
145
|
const partialObject = {
|
|
119
146
|
name: this.name,
|
|
120
147
|
message: this.message,
|
|
121
148
|
} satisfies Partial<FetchResponseErrorObject>;
|
|
122
149
|
|
|
123
|
-
if (!
|
|
150
|
+
if (!includeRequestBody && !includeResponseBody) {
|
|
124
151
|
const request = this.convertRequestToObject({ includeBody: false });
|
|
125
152
|
const response = this.convertResponseToObject({ includeBody: false });
|
|
126
153
|
return { ...partialObject, request, response };
|
|
127
154
|
}
|
|
128
155
|
|
|
129
156
|
return Promise.all([
|
|
130
|
-
this.convertRequestToObject({ includeBody:
|
|
131
|
-
this.convertResponseToObject({ includeBody:
|
|
157
|
+
this.convertRequestToObject({ includeBody: includeRequestBody }),
|
|
158
|
+
this.convertResponseToObject({ includeBody: includeResponseBody }),
|
|
132
159
|
]).then(([request, response]) => ({ ...partialObject, request, response }));
|
|
133
160
|
}
|
|
134
161
|
|
|
135
162
|
private convertRequestToObject(options: { includeBody: true }): Promise<FetchRequestObject>;
|
|
136
163
|
private convertRequestToObject(options: { includeBody: false }): FetchRequestObject;
|
|
164
|
+
private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject;
|
|
137
165
|
private convertRequestToObject(options: { includeBody: boolean }): Promise<FetchRequestObject> | FetchRequestObject {
|
|
138
|
-
const
|
|
166
|
+
const requestObject: FetchRequestObject = {
|
|
139
167
|
url: this.request.url,
|
|
140
168
|
path: this.request.path,
|
|
141
169
|
method: this.request.method,
|
|
142
|
-
headers:
|
|
170
|
+
headers: HttpHeaders.prototype.toObject.call(this.request.headers) as HttpHeadersSchema,
|
|
143
171
|
cache: this.request.cache,
|
|
144
172
|
destination: this.request.destination,
|
|
145
173
|
credentials: this.request.credentials,
|
|
@@ -149,45 +177,50 @@ class FetchResponseError<
|
|
|
149
177
|
redirect: this.request.redirect,
|
|
150
178
|
referrer: this.request.referrer,
|
|
151
179
|
referrerPolicy: this.request.referrerPolicy,
|
|
152
|
-
}
|
|
180
|
+
};
|
|
153
181
|
|
|
154
182
|
if (!options.includeBody) {
|
|
155
|
-
return
|
|
183
|
+
return requestObject;
|
|
156
184
|
}
|
|
157
185
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
186
|
+
// Optimize type checking by narrowing the type of the body
|
|
187
|
+
const bodyAsTextPromise = this.request.text() as Promise<string>;
|
|
188
|
+
|
|
189
|
+
return bodyAsTextPromise.then((bodyAsText) => {
|
|
190
|
+
requestObject.body = bodyAsText.length > 0 ? bodyAsText : null;
|
|
191
|
+
return requestObject;
|
|
192
|
+
});
|
|
162
193
|
}
|
|
163
194
|
|
|
164
195
|
private convertResponseToObject(options: { includeBody: true }): Promise<FetchResponseObject>;
|
|
165
196
|
private convertResponseToObject(options: { includeBody: false }): FetchResponseObject;
|
|
197
|
+
private convertResponseToObject(options: {
|
|
198
|
+
includeBody: boolean;
|
|
199
|
+
}): Promise<FetchResponseObject> | FetchResponseObject;
|
|
166
200
|
private convertResponseToObject(options: {
|
|
167
201
|
includeBody: boolean;
|
|
168
202
|
}): Promise<FetchResponseObject> | FetchResponseObject {
|
|
169
|
-
const
|
|
203
|
+
const responseObject: FetchResponseObject = {
|
|
170
204
|
url: this.response.url,
|
|
171
205
|
type: this.response.type,
|
|
172
206
|
status: this.response.status,
|
|
173
207
|
statusText: this.response.statusText,
|
|
174
208
|
ok: this.response.ok,
|
|
175
|
-
headers:
|
|
209
|
+
headers: HttpHeaders.prototype.toObject.call(this.response.headers) as HttpHeadersSchema,
|
|
176
210
|
redirected: this.response.redirected,
|
|
177
|
-
}
|
|
211
|
+
};
|
|
178
212
|
|
|
179
213
|
if (!options.includeBody) {
|
|
180
|
-
return
|
|
214
|
+
return responseObject;
|
|
181
215
|
}
|
|
182
216
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
body: bodyAsText.length > 0 ? bodyAsText : null,
|
|
186
|
-
}));
|
|
187
|
-
}
|
|
217
|
+
// Optimize type checking by narrowing the type of the body
|
|
218
|
+
const bodyAsTextPromise = this.response.text() as Promise<string>;
|
|
188
219
|
|
|
189
|
-
|
|
190
|
-
|
|
220
|
+
return bodyAsTextPromise.then((bodyAsText) => {
|
|
221
|
+
responseObject.body = bodyAsText.length > 0 ? bodyAsText : null;
|
|
222
|
+
return responseObject;
|
|
223
|
+
});
|
|
191
224
|
}
|
|
192
225
|
}
|
|
193
226
|
|