index.d.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import * as https from 'https';
  2. import * as http from 'http';
  3. import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
  4. import * as url from 'url';
  5. import { Readable, Writable } from 'stream';
  6. import { EventEmitter } from 'events';
  7. import { LookupFunction } from 'net';
  8. export { IncomingHttpHeaders, OutgoingHttpHeaders };
  9. export type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "OPTIONS" | "PATCH" | "TRACE" | "CONNECT";
  10. export as namespace urllib;
  11. export interface RequestOptions {
  12. /** Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'. */
  13. method?: HttpMethod;
  14. /** Alias method */
  15. type?: HttpMethod;
  16. /** Data to be sent. Will be stringify automatically. */
  17. data?: any;
  18. /** Force convert data to query string. */
  19. dataAsQueryString?: boolean;
  20. /** Manually set the content of payload. If set, data will be ignored. */
  21. content?: string | Buffer;
  22. /** Stream to be pipe to the remote.If set, data and content will be ignored. */
  23. stream?: Readable;
  24. /**
  25. * A writable stream to be piped by the response stream.
  26. * Responding data will be write to this stream and callback
  27. * will be called with data set null after finished writing.
  28. */
  29. writeStream?: Writable;
  30. /** consume the writeStream, invoke the callback after writeStream close. */
  31. consumeWriteStream?: boolean;
  32. /**
  33. * The files will send with multipart/form-data format, base on formstream.
  34. * If method not set, will use POST method by default.
  35. */
  36. files?: Array<Readable | Buffer | string> | object | Readable | Buffer | string;
  37. /** Type of request data.Could be json.If it's json, will auto set Content-Type: application/json header. */
  38. contentType?: string;
  39. /**
  40. * urllib default use querystring to stringify form data which don't support nested object,
  41. * will use qs instead of querystring to support nested object by set this option to true.
  42. */
  43. nestedQuerystring?: boolean;
  44. /**
  45. * Type of response data. Could be text or json.
  46. * If it's text, the callbacked data would be a String.
  47. * If it's json, the data of callback would be a parsed JSON Object
  48. * and will auto set Accept: application/json header. Default callbacked data would be a Buffer.
  49. */
  50. dataType?: string;
  51. /** Fix the control characters (U+0000 through U+001F) before JSON parse response. Default is false. */
  52. fixJSONCtlChars?: boolean;
  53. /** Request headers. */
  54. headers?: IncomingHttpHeaders;
  55. /** by default will convert header keys to lowercase */
  56. keepHeaderCase?: boolean;
  57. /**
  58. * Request timeout in milliseconds for connecting phase and response receiving phase.
  59. * Defaults to exports.
  60. * TIMEOUT, both are 5s.You can use timeout: 5000 to tell urllib use same timeout on two phase or set them seperately such as
  61. * timeout: [3000, 5000], which will set connecting timeout to 3s and response 5s.
  62. */
  63. timeout?: number | number[];
  64. /** username:password used in HTTP Basic Authorization. */
  65. auth?: string;
  66. /** username:password used in HTTP Digest Authorization. */
  67. digestAuth?: string;
  68. /** HTTP Agent object.Set false if you does not use agent. */
  69. agent?: http.Agent;
  70. /** HTTPS Agent object. Set false if you does not use agent. */
  71. httpsAgent?: https.Agent;
  72. /**
  73. * An array of strings or Buffers of trusted certificates.
  74. * If this is omitted several well known "root" CAs will be used, like VeriSign.
  75. * These are used to authorize connections.
  76. * Notes: This is necessary only if the server uses the self - signed certificate
  77. */
  78. ca?: string | Buffer | string[] | Buffer[];
  79. /**
  80. * If true, the server certificate is verified against the list of supplied CAs.
  81. * An 'error' event is emitted if verification fails.Default: true.
  82. */
  83. rejectUnauthorized?: boolean;
  84. /** A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. */
  85. pfx?: string | Buffer;
  86. /**
  87. * A string or Buffer containing the private key of the client in PEM format.
  88. * Notes: This is necessary only if using the client certificate authentication
  89. */
  90. key?: string | Buffer;
  91. /**
  92. * A string or Buffer containing the certificate key of the client in PEM format.
  93. * Notes: This is necessary only if using the client certificate authentication
  94. */
  95. cert?: string | Buffer;
  96. /** A string of passphrase for the private key or pfx. */
  97. passphrase?: string;
  98. /** A string describing the ciphers to use or exclude. */
  99. ciphers?: string;
  100. /** The SSL method to use, e.g.SSLv3_method to force SSL version 3. */
  101. secureProtocol?: string;
  102. /** follow HTTP 3xx responses as redirects. defaults to false. */
  103. followRedirect?: boolean;
  104. /** The maximum number of redirects to follow, defaults to 10. */
  105. maxRedirects?: number;
  106. /** Format the redirect url by your self. Default is url.resolve(from, to). */
  107. formatRedirectUrl?: (a: any, b: any) => void;
  108. /** Before request hook, you can change every thing here. */
  109. beforeRequest?: (...args: any[]) => void;
  110. /** let you get the res object when request connected, default false. alias customResponse */
  111. streaming?: boolean;
  112. /** Accept gzip response content and auto decode it, default is false. */
  113. gzip?: boolean;
  114. /** Enable timing or not, default is false. */
  115. timing?: boolean;
  116. /** Enable proxy request, default is false. */
  117. enableProxy?: boolean;
  118. /** proxy agent uri or options, default is null. */
  119. proxy?: string | { [key: string]: any };
  120. /**
  121. * Custom DNS lookup function, default is dns.lookup.
  122. * Require node >= 4.0.0(for http protocol) and node >=8(for https protocol)
  123. */
  124. lookup?: LookupFunction;
  125. /**
  126. * check request address to protect from SSRF and similar attacks.
  127. * It receive two arguments(ip and family) and should return true or false to identified the address is legal or not.
  128. * It rely on lookup and have the same version requirement.
  129. */
  130. checkAddress?: (ip: string, family: number | string) => boolean;
  131. }
  132. export interface HttpClientResponse<T> {
  133. data: T;
  134. status: number;
  135. headers: OutgoingHttpHeaders;
  136. res: http.IncomingMessage;
  137. }
  138. /**
  139. * @param data Outgoing message
  140. * @param res http response
  141. */
  142. export type Callback<T> = (err: Error, data: T, res: http.IncomingMessage) => void;
  143. /**
  144. * Handle all http request, both http and https support well.
  145. *
  146. * @example
  147. * // GET http://httptest.cnodejs.net
  148. * urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {});
  149. * // POST http://httptest.cnodejs.net
  150. * var args = { type: 'post', data: { foo: 'bar' } };
  151. * urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {});
  152. *
  153. * @param url The URL to request, either a String or a Object that return by url.parse.
  154. */
  155. export function request<T = any>(url: string | url.URL, options?: RequestOptions): Promise<HttpClientResponse<T>>;
  156. /**
  157. * @param url The URL to request, either a String or a Object that return by url.parse.
  158. */
  159. export function request<T = any>(url: string | url.URL, callback: Callback<T>): void;
  160. /**
  161. * @param url The URL to request, either a String or a Object that return by url.parse.
  162. */
  163. export function request<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void;
  164. /**
  165. * Handle request with a callback.
  166. * @param url The URL to request, either a String or a Object that return by url.parse.
  167. */
  168. export function requestWithCallback<T = any>(url: string | url.URL, callback: Callback<T>): void;
  169. /**
  170. * @param url The URL to request, either a String or a Object that return by url.parse.
  171. */
  172. export function requestWithCallback<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void;
  173. /**
  174. * yield urllib.requestThunk(url, args)
  175. * @param url The URL to request, either a String or a Object that return by url.parse.
  176. */
  177. export function requestThunk<T = any>(url: string | url.URL, options?: RequestOptions): (callback: Callback<T>) => void;
  178. /**
  179. * alias to request.
  180. * Handle all http request, both http and https support well.
  181. *
  182. * @example
  183. * // GET http://httptest.cnodejs.net
  184. * urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {});
  185. * // POST http://httptest.cnodejs.net
  186. * var args = { type: 'post', data: { foo: 'bar' } };
  187. * urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {});
  188. *
  189. * @param url The URL to request, either a String or a Object that return by url.parse.
  190. * @param options Optional, @see RequestOptions.
  191. */
  192. export function curl<T = any>(url: string | url.URL, options?: RequestOptions): Promise<HttpClientResponse<T>>;
  193. /**
  194. * @param url The URL to request, either a String or a Object that return by url.parse.
  195. */
  196. export function curl<T = any>(url: string | url.URL, callback: Callback<T>): void;
  197. /**
  198. * @param url The URL to request, either a String or a Object that return by url.parse.
  199. */
  200. export function curl<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void;
  201. /**
  202. * The default request timeout(in milliseconds).
  203. */
  204. export const TIMEOUT: number;
  205. /**
  206. * The default request & response timeout(in milliseconds).
  207. */
  208. export const TIMEOUTS: [number, number];
  209. /**
  210. * Request user agent.
  211. */
  212. export const USER_AGENT: string;
  213. /**
  214. * Request http agent.
  215. */
  216. export const agent: http.Agent;
  217. /**
  218. * Request https agent.
  219. */
  220. export const httpsAgent: https.Agent;
  221. export class HttpClient<O extends RequestOptions = RequestOptions> extends EventEmitter {
  222. request<T = any>(url: string | url.URL): Promise<HttpClientResponse<T>>;
  223. request<T = any>(url: string | url.URL, options: O): Promise<HttpClientResponse<T>>;
  224. request<T = any>(url: string | url.URL, callback: Callback<T>): void;
  225. request<T = any>(url: string | url.URL, options: O, callback: Callback<T>): void;
  226. curl<T = any>(url: string | url.URL, options: O): Promise<HttpClientResponse<T>>;
  227. curl<T = any>(url: string | url.URL): Promise<HttpClientResponse<T>>;
  228. curl<T = any>(url: string | url.URL, callback: Callback<T>): void;
  229. curl<T = any>(url: string | url.URL, options: O, callback: Callback<T>): void;
  230. requestThunk(url: string | url.URL, options?: O): (callback: (...args: any[]) => void) => void;
  231. }
  232. export interface RequestOptions2 extends RequestOptions {
  233. retry?: number;
  234. retryDelay?: number;
  235. isRetry?: (res: HttpClientResponse<any>) => boolean;
  236. }
  237. /**
  238. * request method only return a promise,
  239. * compatible with async/await and generator in co.
  240. */
  241. export class HttpClient2 extends HttpClient<RequestOptions2> {}
  242. /**
  243. * Create a HttpClient instance.
  244. */
  245. export function create(options?: RequestOptions): HttpClient;