@unshared/client 0.6.1 → 0.6.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.
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- var handleResponse = require("./CVzmr2NA.cjs");
2
+ var handleResponse = require("./CF3WrArO.cjs");
3
3
  async function fetch(route, options = {}) {
4
4
  const { url, init } = handleResponse.parseRequest(route, options);
5
5
  if (!url) throw new Error("Could not parse request URL");
@@ -11,4 +11,4 @@ async function request(route, options = {}) {
11
11
  }
12
12
  exports.fetch = fetch;
13
13
  exports.request = request;
14
- //# sourceMappingURL=DXrQkl1A.cjs.map
14
+ //# sourceMappingURL=B3aOBa4c.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"DXrQkl1A.cjs","sources":["../../utils/fetch.ts","../../utils/request.ts"],"sourcesContent":["import type { FetchOptions } from './parseRequest'\nimport { parseRequest } from './parseRequest'\n\n/**\n * Fetch a route with the provided options. This function will parse the route and\n * options to create a `Request` object and return the response from the server.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n * @example fetch('GET /users', { query: { limit: 10 } })\n */\nexport async function fetch(route: string, options?: FetchOptions): Promise<Response>\nexport async function fetch(route: string, options: FetchOptions = {}): Promise<Response> {\n const { url, init } = parseRequest(route, options)\n if (!url) throw new Error('Could not parse request URL')\n return await globalThis.fetch(url, init)\n}\n","import type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport interface RequestOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n Data = any,\n Response = globalThis.Response,\n> extends\n FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {\n\n /**\n * The callback that is called when an error occurs during the request.\n */\n onError?: (error: Error) => any\n\n /**\n * The callback that is called when data is received from the request. This callback\n * will be called for each chunk of data that is received from the request.\n */\n onData?: (data: Data) => any\n\n /**\n * The callback that is called when the request is successful. This callback will be\n * called after the request is complete and all data has been received.\n */\n onSuccess?: (response: Response) => any\n\n /**\n * The callback that is called when the status code is not OK. This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response) => any\n\n /**\n * The callback that is called when the request is complete. This callback will be called\n * after the request is complete and all data has been received.\n */\n onEnd?: (response: Response) => any\n}\n\n/**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\nexport async function request(route: string, options?: RequestOptions): Promise<unknown>\nexport async function request(route: string, options: RequestOptions = {}): Promise<unknown> {\n const response = await fetch(route, options)\n return await handleResponse(response, options)\n}\n"],"names":["parseRequest","handleResponse"],"mappings":";;AAaA,eAAsB,MAAM,OAAe,UAAwB,IAAuB;AACxF,QAAM,EAAE,KAAK,KAAA,IAASA,eAAAA,aAAa,OAAO,OAAO;AACjD,MAAI,CAAC,IAAW,OAAA,IAAI,MAAM,6BAA6B;AACvD,SAAO,MAAM,WAAW,MAAM,KAAK,IAAI;AACzC;ACiDA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO;AACpC,SAAA,MAAMC,eAAAA,eAAe,UAAU,OAAO;AAC/C;;;"}
1
+ {"version":3,"file":"B3aOBa4c.cjs","sources":["../../utils/fetch.ts","../../utils/request.ts"],"sourcesContent":["import type { FetchOptions } from './parseRequest'\nimport { parseRequest } from './parseRequest'\n\n/**\n * Fetch a route with the provided options. This function will parse the route and\n * options to create a `Request` object and return the response from the server.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n * @example fetch('GET /users', { query: { limit: 10 } })\n */\nexport async function fetch(route: string, options?: FetchOptions): Promise<Response>\nexport async function fetch(route: string, options: FetchOptions = {}): Promise<Response> {\n const { url, init } = parseRequest(route, options)\n if (!url) throw new Error('Could not parse request URL')\n return await globalThis.fetch(url, init)\n}\n","import type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport interface RequestOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n Data = any,\n Response = globalThis.Response,\n> extends\n FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {\n\n /**\n * The callback that is called when an error occurs during the request.\n */\n onError?: (error: Error) => any\n\n /**\n * The callback that is called when data is received from the request. This callback\n * will be called for each chunk of data that is received from the request.\n */\n onData?: (data: Data) => any\n\n /**\n * The callback that is called when the request is successful. This callback will be\n * called after the request is complete and all data has been received.\n */\n onSuccess?: (response: Response) => any\n\n /**\n * The callback that is called when the status code is not OK. This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response) => any\n\n /**\n * The callback that is called when the request is complete. This callback will be called\n * after the request is complete and all data has been received.\n */\n onEnd?: (response: Response) => any\n}\n\n/**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\nexport async function request(route: string, options?: RequestOptions): Promise<unknown>\nexport async function request(route: string, options: RequestOptions = {}): Promise<unknown> {\n const response = await fetch(route, options)\n return await handleResponse(response, options)\n}\n"],"names":["parseRequest","handleResponse"],"mappings":";;AAaA,eAAsB,MAAM,OAAe,UAAwB,IAAuB;AACxF,QAAM,EAAE,KAAK,KAAA,IAASA,eAAAA,aAAa,OAAO,OAAO;AACjD,MAAI,CAAC,IAAW,OAAA,IAAI,MAAM,6BAA6B;AACvD,SAAO,MAAM,WAAW,MAAM,KAAK,IAAI;AACzC;ACiDA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO;AACpC,SAAA,MAAMC,eAAAA,eAAe,UAAU,OAAO;AAC/C;;;"}
@@ -47,7 +47,7 @@ function toFormData(object) {
47
47
  }
48
48
  function parseRequestBody(context, options) {
49
49
  const { body } = options;
50
- context.init?.method && (["get", "head", "delete"].includes(context.init.method) || body != null && (isFormDataLike(body) ? (context.init.body = toFormData(body), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "multipart/form-data")) : body instanceof ReadableStream ? (context.init.body = body, context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/octet-stream")) : body instanceof File ? (context.init.body = body.stream(), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Disposition", `attachment; filename="${body.name}"`), setHeader(context.init.headers, "Content-Type", body.type), setHeader(context.init.headers, "Content-Length", body.size), setHeader(context.init.headers, "Content-Transfer-Encoding", "binary")) : isObjectLike(body) ? (context.init.body = JSON.stringify(body), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/json")) : context.init.body = body));
50
+ context.init?.method && (["get", "head", "delete"].includes(context.init.method) || body != null && (isFormDataLike(body) ? context.init.body = toFormData(body) : body instanceof ReadableStream ? (context.init.body = body, context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/octet-stream")) : body instanceof File ? (context.init.body = body.stream(), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Disposition", `attachment; filename="${body.name}"`), setHeader(context.init.headers, "Content-Type", body.type), setHeader(context.init.headers, "Content-Length", body.size), setHeader(context.init.headers, "Content-Transfer-Encoding", "binary")) : isObjectLike(body) ? (context.init.body = JSON.stringify(body), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/json")) : context.init.body = body));
51
51
  }
52
52
  function parseRequestHeaders(context, options) {
53
53
  const { headers } = options;
@@ -188,4 +188,4 @@ export {
188
188
  setCookie as s,
189
189
  toFormData as t
190
190
  };
191
- //# sourceMappingURL=CS5r-m4U.js.map
191
+ //# sourceMappingURL=Bsws660T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Bsws660T.js","sources":["../../utils/isObjectLike.ts","../../utils/setHeader.ts","../../utils/parseRequestBasicAuth.ts","../../utils/isFormDataLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/getHeader.ts","../../utils/getCookies.ts","../../utils/setCookie.ts","../../utils/parseRequestToken.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts","../../utils/handleResponseStreamJson.ts","../../utils/handleResponse.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\n\n/**\n * Predicate to check if a value is an object-like value.\n *\n * @param value The value to check.\n * @returns `true` if the value is an object-like value, `false` otherwise.\n * @example isObjectLike({}) // true\n */\nexport function isObjectLike(value: unknown): value is ObjectLike {\n return typeof value === 'object' && value !== null && value.constructor === Object\n}\n","/**\n * Set a header in the `HeadersInit` object whether it is a `Headers` instance, an\n * array of key-value pairs, or an object. It is also case-insensitive, meaning that\n * if a header with the same key but different case is found, it will be replaced.\n *\n * @param headers The headers to set the key-value pair in.\n * @param key The key of the header to set.\n * @param value The value of the header to set.\n * @example\n * const headers = new Headers()\n * setHeader(headers, 'Content-Type', 'application/json')\n * console.log(headers.get('Content-Type')) // 'application/json'\n */\nexport function setHeader(headers: HeadersInit, key: string, value: number | string): void {\n value = String(value)\n if (headers instanceof Headers) {\n headers.set(key, value)\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const index = headers.findIndex(([k]) => k.toLowerCase() === keyLower)\n if (index === -1) headers.push([key, value])\n headers[index] = [key, value]\n }\n else if (typeof headers === 'object' && headers !== null) {\n const keyLower = key.toLowerCase()\n for (const k in headers) {\n if (k.toLowerCase() !== keyLower) continue\n headers[k] = value\n return\n }\n headers[key] = value\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the basic authentication headers based on the provided username and password.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Authorization` header to the request.\n * const context = {}\n * parseRequestBasicAuth(context, { username: 'user', password: 'pass' })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Authorization': 'Basic dXNlcjpwYXNz' } } }\n */\nexport function parseRequestBasicAuth(context: Partial<RequestContext>, options: FetchOptions): void {\n const { username, password } = options\n\n // --- Return early if the username or password is not provided.\n if (typeof username !== 'string' || typeof password !== 'string') return\n\n // --- Encode the credentials and set the Authorization header.\n const credentials = btoa(`${username}:${password}`)\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Authorization', `Basic ${credentials}`)\n}\n","/**\n * A type that represents a FormData-like object, which is a plain object with\n * nested Blob, File, or FileList values. Or a FormData instance.\n */\nexport type FormDataLike = FormData | Record<string, Blob | File | FileList>\n\n/**\n * Predicate to check if a value is FormData-like, meaning it is a plain object\n * with nested Blob, File, or FileList values.\n *\n * @param value The value to check.\n * @returns `true` if the value is FormData-like, `false` otherwise.\n * @example isFormDataLike({ file: new File(['test'], 'test.txt') }) // true\n */\nexport function isFormDataLike(value: unknown): value is FormDataLike {\n if (typeof value !== 'object' || value === null) return false\n if (value instanceof FormData) return true\n const values = Object.values(value)\n if (values.length === 0) return false\n return values.every((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.every(item => item instanceof File)\n return x instanceof Blob\n })\n}\n","import type { FormDataLike } from './isFormDataLike'\n\n/**\n * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.\n *\n * @param object The object to cast to a `FormData` object.\n * @returns The `FormData` object.\n */\nexport function toFormData(object: FormDataLike): FormData {\n if (object instanceof FormData) return object\n const formData = new FormData()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const item of value)\n formData.append(key, item as Blob | string)\n }\n else {\n formData.append(key, value as Blob | string)\n }\n }\n return formData\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { setHeader } from './setHeader'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n */\nexport function parseRequestBody(context: Partial<RequestContext>, options: FetchOptions): void {\n const { body } = options\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (!context.init?.method) return\n if (['get', 'head', 'delete'].includes(context.init.method)) return\n\n // --- If no data is provided, return early.\n if (body === null || body === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(body)) {\n context.init.body = toFormData(body)\n }\n\n // --- If the data is a `ReadableStream`, pass it directly to the body.\n else if (body instanceof ReadableStream) {\n context.init.body = body\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/octet-stream')\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (body instanceof File) {\n context.init.body = body.stream()\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Disposition', `attachment; filename=\"${body.name}\"`)\n setHeader(context.init.headers, 'Content-Type', body.type)\n setHeader(context.init.headers, 'Content-Length', body.size)\n setHeader(context.init.headers, 'Content-Transfer-Encoding', 'binary')\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(body)) {\n context.init.body = JSON.stringify(body)\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/json')\n }\n\n // --- For all other data types, set the body directly.\n else {\n context.init.body = body as BodyInit\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Content-Type` header to the request.\n * const context = {}\n * parseRequestHeaders(context, { headers: { 'Content-Type': 'application/json' } })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }\n */\nexport function parseRequestHeaders(context: Partial<RequestContext>, options: FetchOptions): void {\n const { headers } = options\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (((typeof value !== 'string' || value.length === 0) && typeof value !== 'number')) continue\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, key, value)\n }\n}\n","/**\n * Get a header value from the `HeadersInit` object.\n *\n * @param headers The headers to get the key-value pair from.\n * @param key The key of the header to get.\n * @returns The value of the header.\n * @example\n * const headers = new Headers({ 'Content-Type': 'application/json' })\n * const contentType = getHeader(headers, 'Content-Type')\n * console.log(contentType) // 'application/json'\n */\nexport function getHeader(headers: HeadersInit, key: string): string | undefined {\n if (headers instanceof Headers) {\n return headers.get(key) ?? undefined\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const header = headers.find(([k]) => k.toLowerCase() === keyLower)\n return header ? header[1] : undefined\n }\n else {\n const keyLower = key.toLowerCase()\n const keys = Object.keys(headers)\n const index = keys.findIndex(k => k.toLowerCase() === keyLower)\n return index === -1 ? undefined : headers[keys[index]]\n }\n}\n","import { getHeader } from './getHeader'\n\n/**\n * Extract the cookies from the `HeadersInit` object.\n *\n * @param headers The headers to extract the cookies from.\n * @returns An array of cookies.\n * @example\n * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })\n * const cookies = getCookies(headers) // { key1: 'value1', key2: 'value2' }\n */\nexport function getCookies(headers: HeadersInit): Record<string, string> {\n const value = getHeader(headers, 'Cookie')\n if (!value) return {}\n\n // --- Parse the cookie header.\n const cookies: Record<string, string> = {}\n const parts = value.split(';')\n for (const part of parts) {\n const [key, value] = part.trim().split('=').map(v => v.trim())\n if (!key || !value) continue\n cookies[key] = value\n }\n\n // --- Return the cookies.\n return cookies\n}\n","import { getCookies } from './getCookies'\nimport { setHeader } from './setHeader'\n\n/**\n * Set a cookie in the `HeadersInit` object.\n *\n * @param headers The headers to set the cookie in.\n * @param key The key of the cookie to set.\n * @param value The value of the cookie to set.\n * @example\n * const headers = new Headers()\n * const cookie = { key: 'key1', value: 'value1', path: '/', secure: true }\n * setCookie(headers, cookie)\n * console.log(headers.get('Cookie')) // 'key1=value1; Path=/; Secure'\n */\nexport function setCookie(headers: HeadersInit, key: string, value: string): void {\n const cookies = { ...getCookies(headers), [key]: value }\n const header = Object.entries(cookies).map(([key, value]) => `${key}=${value}`).join('; ')\n setHeader(headers, 'Cookie', header)\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setCookie } from './setCookie'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the token and dynamically extend either the query, headers, or cookies.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n * // Append the `token` to the query parameters.\n * const context = { url: new URL('https://example.com') }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'query', tokenProperty: 'token' })\n * console.log(context.url.searchParams.get('token')) // 'my-token'\n *\n * @example\n * // Append the `token` to the headers.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'header', tokenProperty: 'Authorization' })\n * console.log(context.init.headers.get('Authorization')) // 'Bearer my-token'\n *\n * @example\n * // Append the `token` to the cookies.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'cookie', tokenProperty: 'token' })\n * console.log(context.init.headers.get('Cookie')) // 'token=my-token'\n */\nexport function parseRequestToken(context: Partial<RequestContext>, options: FetchOptions): void {\n const { token, tokenLocation = 'headers', tokenProperty } = options\n\n // --- Return early if the token is not provided.\n if (!token) return\n\n // --- Append the token to the query parameters.\n if (tokenLocation === 'query') {\n if (context.url instanceof URL === false) throw new Error('The `url` must be an instance of `URL`.')\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `query`.')\n context.url.searchParams.set(tokenProperty, token)\n }\n\n // --- Append the token to the path parameters.\n else if (tokenLocation === 'header') {\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n if (tokenProperty) setHeader(context.init.headers, tokenProperty, token)\n else setHeader(context.init.headers, 'Authorization', `Bearer ${token}`)\n }\n\n // --- Append the token to the cookie header.\n else if (tokenLocation === 'cookie') {\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `cookie`.')\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setCookie(context.init.headers, tokenProperty, token)\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid HTTP methods. */\nconst METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])\n\n/**\n * Parses the route name to extract the URL and method. It allows the url and method to be\n * provided in the route name, or in the options object. The method will default to 'get'.\n *\n * @param context The request context to mutate.\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(context: Partial<RequestContext>, route: string, options: FetchOptions): void {\n const { method, baseUrl } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_REQUEST.exec(route)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeMethod = method ?? match.groups.method ?? 'get'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const methodLower = routeMethod.toLowerCase()\n const methodIsValid = METHODS.has(methodLower)\n if (!methodIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeMethod}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n context.init = context.init ?? {}\n context.init.method = methodLower\n context.url = new URL(routeBaseUrl)\n\n // --- Append the path to the URL while making sure there are no double slashes.\n context.url.pathname += context.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n}\n","import type { Loose, MaybeLiteral, ObjectLike } from '@unshared/types'\nimport type { UnionMerge } from '@unshared/types'\nimport type { HttpHeader } from '../HttpHeaders'\nimport type { HttpMethod } from '../HttpMethods'\nimport type { SearchArrayFormat } from './toSearchParams'\nimport { isObjectLike } from './isObjectLike'\nimport { parseRequestBasicAuth } from './parseRequestBasicAuth'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestToken } from './parseRequestToken'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** The methods to use for the request. */\nexport type FetchMethod = Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\n\n/** Headers to include in the request. */\nexport type FetchHeaders = Partial<Record<MaybeLiteral<HttpHeader>, number | string>>\n\n/** Options to pass to the request. */\nexport interface FetchOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n> extends Omit<RequestInit, 'body' | 'headers' | 'method'> {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Method\n\n /**\n * The base URL to use for the request. This URL will be used to resolve the\n * path and query parameters of the request.\n *\n * @example 'https://api.example.com'\n */\n baseUrl?: BaseUrl\n\n /**\n * The data to include in the request. This data will be used to populate the\n * query parameters, body, and headers of the request based on the method type.\n *\n * @example { id: 1 }\n */\n data?: Loose<UnionMerge<Body | Headers | Query>>\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Parameters\n\n /**\n * The query parameters to include in the request.\n */\n query?: Loose<Query>\n\n /**\n * The format to use when serializing the query parameters.\n */\n queryArrayFormat?: SearchArrayFormat\n\n /**\n * The body to include in the request.\n */\n body?: Body extends ObjectLike ? Loose<Body> : Body\n\n /**\n * The headers to include in the request.\n */\n headers?: FetchHeaders & Headers\n\n /**\n * The username for basic authentication.\n */\n username?: string\n\n /**\n * The password for basic authentication.\n */\n password?: string\n\n /**\n * The token for API key authentication.\n */\n token?: string\n\n /**\n * The location where the token should be included in the request.\n */\n tokenLocation?: 'cookie' | 'header' | 'query'\n\n /**\n * The name of the key to use in the request for the token.\n */\n tokenProperty?: string\n}\n\nexport interface RequestContext {\n url: URL\n init: RequestInit\n}\n\n/**\n * Resolves the request body and/or query parameters based on the method type. This function\n * will mutate the `init` object to include the request body and headers based on the data type.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The URL and the `RequestInit` object.\n */\nexport function parseRequest(route: string, options: FetchOptions = {}): RequestContext {\n const {\n username,\n password,\n token,\n tokenLocation,\n tokenProperty,\n data,\n body,\n query,\n parameters,\n headers,\n method,\n baseUrl,\n queryArrayFormat,\n ...init\n } = options\n const context: Partial<RequestContext> = { init }\n const dataObject = isObjectLike(data) ? data : undefined\n\n // --- Parse the URL and insert the path parameters.\n parseRequestUrl(context, route, { baseUrl, method })\n parseRequestParameters(context, { parameters: parameters ?? dataObject })\n parseRequestBasicAuth(context, { username, password })\n\n // --- Depending on the method, parse the query, body, and headers.\n const requestMethod = context.init?.method?.toLowerCase() ?? 'get'\n const requestExpectsBody = ['post', 'put', 'patch'].includes(requestMethod)\n parseRequestQuery(context, { queryArrayFormat, query: requestExpectsBody ? query : query ?? dataObject })\n parseRequestToken(context, { token, tokenLocation, tokenProperty })\n parseRequestBody(context, { body: requestExpectsBody ? body ?? dataObject : undefined })\n parseRequestHeaders(context, { headers })\n\n // --- Return the context with the URL and the `RequestInit` object.\n return context as RequestContext\n}\n","import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\nasync function * createResponseStreamJsonIterator(response: Response, options: RequestOptions): AsyncGenerator<unknown, void, unknown> {\n const { onError, onSuccess, onData, onEnd } = options\n try {\n const body = response.body\n if (body === null) throw new Error('Could not read the response body, it is empty.')\n const reader = body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n const parts = new TextDecoder().decode(value).trim().split('\\0').filter(Boolean)\n\n // --- For each part, parse as JSON and yield the data.\n for (const part of parts) {\n const payload = JSON.parse(part) as unknown\n if (onData) onData(payload)\n yield payload\n }\n }\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a stream of JSON objects. This function\n * will parse the JSON objects and yield the data to the caller. If an error occurs, the `onError`\n * callback will be called and the function will return.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns An awaitable iterator that yields the parsed JSON objects.\n */\nexport function handleResponseStreamJson(response: Response, options: RequestOptions): Awaitable<AsyncIterable<unknown>, unknown[]> {\n const responseIterator = createResponseStreamJsonIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\n\n/**\n * Handle a request response. This function will parse the response based on the content type and\n * return the data. If an error occurs, the `onError` callback will be called and the function will\n * throw an error.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns The parsed data from the response.\n */\nexport async function handleResponse(response: Response, options: RequestOptions = {}): Promise<unknown> {\n const { onError, onSuccess, onData, onEnd, onFailure } = options\n const contentType = response.headers.get('Content-Type')\n\n // --- If the response is not OK, throw an error with the response message.\n if (!response.ok) {\n if (onFailure) await onFailure(response)\n if (onEnd) onEnd(response)\n throw new Error(response.statusText)\n }\n\n // --- If the status code is 204, return an empty response early.\n if (response.status === 204) {\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return\n }\n\n // --- If the response is a text content type, return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/json, parse the JSON and return it.\n if (contentType?.startsWith('application/json')) {\n return await response.json()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data as unknown\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/stream+json, return an iterator that parses the JSON.\n if (contentType?.startsWith('application/stream+json'))\n return handleResponseStreamJson(response, options)\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n}\n"],"names":["value","key"],"mappings":";;AASO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACEgB,SAAA,UAAU,SAAsB,KAAa,OAA8B;AAEzF,MADA,QAAQ,OAAO,KAAK,GAChB,mBAAmB;AACb,YAAA,IAAI,KAAK,KAAK;AAAA,WAEf,MAAM,QAAQ,OAAO,GAAG;AAC/B,UAAM,WAAW,IAAI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CAAC,UACD,UAAQ,OAAO,IAAI,GACnB,aAAW,UAAU,QAAQ,GAC1B,KACR,EACA,MAAM,CAAC,UAAiB;AACnB,UAAA,WAAS,QAAQ,KAAK,GACpB;AAAA,EAAA,CACP,EACA,QAAQ,MAAM;AACT,aAAO,MAAM,QAAQ;AAAA,EAAA,CAC1B,IAID,aAAa,WAAW,yBAAyB,IAC5C,yBAAyB,UAAU,OAAO,KAG/C,aAAW,UAAU,QAAQ,GAC7B,SAAO,MAAM,QAAQ,GAClB,SAAS;AAClB;"}
@@ -47,7 +47,7 @@ function toFormData(object) {
47
47
  }
48
48
  function parseRequestBody(context, options) {
49
49
  const { body } = options;
50
- context.init?.method && (["get", "head", "delete"].includes(context.init.method) || body != null && (isFormDataLike(body) ? (context.init.body = toFormData(body), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "multipart/form-data")) : body instanceof ReadableStream ? (context.init.body = body, context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/octet-stream")) : body instanceof File ? (context.init.body = body.stream(), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Disposition", `attachment; filename="${body.name}"`), setHeader(context.init.headers, "Content-Type", body.type), setHeader(context.init.headers, "Content-Length", body.size), setHeader(context.init.headers, "Content-Transfer-Encoding", "binary")) : isObjectLike(body) ? (context.init.body = JSON.stringify(body), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/json")) : context.init.body = body));
50
+ context.init?.method && (["get", "head", "delete"].includes(context.init.method) || body != null && (isFormDataLike(body) ? context.init.body = toFormData(body) : body instanceof ReadableStream ? (context.init.body = body, context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/octet-stream")) : body instanceof File ? (context.init.body = body.stream(), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Disposition", `attachment; filename="${body.name}"`), setHeader(context.init.headers, "Content-Type", body.type), setHeader(context.init.headers, "Content-Length", body.size), setHeader(context.init.headers, "Content-Transfer-Encoding", "binary")) : isObjectLike(body) ? (context.init.body = JSON.stringify(body), context.init.headers = context.init.headers ?? {}, setHeader(context.init.headers, "Content-Type", "application/json")) : context.init.body = body));
51
51
  }
52
52
  function parseRequestHeaders(context, options) {
53
53
  const { headers } = options;
@@ -186,4 +186,4 @@ exports.parseRequestUrl = parseRequestUrl;
186
186
  exports.setCookie = setCookie;
187
187
  exports.setHeader = setHeader;
188
188
  exports.toFormData = toFormData;
189
- //# sourceMappingURL=CVzmr2NA.cjs.map
189
+ //# sourceMappingURL=CF3WrArO.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CF3WrArO.cjs","sources":["../../utils/isObjectLike.ts","../../utils/setHeader.ts","../../utils/parseRequestBasicAuth.ts","../../utils/isFormDataLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/getHeader.ts","../../utils/getCookies.ts","../../utils/setCookie.ts","../../utils/parseRequestToken.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts","../../utils/handleResponseStreamJson.ts","../../utils/handleResponse.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\n\n/**\n * Predicate to check if a value is an object-like value.\n *\n * @param value The value to check.\n * @returns `true` if the value is an object-like value, `false` otherwise.\n * @example isObjectLike({}) // true\n */\nexport function isObjectLike(value: unknown): value is ObjectLike {\n return typeof value === 'object' && value !== null && value.constructor === Object\n}\n","/**\n * Set a header in the `HeadersInit` object whether it is a `Headers` instance, an\n * array of key-value pairs, or an object. It is also case-insensitive, meaning that\n * if a header with the same key but different case is found, it will be replaced.\n *\n * @param headers The headers to set the key-value pair in.\n * @param key The key of the header to set.\n * @param value The value of the header to set.\n * @example\n * const headers = new Headers()\n * setHeader(headers, 'Content-Type', 'application/json')\n * console.log(headers.get('Content-Type')) // 'application/json'\n */\nexport function setHeader(headers: HeadersInit, key: string, value: number | string): void {\n value = String(value)\n if (headers instanceof Headers) {\n headers.set(key, value)\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const index = headers.findIndex(([k]) => k.toLowerCase() === keyLower)\n if (index === -1) headers.push([key, value])\n headers[index] = [key, value]\n }\n else if (typeof headers === 'object' && headers !== null) {\n const keyLower = key.toLowerCase()\n for (const k in headers) {\n if (k.toLowerCase() !== keyLower) continue\n headers[k] = value\n return\n }\n headers[key] = value\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the basic authentication headers based on the provided username and password.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Authorization` header to the request.\n * const context = {}\n * parseRequestBasicAuth(context, { username: 'user', password: 'pass' })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Authorization': 'Basic dXNlcjpwYXNz' } } }\n */\nexport function parseRequestBasicAuth(context: Partial<RequestContext>, options: FetchOptions): void {\n const { username, password } = options\n\n // --- Return early if the username or password is not provided.\n if (typeof username !== 'string' || typeof password !== 'string') return\n\n // --- Encode the credentials and set the Authorization header.\n const credentials = btoa(`${username}:${password}`)\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Authorization', `Basic ${credentials}`)\n}\n","/**\n * A type that represents a FormData-like object, which is a plain object with\n * nested Blob, File, or FileList values. Or a FormData instance.\n */\nexport type FormDataLike = FormData | Record<string, Blob | File | FileList>\n\n/**\n * Predicate to check if a value is FormData-like, meaning it is a plain object\n * with nested Blob, File, or FileList values.\n *\n * @param value The value to check.\n * @returns `true` if the value is FormData-like, `false` otherwise.\n * @example isFormDataLike({ file: new File(['test'], 'test.txt') }) // true\n */\nexport function isFormDataLike(value: unknown): value is FormDataLike {\n if (typeof value !== 'object' || value === null) return false\n if (value instanceof FormData) return true\n const values = Object.values(value)\n if (values.length === 0) return false\n return values.every((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.every(item => item instanceof File)\n return x instanceof Blob\n })\n}\n","import type { FormDataLike } from './isFormDataLike'\n\n/**\n * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.\n *\n * @param object The object to cast to a `FormData` object.\n * @returns The `FormData` object.\n */\nexport function toFormData(object: FormDataLike): FormData {\n if (object instanceof FormData) return object\n const formData = new FormData()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const item of value)\n formData.append(key, item as Blob | string)\n }\n else {\n formData.append(key, value as Blob | string)\n }\n }\n return formData\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { setHeader } from './setHeader'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n */\nexport function parseRequestBody(context: Partial<RequestContext>, options: FetchOptions): void {\n const { body } = options\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (!context.init?.method) return\n if (['get', 'head', 'delete'].includes(context.init.method)) return\n\n // --- If no data is provided, return early.\n if (body === null || body === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(body)) {\n context.init.body = toFormData(body)\n }\n\n // --- If the data is a `ReadableStream`, pass it directly to the body.\n else if (body instanceof ReadableStream) {\n context.init.body = body\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/octet-stream')\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (body instanceof File) {\n context.init.body = body.stream()\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Disposition', `attachment; filename=\"${body.name}\"`)\n setHeader(context.init.headers, 'Content-Type', body.type)\n setHeader(context.init.headers, 'Content-Length', body.size)\n setHeader(context.init.headers, 'Content-Transfer-Encoding', 'binary')\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(body)) {\n context.init.body = JSON.stringify(body)\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/json')\n }\n\n // --- For all other data types, set the body directly.\n else {\n context.init.body = body as BodyInit\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Content-Type` header to the request.\n * const context = {}\n * parseRequestHeaders(context, { headers: { 'Content-Type': 'application/json' } })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }\n */\nexport function parseRequestHeaders(context: Partial<RequestContext>, options: FetchOptions): void {\n const { headers } = options\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (((typeof value !== 'string' || value.length === 0) && typeof value !== 'number')) continue\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, key, value)\n }\n}\n","/**\n * Get a header value from the `HeadersInit` object.\n *\n * @param headers The headers to get the key-value pair from.\n * @param key The key of the header to get.\n * @returns The value of the header.\n * @example\n * const headers = new Headers({ 'Content-Type': 'application/json' })\n * const contentType = getHeader(headers, 'Content-Type')\n * console.log(contentType) // 'application/json'\n */\nexport function getHeader(headers: HeadersInit, key: string): string | undefined {\n if (headers instanceof Headers) {\n return headers.get(key) ?? undefined\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const header = headers.find(([k]) => k.toLowerCase() === keyLower)\n return header ? header[1] : undefined\n }\n else {\n const keyLower = key.toLowerCase()\n const keys = Object.keys(headers)\n const index = keys.findIndex(k => k.toLowerCase() === keyLower)\n return index === -1 ? undefined : headers[keys[index]]\n }\n}\n","import { getHeader } from './getHeader'\n\n/**\n * Extract the cookies from the `HeadersInit` object.\n *\n * @param headers The headers to extract the cookies from.\n * @returns An array of cookies.\n * @example\n * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })\n * const cookies = getCookies(headers) // { key1: 'value1', key2: 'value2' }\n */\nexport function getCookies(headers: HeadersInit): Record<string, string> {\n const value = getHeader(headers, 'Cookie')\n if (!value) return {}\n\n // --- Parse the cookie header.\n const cookies: Record<string, string> = {}\n const parts = value.split(';')\n for (const part of parts) {\n const [key, value] = part.trim().split('=').map(v => v.trim())\n if (!key || !value) continue\n cookies[key] = value\n }\n\n // --- Return the cookies.\n return cookies\n}\n","import { getCookies } from './getCookies'\nimport { setHeader } from './setHeader'\n\n/**\n * Set a cookie in the `HeadersInit` object.\n *\n * @param headers The headers to set the cookie in.\n * @param key The key of the cookie to set.\n * @param value The value of the cookie to set.\n * @example\n * const headers = new Headers()\n * const cookie = { key: 'key1', value: 'value1', path: '/', secure: true }\n * setCookie(headers, cookie)\n * console.log(headers.get('Cookie')) // 'key1=value1; Path=/; Secure'\n */\nexport function setCookie(headers: HeadersInit, key: string, value: string): void {\n const cookies = { ...getCookies(headers), [key]: value }\n const header = Object.entries(cookies).map(([key, value]) => `${key}=${value}`).join('; ')\n setHeader(headers, 'Cookie', header)\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setCookie } from './setCookie'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the token and dynamically extend either the query, headers, or cookies.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n * // Append the `token` to the query parameters.\n * const context = { url: new URL('https://example.com') }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'query', tokenProperty: 'token' })\n * console.log(context.url.searchParams.get('token')) // 'my-token'\n *\n * @example\n * // Append the `token` to the headers.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'header', tokenProperty: 'Authorization' })\n * console.log(context.init.headers.get('Authorization')) // 'Bearer my-token'\n *\n * @example\n * // Append the `token` to the cookies.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'cookie', tokenProperty: 'token' })\n * console.log(context.init.headers.get('Cookie')) // 'token=my-token'\n */\nexport function parseRequestToken(context: Partial<RequestContext>, options: FetchOptions): void {\n const { token, tokenLocation = 'headers', tokenProperty } = options\n\n // --- Return early if the token is not provided.\n if (!token) return\n\n // --- Append the token to the query parameters.\n if (tokenLocation === 'query') {\n if (context.url instanceof URL === false) throw new Error('The `url` must be an instance of `URL`.')\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `query`.')\n context.url.searchParams.set(tokenProperty, token)\n }\n\n // --- Append the token to the path parameters.\n else if (tokenLocation === 'header') {\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n if (tokenProperty) setHeader(context.init.headers, tokenProperty, token)\n else setHeader(context.init.headers, 'Authorization', `Bearer ${token}`)\n }\n\n // --- Append the token to the cookie header.\n else if (tokenLocation === 'cookie') {\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `cookie`.')\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setCookie(context.init.headers, tokenProperty, token)\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid HTTP methods. */\nconst METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])\n\n/**\n * Parses the route name to extract the URL and method. It allows the url and method to be\n * provided in the route name, or in the options object. The method will default to 'get'.\n *\n * @param context The request context to mutate.\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(context: Partial<RequestContext>, route: string, options: FetchOptions): void {\n const { method, baseUrl } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_REQUEST.exec(route)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeMethod = method ?? match.groups.method ?? 'get'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const methodLower = routeMethod.toLowerCase()\n const methodIsValid = METHODS.has(methodLower)\n if (!methodIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeMethod}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n context.init = context.init ?? {}\n context.init.method = methodLower\n context.url = new URL(routeBaseUrl)\n\n // --- Append the path to the URL while making sure there are no double slashes.\n context.url.pathname += context.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n}\n","import type { Loose, MaybeLiteral, ObjectLike } from '@unshared/types'\nimport type { UnionMerge } from '@unshared/types'\nimport type { HttpHeader } from '../HttpHeaders'\nimport type { HttpMethod } from '../HttpMethods'\nimport type { SearchArrayFormat } from './toSearchParams'\nimport { isObjectLike } from './isObjectLike'\nimport { parseRequestBasicAuth } from './parseRequestBasicAuth'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestToken } from './parseRequestToken'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** The methods to use for the request. */\nexport type FetchMethod = Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\n\n/** Headers to include in the request. */\nexport type FetchHeaders = Partial<Record<MaybeLiteral<HttpHeader>, number | string>>\n\n/** Options to pass to the request. */\nexport interface FetchOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n> extends Omit<RequestInit, 'body' | 'headers' | 'method'> {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Method\n\n /**\n * The base URL to use for the request. This URL will be used to resolve the\n * path and query parameters of the request.\n *\n * @example 'https://api.example.com'\n */\n baseUrl?: BaseUrl\n\n /**\n * The data to include in the request. This data will be used to populate the\n * query parameters, body, and headers of the request based on the method type.\n *\n * @example { id: 1 }\n */\n data?: Loose<UnionMerge<Body | Headers | Query>>\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Parameters\n\n /**\n * The query parameters to include in the request.\n */\n query?: Loose<Query>\n\n /**\n * The format to use when serializing the query parameters.\n */\n queryArrayFormat?: SearchArrayFormat\n\n /**\n * The body to include in the request.\n */\n body?: Body extends ObjectLike ? Loose<Body> : Body\n\n /**\n * The headers to include in the request.\n */\n headers?: FetchHeaders & Headers\n\n /**\n * The username for basic authentication.\n */\n username?: string\n\n /**\n * The password for basic authentication.\n */\n password?: string\n\n /**\n * The token for API key authentication.\n */\n token?: string\n\n /**\n * The location where the token should be included in the request.\n */\n tokenLocation?: 'cookie' | 'header' | 'query'\n\n /**\n * The name of the key to use in the request for the token.\n */\n tokenProperty?: string\n}\n\nexport interface RequestContext {\n url: URL\n init: RequestInit\n}\n\n/**\n * Resolves the request body and/or query parameters based on the method type. This function\n * will mutate the `init` object to include the request body and headers based on the data type.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The URL and the `RequestInit` object.\n */\nexport function parseRequest(route: string, options: FetchOptions = {}): RequestContext {\n const {\n username,\n password,\n token,\n tokenLocation,\n tokenProperty,\n data,\n body,\n query,\n parameters,\n headers,\n method,\n baseUrl,\n queryArrayFormat,\n ...init\n } = options\n const context: Partial<RequestContext> = { init }\n const dataObject = isObjectLike(data) ? data : undefined\n\n // --- Parse the URL and insert the path parameters.\n parseRequestUrl(context, route, { baseUrl, method })\n parseRequestParameters(context, { parameters: parameters ?? dataObject })\n parseRequestBasicAuth(context, { username, password })\n\n // --- Depending on the method, parse the query, body, and headers.\n const requestMethod = context.init?.method?.toLowerCase() ?? 'get'\n const requestExpectsBody = ['post', 'put', 'patch'].includes(requestMethod)\n parseRequestQuery(context, { queryArrayFormat, query: requestExpectsBody ? query : query ?? dataObject })\n parseRequestToken(context, { token, tokenLocation, tokenProperty })\n parseRequestBody(context, { body: requestExpectsBody ? body ?? dataObject : undefined })\n parseRequestHeaders(context, { headers })\n\n // --- Return the context with the URL and the `RequestInit` object.\n return context as RequestContext\n}\n","import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\nasync function * createResponseStreamJsonIterator(response: Response, options: RequestOptions): AsyncGenerator<unknown, void, unknown> {\n const { onError, onSuccess, onData, onEnd } = options\n try {\n const body = response.body\n if (body === null) throw new Error('Could not read the response body, it is empty.')\n const reader = body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n const parts = new TextDecoder().decode(value).trim().split('\\0').filter(Boolean)\n\n // --- For each part, parse as JSON and yield the data.\n for (const part of parts) {\n const payload = JSON.parse(part) as unknown\n if (onData) onData(payload)\n yield payload\n }\n }\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a stream of JSON objects. This function\n * will parse the JSON objects and yield the data to the caller. If an error occurs, the `onError`\n * callback will be called and the function will return.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns An awaitable iterator that yields the parsed JSON objects.\n */\nexport function handleResponseStreamJson(response: Response, options: RequestOptions): Awaitable<AsyncIterable<unknown>, unknown[]> {\n const responseIterator = createResponseStreamJsonIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\n\n/**\n * Handle a request response. This function will parse the response based on the content type and\n * return the data. If an error occurs, the `onError` callback will be called and the function will\n * throw an error.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns The parsed data from the response.\n */\nexport async function handleResponse(response: Response, options: RequestOptions = {}): Promise<unknown> {\n const { onError, onSuccess, onData, onEnd, onFailure } = options\n const contentType = response.headers.get('Content-Type')\n\n // --- If the response is not OK, throw an error with the response message.\n if (!response.ok) {\n if (onFailure) await onFailure(response)\n if (onEnd) onEnd(response)\n throw new Error(response.statusText)\n }\n\n // --- If the status code is 204, return an empty response early.\n if (response.status === 204) {\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return\n }\n\n // --- If the response is a text content type, return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/json, parse the JSON and return it.\n if (contentType?.startsWith('application/json')) {\n return await response.json()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data as unknown\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/stream+json, return an iterator that parses the JSON.\n if (contentType?.startsWith('application/stream+json'))\n return handleResponseStreamJson(response, options)\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n}\n"],"names":["value","key","parseRequestParameters","parseRequestQuery","awaitable"],"mappings":";;AASO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACEgB,SAAA,UAAU,SAAsB,KAAa,OAA8B;AAEzF,MADA,QAAQ,OAAO,KAAK,GAChB,mBAAmB;AACb,YAAA,IAAI,KAAK,KAAK;AAAA,WAEf,MAAM,QAAQ,OAAO,GAAG;AAC/B,UAAM,WAAW,IAAI,YAAY,GAC3B,QAAQ,QAAQ,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,YAAA,MAAkB,QAAQ;AAC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B,KACR,EACA,MAAM,CAAC,UAAiB;AACnB,UAAA,WAAS,QAAQ,KAAK,GACpB;AAAA,EAAA,CACP,EACA,QAAQ,MAAM;AACT,aAAO,MAAM,QAAQ;AAAA,EAAA,CAC1B,IAID,aAAa,WAAW,yBAAyB,IAC5C,yBAAyB,UAAU,OAAO,KAG/C,aAAW,UAAU,QAAQ,GAC7B,SAAO,MAAM,QAAQ,GAClB,SAAS;AAClB;;;;;;;;;;;;;;;;"}
@@ -1,4 +1,4 @@
1
- import { p as parseRequest, h as handleResponse } from "./CS5r-m4U.js";
1
+ import { p as parseRequest, h as handleResponse } from "./Bsws660T.js";
2
2
  async function fetch(route, options = {}) {
3
3
  const { url, init } = parseRequest(route, options);
4
4
  if (!url) throw new Error("Could not parse request URL");
@@ -12,4 +12,4 @@ export {
12
12
  fetch as f,
13
13
  request as r
14
14
  };
15
- //# sourceMappingURL=D1QsGr3A.js.map
15
+ //# sourceMappingURL=DLIwGMI0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"D1QsGr3A.js","sources":["../../utils/fetch.ts","../../utils/request.ts"],"sourcesContent":["import type { FetchOptions } from './parseRequest'\nimport { parseRequest } from './parseRequest'\n\n/**\n * Fetch a route with the provided options. This function will parse the route and\n * options to create a `Request` object and return the response from the server.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n * @example fetch('GET /users', { query: { limit: 10 } })\n */\nexport async function fetch(route: string, options?: FetchOptions): Promise<Response>\nexport async function fetch(route: string, options: FetchOptions = {}): Promise<Response> {\n const { url, init } = parseRequest(route, options)\n if (!url) throw new Error('Could not parse request URL')\n return await globalThis.fetch(url, init)\n}\n","import type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport interface RequestOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n Data = any,\n Response = globalThis.Response,\n> extends\n FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {\n\n /**\n * The callback that is called when an error occurs during the request.\n */\n onError?: (error: Error) => any\n\n /**\n * The callback that is called when data is received from the request. This callback\n * will be called for each chunk of data that is received from the request.\n */\n onData?: (data: Data) => any\n\n /**\n * The callback that is called when the request is successful. This callback will be\n * called after the request is complete and all data has been received.\n */\n onSuccess?: (response: Response) => any\n\n /**\n * The callback that is called when the status code is not OK. This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response) => any\n\n /**\n * The callback that is called when the request is complete. This callback will be called\n * after the request is complete and all data has been received.\n */\n onEnd?: (response: Response) => any\n}\n\n/**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\nexport async function request(route: string, options?: RequestOptions): Promise<unknown>\nexport async function request(route: string, options: RequestOptions = {}): Promise<unknown> {\n const response = await fetch(route, options)\n return await handleResponse(response, options)\n}\n"],"names":[],"mappings":";AAaA,eAAsB,MAAM,OAAe,UAAwB,IAAuB;AACxF,QAAM,EAAE,KAAK,KAAA,IAAS,aAAa,OAAO,OAAO;AACjD,MAAI,CAAC,IAAW,OAAA,IAAI,MAAM,6BAA6B;AACvD,SAAO,MAAM,WAAW,MAAM,KAAK,IAAI;AACzC;ACiDA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO;AACpC,SAAA,MAAM,eAAe,UAAU,OAAO;AAC/C;"}
1
+ {"version":3,"file":"DLIwGMI0.js","sources":["../../utils/fetch.ts","../../utils/request.ts"],"sourcesContent":["import type { FetchOptions } from './parseRequest'\nimport { parseRequest } from './parseRequest'\n\n/**\n * Fetch a route with the provided options. This function will parse the route and\n * options to create a `Request` object and return the response from the server.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n * @example fetch('GET /users', { query: { limit: 10 } })\n */\nexport async function fetch(route: string, options?: FetchOptions): Promise<Response>\nexport async function fetch(route: string, options: FetchOptions = {}): Promise<Response> {\n const { url, init } = parseRequest(route, options)\n if (!url) throw new Error('Could not parse request URL')\n return await globalThis.fetch(url, init)\n}\n","import type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport interface RequestOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n Data = any,\n Response = globalThis.Response,\n> extends\n FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {\n\n /**\n * The callback that is called when an error occurs during the request.\n */\n onError?: (error: Error) => any\n\n /**\n * The callback that is called when data is received from the request. This callback\n * will be called for each chunk of data that is received from the request.\n */\n onData?: (data: Data) => any\n\n /**\n * The callback that is called when the request is successful. This callback will be\n * called after the request is complete and all data has been received.\n */\n onSuccess?: (response: Response) => any\n\n /**\n * The callback that is called when the status code is not OK. This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response) => any\n\n /**\n * The callback that is called when the request is complete. This callback will be called\n * after the request is complete and all data has been received.\n */\n onEnd?: (response: Response) => any\n}\n\n/**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\nexport async function request(route: string, options?: RequestOptions): Promise<unknown>\nexport async function request(route: string, options: RequestOptions = {}): Promise<unknown> {\n const response = await fetch(route, options)\n return await handleResponse(response, options)\n}\n"],"names":[],"mappings":";AAaA,eAAsB,MAAM,OAAe,UAAwB,IAAuB;AACxF,QAAM,EAAE,KAAK,KAAA,IAAS,aAAa,OAAO,OAAO;AACjD,MAAI,CAAC,IAAW,OAAA,IAAI,MAAM,6BAA6B;AACvD,SAAO,MAAM,WAAW,MAAM,KAAK,IAAI;AACzC;ACiDA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO;AACpC,SAAA,MAAM,eAAe,UAAU,OAAO;AAC/C;"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
- var attempt = require("@unshared/functions/attempt"), request = require("./chunks/DXrQkl1A.cjs"), connect = require("./chunks/DJyo3R5b.cjs");
3
- require("./chunks/CVzmr2NA.cjs");
2
+ var attempt = require("@unshared/functions/attempt"), request = require("./chunks/B3aOBa4c.cjs"), connect = require("./chunks/DJyo3R5b.cjs");
3
+ require("./chunks/CF3WrArO.cjs");
4
4
  require("./chunks/BDxlAULu.cjs");
5
5
  require("@unshared/functions/awaitable");
6
6
  class Client {
@@ -1,7 +1,7 @@
1
1
  import { attempt } from "@unshared/functions/attempt";
2
- import { f as fetch, r as request } from "./chunks/D1QsGr3A.js";
2
+ import { f as fetch, r as request } from "./chunks/DLIwGMI0.js";
3
3
  import { c as connect } from "./chunks/C83nLcQu.js";
4
- import "./chunks/CS5r-m4U.js";
4
+ import "./chunks/Bsws660T.js";
5
5
  import "./chunks/B6pUErTM.js";
6
6
  import "@unshared/functions/awaitable";
7
7
  class Client {
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- var resolveOperationTokenOptions = require("./chunks/DEyigyGy.cjs"), handleResponse = require("./chunks/CVzmr2NA.cjs");
2
+ var resolveOperationTokenOptions = require("./chunks/DEyigyGy.cjs"), handleResponse = require("./chunks/CF3WrArO.cjs");
3
3
  require("./chunks/BDxlAULu.cjs");
4
4
  require("@unshared/functions/awaitable");
5
5
  function createService(document, initialOptions) {
@@ -1,5 +1,5 @@
1
1
  import { g as getServerUrl, r as resolveOperation, a as resolveOperationTokenOptions } from "./chunks/B_Gz6Yz8.js";
2
- import { p as parseRequest, h as handleResponse } from "./chunks/CS5r-m4U.js";
2
+ import { p as parseRequest, h as handleResponse } from "./chunks/Bsws660T.js";
3
3
  import "./chunks/B6pUErTM.js";
4
4
  import "@unshared/functions/awaitable";
5
5
  function createService(document, initialOptions) {
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  var createClient = require("./createClient.cjs"), createService = require("./createService.cjs"), HttpHeaders = require("./HttpHeaders.cjs"), HttpMethods = require("./HttpMethods.cjs"), HttpStatusCodes = require("./HttpStatusCodes.cjs");
3
3
  require("@unshared/functions/attempt");
4
- require("./chunks/DXrQkl1A.cjs");
5
- require("./chunks/CVzmr2NA.cjs");
4
+ require("./chunks/B3aOBa4c.cjs");
5
+ require("./chunks/CF3WrArO.cjs");
6
6
  require("./chunks/BDxlAULu.cjs");
7
7
  require("@unshared/functions/awaitable");
8
8
  require("./chunks/DJyo3R5b.cjs");
package/dist/index.js CHANGED
@@ -4,8 +4,8 @@ import { HttpHeader } from "./HttpHeaders.js";
4
4
  import { HttpMethod } from "./HttpMethods.js";
5
5
  import { HttpStatusCode } from "./HttpStatusCodes.js";
6
6
  import "@unshared/functions/attempt";
7
- import "./chunks/D1QsGr3A.js";
8
- import "./chunks/CS5r-m4U.js";
7
+ import "./chunks/DLIwGMI0.js";
8
+ import "./chunks/Bsws660T.js";
9
9
  import "./chunks/B6pUErTM.js";
10
10
  import "@unshared/functions/awaitable";
11
11
  import "./chunks/C83nLcQu.js";
package/dist/utils.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- var request = require("./chunks/DXrQkl1A.cjs"), handleResponse = require("./chunks/CVzmr2NA.cjs"), parseRequestQuery = require("./chunks/BDxlAULu.cjs");
2
+ var request = require("./chunks/B3aOBa4c.cjs"), handleResponse = require("./chunks/CF3WrArO.cjs"), parseRequestQuery = require("./chunks/BDxlAULu.cjs");
3
3
  require("@unshared/functions/awaitable");
4
4
  function getCookie(headers, key) {
5
5
  const cookie = handleResponse.getCookies(headers);
package/dist/utils.js CHANGED
@@ -1,6 +1,6 @@
1
- import { f, r } from "./chunks/D1QsGr3A.js";
2
- import { g as getCookies } from "./chunks/CS5r-m4U.js";
3
- import { a, h, b, i, c, p, d, e, f as f2, j, k, s, l, t } from "./chunks/CS5r-m4U.js";
1
+ import { f, r } from "./chunks/DLIwGMI0.js";
2
+ import { g as getCookies } from "./chunks/Bsws660T.js";
3
+ import { a, h, b, i, c, p, d, e, f as f2, j, k, s, l, t } from "./chunks/Bsws660T.js";
4
4
  import { p as p2, a as a2, t as t2 } from "./chunks/B6pUErTM.js";
5
5
  import "@unshared/functions/awaitable";
6
6
  function getCookie(headers, key) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unshared/client",
3
3
  "type": "module",
4
- "version": "0.6.1",
4
+ "version": "0.6.3",
5
5
  "license": "MIT",
6
6
  "sideEffects": false,
7
7
  "author": "Stanley Horwood <stanley@hsjm.io>",
@@ -68,12 +68,12 @@
68
68
  "LICENSE.md"
69
69
  ],
70
70
  "dependencies": {
71
- "@unshared/functions": "0.6.1",
72
- "@unshared/types": "0.6.1",
71
+ "@unshared/functions": "0.6.3",
72
+ "@unshared/types": "0.6.3",
73
73
  "openapi-types": "12.1.3"
74
74
  },
75
75
  "devDependencies": {
76
- "@unshared/scripts": "0.6.1"
76
+ "@unshared/scripts": "0.6.3"
77
77
  },
78
78
  "scripts": {
79
79
  "build:httpMethods": "tsx ./scripts/buildHttpMethods.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"CS5r-m4U.js","sources":["../../utils/isObjectLike.ts","../../utils/setHeader.ts","../../utils/parseRequestBasicAuth.ts","../../utils/isFormDataLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/getHeader.ts","../../utils/getCookies.ts","../../utils/setCookie.ts","../../utils/parseRequestToken.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts","../../utils/handleResponseStreamJson.ts","../../utils/handleResponse.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\n\n/**\n * Predicate to check if a value is an object-like value.\n *\n * @param value The value to check.\n * @returns `true` if the value is an object-like value, `false` otherwise.\n * @example isObjectLike({}) // true\n */\nexport function isObjectLike(value: unknown): value is ObjectLike {\n return typeof value === 'object' && value !== null && value.constructor === Object\n}\n","/**\n * Set a header in the `HeadersInit` object whether it is a `Headers` instance, an\n * array of key-value pairs, or an object. It is also case-insensitive, meaning that\n * if a header with the same key but different case is found, it will be replaced.\n *\n * @param headers The headers to set the key-value pair in.\n * @param key The key of the header to set.\n * @param value The value of the header to set.\n * @example\n * const headers = new Headers()\n * setHeader(headers, 'Content-Type', 'application/json')\n * console.log(headers.get('Content-Type')) // 'application/json'\n */\nexport function setHeader(headers: HeadersInit, key: string, value: number | string): void {\n value = String(value)\n if (headers instanceof Headers) {\n headers.set(key, value)\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const index = headers.findIndex(([k]) => k.toLowerCase() === keyLower)\n if (index === -1) headers.push([key, value])\n headers[index] = [key, value]\n }\n else if (typeof headers === 'object' && headers !== null) {\n const keyLower = key.toLowerCase()\n for (const k in headers) {\n if (k.toLowerCase() !== keyLower) continue\n headers[k] = value\n return\n }\n headers[key] = value\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the basic authentication headers based on the provided username and password.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Authorization` header to the request.\n * const context = {}\n * parseRequestBasicAuth(context, { username: 'user', password: 'pass' })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Authorization': 'Basic dXNlcjpwYXNz' } } }\n */\nexport function parseRequestBasicAuth(context: Partial<RequestContext>, options: FetchOptions): void {\n const { username, password } = options\n\n // --- Return early if the username or password is not provided.\n if (typeof username !== 'string' || typeof password !== 'string') return\n\n // --- Encode the credentials and set the Authorization header.\n const credentials = btoa(`${username}:${password}`)\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Authorization', `Basic ${credentials}`)\n}\n","/**\n * A type that represents a FormData-like object, which is a plain object with\n * nested Blob, File, or FileList values. Or a FormData instance.\n */\nexport type FormDataLike = FormData | Record<string, Blob | File | FileList>\n\n/**\n * Predicate to check if a value is FormData-like, meaning it is a plain object\n * with nested Blob, File, or FileList values.\n *\n * @param value The value to check.\n * @returns `true` if the value is FormData-like, `false` otherwise.\n * @example isFormDataLike({ file: new File(['test'], 'test.txt') }) // true\n */\nexport function isFormDataLike(value: unknown): value is FormDataLike {\n if (typeof value !== 'object' || value === null) return false\n if (value instanceof FormData) return true\n const values = Object.values(value)\n if (values.length === 0) return false\n return values.every((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.every(item => item instanceof File)\n return x instanceof Blob\n })\n}\n","import type { FormDataLike } from './isFormDataLike'\n\n/**\n * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.\n *\n * @param object The object to cast to a `FormData` object.\n * @returns The `FormData` object.\n */\nexport function toFormData(object: FormDataLike): FormData {\n if (object instanceof FormData) return object\n const formData = new FormData()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const item of value)\n formData.append(key, item as Blob | string)\n }\n else {\n formData.append(key, value as Blob | string)\n }\n }\n return formData\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { setHeader } from './setHeader'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n */\nexport function parseRequestBody(context: Partial<RequestContext>, options: FetchOptions): void {\n const { body } = options\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (!context.init?.method) return\n if (['get', 'head', 'delete'].includes(context.init.method)) return\n\n // --- If no data is provided, return early.\n if (body === null || body === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(body)) {\n context.init.body = toFormData(body)\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'multipart/form-data')\n }\n\n // --- If the data is a `ReadableStream`, pass it directly to the body.\n else if (body instanceof ReadableStream) {\n context.init.body = body\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/octet-stream')\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (body instanceof File) {\n context.init.body = body.stream()\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Disposition', `attachment; filename=\"${body.name}\"`)\n setHeader(context.init.headers, 'Content-Type', body.type)\n setHeader(context.init.headers, 'Content-Length', body.size)\n setHeader(context.init.headers, 'Content-Transfer-Encoding', 'binary')\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(body)) {\n context.init.body = JSON.stringify(body)\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/json')\n }\n\n // --- For all other data types, set the body directly.\n else {\n context.init.body = body as BodyInit\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Content-Type` header to the request.\n * const context = {}\n * parseRequestHeaders(context, { headers: { 'Content-Type': 'application/json' } })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }\n */\nexport function parseRequestHeaders(context: Partial<RequestContext>, options: FetchOptions): void {\n const { headers } = options\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (((typeof value !== 'string' || value.length === 0) && typeof value !== 'number')) continue\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, key, value)\n }\n}\n","/**\n * Get a header value from the `HeadersInit` object.\n *\n * @param headers The headers to get the key-value pair from.\n * @param key The key of the header to get.\n * @returns The value of the header.\n * @example\n * const headers = new Headers({ 'Content-Type': 'application/json' })\n * const contentType = getHeader(headers, 'Content-Type')\n * console.log(contentType) // 'application/json'\n */\nexport function getHeader(headers: HeadersInit, key: string): string | undefined {\n if (headers instanceof Headers) {\n return headers.get(key) ?? undefined\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const header = headers.find(([k]) => k.toLowerCase() === keyLower)\n return header ? header[1] : undefined\n }\n else {\n const keyLower = key.toLowerCase()\n const keys = Object.keys(headers)\n const index = keys.findIndex(k => k.toLowerCase() === keyLower)\n return index === -1 ? undefined : headers[keys[index]]\n }\n}\n","import { getHeader } from './getHeader'\n\n/**\n * Extract the cookies from the `HeadersInit` object.\n *\n * @param headers The headers to extract the cookies from.\n * @returns An array of cookies.\n * @example\n * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })\n * const cookies = getCookies(headers) // { key1: 'value1', key2: 'value2' }\n */\nexport function getCookies(headers: HeadersInit): Record<string, string> {\n const value = getHeader(headers, 'Cookie')\n if (!value) return {}\n\n // --- Parse the cookie header.\n const cookies: Record<string, string> = {}\n const parts = value.split(';')\n for (const part of parts) {\n const [key, value] = part.trim().split('=').map(v => v.trim())\n if (!key || !value) continue\n cookies[key] = value\n }\n\n // --- Return the cookies.\n return cookies\n}\n","import { getCookies } from './getCookies'\nimport { setHeader } from './setHeader'\n\n/**\n * Set a cookie in the `HeadersInit` object.\n *\n * @param headers The headers to set the cookie in.\n * @param key The key of the cookie to set.\n * @param value The value of the cookie to set.\n * @example\n * const headers = new Headers()\n * const cookie = { key: 'key1', value: 'value1', path: '/', secure: true }\n * setCookie(headers, cookie)\n * console.log(headers.get('Cookie')) // 'key1=value1; Path=/; Secure'\n */\nexport function setCookie(headers: HeadersInit, key: string, value: string): void {\n const cookies = { ...getCookies(headers), [key]: value }\n const header = Object.entries(cookies).map(([key, value]) => `${key}=${value}`).join('; ')\n setHeader(headers, 'Cookie', header)\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setCookie } from './setCookie'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the token and dynamically extend either the query, headers, or cookies.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n * // Append the `token` to the query parameters.\n * const context = { url: new URL('https://example.com') }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'query', tokenProperty: 'token' })\n * console.log(context.url.searchParams.get('token')) // 'my-token'\n *\n * @example\n * // Append the `token` to the headers.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'header', tokenProperty: 'Authorization' })\n * console.log(context.init.headers.get('Authorization')) // 'Bearer my-token'\n *\n * @example\n * // Append the `token` to the cookies.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'cookie', tokenProperty: 'token' })\n * console.log(context.init.headers.get('Cookie')) // 'token=my-token'\n */\nexport function parseRequestToken(context: Partial<RequestContext>, options: FetchOptions): void {\n const { token, tokenLocation = 'headers', tokenProperty } = options\n\n // --- Return early if the token is not provided.\n if (!token) return\n\n // --- Append the token to the query parameters.\n if (tokenLocation === 'query') {\n if (context.url instanceof URL === false) throw new Error('The `url` must be an instance of `URL`.')\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `query`.')\n context.url.searchParams.set(tokenProperty, token)\n }\n\n // --- Append the token to the path parameters.\n else if (tokenLocation === 'header') {\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n if (tokenProperty) setHeader(context.init.headers, tokenProperty, token)\n else setHeader(context.init.headers, 'Authorization', `Bearer ${token}`)\n }\n\n // --- Append the token to the cookie header.\n else if (tokenLocation === 'cookie') {\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `cookie`.')\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setCookie(context.init.headers, tokenProperty, token)\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid HTTP methods. */\nconst METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])\n\n/**\n * Parses the route name to extract the URL and method. It allows the url and method to be\n * provided in the route name, or in the options object. The method will default to 'get'.\n *\n * @param context The request context to mutate.\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(context: Partial<RequestContext>, route: string, options: FetchOptions): void {\n const { method, baseUrl } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_REQUEST.exec(route)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeMethod = method ?? match.groups.method ?? 'get'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const methodLower = routeMethod.toLowerCase()\n const methodIsValid = METHODS.has(methodLower)\n if (!methodIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeMethod}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n context.init = context.init ?? {}\n context.init.method = methodLower\n context.url = new URL(routeBaseUrl)\n\n // --- Append the path to the URL while making sure there are no double slashes.\n context.url.pathname += context.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n}\n","import type { Loose, MaybeLiteral, ObjectLike } from '@unshared/types'\nimport type { UnionMerge } from '@unshared/types'\nimport type { HttpHeader } from '../HttpHeaders'\nimport type { HttpMethod } from '../HttpMethods'\nimport type { SearchArrayFormat } from './toSearchParams'\nimport { isObjectLike } from './isObjectLike'\nimport { parseRequestBasicAuth } from './parseRequestBasicAuth'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestToken } from './parseRequestToken'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** The methods to use for the request. */\nexport type FetchMethod = Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\n\n/** Headers to include in the request. */\nexport type FetchHeaders = Partial<Record<MaybeLiteral<HttpHeader>, number | string>>\n\n/** Options to pass to the request. */\nexport interface FetchOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n> extends Omit<RequestInit, 'body' | 'headers' | 'method'> {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Method\n\n /**\n * The base URL to use for the request. This URL will be used to resolve the\n * path and query parameters of the request.\n *\n * @example 'https://api.example.com'\n */\n baseUrl?: BaseUrl\n\n /**\n * The data to include in the request. This data will be used to populate the\n * query parameters, body, and headers of the request based on the method type.\n *\n * @example { id: 1 }\n */\n data?: Loose<UnionMerge<Body | Headers | Query>>\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Parameters\n\n /**\n * The query parameters to include in the request.\n */\n query?: Loose<Query>\n\n /**\n * The format to use when serializing the query parameters.\n */\n queryArrayFormat?: SearchArrayFormat\n\n /**\n * The body to include in the request.\n */\n body?: Body extends ObjectLike ? Loose<Body> : Body\n\n /**\n * The headers to include in the request.\n */\n headers?: FetchHeaders & Headers\n\n /**\n * The username for basic authentication.\n */\n username?: string\n\n /**\n * The password for basic authentication.\n */\n password?: string\n\n /**\n * The token for API key authentication.\n */\n token?: string\n\n /**\n * The location where the token should be included in the request.\n */\n tokenLocation?: 'cookie' | 'header' | 'query'\n\n /**\n * The name of the key to use in the request for the token.\n */\n tokenProperty?: string\n}\n\nexport interface RequestContext {\n url: URL\n init: RequestInit\n}\n\n/**\n * Resolves the request body and/or query parameters based on the method type. This function\n * will mutate the `init` object to include the request body and headers based on the data type.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The URL and the `RequestInit` object.\n */\nexport function parseRequest(route: string, options: FetchOptions = {}): RequestContext {\n const {\n username,\n password,\n token,\n tokenLocation,\n tokenProperty,\n data,\n body,\n query,\n parameters,\n headers,\n method,\n baseUrl,\n queryArrayFormat,\n ...init\n } = options\n const context: Partial<RequestContext> = { init }\n const dataObject = isObjectLike(data) ? data : undefined\n\n // --- Parse the URL and insert the path parameters.\n parseRequestUrl(context, route, { baseUrl, method })\n parseRequestParameters(context, { parameters: parameters ?? dataObject })\n parseRequestBasicAuth(context, { username, password })\n\n // --- Depending on the method, parse the query, body, and headers.\n const requestMethod = context.init?.method?.toLowerCase() ?? 'get'\n const requestExpectsBody = ['post', 'put', 'patch'].includes(requestMethod)\n parseRequestQuery(context, { queryArrayFormat, query: requestExpectsBody ? query : query ?? dataObject })\n parseRequestToken(context, { token, tokenLocation, tokenProperty })\n parseRequestBody(context, { body: requestExpectsBody ? body ?? dataObject : undefined })\n parseRequestHeaders(context, { headers })\n\n // --- Return the context with the URL and the `RequestInit` object.\n return context as RequestContext\n}\n","import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\nasync function * createResponseStreamJsonIterator(response: Response, options: RequestOptions): AsyncGenerator<unknown, void, unknown> {\n const { onError, onSuccess, onData, onEnd } = options\n try {\n const body = response.body\n if (body === null) throw new Error('Could not read the response body, it is empty.')\n const reader = body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n const parts = new TextDecoder().decode(value).trim().split('\\0').filter(Boolean)\n\n // --- For each part, parse as JSON and yield the data.\n for (const part of parts) {\n const payload = JSON.parse(part) as unknown\n if (onData) onData(payload)\n yield payload\n }\n }\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a stream of JSON objects. This function\n * will parse the JSON objects and yield the data to the caller. If an error occurs, the `onError`\n * callback will be called and the function will return.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns An awaitable iterator that yields the parsed JSON objects.\n */\nexport function handleResponseStreamJson(response: Response, options: RequestOptions): Awaitable<AsyncIterable<unknown>, unknown[]> {\n const responseIterator = createResponseStreamJsonIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\n\n/**\n * Handle a request response. This function will parse the response based on the content type and\n * return the data. If an error occurs, the `onError` callback will be called and the function will\n * throw an error.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns The parsed data from the response.\n */\nexport async function handleResponse(response: Response, options: RequestOptions = {}): Promise<unknown> {\n const { onError, onSuccess, onData, onEnd, onFailure } = options\n const contentType = response.headers.get('Content-Type')\n\n // --- If the response is not OK, throw an error with the response message.\n if (!response.ok) {\n if (onFailure) await onFailure(response)\n if (onEnd) onEnd(response)\n throw new Error(response.statusText)\n }\n\n // --- If the status code is 204, return an empty response early.\n if (response.status === 204) {\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return\n }\n\n // --- If the response is a text content type, return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/json, parse the JSON and return it.\n if (contentType?.startsWith('application/json')) {\n return await response.json()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data as unknown\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/stream+json, return an iterator that parses the JSON.\n if (contentType?.startsWith('application/stream+json'))\n return handleResponseStreamJson(response, options)\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n}\n"],"names":["value","key"],"mappings":";;AASO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACEgB,SAAA,UAAU,SAAsB,KAAa,OAA8B;AAEzF,MADA,QAAQ,OAAO,KAAK,GAChB,mBAAmB;AACb,YAAA,IAAI,KAAK,KAAK;AAAA,WAEf,MAAM,QAAQ,OAAO,GAAG;AAC/B,UAAM,WAAW,IAAI,YAAY,GAC3B,QAAQ,QAAQ,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,YAAA,MAAkB,QAAQ;AACjE,cAAU,MAAI,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC,GAC3C,QAAQ,KAAK,IAAI,CAAC,KAAK,KAAK;AAAA,EAErB,WAAA,OAAO,WAAY,YAAY,YAAY,MAAM;AAClD,UAAA,WAAW,IAAI,YAAY;AACjC,eAAW,KAAK;AACV,UAAA,EAAE,YAAY,MAAM,UACxB;AAAA,gBAAQ,CAAC,IAAI;AACb;AAAA,MAAA;AAEF,YAAQ,GAAG,I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GAC7B,SAAO,MAAM,QAAQ,GAClB,SAAS;AAClB;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"CVzmr2NA.cjs","sources":["../../utils/isObjectLike.ts","../../utils/setHeader.ts","../../utils/parseRequestBasicAuth.ts","../../utils/isFormDataLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/getHeader.ts","../../utils/getCookies.ts","../../utils/setCookie.ts","../../utils/parseRequestToken.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts","../../utils/handleResponseStreamJson.ts","../../utils/handleResponse.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\n\n/**\n * Predicate to check if a value is an object-like value.\n *\n * @param value The value to check.\n * @returns `true` if the value is an object-like value, `false` otherwise.\n * @example isObjectLike({}) // true\n */\nexport function isObjectLike(value: unknown): value is ObjectLike {\n return typeof value === 'object' && value !== null && value.constructor === Object\n}\n","/**\n * Set a header in the `HeadersInit` object whether it is a `Headers` instance, an\n * array of key-value pairs, or an object. It is also case-insensitive, meaning that\n * if a header with the same key but different case is found, it will be replaced.\n *\n * @param headers The headers to set the key-value pair in.\n * @param key The key of the header to set.\n * @param value The value of the header to set.\n * @example\n * const headers = new Headers()\n * setHeader(headers, 'Content-Type', 'application/json')\n * console.log(headers.get('Content-Type')) // 'application/json'\n */\nexport function setHeader(headers: HeadersInit, key: string, value: number | string): void {\n value = String(value)\n if (headers instanceof Headers) {\n headers.set(key, value)\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const index = headers.findIndex(([k]) => k.toLowerCase() === keyLower)\n if (index === -1) headers.push([key, value])\n headers[index] = [key, value]\n }\n else if (typeof headers === 'object' && headers !== null) {\n const keyLower = key.toLowerCase()\n for (const k in headers) {\n if (k.toLowerCase() !== keyLower) continue\n headers[k] = value\n return\n }\n headers[key] = value\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the basic authentication headers based on the provided username and password.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Authorization` header to the request.\n * const context = {}\n * parseRequestBasicAuth(context, { username: 'user', password: 'pass' })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Authorization': 'Basic dXNlcjpwYXNz' } } }\n */\nexport function parseRequestBasicAuth(context: Partial<RequestContext>, options: FetchOptions): void {\n const { username, password } = options\n\n // --- Return early if the username or password is not provided.\n if (typeof username !== 'string' || typeof password !== 'string') return\n\n // --- Encode the credentials and set the Authorization header.\n const credentials = btoa(`${username}:${password}`)\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Authorization', `Basic ${credentials}`)\n}\n","/**\n * A type that represents a FormData-like object, which is a plain object with\n * nested Blob, File, or FileList values. Or a FormData instance.\n */\nexport type FormDataLike = FormData | Record<string, Blob | File | FileList>\n\n/**\n * Predicate to check if a value is FormData-like, meaning it is a plain object\n * with nested Blob, File, or FileList values.\n *\n * @param value The value to check.\n * @returns `true` if the value is FormData-like, `false` otherwise.\n * @example isFormDataLike({ file: new File(['test'], 'test.txt') }) // true\n */\nexport function isFormDataLike(value: unknown): value is FormDataLike {\n if (typeof value !== 'object' || value === null) return false\n if (value instanceof FormData) return true\n const values = Object.values(value)\n if (values.length === 0) return false\n return values.every((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.every(item => item instanceof File)\n return x instanceof Blob\n })\n}\n","import type { FormDataLike } from './isFormDataLike'\n\n/**\n * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.\n *\n * @param object The object to cast to a `FormData` object.\n * @returns The `FormData` object.\n */\nexport function toFormData(object: FormDataLike): FormData {\n if (object instanceof FormData) return object\n const formData = new FormData()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const item of value)\n formData.append(key, item as Blob | string)\n }\n else {\n formData.append(key, value as Blob | string)\n }\n }\n return formData\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { setHeader } from './setHeader'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n */\nexport function parseRequestBody(context: Partial<RequestContext>, options: FetchOptions): void {\n const { body } = options\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (!context.init?.method) return\n if (['get', 'head', 'delete'].includes(context.init.method)) return\n\n // --- If no data is provided, return early.\n if (body === null || body === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(body)) {\n context.init.body = toFormData(body)\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'multipart/form-data')\n }\n\n // --- If the data is a `ReadableStream`, pass it directly to the body.\n else if (body instanceof ReadableStream) {\n context.init.body = body\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/octet-stream')\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (body instanceof File) {\n context.init.body = body.stream()\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Disposition', `attachment; filename=\"${body.name}\"`)\n setHeader(context.init.headers, 'Content-Type', body.type)\n setHeader(context.init.headers, 'Content-Length', body.size)\n setHeader(context.init.headers, 'Content-Transfer-Encoding', 'binary')\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(body)) {\n context.init.body = JSON.stringify(body)\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, 'Content-Type', 'application/json')\n }\n\n // --- For all other data types, set the body directly.\n else {\n context.init.body = body as BodyInit\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Content-Type` header to the request.\n * const context = {}\n * parseRequestHeaders(context, { headers: { 'Content-Type': 'application/json' } })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }\n */\nexport function parseRequestHeaders(context: Partial<RequestContext>, options: FetchOptions): void {\n const { headers } = options\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (((typeof value !== 'string' || value.length === 0) && typeof value !== 'number')) continue\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setHeader(context.init.headers, key, value)\n }\n}\n","/**\n * Get a header value from the `HeadersInit` object.\n *\n * @param headers The headers to get the key-value pair from.\n * @param key The key of the header to get.\n * @returns The value of the header.\n * @example\n * const headers = new Headers({ 'Content-Type': 'application/json' })\n * const contentType = getHeader(headers, 'Content-Type')\n * console.log(contentType) // 'application/json'\n */\nexport function getHeader(headers: HeadersInit, key: string): string | undefined {\n if (headers instanceof Headers) {\n return headers.get(key) ?? undefined\n }\n else if (Array.isArray(headers)) {\n const keyLower = key.toLowerCase()\n const header = headers.find(([k]) => k.toLowerCase() === keyLower)\n return header ? header[1] : undefined\n }\n else {\n const keyLower = key.toLowerCase()\n const keys = Object.keys(headers)\n const index = keys.findIndex(k => k.toLowerCase() === keyLower)\n return index === -1 ? undefined : headers[keys[index]]\n }\n}\n","import { getHeader } from './getHeader'\n\n/**\n * Extract the cookies from the `HeadersInit` object.\n *\n * @param headers The headers to extract the cookies from.\n * @returns An array of cookies.\n * @example\n * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })\n * const cookies = getCookies(headers) // { key1: 'value1', key2: 'value2' }\n */\nexport function getCookies(headers: HeadersInit): Record<string, string> {\n const value = getHeader(headers, 'Cookie')\n if (!value) return {}\n\n // --- Parse the cookie header.\n const cookies: Record<string, string> = {}\n const parts = value.split(';')\n for (const part of parts) {\n const [key, value] = part.trim().split('=').map(v => v.trim())\n if (!key || !value) continue\n cookies[key] = value\n }\n\n // --- Return the cookies.\n return cookies\n}\n","import { getCookies } from './getCookies'\nimport { setHeader } from './setHeader'\n\n/**\n * Set a cookie in the `HeadersInit` object.\n *\n * @param headers The headers to set the cookie in.\n * @param key The key of the cookie to set.\n * @param value The value of the cookie to set.\n * @example\n * const headers = new Headers()\n * const cookie = { key: 'key1', value: 'value1', path: '/', secure: true }\n * setCookie(headers, cookie)\n * console.log(headers.get('Cookie')) // 'key1=value1; Path=/; Secure'\n */\nexport function setCookie(headers: HeadersInit, key: string, value: string): void {\n const cookies = { ...getCookies(headers), [key]: value }\n const header = Object.entries(cookies).map(([key, value]) => `${key}=${value}`).join('; ')\n setHeader(headers, 'Cookie', header)\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { setCookie } from './setCookie'\nimport { setHeader } from './setHeader'\n\n/**\n * Parse the token and dynamically extend either the query, headers, or cookies.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n * // Append the `token` to the query parameters.\n * const context = { url: new URL('https://example.com') }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'query', tokenProperty: 'token' })\n * console.log(context.url.searchParams.get('token')) // 'my-token'\n *\n * @example\n * // Append the `token` to the headers.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'header', tokenProperty: 'Authorization' })\n * console.log(context.init.headers.get('Authorization')) // 'Bearer my-token'\n *\n * @example\n * // Append the `token` to the cookies.\n * const context = { init: { headers: new Headers() } }\n * parseRequestToken(context, { token: 'my-token', tokenLocation: 'cookie', tokenProperty: 'token' })\n * console.log(context.init.headers.get('Cookie')) // 'token=my-token'\n */\nexport function parseRequestToken(context: Partial<RequestContext>, options: FetchOptions): void {\n const { token, tokenLocation = 'headers', tokenProperty } = options\n\n // --- Return early if the token is not provided.\n if (!token) return\n\n // --- Append the token to the query parameters.\n if (tokenLocation === 'query') {\n if (context.url instanceof URL === false) throw new Error('The `url` must be an instance of `URL`.')\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `query`.')\n context.url.searchParams.set(tokenProperty, token)\n }\n\n // --- Append the token to the path parameters.\n else if (tokenLocation === 'header') {\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n if (tokenProperty) setHeader(context.init.headers, tokenProperty, token)\n else setHeader(context.init.headers, 'Authorization', `Bearer ${token}`)\n }\n\n // --- Append the token to the cookie header.\n else if (tokenLocation === 'cookie') {\n if (!tokenProperty) throw new Error('The `tokenProperty` must be provided when using `tokenLocation` of `cookie`.')\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n setCookie(context.init.headers, tokenProperty, token)\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid HTTP methods. */\nconst METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])\n\n/**\n * Parses the route name to extract the URL and method. It allows the url and method to be\n * provided in the route name, or in the options object. The method will default to 'get'.\n *\n * @param context The request context to mutate.\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(context: Partial<RequestContext>, route: string, options: FetchOptions): void {\n const { method, baseUrl } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_REQUEST.exec(route)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeMethod = method ?? match.groups.method ?? 'get'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const methodLower = routeMethod.toLowerCase()\n const methodIsValid = METHODS.has(methodLower)\n if (!methodIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeMethod}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n context.init = context.init ?? {}\n context.init.method = methodLower\n context.url = new URL(routeBaseUrl)\n\n // --- Append the path to the URL while making sure there are no double slashes.\n context.url.pathname += context.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n}\n","import type { Loose, MaybeLiteral, ObjectLike } from '@unshared/types'\nimport type { UnionMerge } from '@unshared/types'\nimport type { HttpHeader } from '../HttpHeaders'\nimport type { HttpMethod } from '../HttpMethods'\nimport type { SearchArrayFormat } from './toSearchParams'\nimport { isObjectLike } from './isObjectLike'\nimport { parseRequestBasicAuth } from './parseRequestBasicAuth'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestToken } from './parseRequestToken'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** The methods to use for the request. */\nexport type FetchMethod = Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\n\n/** Headers to include in the request. */\nexport type FetchHeaders = Partial<Record<MaybeLiteral<HttpHeader>, number | string>>\n\n/** Options to pass to the request. */\nexport interface FetchOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n> extends Omit<RequestInit, 'body' | 'headers' | 'method'> {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Method\n\n /**\n * The base URL to use for the request. This URL will be used to resolve the\n * path and query parameters of the request.\n *\n * @example 'https://api.example.com'\n */\n baseUrl?: BaseUrl\n\n /**\n * The data to include in the request. This data will be used to populate the\n * query parameters, body, and headers of the request based on the method type.\n *\n * @example { id: 1 }\n */\n data?: Loose<UnionMerge<Body | Headers | Query>>\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Parameters\n\n /**\n * The query parameters to include in the request.\n */\n query?: Loose<Query>\n\n /**\n * The format to use when serializing the query parameters.\n */\n queryArrayFormat?: SearchArrayFormat\n\n /**\n * The body to include in the request.\n */\n body?: Body extends ObjectLike ? Loose<Body> : Body\n\n /**\n * The headers to include in the request.\n */\n headers?: FetchHeaders & Headers\n\n /**\n * The username for basic authentication.\n */\n username?: string\n\n /**\n * The password for basic authentication.\n */\n password?: string\n\n /**\n * The token for API key authentication.\n */\n token?: string\n\n /**\n * The location where the token should be included in the request.\n */\n tokenLocation?: 'cookie' | 'header' | 'query'\n\n /**\n * The name of the key to use in the request for the token.\n */\n tokenProperty?: string\n}\n\nexport interface RequestContext {\n url: URL\n init: RequestInit\n}\n\n/**\n * Resolves the request body and/or query parameters based on the method type. This function\n * will mutate the `init` object to include the request body and headers based on the data type.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The URL and the `RequestInit` object.\n */\nexport function parseRequest(route: string, options: FetchOptions = {}): RequestContext {\n const {\n username,\n password,\n token,\n tokenLocation,\n tokenProperty,\n data,\n body,\n query,\n parameters,\n headers,\n method,\n baseUrl,\n queryArrayFormat,\n ...init\n } = options\n const context: Partial<RequestContext> = { init }\n const dataObject = isObjectLike(data) ? data : undefined\n\n // --- Parse the URL and insert the path parameters.\n parseRequestUrl(context, route, { baseUrl, method })\n parseRequestParameters(context, { parameters: parameters ?? dataObject })\n parseRequestBasicAuth(context, { username, password })\n\n // --- Depending on the method, parse the query, body, and headers.\n const requestMethod = context.init?.method?.toLowerCase() ?? 'get'\n const requestExpectsBody = ['post', 'put', 'patch'].includes(requestMethod)\n parseRequestQuery(context, { queryArrayFormat, query: requestExpectsBody ? query : query ?? dataObject })\n parseRequestToken(context, { token, tokenLocation, tokenProperty })\n parseRequestBody(context, { body: requestExpectsBody ? body ?? dataObject : undefined })\n parseRequestHeaders(context, { headers })\n\n // --- Return the context with the URL and the `RequestInit` object.\n return context as RequestContext\n}\n","import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\nasync function * createResponseStreamJsonIterator(response: Response, options: RequestOptions): AsyncGenerator<unknown, void, unknown> {\n const { onError, onSuccess, onData, onEnd } = options\n try {\n const body = response.body\n if (body === null) throw new Error('Could not read the response body, it is empty.')\n const reader = body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n const parts = new TextDecoder().decode(value).trim().split('\\0').filter(Boolean)\n\n // --- For each part, parse as JSON and yield the data.\n for (const part of parts) {\n const payload = JSON.parse(part) as unknown\n if (onData) onData(payload)\n yield payload\n }\n }\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a stream of JSON objects. This function\n * will parse the JSON objects and yield the data to the caller. If an error occurs, the `onError`\n * callback will be called and the function will return.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns An awaitable iterator that yields the parsed JSON objects.\n */\nexport function handleResponseStreamJson(response: Response, options: RequestOptions): Awaitable<AsyncIterable<unknown>, unknown[]> {\n const responseIterator = createResponseStreamJsonIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\n\n/**\n * Handle a request response. This function will parse the response based on the content type and\n * return the data. If an error occurs, the `onError` callback will be called and the function will\n * throw an error.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns The parsed data from the response.\n */\nexport async function handleResponse(response: Response, options: RequestOptions = {}): Promise<unknown> {\n const { onError, onSuccess, onData, onEnd, onFailure } = options\n const contentType = response.headers.get('Content-Type')\n\n // --- If the response is not OK, throw an error with the response message.\n if (!response.ok) {\n if (onFailure) await onFailure(response)\n if (onEnd) onEnd(response)\n throw new Error(response.statusText)\n }\n\n // --- If the status code is 204, return an empty response early.\n if (response.status === 204) {\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return\n }\n\n // --- If the response is a text content type, return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/json, parse the JSON and return it.\n if (contentType?.startsWith('application/json')) {\n return await response.json()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data as unknown\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/stream+json, return an iterator that parses the JSON.\n if (contentType?.startsWith('application/stream+json'))\n return handleResponseStreamJson(response, options)\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n}\n"],"names":["value","key","parseRequestParameters","parseRequestQuery","awaitable"],"mappings":";;AASO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACEgB,SAAA,UAAU,SAAsB,KAAa,OAA8B;AAEzF,MADA,QAAQ,OAAO,KAAK,GAChB,mBAAmB;AACb,YAAA,IAAI,KAAK,KAAK;AAAA,WAEf,MAAM,QAAQ,OAAO,GAAG;AAC/B,UAAM,WAAW,IAAI,YAAY,GAC3B,QAAQ,QAAQ,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,YAAA,MAAkB,QAAQ;AACjE,cAAU,MAAI,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC,GAC3C,QAAQ,KAAK,IAAI,CAAC,KAAK,KAAK;AAAA,EAErB,WAAA,OAAO,WAAY,YAAY,YAAY,MAAM;AAClD,UAAA,WAAW,IAAI,YAAY;AACjC,eAAW,KAAK;AACV,UAAA,EAAE,YAAY,MAAM,UACxB;AAAA,gBAAQ,CAAC,IAAI;AACb;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