@happy-ts/fetch-t 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +132 -0
- package/LICENSE +21 -674
- package/README.cn.md +135 -47
- package/README.md +133 -50
- package/dist/main.cjs +37 -23
- package/dist/main.cjs.map +1 -1
- package/dist/main.mjs +33 -21
- package/dist/main.mjs.map +1 -1
- package/dist/types.d.ts +432 -207
- package/package.json +37 -23
- package/dist/types.d.ts.map +0 -1
- package/docs/README.md +0 -39
- package/docs/classes/FetchError.md +0 -49
- package/docs/functions/fetchT.md +0 -403
- package/docs/interfaces/FetchInit.md +0 -25
- package/docs/interfaces/FetchProgress.md +0 -18
- package/docs/interfaces/FetchTask.md +0 -46
- package/docs/type-aliases/FetchResponse.md +0 -22
- package/docs/type-aliases/FetchResponseType.md +0 -15
- package/docs/variables/ABORT_ERROR.md +0 -15
- package/docs/variables/TIMEOUT_ERROR.md +0 -15
- package/src/fetch/constants.ts +0 -9
- package/src/fetch/defines.ts +0 -104
- package/src/fetch/fetch.ts +0 -292
- package/src/mod.ts +0 -3
package/dist/main.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.cjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Name of abort error;\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Name of timeout error;\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Represents the response of a fetch operation, encapsulating the result data or any error that occurred.\n *\n * @typeParam T - The type of the data expected in the response.\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Defines the structure and behavior of a fetch task, including the ability to abort the task and check its status.\n *\n * @typeParam T - The type of the data expected in the response.\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason for the abortion.\n *\n * @param reason - An optional parameter to indicate why the task was aborted.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n */\n readonly aborted: boolean;\n\n /**\n * The response of the fetch task, represented as an `AsyncResult`.\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type of the fetch request.\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json';\n\n/**\n * Represents the progress of a fetch operation.\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received.\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Extends the standard `RequestInit` interface from the Fetch API to include additional custom options.\n */\nexport interface FetchInit extends RequestInit {\n /**\n * Indicates whether the fetch request should be abortable.\n */\n abortable?: boolean;\n\n /**\n * Specifies the expected response type of the fetch request.\n */\n responseType?: FetchResponseType;\n\n /**\n * Specifies the maximum time in milliseconds to wait for the fetch request to complete.\n */\n timeout?: number;\n\n /**\n * Specifies a function to be called when the fetch request makes progress.\n * @param progressResult - The progress of the fetch request.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Specifies a function to be called when the fetch request receives a chunk of data.\n * @param chunk - The chunk of data received.\n */\n onChunk?: (chunk: Uint8Array) => void;\n}\n\n/**\n * Represents an error that occurred during a fetch operation when the response is not ok.\n */\nexport class FetchError extends Error {\n /**\n * The name of the error.\n */\n override name = 'FetchError';\n /**\n * The status code of the response.\n */\n status = 0;\n\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}","import { Err, Ok } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { TIMEOUT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchTask } from './defines.ts';\n\n/**\n * Fetches a resource from the network as a text string and returns a `FetchTask` representing the operation.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns a `FetchTask` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns a `FetchTask` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning a `FetchTask` representing the operation.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with a response parsed as JSON.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T>;\n\n/**\n * Fetches a resource from the network as a text string and returns a `FetchResponse` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'text'.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns a `FetchResponse` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'arraybuffer'.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob and returns a `FetchResponse` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'blob'.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning a `FetchResponse` representing the operation.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'json'.\n * @returns A `FetchResponse` representing the operation with a response parsed as JSON.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n responseType: 'json';\n}): FetchResponse<T, Error>;\n\n/**\n * Fetches a resource from the network and returns a `FetchTask` representing the operation with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, indicating that the operation should be abortable.\n * @returns A `FetchTask` representing the operation with a generic `Response`.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` or `FetchTask` based on the provided options.\n *\n * @typeParam T - The expected type of the response data when not using a specific `responseType`.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;\n\n/**\n * Fetches a resource from the network and returns either a `FetchTask` or `FetchResponse` based on the provided options.\n *\n * @typeParam T - The expected type of the response data when not using a specific `responseType`.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` or `FetchResponse` depending on the provided options in `init`.\n */\nexport function fetchT<T>(url: string | URL, init?: FetchInit): FetchTask<T> | FetchResponse<T> {\n // most cases\n if (typeof url !== 'string') {\n invariant(url instanceof URL, () => `Url must be a string or URL object but received ${ url }.`);\n }\n\n const {\n // default not abort able\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = init ?? {};\n\n const shouldWaitTimeout = timeout != null;\n let cancelTimer: (() => void) | null;\n\n if (shouldWaitTimeout) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `Timeout must be a number greater than 0 but received ${ timeout }.`);\n }\n\n let controller: AbortController;\n\n if (abortable || shouldWaitTimeout) {\n controller = new AbortController();\n rest.signal = controller.signal;\n }\n\n const response: FetchResponse<T> = fetch(url, rest).then(async (res): FetchResponse<T> => {\n cancelTimer?.();\n\n if (!res.ok) {\n await res.body?.cancel();\n return Err(new FetchError(res.statusText, res.status));\n }\n\n if (res.body) {\n // should notify progress or data chunk?\n const shouldNotifyProgress = typeof onProgress === 'function';\n const shouldNotifyChunk = typeof onChunk === 'function';\n\n if ((shouldNotifyProgress || shouldNotifyChunk)) {\n // tee the original stream to two streams, one for notify progress, another for response\n const [stream1, stream2] = res.body.tee();\n\n const reader = stream1.getReader();\n // may has no content-length\n let totalByteLength: number | null = null;\n let completedByteLength = 0;\n\n if (shouldNotifyProgress) {\n // try to get content-length\n // compatible with http/2\n const contentLength = res.headers.get('content-length') ?? res.headers.get('Content-Length');\n if (contentLength == null) {\n // response headers has no content-length\n onProgress(Err(new Error('No content-length in response headers.')));\n } else {\n totalByteLength = parseInt(contentLength, 10);\n }\n }\n\n reader.read().then(function notify({ done, value }) {\n if (done) {\n return;\n }\n\n // notify chunk\n if (shouldNotifyChunk) {\n onChunk(value);\n }\n\n // notify progress\n if (shouldNotifyProgress && totalByteLength != null) {\n completedByteLength += value.byteLength;\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n }\n\n\n // continue to read\n reader.read().then(notify);\n });\n\n // replace the original response with the new one\n res = new Response(stream2, {\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n });\n }\n }\n\n switch (responseType) {\n case 'arraybuffer': {\n return Ok(await res.arrayBuffer() as T);\n }\n case 'blob': {\n return Ok(await res.blob() as T);\n }\n case 'json': {\n try {\n return Ok(await res.json() as T);\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await res.text() as T);\n }\n default: {\n // default return the Response object\n return Ok(res as T);\n }\n }\n }).catch((err) => {\n cancelTimer?.();\n\n return Err(err);\n });\n\n if (shouldWaitTimeout) {\n const timer = setTimeout(() => {\n if (!controller.signal.aborted) {\n const error = new Error();\n error.name = TIMEOUT_ERROR;\n controller.abort(error);\n }\n }, timeout);\n\n cancelTimer = (): void => {\n if (timer) {\n clearTimeout(timer);\n }\n\n cancelTimer = null;\n };\n }\n\n if (abortable) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n cancelTimer?.();\n controller.abort(reason);\n },\n\n get aborted(): boolean {\n return controller.signal.aborted;\n },\n\n get response(): FetchResponse<T> {\n return response;\n },\n };\n } else {\n return response;\n }\n}"],"names":["Err","Ok"],"mappings":";;;;;AAGO,MAAM,WAAA,GAAc;AAKpB,MAAM,aAAA,GAAgB;;ACiFtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAIhB,MAAA,GAAS,CAAA;AAAA,EAET,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AC0BO,SAA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,GAAG,OAAO,CAAA;AAEV,IAAA,WAAA,GAAc,MAAY;AACtB,MAAA,IAAI,KAAA,EAAO;AACP,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACtB;AAEA,MAAA,WAAA,GAAc,IAAA;AAAA,IAClB,CAAA;AAAA,EACJ;AAEA,EAAA,IAAI,SAAA,EAAW;AACX,IAAA,OAAO;AAAA;AAAA,MAEH,MAAM,MAAA,EAAoB;AACtB,QAAA,WAAA,IAAc;AACd,QAAA,UAAA,CAAW,MAAM,MAAM,CAAA;AAAA,MAC3B,CAAA;AAAA,MAEA,IAAI,OAAA,GAAmB;AACnB,QAAA,OAAO,WAAW,MAAA,CAAO,OAAA;AAAA,MAC7B,CAAA;AAAA,MAEA,IAAI,QAAA,GAA6B;AAC7B,QAAA,OAAO,QAAA;AAAA,MACX;AAAA,KACJ;AAAA,EACJ,CAAA,MAAO;AACH,IAAA,OAAO,QAAA;AAAA,EACX;AACJ;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"main.cjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Error name for aborted fetch requests.\n *\n * This matches the standard `AbortError` name used by the Fetch API when a request\n * is cancelled via `AbortController.abort()`.\n *\n * @example\n * ```typescript\n * import { fetchT, ABORT_ERROR } from '@happy-ts/fetch-t';\n *\n * const task = fetchT('https://api.example.com/data', { abortable: true });\n * task.abort();\n *\n * const result = await task.response;\n * result.inspectErr((err) => {\n * if (err.name === ABORT_ERROR) {\n * console.log('Request was aborted');\n * }\n * });\n * ```\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Error name for timed out fetch requests.\n *\n * This is set on the `Error.name` property when a request exceeds the specified\n * `timeout` duration and is automatically aborted.\n *\n * @example\n * ```typescript\n * import { fetchT, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/slow-endpoint', {\n * timeout: 5000, // 5 seconds\n * });\n *\n * result.inspectErr((err) => {\n * if (err.name === TIMEOUT_ERROR) {\n * console.log('Request timed out after 5 seconds');\n * }\n * });\n * ```\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Represents the response of a fetch operation as an async Result type.\n *\n * This is an alias for `AsyncResult<T, E>` from the `happy-rusty` library,\n * providing Rust-like error handling without throwing exceptions.\n *\n * @typeParam T - The type of the data expected in a successful response.\n * @typeParam E - The type of the error (defaults to `any`). Typically `Error` or `FetchError`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponse } from '@happy-ts/fetch-t';\n *\n * // FetchResponse is a Promise that resolves to Result<T, E>\n * const response: FetchResponse<string> = fetchT('https://api.example.com', {\n * responseType: 'text',\n * });\n *\n * const result = await response;\n * result\n * .inspect((text) => console.log('Success:', text))\n * .inspectErr((err) => console.error('Error:', err));\n * ```\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Represents an abortable fetch operation with control methods.\n *\n * Returned when `abortable: true` is set in the fetch options. Provides\n * the ability to cancel the request and check its abort status.\n *\n * @typeParam T - The type of the data expected in the response.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchTask } from '@happy-ts/fetch-t';\n *\n * interface User {\n * id: number;\n * name: string;\n * }\n *\n * const task: FetchTask<User> = fetchT<User>('https://api.example.com/user/1', {\n * abortable: true,\n * responseType: 'json',\n * });\n *\n * // Check if aborted\n * console.log('Is aborted:', task.aborted); // false\n *\n * // Abort with optional reason\n * task.abort('User navigated away');\n *\n * // Access the response (will be an error after abort)\n * const result = await task.response;\n * result.inspectErr((err) => console.log('Aborted:', err.message));\n * ```\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason.\n *\n * Once aborted, the `response` promise will resolve to an `Err` containing\n * an `AbortError`. The abort reason can be any value and will be passed\n * to the underlying `AbortController.abort()`.\n *\n * @param reason - An optional value indicating why the task was aborted.\n * This can be an Error, string, or any other value.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n *\n * Returns `true` if `abort()` was called or if the request timed out.\n */\n readonly aborted: boolean;\n\n /**\n * The response promise of the fetch task.\n *\n * Resolves to `Ok<T>` on success, or `Err<Error>` on failure (including abort).\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type for automatic parsing.\n *\n * - `'text'` - Parse response as string via `Response.text()`\n * - `'json'` - Parse response as JSON via `Response.json()`\n * - `'arraybuffer'` - Parse response as ArrayBuffer via `Response.arrayBuffer()`\n * - `'blob'` - Parse response as Blob via `Response.blob()`\n *\n * If not specified, the raw `Response` object is returned.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseType } from '@happy-ts/fetch-t';\n *\n * const responseType: FetchResponseType = 'json';\n *\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * ```\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json';\n\n/**\n * Represents the download progress of a fetch operation.\n *\n * Passed to the `onProgress` callback when tracking download progress.\n * Note: Progress tracking requires the server to send a `Content-Length` header.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchProgress } from '@happy-ts/fetch-t';\n *\n * await fetchT('https://example.com/file.zip', {\n * responseType: 'blob',\n * onProgress: (result) => {\n * result.inspect((progress: FetchProgress) => {\n * const percent = (progress.completedByteLength / progress.totalByteLength) * 100;\n * console.log(`Downloaded: ${percent.toFixed(1)}%`);\n * });\n * },\n * });\n * ```\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received (from Content-Length header).\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Extended fetch options that add additional capabilities to the standard `RequestInit`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchInit } from '@happy-ts/fetch-t';\n *\n * const options: FetchInit = {\n * // Standard RequestInit options\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ key: 'value' }),\n *\n * // Extended options\n * abortable: true, // Return FetchTask for manual abort control\n * responseType: 'json', // Auto-parse response as JSON\n * timeout: 10000, // Abort after 10 seconds\n * onProgress: (result) => { // Track download progress\n * result.inspect(({ completedByteLength, totalByteLength }) => {\n * console.log(`${completedByteLength}/${totalByteLength}`);\n * });\n * },\n * onChunk: (chunk) => { // Receive raw data chunks\n * console.log('Received chunk:', chunk.byteLength, 'bytes');\n * },\n * };\n *\n * const task = fetchT('https://api.example.com/upload', options);\n * ```\n */\nexport interface FetchInit extends RequestInit {\n /**\n * When `true`, returns a `FetchTask` instead of `FetchResponse`.\n *\n * The `FetchTask` provides `abort()` method and `aborted` status.\n *\n * @default false\n */\n abortable?: boolean;\n\n /**\n * Specifies how the response body should be parsed.\n *\n * - `'text'` - Returns `string`\n * - `'json'` - Returns parsed JSON (type `T`)\n * - `'arraybuffer'` - Returns `ArrayBuffer`\n * - `'blob'` - Returns `Blob`\n * - `undefined` - Returns raw `Response` object\n */\n responseType?: FetchResponseType;\n\n /**\n * Maximum time in milliseconds to wait for the request to complete.\n *\n * If exceeded, the request is automatically aborted with a `TimeoutError`.\n * Must be a positive number.\n */\n timeout?: number;\n\n /**\n * Callback invoked during download to report progress.\n *\n * Receives an `IOResult<FetchProgress>`:\n * - `Ok(FetchProgress)` - Progress update with byte counts\n * - `Err(Error)` - If `Content-Length` header is missing (called once)\n *\n * @param progressResult - The progress result, either success with progress data or error.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Callback invoked when a chunk of data is received.\n *\n * Useful for streaming or processing data as it arrives.\n * Each chunk is a `Uint8Array` containing the raw bytes.\n *\n * @param chunk - The raw data chunk received from the response stream.\n */\n onChunk?: (chunk: Uint8Array) => void;\n}\n\n/**\n * Custom error class for HTTP error responses (non-2xx status codes).\n *\n * Thrown when `Response.ok` is `false`. Contains the HTTP status code\n * for programmatic error handling.\n *\n * @example\n * ```typescript\n * import { fetchT, FetchError } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/not-found', {\n * responseType: 'json',\n * });\n *\n * result.inspectErr((err) => {\n * if (err instanceof FetchError) {\n * console.log('HTTP Status:', err.status); // e.g., 404\n * console.log('Status Text:', err.message); // e.g., \"Not Found\"\n *\n * // Handle specific status codes\n * switch (err.status) {\n * case 401:\n * console.log('Unauthorized - please login');\n * break;\n * case 404:\n * console.log('Resource not found');\n * break;\n * case 500:\n * console.log('Server error');\n * break;\n * }\n * }\n * });\n * ```\n */\nexport class FetchError extends Error {\n /**\n * The error name, always `'FetchError'`.\n */\n override name = 'FetchError';\n\n /**\n * The HTTP status code of the response (e.g., 404, 500).\n */\n status = 0;\n\n /**\n * Creates a new FetchError instance.\n *\n * @param message - The status text from the HTTP response (e.g., \"Not Found\").\n * @param status - The HTTP status code (e.g., 404).\n */\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n","import { Err, Ok } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { TIMEOUT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchTask } from './defines.ts';\n\n/**\n * Fetches a resource from the network as a text string and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'text'`.\n * @returns A `FetchTask` representing the abortable operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'arraybuffer'`.\n * @returns A `FetchTask` representing the abortable operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'blob'`.\n * @returns A `FetchTask` representing the abortable operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning an abortable `FetchTask`.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'json'`.\n * @returns A `FetchTask` representing the abortable operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T>;\n\n/**\n * Fetches a resource from the network as a text string.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'text'`.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'`.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'blob'`.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'json'`.\n * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n responseType: 'json';\n}): FetchResponse<T, Error>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true`.\n * @returns A `FetchTask` representing the abortable operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Optional additional options for the fetch operation.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;\n\n/**\n * Enhanced fetch function that wraps the native Fetch API with additional capabilities.\n *\n * Features:\n * - **Abortable requests**: Set `abortable: true` to get a `FetchTask` with `abort()` method.\n * - **Type-safe responses**: Use `responseType` to automatically parse responses as text, JSON, ArrayBuffer, or Blob.\n * - **Timeout support**: Set `timeout` in milliseconds to auto-abort long-running requests.\n * - **Progress tracking**: Use `onProgress` callback to track download progress (requires Content-Length header).\n * - **Chunk streaming**: Use `onChunk` callback to receive raw data chunks as they arrive.\n * - **Result type error handling**: Returns `Result<T, Error>` instead of throwing exceptions.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, extending standard `RequestInit` with custom properties.\n * @returns A `FetchTask<T>` if `abortable: true`, otherwise a `FetchResponse<T>` (which is `AsyncResult<T, Error>`).\n * @throws {Error} If `url` is not a string or URL object.\n * @throws {Error} If `timeout` is specified but is not a positive number.\n *\n * @example\n * // Basic GET request - returns Response object wrapped in Result\n * const result = await fetchT('https://api.example.com/data');\n * result\n * .inspect((res) => console.log('Status:', res.status))\n * .inspectErr((err) => console.error('Error:', err));\n *\n * @example\n * // GET JSON with type safety\n * interface User {\n * id: number;\n * name: string;\n * }\n * const result = await fetchT<User>('https://api.example.com/user/1', {\n * responseType: 'json',\n * });\n * result.inspect((user) => console.log(user.name));\n *\n * @example\n * // POST request with JSON body\n * const result = await fetchT<User>('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'John' }),\n * responseType: 'json',\n * });\n *\n * @example\n * // Abortable request with timeout\n * const task = fetchT('https://api.example.com/data', {\n * abortable: true,\n * timeout: 5000, // 5 seconds\n * });\n *\n * // Cancel the request if needed\n * task.abort('User cancelled');\n *\n * // Check if aborted\n * console.log('Aborted:', task.aborted);\n *\n * // Wait for response\n * const result = await task.response;\n *\n * @example\n * // Track download progress\n * const result = await fetchT('https://example.com/large-file.zip', {\n * responseType: 'blob',\n * onProgress: (progressResult) => {\n * progressResult\n * .inspect(({ completedByteLength, totalByteLength }) => {\n * const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);\n * console.log(`Progress: ${percent}%`);\n * })\n * .inspectErr((err) => console.warn('Progress unavailable:', err.message));\n * },\n * });\n *\n * @example\n * // Stream data chunks\n * const chunks: Uint8Array[] = [];\n * const result = await fetchT('https://example.com/stream', {\n * onChunk: (chunk) => chunks.push(chunk),\n * });\n */\nexport function fetchT<T>(url: string | URL, init?: FetchInit): FetchTask<T> | FetchResponse<T> {\n // Fast path: most URLs are passed as strings\n if (typeof url !== 'string') {\n invariant(url instanceof URL, () => `Url must be a string or URL object but received ${ url }.`);\n }\n\n const {\n // default not abortable\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = init ?? {};\n\n const shouldWaitTimeout = timeout != null;\n let cancelTimer: (() => void) | null;\n\n if (shouldWaitTimeout) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `Timeout must be a number greater than 0 but received ${ timeout }.`);\n }\n\n let controller: AbortController;\n\n if (abortable || shouldWaitTimeout) {\n controller = new AbortController();\n rest.signal = controller.signal;\n }\n\n const response: FetchResponse<T> = fetch(url, rest).then(async (res): FetchResponse<T> => {\n cancelTimer?.();\n\n if (!res.ok) {\n await res.body?.cancel();\n return Err(new FetchError(res.statusText, res.status));\n }\n\n if (res.body) {\n // should notify progress or data chunk?\n const shouldNotifyProgress = typeof onProgress === 'function';\n const shouldNotifyChunk = typeof onChunk === 'function';\n\n if ((shouldNotifyProgress || shouldNotifyChunk)) {\n // tee the original stream to two streams, one for notify progress, another for response\n const [stream1, stream2] = res.body.tee();\n\n const reader = stream1.getReader();\n // Content-Length may not be present in response headers\n let totalByteLength: number | null = null;\n let completedByteLength = 0;\n\n if (shouldNotifyProgress) {\n // Headers.get() is case-insensitive per spec\n const contentLength = res.headers.get('content-length');\n if (contentLength == null) {\n // response headers has no content-length\n try {\n onProgress(Err(new Error('No content-length in response headers.')));\n } catch {\n // Silently ignore user callback errors\n }\n } else {\n totalByteLength = parseInt(contentLength, 10);\n }\n }\n\n reader.read().then(function notify({ done, value }) {\n if (done) {\n return;\n }\n\n // notify chunk\n if (shouldNotifyChunk) {\n try {\n onChunk(value);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n // notify progress\n if (shouldNotifyProgress && totalByteLength != null) {\n completedByteLength += value.byteLength;\n try {\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n // Continue reading the stream\n reader.read().then(notify).catch(() => {\n // Silently ignore stream read errors (will be handled by main response)\n });\n }).catch(() => {\n // Silently ignore initial stream read errors (will be handled by main response)\n });\n\n // replace the original response with the new one\n res = new Response(stream2, {\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n });\n }\n }\n\n switch (responseType) {\n case 'arraybuffer': {\n return Ok(await res.arrayBuffer() as T);\n }\n case 'blob': {\n return Ok(await res.blob() as T);\n }\n case 'json': {\n try {\n return Ok(await res.json() as T);\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await res.text() as T);\n }\n default: {\n // default return the Response object\n return Ok(res as T);\n }\n }\n }).catch((err) => {\n cancelTimer?.();\n\n return Err(err);\n });\n\n if (shouldWaitTimeout) {\n const timer = setTimeout(() => {\n const error = new Error();\n error.name = TIMEOUT_ERROR;\n controller.abort(error);\n }, timeout);\n\n cancelTimer = (): void => {\n clearTimeout(timer);\n cancelTimer = null;\n };\n }\n\n if (abortable) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n cancelTimer?.();\n controller.abort(reason);\n },\n\n get aborted(): boolean {\n return controller.signal.aborted;\n },\n\n get response(): FetchResponse<T> {\n return response;\n },\n };\n }\n\n return response;\n}"],"names":["Err","Ok"],"mappings":";;;;;;;AAqBO,MAAM,WAAA,GAAc;AAuBpB,MAAM,aAAA,GAAgB;;ACwNtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAKhB,MAAA,GAAS,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AChFO,SAAS,MAAA,CAAU,KAAmB,IAAA,EAAmD;AAE5F,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AACzB,IAAA,SAAA,CAAU,GAAA,YAAe,GAAA,EAAK,MAAM,CAAA,gDAAA,EAAoD,GAAI,CAAA,CAAA,CAAG,CAAA;AAAA,EACnG;AAEA,EAAA,MAAM;AAAA;AAAA,IAEF,SAAA,GAAY,KAAA;AAAA,IACZ,YAAA;AAA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AA,EACJ;AAEA,EAAA,IAAI,SAAA,EAAW;AACX,IAAA,OAAO;AAAA;AAAA,MAEH,MAAM,MAAA,EAAoB;AACtB,QAAA,WAAA,IAAc;AACd,QAAA,UAAA,CAAW,MAAM,MAAM,CAAA;AAAA,MAC3B,CAAA;AAAA,MAEA,IAAI,OAAA,GAAmB;AACnB,QAAA,OAAO,WAAW,MAAA,CAAO,OAAA;AAAA,MAC7B,CAAA;AAAA,MAEA,IAAI,QAAA,GAA6B;AAC7B,QAAA,OAAO,QAAA;AAAA,MACX;AAAA,KACJ;AAAA,EACJ;AAEA,EAAA,OAAO,QAAA;AACX;;;;;;;"}
|
package/dist/main.mjs
CHANGED
|
@@ -6,13 +6,19 @@ const TIMEOUT_ERROR = "TimeoutError";
|
|
|
6
6
|
|
|
7
7
|
class FetchError extends Error {
|
|
8
8
|
/**
|
|
9
|
-
* The name
|
|
9
|
+
* The error name, always `'FetchError'`.
|
|
10
10
|
*/
|
|
11
11
|
name = "FetchError";
|
|
12
12
|
/**
|
|
13
|
-
* The status code of the response.
|
|
13
|
+
* The HTTP status code of the response (e.g., 404, 500).
|
|
14
14
|
*/
|
|
15
15
|
status = 0;
|
|
16
|
+
/**
|
|
17
|
+
* Creates a new FetchError instance.
|
|
18
|
+
*
|
|
19
|
+
* @param message - The status text from the HTTP response (e.g., "Not Found").
|
|
20
|
+
* @param status - The HTTP status code (e.g., 404).
|
|
21
|
+
*/
|
|
16
22
|
constructor(message, status) {
|
|
17
23
|
super(message);
|
|
18
24
|
this.status = status;
|
|
@@ -24,7 +30,7 @@ function fetchT(url, init) {
|
|
|
24
30
|
invariant(url instanceof URL, () => `Url must be a string or URL object but received ${url}.`);
|
|
25
31
|
}
|
|
26
32
|
const {
|
|
27
|
-
// default not
|
|
33
|
+
// default not abortable
|
|
28
34
|
abortable = false,
|
|
29
35
|
responseType,
|
|
30
36
|
timeout,
|
|
@@ -57,9 +63,12 @@ function fetchT(url, init) {
|
|
|
57
63
|
let totalByteLength = null;
|
|
58
64
|
let completedByteLength = 0;
|
|
59
65
|
if (shouldNotifyProgress) {
|
|
60
|
-
const contentLength = res.headers.get("content-length")
|
|
66
|
+
const contentLength = res.headers.get("content-length");
|
|
61
67
|
if (contentLength == null) {
|
|
62
|
-
|
|
68
|
+
try {
|
|
69
|
+
onProgress(Err(new Error("No content-length in response headers.")));
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
63
72
|
} else {
|
|
64
73
|
totalByteLength = parseInt(contentLength, 10);
|
|
65
74
|
}
|
|
@@ -69,16 +78,24 @@ function fetchT(url, init) {
|
|
|
69
78
|
return;
|
|
70
79
|
}
|
|
71
80
|
if (shouldNotifyChunk) {
|
|
72
|
-
|
|
81
|
+
try {
|
|
82
|
+
onChunk(value);
|
|
83
|
+
} catch {
|
|
84
|
+
}
|
|
73
85
|
}
|
|
74
86
|
if (shouldNotifyProgress && totalByteLength != null) {
|
|
75
87
|
completedByteLength += value.byteLength;
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
88
|
+
try {
|
|
89
|
+
onProgress(Ok({
|
|
90
|
+
totalByteLength,
|
|
91
|
+
completedByteLength
|
|
92
|
+
}));
|
|
93
|
+
} catch {
|
|
94
|
+
}
|
|
80
95
|
}
|
|
81
|
-
reader.read().then(notify)
|
|
96
|
+
reader.read().then(notify).catch(() => {
|
|
97
|
+
});
|
|
98
|
+
}).catch(() => {
|
|
82
99
|
});
|
|
83
100
|
res = new Response(stream2, {
|
|
84
101
|
headers: res.headers,
|
|
@@ -114,16 +131,12 @@ function fetchT(url, init) {
|
|
|
114
131
|
});
|
|
115
132
|
if (shouldWaitTimeout) {
|
|
116
133
|
const timer = setTimeout(() => {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
controller.abort(error);
|
|
121
|
-
}
|
|
134
|
+
const error = new Error();
|
|
135
|
+
error.name = TIMEOUT_ERROR;
|
|
136
|
+
controller.abort(error);
|
|
122
137
|
}, timeout);
|
|
123
138
|
cancelTimer = () => {
|
|
124
|
-
|
|
125
|
-
clearTimeout(timer);
|
|
126
|
-
}
|
|
139
|
+
clearTimeout(timer);
|
|
127
140
|
cancelTimer = null;
|
|
128
141
|
};
|
|
129
142
|
}
|
|
@@ -141,9 +154,8 @@ function fetchT(url, init) {
|
|
|
141
154
|
return response;
|
|
142
155
|
}
|
|
143
156
|
};
|
|
144
|
-
} else {
|
|
145
|
-
return response;
|
|
146
157
|
}
|
|
158
|
+
return response;
|
|
147
159
|
}
|
|
148
160
|
|
|
149
161
|
export { ABORT_ERROR, FetchError, TIMEOUT_ERROR, fetchT };
|
package/dist/main.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.mjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Name of abort error;\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Name of timeout error;\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Represents the response of a fetch operation, encapsulating the result data or any error that occurred.\n *\n * @typeParam T - The type of the data expected in the response.\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Defines the structure and behavior of a fetch task, including the ability to abort the task and check its status.\n *\n * @typeParam T - The type of the data expected in the response.\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason for the abortion.\n *\n * @param reason - An optional parameter to indicate why the task was aborted.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n */\n readonly aborted: boolean;\n\n /**\n * The response of the fetch task, represented as an `AsyncResult`.\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type of the fetch request.\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json';\n\n/**\n * Represents the progress of a fetch operation.\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received.\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Extends the standard `RequestInit` interface from the Fetch API to include additional custom options.\n */\nexport interface FetchInit extends RequestInit {\n /**\n * Indicates whether the fetch request should be abortable.\n */\n abortable?: boolean;\n\n /**\n * Specifies the expected response type of the fetch request.\n */\n responseType?: FetchResponseType;\n\n /**\n * Specifies the maximum time in milliseconds to wait for the fetch request to complete.\n */\n timeout?: number;\n\n /**\n * Specifies a function to be called when the fetch request makes progress.\n * @param progressResult - The progress of the fetch request.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Specifies a function to be called when the fetch request receives a chunk of data.\n * @param chunk - The chunk of data received.\n */\n onChunk?: (chunk: Uint8Array) => void;\n}\n\n/**\n * Represents an error that occurred during a fetch operation when the response is not ok.\n */\nexport class FetchError extends Error {\n /**\n * The name of the error.\n */\n override name = 'FetchError';\n /**\n * The status code of the response.\n */\n status = 0;\n\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}","import { Err, Ok } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { TIMEOUT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchTask } from './defines.ts';\n\n/**\n * Fetches a resource from the network as a text string and returns a `FetchTask` representing the operation.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns a `FetchTask` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns a `FetchTask` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning a `FetchTask` representing the operation.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` representing the operation with a response parsed as JSON.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T>;\n\n/**\n * Fetches a resource from the network as a text string and returns a `FetchResponse` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'text'.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns a `FetchResponse` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'arraybuffer'.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob and returns a `FetchResponse` representing the operation.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'blob'.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning a `FetchResponse` representing the operation.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, specifying the response type as 'json'.\n * @returns A `FetchResponse` representing the operation with a response parsed as JSON.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n responseType: 'json';\n}): FetchResponse<T, Error>;\n\n/**\n * Fetches a resource from the network and returns a `FetchTask` representing the operation with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, indicating that the operation should be abortable.\n * @returns A `FetchTask` representing the operation with a generic `Response`.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` or `FetchTask` based on the provided options.\n *\n * @typeParam T - The expected type of the response data when not using a specific `responseType`.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;\n\n/**\n * Fetches a resource from the network and returns either a `FetchTask` or `FetchResponse` based on the provided options.\n *\n * @typeParam T - The expected type of the response data when not using a specific `responseType`.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, including custom `FetchInit` properties.\n * @returns A `FetchTask` or `FetchResponse` depending on the provided options in `init`.\n */\nexport function fetchT<T>(url: string | URL, init?: FetchInit): FetchTask<T> | FetchResponse<T> {\n // most cases\n if (typeof url !== 'string') {\n invariant(url instanceof URL, () => `Url must be a string or URL object but received ${ url }.`);\n }\n\n const {\n // default not abort able\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = init ?? {};\n\n const shouldWaitTimeout = timeout != null;\n let cancelTimer: (() => void) | null;\n\n if (shouldWaitTimeout) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `Timeout must be a number greater than 0 but received ${ timeout }.`);\n }\n\n let controller: AbortController;\n\n if (abortable || shouldWaitTimeout) {\n controller = new AbortController();\n rest.signal = controller.signal;\n }\n\n const response: FetchResponse<T> = fetch(url, rest).then(async (res): FetchResponse<T> => {\n cancelTimer?.();\n\n if (!res.ok) {\n await res.body?.cancel();\n return Err(new FetchError(res.statusText, res.status));\n }\n\n if (res.body) {\n // should notify progress or data chunk?\n const shouldNotifyProgress = typeof onProgress === 'function';\n const shouldNotifyChunk = typeof onChunk === 'function';\n\n if ((shouldNotifyProgress || shouldNotifyChunk)) {\n // tee the original stream to two streams, one for notify progress, another for response\n const [stream1, stream2] = res.body.tee();\n\n const reader = stream1.getReader();\n // may has no content-length\n let totalByteLength: number | null = null;\n let completedByteLength = 0;\n\n if (shouldNotifyProgress) {\n // try to get content-length\n // compatible with http/2\n const contentLength = res.headers.get('content-length') ?? res.headers.get('Content-Length');\n if (contentLength == null) {\n // response headers has no content-length\n onProgress(Err(new Error('No content-length in response headers.')));\n } else {\n totalByteLength = parseInt(contentLength, 10);\n }\n }\n\n reader.read().then(function notify({ done, value }) {\n if (done) {\n return;\n }\n\n // notify chunk\n if (shouldNotifyChunk) {\n onChunk(value);\n }\n\n // notify progress\n if (shouldNotifyProgress && totalByteLength != null) {\n completedByteLength += value.byteLength;\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n }\n\n\n // continue to read\n reader.read().then(notify);\n });\n\n // replace the original response with the new one\n res = new Response(stream2, {\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n });\n }\n }\n\n switch (responseType) {\n case 'arraybuffer': {\n return Ok(await res.arrayBuffer() as T);\n }\n case 'blob': {\n return Ok(await res.blob() as T);\n }\n case 'json': {\n try {\n return Ok(await res.json() as T);\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await res.text() as T);\n }\n default: {\n // default return the Response object\n return Ok(res as T);\n }\n }\n }).catch((err) => {\n cancelTimer?.();\n\n return Err(err);\n });\n\n if (shouldWaitTimeout) {\n const timer = setTimeout(() => {\n if (!controller.signal.aborted) {\n const error = new Error();\n error.name = TIMEOUT_ERROR;\n controller.abort(error);\n }\n }, timeout);\n\n cancelTimer = (): void => {\n if (timer) {\n clearTimeout(timer);\n }\n\n cancelTimer = null;\n };\n }\n\n if (abortable) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n cancelTimer?.();\n controller.abort(reason);\n },\n\n get aborted(): boolean {\n return controller.signal.aborted;\n },\n\n get response(): FetchResponse<T> {\n return response;\n },\n };\n } else {\n return response;\n }\n}"],"names":[],"mappings":";;;AAGO,MAAM,WAAA,GAAc;AAKpB,MAAM,aAAA,GAAgB;;ACiFtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAIhB,MAAA,GAAS,CAAA;AAAA,EAET,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AC0BO,SAAS,MAAA,CAAU,KAAmB,IAAA,EAAmD;AAE5F,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AACzB,IAAA,SAAA,CAAU,GAAA,YAAe,GAAA,EAAK,MAAM,CAAA,gDAAA,EAAoD,GAAI,CAAA,CAAA,CAAG,CAAA;AAAA,EACnG;AAEA,EAAA,MAAM;AAAA;AAAA,IAEF,SAAA,GAAY,KAAA;AAAA,IACZ,YAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,GAAG;AA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AAA;AAAA,MAEA,IAAI,OAAA,GAAmB;AACnB,QAAA,OAAO,WAAW,MAAA,CAAO,OAAA;AAAA,MAC7B,CAAA;AAAA,MAEA,IAAI,QAAA,GAA6B;AAC7B,QAAA,OAAO,QAAA;AAAA,MACX;AAAA,KACJ;AAAA,EACJ,CAAA,MAAO;AACH,IAAA,OAAO,QAAA;AAAA,EACX;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"main.mjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Error name for aborted fetch requests.\n *\n * This matches the standard `AbortError` name used by the Fetch API when a request\n * is cancelled via `AbortController.abort()`.\n *\n * @example\n * ```typescript\n * import { fetchT, ABORT_ERROR } from '@happy-ts/fetch-t';\n *\n * const task = fetchT('https://api.example.com/data', { abortable: true });\n * task.abort();\n *\n * const result = await task.response;\n * result.inspectErr((err) => {\n * if (err.name === ABORT_ERROR) {\n * console.log('Request was aborted');\n * }\n * });\n * ```\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Error name for timed out fetch requests.\n *\n * This is set on the `Error.name` property when a request exceeds the specified\n * `timeout` duration and is automatically aborted.\n *\n * @example\n * ```typescript\n * import { fetchT, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/slow-endpoint', {\n * timeout: 5000, // 5 seconds\n * });\n *\n * result.inspectErr((err) => {\n * if (err.name === TIMEOUT_ERROR) {\n * console.log('Request timed out after 5 seconds');\n * }\n * });\n * ```\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Represents the response of a fetch operation as an async Result type.\n *\n * This is an alias for `AsyncResult<T, E>` from the `happy-rusty` library,\n * providing Rust-like error handling without throwing exceptions.\n *\n * @typeParam T - The type of the data expected in a successful response.\n * @typeParam E - The type of the error (defaults to `any`). Typically `Error` or `FetchError`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponse } from '@happy-ts/fetch-t';\n *\n * // FetchResponse is a Promise that resolves to Result<T, E>\n * const response: FetchResponse<string> = fetchT('https://api.example.com', {\n * responseType: 'text',\n * });\n *\n * const result = await response;\n * result\n * .inspect((text) => console.log('Success:', text))\n * .inspectErr((err) => console.error('Error:', err));\n * ```\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Represents an abortable fetch operation with control methods.\n *\n * Returned when `abortable: true` is set in the fetch options. Provides\n * the ability to cancel the request and check its abort status.\n *\n * @typeParam T - The type of the data expected in the response.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchTask } from '@happy-ts/fetch-t';\n *\n * interface User {\n * id: number;\n * name: string;\n * }\n *\n * const task: FetchTask<User> = fetchT<User>('https://api.example.com/user/1', {\n * abortable: true,\n * responseType: 'json',\n * });\n *\n * // Check if aborted\n * console.log('Is aborted:', task.aborted); // false\n *\n * // Abort with optional reason\n * task.abort('User navigated away');\n *\n * // Access the response (will be an error after abort)\n * const result = await task.response;\n * result.inspectErr((err) => console.log('Aborted:', err.message));\n * ```\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason.\n *\n * Once aborted, the `response` promise will resolve to an `Err` containing\n * an `AbortError`. The abort reason can be any value and will be passed\n * to the underlying `AbortController.abort()`.\n *\n * @param reason - An optional value indicating why the task was aborted.\n * This can be an Error, string, or any other value.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n *\n * Returns `true` if `abort()` was called or if the request timed out.\n */\n readonly aborted: boolean;\n\n /**\n * The response promise of the fetch task.\n *\n * Resolves to `Ok<T>` on success, or `Err<Error>` on failure (including abort).\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type for automatic parsing.\n *\n * - `'text'` - Parse response as string via `Response.text()`\n * - `'json'` - Parse response as JSON via `Response.json()`\n * - `'arraybuffer'` - Parse response as ArrayBuffer via `Response.arrayBuffer()`\n * - `'blob'` - Parse response as Blob via `Response.blob()`\n *\n * If not specified, the raw `Response` object is returned.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseType } from '@happy-ts/fetch-t';\n *\n * const responseType: FetchResponseType = 'json';\n *\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * ```\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json';\n\n/**\n * Represents the download progress of a fetch operation.\n *\n * Passed to the `onProgress` callback when tracking download progress.\n * Note: Progress tracking requires the server to send a `Content-Length` header.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchProgress } from '@happy-ts/fetch-t';\n *\n * await fetchT('https://example.com/file.zip', {\n * responseType: 'blob',\n * onProgress: (result) => {\n * result.inspect((progress: FetchProgress) => {\n * const percent = (progress.completedByteLength / progress.totalByteLength) * 100;\n * console.log(`Downloaded: ${percent.toFixed(1)}%`);\n * });\n * },\n * });\n * ```\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received (from Content-Length header).\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Extended fetch options that add additional capabilities to the standard `RequestInit`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchInit } from '@happy-ts/fetch-t';\n *\n * const options: FetchInit = {\n * // Standard RequestInit options\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ key: 'value' }),\n *\n * // Extended options\n * abortable: true, // Return FetchTask for manual abort control\n * responseType: 'json', // Auto-parse response as JSON\n * timeout: 10000, // Abort after 10 seconds\n * onProgress: (result) => { // Track download progress\n * result.inspect(({ completedByteLength, totalByteLength }) => {\n * console.log(`${completedByteLength}/${totalByteLength}`);\n * });\n * },\n * onChunk: (chunk) => { // Receive raw data chunks\n * console.log('Received chunk:', chunk.byteLength, 'bytes');\n * },\n * };\n *\n * const task = fetchT('https://api.example.com/upload', options);\n * ```\n */\nexport interface FetchInit extends RequestInit {\n /**\n * When `true`, returns a `FetchTask` instead of `FetchResponse`.\n *\n * The `FetchTask` provides `abort()` method and `aborted` status.\n *\n * @default false\n */\n abortable?: boolean;\n\n /**\n * Specifies how the response body should be parsed.\n *\n * - `'text'` - Returns `string`\n * - `'json'` - Returns parsed JSON (type `T`)\n * - `'arraybuffer'` - Returns `ArrayBuffer`\n * - `'blob'` - Returns `Blob`\n * - `undefined` - Returns raw `Response` object\n */\n responseType?: FetchResponseType;\n\n /**\n * Maximum time in milliseconds to wait for the request to complete.\n *\n * If exceeded, the request is automatically aborted with a `TimeoutError`.\n * Must be a positive number.\n */\n timeout?: number;\n\n /**\n * Callback invoked during download to report progress.\n *\n * Receives an `IOResult<FetchProgress>`:\n * - `Ok(FetchProgress)` - Progress update with byte counts\n * - `Err(Error)` - If `Content-Length` header is missing (called once)\n *\n * @param progressResult - The progress result, either success with progress data or error.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Callback invoked when a chunk of data is received.\n *\n * Useful for streaming or processing data as it arrives.\n * Each chunk is a `Uint8Array` containing the raw bytes.\n *\n * @param chunk - The raw data chunk received from the response stream.\n */\n onChunk?: (chunk: Uint8Array) => void;\n}\n\n/**\n * Custom error class for HTTP error responses (non-2xx status codes).\n *\n * Thrown when `Response.ok` is `false`. Contains the HTTP status code\n * for programmatic error handling.\n *\n * @example\n * ```typescript\n * import { fetchT, FetchError } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/not-found', {\n * responseType: 'json',\n * });\n *\n * result.inspectErr((err) => {\n * if (err instanceof FetchError) {\n * console.log('HTTP Status:', err.status); // e.g., 404\n * console.log('Status Text:', err.message); // e.g., \"Not Found\"\n *\n * // Handle specific status codes\n * switch (err.status) {\n * case 401:\n * console.log('Unauthorized - please login');\n * break;\n * case 404:\n * console.log('Resource not found');\n * break;\n * case 500:\n * console.log('Server error');\n * break;\n * }\n * }\n * });\n * ```\n */\nexport class FetchError extends Error {\n /**\n * The error name, always `'FetchError'`.\n */\n override name = 'FetchError';\n\n /**\n * The HTTP status code of the response (e.g., 404, 500).\n */\n status = 0;\n\n /**\n * Creates a new FetchError instance.\n *\n * @param message - The status text from the HTTP response (e.g., \"Not Found\").\n * @param status - The HTTP status code (e.g., 404).\n */\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n","import { Err, Ok } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { TIMEOUT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchTask } from './defines.ts';\n\n/**\n * Fetches a resource from the network as a text string and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'text'`.\n * @returns A `FetchTask` representing the abortable operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'arraybuffer'`.\n * @returns A `FetchTask` representing the abortable operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'blob'`.\n * @returns A `FetchTask` representing the abortable operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning an abortable `FetchTask`.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'json'`.\n * @returns A `FetchTask` representing the abortable operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T>;\n\n/**\n * Fetches a resource from the network as a text string.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'text'`.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'`.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'blob'`.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'json'`.\n * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n responseType: 'json';\n}): FetchResponse<T, Error>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true`.\n * @returns A `FetchTask` representing the abortable operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Optional additional options for the fetch operation.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;\n\n/**\n * Enhanced fetch function that wraps the native Fetch API with additional capabilities.\n *\n * Features:\n * - **Abortable requests**: Set `abortable: true` to get a `FetchTask` with `abort()` method.\n * - **Type-safe responses**: Use `responseType` to automatically parse responses as text, JSON, ArrayBuffer, or Blob.\n * - **Timeout support**: Set `timeout` in milliseconds to auto-abort long-running requests.\n * - **Progress tracking**: Use `onProgress` callback to track download progress (requires Content-Length header).\n * - **Chunk streaming**: Use `onChunk` callback to receive raw data chunks as they arrive.\n * - **Result type error handling**: Returns `Result<T, Error>` instead of throwing exceptions.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, extending standard `RequestInit` with custom properties.\n * @returns A `FetchTask<T>` if `abortable: true`, otherwise a `FetchResponse<T>` (which is `AsyncResult<T, Error>`).\n * @throws {Error} If `url` is not a string or URL object.\n * @throws {Error} If `timeout` is specified but is not a positive number.\n *\n * @example\n * // Basic GET request - returns Response object wrapped in Result\n * const result = await fetchT('https://api.example.com/data');\n * result\n * .inspect((res) => console.log('Status:', res.status))\n * .inspectErr((err) => console.error('Error:', err));\n *\n * @example\n * // GET JSON with type safety\n * interface User {\n * id: number;\n * name: string;\n * }\n * const result = await fetchT<User>('https://api.example.com/user/1', {\n * responseType: 'json',\n * });\n * result.inspect((user) => console.log(user.name));\n *\n * @example\n * // POST request with JSON body\n * const result = await fetchT<User>('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'John' }),\n * responseType: 'json',\n * });\n *\n * @example\n * // Abortable request with timeout\n * const task = fetchT('https://api.example.com/data', {\n * abortable: true,\n * timeout: 5000, // 5 seconds\n * });\n *\n * // Cancel the request if needed\n * task.abort('User cancelled');\n *\n * // Check if aborted\n * console.log('Aborted:', task.aborted);\n *\n * // Wait for response\n * const result = await task.response;\n *\n * @example\n * // Track download progress\n * const result = await fetchT('https://example.com/large-file.zip', {\n * responseType: 'blob',\n * onProgress: (progressResult) => {\n * progressResult\n * .inspect(({ completedByteLength, totalByteLength }) => {\n * const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);\n * console.log(`Progress: ${percent}%`);\n * })\n * .inspectErr((err) => console.warn('Progress unavailable:', err.message));\n * },\n * });\n *\n * @example\n * // Stream data chunks\n * const chunks: Uint8Array[] = [];\n * const result = await fetchT('https://example.com/stream', {\n * onChunk: (chunk) => chunks.push(chunk),\n * });\n */\nexport function fetchT<T>(url: string | URL, init?: FetchInit): FetchTask<T> | FetchResponse<T> {\n // Fast path: most URLs are passed as strings\n if (typeof url !== 'string') {\n invariant(url instanceof URL, () => `Url must be a string or URL object but received ${ url }.`);\n }\n\n const {\n // default not abortable\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = init ?? {};\n\n const shouldWaitTimeout = timeout != null;\n let cancelTimer: (() => void) | null;\n\n if (shouldWaitTimeout) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `Timeout must be a number greater than 0 but received ${ timeout }.`);\n }\n\n let controller: AbortController;\n\n if (abortable || shouldWaitTimeout) {\n controller = new AbortController();\n rest.signal = controller.signal;\n }\n\n const response: FetchResponse<T> = fetch(url, rest).then(async (res): FetchResponse<T> => {\n cancelTimer?.();\n\n if (!res.ok) {\n await res.body?.cancel();\n return Err(new FetchError(res.statusText, res.status));\n }\n\n if (res.body) {\n // should notify progress or data chunk?\n const shouldNotifyProgress = typeof onProgress === 'function';\n const shouldNotifyChunk = typeof onChunk === 'function';\n\n if ((shouldNotifyProgress || shouldNotifyChunk)) {\n // tee the original stream to two streams, one for notify progress, another for response\n const [stream1, stream2] = res.body.tee();\n\n const reader = stream1.getReader();\n // Content-Length may not be present in response headers\n let totalByteLength: number | null = null;\n let completedByteLength = 0;\n\n if (shouldNotifyProgress) {\n // Headers.get() is case-insensitive per spec\n const contentLength = res.headers.get('content-length');\n if (contentLength == null) {\n // response headers has no content-length\n try {\n onProgress(Err(new Error('No content-length in response headers.')));\n } catch {\n // Silently ignore user callback errors\n }\n } else {\n totalByteLength = parseInt(contentLength, 10);\n }\n }\n\n reader.read().then(function notify({ done, value }) {\n if (done) {\n return;\n }\n\n // notify chunk\n if (shouldNotifyChunk) {\n try {\n onChunk(value);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n // notify progress\n if (shouldNotifyProgress && totalByteLength != null) {\n completedByteLength += value.byteLength;\n try {\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n // Continue reading the stream\n reader.read().then(notify).catch(() => {\n // Silently ignore stream read errors (will be handled by main response)\n });\n }).catch(() => {\n // Silently ignore initial stream read errors (will be handled by main response)\n });\n\n // replace the original response with the new one\n res = new Response(stream2, {\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n });\n }\n }\n\n switch (responseType) {\n case 'arraybuffer': {\n return Ok(await res.arrayBuffer() as T);\n }\n case 'blob': {\n return Ok(await res.blob() as T);\n }\n case 'json': {\n try {\n return Ok(await res.json() as T);\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await res.text() as T);\n }\n default: {\n // default return the Response object\n return Ok(res as T);\n }\n }\n }).catch((err) => {\n cancelTimer?.();\n\n return Err(err);\n });\n\n if (shouldWaitTimeout) {\n const timer = setTimeout(() => {\n const error = new Error();\n error.name = TIMEOUT_ERROR;\n controller.abort(error);\n }, timeout);\n\n cancelTimer = (): void => {\n clearTimeout(timer);\n cancelTimer = null;\n };\n }\n\n if (abortable) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n cancelTimer?.();\n controller.abort(reason);\n },\n\n get aborted(): boolean {\n return controller.signal.aborted;\n },\n\n get response(): FetchResponse<T> {\n return response;\n },\n };\n }\n\n return response;\n}"],"names":[],"mappings":";;;AAqBO,MAAM,WAAA,GAAc;AAuBpB,MAAM,aAAA,GAAgB;;ACwNtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAKhB,MAAA,GAAS,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AChFO,SAAS,MAAA,CAAU,KAAmB,IAAA,EAAmD;AAE5F,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AACzB,IAAA,SAAA,CAAU,GAAA,YAAe,GAAA,EAAK,MAAM,CAAA,gDAAA,EAAoD,GAAI,CAAA,CAAA,CAAG,CAAA;AAAA,EACnG;AAEA,EAAA,MAAM;AAAA;AAAA,IAEF,SAAA,GAAY,KAAA;AAAA,IACZ,YAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,GAAG;AAAA,GACP,GAAI,QAAQ,EAAC;AAEb,EAAA,MAAM,oBAAoB,OAAA,IAAW,IAAA;AACrC,EAAA,IAAI,WAAA;AAEJ,EAAA,IAAI,iBAAA,EAAmB;AACnB,IAAA,SAAA,CAAU,OAAO,YAAY,QAAA,IAAY,OAAA,GAAU,GAAG,MAAM,CAAA,qDAAA,EAAyD,OAAQ,CAAA,CAAA,CAAG,CAAA;AAAA,EACpI;AAEA,EAAA,IAAI,UAAA;AAEJ,EAA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