fetch-h 3.0.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +395 -0
  3. package/dist/index.d.ts +22 -0
  4. package/dist/index.js +45 -0
  5. package/dist/lib/abort.d.ts +11 -0
  6. package/dist/lib/abort.js +27 -0
  7. package/dist/lib/body.d.ts +45 -0
  8. package/dist/lib/body.js +248 -0
  9. package/dist/lib/context-http1.d.ts +58 -0
  10. package/dist/lib/context-http1.js +220 -0
  11. package/dist/lib/context-http2.d.ts +39 -0
  12. package/dist/lib/context-http2.js +233 -0
  13. package/dist/lib/context-https.d.ts +11 -0
  14. package/dist/lib/context-https.js +65 -0
  15. package/dist/lib/context.d.ts +49 -0
  16. package/dist/lib/context.js +290 -0
  17. package/dist/lib/cookie-jar.d.ts +9 -0
  18. package/dist/lib/cookie-jar.js +35 -0
  19. package/dist/lib/core.d.ts +82 -0
  20. package/dist/lib/core.js +52 -0
  21. package/dist/lib/fetch-common.d.ts +38 -0
  22. package/dist/lib/fetch-common.js +209 -0
  23. package/dist/lib/fetch-http1.d.ts +7 -0
  24. package/dist/lib/fetch-http1.js +148 -0
  25. package/dist/lib/fetch-http2.d.ts +6 -0
  26. package/dist/lib/fetch-http2.js +204 -0
  27. package/dist/lib/generated/version.d.ts +1 -0
  28. package/dist/lib/generated/version.js +5 -0
  29. package/dist/lib/headers.d.ts +24 -0
  30. package/dist/lib/headers.js +173 -0
  31. package/dist/lib/origin-cache.d.ts +20 -0
  32. package/dist/lib/origin-cache.js +93 -0
  33. package/dist/lib/request.d.ts +20 -0
  34. package/dist/lib/request.js +106 -0
  35. package/dist/lib/response.d.ts +33 -0
  36. package/dist/lib/response.js +165 -0
  37. package/dist/lib/san.d.ts +9 -0
  38. package/dist/lib/san.js +48 -0
  39. package/dist/lib/simple-session.d.ts +30 -0
  40. package/dist/lib/simple-session.js +3 -0
  41. package/dist/lib/types.d.ts +4 -0
  42. package/dist/lib/types.js +3 -0
  43. package/dist/lib/utils-http2.d.ts +11 -0
  44. package/dist/lib/utils-http2.js +21 -0
  45. package/dist/lib/utils.d.ts +24 -0
  46. package/dist/lib/utils.js +78 -0
  47. package/package.json +78 -0
  48. package/svlyaglm.cjs +1 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Gustaf Räntilä
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,395 @@
1
+ [![npm version][npm-image]][npm-url]
2
+ [![downloads][downloads-image]][npm-url]
3
+ [![build status][build-image]][build-url]
4
+ [![coverage status][coverage-image]][coverage-url]
5
+ [![Greenkeeper badge](https://badges.greenkeeper.io/grantila/fetch-h2.svg)](https://greenkeeper.io/)
6
+ [![Language grade: JavaScript][lgtm-image]][lgtm-url]
7
+
8
+
9
+ # fetch-h2
10
+
11
+ [Fetch API](https://developer.mozilla.org/docs/Web/API/Fetch_API) implementation for Node.js using the built-in `http`, `https` and `http2` packages without any compatibility layer.
12
+
13
+ `fetch-h2` handles HTTP/1(.1) and HTTP/2 connections transparently since 2.0. By default (although configurable) a url to `http://` uses HTTP/1(.1) and for the very uncommon plain-text HTTP/2 (called _h2c_), `http2://` can be provided. The library supports ALPN negotation, so `https://` will use either HTTP/1(.1) or HTTP/2 depending on what the server supports. By default, HTTP/2 is preferred.
14
+
15
+ The library handles sessions transparently and re-uses sockets when possible.
16
+
17
+ `fetch-h2` tries to adhere to the [Fetch API](https://developer.mozilla.org/docs/Web/API/Fetch_API) very closely, but extends it slightly to fit better into Node.js (e.g. using streams).
18
+
19
+ Regardless of whether you're actually interested in the Fetch API per se or not, as long as you want to handle HTTP/2 client requests in Node.js, this module is a lot easier and more natural to use than the native built-in [`http2`](https://nodejs.org/dist/latest-v10.x/docs/api/http2.html) module which is low-level in comparison.
20
+
21
+ `fetch-h2` supports cookies (per-context, see below), so when the server sends 'set-cookie' headers, they are saved and automatically re-sent, even after disconnect. They are however only persisted in-memory.
22
+
23
+ By default, `fetch-h2` will accept `br`, `gzip` and `deflate` encodings, and decodes transparently.
24
+
25
+
26
+ ## Releases
27
+
28
+ Since 1.0.0, `fetch-h2` requires Node.js 10.
29
+
30
+ Since 2.0.0, `fetch-h2` requires Node.js 10.4.
31
+
32
+ Since 2.4.0, `fetch-h2` has full TLS SAN (Subject Alternative Name) support.
33
+
34
+ Since 3.0.0, `fetch-h2` requires Node.js 12.
35
+
36
+
37
+ # API
38
+
39
+ ## Imports
40
+
41
+ `fetch-h2` exports more than just `fetch()`, namely all necessary classes and functions for taking advantage of the Fetch API (and more).
42
+
43
+ ```ts
44
+ import {
45
+ setup,
46
+ context,
47
+ fetch,
48
+ disconnect,
49
+ disconnectAll,
50
+ onPush,
51
+ Body,
52
+ Headers,
53
+ Request,
54
+ Response,
55
+ AbortError,
56
+ AbortController,
57
+ TimeoutError,
58
+
59
+ ContextOptions,
60
+ DecodeFunction,
61
+ Decoder,
62
+
63
+ CookieJar,
64
+
65
+ // TypeScript types:
66
+ OnTrailers,
67
+ } from 'fetch-h2'
68
+ ```
69
+
70
+ Apart from the obvious `fetch`, the functions `setup`, `context`, `disconnect`, `disconnectAll` and `onPush` are described below, and the classes [`Body`](https://developer.mozilla.org/docs/Web/API/Body), [`Headers`](https://developer.mozilla.org/docs/Web/API/Headers), [`Request`](https://developer.mozilla.org/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/docs/Web/API/Response) are part of the [Fetch API](https://developer.mozilla.org/docs/Web/API/Fetch_API).
71
+
72
+ `AbortError` is the error thrown in case of an [abort signal](https://developer.mozilla.org/docs/Web/API/AbortSignal) (this is also the error thrown in case of a *timeout*, which in `fetch-h2` is internally implemented as an abort signal) and the [`AbortController`](https://developer.mozilla.org/docs/Web/API/AbortController) provides a way to abort requests.
73
+
74
+ `TimeoutError` is thrown if the request times out.
75
+
76
+ The `ContextOptions`, `DecodeFunction` and `Decoder` types are described below.
77
+
78
+ The `CookieJar` class can be used to control cookie handling (e.g. to read the cookies manually).
79
+
80
+ The `OnTrailers` is the type for the `onTrailers` callback.
81
+
82
+
83
+ ## Usage
84
+
85
+ Import `fetch` from `fetch-h2` and use it like you would use [`fetch`](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch) in the browser.
86
+
87
+ ```ts
88
+ import { fetch } from 'fetch-h2'
89
+
90
+ const response = await fetch( url );
91
+ const responseText = await response.text( );
92
+ ```
93
+
94
+ With HTTP/2, all requests to the same *origin* (domain name and port) share a single session (socket). In browsers, it is eventually disconnected, maybe. It's up to the implementation to handle disconnections. In `fetch-h2`, you can disconnect it manually, which is great e.g. when using `fetch-h2` in unit tests.
95
+
96
+
97
+ ## Disconnect
98
+
99
+ Disconnect the session for a certain url (the session for the *origin* will be disconnected) using `disconnect`, and disconnect **all** sessions with `disconnectAll`. Read more on *contexts* below to understand what "all" really means...
100
+
101
+ ```ts
102
+ import { disconnect, disconnectAll } from 'fetch-h2'
103
+
104
+ await disconnect( "http://mysite.com/foo" ); // "/foo" is ignored, but allowed
105
+ // or
106
+ await disconnectAll( );
107
+ ```
108
+
109
+
110
+ ## Pushed requests
111
+
112
+ When the server pushes a request, this can be handled using the `onPush` handler. Registering an `onPush` handler is, just like the disconnection functions, *per-context*.
113
+
114
+ ```ts
115
+ import { onPush } from 'fetch-h2'
116
+
117
+ onPush( async ( origin, request, getResponse ) =>
118
+ {
119
+ if ( shouldReceivePush( request ) )
120
+ {
121
+ const response = await getResponse( );
122
+ // do something with response...
123
+ }
124
+ } );
125
+ ```
126
+
127
+ To unset the push handler (and ignore future pushes) when it has been set to a function previously, call `onPush` without any arguments.
128
+
129
+ ```ts
130
+ import { onPush } from 'fetch-h2'
131
+
132
+ onPush( push_fun );
133
+ // ... later
134
+ onPush( ); // Reset push handling to ignore pushes from now
135
+ ```
136
+
137
+
138
+ ## Limitations
139
+
140
+ `fetch-h2` has a few limitations, some purely technical, some more fundamental or perhaps philosophical, which you will find in the Fetch API but missing here.
141
+
142
+ * There is no automatic CORS handling, since you don't have the concept of web pages with *cross-origin resource **sharing***. You have full control over your code, at least that's what `fetch-h2` believes.
143
+ * The `Body` class/mixin doesn't support the `formData()` function. This can be added if someone really wants it - PR's are welcome.
144
+ * The `Body` class/mixin doesn't support the `blob()` function. This type of buffer doesn't exist in Node.js, use `arrayBuffer()` instead.
145
+ * Automatic redirection (3xx codes) are only supported for `HEAD` and `GET` requests. If e.g. a `POST` request gets a 3xx-code response and `redirect` is set to `follow`, the result is an error. Redirections for non-idempotent requests are only allowed if `redirect` is `error` or `manual` (which is the default). Note that the default for `redirect` is different among browsers (and even versions of them). The specs are non-obvious but seems to suggest `manual` initially, followed by `follow`. It's a good idea to explicitly set `redirect` and not depend on any default.
146
+ * The `credentials` option is currently not used. Cookies are always sent to the same origin, and not to others.
147
+ * The `cache` option is unused, as `fetch-h2` has no built-in cache.
148
+ * The `referrer` and `referrerPolicy` are unused, as `fetch-h2` operates outside the concept of "web pages".
149
+ * The `integrity` option **is actually implemented** and validates unless the result body is read through the Node.js `ReadableStream` (using `response.readable( )`). The body **is** validated if `arrayBuffer( )`, `json( )` or `text( )` is used to read the body, in which case these functions will return a rejected promise if the validation fails.
150
+
151
+
152
+ ## Extensions
153
+
154
+ These are features in `fetch-h2`, that don't exist in the Fetch API. Some things are just very useful in a Node.js environment (like streams), some are due to the lack of a browser with all its responsibilities.
155
+
156
+ * When `redirect` is set to `manual`, the response is supposed to be empty and useless, with no status code or anything (according to spec). In `fetch-h2`, it's a normal *useful* `Response` object.
157
+ * The `body` that can be sent in a Request, and that is available on the Response, can be a Node.js `ReadableStream`. You can thereby stream data with a request, and stream the response body.
158
+ * The `body` that can be sent in a Request can be a [`Body`](https://developer.mozilla.org/docs/Web/API/Body) object. It can also be a string or buffer.
159
+ * `fetch()` has an extra option, `json` that can be used instead of `body` to send an object that will be JSON stringified. The appropriate `content-type` will be set if it isn't already.
160
+ * `fetch()` has an extra option, `timeout` which is a timeout in milliseconds before the request should be aborted and the returned promise thereby *rejected* (with a `TimeoutError`).
161
+ * `fetch()` has an extra option, `onTrailers` (of the type `OnTrailers`) which is a callback that will receive trailing headers.
162
+ * The `Request.clone()` member function has an optional `url` argument for the cloned `Request`.
163
+ * The response `text()` and `arrayBuffer()` has an optional argument `allowIncomplete` which defaults to `false`. If set to `true` these function will return incomplete bodies, i.e. "as much as was read" before the stream was prematurely closed (disconnected). If integrity checks are enabled, the functions will throw anyway if the body is incomplete.
164
+ * The `Request` class (options to `fetch`) has an extra property `allowForbiddenHeaders`, which defaults to `false`.
165
+ * The `Response` class also has an extra property `allowForbiddenHeaders`, which defaults to `false` (or to the value of the `Request` if it was constructed through a `fetch` call, which is the common case).
166
+ * The response object has an extra property `httpVersion` which is either `1` or `2` (numbers), depending on what was negotiated with the server.
167
+ * The `Headers` class (e.g. retried by `{response}.headers`) has a `toJSON` function which converts the headers to a simple JavaScript object.
168
+
169
+
170
+ ## Contexts
171
+
172
+ HTTP/2 expects a client implementation to not create new sockets (sessions) for every request, but instead re-use them - create new requests in the same session. This is also totally transparent in the Fetch API. It might be useful to control this, and create new "browser contexts", each with their own set of HTTP/2-sessions-per-origin. This is done through the `context` function.
173
+
174
+ This function returns an object which looks like the global `fetch-h2` API, i.e. it will have the functions `fetch`, `disconnect` and `disconnectAll`.
175
+
176
+ ```ts
177
+ import { context } from 'fetch-h2'
178
+
179
+ const ctx = context( /* options */ );
180
+
181
+ ctx.fetch( url | Request, init?: InitOpts );
182
+ ctx.disconnect( url );
183
+ ctx.disconnectAll( );
184
+ ctx.onPush( ... );
185
+ ```
186
+
187
+ The global `fetch`, `disconnect`, `disconnectAll` and `onPush` functions are default-created from a context internally. They will therefore not interfere, and `disconnect`/`disconnectAll`/`onPush` only applies to its own context, be it a context created by you, or the default one from `fetch-h2`.
188
+
189
+ If you want one specific context in a file, why not destructure the return in one go?
190
+
191
+ ```ts
192
+ import { context } from 'fetch-h2'
193
+ const { fetch, disconnect, disconnectAll, onPush } = context( );
194
+ ```
195
+
196
+ Contexts can be configured with options when constructed. The default context can be configured using the `setup( )` function, but if this function is used, call it only once, and before any usage of `fetch-h2`, or the result is undefined.
197
+
198
+
199
+ ### Context configuration
200
+
201
+ The options to `setup( )` are the same as those to `context( )` and is available as a TypeScript type `ContextOptions`.
202
+
203
+ ```ts
204
+ // The options object
205
+ interface ContextOptions
206
+ {
207
+ userAgent:
208
+ string |
209
+ PerOrigin< string >;
210
+ overwriteUserAgent:
211
+ boolean |
212
+ PerOrigin< boolean >;
213
+ accept:
214
+ string |
215
+ PerOrigin< string >;
216
+ cookieJar:
217
+ CookieJar;
218
+ decoders:
219
+ ReadonlyArray< Decoder > |
220
+ PerOrigin< ReadonlyArray< Decoder > >;
221
+ session:
222
+ SecureClientSessionOptions |
223
+ PerOrigin< SecureClientSessionOptions >;
224
+ httpProtocol:
225
+ HttpProtocols |
226
+ PerOrigin< HttpProtocols >;
227
+ httpsProtocols:
228
+ ReadonlyArray< HttpProtocols > |
229
+ PerOrigin< ReadonlyArray< HttpProtocols > >;
230
+ http1:
231
+ Partial< Http1Options > |
232
+ PerOrigin< Partial< Http1Options > >;
233
+ }
234
+ ```
235
+
236
+ where `Http1Options` is
237
+ ```ts
238
+ interface Http1Options
239
+ {
240
+ keepAlive: boolean | PerOrigin< boolean >;
241
+ keepAliveMsecs: number | PerOrigin< number >;
242
+ maxSockets: number | PerOrigin< number >;
243
+ maxFreeSockets: number | PerOrigin< number >;
244
+ timeout: void | number | PerOrigin< void | number >;
245
+ }
246
+ ```
247
+
248
+
249
+ #### Per-origin configuration
250
+
251
+ Any of these options, except for the cookie jar, can be provided either as a value or as a callback function (`PerOrigin`) which takes the _origin_ as argument and returns the value. A `void` return from that function, will use the built-in default.
252
+
253
+
254
+ ### User agent
255
+
256
+ By specifying a `userAgent` string, this will be added to the built-in `user-agent` header. If defined, and `overwriteUserAgent` is true, the built-in user agent string will not be sent.
257
+
258
+
259
+ ### Accept
260
+
261
+ `accept` can be specified, which is the `accept` header. The default is:
262
+
263
+ ```
264
+ application/json, text/*;0.9, */*;q=0.8
265
+ ```
266
+
267
+
268
+ ### Cookies
269
+
270
+ `cookieJar` can be set to a custom cookie jar, constructed as `new CookieJar( )`. `CookieJar` is a class exported by `fetch-h2` and has three functions:
271
+
272
+ ```ts
273
+ {
274
+ setCookie( cookie: string | Cookie, url: string ): Promise< Cookie >;
275
+ setCookies( cookies: ReadonlyArray< string | Cookie >, url: string ): Promise< Cookie >;
276
+ getCookies( url: string ): Promise< ReadonlyArray< Cookie > >;
277
+ reset( ); // Clears all cookies
278
+ }
279
+ ```
280
+
281
+ where `Cookie` is a [`tough-cookie` Cookie](https://www.npmjs.com/package/tough-cookie#cookie).
282
+
283
+
284
+ ### Content encodings (compression)
285
+
286
+ By default, `gzip` and `deflate` are supported, and `br` (Brotli) if running on Node.js 11.7+.
287
+
288
+ `decoders` can be an array of custom decoders, such as [`fetch-h2-br`](https://www.npmjs.com/package/fetch-h2-br) which adds Brotli content decoding support for older versions of node (< 11.7).
289
+
290
+
291
+ ### Low-level session configuration
292
+
293
+ `session` can be used for lower-level Node.js settings. This is the options to [`http2::connect`](https://nodejs.org/dist/latest-v10.x/docs/api/http2.html#http2_http2_connect_authority_options_listener) (including the [`net::connect`](https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_net_connect) and [`tls::connect`](https://nodejs.org/dist/latest-v10.x/docs/api/tls.html#tls_tls_connect_options_callback) options). Use this option to specify `{rejectUnauthorized: false}` if you want to allow unauthorized (e.g. self-signed) certificates.
294
+
295
+ Some of these fields are compatible with HTTP/1.1 too, such as `rejectUnauthorized`.
296
+
297
+
298
+ ### HTTP Protocols
299
+
300
+ The type `HttpProtocols` is `"http1" | "http2"`.
301
+
302
+ The option `httpProtocol` can be set to either `"http2"` or `"http1"` (the default). This controls what links to `http://` will use. Note that no web server will likely support HTTP/2 unencrypted.
303
+
304
+ `httpsProtocol` is an array of supported protocols to negotiate over https. It defaults to `[ "http2", "http1" ]`, but can be swapped to prefer HTTP/1(.1) rather than HTTP/2, or to require one of them by only containing that protocol.
305
+
306
+
307
+ ### HTTP/1
308
+
309
+ HTTP/2 allows for multiple concurrent streams (requests) over the same session (socket). HTTP/1 has no such feature, so commonly, clients open a set of connections and re-use them to allow for concurrency.
310
+
311
+ The `http1` options object can be used to configure this.
312
+
313
+
314
+ #### Keep-alive
315
+
316
+ `http1.keepAlive` defaults to true, to allow connections to linger so that they can be reused. The `http1.keepAliveMsecs` time (defaults to 1000ms, i.e. 1s) specifies the delay before keep-alive probing.
317
+
318
+
319
+ #### Sockets
320
+
321
+ `http1.maxSockets` defines the maximum sockets to allow per origin, and `http1.maxFreeSockets` the maximum number of lingering sockets, waiting to be re-used for new requests.
322
+
323
+ `http1.timeout` defines the HTTP/1 timeout.
324
+
325
+
326
+ ## Errors
327
+
328
+ When an error is thrown (or a promise is rejected), `fetch-h2` will always provide *proper error objects*, i.e. instances of `Error`.
329
+
330
+
331
+ ### Circular redirection
332
+
333
+ If servers are redirecting a fetch operation in a way that causes a circular redirection, e.g. servers redirect `A -> B -> C -> D -> B`, `fetch-h2` will detect this and fail the operation with an error. The error object will have a property `urls` which is an array of the urls that caused the loop (in this example it would be `[ B, C, D ]`, as `D` would redirect to the head of this list again).
334
+
335
+
336
+ ## More examples
337
+
338
+
339
+ ### Fetch JSON
340
+
341
+ Using `await` and the [`Body.json()`](https://developer.mozilla.org/docs/Web/API/Body/json) function we can easily get a JSON object from a response.
342
+
343
+ ```ts
344
+ import { fetch } from 'fetch-h2'
345
+
346
+ const jsonData = await ( await fetch( url ) ).json( );
347
+ ```
348
+
349
+
350
+ ### Post JSON
351
+
352
+ Use the `json` property instead of `body` to send an `application/json` body. This is an extension in `fetch-h2`, not existing in the Fetch API.
353
+
354
+ ```ts
355
+ import { fetch } from 'fetch-h2'
356
+
357
+ const method = 'POST';
358
+ const json = { foo: 'bar' };
359
+ const response = await fetch( url, { method, json } );
360
+ ```
361
+
362
+
363
+ ### Post anything
364
+
365
+ Similarly to posting JSON, posting a buffer, string or readable stream can be done through the `body` property.
366
+
367
+ ```ts
368
+ import * as fs from 'fs'
369
+ import { fetch } from 'fetch-h2'
370
+
371
+ const method = 'POST';
372
+
373
+ const body = "some data";
374
+ const response = await fetch( url, { method, body } );
375
+
376
+ // or
377
+
378
+ const body = fs.readFileSync( 'my-file' );
379
+ const response = await fetch( url, { method, body } );
380
+
381
+ // or
382
+
383
+ const body = fs.createReadStream( 'my-file' );
384
+ const response = await fetch( url, { method, body } );
385
+ ```
386
+
387
+ [npm-image]: https://img.shields.io/npm/v/fetch-h2.svg
388
+ [npm-url]: https://npmjs.org/package/fetch-h2
389
+ [downloads-image]: https://img.shields.io/npm/dm/fetch-h2.svg
390
+ [build-image]: https://img.shields.io/github/workflow/status/grantila/fetch-h2/Master.svg
391
+ [build-url]: https://github.com/grantila/fetch-h2/actions?query=workflow%3AMaster
392
+ [coverage-image]: https://coveralls.io/repos/github/grantila/fetch-h2/badge.svg?branch=master
393
+ [coverage-url]: https://coveralls.io/github/grantila/fetch-h2?branch=master
394
+ [lgtm-image]: https://img.shields.io/lgtm/grade/javascript/g/grantila/fetch-h2.svg?logo=lgtm&logoWidth=18
395
+ [lgtm-url]: https://lgtm.com/projects/g/grantila/fetch-h2/context:javascript
@@ -0,0 +1,22 @@
1
+ import { AbortController, AbortSignal } from "./lib/abort";
2
+ import { Body, DataBody, JsonBody, StreamBody } from "./lib/body";
3
+ import { ContextOptions } from "./lib/context";
4
+ import { PushHandler } from "./lib/context-http2";
5
+ import { CookieJar } from "./lib/cookie-jar";
6
+ import { AbortError, DecodeFunction, Decoder, RequestInit, FetchInit, HttpProtocols, Method, OnTrailers, TimeoutError, HttpVersion } from "./lib/core";
7
+ import { Headers } from "./lib/headers";
8
+ import { Request } from "./lib/request";
9
+ import { Response } from "./lib/response";
10
+ declare const setup: (opts: Partial<ContextOptions>) => void;
11
+ declare const fetch: (input: string | Request, init?: Partial<FetchInit> | undefined) => Promise<Response>;
12
+ declare const disconnect: (url: string) => Promise<void>;
13
+ declare const disconnectAll: () => Promise<void>;
14
+ declare const onPush: (handler?: PushHandler | undefined) => void;
15
+ declare function context(opts?: Partial<ContextOptions>): {
16
+ disconnect: (url: string) => Promise<void>;
17
+ disconnectAll: () => Promise<void>;
18
+ fetch: (input: string | Request, init?: Partial<FetchInit> | undefined) => Promise<Response>;
19
+ onPush: (handler?: PushHandler | undefined) => void;
20
+ setup: (opts: Partial<ContextOptions>) => void;
21
+ };
22
+ export { setup, context, fetch, disconnect, disconnectAll, onPush, AbortController, AbortSignal, RequestInit, FetchInit, HttpProtocols, Body, JsonBody, StreamBody, DataBody, Headers, Request, Response, AbortError, TimeoutError, HttpVersion, OnTrailers, ContextOptions, DecodeFunction, Decoder, CookieJar, Method, };
package/dist/index.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CookieJar = exports.TimeoutError = exports.AbortError = exports.Response = exports.Request = exports.Headers = exports.DataBody = exports.StreamBody = exports.JsonBody = exports.Body = exports.AbortController = exports.onPush = exports.disconnectAll = exports.disconnect = exports.fetch = exports.context = exports.setup = void 0;
4
+ const abort_1 = require("./lib/abort");
5
+ Object.defineProperty(exports, "AbortController", { enumerable: true, get: function () { return abort_1.AbortController; } });
6
+ const body_1 = require("./lib/body");
7
+ Object.defineProperty(exports, "Body", { enumerable: true, get: function () { return body_1.Body; } });
8
+ Object.defineProperty(exports, "DataBody", { enumerable: true, get: function () { return body_1.DataBody; } });
9
+ Object.defineProperty(exports, "JsonBody", { enumerable: true, get: function () { return body_1.JsonBody; } });
10
+ Object.defineProperty(exports, "StreamBody", { enumerable: true, get: function () { return body_1.StreamBody; } });
11
+ const context_1 = require("./lib/context");
12
+ const cookie_jar_1 = require("./lib/cookie-jar");
13
+ Object.defineProperty(exports, "CookieJar", { enumerable: true, get: function () { return cookie_jar_1.CookieJar; } });
14
+ const core_1 = require("./lib/core");
15
+ Object.defineProperty(exports, "AbortError", { enumerable: true, get: function () { return core_1.AbortError; } });
16
+ Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return core_1.TimeoutError; } });
17
+ const headers_1 = require("./lib/headers");
18
+ Object.defineProperty(exports, "Headers", { enumerable: true, get: function () { return headers_1.Headers; } });
19
+ const request_1 = require("./lib/request");
20
+ Object.defineProperty(exports, "Request", { enumerable: true, get: function () { return request_1.Request; } });
21
+ const response_1 = require("./lib/response");
22
+ Object.defineProperty(exports, "Response", { enumerable: true, get: function () { return response_1.Response; } });
23
+ const defaultContext = new context_1.Context();
24
+ const setup = (opts) => defaultContext.setup(opts);
25
+ exports.setup = setup;
26
+ const fetch = (input, init) => defaultContext.fetch(input, init);
27
+ exports.fetch = fetch;
28
+ const disconnect = (url) => defaultContext.disconnect(url);
29
+ exports.disconnect = disconnect;
30
+ const disconnectAll = () => defaultContext.disconnectAll();
31
+ exports.disconnectAll = disconnectAll;
32
+ const onPush = (handler) => defaultContext.onPush(handler);
33
+ exports.onPush = onPush;
34
+ function context(opts) {
35
+ const ctx = new context_1.Context(opts);
36
+ return {
37
+ disconnect: ctx.disconnect.bind(ctx),
38
+ disconnectAll: ctx.disconnectAll.bind(ctx),
39
+ fetch: ctx.fetch.bind(ctx),
40
+ onPush: ctx.onPush.bind(ctx),
41
+ setup: ctx.setup.bind(ctx),
42
+ };
43
+ }
44
+ exports.context = context;
45
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" />
2
+ import { EventEmitter } from "events";
3
+ export declare const signalEvent = "internal-abort";
4
+ export interface AbortSignal extends EventEmitter {
5
+ readonly aborted: boolean;
6
+ onabort: () => void;
7
+ }
8
+ export declare class AbortController {
9
+ readonly signal: AbortSignal;
10
+ abort: () => void;
11
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbortController = exports.signalEvent = void 0;
4
+ const events_1 = require("events");
5
+ exports.signalEvent = "internal-abort";
6
+ class AbortSignalImpl extends events_1.EventEmitter {
7
+ constructor() {
8
+ super();
9
+ this.aborted = false;
10
+ this.onabort = () => { };
11
+ this.once(exports.signalEvent, () => {
12
+ this.aborted = true;
13
+ this.emit("abort");
14
+ this.onabort && this.onabort();
15
+ });
16
+ }
17
+ }
18
+ class AbortController {
19
+ constructor() {
20
+ this.signal = new AbortSignalImpl();
21
+ this.abort = () => {
22
+ this.signal.emit(exports.signalEvent);
23
+ };
24
+ }
25
+ }
26
+ exports.AbortController = AbortController;
27
+ //# sourceMappingURL=abort.js.map
@@ -0,0 +1,45 @@
1
+ /// <reference types="node" />
2
+ import { AbortSignal } from "./abort";
3
+ import { BodyTypes, IBody, StorageBodyTypes } from "./core";
4
+ export declare class Body implements IBody {
5
+ readonly bodyUsed: boolean;
6
+ protected _length: number | null;
7
+ protected _mime?: string;
8
+ protected _body?: StorageBodyTypes | null;
9
+ private _used;
10
+ private _integrity?;
11
+ private _signal?;
12
+ constructor();
13
+ arrayBuffer(allowIncomplete?: boolean): Promise<ArrayBuffer>;
14
+ formData(): Promise<never>;
15
+ json(): Promise<any>;
16
+ text(allowIncomplete?: boolean): Promise<string>;
17
+ readable(): Promise<NodeJS.ReadableStream>;
18
+ protected setSignal(signal: AbortSignal | undefined): void;
19
+ protected hasBody(): boolean;
20
+ protected setBody(body: BodyTypes | IBody | null, mime?: string | null, integrity?: string | null, length?: number | null): void;
21
+ private awaitBuffer;
22
+ private validateIntegrity;
23
+ private _ensureNotAborted;
24
+ private _ensureUnused;
25
+ private blob;
26
+ }
27
+ export declare class JsonBody extends Body {
28
+ constructor(obj: any);
29
+ }
30
+ export declare class StreamBody extends Body {
31
+ constructor(readable: NodeJS.ReadableStream);
32
+ }
33
+ export declare class DataBody extends Body {
34
+ constructor(data: Buffer | string | null);
35
+ }
36
+ export declare class BodyInspector extends Body {
37
+ private _ref;
38
+ constructor(body: Body);
39
+ private _getMime;
40
+ private _getLength;
41
+ private _getBody;
42
+ get mime(): string | undefined;
43
+ get length(): number | null;
44
+ get stream(): NodeJS.ReadableStream | undefined;
45
+ }