@unshared/client 0.6.5 → 0.7.0

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.
Files changed (52) hide show
  1. package/dist/HttpHeaders.cjs +1 -1
  2. package/dist/HttpHeaders.cjs.map +1 -1
  3. package/dist/HttpHeaders.d.ts +10145 -1117
  4. package/dist/HttpHeaders.js +1 -1
  5. package/dist/HttpHeaders.js.map +1 -1
  6. package/dist/HttpMethods.cjs.map +1 -1
  7. package/dist/HttpMethods.d.ts +506 -20
  8. package/dist/HttpMethods.js.map +1 -1
  9. package/dist/HttpStatusCodes.cjs.map +1 -1
  10. package/dist/HttpStatusCodes.d.ts +2539 -83
  11. package/dist/HttpStatusCodes.js.map +1 -1
  12. package/dist/chunks/{CThSMMCZ.cjs → -InYnohy.cjs} +41 -50
  13. package/dist/chunks/{CThSMMCZ.cjs.map → -InYnohy.cjs.map} +1 -1
  14. package/dist/chunks/B6pUErTM.js.map +1 -1
  15. package/dist/chunks/BDxlAULu.cjs.map +1 -1
  16. package/dist/chunks/B_Gz6Yz8.js.map +1 -1
  17. package/dist/chunks/C83nLcQu.js.map +1 -1
  18. package/dist/chunks/{CQUndCW0.cjs → CNNxr5Ws.cjs} +8 -4
  19. package/dist/chunks/CNNxr5Ws.cjs.map +1 -0
  20. package/dist/chunks/{BGG3bT7O.d.ts → CNqEW-S3.d.ts} +12 -8
  21. package/dist/chunks/ClHrsaTt.js +19 -0
  22. package/dist/chunks/ClHrsaTt.js.map +1 -0
  23. package/dist/chunks/DEyigyGy.cjs.map +1 -1
  24. package/dist/chunks/DJyo3R5b.cjs.map +1 -1
  25. package/dist/chunks/{DAtM4FUl.d.ts → DKPTfBgy.d.ts} +1 -1
  26. package/dist/chunks/{uqfvs89o.js → DZ2MwV7J.js} +41 -50
  27. package/dist/chunks/{uqfvs89o.js.map → DZ2MwV7J.js.map} +1 -1
  28. package/dist/createClient.cjs +2 -2
  29. package/dist/createClient.cjs.map +1 -1
  30. package/dist/createClient.d.ts +3 -2
  31. package/dist/createClient.js +2 -2
  32. package/dist/createClient.js.map +1 -1
  33. package/dist/createService.cjs +1 -1
  34. package/dist/createService.cjs.map +1 -1
  35. package/dist/createService.d.ts +3 -2
  36. package/dist/createService.js +1 -1
  37. package/dist/createService.js.map +1 -1
  38. package/dist/index.cjs +2 -2
  39. package/dist/index.d.ts +3 -2
  40. package/dist/index.js +2 -2
  41. package/dist/openapi.cjs.map +1 -1
  42. package/dist/openapi.d.ts +20 -2
  43. package/dist/openapi.js.map +1 -1
  44. package/dist/utils.cjs +1 -1
  45. package/dist/utils.cjs.map +1 -1
  46. package/dist/utils.d.ts +5 -5
  47. package/dist/utils.js +3 -3
  48. package/dist/utils.js.map +1 -1
  49. package/package.json +4 -4
  50. package/dist/chunks/CQUndCW0.cjs.map +0 -1
  51. package/dist/chunks/xJaQKKe2.js +0 -15
  52. package/dist/chunks/xJaQKKe2.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CNNxr5Ws.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 { Awaitable } from '@unshared/functions/awaitable'\nimport type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport type RequestOptionsOnData<T> =\n T extends AsyncGenerator<infer U, any, any> ? (data: U, request: RequestOptions) => any\n : T extends Awaitable<AsyncGenerator<infer U, any, any>> ? (data: U, request: RequestOptions) => any\n : (data: T, request: RequestOptions) => any\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. Note that\n * when defined, the function will not throw an error, but instead return `undefined`.\n * If you want to throw an error, you have to throw it manually in the callback.\n */\n onError?: (error: Error, request: RequestOptions) => 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?: RequestOptionsOnData<Data>\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, request: RequestOptions) => any\n\n /**\n * The callback that is called when the status code is not OK (200-299). This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response, request: RequestOptions) => 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, request: RequestOptions) => 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 .catch((error: Error) => {\n if (options.onError) options.onError(error, options)\n else throw error\n })\n if (!response) return\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,IAAK,OAAM,IAAI,MAAM,6BAA6B;AACvD,SAAO,MAAM,WAAW,MAAM,KAAK,IAAI;AACzC;ACyDA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO,EACxC,MAAM,CAAC,UAAiB;AACvB,QAAI,QAAQ,QAAS,SAAQ,QAAQ,OAAO,OAAO;AAAA,QAC9C,OAAM;AAAA,EACb,CAAC;AACH,MAAK;AACL,WAAO,MAAMC,eAAAA,eAAe,UAAU,OAAO;AAC/C;;;"}
@@ -1,3 +1,4 @@
1
+ import { Awaitable } from '@unshared/functions/awaitable';
1
2
  import { MaybeArray, ObjectLike, Loose, UnionMerge, MaybeLiteral } from '@unshared/types';
2
3
  import { HttpHeader } from '../HttpHeaders.js';
3
4
  import { HttpMethod } from '../HttpMethods.js';
@@ -115,31 +116,34 @@ interface RequestContext {
115
116
  */
116
117
  declare function parseRequest(route: string, options?: FetchOptions): RequestContext;
117
118
 
119
+ type RequestOptionsOnData<T> = T extends AsyncGenerator<infer U, any, any> ? (data: U, request: RequestOptions) => any : T extends Awaitable<AsyncGenerator<infer U, any, any>> ? (data: U, request: RequestOptions) => any : (data: T, request: RequestOptions) => any;
118
120
  interface RequestOptions<Method extends FetchMethod = FetchMethod, BaseUrl extends string = string, Parameters extends ObjectLike = ObjectLike, Query extends ObjectLike = ObjectLike, Body = unknown, Headers extends ObjectLike = ObjectLike, Data = any, Response = globalThis.Response> extends FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {
119
121
  /**
120
- * The callback that is called when an error occurs during the request.
122
+ * The callback that is called when an error occurs during the request. Note that
123
+ * when defined, the function will not throw an error, but instead return `undefined`.
124
+ * If you want to throw an error, you have to throw it manually in the callback.
121
125
  */
122
- onError?: (error: Error) => any;
126
+ onError?: (error: Error, request: RequestOptions) => any;
123
127
  /**
124
128
  * The callback that is called when data is received from the request. This callback
125
129
  * will be called for each chunk of data that is received from the request.
126
130
  */
127
- onData?: (data: Data) => any;
131
+ onData?: RequestOptionsOnData<Data>;
128
132
  /**
129
133
  * The callback that is called when the request is successful. This callback will be
130
134
  * called after the request is complete and all data has been received.
131
135
  */
132
- onSuccess?: (response: Response) => any;
136
+ onSuccess?: (response: Response, request: RequestOptions) => any;
133
137
  /**
134
- * The callback that is called when the status code is not OK. This callback will be called
138
+ * The callback that is called when the status code is not OK (200-299). This callback will be called
135
139
  * after the request is complete and before the data is consumed.
136
140
  */
137
- onFailure?: (response: Response) => any;
141
+ onFailure?: (response: Response, request: RequestOptions) => any;
138
142
  /**
139
143
  * The callback that is called when the request is complete. This callback will be called
140
144
  * after the request is complete and all data has been received.
141
145
  */
142
- onEnd?: (response: Response) => any;
146
+ onEnd?: (response: Response, request: RequestOptions) => any;
143
147
  }
144
148
  /**
145
149
  * Fetch a route from the API and return the data. If the client was instantiated with an
@@ -162,4 +166,4 @@ interface RequestOptions<Method extends FetchMethod = FetchMethod, BaseUrl exten
162
166
  declare function request(route: string, options?: RequestOptions): Promise<unknown>;
163
167
 
164
168
  export { parseRequest as p, request as r, toSearchParams as t };
165
- export type { FetchOptions as F, RequestOptions as R, SearchParamsObject as S, ToSearchParamsOptions as T, FetchMethod as a, RequestContext as b, FetchHeaders as c, SearchArrayFormat as d };
169
+ export type { FetchOptions as F, RequestOptions as R, SearchParamsObject as S, ToSearchParamsOptions as T, FetchMethod as a, RequestContext as b, FetchHeaders as c, RequestOptionsOnData as d, SearchArrayFormat as e };
@@ -0,0 +1,19 @@
1
+ import { p as parseRequest, h as handleResponse } from "./DZ2MwV7J.js";
2
+ async function fetch(route, options = {}) {
3
+ const { url, init } = parseRequest(route, options);
4
+ if (!url) throw new Error("Could not parse request URL");
5
+ return await globalThis.fetch(url, init);
6
+ }
7
+ async function request(route, options = {}) {
8
+ const response = await fetch(route, options).catch((error) => {
9
+ if (options.onError) options.onError(error, options);
10
+ else throw error;
11
+ });
12
+ if (response)
13
+ return await handleResponse(response, options);
14
+ }
15
+ export {
16
+ fetch as f,
17
+ request as r
18
+ };
19
+ //# sourceMappingURL=ClHrsaTt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClHrsaTt.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 { Awaitable } from '@unshared/functions/awaitable'\nimport type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport type RequestOptionsOnData<T> =\n T extends AsyncGenerator<infer U, any, any> ? (data: U, request: RequestOptions) => any\n : T extends Awaitable<AsyncGenerator<infer U, any, any>> ? (data: U, request: RequestOptions) => any\n : (data: T, request: RequestOptions) => any\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. Note that\n * when defined, the function will not throw an error, but instead return `undefined`.\n * If you want to throw an error, you have to throw it manually in the callback.\n */\n onError?: (error: Error, request: RequestOptions) => 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?: RequestOptionsOnData<Data>\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, request: RequestOptions) => any\n\n /**\n * The callback that is called when the status code is not OK (200-299). This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response, request: RequestOptions) => 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, request: RequestOptions) => 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 .catch((error: Error) => {\n if (options.onError) options.onError(error, options)\n else throw error\n })\n if (!response) return\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,IAAK,OAAM,IAAI,MAAM,6BAA6B;AACvD,SAAO,MAAM,WAAW,MAAM,KAAK,IAAI;AACzC;ACyDA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAM,MAAM,OAAO,OAAO,EACxC,MAAM,CAAC,UAAiB;AACvB,QAAI,QAAQ,QAAS,SAAQ,QAAQ,OAAO,OAAO;AAAA,QAC9C,OAAM;AAAA,EACb,CAAC;AACH,MAAK;AACL,WAAO,MAAM,eAAe,UAAU,OAAO;AAC/C;"}
@@ -1 +1 @@
1
- {"version":3,"file":"DEyigyGy.cjs","sources":["../../openapi/getServerUrl.ts","../../openapi/resolveOperation.ts","../../openapi/isOpenAPIV3.ts","../../openapi/resolveOperationTokenOptions.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Get the base URL of an OpenAPI specification. */\nexport type ServerUrl<T> =\n\n // --- Handle OpenAPI 2.0 specifications.\n T extends {\n host: infer Host extends string\n basePath?: infer BasePath extends string\n schemes?: Array<infer Scheme extends string>\n }\n ? `${Scheme}://${Host}${BasePath}`\n\n // --- Handle OpenAPI 3.0 specifications.\n : T extends { servers: Array<{ url: infer U extends string }> }\n ? U\n : string\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 getServerUrl<T>(specification: T): ServerUrl<T> {\n\n // --- Ensure the specification is an object.\n if (\n !specification\n || typeof specification !== 'object'\n || specification === null)\n throw new Error('Invalid OpenAPI specification.')\n\n // --- Handle OpenAPI 3.0 specifications.\n if (\n 'servers' in specification\n && Array.isArray(specification.servers)\n && specification.servers.length > 0\n && 'url' in specification.servers[0]\n && typeof specification.servers[0].url === 'string'\n && specification.servers[0].url.length > 0)\n return specification.servers[0].url as ServerUrl<T>\n\n // --- Handle OpenAPI 2.0 specifications.\n if (\n 'host' in specification\n && typeof specification.host === 'string') {\n\n const scheme = (\n 'schemes' in specification\n && Array.isArray(specification.schemes)\n && specification.schemes.length > 0\n && typeof specification.schemes[0] === 'string')\n ? specification.schemes[0]\n : 'https'\n\n const basePath = (\n 'basePath' in specification\n && typeof specification.basePath === 'string'\n && specification.basePath.length > 0)\n ? specification.basePath\n : '/'\n\n return `${scheme}://${specification.host}${basePath}` as ServerUrl<T>\n }\n\n throw new Error('No base URL found in the OpenAPI specification.')\n}\n","import type { CollectKey, Pretty } from '@unshared/types'\nimport type { OpenAPI } from 'openapi-types'\nimport type { FetchMethod } from '../utils/parseRequest'\n\n/** The HTTP methods supported by OpenAPI. */\nconst methods = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch'] as const\n\n/** Union of all operation IDs in the specification. */\nexport type OperationId<T> =\nT extends { paths: infer P }\n ? P extends Record<string, infer R>\n ? R extends Record<string, infer O>\n ? O extends { operationId: infer N }\n ? N\n : string\n : string\n : string\n : string\n\n/** A union of possible Operations types in the specification. */\nexport type Operation = OpenAPI.Operation & { method: FetchMethod; path: string }\n\n/** Find an operation by its operationId in an OpenAPI specification. */\nexport type OperationById<T, U extends OperationId<T>> =\n T extends { paths: infer P }\n ? CollectKey<P> extends Record<string, infer R>\n ? CollectKey<R> extends Record<string, infer O>\n ? O extends { $key: [infer P extends string, infer M extends string]; operationId: U }\n ? Pretty<Omit<O, '$key'> & { method: M; path: P }>\n : never\n : never\n : never\n : never\n\n/**\n * Given an OpenAPI specification, find an operation by its operationId.\n *\n * @param document The OpenAPI specification document.\n * @param operationId The operationId of the operation to resolve.\n * @returns The resolved operation.\n * @example resolveOperation(document, 'getUser') // { method: 'get', path: '/users/{username}', ... }\n */\nexport function resolveOperation<T, U extends OperationId<T>>(document: T, operationId: U): OperationById<T, U>\nexport function resolveOperation(document: object, operationId: string): Operation\nexport function resolveOperation(document: object, operationId: string): Operation {\n\n // --- Validate the specification.\n if (!document\n || typeof document !== 'object'\n || document === null\n || 'paths' in document === false\n || typeof document.paths !== 'object'\n || document.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 = document.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 }\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","/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV3 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v3.0 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v3.0 specification, `false` otherwise.\n * @example isOpenAPIV3({ openapi: '3.0.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV3(value: unknown): value is OpenAPIV3.Document {\n return typeof value === 'object'\n && value !== null\n && 'openapi' in value\n && value.openapi === '3.0.0'\n}\n","import type { OpenAPI, OpenAPIV3 as V3 } from 'openapi-types'\nimport { isOpenAPIV3 } from './isOpenAPIV3'\n\nexport interface TokenOptions {\n tokenLocation?: 'cookie' | 'header' | 'query'\n tokenProperty?: string\n}\n\n/**\n * Resolve the location of the apiKey token based on the OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param operation The OpenAPI operation object.\n * @returns The location of the apiKey token ('query' | 'cookie' | 'header').\n * @example resolveOperationTokenOptions(document, operation) // => { tokenLocation: 'header', tokenProperty: 'X-API-Key' }\n */\nexport function resolveOperationTokenOptions(document: object, operation: OpenAPI.Operation): TokenOptions {\n if (!isOpenAPIV3(document)) return {}\n\n // --- Find the security scheme in the OpenAPI specification.\n const security = operation.security ?? document.security\n if (!security) return {}\n const securityScheme = document?.components?.securitySchemes\n if (!securityScheme) return {}\n\n // --- Find the first security scheme that is an apiKey.\n for (const requirement of security) {\n for (const key in requirement) {\n const scheme = securityScheme[key] as V3.SecuritySchemeObject\n if (typeof scheme !== 'object' || scheme === null) continue\n if (scheme.type === 'apiKey') {\n return {\n tokenLocation: scheme.in as 'cookie' | 'header' | 'query',\n tokenProperty: scheme.name,\n }\n }\n }\n }\n\n // --- Return an empty object if no apiKey was found.\n return {}\n}\n"],"names":[],"mappings":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AA,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;ACnEO,SAAS,YAAY,OAA6C;AAChE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACCgB,SAAA,6BAA6B,UAAkB,WAA4C;AACzG,MAAI,CAAC,YAAY,QAAQ,UAAU,CAAC;AAG9B,QAAA,WAAW,UAAU,YAAY,SAAS;AAC5C,MAAA,CAAC,SAAU,QAAO,CAAC;AACjB,QAAA,iBAAiB,UAAU,YAAY;AACzC,MAAA,CAAC,eAAgB,QAAO,CAAC;AAG7B,aAAW,eAAe;AACxB,eAAW,OAAO,aAAa;AACvB,YAAA,SAAS,eAAe,GAAG;AACjC,UAAI,SAAO,UAAW,YAAY,WAAW,SACzC,OAAO,SAAS;AACX,eAAA;AAAA,UACL,eAAe,OAAO;AAAA,UACtB,eAAe,OAAO;AAAA,QACxB;AAAA,IAAA;AAMN,SAAO,CAAC;AACV;;;;;"}
1
+ {"version":3,"file":"DEyigyGy.cjs","sources":["../../openapi/getServerUrl.ts","../../openapi/resolveOperation.ts","../../openapi/isOpenAPIV3.ts","../../openapi/resolveOperationTokenOptions.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Get the base URL of an OpenAPI specification. */\nexport type ServerUrl<T> =\n\n // --- Handle OpenAPI 2.0 specifications.\n T extends {\n host: infer Host extends string\n basePath?: infer BasePath extends string\n schemes?: Array<infer Scheme extends string>\n }\n ? `${Scheme}://${Host}${BasePath}`\n\n // --- Handle OpenAPI 3.0 specifications.\n : T extends { servers: Array<{ url: infer U extends string }> }\n ? U\n : string\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 getServerUrl<T>(specification: T): ServerUrl<T> {\n\n // --- Ensure the specification is an object.\n if (\n !specification\n || typeof specification !== 'object'\n || specification === null)\n throw new Error('Invalid OpenAPI specification.')\n\n // --- Handle OpenAPI 3.0 specifications.\n if (\n 'servers' in specification\n && Array.isArray(specification.servers)\n && specification.servers.length > 0\n && 'url' in specification.servers[0]\n && typeof specification.servers[0].url === 'string'\n && specification.servers[0].url.length > 0)\n return specification.servers[0].url as ServerUrl<T>\n\n // --- Handle OpenAPI 2.0 specifications.\n if (\n 'host' in specification\n && typeof specification.host === 'string') {\n\n const scheme = (\n 'schemes' in specification\n && Array.isArray(specification.schemes)\n && specification.schemes.length > 0\n && typeof specification.schemes[0] === 'string')\n ? specification.schemes[0]\n : 'https'\n\n const basePath = (\n 'basePath' in specification\n && typeof specification.basePath === 'string'\n && specification.basePath.length > 0)\n ? specification.basePath\n : '/'\n\n return `${scheme}://${specification.host}${basePath}` as ServerUrl<T>\n }\n\n throw new Error('No base URL found in the OpenAPI specification.')\n}\n","import type { CollectKey, Pretty } from '@unshared/types'\nimport type { OpenAPI } from 'openapi-types'\nimport type { FetchMethod } from '../utils/parseRequest'\n\n/** The HTTP methods supported by OpenAPI. */\nconst methods = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch'] as const\n\n/** Union of all operation IDs in the specification. */\nexport type OperationId<T> =\nT extends { paths: infer P }\n ? P extends Record<string, infer R>\n ? R extends Record<string, infer O>\n ? O extends { operationId: infer N }\n ? N\n : string\n : string\n : string\n : string\n\n/** A union of possible Operations types in the specification. */\nexport type Operation = OpenAPI.Operation & { method: FetchMethod; path: string }\n\n/** Find an operation by its operationId in an OpenAPI specification. */\nexport type OperationById<T, U extends OperationId<T>> =\n T extends { paths: infer P }\n ? CollectKey<P> extends Record<string, infer R>\n ? CollectKey<R> extends Record<string, infer O>\n ? O extends { $key: [infer P extends string, infer M extends string]; operationId: U }\n ? Pretty<Omit<O, '$key'> & { method: M; path: P }>\n : never\n : never\n : never\n : never\n\n/**\n * Given an OpenAPI specification, find an operation by its operationId.\n *\n * @param document The OpenAPI specification document.\n * @param operationId The operationId of the operation to resolve.\n * @returns The resolved operation.\n * @example resolveOperation(document, 'getUser') // { method: 'get', path: '/users/{username}', ... }\n */\nexport function resolveOperation<T, U extends OperationId<T>>(document: T, operationId: U): OperationById<T, U>\nexport function resolveOperation(document: object, operationId: string): Operation\nexport function resolveOperation(document: object, operationId: string): Operation {\n\n // --- Validate the specification.\n if (!document\n || typeof document !== 'object'\n || document === null\n || 'paths' in document === false\n || typeof document.paths !== 'object'\n || document.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 = document.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 }\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","/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV3 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v3.0 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v3.0 specification, `false` otherwise.\n * @example isOpenAPIV3({ openapi: '3.0.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV3(value: unknown): value is OpenAPIV3.Document {\n return typeof value === 'object'\n && value !== null\n && 'openapi' in value\n && value.openapi === '3.0.0'\n}\n","import type { OpenAPI, OpenAPIV3 as V3 } from 'openapi-types'\nimport { isOpenAPIV3 } from './isOpenAPIV3'\n\nexport interface TokenOptions {\n tokenLocation?: 'cookie' | 'header' | 'query'\n tokenProperty?: string\n}\n\n/**\n * Resolve the location of the apiKey token based on the OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param operation The OpenAPI operation object.\n * @returns The location of the apiKey token ('query' | 'cookie' | 'header').\n * @example resolveOperationTokenOptions(document, operation) // => { tokenLocation: 'header', tokenProperty: 'X-API-Key' }\n */\nexport function resolveOperationTokenOptions(document: object, operation: OpenAPI.Operation): TokenOptions {\n if (!isOpenAPIV3(document)) return {}\n\n // --- Find the security scheme in the OpenAPI specification.\n const security = operation.security ?? document.security\n if (!security) return {}\n const securityScheme = document?.components?.securitySchemes\n if (!securityScheme) return {}\n\n // --- Find the first security scheme that is an apiKey.\n for (const requirement of security) {\n for (const key in requirement) {\n const scheme = securityScheme[key] as V3.SecuritySchemeObject\n if (typeof scheme !== 'object' || scheme === null) continue\n if (scheme.type === 'apiKey') {\n return {\n tokenLocation: scheme.in as 'cookie' | 'header' | 'query',\n tokenProperty: scheme.name,\n }\n }\n }\n }\n\n // --- Return an empty object if no apiKey was found.\n return {}\n}\n"],"names":[],"mappings":";AAwBO,SAAS,aAAgB,eAAgC;AAG9D,MACE,CAAC,iBACE,OAAO,iBAAkB,YACzB,kBAAkB;AACrB,UAAM,IAAI,MAAM,gCAAgC;AAGlD,MACE,aAAa,iBACV,MAAM,QAAQ,cAAc,OAAO,KACnC,cAAc,QAAQ,SAAS,KAC/B,SAAS,cAAc,QAAQ,CAAC,KAChC,OAAO,cAAc,QAAQ,CAAC,EAAE,OAAQ,YACxC,cAAc,QAAQ,CAAC,EAAE,IAAI,SAAS;AACzC,WAAO,cAAc,QAAQ,CAAC,EAAE;AAGlC,MACE,UAAU,iBACP,OAAO,cAAc,QAAS,UAAU;AAE3C,UAAM,SACJ,aAAa,iBACV,MAAM,QAAQ,cAAc,OAAO,KACnC,cAAc,QAAQ,SAAS,KAC/B,OAAO,cAAc,QAAQ,CAAC,KAAM,WACrC,cAAc,QAAQ,CAAC,IACvB,SAEE,WACJ,cAAc,iBACX,OAAO,cAAc,YAAa,YAClC,cAAc,SAAS,SAA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AS;AAClB,eAAO;AAAA,UACL,eAAe,OAAO;AAAA,UACtB,eAAe,OAAO;AAAA,QAAA;AAAA,IAG5B;AAIF,SAAO,CAAA;AACT;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"DJyo3R5b.cjs","sources":["../../websocket/parseConnectOptions.ts","../../websocket/connect.ts"],"sourcesContent":["import type { Loose, ObjectLike, UnionMerge } from '@unshared/types'\nimport { parseRequestParameters } from '../utils/parseRequestParameters'\nimport { parseRequestQuery } from '../utils/parseRequestQuery'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_CONNECTION_CHANNEL = /^((?<protocol>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid WebSocket protocols. */\nconst PROTOCOLS = new Set(['ws', 'wss'])\n\n/** The protocols to use for the connection. */\nexport type ConnectProtocol = 'WS' | 'WSS'\n\n/** Options to pass to the `createChannel` function. */\nexport interface ConnectOptions<\n BaseUrl extends string = string,\n Query extends ObjectLike = ObjectLike,\n Parameters extends ObjectLike = ObjectLike,\n ClientData extends ObjectLike = any,\n ServerData extends ObjectLike = any,\n> {\n\n /** The protocol to use when connecting to the server. */\n protocol?: Lowercase<ConnectProtocol> | Uppercase<ConnectProtocol>\n\n /** The base URL to connect to. */\n baseUrl?: BaseUrl\n\n /**\n * The path parameters to use when connecting to the server. These parameters will be used to\n * fill in the path parameters of the connection URL.\n *\n * @example { id: 1 }\n */\n parameters?: Parameters\n\n /**\n * The query parameters to use when connecting to the server. These parameters will be used to\n * fill in the query parameters of the connection URL.\n *\n * @example { limit: 10, offset: 0 }\n */\n query?: Loose<Query>\n\n /**\n * The data to send when creating the connection. Namely, the path parameters\n * to use when connecting to the server.\n *\n * @example\n *\n * // Create a new connection to `http://localhost:8080/users/1`.\n * connect('GET /users/:id', {\n * data: { id: 1 },\n * baseUrl: 'http://localhost:8080'\n * })\n */\n data?: UnionMerge<Loose<Query> | Parameters>\n\n /**\n * The payload to send when creating the connection. Namely, the initial message\n * to send to the server when the connection is established.\n */\n initialPayload?: Loose<ClientData>\n\n /**\n * Weather to reconnect the connection when it is closed unexpectedly. If `true`,\n * the connection will automatically reconnect when it is closed. If `false`, the\n * connection will not reconnect when it is closed.\n *\n * @default false\n */\n autoReconnect?: boolean\n\n /**\n * The delay in milliseconds to wait before reconnecting the connection. This delay\n * will be used to wait before reconnecting the connection after it is closed.\n *\n * @default 0\n */\n reconnectDelay?: number\n\n /**\n * The maximum number of times to reconnect the connection before giving up. This\n * number will be used to determine when to stop trying to reconnect the connection.\n *\n * @default 3\n */\n reconnectLimit?: number\n\n /**\n * The function to call when the connection is opened. This function will be called\n * when the connection is successfully opened or reconnected.\n */\n onOpen?: (event: Event) => void\n\n /**\n * The function to call when the connection is closed with an error. This function will\n * be called when the connection is closed unexpectedly with an error.\n */\n onError?: (event: Event) => void\n\n /**\n * The function to call when the connection is closed. This function will be called\n * when the connection is closed unexpectedly or when the connection is closed manually.\n */\n onClose?: (event: CloseEvent) => void\n\n /**\n * The function to call when a message is received from the server. This function will\n * be called when a message is received from the server.\n */\n onMessage?: (data: ServerData) => void\n}\n\nexport interface WebSocketParameters {\n url: URL\n protocol?: 'ws' | 'wss'\n}\n\nfunction parseConnectUrl(parameters: WebSocketParameters, channel: string, options: ConnectOptions): void {\n const { baseUrl, protocol } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_CONNECTION_CHANNEL.exec(channel)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeProtocol = protocol ?? match.groups.protocol ?? 'ws'\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 protocolLower = routeProtocol.toLowerCase()\n const protocolIsValid = PROTOCOLS.has(protocolLower)\n if (!protocolIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeProtocol}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n parameters.url = new URL(routeBaseUrl)\n parameters.url.pathname += parameters.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n parameters.protocol = protocolLower as 'ws' | 'wss'\n}\n\nexport function parseConnectOptions(channel: string, options: ConnectOptions): WebSocketParameters {\n const { baseUrl, protocol, data, parameters = data, query = data } = options\n const wsParameters: WebSocketParameters = { url: new URL('about:blank') }\n parseConnectUrl(wsParameters, channel, { baseUrl, protocol })\n parseRequestParameters(wsParameters, { parameters })\n parseRequestQuery(wsParameters, { query })\n return wsParameters\n}\n","import type { ConnectOptions } from './parseConnectOptions'\nimport { parseConnectOptions } from './parseConnectOptions'\n\ntype RemoveListener = () => void\n\ntype ClientData<T extends ConnectOptions> =\n T extends ConnectOptions<any, any, any, infer R, any> ? R : any\n\ntype ServerData<T extends ConnectOptions> =\n T extends ConnectOptions<any, any, any, any, infer R> ? R : any\n\nexport class WebSocketChannel<T extends ConnectOptions = ConnectOptions> {\n constructor(public channel: string, public options: T) {}\n\n /** The WebSocket connection to the server. */\n public webSocket: undefined | WebSocket\n\n /**\n * Open a new WebSocket connection to the server. The connection will be opened with the given\n * URL and protocols. If the connection is already open, the connection will be closed before\n * opening a new connection. Also add the event listeners that were passed in the options.\n *\n * @returns The WebSocket connection.\n */\n async open(): Promise<this> {\n if (this.webSocket) await this.close()\n const { url, protocol } = parseConnectOptions(this.channel, this.options)\n this.webSocket = new WebSocket(url, protocol)\n\n // --- Return a promise that resolves when the connection is opened.\n const promise = new Promise<void>((resolve, rejects) => {\n this.webSocket!.addEventListener('error', () => rejects(new Error('Failed to open the WebSocket connection')), { once: true })\n this.webSocket!.addEventListener('open', () => {\n if (this.options.initialPayload) this.send(this.options.initialPayload as ClientData<T>)\n resolve()\n }, { once: true })\n })\n\n // --- Add the options' hooks to the WebSocket connection.\n if (this.options.onOpen) this.on('open', this.options.onOpen, { once: true })\n if (this.options.onClose) this.on('close', this.options.onClose, { once: true })\n if (this.options.onError) this.on('error', this.options.onError)\n if (this.options.onMessage) this.on('message', message => this.options.onMessage!(message))\n\n // --- Handle reconnection when the connection is closed unexpectedly.\n this.webSocket.addEventListener('close', (event) => {\n if (event.code === 1000) return\n if (!this.options.autoReconnect) return\n if (this.options.reconnectLimit && event.wasClean) return\n setTimeout(() => void this.open(), this.options.reconnectDelay ?? 0)\n }, { once: true })\n\n return promise.then(() => this)\n }\n\n /**\n * Send a payload to the server. The payload will be serialized to JSON before sending.\n *\n * @param payload The data to send to the server.\n */\n send(payload: ClientData<T>) {\n if (!this.webSocket) throw new Error('WebSocket connection is not open')\n const json = JSON.stringify(payload)\n this.webSocket.send(json)\n }\n\n /**\n * Listen for events from the server. The event will be deserialized from JSON before calling the callback.\n *\n * @param event The event to listen for.\n * @param callback The callback to call when the event is received.\n * @returns A function to remove the event listener.\n */\n on(event: 'message', callback: (data: ServerData<T>) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: 'close', callback: (event: CloseEvent) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: 'error', callback: (event: Event) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: 'open', callback: (event: Event) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: string, callback: (data: any) => any, options?: AddEventListenerOptions) {\n if (!this.webSocket) throw new Error('WebSocket connection has not been opened yet')\n\n const listener = async(event: CloseEvent | Event | MessageEvent<Blob>): Promise<void> => {\n if (event.type !== 'message') callback(event)\n // @ts-expect-error: `data` exists on the event.\n let data = event.data as unknown\n if (data instanceof Blob) data = await data.text()\n try { data = JSON.parse(data as string) }\n catch { console.error('Failed to parse the message:', data) }\n callback(data)\n }\n\n /* eslint-disable @typescript-eslint/no-misused-promises */\n this.webSocket.addEventListener(event, listener, options)\n return () => this.webSocket!.removeEventListener(event, listener)\n /* eslint-enable @typescript-eslint/no-misused-promises */\n }\n\n /**\n * Close the WebSocket connection to the server. The connection will not be able to send or receive\n * messages after it is closed.\n */\n async close() {\n if (!this.webSocket) throw new Error('WebSocket connection has not been opened yet')\n if (this.webSocket.readyState === WebSocket.CLOSED) return\n if (this.webSocket.readyState === WebSocket.CLOSING) return\n this.webSocket.close(1000, 'Client closed the connection')\n await new Promise<void>(resolve => this.webSocket!.addEventListener('close', () => resolve()))\n }\n}\n\n/**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param route The name of the route to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\nexport function connect(route: string, options: ConnectOptions): WebSocketChannel {\n return new WebSocketChannel(route, options)\n}\n"],"names":["parseRequestParameters","parseRequestQuery","event"],"mappings":";;AAKA,MAAM,yBAAyB,yEAGzB,YAAY,oBAAI,IAAI,CAAC,MAAM,KAAK,CAAC;AA+GvC,SAAS,gBAAgB,YAAiC,SAAiB,SAA+B;AAClG,QAAA,EAAE,SAAS,aAAa,SAGxB,QAAQ,uBAAuB,KAAK,OAAO;AACjD,MAAI,CAAC,OAAO,OAAc,OAAA,IAAI,MAAM,iEAAiE;AAC/F,QAAA,gBAAgB,YAAY,MAAM,OAAO,YAAY,MACrD,eAAe,WAAW,MAAM,OAAO;AAG7C,MAAI,CAAC,aAAoB,OAAA,IAAI,MAAM,uEAAuE;AAGpG,QAAA,gBAAgB,cAAc,YAAY;AAE5C,MAAA,CADoB,UAAU,IAAI,aAAa,SACvB,IAAI,MAAM,+DAA+D,aAAa,gBAAgB;AAGvH,aAAA,MAAM,IAAI,IAAI,YAAY,GACrC,WAAW,IAAI,YAAY,WAAW,IAAI,SAAS,SAAS,GAAG,IAAI,MAAM,OAAO,KAAK,MAAM,CAAC,IAAI,MAAM,OAAO,MAC7G,WAAW,WAAW;AACxB;AAEgB,SAAA,oBAAoB,SAAiB,SAA8C;AACjG,QAAM,EAAE,SAAS,UAAU,MAAM,aAAa,MAAM,QAAQ,KAAA,IAAS,SAC/D,eAAoC,EAAE,KAAK,IAAI,IAAI,aAAa,EAAE;AACxE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,OAAO,OAAO;AAC5C;;;;"}
1
+ {"version":3,"file":"DJyo3R5b.cjs","sources":["../../websocket/parseConnectOptions.ts","../../websocket/connect.ts"],"sourcesContent":["import type { Loose, ObjectLike, UnionMerge } from '@unshared/types'\nimport { parseRequestParameters } from '../utils/parseRequestParameters'\nimport { parseRequestQuery } from '../utils/parseRequestQuery'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_CONNECTION_CHANNEL = /^((?<protocol>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid WebSocket protocols. */\nconst PROTOCOLS = new Set(['ws', 'wss'])\n\n/** The protocols to use for the connection. */\nexport type ConnectProtocol = 'WS' | 'WSS'\n\n/** Options to pass to the `createChannel` function. */\nexport interface ConnectOptions<\n BaseUrl extends string = string,\n Query extends ObjectLike = ObjectLike,\n Parameters extends ObjectLike = ObjectLike,\n ClientData extends ObjectLike = any,\n ServerData extends ObjectLike = any,\n> {\n\n /** The protocol to use when connecting to the server. */\n protocol?: Lowercase<ConnectProtocol> | Uppercase<ConnectProtocol>\n\n /** The base URL to connect to. */\n baseUrl?: BaseUrl\n\n /**\n * The path parameters to use when connecting to the server. These parameters will be used to\n * fill in the path parameters of the connection URL.\n *\n * @example { id: 1 }\n */\n parameters?: Parameters\n\n /**\n * The query parameters to use when connecting to the server. These parameters will be used to\n * fill in the query parameters of the connection URL.\n *\n * @example { limit: 10, offset: 0 }\n */\n query?: Loose<Query>\n\n /**\n * The data to send when creating the connection. Namely, the path parameters\n * to use when connecting to the server.\n *\n * @example\n *\n * // Create a new connection to `http://localhost:8080/users/1`.\n * connect('GET /users/:id', {\n * data: { id: 1 },\n * baseUrl: 'http://localhost:8080'\n * })\n */\n data?: UnionMerge<Loose<Query> | Parameters>\n\n /**\n * The payload to send when creating the connection. Namely, the initial message\n * to send to the server when the connection is established.\n */\n initialPayload?: Loose<ClientData>\n\n /**\n * Weather to reconnect the connection when it is closed unexpectedly. If `true`,\n * the connection will automatically reconnect when it is closed. If `false`, the\n * connection will not reconnect when it is closed.\n *\n * @default false\n */\n autoReconnect?: boolean\n\n /**\n * The delay in milliseconds to wait before reconnecting the connection. This delay\n * will be used to wait before reconnecting the connection after it is closed.\n *\n * @default 0\n */\n reconnectDelay?: number\n\n /**\n * The maximum number of times to reconnect the connection before giving up. This\n * number will be used to determine when to stop trying to reconnect the connection.\n *\n * @default 3\n */\n reconnectLimit?: number\n\n /**\n * The function to call when the connection is opened. This function will be called\n * when the connection is successfully opened or reconnected.\n */\n onOpen?: (event: Event) => void\n\n /**\n * The function to call when the connection is closed with an error. This function will\n * be called when the connection is closed unexpectedly with an error.\n */\n onError?: (event: Event) => void\n\n /**\n * The function to call when the connection is closed. This function will be called\n * when the connection is closed unexpectedly or when the connection is closed manually.\n */\n onClose?: (event: CloseEvent) => void\n\n /**\n * The function to call when a message is received from the server. This function will\n * be called when a message is received from the server.\n */\n onMessage?: (data: ServerData) => void\n}\n\nexport interface WebSocketParameters {\n url: URL\n protocol?: 'ws' | 'wss'\n}\n\nfunction parseConnectUrl(parameters: WebSocketParameters, channel: string, options: ConnectOptions): void {\n const { baseUrl, protocol } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_CONNECTION_CHANNEL.exec(channel)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeProtocol = protocol ?? match.groups.protocol ?? 'ws'\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 protocolLower = routeProtocol.toLowerCase()\n const protocolIsValid = PROTOCOLS.has(protocolLower)\n if (!protocolIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeProtocol}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n parameters.url = new URL(routeBaseUrl)\n parameters.url.pathname += parameters.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n parameters.protocol = protocolLower as 'ws' | 'wss'\n}\n\nexport function parseConnectOptions(channel: string, options: ConnectOptions): WebSocketParameters {\n const { baseUrl, protocol, data, parameters = data, query = data } = options\n const wsParameters: WebSocketParameters = { url: new URL('about:blank') }\n parseConnectUrl(wsParameters, channel, { baseUrl, protocol })\n parseRequestParameters(wsParameters, { parameters })\n parseRequestQuery(wsParameters, { query })\n return wsParameters\n}\n","import type { ConnectOptions } from './parseConnectOptions'\nimport { parseConnectOptions } from './parseConnectOptions'\n\ntype RemoveListener = () => void\n\ntype ClientData<T extends ConnectOptions> =\n T extends ConnectOptions<any, any, any, infer R, any> ? R : any\n\ntype ServerData<T extends ConnectOptions> =\n T extends ConnectOptions<any, any, any, any, infer R> ? R : any\n\nexport class WebSocketChannel<T extends ConnectOptions = ConnectOptions> {\n constructor(public channel: string, public options: T) {}\n\n /** The WebSocket connection to the server. */\n public webSocket: undefined | WebSocket\n\n /**\n * Open a new WebSocket connection to the server. The connection will be opened with the given\n * URL and protocols. If the connection is already open, the connection will be closed before\n * opening a new connection. Also add the event listeners that were passed in the options.\n *\n * @returns The WebSocket connection.\n */\n async open(): Promise<this> {\n if (this.webSocket) await this.close()\n const { url, protocol } = parseConnectOptions(this.channel, this.options)\n this.webSocket = new WebSocket(url, protocol)\n\n // --- Return a promise that resolves when the connection is opened.\n const promise = new Promise<void>((resolve, rejects) => {\n this.webSocket!.addEventListener('error', () => rejects(new Error('Failed to open the WebSocket connection')), { once: true })\n this.webSocket!.addEventListener('open', () => {\n if (this.options.initialPayload) this.send(this.options.initialPayload as ClientData<T>)\n resolve()\n }, { once: true })\n })\n\n // --- Add the options' hooks to the WebSocket connection.\n if (this.options.onOpen) this.on('open', this.options.onOpen, { once: true })\n if (this.options.onClose) this.on('close', this.options.onClose, { once: true })\n if (this.options.onError) this.on('error', this.options.onError)\n if (this.options.onMessage) this.on('message', message => this.options.onMessage!(message))\n\n // --- Handle reconnection when the connection is closed unexpectedly.\n this.webSocket.addEventListener('close', (event) => {\n if (event.code === 1000) return\n if (!this.options.autoReconnect) return\n if (this.options.reconnectLimit && event.wasClean) return\n setTimeout(() => void this.open(), this.options.reconnectDelay ?? 0)\n }, { once: true })\n\n return promise.then(() => this)\n }\n\n /**\n * Send a payload to the server. The payload will be serialized to JSON before sending.\n *\n * @param payload The data to send to the server.\n */\n send(payload: ClientData<T>) {\n if (!this.webSocket) throw new Error('WebSocket connection is not open')\n const json = JSON.stringify(payload)\n this.webSocket.send(json)\n }\n\n /**\n * Listen for events from the server. The event will be deserialized from JSON before calling the callback.\n *\n * @param event The event to listen for.\n * @param callback The callback to call when the event is received.\n * @returns A function to remove the event listener.\n */\n on(event: 'message', callback: (data: ServerData<T>) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: 'close', callback: (event: CloseEvent) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: 'error', callback: (event: Event) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: 'open', callback: (event: Event) => any, options?: AddEventListenerOptions): RemoveListener\n on(event: string, callback: (data: any) => any, options?: AddEventListenerOptions) {\n if (!this.webSocket) throw new Error('WebSocket connection has not been opened yet')\n\n const listener = async(event: CloseEvent | Event | MessageEvent<Blob>): Promise<void> => {\n if (event.type !== 'message') callback(event)\n // @ts-expect-error: `data` exists on the event.\n let data = event.data as unknown\n if (data instanceof Blob) data = await data.text()\n try { data = JSON.parse(data as string) }\n catch { console.error('Failed to parse the message:', data) }\n callback(data)\n }\n\n /* eslint-disable @typescript-eslint/no-misused-promises */\n this.webSocket.addEventListener(event, listener, options)\n return () => this.webSocket!.removeEventListener(event, listener)\n /* eslint-enable @typescript-eslint/no-misused-promises */\n }\n\n /**\n * Close the WebSocket connection to the server. The connection will not be able to send or receive\n * messages after it is closed.\n */\n async close() {\n if (!this.webSocket) throw new Error('WebSocket connection has not been opened yet')\n if (this.webSocket.readyState === WebSocket.CLOSED) return\n if (this.webSocket.readyState === WebSocket.CLOSING) return\n this.webSocket.close(1000, 'Client closed the connection')\n await new Promise<void>(resolve => this.webSocket!.addEventListener('close', () => resolve()))\n }\n}\n\n/**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param route The name of the route to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\nexport function connect(route: string, options: ConnectOptions): WebSocketChannel {\n return new WebSocketChannel(route, options)\n}\n"],"names":["parseRequestParameters","parseRequestQuery","event"],"mappings":";;AAKA,MAAM,yBAAyB,yEAGzB,YAAY,oBAAI,IAAI,CAAC,MAAM,KAAK,CAAC;AA+GvC,SAAS,gBAAgB,YAAiC,SAAiB,SAA+B;AACxG,QAAM,EAAE,SAAS,aAAa,SAGxB,QAAQ,uBAAuB,KAAK,OAAO;AACjD,MAAI,CAAC,OAAO,OAAQ,OAAM,IAAI,MAAM,iEAAiE;AACrG,QAAM,gBAAgB,YAAY,MAAM,OAAO,YAAY,MACrD,eAAe,WAAW,MAAM,OAAO;AAG7C,MAAI,CAAC,aAAc,OAAM,IAAI,MAAM,uEAAuE;AAG1G,QAAM,gBAAgB,cAAc,YAAA;AAEpC,MAAI,CADoB,UAAU,IAAI,aAAa,SACvB,IAAI,MAAM,+DAA+D,aAAa,gBAAgB;AAGlI,aAAW,MAAM,IAAI,IAAI,YAAY,GACrC,WAAW,IAAI,YAAY,WAAW,IAAI,SAAS,SAAS,GAAG,IAAI,MAAM,OAAO,KAAK,MAAM,CAAC,IAAI,MAAM,OAAO,MAC7G,WAAW,WAAW;AACxB;AAEO,SAAS,oBAAoB,SAAiB,SAA8C;AACjG,QAAM,EAAE,SAAS,UAAU,MAAM,aAAa,MAAM,QAAQ,KAAA,IAAS,SAC/D,eAAoC,EAAE,KAAK,IAAI,IAAI,aAAa,EAAA;AACtE,SAAA,gBAAgB,cAAc,SAAS,EAAE,SAAS,SAAA,CAAU,GAC5DA,kBAAAA,uBAAuB,cAAc,EAAE,WAAA,CAAY,GACnDC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2
- import { a as FetchMethod, R as RequestOptions } from './BGG3bT7O.js';
2
+ import { a as FetchMethod, R as RequestOptions } from './CNqEW-S3.js';
3
3
  import { OpenAPI } from 'openapi-types';
4
4
 
5
5
  /** Get the base URL of an OpenAPI specification. */
@@ -139,14 +139,15 @@ async function* createResponseStreamJsonIterator(response, options) {
139
139
  const parts = new TextDecoder().decode(value).trim().split("\0").filter(Boolean);
140
140
  for (const part of parts) {
141
141
  const payload = JSON.parse(part);
142
- onData && onData(payload), yield payload;
142
+ onData && await onData(payload, options), yield payload;
143
143
  }
144
144
  }
145
- onSuccess && onSuccess(response);
145
+ onSuccess && await onSuccess(response, options);
146
146
  } catch (error) {
147
- onError && onError(error);
147
+ if (onError) await onError(error, options);
148
+ else throw error;
148
149
  } finally {
149
- onEnd && onEnd(response);
150
+ onEnd && await onEnd(response, options);
150
151
  }
151
152
  }
152
153
  function handleResponseStreamJson(response, options) {
@@ -156,10 +157,24 @@ function handleResponseStreamJson(response, options) {
156
157
  async function* createResponseStreamSseIterator(response, options) {
157
158
  const { onError, onSuccess, onData, onEnd } = options;
158
159
  try {
160
+ let flush2 = function() {
161
+ if (bufferData === "") return;
162
+ bufferData.endsWith(`
163
+ `) && (bufferData = bufferData.slice(0, -1));
164
+ const sseEvent = {};
165
+ bufferEvent !== "" && (sseEvent.event = bufferEvent), bufferId !== "" && (sseEvent.id = bufferId), bufferRetry !== void 0 && (sseEvent.retry = bufferRetry);
166
+ try {
167
+ sseEvent.data = JSON.parse(bufferData);
168
+ } catch {
169
+ sseEvent.data = bufferData;
170
+ }
171
+ return bufferData = "", bufferEvent = "", bufferId = "", bufferRetry = void 0, sseEvent;
172
+ };
173
+ var flush = flush2;
159
174
  const body = response.body;
160
175
  if (body === null) throw new Error("Could not read the response body, it is empty.");
161
176
  const reader = body.getReader(), decoder = new TextDecoder();
162
- let buffer = "", dataBuffer = "", eventTypeBuffer = "", lastEventIdBuffer = "", retryBuffer;
177
+ let buffer = "", bufferData = "", bufferEvent = "", bufferId = "", bufferRetry;
163
178
  for (; ; ) {
164
179
  const { done, value } = await reader.read();
165
180
  if (done) break;
@@ -168,50 +183,24 @@ async function* createResponseStreamSseIterator(response, options) {
168
183
  buffer = lines.pop() ?? "";
169
184
  for (const line of lines) {
170
185
  if (line === "") {
171
- if (dataBuffer !== "") {
172
- dataBuffer.endsWith(`
173
- `) && (dataBuffer = dataBuffer.slice(0, -1));
174
- const sseEvent = { data: dataBuffer };
175
- eventTypeBuffer !== "" && (sseEvent.event = eventTypeBuffer), lastEventIdBuffer !== "" && (sseEvent.id = lastEventIdBuffer), retryBuffer !== void 0 && (sseEvent.retry = retryBuffer), onData && onData(sseEvent), yield sseEvent;
176
- }
177
- dataBuffer = "", eventTypeBuffer = "";
186
+ const event2 = flush2();
187
+ event2 && (yield event2), event2 && onData && await onData(event2, options);
178
188
  continue;
179
189
  }
180
190
  if (line.startsWith(":")) continue;
181
191
  const colonIndex = line.indexOf(":");
182
192
  let fieldName, fieldValue;
183
- switch (colonIndex === -1 ? (fieldName = line, fieldValue = "") : (fieldName = line.slice(0, colonIndex), fieldValue = line.slice(colonIndex + 1), fieldValue.startsWith(" ") && (fieldValue = fieldValue.slice(1))), fieldName) {
184
- case "event": {
185
- eventTypeBuffer = fieldValue;
186
- break;
187
- }
188
- case "data": {
189
- dataBuffer += `${fieldValue}
190
- `;
191
- break;
192
- }
193
- case "id": {
194
- fieldValue.includes("\0") || (lastEventIdBuffer = fieldValue);
195
- break;
196
- }
197
- case "retry": {
198
- /^\d+$/.test(fieldValue) && (retryBuffer = Number.parseInt(fieldValue, 10));
199
- break;
200
- }
201
- }
193
+ colonIndex === -1 ? (fieldName = line, fieldValue = "") : (fieldName = line.slice(0, colonIndex), fieldValue = line.slice(colonIndex + 1), fieldValue.startsWith(" ") && (fieldValue = fieldValue.slice(1))), fieldName === "event" ? bufferEvent = fieldValue : fieldName === "data" ? bufferData += `${fieldValue}
194
+ ` : fieldName === "id" ? fieldValue.includes("\0") || (bufferId = fieldValue) : fieldName === "retry" && /^\d+$/.test(fieldValue) && (bufferRetry = Number.parseInt(fieldValue, 10));
202
195
  }
203
196
  }
204
- if (dataBuffer !== "") {
205
- dataBuffer.endsWith(`
206
- `) && (dataBuffer = dataBuffer.slice(0, -1));
207
- const sseEvent = { data: dataBuffer };
208
- eventTypeBuffer !== "" && (sseEvent.event = eventTypeBuffer), lastEventIdBuffer !== "" && (sseEvent.id = lastEventIdBuffer), retryBuffer !== void 0 && (sseEvent.retry = retryBuffer), onData && onData(sseEvent), yield sseEvent;
209
- }
210
- onSuccess && onSuccess(response);
197
+ const event = flush2();
198
+ event && (yield event), event && onData && await onData(event, options), onSuccess && await onSuccess(response, options);
211
199
  } catch (error) {
212
- throw onError && onError(error), error;
200
+ if (onError) await onError(error, options);
201
+ else throw error;
213
202
  } finally {
214
- onEnd && onEnd(response);
203
+ onEnd && await onEnd(response, options);
215
204
  }
216
205
  }
217
206
  function handleResponseStreamSse(response, options) {
@@ -221,20 +210,22 @@ function handleResponseStreamSse(response, options) {
221
210
  async function handleResponse(response, options = {}) {
222
211
  const { onError, onSuccess, onData, onEnd, onFailure } = options, contentType = response.headers.get("Content-Type");
223
212
  if (!response.ok)
224
- throw onFailure && await onFailure(response), onEnd && onEnd(response), new Error(response.statusText);
213
+ throw onFailure && await onFailure(response, options), onEnd && await onEnd(response, options), new Error(response.statusText);
225
214
  if (response.status === 204) {
226
- onSuccess && onSuccess(response), onEnd && onEnd(response);
215
+ onSuccess && await onSuccess(response, options), onEnd && await onEnd(response, options);
227
216
  return;
228
217
  }
229
- return contentType?.startsWith("application/stream+json") ? handleResponseStreamJson(response, options) : contentType?.startsWith("text/event-stream") ? handleResponseStreamSse(response, options) : contentType?.startsWith("application/json") ? await response.json().then((data) => (onData && onData(data), onSuccess && onSuccess(response), data)).catch((error) => {
230
- throw onError && onError(error), error;
218
+ return contentType?.startsWith("application/stream+json") ? handleResponseStreamJson(response, options) : contentType?.startsWith("text/event-stream") ? handleResponseStreamSse(response, options) : contentType?.startsWith("application/json") ? await response.json().then(async (data) => (onData && await onData(data, options), onSuccess && await onSuccess(response, options), data)).catch(async (error) => {
219
+ if (onError) await onError(error, options);
220
+ else throw error;
231
221
  }).finally(() => {
232
- onEnd && onEnd(response);
233
- }) : contentType?.startsWith("text/") ? await response.text().then((data) => (onData && onData(data), onSuccess && onSuccess(response), data)).catch((error) => {
234
- throw onError && onError(error), error;
222
+ onEnd && onEnd(response, options);
223
+ }) : contentType?.startsWith("text/") ? await response.text().then(async (data) => (onData && await onData(data, options), onSuccess && await onSuccess(response, options), data)).catch(async (error) => {
224
+ if (onError) await onError(error, options);
225
+ else throw error;
235
226
  }).finally(() => {
236
- onEnd && onEnd(response);
237
- }) : (onSuccess && onSuccess(response), onEnd && onEnd(response), response.body);
227
+ onEnd && onEnd(response, options);
228
+ }) : (onSuccess && onSuccess(response, options), onEnd && onEnd(response, options), response.body);
238
229
  }
239
230
  export {
240
231
  getHeader as a,
@@ -254,4 +245,4 @@ export {
254
245
  setCookie as s,
255
246
  toFormData as t
256
247
  };
257
- //# sourceMappingURL=uqfvs89o.js.map
248
+ //# sourceMappingURL=DZ2MwV7J.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"uqfvs89o.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/handleResponseStreamSse.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","/* eslint-disable sonarjs/cognitive-complexity */\nimport type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\n/** SSE event data structure */\nexport interface SseEvent {\n\n /** The event type */\n event?: string\n\n /** The event data */\n data: string\n\n /** The event ID */\n id?: string\n\n /** The retry timeout in milliseconds */\n retry?: number\n}\n\nasync function * createResponseStreamSseIterator(response: Response, options: RequestOptions): AsyncGenerator<SseEvent, 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 const decoder = new TextDecoder()\n let buffer = ''\n\n // SSE parsing state buffers according to spec\n let dataBuffer = ''\n let eventTypeBuffer = ''\n let lastEventIdBuffer = ''\n let retryBuffer: number | undefined\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n\n // Split on all valid line endings: CRLF, LF, CR\n const lines = buffer.split(/\\r\\n|\\n|\\r/)\n\n // Keep the last incomplete line in the buffer\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n // Empty line dispatches the event\n if (line === '') {\n if (dataBuffer !== '') {\n // Remove final trailing newline from data buffer as per spec\n if (dataBuffer.endsWith('\\n'))\n dataBuffer = dataBuffer.slice(0, -1)\n\n const sseEvent: SseEvent = { data: dataBuffer }\n if (eventTypeBuffer !== '') sseEvent.event = eventTypeBuffer\n if (lastEventIdBuffer !== '') sseEvent.id = lastEventIdBuffer\n if (retryBuffer !== undefined) sseEvent.retry = retryBuffer\n\n if (onData) onData(sseEvent)\n yield sseEvent\n }\n\n // Reset buffers\n dataBuffer = ''\n eventTypeBuffer = ''\n // Note: lastEventIdBuffer and retryBuffer persist across events\n continue\n }\n\n // Skip comment lines (start with colon)\n if (line.startsWith(':')) continue\n\n // Parse field\n const colonIndex = line.indexOf(':')\n let fieldName: string\n let fieldValue: string\n\n if (colonIndex === -1) {\n // No colon means field name only, empty value\n fieldName = line\n fieldValue = ''\n }\n else {\n fieldName = line.slice(0, colonIndex)\n fieldValue = line.slice(colonIndex + 1)\n // Remove single leading space if present\n if (fieldValue.startsWith(' '))\n fieldValue = fieldValue.slice(1)\n\n }\n\n // Process field according to spec\n switch (fieldName) {\n case 'event': {\n eventTypeBuffer = fieldValue\n break\n }\n case 'data': {\n dataBuffer += `${fieldValue}\\n`\n break\n }\n case 'id': {\n if (!fieldValue.includes('\\0')) { // spec: id cannot contain null chars\n lastEventIdBuffer = fieldValue\n }\n break\n }\n case 'retry': {\n // Must be ASCII digits only\n if (/^\\d+$/.test(fieldValue))\n retryBuffer = Number.parseInt(fieldValue, 10)\n\n break\n }\n // Other fields are ignored per spec\n }\n }\n }\n\n // Handle any remaining event in buffer at end of stream\n if (dataBuffer !== '') {\n if (dataBuffer.endsWith('\\n'))\n dataBuffer = dataBuffer.slice(0, -1)\n\n const sseEvent: SseEvent = { data: dataBuffer }\n if (eventTypeBuffer !== '') sseEvent.event = eventTypeBuffer\n if (lastEventIdBuffer !== '') sseEvent.id = lastEventIdBuffer\n if (retryBuffer !== undefined) sseEvent.retry = retryBuffer\n\n if (onData) onData(sseEvent)\n yield sseEvent\n }\n\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n throw error\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a Server-Sent Events stream. This function\n * will parse the SSE events 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 SSE events.\n */\nexport function handleResponseStreamSse(response: Response, options: RequestOptions): Awaitable<AsyncIterable<SseEvent>, SseEvent[]> {\n const responseIterator = createResponseStreamSseIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\nimport { handleResponseStreamSse } from './handleResponseStreamSse'\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 application/stream+json, return an iterator that parses the JSON.\n if (contentType?.startsWith('application/stream+json'))\n return handleResponseStreamJson(response, options)\n\n // --- If the response is a text/event-stream, return an iterator that parses the SSE events.\n if (contentType?.startsWith('text/event-stream'))\n return handleResponseStreamSse(response, options)\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 text content type (but not event-stream), 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 // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n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AAI,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,KAID,aAAW,UAAU,QAAQ,GAC7B,SAAO,MAAM,QAAQ,GAClB,SAAS;AAClB;"}
1
+ {"version":3,"file":"DZ2MwV7J.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/handleResponseStreamSse.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) await onData(payload, options)\n yield payload\n }\n }\n if (onSuccess) await onSuccess(response, options)\n }\n catch (error) {\n if (onError) await onError(error as Error, options)\n else throw error\n }\n finally {\n if (onEnd) await onEnd(response, options)\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","/* eslint-disable sonarjs/cognitive-complexity */\nimport type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\n/** SSE event data structure */\nexport interface SseEvent<T = string> {\n\n /** The event type */\n event?: string\n\n /** The event data */\n data: T\n\n /** The event ID */\n id?: string\n\n /** The retry timeout in milliseconds */\n retry?: number\n}\n\nasync function * createResponseStreamSseIterator<T>(response: Response, options: RequestOptions): AsyncGenerator<SseEvent<T>, 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 const decoder = new TextDecoder()\n\n // SSE parsing state buffers according to spec\n let buffer = ''\n let bufferData = ''\n let bufferEvent = ''\n let bufferId = ''\n let bufferRetry: number | undefined\n\n function flush() {\n if (bufferData === '') return\n if (bufferData.endsWith('\\n')) bufferData = bufferData.slice(0, -1)\n const sseEvent = {} as SseEvent<unknown>\n\n // --- Set `event`, `id`, and `retry` fields if they are set\n if (bufferEvent !== '') sseEvent.event = bufferEvent\n if (bufferId !== '') sseEvent.id = bufferId\n if (bufferRetry !== undefined) sseEvent.retry = bufferRetry\n\n // --- Attempt to parse the `data` field as JSON if it looks like an object\n try { sseEvent.data = JSON.parse(bufferData) as object }\n catch { sseEvent.data = bufferData }\n\n // --- Reset buffers for the next event\n bufferData = ''\n bufferEvent = ''\n bufferId = ''\n bufferRetry = undefined\n\n return sseEvent as SseEvent<T>\n }\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n // --- Split on all valid line endings: CRLF, LF, CR\n // --- Additionally, keep the last incomplete line in the buffer\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split(/\\r\\n|\\n|\\r/)\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n\n // --- Empty line dispatches the event.\n if (line === '') {\n const event = flush()\n if (event) yield event\n if (event && onData) await onData(event, options)\n continue\n }\n\n // --- Skip comment lines (start with colon)\n if (line.startsWith(':')) continue\n\n // --- Parse field name and value by finding the first colon.\n const colonIndex = line.indexOf(':')\n let fieldName: string\n let fieldValue: string\n\n // --- No colon means field name only, empty value\n if (colonIndex === -1) {\n fieldName = line\n fieldValue = ''\n }\n else {\n fieldName = line.slice(0, colonIndex)\n fieldValue = line.slice(colonIndex + 1)\n if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1)\n }\n\n // --- Extract event type, data, id, and retry fields according to spec\n // --- Note that id must not contain null characters and retry must be a valid number.\n if (fieldName === 'event') {\n bufferEvent = fieldValue\n }\n else if (fieldName === 'data') {\n bufferData += `${fieldValue}\\n`\n }\n else if (fieldName === 'id') {\n if (!fieldValue.includes('\\0'))\n bufferId = fieldValue\n }\n else if (fieldName === 'retry' && /^\\d+$/.test(fieldValue)) {\n bufferRetry = Number.parseInt(fieldValue, 10)\n }\n }\n }\n\n // --- Handle any remaining event in buffer at end of stream\n const event = flush()\n if (event) yield event\n if (event && onData) await onData(event, options)\n if (onSuccess) await onSuccess(response, options)\n }\n catch (error) {\n if (onError) await onError(error as Error, options)\n else throw error\n }\n finally {\n if (onEnd) await onEnd(response, options)\n }\n}\n\n/**\n * Handle a request response where the content type is a Server-Sent Events stream. This function\n * will parse the SSE events 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 SSE events.\n */\nexport function handleResponseStreamSse<T>(response: Response, options: RequestOptions): Awaitable<AsyncIterable<SseEvent<T>>, Array<SseEvent<T>>> {\n const responseIterator = createResponseStreamSseIterator<T>(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\nimport { handleResponseStreamSse } from './handleResponseStreamSse'\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, options)\n if (onEnd) await onEnd(response, options)\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) await onSuccess(response, options)\n if (onEnd) await onEnd(response, options)\n return\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 // --- If the response is a text/event-stream, return an iterator that parses the SSE events.\n if (contentType?.startsWith('text/event-stream'))\n return handleResponseStreamSse(response, options)\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(async(data) => {\n if (onData) await onData(data, options)\n if (onSuccess) await onSuccess(response, options)\n return data as unknown\n })\n .catch(async(error: Error) => {\n if (onError) await onError(error, options)\n else throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response, options)\n })\n }\n\n // --- If the response is a text content type (but not event-stream), return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then(async(data) => {\n if (onData) await onData(data, options)\n if (onSuccess) await onSuccess(response, options)\n return data\n })\n .catch(async(error: Error) => {\n if (onError) await onError(error, options)\n else throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response, options)\n })\n }\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response, options)\n if (onEnd) onEnd(response, options)\n return response.body\n}\n"],"names":["value","key","flush","event"],"mappings":";;AASO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACEO,SAAS,UAAU,SAAsB,KAAa,OAA8B;AAEzF,MADA,QAAQ,OAAO,KAAK,GAChB,mBAAmB;AACrB,YAAQ,IAAI,KAAK,KAAK;AAAA,WAEf,MAAM,QAAQ,OAAO,GAAG;AAC/B,UAAM,WAAW,IAAI,YAAA,GACf,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,EAC9B,WACS,OAAO,W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aAAW,MAAM,UAAU,UAAU,OAAO,GAC5C,SAAO,MAAM,MAAM,UAAU,OAAO,GAClC,IAAI,MAAM,SAAS,UAAU;AAIrC,MAAI,SAAS,WAAW,KAAK;AACvB,iBAAW,MAAM,UAAU,UAAU,OAAO,GAC5C,SAAO,MAAM,MAAM,UAAU,OAAO;AACxC;AAAA,EACF;AAGA,SAAI,aAAa,WAAW,yBAAyB,IAC5C,yBAAyB,UAAU,OAAO,IAG/C,aAAa,WAAW,mBAAmB,IACtC,wBAAwB,UAAU,OAAO,IAG9C,aAAa,WAAW,kBAAkB,IACrC,MAAM,SAAS,KAAA,EACnB,KAAK,OAAM,UACN,UAAQ,MAAM,OAAO,MAAM,OAAO,GAClC,aAAW,MAAM,UAAU,UAAU,OAAO,GACzC,KACR,EACA,MAAM,OAAM,UAAiB;AAC5B,QAAI,QAAS,OAAM,QAAQ,OAAO,OAAO;AAAA,QACpC,OAAM;AAAA,EACb,CAAC,EACA,QAAQ,MAAM;AACT,aAAO,MAAM,UAAU,OAAO;AAAA,EACpC,CAAC,IAID,aAAa,WAAW,OAAO,IAC1B,MAAM,SAAS,OACnB,KAAK,OAAM,UACN,UAAQ,MAAM,OAAO,MAAM,OAAO,GAClC,aAAW,MAAM,UAAU,UAAU,OAAO,GACzC,KACR,EACA,MAAM,OAAM,UAAiB;AAC5B,QAAI,QAAS,OAAM,QAAQ,OAAO,OAAO;AAAA,QACpC,OAAM;AAAA,EACb,CAAC,EACA,QAAQ,MAAM;AACT,aAAO,MAAM,UAAU,OAAO;AAAA,EACpC,CAAC,KAID,aAAW,UAAU,UAAU,OAAO,GACtC,SAAO,MAAM,UAAU,OAAO,GAC3B,SAAS;AAClB;"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
- var attempt = require("@unshared/functions/attempt"), request = require("./chunks/CQUndCW0.cjs"), connect = require("./chunks/DJyo3R5b.cjs");
3
- require("./chunks/CThSMMCZ.cjs");
2
+ var attempt = require("@unshared/functions/attempt"), request = require("./chunks/CNNxr5Ws.cjs"), connect = require("./chunks/DJyo3R5b.cjs");
3
+ require("./chunks/-InYnohy.cjs");
4
4
  require("./chunks/BDxlAULu.cjs");
5
5
  require("@unshared/functions/awaitable");
6
6
  class Client {