@unshared/client 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"C3RyfPUw.cjs","sources":["../../utils/isFormDataLike.ts","../../utils/isObjectLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/parseRequestParameters.ts","../../utils/toSearchParams.ts","../../utils/parseRequestQuery.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts"],"sourcesContent":["/**\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 return Object.values(value).some((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.some(item => item instanceof File)\n return x instanceof Blob\n })\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 Record<string, unknown> {\n return typeof value === 'object' && value !== null && value.constructor === Object\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 { RequestContext, RequestOptions } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param route The route path.\n * @param options The request options.\n * @param context The request context.\n */\nexport function parseRequestBody(route: string, options: Pick<RequestOptions, 'body' | 'data'>, context: RequestContext): void {\n const { data, body } = options\n const { init } = context\n init.headers = init.headers ?? {}\n\n // --- If the `body` is provided, return early.\n if (body !== undefined) {\n init.body = body\n return\n }\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (['get', 'head', 'delete'].includes(init.method ?? 'get')) return\n\n // --- If no data is provided, return early.\n if (data === null || data === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(data)) {\n init.body = toFormData(data)\n init.headers = { ...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 (data instanceof ReadableStream) {\n init.body = data\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (data instanceof File) {\n init.body = data.stream()\n init.headers = { ...init.headers, 'Content-Type': 'application/octet-stream' }\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(data)) {\n init.body = JSON.stringify(data)\n init.headers = { ...init.headers, 'Content-Type': 'application/json' }\n }\n}\n","import type { RequestContext, RequestOptions } from './parseRequest'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param route The route path.\n * @param options The request options.\n * @param context The request context.\n */\nexport function parseRequestHeaders(route: string, options: Pick<RequestOptions, 'headers'>, context: RequestContext): void {\n const { headers } = options\n const { init } = context\n init.headers = init.headers ?? {}\n\n // --- If no headers are provided, return early.\n if (!headers) return\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (value === undefined) continue\n if (typeof value !== 'string') continue\n init.headers = { ...init.headers, [key]: value }\n }\n}\n","import type { RequestContext, RequestOptions } from './parseRequest'\nimport { isObjectLike } from './isObjectLike'\n\n/** Regular expression to match path parameters in the URL. */\nconst EXP_PATH_PARAMETER = /:([\\w-]+)|%7B([\\w-]+)%7D/g\n\n/**\n * Parse the request parameters from the request data. This function will append\n * the path parameters to the URL based on the method and the data provided.\n *\n * @param route The name of the route to fetch. (ignored)\n * @param options The options to pass to the request.\n * @param context The request context to modify.\n * @example\n * // Using `express` style path parameters.\n * parseRequestParameters('GET /users/:id', { data: { id: 1 } }, context)\n *\n * // Using `OpenAPI` style path parameters.\n * parseRequestParameters('GET /users/{id}', { data: { id: 1 } }, context)\n */\nexport function parseRequestParameters(route: string, options: Pick<RequestOptions, 'data' | 'parameters'>, context: RequestContext): void {\n const { url } = context\n const { data, parameters = {} } = options\n\n // --- If the method has a parameter, fill the path with the data.\n if (!url) throw new Error('Could not resolve the `RequestInit` object: the `url` is missing.')\n const pathParameters = url.pathname.match(EXP_PATH_PARAMETER)\n if (!pathParameters) return\n\n // --- If a path parameter is provided in the data, fill the path with the data.\n if (isObjectLike(data)) {\n for (const key in data) {\n const value = data[key]\n if (value === undefined) continue\n if (typeof value !== 'string') continue\n if (parameters[key] !== undefined) continue\n parameters[key] = value\n delete data[key]\n }\n }\n\n // --- Apply the path parameters to the URL.\n for (const parameter of pathParameters.values()) {\n const key = parameter.replaceAll(EXP_PATH_PARAMETER, '$1$2')\n const value = parameters[key]\n if (value === undefined) continue\n if (typeof value !== 'string') continue\n url.pathname = url.pathname.replace(parameter, value)\n }\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { MaybeArray } from '@unshared/types'\n\n/** An object that can be converted to a query string. */\nexport type SearchParamsObject = Record<string, MaybeArray<boolean | number | string> | undefined>\n\n/** The search array format options. */\nexport type SearchArrayFormat = 'brackets' | 'comma' | 'flat' | 'indices' | 'path'\n\n/** Options for the query string conversion. */\nexport interface ToSearchParamsOptions {\n\n /**\n * Defines how to handle arrays in the object. There is no standard way to\n * represent arrays in query strings, so this option allows you to choose\n * how to handle them. Additionally, you can provide a custom function to\n * handle it yourself.\n *\n * - `brackets` (default): Convert arrays to `key[]=value&key[]=value` format.\n * - `indices`: Convert arrays to `key[0]=value&key[1]=value` format.\n * - `comma`: Convert arrays to `key=value1,value2` format.\n * - `path`: Convert arrays to `key.0=value&key.1=value` format.\n * - `flat`: Convert arrays to `key=value1&key=value2` format.\n *\n * @default 'flat'\n */\n searchArrayFormat?: SearchArrayFormat\n}\n\n/**\n * Convert object to query string parameters. Converting all values to strings\n * and arrays to `key[0]=value&key[1]=value` format.\n *\n * @param object The object to convert to a query string.\n * @param options The query string options.\n * @returns The `URLSearchParams` object.\n */\nexport function toSearchParams(object: SearchParamsObject, options: ToSearchParamsOptions = {}): URLSearchParams {\n const { searchArrayFormat = 'flat' } = options\n const search = new URLSearchParams()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n\n // --- Convert arrays based on the format.\n if (Array.isArray(value)) {\n if (searchArrayFormat === 'brackets') for (const v of value) search.append(`${key}[]`, String(v))\n else if (searchArrayFormat === 'indices') for (const [i, v] of value.entries()) search.append(`${key}[${i}]`, String(v))\n else if (searchArrayFormat === 'comma') search.append(key, value.join(','))\n else if (searchArrayFormat === 'path') for (const [i, v] of value.entries()) search.append(`${key}.${i}`, String(v))\n else if (searchArrayFormat === 'flat') for (const v of value) search.append(key, String(v))\n }\n\n // --- Convert all values to strings.\n else { search.append(key, value.toString()) }\n }\n\n // --- Return the query string.\n return search\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { RequestContext, RequestOptions } from './parseRequest'\nimport { isObjectLike } from './isObjectLike'\nimport { toSearchParams } from './toSearchParams'\n\n/**\n * Parse the query parameters from the request data. This function will append\n * the query parameters to the URL based on the method and the data provided.\n *\n * @param route The name of the route to fetch. (ignored)\n * @param options The options to pass to the request.\n * @param context The request context to modify.\n */\nexport function parseRequestQuery(route: string, options: Pick<RequestOptions, 'data' | 'query' | 'searchArrayFormat'>, context: RequestContext): void {\n const { url, init } = context\n const { data, query = {}, searchArrayFormat } = options\n if (!url) throw new Error('Could not resolve the `RequestInit` object: the `url` is missing.')\n\n // --- Append the `data` to the query parameters if the method does not expect a body.\n const isExpectingBody = ['post', 'put', 'patch'].includes(init.method ?? 'get')\n if (!isExpectingBody && isObjectLike(data)) {\n for (const key in data) {\n if (data[key] === undefined) continue\n if (query[key] !== undefined) continue\n // @ts-expect-error: Ignore type mismatch.\n query[key] = data[key]\n delete data[key]\n }\n }\n\n // --- Apply the query parameters to the URL.\n url.search = toSearchParams(query, { searchArrayFormat }).toString()\n}\n","import type { RequestContext, RequestOptions } 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 route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @param context The request context to modify.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(route: string, options: Pick<RequestOptions, 'baseUrl' | 'method'>, context: RequestContext): 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","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { MaybeLiteral } from '@unshared/types'\nimport type { Override } from '@unshared/types'\nimport type { HttpHeader, HttpMethod } from '../types'\nimport type { SearchArrayFormat, SearchParamsObject } from './toSearchParams'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** Headers to include in the request. */\nexport type RequestHeaders = Partial<Record<MaybeLiteral<HttpHeader>, string>>\n\nexport type RequestOptions = Override<RequestInit, {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\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?: string\n\n /**\n * The data to pass to the request. This data will be used to fill the path\n * parameters, query parameters, body, and form data of the request based on\n * the route method.\n */\n data?: Blob | File | FileList | FormData | ReadableStream | Record<string, unknown> | string\n\n /**\n * The headers to include in the request.\n */\n headers?: RequestHeaders\n\n /**\n * Query parameters to include in the request.\n */\n query?: SearchParamsObject\n\n /**\n * The format to use when serializing the query parameters.\n */\n searchArrayFormat?: SearchArrayFormat\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Record<string, number | 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: RequestOptions = {}) {\n const { data, body, query, headers, parameters, baseUrl, method, searchArrayFormat, ...requestInit } = options\n const context: RequestContext = { init: requestInit }\n parseRequestUrl(route, { baseUrl, method }, context)\n parseRequestParameters(route, { data, parameters }, context)\n parseRequestQuery(route, { data, query, searchArrayFormat }, context)\n parseRequestBody(route, { body, data }, context)\n parseRequestHeaders(route, { headers }, context)\n return context\n}\n"],"names":[],"mappings":";AAcO,SAAS,eAAe,OAAuC;AACpE,SAAI,OAAO,SAAU,YAAY,UAAU,OAAa,KACpD,iBAAiB,WAAiB,KAC/B,OAAO,OAAO,KAAK,EAAE,KAAK,CAAC,MAC5B,aAAa,OAAa,KAC1B,MAAM,QAAQ,CAAC,IAAU,EAAE,KAAK,CAAQ,SAAA,gBAAgB,IAAI,IACzD,aAAa,IACrB;AACH;ACfO,SAAS,aAAa,OAAkD;AAC7E,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACDO,SAAS,WAAW,QAAgC;AACrD,MAAA,kBAAkB,SAAiB,QAAA;AACjC,QAAA,WAAW,IAAI,SAAS;AAC9B,aAAW,OAAO,QAAQ;AAClB,UAAA,QAAQ,OAAO,GAAG;AACxB,QAAI,UAAU;AACV,UAAA,MAAM,QAAQ,KAAK;AACrB,mBAAW,QAAQ;AACR,mBAAA,OAAO,KAAK,IAAqB;AAAA;AAGnC,iBAAA,OAAO,KAAK,KAAsB;AAAA,EAAA;AAGxC,SAAA;AACT;ACXgB,SAAA,iBAAiB,OAAe,SAAgD,SAA+B;AAC7H,QAAM,EAAE,MAAM,KAAA,IAAS,SACjB,EAAE,SAAS;AAIjB,MAHA,KAAK,UAAU,KAAK,WAAW,IAG3B,SAAS,QAAW;AACtB,SAAK,OAAO;AACZ;AAAA,EAAA;AAIE,GAAC,OAAO,QAAQ,QAAQ,EAAE,SAAS,KAAK,UAAU,KAAK,KAGvD,QAAS,SAGT,eAAe,IAAI,KACrB,KAAK,OAAO,WAAW,IAAI,GAC3B,KA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AG,OAAO,GACxC;AACT;;;;;;;;;;;"}
@@ -0,0 +1,72 @@
1
+ const methods = ["get", "put", "post", "delete", "options", "head", "patch"];
2
+ function getOperationById(specification, operationId) {
3
+ if (!specification || typeof specification != "object" || specification === null || !("paths" in specification) || typeof specification.paths != "object" || specification.paths === null)
4
+ throw new Error("Missing paths object in the OpenAPI specification.");
5
+ const paths = specification.paths;
6
+ for (const path in paths) {
7
+ const route = paths[path];
8
+ if (!(typeof route != "object" || route === null))
9
+ for (const method of methods) {
10
+ const operation = route[method];
11
+ if (!(!(method in route) || typeof operation != "object" || operation === null || !("operationId" in operation) || operation.operationId !== operationId))
12
+ return { ...route[method], method, path };
13
+ }
14
+ }
15
+ throw new Error(`Operation "${operationId}" not found in specification.`);
16
+ }
17
+ function getBaseUrl(specification) {
18
+ if ("servers" in specification && Array.isArray(specification.servers) && specification.servers.length > 0)
19
+ return specification.servers[0].url;
20
+ if ("host" in specification && typeof specification.host == "string") {
21
+ const scheme = specification.schemes && specification.schemes.length > 0 ? specification.schemes[0] : "https", basePath = specification.basePath && typeof specification.basePath == "string" ? specification.basePath : "/";
22
+ return `${scheme}://${specification.host}${basePath}`;
23
+ }
24
+ throw new Error("No base URL found in the OpenAPI specification.");
25
+ }
26
+ function getOperationByRoute(specification, name) {
27
+ if (!specification || typeof specification != "object" || specification === null || !("paths" in specification) || typeof specification.paths != "object" || specification.paths === null)
28
+ throw new Error("Missing paths object in the OpenAPI specification.");
29
+ const match = /^(get|post|put|patch|delete|head|options) (\/.+)$/i.exec(name);
30
+ if (!match) throw new Error("Could not resolve the path and method from the route name.");
31
+ const [, routeMethod, routePath] = match, method = routeMethod.toLowerCase(), path = specification.paths[routePath];
32
+ if (!path) throw new Error(`Route "${name}" not found in specification.`);
33
+ if (typeof path != "object" || path === null) throw new Error("Invalid path object in the OpenAPI specification.");
34
+ if (!(method in path)) throw new Error(`Method "${method}" not found in path "${routePath}".`);
35
+ return { ...path[method], method, path: routePath };
36
+ }
37
+ function isReferenceObject(value) {
38
+ return typeof value == "object" && value !== null && "$ref" in value && typeof value.$ref == "string";
39
+ }
40
+ function resolveReference(reference, document) {
41
+ if (!isReferenceObject(reference))
42
+ throw new TypeError("Expected value to be an OpenAPI reference object.");
43
+ if (typeof document != "object" || document === null)
44
+ throw new TypeError("Expected OpenAPI specification to be an object.");
45
+ const referenceParts = reference.$ref.replace(/^#\//, "").split("/");
46
+ let result = document;
47
+ for (const part of referenceParts) {
48
+ if (result === void 0 || typeof result != "object" || result === null) break;
49
+ const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
50
+ result = result[key];
51
+ }
52
+ if (result === void 0)
53
+ throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`);
54
+ return result;
55
+ }
56
+ function resolveDocument(value, document = value) {
57
+ return new Proxy(value, {
58
+ get(target, property) {
59
+ let value2 = target[property];
60
+ return document ? (isReferenceObject(value2) && (value2 = resolveReference(value2, document)), typeof value2 == "object" && value2 !== null ? resolveDocument(value2, document) : value2) : value2;
61
+ }
62
+ });
63
+ }
64
+ export {
65
+ getOperationById as a,
66
+ getOperationByRoute as b,
67
+ resolveReference as c,
68
+ getBaseUrl as g,
69
+ isReferenceObject as i,
70
+ resolveDocument as r
71
+ };
72
+ //# sourceMappingURL=CRISqhP7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CRISqhP7.js","sources":["../../openapi/getOperationById.ts","../../openapi/getBaseUrl.ts","../../openapi/getOperationByRoute.ts","../../openapi/isReferenceObject.ts","../../openapi/resolveReference.ts","../../openapi/resolveDocument.ts"],"sourcesContent":["import type { OpenAPI } from 'openapi-types'\nimport type { OpenAPIV2 } from './OpenApiV2'\n\n/** The HTTP methods supported by OpenAPI. */\nconst methods = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch'] as const\n\n/**\n * Given an OpenAPI specification, find an operation by its operationId.\n *\n * @param specification The OpenAPI specification.\n * @param operationId The operationId of the operation to resolve.\n * @returns The resolved operation.\n * @example openapiGetOperation(specification, 'getUser') // { method: 'get', path: '/users/{username}', ... }\n */\nexport function getOperationById<T, U extends OpenAPIV2.OperationId<T>>(\n specification: T,\n operationId: U,\n): OpenAPIV2.OperationById<T, U> {\n\n // --- Validate the specification.\n if (!specification\n || typeof specification !== 'object'\n || specification === null\n || 'paths' in specification === false\n || typeof specification.paths !== 'object'\n || specification.paths === null)\n throw new Error('Missing paths object in the OpenAPI specification.')\n\n // --- Search for the operation in the specification's paths.\n const paths = specification.paths as OpenAPI.Document['paths']\n for (const path in paths) {\n const route = paths[path]\n if (typeof route !== 'object' || route === null) continue\n\n // --- Search in each method for the operation.\n for (const method of methods) {\n const operation = route[method]\n if (method in route === false\n || typeof operation !== 'object'\n || operation === null\n || 'operationId' in operation === false\n || operation.operationId !== operationId) continue\n\n // --- Route was found, return the operation.\n return { ...route[method], method, path } as OpenAPIV2.OperationById<T, U>\n }\n }\n\n // --- Throw an error if the operation was not found.\n throw new Error(`Operation \"${operationId}\" not found in specification.`)\n}\n","import type { OpenAPI } from 'openapi-types'\n\n/**\n * Given an OpenAPI specification, get the first base URL.\n *\n * @param specification The OpenAPI specification.\n * @returns The first base URL.\n * @example getBaseUrl(specification) // 'https://api.example.com/v1'\n */\nexport function getBaseUrl(specification: OpenAPI.Document): string {\n\n // --- Handle OpenAPI 3.0 specifications.\n if ('servers' in specification && Array.isArray(specification.servers) && specification.servers.length > 0)\n return specification.servers[0].url\n\n // --- Handle OpenAPI 2.0 specifications.\n if ('host' in specification && typeof specification.host === 'string') {\n const scheme = specification.schemes && specification.schemes.length > 0 ? specification.schemes[0] : 'https'\n const basePath = specification.basePath && typeof specification.basePath === 'string' ? specification.basePath : '/'\n return `${scheme}://${specification.host}${basePath}`\n }\n\n throw new Error('No base URL found in the OpenAPI specification.')\n}\n","import type { OpenAPI } from 'openapi-types'\nimport type { OpenAPIV2 } from './OpenApiV2'\n\n/**\n * Given an OpenAPI specification, find a route by its name.\n *\n * @param specification The OpenAPI specification.\n * @param name The name of the route to resolve.\n * @returns The resolved route.\n * @example getOperationByRoute(specification, 'GET /users') // { method: 'get', path: '/users', ... }\n */\nexport function getOperationByRoute<\n T extends object,\n U extends OpenAPIV2.Route<T>,\n>(\n specification: Readonly<T>,\n name: U,\n): OpenAPIV2.OperationByRoute<T, U> {\n\n // --- Assert the specification has a paths object.\n if (!specification\n || typeof specification !== 'object'\n || specification === null\n || 'paths' in specification === false\n || typeof specification.paths !== 'object'\n || specification.paths === null)\n throw new Error('Missing paths object in the OpenAPI specification.')\n\n // --- Extract the path and method from the name.\n const match = /^(get|post|put|patch|delete|head|options) (\\/.+)$/i.exec(name)\n if (!match) throw new Error('Could not resolve the path and method from the route name.')\n const [, routeMethod, routePath] = match\n const method = routeMethod.toLowerCase()\n\n // --- Search for the route in the specification's paths.\n const paths = specification.paths as Record<string, OpenAPI.Operation>\n const path = paths[routePath]\n if (!path) throw new Error(`Route \"${name}\" not found in specification.`)\n if (typeof path !== 'object' || path === null) throw new Error('Invalid path object in the OpenAPI specification.')\n if (method in path === false) throw new Error(`Method \"${method}\" not found in path \"${routePath}\".`)\n const operation = path[method as keyof typeof path] as OpenAPI.Operation\n return { ...operation, method, path: routePath } as OpenAPIV2.OperationByRoute<T, U>\n}\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T> =\n T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":"AAIA,MAAM,UAAU,CAAC,OAAO,OAAO,QAAQ,UAAU,WAAW,QAAQ,OAAO;AAU3D,SAAA,iBACd,eACA,aAC+B;AAG/B,MAAI,CAAC,iBACA,OAAO,iBAAkB,YACzB,kBAAkB,QAClB,EAAW,WAAA,kBACX,OAAO,cAAc,SAAU,YAC/B,cAAc,UAAU;AACrB,UAAA,IAAI,MAAM,oDAAoD;AAGtE,QAAM,QAAQ,cAAc;AAC5B,aAAW,QAAQ,OAAO;AAClB,UAAA,QAAQ,MAAM,IAAI;AACpB,QAAA,EAAA,OAAO,SAAU,YAAY,UAAU;AAG3C,iBAAW,UAAU,SAAS;AACtB,cAAA,YAAY,MAAM,MAAM;AAC1B,YAAA,EAAA,EAAA,UAAU,UACT,OAAO,aAAc,YACrB,cAAc,QACd,EAAA,iBAAiB,cACjB,UAAU,gBAAgB;AAG/B,iBAAO,EAAE,GAAG,MAAM,MAAM,GAAG,QAAQ,KAAK;AAAA,MAAA;AAAA,EAC1C;AAIF,QAAM,IAAI,MAAM,cAAc,WAAW,+BAA+B;AAC1E;ACzCO,SAAS,WAAW,eAAyC;AAG9D,MAAA,aAAa,iBAAiB,MAAM,QAAQ,cAAc,OAAO,KAAK,cAAc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,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACvDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;"}
@@ -0,0 +1,104 @@
1
+ function isFormDataLike(value) {
2
+ return typeof value != "object" || value === null ? !1 : value instanceof FormData ? !0 : Object.values(value).some((x) => x instanceof File ? !0 : Array.isArray(x) ? x.some((item) => item instanceof File) : x instanceof Blob);
3
+ }
4
+ function isObjectLike(value) {
5
+ return typeof value == "object" && value !== null && value.constructor === Object;
6
+ }
7
+ function toFormData(object) {
8
+ if (object instanceof FormData) return object;
9
+ const formData = new FormData();
10
+ for (const key in object) {
11
+ const value = object[key];
12
+ if (value !== void 0)
13
+ if (Array.isArray(value))
14
+ for (const item of value)
15
+ formData.append(key, item);
16
+ else
17
+ formData.append(key, value);
18
+ }
19
+ return formData;
20
+ }
21
+ function parseRequestBody(route, options, context) {
22
+ const { data, body } = options, { init } = context;
23
+ if (init.headers = init.headers ?? {}, body !== void 0) {
24
+ init.body = body;
25
+ return;
26
+ }
27
+ ["get", "head", "delete"].includes(init.method ?? "get") || data != null && (isFormDataLike(data) ? (init.body = toFormData(data), init.headers = { ...init.headers, "Content-Type": "multipart/form-data" }) : data instanceof ReadableStream ? init.body = data : data instanceof File ? (init.body = data.stream(), init.headers = { ...init.headers, "Content-Type": "application/octet-stream" }) : isObjectLike(data) && (init.body = JSON.stringify(data), init.headers = { ...init.headers, "Content-Type": "application/json" }));
28
+ }
29
+ function parseRequestHeaders(route, options, context) {
30
+ const { headers } = options, { init } = context;
31
+ if (init.headers = init.headers ?? {}, !!headers)
32
+ for (const key in headers) {
33
+ const value = headers[key];
34
+ value !== void 0 && typeof value == "string" && (init.headers = { ...init.headers, [key]: value });
35
+ }
36
+ }
37
+ const EXP_PATH_PARAMETER = /:([\w-]+)|%7B([\w-]+)%7D/g;
38
+ function parseRequestParameters(route, options, context) {
39
+ const { url } = context, { data, parameters = {} } = options;
40
+ if (!url) throw new Error("Could not resolve the `RequestInit` object: the `url` is missing.");
41
+ const pathParameters = url.pathname.match(EXP_PATH_PARAMETER);
42
+ if (pathParameters) {
43
+ if (isObjectLike(data))
44
+ for (const key in data) {
45
+ const value = data[key];
46
+ value !== void 0 && typeof value == "string" && parameters[key] === void 0 && (parameters[key] = value, delete data[key]);
47
+ }
48
+ for (const parameter of pathParameters.values()) {
49
+ const key = parameter.replaceAll(EXP_PATH_PARAMETER, "$1$2"), value = parameters[key];
50
+ value !== void 0 && typeof value == "string" && (url.pathname = url.pathname.replace(parameter, value));
51
+ }
52
+ }
53
+ }
54
+ function toSearchParams(object, options = {}) {
55
+ const { searchArrayFormat = "flat" } = options, search = new URLSearchParams();
56
+ for (const key in object) {
57
+ const value = object[key];
58
+ if (value !== void 0)
59
+ if (Array.isArray(value)) {
60
+ if (searchArrayFormat === "brackets") for (const v of value) search.append(`${key}[]`, String(v));
61
+ else if (searchArrayFormat === "indices") for (const [i, v] of value.entries()) search.append(`${key}[${i}]`, String(v));
62
+ else if (searchArrayFormat === "comma") search.append(key, value.join(","));
63
+ else if (searchArrayFormat === "path") for (const [i, v] of value.entries()) search.append(`${key}.${i}`, String(v));
64
+ else if (searchArrayFormat === "flat") for (const v of value) search.append(key, String(v));
65
+ } else
66
+ search.append(key, value.toString());
67
+ }
68
+ return search;
69
+ }
70
+ function parseRequestQuery(route, options, context) {
71
+ const { url, init } = context, { data, query = {}, searchArrayFormat } = options;
72
+ if (!url) throw new Error("Could not resolve the `RequestInit` object: the `url` is missing.");
73
+ if (!["post", "put", "patch"].includes(init.method ?? "get") && isObjectLike(data))
74
+ for (const key in data)
75
+ data[key] !== void 0 && query[key] === void 0 && (query[key] = data[key], delete data[key]);
76
+ url.search = toSearchParams(query, { searchArrayFormat }).toString();
77
+ }
78
+ const EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\/{2}[^/]+)?(?<path>\/[^\s?]*)/i, METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete", "head", "options"]);
79
+ function parseRequestUrl(route, options, context) {
80
+ const { method, baseUrl } = options, match = EXP_REQUEST.exec(route);
81
+ if (!match?.groups) throw new Error("Could not resolve the `RequestInit` object: Invalid route name.");
82
+ const routeMethod = method ?? match.groups.method ?? "get", routeBaseUrl = baseUrl ?? match.groups.url;
83
+ if (!routeBaseUrl) throw new Error("Could not resolve the `RequestInit` object: the `baseUrl` is missing.");
84
+ const methodLower = routeMethod.toLowerCase();
85
+ if (!METHODS.has(methodLower)) throw new Error(`Could not resolve the \`RequestInit\` object:, the method \`${routeMethod}\` is invalid.`);
86
+ context.init = context.init ?? {}, context.init.method = methodLower, context.url = new URL(routeBaseUrl), context.url.pathname += context.url.pathname.endsWith("/") ? match.groups.path.slice(1) : match.groups.path;
87
+ }
88
+ function parseRequest(route, options = {}) {
89
+ const { data, body, query, headers, parameters, baseUrl, method, searchArrayFormat, ...requestInit } = options, context = { init: requestInit };
90
+ return parseRequestUrl(route, { baseUrl, method }, context), parseRequestParameters(route, { data, parameters }, context), parseRequestQuery(route, { data, query, searchArrayFormat }, context), parseRequestBody(route, { body, data }, context), parseRequestHeaders(route, { headers }, context), context;
91
+ }
92
+ export {
93
+ isObjectLike as a,
94
+ parseRequestBody as b,
95
+ parseRequestHeaders as c,
96
+ parseRequestParameters as d,
97
+ parseRequestQuery as e,
98
+ parseRequestUrl as f,
99
+ toSearchParams as g,
100
+ isFormDataLike as i,
101
+ parseRequest as p,
102
+ toFormData as t
103
+ };
104
+ //# sourceMappingURL=wF9C7mO0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wF9C7mO0.js","sources":["../../utils/isFormDataLike.ts","../../utils/isObjectLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/parseRequestParameters.ts","../../utils/toSearchParams.ts","../../utils/parseRequestQuery.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts"],"sourcesContent":["/**\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 return Object.values(value).some((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.some(item => item instanceof File)\n return x instanceof Blob\n })\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 Record<string, unknown> {\n return typeof value === 'object' && value !== null && value.constructor === Object\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 { RequestContext, RequestOptions } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param route The route path.\n * @param options The request options.\n * @param context The request context.\n */\nexport function parseRequestBody(route: string, options: Pick<RequestOptions, 'body' | 'data'>, context: RequestContext): void {\n const { data, body } = options\n const { init } = context\n init.headers = init.headers ?? {}\n\n // --- If the `body` is provided, return early.\n if (body !== undefined) {\n init.body = body\n return\n }\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (['get', 'head', 'delete'].includes(init.method ?? 'get')) return\n\n // --- If no data is provided, return early.\n if (data === null || data === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(data)) {\n init.body = toFormData(data)\n init.headers = { ...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 (data instanceof ReadableStream) {\n init.body = data\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (data instanceof File) {\n init.body = data.stream()\n init.headers = { ...init.headers, 'Content-Type': 'application/octet-stream' }\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(data)) {\n init.body = JSON.stringify(data)\n init.headers = { ...init.headers, 'Content-Type': 'application/json' }\n }\n}\n","import type { RequestContext, RequestOptions } from './parseRequest'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param route The route path.\n * @param options The request options.\n * @param context The request context.\n */\nexport function parseRequestHeaders(route: string, options: Pick<RequestOptions, 'headers'>, context: RequestContext): void {\n const { headers } = options\n const { init } = context\n init.headers = init.headers ?? {}\n\n // --- If no headers are provided, return early.\n if (!headers) return\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (value === undefined) continue\n if (typeof value !== 'string') continue\n init.headers = { ...init.headers, [key]: value }\n }\n}\n","import type { RequestContext, RequestOptions } from './parseRequest'\nimport { isObjectLike } from './isObjectLike'\n\n/** Regular expression to match path parameters in the URL. */\nconst EXP_PATH_PARAMETER = /:([\\w-]+)|%7B([\\w-]+)%7D/g\n\n/**\n * Parse the request parameters from the request data. This function will append\n * the path parameters to the URL based on the method and the data provided.\n *\n * @param route The name of the route to fetch. (ignored)\n * @param options The options to pass to the request.\n * @param context The request context to modify.\n * @example\n * // Using `express` style path parameters.\n * parseRequestParameters('GET /users/:id', { data: { id: 1 } }, context)\n *\n * // Using `OpenAPI` style path parameters.\n * parseRequestParameters('GET /users/{id}', { data: { id: 1 } }, context)\n */\nexport function parseRequestParameters(route: string, options: Pick<RequestOptions, 'data' | 'parameters'>, context: RequestContext): void {\n const { url } = context\n const { data, parameters = {} } = options\n\n // --- If the method has a parameter, fill the path with the data.\n if (!url) throw new Error('Could not resolve the `RequestInit` object: the `url` is missing.')\n const pathParameters = url.pathname.match(EXP_PATH_PARAMETER)\n if (!pathParameters) return\n\n // --- If a path parameter is provided in the data, fill the path with the data.\n if (isObjectLike(data)) {\n for (const key in data) {\n const value = data[key]\n if (value === undefined) continue\n if (typeof value !== 'string') continue\n if (parameters[key] !== undefined) continue\n parameters[key] = value\n delete data[key]\n }\n }\n\n // --- Apply the path parameters to the URL.\n for (const parameter of pathParameters.values()) {\n const key = parameter.replaceAll(EXP_PATH_PARAMETER, '$1$2')\n const value = parameters[key]\n if (value === undefined) continue\n if (typeof value !== 'string') continue\n url.pathname = url.pathname.replace(parameter, value)\n }\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { MaybeArray } from '@unshared/types'\n\n/** An object that can be converted to a query string. */\nexport type SearchParamsObject = Record<string, MaybeArray<boolean | number | string> | undefined>\n\n/** The search array format options. */\nexport type SearchArrayFormat = 'brackets' | 'comma' | 'flat' | 'indices' | 'path'\n\n/** Options for the query string conversion. */\nexport interface ToSearchParamsOptions {\n\n /**\n * Defines how to handle arrays in the object. There is no standard way to\n * represent arrays in query strings, so this option allows you to choose\n * how to handle them. Additionally, you can provide a custom function to\n * handle it yourself.\n *\n * - `brackets` (default): Convert arrays to `key[]=value&key[]=value` format.\n * - `indices`: Convert arrays to `key[0]=value&key[1]=value` format.\n * - `comma`: Convert arrays to `key=value1,value2` format.\n * - `path`: Convert arrays to `key.0=value&key.1=value` format.\n * - `flat`: Convert arrays to `key=value1&key=value2` format.\n *\n * @default 'flat'\n */\n searchArrayFormat?: SearchArrayFormat\n}\n\n/**\n * Convert object to query string parameters. Converting all values to strings\n * and arrays to `key[0]=value&key[1]=value` format.\n *\n * @param object The object to convert to a query string.\n * @param options The query string options.\n * @returns The `URLSearchParams` object.\n */\nexport function toSearchParams(object: SearchParamsObject, options: ToSearchParamsOptions = {}): URLSearchParams {\n const { searchArrayFormat = 'flat' } = options\n const search = new URLSearchParams()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n\n // --- Convert arrays based on the format.\n if (Array.isArray(value)) {\n if (searchArrayFormat === 'brackets') for (const v of value) search.append(`${key}[]`, String(v))\n else if (searchArrayFormat === 'indices') for (const [i, v] of value.entries()) search.append(`${key}[${i}]`, String(v))\n else if (searchArrayFormat === 'comma') search.append(key, value.join(','))\n else if (searchArrayFormat === 'path') for (const [i, v] of value.entries()) search.append(`${key}.${i}`, String(v))\n else if (searchArrayFormat === 'flat') for (const v of value) search.append(key, String(v))\n }\n\n // --- Convert all values to strings.\n else { search.append(key, value.toString()) }\n }\n\n // --- Return the query string.\n return search\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { RequestContext, RequestOptions } from './parseRequest'\nimport { isObjectLike } from './isObjectLike'\nimport { toSearchParams } from './toSearchParams'\n\n/**\n * Parse the query parameters from the request data. This function will append\n * the query parameters to the URL based on the method and the data provided.\n *\n * @param route The name of the route to fetch. (ignored)\n * @param options The options to pass to the request.\n * @param context The request context to modify.\n */\nexport function parseRequestQuery(route: string, options: Pick<RequestOptions, 'data' | 'query' | 'searchArrayFormat'>, context: RequestContext): void {\n const { url, init } = context\n const { data, query = {}, searchArrayFormat } = options\n if (!url) throw new Error('Could not resolve the `RequestInit` object: the `url` is missing.')\n\n // --- Append the `data` to the query parameters if the method does not expect a body.\n const isExpectingBody = ['post', 'put', 'patch'].includes(init.method ?? 'get')\n if (!isExpectingBody && isObjectLike(data)) {\n for (const key in data) {\n if (data[key] === undefined) continue\n if (query[key] !== undefined) continue\n // @ts-expect-error: Ignore type mismatch.\n query[key] = data[key]\n delete data[key]\n }\n }\n\n // --- Apply the query parameters to the URL.\n url.search = toSearchParams(query, { searchArrayFormat }).toString()\n}\n","import type { RequestContext, RequestOptions } 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 route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @param context The request context to modify.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(route: string, options: Pick<RequestOptions, 'baseUrl' | 'method'>, context: RequestContext): 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","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { MaybeLiteral } from '@unshared/types'\nimport type { Override } from '@unshared/types'\nimport type { HttpHeader, HttpMethod } from '../types'\nimport type { SearchArrayFormat, SearchParamsObject } from './toSearchParams'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** Headers to include in the request. */\nexport type RequestHeaders = Partial<Record<MaybeLiteral<HttpHeader>, string>>\n\nexport type RequestOptions = Override<RequestInit, {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\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?: string\n\n /**\n * The data to pass to the request. This data will be used to fill the path\n * parameters, query parameters, body, and form data of the request based on\n * the route method.\n */\n data?: Blob | File | FileList | FormData | ReadableStream | Record<string, unknown> | string\n\n /**\n * The headers to include in the request.\n */\n headers?: RequestHeaders\n\n /**\n * Query parameters to include in the request.\n */\n query?: SearchParamsObject\n\n /**\n * The format to use when serializing the query parameters.\n */\n searchArrayFormat?: SearchArrayFormat\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Record<string, number | 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: RequestOptions = {}) {\n const { data, body, query, headers, parameters, baseUrl, method, searchArrayFormat, ...requestInit } = options\n const context: RequestContext = { init: requestInit }\n parseRequestUrl(route, { baseUrl, method }, context)\n parseRequestParameters(route, { data, parameters }, context)\n parseRequestQuery(route, { data, query, searchArrayFormat }, context)\n parseRequestBody(route, { body, data }, context)\n parseRequestHeaders(route, { headers }, context)\n return context\n}\n"],"names":[],"mappings":"AAcO,SAAS,eAAe,OAAuC;AACpE,SAAI,OAAO,SAAU,YAAY,UAAU,OAAa,KACpD,iBAAiB,WAAiB,KAC/B,OAAO,OAAO,KAAK,EAAE,KAAK,CAAC,MAC5B,aAAa,OAAa,KAC1B,MAAM,QAAQ,CAAC,IAAU,EAAE,KAAK,CAAQ,SAAA,gBAAgB,IAAI,IACzD,aAAa,IACrB;AACH;ACfO,SAAS,aAAa,OAAkD;AAC7E,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACDO,SAAS,WAAW,QAAgC;AACrD,MAAA,kBAAkB,SAAiB,QAAA;AACjC,QAAA,WAAW,IAAI,SAAS;AAC9B,aAAW,OAAO,QAAQ;AAClB,UAAA,QAAQ,OAAO,GAAG;AACxB,QAAI,UAAU;AACV,UAAA,MAAM,QAAQ,KAAK;AACrB,mBAAW,QAAQ;AACR,mBAAA,OAAO,KAAK,IAAqB;AAAA;AAGnC,iBAAA,OAAO,KAAK,KAAsB;AAAA,EAAA;AAGxC,SAAA;AACT;ACXgB,SAAA,iBAAiB,OA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mB,GAAG,gBAAgB,SACjG,UAA0B,EAAE,MAAM,YAAY;AACpD,SAAA,gBAAgB,OAAO,EAAE,SAAS,OAAO,GAAG,OAAO,GACnD,uBAAuB,OAAO,EAAE,MAAM,WAAW,GAAG,OAAO,GAC3D,kBAAkB,OAAO,EAAE,MAAM,OAAO,qBAAqB,OAAO,GACpE,iBAAiB,OAAO,EAAE,MAAM,KAAQ,GAAA,OAAO,GAC/C,oBAAoB,OAAO,EAAE,QAAQ,GAAG,OAAO,GACxC;AACT;"}
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var fetch = require("./fetch.cjs"), index = require("./chunks/BzqHK4CV.cjs");
3
+ require("./chunks/C3RyfPUw.cjs");
4
+ function createClient(documentOrUrl, initialOptions = {}) {
5
+ const specifications = typeof documentOrUrl == "string" ? void 0 : documentOrUrl;
6
+ async function fetchByOperationId(operationId, options) {
7
+ if (!specifications) throw new Error("No OpenAPI specification provided.");
8
+ const operation = index.getOperationById(specifications, operationId);
9
+ if (!operation) throw new Error(`Operation ID "${operationId}" not found.`);
10
+ const { method, path, responses = {} } = operation, response = await fetch.fetch(path, {
11
+ method,
12
+ baseUrl: index.getBaseUrl(specifications),
13
+ ...initialOptions,
14
+ ...options
15
+ });
16
+ if (response.ok) return response.json();
17
+ const status = response.status.toString();
18
+ throw status in responses && typeof responses[status] == "object" && responses[status] !== null && "description" in responses[status] && typeof responses[status].description == "string" ? new Error(responses[status].description) : new Error(response.statusText);
19
+ }
20
+ return new Proxy({}, {
21
+ get(_, property) {
22
+ return property === "fetch" ? fetch.fetch : (options) => fetchByOperationId(property, options);
23
+ }
24
+ });
25
+ }
26
+ exports.createClient = createClient;
27
+ //# sourceMappingURL=createClient.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createClient.cjs","sources":["../createClient.ts"],"sourcesContent":["import type { MaybeLiteral, Override, Pretty } from '@unshared/types'\nimport type { OpenAPI, OpenAPIV2 as V2, OpenAPIV3 as V3, OpenAPIV3_1 as V3_1 } from 'openapi-types'\nimport type { RequestOptions } from './utils/index'\nimport { fetch } from './fetch'\nimport { getOperationById } from './openapi/getOperationById'\nimport { getBaseUrl, type OpenAPIV2, type OpenAPIV3 } from './openapi/index'\n\ntype ClientBaseUrl<T> =\n MaybeLiteral<\n T extends V2.Document ? OpenAPIV2.ServerUrl<T>\n : T extends V3.Document ? OpenAPIV3.ServerUrl<T>\n : T extends V3_1.Document ? OpenAPIV3.ServerUrl<T>\n : string\n >\n\ntype ClientFetch<T> =\n T extends V2.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV2.RequestInit<OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV2.Response<OpenAPIV2.OperationByRoute<T, P>>>\n : T extends V3.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV3.Response<OpenAPIV2.OperationByRoute<T, P>>>\n : T extends V3_1.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV3.Response<OpenAPIV2.OperationByRoute<T, P>>>\n : typeof globalThis.fetch\n\ntype ClientFetchOperation<T, U extends OpenAPIV2.OperationId<T>> =\n T extends V2.Document ? (options: OpenAPIV2.RequestInit<OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV2.ResponseBody<OpenAPIV2.OperationById<T, U>>>\n : T extends V3.Document ? (options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV3.ResponseBody<OpenAPIV2.OperationById<T, U>>>\n : T extends V3_1.Document ? (options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV3.ResponseBody<OpenAPIV2.OperationById<T, U>>>\n : (options: RequestOptions) => Promise<Response>\n\nexport type Client<T = OpenAPI.Document> =\n Pretty<\n & { [K in OpenAPIV2.OperationId<T>]: ClientFetchOperation<T, K> }\n & { fetch: ClientFetch<T> }\n >\n\nexport type ClientOptions<T = any> = Pretty<Override<RequestOptions, {\n baseUrl?: ClientBaseUrl<T>\n\n /**\n * The headers to include in every request made by the client.\n *\n * @example { 'Authorization': 'Bearer ...' }\n */\n headers?: T extends V3.Document\n ? OpenAPIV3.ServerHeaders<T>\n : Record<string, string>\n}>>\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n * const client = createClient(document)\n * await client.fetch({ ... })\n */\n// @ts-expect-error: `ClientOptions` is not assignable to `ClientOptions<T>`.\nexport function createClient<T extends OpenAPI.Document>(document: Readonly<T>, initialOptions?: ClientOptions<T>): Client<T>\nexport function createClient<T extends OpenAPI.Document>(url: ClientBaseUrl<T>, initialOptions?: ClientOptions<T>): Client<T>\nexport function createClient(documentOrUrl: Readonly<OpenAPI.Document> | string, initialOptions: ClientOptions = {}): Client {\n const specifications = typeof documentOrUrl === 'string' ? undefined : documentOrUrl\n\n async function fetchByOperationId(operationId: string, options: ClientOptions<any>) {\n if (!specifications) throw new Error('No OpenAPI specification provided.')\n const operation = getOperationById(specifications, operationId) as { method: string; path: string } & OpenAPI.Operation\n if (!operation) throw new Error(`Operation ID \"${operationId}\" not found.`)\n const { method, path, responses = {} } = operation\n const response = await fetch(path, {\n method,\n baseUrl: getBaseUrl(specifications),\n ...initialOptions,\n ...options,\n })\n\n // --- Return the JSON response if successful.\n if (response.ok) return response.json() as Promise<unknown>\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n\n return new Proxy({}, {\n get(_, property: string) {\n if (property === 'fetch') return fetch\n return (options: Record<string, unknown>) => fetchByOperationId(property, options)\n },\n }) as unknown as Client\n}\n"],"names":["getOperationById","fetch","getBaseUrl"],"mappings":";;;AA2DO,SAAS,aAAa,eAAoD,iBAAgC,IAAY;AAC3H,QAAM,iBAAiB,OAAO,iBAAkB,WAAW,SAAY;AAExD,iBAAA,mBAAmB,aAAqB,SAA6B;AAClF,QAAI,CAAC,eAAsB,OAAA,IAAI,MAAM,oCAAoC;AACnE,UAAA,YAAYA,MAAAA,iBAAiB,gBAAgB,WAAW;AAC9D,QAAI,CAAC,UAAW,OAAM,IAAI,MAAM,iBAAiB,WAAW,cAAc;AACpE,UAAA,EAAE,QAAQ,MAAM,YAAY,CAAA,MAAO,WACnC,WAAW,MAAMC,MAAA,MAAM,MAAM;AAAA,MACjC;AAAA,MACA,SAASC,iBAAW,cAAc;AAAA,MAClC,GAAG;AAAA,MACH,GAAG;AAAA,IAAA,CACJ;AAGD,QAAI,SAAS,GAAW,QAAA,SAAS,KAAK;AAGhC,UAAA,SAAS,SAAS,OAAO,SAAS;AACxC,UAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,EAAA;AAG9B,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,UAAkB;AACvB,aAAI,aAAa,UAAgBD,MAAA,QAC1B,CAAC,YAAqC,mBAAmB,UAAU,OAAO;AAAA,IAAA;AAAA,EACnF,CACD;AACH;;"}
@@ -0,0 +1,37 @@
1
+ import { Pretty, Override, MaybeLiteral } from '@unshared/types';
2
+ import { OpenAPI, OpenAPIV3, OpenAPIV2 as OpenAPIV2$1, OpenAPIV3_1 } from 'openapi-types';
3
+ import { a as RequestOptions } from './chunks/B0duX_ls.js';
4
+ import { O as OpenAPIV2, a as OpenAPIV3$1 } from './chunks/BIx2AaJH.js';
5
+ import './chunks/8BFCFxqa.js';
6
+
7
+ type ClientBaseUrl<T> = MaybeLiteral<T extends OpenAPIV2$1.Document ? OpenAPIV2.ServerUrl<T> : T extends OpenAPIV3.Document ? OpenAPIV3$1.ServerUrl<T> : T extends OpenAPIV3_1.Document ? OpenAPIV3$1.ServerUrl<T> : string>;
8
+ type ClientFetch<T> = T extends OpenAPIV2$1.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV2.RequestInit<OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV2.Response<OpenAPIV2.OperationByRoute<T, P>>> : T extends OpenAPIV3.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV3$1.RequestInit<T, OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV3$1.Response<OpenAPIV2.OperationByRoute<T, P>>> : T extends OpenAPIV3_1.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV3$1.RequestInit<T, OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV3$1.Response<OpenAPIV2.OperationByRoute<T, P>>> : typeof globalThis.fetch;
9
+ type ClientFetchOperation<T, U extends OpenAPIV2.OperationId<T>> = T extends OpenAPIV2$1.Document ? (options: OpenAPIV2.RequestInit<OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV2.ResponseBody<OpenAPIV2.OperationById<T, U>>> : T extends OpenAPIV3.Document ? (options: OpenAPIV3$1.RequestInit<T, OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV3$1.ResponseBody<OpenAPIV2.OperationById<T, U>>> : T extends OpenAPIV3_1.Document ? (options: OpenAPIV3$1.RequestInit<T, OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV3$1.ResponseBody<OpenAPIV2.OperationById<T, U>>> : (options: RequestOptions) => Promise<Response>;
10
+ type Client<T = OpenAPI.Document> = Pretty<{
11
+ [K in OpenAPIV2.OperationId<T>]: ClientFetchOperation<T, K>;
12
+ } & {
13
+ fetch: ClientFetch<T>;
14
+ }>;
15
+ type ClientOptions<T = any> = Pretty<Override<RequestOptions, {
16
+ baseUrl?: ClientBaseUrl<T>;
17
+ /**
18
+ * The headers to include in every request made by the client.
19
+ *
20
+ * @example { 'Authorization': 'Bearer ...' }
21
+ */
22
+ headers?: T extends OpenAPIV3.Document ? OpenAPIV3$1.ServerHeaders<T> : Record<string, string>;
23
+ }>>;
24
+ /**
25
+ * Create a new client instance for the given OpenAPI specification.
26
+ *
27
+ * @param document The OpenAPI specification document.
28
+ * @param initialOptions The initial options to use for every request.
29
+ * @returns The client instance.
30
+ * @example
31
+ * const client = createClient(document)
32
+ * await client.fetch({ ... })
33
+ */
34
+ declare function createClient<T extends OpenAPI.Document>(document: Readonly<T>, initialOptions?: ClientOptions<T>): Client<T>;
35
+ declare function createClient<T extends OpenAPI.Document>(url: ClientBaseUrl<T>, initialOptions?: ClientOptions<T>): Client<T>;
36
+
37
+ export { type Client, type ClientOptions, createClient };
@@ -0,0 +1,29 @@
1
+ import { fetch } from "./fetch.js";
2
+ import { a as getOperationById, g as getBaseUrl } from "./chunks/CRISqhP7.js";
3
+ import "./chunks/wF9C7mO0.js";
4
+ function createClient(documentOrUrl, initialOptions = {}) {
5
+ const specifications = typeof documentOrUrl == "string" ? void 0 : documentOrUrl;
6
+ async function fetchByOperationId(operationId, options) {
7
+ if (!specifications) throw new Error("No OpenAPI specification provided.");
8
+ const operation = getOperationById(specifications, operationId);
9
+ if (!operation) throw new Error(`Operation ID "${operationId}" not found.`);
10
+ const { method, path, responses = {} } = operation, response = await fetch(path, {
11
+ method,
12
+ baseUrl: getBaseUrl(specifications),
13
+ ...initialOptions,
14
+ ...options
15
+ });
16
+ if (response.ok) return response.json();
17
+ const status = response.status.toString();
18
+ throw status in responses && typeof responses[status] == "object" && responses[status] !== null && "description" in responses[status] && typeof responses[status].description == "string" ? new Error(responses[status].description) : new Error(response.statusText);
19
+ }
20
+ return new Proxy({}, {
21
+ get(_, property) {
22
+ return property === "fetch" ? fetch : (options) => fetchByOperationId(property, options);
23
+ }
24
+ });
25
+ }
26
+ export {
27
+ createClient
28
+ };
29
+ //# sourceMappingURL=createClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { MaybeLiteral, Override, Pretty } from '@unshared/types'\nimport type { OpenAPI, OpenAPIV2 as V2, OpenAPIV3 as V3, OpenAPIV3_1 as V3_1 } from 'openapi-types'\nimport type { RequestOptions } from './utils/index'\nimport { fetch } from './fetch'\nimport { getOperationById } from './openapi/getOperationById'\nimport { getBaseUrl, type OpenAPIV2, type OpenAPIV3 } from './openapi/index'\n\ntype ClientBaseUrl<T> =\n MaybeLiteral<\n T extends V2.Document ? OpenAPIV2.ServerUrl<T>\n : T extends V3.Document ? OpenAPIV3.ServerUrl<T>\n : T extends V3_1.Document ? OpenAPIV3.ServerUrl<T>\n : string\n >\n\ntype ClientFetch<T> =\n T extends V2.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV2.RequestInit<OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV2.Response<OpenAPIV2.OperationByRoute<T, P>>>\n : T extends V3.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV3.Response<OpenAPIV2.OperationByRoute<T, P>>>\n : T extends V3_1.Document ? <P extends OpenAPIV2.Route<T>>(name: P, options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationByRoute<T, P>>) => Promise<OpenAPIV3.Response<OpenAPIV2.OperationByRoute<T, P>>>\n : typeof globalThis.fetch\n\ntype ClientFetchOperation<T, U extends OpenAPIV2.OperationId<T>> =\n T extends V2.Document ? (options: OpenAPIV2.RequestInit<OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV2.ResponseBody<OpenAPIV2.OperationById<T, U>>>\n : T extends V3.Document ? (options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV3.ResponseBody<OpenAPIV2.OperationById<T, U>>>\n : T extends V3_1.Document ? (options: OpenAPIV3.RequestInit<T, OpenAPIV2.OperationById<T, U>>) => Promise<OpenAPIV3.ResponseBody<OpenAPIV2.OperationById<T, U>>>\n : (options: RequestOptions) => Promise<Response>\n\nexport type Client<T = OpenAPI.Document> =\n Pretty<\n & { [K in OpenAPIV2.OperationId<T>]: ClientFetchOperation<T, K> }\n & { fetch: ClientFetch<T> }\n >\n\nexport type ClientOptions<T = any> = Pretty<Override<RequestOptions, {\n baseUrl?: ClientBaseUrl<T>\n\n /**\n * The headers to include in every request made by the client.\n *\n * @example { 'Authorization': 'Bearer ...' }\n */\n headers?: T extends V3.Document\n ? OpenAPIV3.ServerHeaders<T>\n : Record<string, string>\n}>>\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n * const client = createClient(document)\n * await client.fetch({ ... })\n */\n// @ts-expect-error: `ClientOptions` is not assignable to `ClientOptions<T>`.\nexport function createClient<T extends OpenAPI.Document>(document: Readonly<T>, initialOptions?: ClientOptions<T>): Client<T>\nexport function createClient<T extends OpenAPI.Document>(url: ClientBaseUrl<T>, initialOptions?: ClientOptions<T>): Client<T>\nexport function createClient(documentOrUrl: Readonly<OpenAPI.Document> | string, initialOptions: ClientOptions = {}): Client {\n const specifications = typeof documentOrUrl === 'string' ? undefined : documentOrUrl\n\n async function fetchByOperationId(operationId: string, options: ClientOptions<any>) {\n if (!specifications) throw new Error('No OpenAPI specification provided.')\n const operation = getOperationById(specifications, operationId) as { method: string; path: string } & OpenAPI.Operation\n if (!operation) throw new Error(`Operation ID \"${operationId}\" not found.`)\n const { method, path, responses = {} } = operation\n const response = await fetch(path, {\n method,\n baseUrl: getBaseUrl(specifications),\n ...initialOptions,\n ...options,\n })\n\n // --- Return the JSON response if successful.\n if (response.ok) return response.json() as Promise<unknown>\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n\n return new Proxy({}, {\n get(_, property: string) {\n if (property === 'fetch') return fetch\n return (options: Record<string, unknown>) => fetchByOperationId(property, options)\n },\n }) as unknown as Client\n}\n"],"names":[],"mappings":";;;AA2DO,SAAS,aAAa,eAAoD,iBAAgC,IAAY;AAC3H,QAAM,iBAAiB,OAAO,iBAAkB,WAAW,SAAY;AAExD,iBAAA,mBAAmB,aAAqB,SAA6B;AAClF,QAAI,CAAC,eAAsB,OAAA,IAAI,MAAM,oCAAoC;AACnE,UAAA,YAAY,iBAAiB,gBAAgB,WAAW;AAC9D,QAAI,CAAC,UAAW,OAAM,IAAI,MAAM,iBAAiB,WAAW,cAAc;AACpE,UAAA,EAAE,QAAQ,MAAM,YAAY,CAAA,MAAO,WACnC,WAAW,MAAM,MAAM,MAAM;AAAA,MACjC;AAAA,MACA,SAAS,WAAW,cAAc;AAAA,MAClC,GAAG;AAAA,MACH,GAAG;AAAA,IAAA,CACJ;AAGD,QAAI,SAAS,GAAW,QAAA,SAAS,KAAK;AAGhC,UAAA,SAAS,SAAS,OAAO,SAAS;AACxC,UAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,EAAA;AAG9B,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,UAAkB;AACvB,aAAI,aAAa,UAAgB,QAC1B,CAAC,YAAqC,mBAAmB,UAAU,OAAO;AAAA,IAAA;AAAA,EACnF,CACD;AACH;"}
package/dist/fetch.cjs ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ var parseRequest = require("./chunks/C3RyfPUw.cjs");
3
+ function fetch(route, options) {
4
+ const { url, init } = parseRequest.parseRequest(route, options);
5
+ return globalThis.fetch(url, init);
6
+ }
7
+ exports.fetch = fetch;
8
+ //# sourceMappingURL=fetch.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.cjs","sources":["../fetch.ts"],"sourcesContent":["import { parseRequest } from './utils/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 function fetch(route: string, options: Record<string, unknown>) {\n const { url, init } = parseRequest(route, options)\n return globalThis.fetch(url!, init)\n}\n"],"names":["parseRequest"],"mappings":";;AAWgB,SAAA,MAAM,OAAe,SAAkC;AACrE,QAAM,EAAE,KAAK,KAAA,IAASA,aAAAA,aAAa,OAAO,OAAO;AAC1C,SAAA,WAAW,MAAM,KAAM,IAAI;AACpC;;"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Fetch a route with the provided options. This function will parse the route and
3
+ * options to create a `Request` object and return the response from the server.
4
+ *
5
+ * @param route The name of the route to fetch.
6
+ * @param options The options to pass to the request.
7
+ * @returns The response from the server.
8
+ * @example fetch('GET /users', { query: { limit: 10 } })
9
+ */
10
+ declare function fetch(route: string, options: Record<string, unknown>): Promise<Response>;
11
+
12
+ export { fetch };
package/dist/fetch.js ADDED
@@ -0,0 +1,9 @@
1
+ import { p as parseRequest } from "./chunks/wF9C7mO0.js";
2
+ function fetch(route, options) {
3
+ const { url, init } = parseRequest(route, options);
4
+ return globalThis.fetch(url, init);
5
+ }
6
+ export {
7
+ fetch
8
+ };
9
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.js","sources":["../fetch.ts"],"sourcesContent":["import { parseRequest } from './utils/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 function fetch(route: string, options: Record<string, unknown>) {\n const { url, init } = parseRequest(route, options)\n return globalThis.fetch(url!, init)\n}\n"],"names":[],"mappings":";AAWgB,SAAA,MAAM,OAAe,SAAkC;AACrE,QAAM,EAAE,KAAK,KAAA,IAAS,aAAa,OAAO,OAAO;AAC1C,SAAA,WAAW,MAAM,KAAM,IAAI;AACpC;"}
package/dist/index.cjs ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var createClient = require("./createClient.cjs"), fetch = require("./fetch.cjs");
3
+ require("./openapi.cjs");
4
+ require("./utils.cjs");
5
+ var index = require("./chunks/BzqHK4CV.cjs"), parseRequest = require("./chunks/C3RyfPUw.cjs"), HttpHeader = /* @__PURE__ */ ((HttpHeader2) => (HttpHeader2["Accept-CH"] = "Accept-CH", HttpHeader2["Accept-Charset"] = "Accept-Charset", HttpHeader2["Accept-Encoding"] = "Accept-Encoding", HttpHeader2["Accept-Language"] = "Accept-Language", HttpHeader2["Accept-Patch"] = "Accept-Patch", HttpHeader2["Accept-Post"] = "Accept-Post", HttpHeader2["Accept-Ranges"] = "Accept-Ranges", HttpHeader2.Accept = "Accept", HttpHeader2["Access-Control-Allow-Credentials"] = "Access-Control-Allow-Credentials", HttpHeader2["Access-Control-Allow-Headers"] = "Access-Control-Allow-Headers", HttpHeader2["Access-Control-Allow-Methods"] = "Access-Control-Allow-Methods", HttpHeader2["Access-Control-Allow-Origin"] = "Access-Control-Allow-Origin", HttpHeader2["Access-Control-Expose-Headers"] = "Access-Control-Expose-Headers", HttpHeader2["Access-Control-Max-Age"] = "Access-Control-Max-Age", HttpHeader2["Access-Control-Request-Headers"] = "Access-Control-Request-Headers", HttpHeader2["Access-Control-Request-Method"] = "Access-Control-Request-Method", HttpHeader2.Age = "Age", HttpHeader2.Allow = "Allow", HttpHeader2["Alt-Svc"] = "Alt-Svc", HttpHeader2["Alt-Used"] = "Alt-Used", HttpHeader2["Attribution-Reporting-Eligible"] = "Attribution-Reporting-Eligible", HttpHeader2["Attribution-Reporting-Register-Source"] = "Attribution-Reporting-Register-Source", HttpHeader2["Attribution-Reporting-Register-Trigger"] = "Attribution-Reporting-Register-Trigger", HttpHeader2.Authorization = "Authorization", HttpHeader2["Cache-Control"] = "Cache-Control", HttpHeader2["Clear-Site-Data"] = "Clear-Site-Data", HttpHeader2.Connection = "Connection", HttpHeader2["Content-Digest"] = "Content-Digest", HttpHeader2["Content-Disposition"] = "Content-Disposition", HttpHeader2["Content-DPR"] = "Content-DPR", HttpHeader2["Content-Encoding"] = "Content-Encoding", HttpHeader2["Content-Language"] = "Content-Language", HttpHeader2["Content-Length"] = "Content-Length", HttpHeader2["Content-Location"] = "Content-Location", HttpHeader2["Content-Range"] = "Content-Range", HttpHeader2["Content-Security-Policy-Report-Only"] = "Content-Security-Policy-Report-Only", HttpHeader2["Content-Security-Policy"] = "Content-Security-Policy", HttpHeader2["Content-Type"] = "Content-Type", HttpHeader2.Cookie = "Cookie", HttpHeader2["Critical-CH"] = "Critical-CH", HttpHeader2["Cross-Origin-Embedder-Policy"] = "Cross-Origin-Embedder-Policy", HttpHeader2["Cross-Origin-Opener-Policy"] = "Cross-Origin-Opener-Policy", HttpHeader2["Cross-Origin-Resource-Policy"] = "Cross-Origin-Resource-Policy", HttpHeader2.Date = "Date", HttpHeader2["Device-Memory"] = "Device-Memory", HttpHeader2.Digest = "Digest", HttpHeader2.DNT = "DNT", HttpHeader2.Downlink = "Downlink", HttpHeader2.DPR = "DPR", HttpHeader2["Early-Data"] = "Early-Data", HttpHeader2.ECT = "ECT", HttpHeader2.ETag = "ETag", HttpHeader2["Expect-CT"] = "Expect-CT", HttpHeader2.Expect = "Expect", HttpHeader2.Expires = "Expires", HttpHeader2.Forwarded = "Forwarded", HttpHeader2.From = "From", HttpHeader2.Host = "Host", HttpHeader2["If-Match"] = "If-Match", HttpHeader2["If-Modified-Since"] = "If-Modified-Since", HttpHeader2["If-None-Match"] = "If-None-Match", HttpHeader2["If-Range"] = "If-Range", HttpHeader2["If-Unmodified-Since"] = "If-Unmodified-Since", HttpHeader2["Keep-Alive"] = "Keep-Alive", HttpHeader2["Last-Modified"] = "Last-Modified", HttpHeader2.Link = "Link", HttpHeader2.Location = "Location", HttpHeader2["Max-Forwards"] = "Max-Forwards", HttpHeader2.NEL = "NEL", HttpHeader2["No-Vary-Search"] = "No-Vary-Search", HttpHeader2["Observe-Browsing-Topics"] = "Observe-Browsing-Topics", HttpHeader2["Origin-Agent-Cluster"] = "Origin-Agent-Cluster", HttpHeader2.Origin = "Origin", HttpHeader2["Permissions-Policy"] = "Permissions-Policy", HttpHeader2.Pragma = "Pragma", HttpHeader2.Priority = "Priority", HttpHeader2["Proxy-Authenticate"] = "Proxy-Authenticate", HttpHeader2["Proxy-Authorization"] = "Proxy-Authorization", HttpHeader2.Range = "Range", HttpHeader2.Referer = "Referer", HttpHeader2["Referrer-Policy"] = "Referrer-Policy", HttpHeader2.Refresh = "Refresh", HttpHeader2["Report-To"] = "Report-To", HttpHeader2["Reporting-Endpoints"] = "Reporting-Endpoints", HttpHeader2["Repr-Digest"] = "Repr-Digest", HttpHeader2["Retry-After"] = "Retry-After", HttpHeader2.RTT = "RTT", HttpHeader2["Save-Data"] = "Save-Data", HttpHeader2["Sec-Browsing-Topics"] = "Sec-Browsing-Topics", HttpHeader2["Sec-CH-Prefers-Color-Scheme"] = "Sec-CH-Prefers-Color-Scheme", HttpHeader2["Sec-CH-Prefers-Reduced-Motion"] = "Sec-CH-Prefers-Reduced-Motion", HttpHeader2["Sec-CH-Prefers-Reduced-Transparency"] = "Sec-CH-Prefers-Reduced-Transparency", HttpHeader2["Sec-CH-UA-Arch"] = "Sec-CH-UA-Arch", HttpHeader2["Sec-CH-UA-Bitness"] = "Sec-CH-UA-Bitness", HttpHeader2["Sec-CH-UA-Full-Version-List"] = "Sec-CH-UA-Full-Version-List", HttpHeader2["Sec-CH-UA-Full-Version"] = "Sec-CH-UA-Full-Version", HttpHeader2["Sec-CH-UA-Mobile"] = "Sec-CH-UA-Mobile", HttpHeader2["Sec-CH-UA-Model"] = "Sec-CH-UA-Model", HttpHeader2["Sec-CH-UA-Platform-Version"] = "Sec-CH-UA-Platform-Version", HttpHeader2["Sec-CH-UA-Platform"] = "Sec-CH-UA-Platform", HttpHeader2["Sec-CH-UA"] = "Sec-CH-UA", HttpHeader2["Sec-Fetch-Dest"] = "Sec-Fetch-Dest", HttpHeader2["Sec-Fetch-Mode"] = "Sec-Fetch-Mode", HttpHeader2["Sec-Fetch-Site"] = "Sec-Fetch-Site", HttpHeader2["Sec-Fetch-User"] = "Sec-Fetch-User", HttpHeader2["Sec-GPC"] = "Sec-GPC", HttpHeader2["Sec-Purpose"] = "Sec-Purpose", HttpHeader2["Sec-WebSocket-Accept"] = "Sec-WebSocket-Accept", HttpHeader2["Sec-WebSocket-Extensions"] = "Sec-WebSocket-Extensions", HttpHeader2["Sec-WebSocket-Key"] = "Sec-WebSocket-Key", HttpHeader2["Sec-WebSocket-Protocol"] = "Sec-WebSocket-Protocol", HttpHeader2["Sec-WebSocket-Version"] = "Sec-WebSocket-Version", HttpHeader2["Server-Timing"] = "Server-Timing", HttpHeader2.Server = "Server", HttpHeader2["Service-Worker-Navigation-Preload"] = "Service-Worker-Navigation-Preload", HttpHeader2["Set-Cookie"] = "Set-Cookie", HttpHeader2["Set-Login"] = "Set-Login", HttpHeader2.SourceMap = "SourceMap", HttpHeader2["Speculation-Rules"] = "Speculation-Rules", HttpHeader2["Strict-Transport-Security"] = "Strict-Transport-Security", HttpHeader2["Supports-Loading-Mode"] = "Supports-Loading-Mode", HttpHeader2.TE = "TE", HttpHeader2["Timing-Allow-Origin"] = "Timing-Allow-Origin", HttpHeader2.Tk = "Tk", HttpHeader2.Trailer = "Trailer", HttpHeader2["Transfer-Encoding"] = "Transfer-Encoding", HttpHeader2["Upgrade-Insecure-Requests"] = "Upgrade-Insecure-Requests", HttpHeader2.Upgrade = "Upgrade", HttpHeader2["User-Agent"] = "User-Agent", HttpHeader2.Vary = "Vary", HttpHeader2.Via = "Via", HttpHeader2["Viewport-Width"] = "Viewport-Width", HttpHeader2["Want-Content-Digest"] = "Want-Content-Digest", HttpHeader2["Want-Digest"] = "Want-Digest", HttpHeader2["Want-Repr-Digest"] = "Want-Repr-Digest", HttpHeader2.Warning = "Warning", HttpHeader2.Width = "Width", HttpHeader2["WWW-Authenticate"] = "WWW-Authenticate", HttpHeader2["X-Content-Type-Options"] = "X-Content-Type-Options", HttpHeader2["X-DNS-Prefetch-Control"] = "X-DNS-Prefetch-Control", HttpHeader2["X-Forwarded-For"] = "X-Forwarded-For", HttpHeader2["X-Forwarded-Host"] = "X-Forwarded-Host", HttpHeader2["X-Forwarded-Proto"] = "X-Forwarded-Proto", HttpHeader2["X-Frame-Options"] = "X-Frame-Options", HttpHeader2["X-XSS-Protection"] = "X-XSS-Protection", HttpHeader2))(HttpHeader || {}), HttpMethod = /* @__PURE__ */ ((HttpMethod2) => (HttpMethod2.CONNECT = "CONNECT", HttpMethod2.DELETE = "DELETE", HttpMethod2.GET = "GET", HttpMethod2.HEAD = "HEAD", HttpMethod2.OPTIONS = "OPTIONS", HttpMethod2.PATCH = "PATCH", HttpMethod2.POST = "POST", HttpMethod2.PUT = "PUT", HttpMethod2.TRACE = "TRACE", HttpMethod2))(HttpMethod || {}), HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => (HttpStatusCode2[HttpStatusCode2.CONTINUE = 100] = "CONTINUE", HttpStatusCode2[HttpStatusCode2.SWITCHING_PROTOCOLS = 101] = "SWITCHING_PROTOCOLS", HttpStatusCode2[HttpStatusCode2.PROCESSING = 102] = "PROCESSING", HttpStatusCode2[HttpStatusCode2.EARLY_HINTS = 103] = "EARLY_HINTS", HttpStatusCode2[HttpStatusCode2.OK = 200] = "OK", HttpStatusCode2[HttpStatusCode2.CREATED = 201] = "CREATED", HttpStatusCode2[HttpStatusCode2.ACCEPTED = 202] = "ACCEPTED", HttpStatusCode2[HttpStatusCode2.NON_AUTHORITATIVE_INFORMATION = 203] = "NON_AUTHORITATIVE_INFORMATION", HttpStatusCode2[HttpStatusCode2.NO_CONTENT = 204] = "NO_CONTENT", HttpStatusCode2[HttpStatusCode2.RESET_CONTENT = 205] = "RESET_CONTENT", HttpStatusCode2[HttpStatusCode2.PARTIAL_CONTENT = 206] = "PARTIAL_CONTENT", HttpStatusCode2[HttpStatusCode2.MULTI_STATUS = 207] = "MULTI_STATUS", HttpStatusCode2[HttpStatusCode2.ALREADY_REPORTED = 208] = "ALREADY_REPORTED", HttpStatusCode2[HttpStatusCode2.IM_USED = 226] = "IM_USED", HttpStatusCode2[HttpStatusCode2.MULTIPLE_CHOICES = 300] = "MULTIPLE_CHOICES", HttpStatusCode2[HttpStatusCode2.MOVED_PERMANENTLY = 301] = "MOVED_PERMANENTLY", HttpStatusCode2[HttpStatusCode2.FOUND = 302] = "FOUND", HttpStatusCode2[HttpStatusCode2.SEE_OTHER = 303] = "SEE_OTHER", HttpStatusCode2[HttpStatusCode2.NOT_MODIFIED = 304] = "NOT_MODIFIED", HttpStatusCode2[HttpStatusCode2.TEMPORARY_REDIRECT = 307] = "TEMPORARY_REDIRECT", HttpStatusCode2[HttpStatusCode2.PERMANENT_REDIRECT = 308] = "PERMANENT_REDIRECT", HttpStatusCode2[HttpStatusCode2.BAD_REQUEST = 400] = "BAD_REQUEST", HttpStatusCode2[HttpStatusCode2.UNAUTHORIZED = 401] = "UNAUTHORIZED", HttpStatusCode2[HttpStatusCode2.PAYMENT_REQUIRED = 402] = "PAYMENT_REQUIRED", HttpStatusCode2[HttpStatusCode2.FORBIDDEN = 403] = "FORBIDDEN", HttpStatusCode2[HttpStatusCode2.NOT_FOUND = 404] = "NOT_FOUND", HttpStatusCode2[HttpStatusCode2.METHOD_NOT_ALLOWED = 405] = "METHOD_NOT_ALLOWED", HttpStatusCode2[HttpStatusCode2.NOT_ACCEPTABLE = 406] = "NOT_ACCEPTABLE", HttpStatusCode2[HttpStatusCode2.PROXY_AUTHENTICATION_REQUIRED = 407] = "PROXY_AUTHENTICATION_REQUIRED", HttpStatusCode2[HttpStatusCode2.REQUEST_TIMEOUT = 408] = "REQUEST_TIMEOUT", HttpStatusCode2[HttpStatusCode2.CONFLICT = 409] = "CONFLICT", HttpStatusCode2[HttpStatusCode2.GONE = 410] = "GONE", HttpStatusCode2[HttpStatusCode2.LENGTH_REQUIRED = 411] = "LENGTH_REQUIRED", HttpStatusCode2[HttpStatusCode2.PRECONDITION_FAILED = 412] = "PRECONDITION_FAILED", HttpStatusCode2[HttpStatusCode2.CONTENT_TOO_LARGE = 413] = "CONTENT_TOO_LARGE", HttpStatusCode2[HttpStatusCode2.URI_TOO_LONG = 414] = "URI_TOO_LONG", HttpStatusCode2[HttpStatusCode2.UNSUPPORTED_MEDIA_TYPE = 415] = "UNSUPPORTED_MEDIA_TYPE", HttpStatusCode2[HttpStatusCode2.RANGE_NOT_SATISFIABLE = 416] = "RANGE_NOT_SATISFIABLE", HttpStatusCode2[HttpStatusCode2.EXPECTATION_FAILED = 417] = "EXPECTATION_FAILED", HttpStatusCode2[HttpStatusCode2.I_M_A_TEAPOT = 418] = "I_M_A_TEAPOT", HttpStatusCode2[HttpStatusCode2.MISDIRECTED_REQUEST = 421] = "MISDIRECTED_REQUEST", HttpStatusCode2[HttpStatusCode2.UNPROCESSABLE_CONTENT = 422] = "UNPROCESSABLE_CONTENT", HttpStatusCode2[HttpStatusCode2.LOCKED = 423] = "LOCKED", HttpStatusCode2[HttpStatusCode2.FAILED_DEPENDENCY = 424] = "FAILED_DEPENDENCY", HttpStatusCode2[HttpStatusCode2.TOO_EARLY = 425] = "TOO_EARLY", HttpStatusCode2[HttpStatusCode2.UPGRADE_REQUIRED = 426] = "UPGRADE_REQUIRED", HttpStatusCode2[HttpStatusCode2.PRECONDITION_REQUIRED = 428] = "PRECONDITION_REQUIRED", HttpStatusCode2[HttpStatusCode2.TOO_MANY_REQUESTS = 429] = "TOO_MANY_REQUESTS", HttpStatusCode2[HttpStatusCode2.REQUEST_HEADER_FIELDS_TOO_LARGE = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE", HttpStatusCode2[HttpStatusCode2.UNAVAILABLE_FOR_LEGAL_REASONS = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS", HttpStatusCode2[HttpStatusCode2.INTERNAL_SERVER_ERROR = 500] = "INTERNAL_SERVER_ERROR", HttpStatusCode2[HttpStatusCode2.NOT_IMPLEMENTED = 501] = "NOT_IMPLEMENTED", HttpStatusCode2[HttpStatusCode2.BAD_GATEWAY = 502] = "BAD_GATEWAY", HttpStatusCode2[HttpStatusCode2.SERVICE_UNAVAILABLE = 503] = "SERVICE_UNAVAILABLE", HttpStatusCode2[HttpStatusCode2.GATEWAY_TIMEOUT = 504] = "GATEWAY_TIMEOUT", HttpStatusCode2[HttpStatusCode2.HTTP_VERSION_NOT_SUPPORTED = 505] = "HTTP_VERSION_NOT_SUPPORTED", HttpStatusCode2[HttpStatusCode2.VARIANT_ALSO_NEGOTIATES = 506] = "VARIANT_ALSO_NEGOTIATES", HttpStatusCode2[HttpStatusCode2.INSUFFICIENT_STORAGE = 507] = "INSUFFICIENT_STORAGE", HttpStatusCode2[HttpStatusCode2.LOOP_DETECTED = 508] = "LOOP_DETECTED", HttpStatusCode2[HttpStatusCode2.NOT_EXTENDED = 510] = "NOT_EXTENDED", HttpStatusCode2[HttpStatusCode2.NETWORK_AUTHENTICATION_REQUIRED = 511] = "NETWORK_AUTHENTICATION_REQUIRED", HttpStatusCode2))(HttpStatusCode || {});
6
+ exports.createClient = createClient.createClient;
7
+ exports.fetch = fetch.fetch;
8
+ exports.getBaseUrl = index.getBaseUrl;
9
+ exports.getOperationById = index.getOperationById;
10
+ exports.getOperationByRoute = index.getOperationByRoute;
11
+ exports.isReferenceObject = index.isReferenceObject;
12
+ exports.resolveDocument = index.resolveDocument;
13
+ exports.resolveReference = index.resolveReference;
14
+ exports.isFormDataLike = parseRequest.isFormDataLike;
15
+ exports.isObjectLike = parseRequest.isObjectLike;
16
+ exports.parseRequest = parseRequest.parseRequest;
17
+ exports.parseRequestBody = parseRequest.parseRequestBody;
18
+ exports.parseRequestHeaders = parseRequest.parseRequestHeaders;
19
+ exports.parseRequestParameters = parseRequest.parseRequestParameters;
20
+ exports.parseRequestQuery = parseRequest.parseRequestQuery;
21
+ exports.parseRequestUrl = parseRequest.parseRequestUrl;
22
+ exports.toFormData = parseRequest.toFormData;
23
+ exports.toSearchParams = parseRequest.toSearchParams;
24
+ exports.HttpHeader = HttpHeader;
25
+ exports.HttpMethod = HttpMethod;
26
+ exports.HttpStatusCode = HttpStatusCode;
27
+ //# sourceMappingURL=index.cjs.map