weida-http 0.0.0-stage → 0.1.0-alpha.19

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/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # weida-http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ HTTP/1.1, HTTP/2 and HTTP/3 for Node, Bun and Deno, a client and a server: one Node-API addon over
4
+ `libweida_http`, the C ABI of the Rust [weida](https://weida.doodleshnookie.net/) HTTP library,
5
+ with an ES module and TypeScript types on top. The client pools connections, negotiates HTTP/2
6
+ over TLS by ALPN and speaks HTTP/3 over QUIC; the server binds TCP, TLS and QUIC listeners and
7
+ hands out one exchange per request. Bodies stream both ways, with trailers, under bounds you set.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install weida-http
13
+ ```
14
+
15
+ The package ships prebuilt binaries, so installing it needs no Rust toolchain and no compiler.
16
+
17
+ | Platform | Prebuild |
18
+ | --- | --- |
19
+ | Linux x64, Linux arm64 (glibc) | `linux-x64`, `linux-arm64` |
20
+ | macOS on Apple silicon | `darwin-arm64` |
21
+ | Windows x64 | `win32-x64` |
22
+
23
+ It runs on Node 20 and later, on Bun, and on Deno with `--allow-read --allow-env --allow-ffi`
24
+ (the sockets are the native library's, so Deno needs no `--allow-net`). With `weida-native-full`
25
+ installed at the same version, it and `weida` share one native library (`weida/http` is this
26
+ package).
27
+
28
+ ## Example
29
+
30
+ ```js
31
+ import * as http from "weida-http";
32
+
33
+ const server = new http.Server();
34
+ const address = await server.bindTcp("127.0.0.1:0");
35
+
36
+ const serving = (async () => {
37
+ for await (const exchange of server) {
38
+ await exchange.respond(200, {
39
+ headers: { "content-type": "text/plain" },
40
+ body: new TextEncoder().encode("hello"),
41
+ });
42
+ exchange.drop();
43
+ }
44
+ })();
45
+
46
+ const client = new http.Client();
47
+ const response = await client.request("GET", `http://127.0.0.1:${address.port}/`);
48
+ console.log(response.status, new TextDecoder().decode(await response.read(1 << 20)));
49
+
50
+ await server.close();
51
+ await serving;
52
+ ```
53
+
54
+ The JavaScript thread never blocks: every wait is a promise, and every waiting method takes
55
+ `{ signal }`, so `AbortSignal.timeout(ms)` is the timeout. A body is `for await (const chunk of
56
+ response)` or `await response.read(max)` under a cap you choose (`null` asks for none by name).
57
+ Durations are milliseconds. Failures are one class, `HttpError`, to branch on by `error.kind`
58
+ (`"Io"`, `"Timeout"`, `"TooLarge"`, ...) or `error.code` (`"WEIDA_HTTP_ETOO_LARGE"`).
59
+
60
+ ## Learn more
61
+
62
+ - [Website](https://weida.doodleshnookie.net/) and this package's
63
+ [feature sheet](https://weida.doodleshnookie.net/libraries/http-js/) with every class and
64
+ method
65
+ - [Repository](https://github.com/tuco86/weida), package in `crates/js/weida-http`
66
+
67
+ Status: alpha (`0.1.0-alpha.N`); breaking changes are permitted within `0.x`.
68
+
69
+ ## License
70
+
71
+ MIT OR Apache-2.0, at your option.
package/lib/errors.js ADDED
@@ -0,0 +1,31 @@
1
+ // The one error class every failure of libweida_http throws (docs/c/README.md
2
+ // R9, docs/libraries/http-js.md section 7): the shared base's `code` and
3
+ // `errno`, the kind of failure it is, and libweida_http's thread-local
4
+ // record, which the addon sets from the call that failed.
5
+ import native from "./native.js";
6
+ import { WeidaError } from "./shared/errors.js";
7
+
8
+ export class HttpError extends WeidaError {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "HttpError";
12
+ /** What failed, as the Python package names its exception class: "Io",
13
+ * "Timeout", "Reset", "TooLarge", "InvalidUrl", ...; "HttpError" for a
14
+ * code this package does not know. */
15
+ this.kind = "HttpError";
16
+ /** What the library names beyond the message: the step of a "Timeout"
17
+ * (`the TCP connect`, ...), the feature of an "Unsupported"
18
+ * (`CONNECT`, ...). */
19
+ this.condition = null;
20
+ /** The raw OS error of an "Io" failure, when it carried one. */
21
+ this.osCode = null;
22
+ /** The error code of a "Reset": HTTP/2's RST_STREAM or HTTP/3's stream
23
+ * reset code, saturated to a C int. */
24
+ this.reasonCode = null;
25
+ /** The cap of a "TooLarge", in bytes: a number, or a BigInt past
26
+ * Number.MAX_SAFE_INTEGER. */
27
+ this.max = null;
28
+ }
29
+ }
30
+
31
+ native.setErrorClass(HttpError);
package/lib/index.d.ts ADDED
@@ -0,0 +1,349 @@
1
+ // Types of weida-http (lib/index.js; docs/libraries/http-js.md).
2
+ import type { KeyObject, X509Certificate } from "node:crypto";
3
+
4
+ /** Bytes: a Uint8Array (a Buffer is one), another ArrayBuffer view or an
5
+ * ArrayBuffer. A string is refused. */
6
+ export type Bytes = Uint8Array | ArrayBufferView | ArrayBuffer;
7
+
8
+ /** An integer a C `uint64_t` holds: a number up to Number.MAX_SAFE_INTEGER,
9
+ * or a BigInt. */
10
+ export type Count = number | bigint;
11
+
12
+ export interface Signal {
13
+ signal?: AbortSignal;
14
+ }
15
+
16
+ /** What failed, as the Python package names its exception class. */
17
+ export type HttpErrorKind =
18
+ | "Io"
19
+ | "Runtime"
20
+ | "DecodeError"
21
+ | "EncodeError"
22
+ | "Tls"
23
+ | "Timeout"
24
+ | "ProtocolError"
25
+ | "Reset"
26
+ | "GoingAway"
27
+ | "ConnectionClosed"
28
+ | "TooLarge"
29
+ | "Unsupported"
30
+ | "Configuration"
31
+ | "InvalidUrl"
32
+ | "InvalidArgument"
33
+ | "Closed"
34
+ | "Panic"
35
+ | "Interrupted"
36
+ | "HttpError";
37
+
38
+ /** Every failure of libweida_http. */
39
+ export class HttpError extends Error {
40
+ readonly name: "HttpError";
41
+ /** The R9 constant name, e.g. "WEIDA_HTTP_ETOO_LARGE"; null for a code
42
+ * this package does not know. */
43
+ code: string | null;
44
+ /** The positive status code. */
45
+ errno: number;
46
+ /** What failed: the name of the Python package's exception class. */
47
+ kind: HttpErrorKind;
48
+ /** The step of a "Timeout", the feature of an "Unsupported". */
49
+ condition: string | null;
50
+ /** The raw OS error of an "Io" failure, when it carried one. */
51
+ osCode: number | null;
52
+ /** The stream reset code of a "Reset". */
53
+ reasonCode: number | null;
54
+ /** The cap of a "TooLarge", in bytes. */
55
+ max: Count | null;
56
+ }
57
+
58
+ /** Every constant of weida_http.h by name. */
59
+ export const CONSTANTS: Readonly<Record<string, number>>;
60
+ export const DEFAULT_MAX_HEAD_BYTES: number;
61
+ export const DEFAULT_MAX_FIELDS: number;
62
+ export const DEFAULT_MAX_CHUNK_LINE: number;
63
+ export const DEFAULT_MAX_FRAME_SIZE: number;
64
+
65
+ export function version(): string;
66
+ export function libraryPath(): string;
67
+ export function strerror(code: number): string;
68
+
69
+ /** Request methods; any token is one. */
70
+ export const Method: Readonly<{
71
+ GET: "GET";
72
+ HEAD: "HEAD";
73
+ POST: "POST";
74
+ PUT: "PUT";
75
+ DELETE: "DELETE";
76
+ OPTIONS: "OPTIONS";
77
+ PATCH: "PATCH";
78
+ TRACE: "TRACE";
79
+ CONNECT: "CONNECT";
80
+ /** The token, or kind "EncodeError". */
81
+ check(token: string): string;
82
+ }>;
83
+
84
+ /** Response statuses; any integer from 100 to 999 is one. */
85
+ export const Status: Readonly<{
86
+ OK: 200;
87
+ NO_CONTENT: 204;
88
+ BAD_REQUEST: 400;
89
+ NOT_FOUND: 404;
90
+ INTERNAL_SERVER_ERROR: 500;
91
+ NOT_IMPLEMENTED: 501;
92
+ /** The code, or kind "ProtocolError". */
93
+ check(code: number): number;
94
+ isInformational(code: number): boolean;
95
+ isSuccess(code: number): boolean;
96
+ isRedirection(code: number): boolean;
97
+ }>;
98
+
99
+ export type Version = "HTTP/1.1" | "HTTP/2" | "HTTP/3";
100
+ export const Version: Readonly<{ HTTP11: "HTTP/1.1"; HTTP2: "HTTP/2"; HTTP3: "HTTP/3" }>;
101
+
102
+ export type Protocol = "auto" | "http1" | "http2" | "http3";
103
+ export const Protocol: Readonly<{ AUTO: "auto"; HTTP1: "http1"; HTTP2: "http2"; HTTP3: "http3" }>;
104
+
105
+ export type ClientAuth = "none" | "optional" | "required";
106
+ export const ClientAuth: Readonly<{ NONE: "none"; OPTIONAL: "optional"; REQUIRED: "required" }>;
107
+
108
+ /** A field value: a string (ISO-8859-1) or bytes. */
109
+ export type FieldValue = string | Bytes;
110
+
111
+ /** What a `headers` or `trailers` option takes. */
112
+ export type FieldsInit = Fields | Record<string, FieldValue> | Iterable<readonly [string, FieldValue]>;
113
+
114
+ /** The fields of an HTTP message, in order, names case-insensitive. */
115
+ export class Fields implements Iterable<[string, string]> {
116
+ constructor(items?: FieldsInit | null);
117
+ add(name: string, value: FieldValue, options?: { sensitive?: boolean }): void;
118
+ set(name: string, value: FieldValue): void;
119
+ remove(name: string): boolean;
120
+ get(name: string): string | null;
121
+ get<T>(name: string, fallback: T): string | T;
122
+ getAll(name: string): string[];
123
+ has(name: string): boolean;
124
+ readonly size: number;
125
+ raw(): Array<[string, Uint8Array]>;
126
+ copy(): Fields;
127
+ equals(other: unknown): boolean;
128
+ [Symbol.iterator](): Iterator<[string, string]>;
129
+ toString(): string;
130
+ }
131
+
132
+ /** An absolute http or https URL, parsed by the library. */
133
+ export class Url {
134
+ constructor(input: string);
135
+ static parse(input: string): Url;
136
+ readonly scheme: "http" | "https";
137
+ readonly host: string;
138
+ readonly port: number;
139
+ readonly pathAndQuery: string;
140
+ readonly authority: string;
141
+ toString(): string;
142
+ toJSON(): string;
143
+ equals(other: unknown): boolean;
144
+ }
145
+
146
+ /** Where a listener bound. */
147
+ export class Address {
148
+ constructor(host: string, port: number);
149
+ static parse(input: string): Address;
150
+ readonly host: string;
151
+ readonly port: number;
152
+ toString(): string;
153
+ toJSON(): string;
154
+ }
155
+
156
+ export interface LimitsOptions {
157
+ maxHeadBytes?: Count | null;
158
+ maxFields?: Count | null;
159
+ maxChunkLine?: Count | null;
160
+ maxFrameSize?: number | null;
161
+ }
162
+
163
+ export class Limits {
164
+ constructor(options?: LimitsOptions);
165
+ readonly maxHeadBytes: Count | null;
166
+ readonly maxFields: Count | null;
167
+ readonly maxChunkLine: Count | null;
168
+ readonly maxFrameSize: number | null;
169
+ }
170
+
171
+ /** A trust anchor: PEM bytes, an X509Certificate, or the path of a PEM file
172
+ * (a string or a file: URL). */
173
+ export type Anchor = Uint8Array | X509Certificate | string | URL;
174
+
175
+ /** A certificate and its private key. */
176
+ export interface Identity {
177
+ cert: Uint8Array | X509Certificate | X509Certificate[];
178
+ key: Uint8Array | KeyObject;
179
+ }
180
+
181
+ export interface ClientTlsOptions {
182
+ ca?: Anchor | Anchor[] | null;
183
+ identity?: Identity | null;
184
+ verify?: boolean;
185
+ }
186
+
187
+ export class ClientTls {
188
+ constructor(options?: ClientTlsOptions);
189
+ readonly ca: readonly Anchor[];
190
+ readonly identity: Readonly<Identity> | null;
191
+ readonly verify: boolean;
192
+ }
193
+
194
+ export interface ServerTlsOptions {
195
+ clientCa?: Anchor | Anchor[] | null;
196
+ clientAuth?: ClientAuth;
197
+ }
198
+
199
+ export class ServerTls {
200
+ constructor(identity: Identity, options?: ServerTlsOptions);
201
+ readonly identity: Readonly<Identity>;
202
+ readonly clientCa: readonly Uint8Array[];
203
+ readonly clientAuth: ClientAuth;
204
+ }
205
+
206
+ export interface ClientOptionsInit {
207
+ tls?: ClientTls | null;
208
+ protocol?: Protocol | null;
209
+ connectTimeoutMs?: number | null;
210
+ idleTimeoutMs?: number | null;
211
+ maxIdlePerOrigin?: Count | null;
212
+ maxResolvedAddresses?: Count | null;
213
+ streamWindow?: number | null;
214
+ connectionWindow?: number | null;
215
+ limits?: Limits | null;
216
+ }
217
+
218
+ export class ClientOptions {
219
+ constructor(options?: ClientOptionsInit);
220
+ readonly tls: ClientTls | null;
221
+ readonly protocol: Protocol | null;
222
+ readonly connectTimeoutMs: number | null;
223
+ readonly idleTimeoutMs: number | null;
224
+ readonly maxIdlePerOrigin: Count | null;
225
+ readonly maxResolvedAddresses: Count | null;
226
+ readonly streamWindow: number | null;
227
+ readonly connectionWindow: number | null;
228
+ readonly limits: Limits | null;
229
+ }
230
+
231
+ export interface ServerOptionsInit {
232
+ maxConnections?: Count | null;
233
+ acceptQueue?: Count | null;
234
+ maxConcurrentStreams?: number | null;
235
+ headerTimeoutMs?: number | null;
236
+ idleTimeoutMs?: number | null;
237
+ closeTimeoutMs?: number | null;
238
+ streamWindow?: number | null;
239
+ connectionWindow?: number | null;
240
+ limits?: Limits | null;
241
+ }
242
+
243
+ export class ServerOptions {
244
+ constructor(options?: ServerOptionsInit);
245
+ readonly maxConnections: Count | null;
246
+ readonly acceptQueue: Count | null;
247
+ readonly maxConcurrentStreams: number | null;
248
+ readonly headerTimeoutMs: number | null;
249
+ readonly idleTimeoutMs: number | null;
250
+ readonly closeTimeoutMs: number | null;
251
+ readonly streamWindow: number | null;
252
+ readonly connectionWindow: number | null;
253
+ readonly limits: Limits | null;
254
+ }
255
+
256
+ /** An object that owns a native handle. */
257
+ declare class Handle {
258
+ /** Releases the handle now; pending waits end with kind "Closed". */
259
+ drop(): void;
260
+ [Symbol.dispose](): void;
261
+ }
262
+
263
+ export class Context extends Handle {
264
+ constructor(options?: { workerThreads?: Count | null });
265
+ static owned(workerThreads?: Count | null): Context;
266
+ /** Always throws kind "Runtime". */
267
+ static current(): never;
268
+ static sharing(other: Context): Context;
269
+ }
270
+
271
+ /** A body that arrives: a stream of chunks. */
272
+ export class Body extends Handle implements AsyncIterable<Uint8Array> {
273
+ private constructor();
274
+ recv(options?: Signal): Promise<Uint8Array | null>;
275
+ /** The rest of the body under the cap `max`; null for no cap. */
276
+ read(max: Count | null, options?: Signal): Promise<Uint8Array>;
277
+ readonly contentLength: Count | null;
278
+ readonly trailers: Fields | null;
279
+ stream(): ReadableStream<Uint8Array>;
280
+ [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
281
+ }
282
+
283
+ declare class Message extends Handle implements AsyncIterable<Uint8Array> {
284
+ readonly body: Body;
285
+ readonly contentLength: Count | null;
286
+ readonly trailers: Fields | null;
287
+ read(max: Count | null, options?: Signal): Promise<Uint8Array>;
288
+ [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
289
+ }
290
+
291
+ export class Response extends Message {
292
+ private constructor();
293
+ readonly status: number;
294
+ readonly version: Version;
295
+ readonly headers: Fields;
296
+ }
297
+
298
+ export class OpenRequest extends Handle {
299
+ private constructor();
300
+ write(data: Bytes, options?: Signal): Promise<void>;
301
+ finish(options?: { trailers?: FieldsInit | null; signal?: AbortSignal }): Promise<Response>;
302
+ }
303
+
304
+ export interface RequestOptions extends Signal {
305
+ headers?: FieldsInit | null;
306
+ body?: Bytes | null;
307
+ }
308
+
309
+ export class Client extends Handle {
310
+ constructor(options?: ClientOptions | null, how?: { context?: Context | null });
311
+ request(method: string, url: string | Url | URL, options?: RequestOptions): Promise<Response>;
312
+ open(
313
+ method: string,
314
+ url: string | Url | URL,
315
+ options?: { headers?: FieldsInit | null; signal?: AbortSignal },
316
+ ): Promise<OpenRequest>;
317
+ }
318
+
319
+ export class BodyWriter extends Handle {
320
+ private constructor();
321
+ write(data: Bytes, options?: Signal): Promise<void>;
322
+ finish(options?: { trailers?: FieldsInit | null; signal?: AbortSignal }): Promise<void>;
323
+ }
324
+
325
+ export class Exchange extends Message {
326
+ private constructor();
327
+ readonly method: string;
328
+ readonly scheme: "http" | "https";
329
+ readonly authority: string;
330
+ readonly path: string;
331
+ readonly version: Version;
332
+ readonly peer: string;
333
+ readonly headers: Fields;
334
+ respond(status: number, options?: RequestOptions): Promise<void>;
335
+ respondStream(status: number, options?: { headers?: FieldsInit | null; signal?: AbortSignal }): Promise<BodyWriter>;
336
+ }
337
+
338
+ /** A bind address: `ip:port` text, an Address or `{ host, port }`. */
339
+ export type BindAddress = string | Address | { host: string; port: number };
340
+
341
+ export class Server extends Handle implements AsyncIterable<Exchange> {
342
+ constructor(options?: ServerOptions | null, how?: { context?: Context | null });
343
+ bindTcp(address: BindAddress, options?: Signal): Promise<Address>;
344
+ bindTls(address: BindAddress, tls: ServerTls, options?: Signal): Promise<Address>;
345
+ bindQuic(address: BindAddress, tls: ServerTls, options?: Signal): Promise<Address>;
346
+ accept(options?: Signal): Promise<Exchange>;
347
+ close(options?: Signal): Promise<void>;
348
+ [Symbol.asyncIterator](): AsyncIterator<Exchange>;
349
+ }