fetch.d.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /**
  2. * An environment's implementation of ``getUrl`` must return this type.
  3. */
  4. export type GetUrlResponse = {
  5. statusCode: number;
  6. statusMessage: string;
  7. headers: Record<string, string>;
  8. body: null | Uint8Array;
  9. };
  10. /**
  11. * This can be used to control how throttling is handled in
  12. * [[FetchRequest-setThrottleParams]].
  13. */
  14. export type FetchThrottleParams = {
  15. maxAttempts?: number;
  16. slotInterval?: number;
  17. };
  18. /**
  19. * Called before any network request, allowing updated headers (e.g. Bearer tokens), etc.
  20. */
  21. export type FetchPreflightFunc = (req: FetchRequest) => Promise<FetchRequest>;
  22. /**
  23. * Called on the response, allowing client-based throttling logic or post-processing.
  24. */
  25. export type FetchProcessFunc = (req: FetchRequest, resp: FetchResponse) => Promise<FetchResponse>;
  26. /**
  27. * Called prior to each retry; return true to retry, false to abort.
  28. */
  29. export type FetchRetryFunc = (req: FetchRequest, resp: FetchResponse, attempt: number) => Promise<boolean>;
  30. /**
  31. * Called on Gateway URLs.
  32. */
  33. export type FetchGatewayFunc = (url: string, signal?: FetchCancelSignal) => Promise<FetchRequest | FetchResponse>;
  34. /**
  35. * Used to perform a fetch; use this to override the underlying network
  36. * fetch layer. In NodeJS, the default uses the "http" and "https" libraries
  37. * and in the browser ``fetch`` is used. If you wish to use Axios, this is
  38. * how you would register it.
  39. */
  40. export type FetchGetUrlFunc = (req: FetchRequest, signal?: FetchCancelSignal) => Promise<GetUrlResponse>;
  41. /**
  42. * @_ignore
  43. */
  44. export declare class FetchCancelSignal {
  45. #private;
  46. constructor(request: FetchRequest);
  47. addListener(listener: () => void): void;
  48. get cancelled(): boolean;
  49. checkSignal(): void;
  50. }
  51. /**
  52. * Represents a request for a resource using a URI.
  53. *
  54. * By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``,
  55. * and ``IPFS:``.
  56. *
  57. * Additional schemes can be added globally using [[registerGateway]].
  58. *
  59. * @example:
  60. * req = new FetchRequest("https://www.ricmoo.com")
  61. * resp = await req.send()
  62. * resp.body.length
  63. * //_result:
  64. */
  65. export declare class FetchRequest implements Iterable<[key: string, value: string]> {
  66. #private;
  67. /**
  68. * The fetch URL to request.
  69. */
  70. get url(): string;
  71. set url(url: string);
  72. /**
  73. * The fetch body, if any, to send as the request body. //(default: null)//
  74. *
  75. * When setting a body, the intrinsic ``Content-Type`` is automatically
  76. * set and will be used if **not overridden** by setting a custom
  77. * header.
  78. *
  79. * If %%body%% is null, the body is cleared (along with the
  80. * intrinsic ``Content-Type``).
  81. *
  82. * If %%body%% is a string, the intrinsic ``Content-Type`` is set to
  83. * ``text/plain``.
  84. *
  85. * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to
  86. * ``application/octet-stream``.
  87. *
  88. * If %%body%% is any other object, the intrinsic ``Content-Type`` is
  89. * set to ``application/json``.
  90. */
  91. get body(): null | Uint8Array;
  92. set body(body: null | string | Readonly<object> | Readonly<Uint8Array>);
  93. /**
  94. * Returns true if the request has a body.
  95. */
  96. hasBody(): this is (FetchRequest & {
  97. body: Uint8Array;
  98. });
  99. /**
  100. * The HTTP method to use when requesting the URI. If no method
  101. * has been explicitly set, then ``GET`` is used if the body is
  102. * null and ``POST`` otherwise.
  103. */
  104. get method(): string;
  105. set method(method: null | string);
  106. /**
  107. * The headers that will be used when requesting the URI. All
  108. * keys are lower-case.
  109. *
  110. * This object is a copy, so any changes will **NOT** be reflected
  111. * in the ``FetchRequest``.
  112. *
  113. * To set a header entry, use the ``setHeader`` method.
  114. */
  115. get headers(): Record<string, string>;
  116. /**
  117. * Get the header for %%key%%, ignoring case.
  118. */
  119. getHeader(key: string): string;
  120. /**
  121. * Set the header for %%key%% to %%value%%. All values are coerced
  122. * to a string.
  123. */
  124. setHeader(key: string, value: string | number): void;
  125. /**
  126. * Clear all headers, resetting all intrinsic headers.
  127. */
  128. clearHeaders(): void;
  129. [Symbol.iterator](): Iterator<[key: string, value: string]>;
  130. /**
  131. * The value that will be sent for the ``Authorization`` header.
  132. *
  133. * To set the credentials, use the ``setCredentials`` method.
  134. */
  135. get credentials(): null | string;
  136. /**
  137. * Sets an ``Authorization`` for %%username%% with %%password%%.
  138. */
  139. setCredentials(username: string, password: string): void;
  140. /**
  141. * Enable and request gzip-encoded responses. The response will
  142. * automatically be decompressed. //(default: true)//
  143. */
  144. get allowGzip(): boolean;
  145. set allowGzip(value: boolean);
  146. /**
  147. * Allow ``Authentication`` credentials to be sent over insecure
  148. * channels. //(default: false)//
  149. */
  150. get allowInsecureAuthentication(): boolean;
  151. set allowInsecureAuthentication(value: boolean);
  152. /**
  153. * The timeout (in milliseconds) to wait for a complete response.
  154. * //(default: 5 minutes)//
  155. */
  156. get timeout(): number;
  157. set timeout(timeout: number);
  158. /**
  159. * This function is called prior to each request, for example
  160. * during a redirection or retry in case of server throttling.
  161. *
  162. * This offers an opportunity to populate headers or update
  163. * content before sending a request.
  164. */
  165. get preflightFunc(): null | FetchPreflightFunc;
  166. set preflightFunc(preflight: null | FetchPreflightFunc);
  167. /**
  168. * This function is called after each response, offering an
  169. * opportunity to provide client-level throttling or updating
  170. * response data.
  171. *
  172. * Any error thrown in this causes the ``send()`` to throw.
  173. *
  174. * To schedule a retry attempt (assuming the maximum retry limit
  175. * has not been reached), use [[response.throwThrottleError]].
  176. */
  177. get processFunc(): null | FetchProcessFunc;
  178. set processFunc(process: null | FetchProcessFunc);
  179. /**
  180. * This function is called on each retry attempt.
  181. */
  182. get retryFunc(): null | FetchRetryFunc;
  183. set retryFunc(retry: null | FetchRetryFunc);
  184. /**
  185. * This function is called to fetch content from HTTP and
  186. * HTTPS URLs and is platform specific (e.g. nodejs vs
  187. * browsers).
  188. *
  189. * This is by default the currently registered global getUrl
  190. * function, which can be changed using [[registerGetUrl]].
  191. * If this has been set, setting is to ``null`` will cause
  192. * this FetchRequest (and any future clones) to revert back to
  193. * using the currently registered global getUrl function.
  194. *
  195. * Setting this is generally not necessary, but may be useful
  196. * for developers that wish to intercept requests or to
  197. * configurege a proxy or other agent.
  198. */
  199. get getUrlFunc(): FetchGetUrlFunc;
  200. set getUrlFunc(value: null | FetchGetUrlFunc);
  201. /**
  202. * Create a new FetchRequest instance with default values.
  203. *
  204. * Once created, each property may be set before issuing a
  205. * ``.send()`` to make the request.
  206. */
  207. constructor(url: string);
  208. toString(): string;
  209. /**
  210. * Update the throttle parameters used to determine maximum
  211. * attempts and exponential-backoff properties.
  212. */
  213. setThrottleParams(params: FetchThrottleParams): void;
  214. /**
  215. * Resolves to the response by sending the request.
  216. */
  217. send(): Promise<FetchResponse>;
  218. /**
  219. * Cancels the inflight response, causing a ``CANCELLED``
  220. * error to be rejected from the [[send]].
  221. */
  222. cancel(): void;
  223. /**
  224. * Returns a new [[FetchRequest]] that represents the redirection
  225. * to %%location%%.
  226. */
  227. redirect(location: string): FetchRequest;
  228. /**
  229. * Create a new copy of this request.
  230. */
  231. clone(): FetchRequest;
  232. /**
  233. * Locks all static configuration for gateways and FetchGetUrlFunc
  234. * registration.
  235. */
  236. static lockConfig(): void;
  237. /**
  238. * Get the current Gateway function for %%scheme%%.
  239. */
  240. static getGateway(scheme: string): null | FetchGatewayFunc;
  241. /**
  242. * Use the %%func%% when fetching URIs using %%scheme%%.
  243. *
  244. * This method affects all requests globally.
  245. *
  246. * If [[lockConfig]] has been called, no change is made and this
  247. * throws.
  248. */
  249. static registerGateway(scheme: string, func: FetchGatewayFunc): void;
  250. /**
  251. * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.
  252. *
  253. * This method affects all requests globally.
  254. *
  255. * If [[lockConfig]] has been called, no change is made and this
  256. * throws.
  257. */
  258. static registerGetUrl(getUrl: FetchGetUrlFunc): void;
  259. /**
  260. * Creates a getUrl function that fetches content from HTTP and
  261. * HTTPS URLs.
  262. *
  263. * The available %%options%% are dependent on the platform
  264. * implementation of the default getUrl function.
  265. *
  266. * This is not generally something that is needed, but is useful
  267. * when trying to customize simple behaviour when fetching HTTP
  268. * content.
  269. */
  270. static createGetUrlFunc(options?: Record<string, any>): FetchGetUrlFunc;
  271. /**
  272. * Creates a function that can "fetch" data URIs.
  273. *
  274. * Note that this is automatically done internally to support
  275. * data URIs, so it is not necessary to register it.
  276. *
  277. * This is not generally something that is needed, but may
  278. * be useful in a wrapper to perfom custom data URI functionality.
  279. */
  280. static createDataGateway(): FetchGatewayFunc;
  281. /**
  282. * Creates a function that will fetch IPFS (unvalidated) from
  283. * a custom gateway baseUrl.
  284. *
  285. * The default IPFS gateway used internally is
  286. * ``"https:/\/gateway.ipfs.io/ipfs/"``.
  287. */
  288. static createIpfsGatewayFunc(baseUrl: string): FetchGatewayFunc;
  289. }
  290. /**
  291. * The response for a FetchRequest.
  292. */
  293. export declare class FetchResponse implements Iterable<[key: string, value: string]> {
  294. #private;
  295. toString(): string;
  296. /**
  297. * The response status code.
  298. */
  299. get statusCode(): number;
  300. /**
  301. * The response status message.
  302. */
  303. get statusMessage(): string;
  304. /**
  305. * The response headers. All keys are lower-case.
  306. */
  307. get headers(): Record<string, string>;
  308. /**
  309. * The response body, or ``null`` if there was no body.
  310. */
  311. get body(): null | Readonly<Uint8Array>;
  312. /**
  313. * The response body as a UTF-8 encoded string, or the empty
  314. * string (i.e. ``""``) if there was no body.
  315. *
  316. * An error is thrown if the body is invalid UTF-8 data.
  317. */
  318. get bodyText(): string;
  319. /**
  320. * The response body, decoded as JSON.
  321. *
  322. * An error is thrown if the body is invalid JSON-encoded data
  323. * or if there was no body.
  324. */
  325. get bodyJson(): any;
  326. [Symbol.iterator](): Iterator<[key: string, value: string]>;
  327. constructor(statusCode: number, statusMessage: string, headers: Readonly<Record<string, string>>, body: null | Uint8Array, request?: FetchRequest);
  328. /**
  329. * Return a Response with matching headers and body, but with
  330. * an error status code (i.e. 599) and %%message%% with an
  331. * optional %%error%%.
  332. */
  333. makeServerError(message?: string, error?: Error): FetchResponse;
  334. /**
  335. * If called within a [request.processFunc](FetchRequest-processFunc)
  336. * call, causes the request to retry as if throttled for %%stall%%
  337. * milliseconds.
  338. */
  339. throwThrottleError(message?: string, stall?: number): never;
  340. /**
  341. * Get the header value for %%key%%, ignoring case.
  342. */
  343. getHeader(key: string): string;
  344. /**
  345. * Returns true if the response has a body.
  346. */
  347. hasBody(): this is (FetchResponse & {
  348. body: Uint8Array;
  349. });
  350. /**
  351. * The request made for this response.
  352. */
  353. get request(): null | FetchRequest;
  354. /**
  355. * Returns true if this response was a success statusCode.
  356. */
  357. ok(): boolean;
  358. /**
  359. * Throws a ``SERVER_ERROR`` if this response is not ok.
  360. */
  361. assertOk(): void;
  362. }
  363. //# sourceMappingURL=fetch.d.ts.map