webhoster 0.1.1 → 0.3.0

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.
Files changed (85) hide show
  1. package/.eslintrc.json +74 -58
  2. package/.github/copilot-instructions.md +100 -0
  3. package/.github/workflows/test-matrix.yml +37 -0
  4. package/.test/benchmark.js +28 -0
  5. package/.test/constants.js +4 -0
  6. package/{test → .test}/http2server.js +1 -1
  7. package/{test → .test}/httpserver.js +1 -1
  8. package/{test → .test}/index.js +178 -192
  9. package/.test/multipromise.js +32 -0
  10. package/{test → .test}/tls.js +3 -3
  11. package/{test → .test}/urlencoded.js +3 -0
  12. package/.vscode/launch.json +24 -3
  13. package/README.md +116 -90
  14. package/data/CookieObject.js +14 -14
  15. package/errata/socketio.js +6 -11
  16. package/examples/starter.js +11 -0
  17. package/helpers/HeadersParser.js +7 -8
  18. package/helpers/HttpListener.js +387 -42
  19. package/helpers/RequestHeaders.js +43 -36
  20. package/helpers/RequestReader.js +27 -26
  21. package/helpers/ResponseHeaders.js +47 -36
  22. package/jsconfig.json +1 -1
  23. package/lib/HttpHandler.js +447 -277
  24. package/lib/HttpRequest.js +383 -39
  25. package/lib/HttpResponse.js +316 -52
  26. package/lib/HttpTransaction.js +146 -0
  27. package/middleware/AutoHeadersMiddleware.js +73 -0
  28. package/middleware/CORSMiddleware.js +45 -47
  29. package/middleware/CaseInsensitiveHeadersMiddleware.js +5 -11
  30. package/middleware/ContentDecoderMiddleware.js +81 -35
  31. package/middleware/ContentEncoderMiddleware.js +179 -132
  32. package/middleware/ContentLengthMiddleware.js +66 -41
  33. package/middleware/ContentWriterMiddleware.js +5 -5
  34. package/middleware/HashMiddleware.js +68 -40
  35. package/middleware/HeadMethodMiddleware.js +24 -21
  36. package/middleware/MethodMiddleware.js +29 -36
  37. package/middleware/PathMiddleware.js +49 -66
  38. package/middleware/ReadFormData.js +99 -0
  39. package/middleware/SendJsonMiddleware.js +131 -0
  40. package/middleware/SendStringMiddleware.js +87 -0
  41. package/package.json +38 -29
  42. package/polyfill/FormData.js +164 -0
  43. package/rollup.config.js +0 -1
  44. package/scripts/test-all-sync.sh +6 -0
  45. package/scripts/test-all.sh +7 -0
  46. package/templates/starter.js +53 -0
  47. package/test/fixtures/stream.js +68 -0
  48. package/test/helpers/HttpListener/construct.js +18 -0
  49. package/test/helpers/HttpListener/customOptions.js +22 -0
  50. package/test/helpers/HttpListener/doubleCreate.js +40 -0
  51. package/test/helpers/HttpListener/events.js +77 -0
  52. package/test/helpers/HttpListener/http.js +31 -0
  53. package/test/helpers/HttpListener/http2.js +41 -0
  54. package/test/helpers/HttpListener/https.js +38 -0
  55. package/test/helpers/HttpListener/startAll.js +31 -0
  56. package/test/helpers/HttpListener/stopNotStarted.js +23 -0
  57. package/test/lib/HttpHandler/class.js +8 -0
  58. package/test/lib/HttpHandler/handleRequest.js +11 -0
  59. package/test/lib/HttpHandler/middleware.js +941 -0
  60. package/test/lib/HttpHandler/parse.js +41 -0
  61. package/test/lib/HttpRequest/class.js +8 -0
  62. package/test/lib/HttpRequest/downstream.js +171 -0
  63. package/test/lib/HttpRequest/properties.js +101 -0
  64. package/test/lib/HttpRequest/read.js +518 -0
  65. package/test/lib/HttpResponse/class.js +8 -0
  66. package/test/lib/HttpResponse/properties.js +59 -0
  67. package/test/lib/HttpResponse/send.js +275 -0
  68. package/test/lib/HttpTransaction/class.js +8 -0
  69. package/test/lib/HttpTransaction/ping.js +50 -0
  70. package/test/lib/HttpTransaction/push.js +89 -0
  71. package/test/middleware/SendJsonMiddleware.js +222 -0
  72. package/test/sanity.js +10 -0
  73. package/test/templates/starter.js +93 -0
  74. package/tsconfig.json +12 -0
  75. package/types/index.js +61 -34
  76. package/types/typings.d.ts +8 -9
  77. package/utils/AsyncObject.js +6 -3
  78. package/utils/CaseInsensitiveObject.js +2 -3
  79. package/utils/function.js +1 -7
  80. package/utils/headers.js +42 -0
  81. package/utils/qualityValues.js +1 -1
  82. package/utils/stream.js +4 -20
  83. package/index.cjs +0 -3190
  84. package/test/constants.js +0 -4
  85. /package/{test → .test}/cookietester.js +0 -0
@@ -1,68 +1,412 @@
1
- /** @typedef {import('stream').Readable} Readable */
1
+ import { Readable } from 'node:stream';
2
+ import { URLSearchParams } from 'node:url';
3
+
2
4
  /** @typedef {import('../types').RequestMethod} RequestMethod */
3
5
  /** @typedef {import('http').IncomingHttpHeaders} IncomingHttpHeaders */
6
+ /** @typedef {import('../types/index.js').MediaType} MediaType */
7
+
8
+ /** @typedef {Partial<MediaType> & {parse:(this:HttpRequest)=>any|PromiseLike<any>, test?:(this:HttpRequest, mediaType: MediaType)=>boolean}} ContentReaderRegistration */
9
+
10
+ /** @type {import('stream/consumers')} */
11
+ let streamConsumers;
12
+ try {
13
+ streamConsumers = await import(new URL('node:stream/consumers').toString());
14
+ } catch {}
15
+
16
+ let BlobClass = (typeof Blob === 'undefined' ? undefined : Blob);
4
17
 
5
18
  /**
6
- * @typedef {Object} HttpRequestOptions
7
- * @prop {RequestMethod} method always uppercase
8
- * @prop {URL} url
9
- * @prop {!IncomingHttpHeaders} headers
10
- * @prop {Object<string,any>} [locals]
19
+ * @typedef HttpRequestOptions
20
+ * @prop {IncomingHttpHeaders} [headers]
21
+ * @prop {RequestMethod} method
11
22
  * @prop {Readable} stream
12
- * @prop {import('net').Socket|import('tls').TLSSocket} [socket]
13
- * @prop {boolean} [canPing]
14
- * @prop {function():Promise<any>} [onPing]
15
- * @prop {boolean} [unsealed]
23
+ * @prop {string} href URL.href
24
+ * @prop {URL['origin']} origin URL.origin
25
+ * @prop {URL['protocol']} protocol URL.protocol
26
+ * @prop {URL['username']} username URL.username
27
+ * @prop {URL['password']} password URL.password
28
+ * @prop {URL['host']} host URL.host
29
+ * @prop {URL['hostname']} hostname URL.hostname
30
+ * @prop {URL['port']} port URL.port
31
+ * @prop {URL['pathname']} pathname URL.pathname
32
+ * @prop {URL['search']} search URL.search
33
+ * @prop {URL['hash']} hash URL.hash
34
+ * @prop {string} scheme
35
+ * @prop {string} authority
36
+ * @prop {string} path unparsed path
37
+ * @prop {string} url unparsed url
38
+ * @prop {string} query
39
+ * @prop {string} fragment
16
40
  */
17
41
 
42
+ /**
43
+ * @implements {URL}
44
+ */
18
45
  export default class HttpRequest {
19
- #canPing = false;
46
+ /** @type {ReadableStream} */
47
+ #readable;
48
+
49
+ #bodyUsed = false;
50
+
51
+ /** @type {MediaType} */
52
+ #mediaType;
53
+
54
+ /** @type {URLSearchParams} */
55
+ #searchParams;
56
+
57
+ /** @type {number} Minimum initial buffer size when working with chunks. Default 64KB */
58
+ MIN_INITIAL_BUFFER_SIZE = 16 * 1024;
20
59
 
21
- /** @type {function():Promise<any>} */
22
- #onPing = null;
60
+ /** @type {number} Maximium initial buffer size when working with chunks. Default 4MB */
61
+ MAX_INITIAL_BUFFER_SIZE = 4 * 1024 * 1024;
62
+
63
+ /** @type {number} Absolute maximum buffer size to be allocated per request. Default 64MB */
64
+ MAX_BUFFER_SIZE = 64 * 1024 * 1024;
65
+
66
+ /** @type {ContentReaderRegistration[]} */
67
+ contentReaders = [
68
+ { type: 'text', parse: this.text },
69
+ { type: 'application', subtype: 'json', parse: this.json },
70
+ { suffix: 'json', parse: this.json },
71
+ ];
23
72
 
24
73
  /** @param {HttpRequestOptions} options */
25
74
  constructor(options) {
26
- /** @type {RequestMethod} */
27
- this.method = (options.method.toUpperCase());
28
- this.url = options.url;
29
75
  /** @type {IncomingHttpHeaders} */
30
- this.headers = options.headers;
76
+ this.headers = options.headers ?? {};
77
+ this.method = options.method;
31
78
  this.stream = options.stream;
32
- this.socket = options.socket;
33
- this.#canPing = options.canPing ?? false;
34
- this.#onPing = options.onPing;
35
- this.locals = options.locals || {};
36
- this.unsealed = options.unsealed ?? false;
37
- if (!this.unsealed) {
38
- Object.seal(this);
79
+
80
+ this.href = options.href;
81
+ this.origin = options.origin;
82
+ this.protocol = options.protocol;
83
+ this.username = options.username;
84
+ this.password = options.password;
85
+ this.host = options.host;
86
+ this.hostname = options.hostname;
87
+ this.port = options.port;
88
+ this.pathname = options.pathname;
89
+ this.search = options.search;
90
+ this.hash = options.hash;
91
+
92
+ this.scheme = options.scheme;
93
+ this.authority = options.authority;
94
+ this.path = options.path;
95
+ this.query = options.query;
96
+ this.fragment = options.fragment;
97
+ this.url = options.url;
98
+ }
99
+
100
+ /**
101
+ * @param {import('stream').Duplex} downstream
102
+ * @param {Object} [options]
103
+ * @param {boolean} [options.forwardErrors=true] Forward errors back toward source
104
+ * @param {boolean} [options.autoPipe=true]
105
+ * @param {boolean} [options.autoDestroy=true] Ignored if auto-piping
106
+ * @param {boolean} [options.autoPause=false]
107
+ * @return {Readable} previous tailend stream
108
+ */
109
+ addDownstream(downstream, options = {}) {
110
+ const inputStream = this.stream;
111
+ this.stream = downstream;
112
+
113
+ if (!inputStream.readable) throw new Error('STREAM_NOT_READABLE');
114
+
115
+ if (options.forwardErrors !== false) {
116
+ downstream.on('error', (error) => inputStream.emit('error', error));
117
+ }
118
+
119
+ if (options.autoPipe !== false) {
120
+ inputStream.pipe(downstream);
121
+ } else if (options.autoDestroy !== false) {
122
+ inputStream.on('close', () => downstream.destroy());
123
+ inputStream.on('end', () => downstream.destroy());
39
124
  }
125
+
126
+ if (options.autoPause) {
127
+ inputStream.pause();
128
+ }
129
+
130
+ return inputStream;
40
131
  }
41
132
 
133
+ get bodyUsed() { return this.#bodyUsed; }
134
+
42
135
  /**
43
- * @param {Readable} stream
44
- * @return {Readable} previousStream
136
+ * @throws {Error<'NOT_SUPPORTED'>}
137
+ * @return {?ReadableStream}
45
138
  */
46
- replaceStream(stream) {
47
- const previousStream = this.stream;
48
- this.stream = stream;
49
- return previousStream;
139
+ get readable() {
140
+ if (this.#readable === undefined) {
141
+ if (this.method === 'GET' || this.method === 'HEAD') {
142
+ this.#readable = null;
143
+ } else if (Readable.toWeb) {
144
+ this.#readable = Readable.toWeb(this.stream);
145
+ this.#bodyUsed = true;
146
+ } else {
147
+ // Should use await .blob().stream() instead.
148
+ throw new Error('NOT_SUPPORTED');
149
+ }
150
+ }
151
+ return this.#readable;
50
152
  }
51
153
 
52
- get canPing() {
53
- return this.#canPing;
154
+ async read() {
155
+ if (this.method === 'GET' || this.method === 'HEAD') {
156
+ return this.searchParams;
157
+ }
158
+ const {
159
+ type, tree, subtype, suffix,
160
+ } = this.mediaType;
161
+ for (const entry of this.contentReaders) {
162
+ if (entry.type && entry.type !== type) continue;
163
+ if (entry.subtype && entry.subtype !== subtype) continue;
164
+ if (entry.tree && entry.tree !== tree) continue;
165
+ if (entry.suffix && entry.suffix !== suffix) continue;
166
+ if (entry.test && !entry.test.call(this, this.mediaType)) continue;
167
+ // eslint-disable-next-line @typescript-eslint/return-await, no-await-in-loop
168
+ return await entry.parse.call(this);
169
+ }
170
+ const chunks = [];
171
+ for await (const chunk of this.stream) {
172
+ chunks.push(chunk);
173
+ }
174
+ this.#bodyUsed = true;
175
+ if (!chunks.length) return null;
176
+ const [firstChunk] = chunks;
177
+ if (chunks.length === 1) return firstChunk;
178
+ if (Buffer.isBuffer(firstChunk)) {
179
+ return Buffer.concat(chunks);
180
+ }
181
+ if (typeof firstChunk === 'string') {
182
+ return chunks.join('');
183
+ }
184
+ return chunks;
54
185
  }
55
186
 
56
187
  /**
57
- * @return {Promise<any>}
188
+ * @throws {Error<'MAX_BUFFER_SIZE_REACHED'>}
189
+ * @return {Promise<Buffer>}
58
190
  */
59
- ping() {
60
- if (!this.#onPing) {
61
- return Promise.reject(new Error('NOT_IMPLEMENTED'));
191
+ async buffer() {
192
+ try {
193
+ if (streamConsumers) {
194
+ return await streamConsumers.buffer(this.stream);
195
+ }
196
+ let buffer;
197
+ let offset = 0;
198
+ const sourceEncoding = this.stream.readableEncoding;
199
+ for await (const c of this.stream) {
200
+ const chunk = sourceEncoding ? Buffer.from(c, sourceEncoding) : c;
201
+ if (!buffer) {
202
+ // Initial buffer allocation. Use content-length as reference, but not hard requirement.
203
+ // Size up to content-length, capped by MAX_INITIAL_BUFFER_SIZE
204
+ // Size down to chunk-length, capped by MIN_INITIAL_BUFFER_SIZE
205
+ const contentLength = Number.parseInt(this.headers['content-length'], 10);
206
+ const initialSize = (contentLength > 0 && chunk.length < contentLength)
207
+ ? Math.min(this.MAX_INITIAL_BUFFER_SIZE, contentLength)
208
+ : Math.max(chunk.length, this.MIN_INITIAL_BUFFER_SIZE);
209
+ buffer = Buffer.allocUnsafe(initialSize);
210
+ } else if (buffer.length < offset + chunk.length) {
211
+ if (buffer.length === this.MAX_BUFFER_SIZE) {
212
+ throw new Error('MAX_BUFFER_SIZE_REACHED');
213
+ }
214
+ const temporaryBuffer = buffer;
215
+ buffer = Buffer.allocUnsafe(Math.min(this.MAX_BUFFER_SIZE, temporaryBuffer.length * 2));
216
+ temporaryBuffer.copy(buffer, 0, 0, temporaryBuffer.length);
217
+ }
218
+ chunk.copy(buffer, offset, 0, chunk.length);
219
+ offset += chunk.length;
220
+ }
221
+ // Must partition to clear unsafe allocation
222
+ return buffer.slice(0, offset);
223
+ } finally {
224
+ this.#bodyUsed = true;
62
225
  }
63
- if (!this.#canPing) {
64
- return Promise.reject(new Error('NOT_SUPPORTED'));
226
+ }
227
+
228
+ /**
229
+ * @return {Promise<ArrayBuffer>}
230
+ */
231
+ async arrayBuffer() {
232
+ try {
233
+ if (streamConsumers) {
234
+ return await streamConsumers.arrayBuffer(this.stream);
235
+ }
236
+ const buffer = await this.buffer();
237
+ return buffer.buffer;
238
+ } finally {
239
+ this.#bodyUsed = true;
240
+ }
241
+ }
242
+
243
+ async blob() {
244
+ if (streamConsumers) {
245
+ const contentType = this.headers['content-type'];
246
+ // @ts-expect-error Bad typings
247
+ const result = await streamConsumers.blob(this.stream, {
248
+ type: contentType,
249
+ });
250
+ this.#bodyUsed = true;
251
+ if (!contentType || result.type === contentType) {
252
+ return result;
253
+ }
254
+ // Proxy needed to set type.
255
+ return new Proxy(result, {
256
+ get: (target, p, receiver) => {
257
+ if (p === 'type') return this.headers['content-type'];
258
+ return Reflect.get(target, p, receiver);
259
+ },
260
+ });
261
+ }
262
+
263
+ if (BlobClass === undefined) {
264
+ try {
265
+ const module = await import('node:buffer');
266
+ if ('Blob' in module === false) throw new Error('NOT_SUPPORTED');
267
+ BlobClass = module.Blob;
268
+ } catch {
269
+ BlobClass = null;
270
+ }
271
+ }
272
+
273
+ if (BlobClass === null) {
274
+ throw new Error('NOT_SUPPORTED');
275
+ }
276
+
277
+ try {
278
+ const chunks = [];
279
+ for await (const chunk of this.stream) { chunks.push(chunk); }
280
+ return new BlobClass(chunks, {
281
+ type: this.headers['content-type'],
282
+ });
283
+ } finally {
284
+ this.#bodyUsed = true;
285
+ }
286
+ }
287
+
288
+ async text() {
289
+ try {
290
+ const encoding = this.bufferEncoding;
291
+ if (encoding === 'utf-8' && streamConsumers) {
292
+ return await streamConsumers.text(this.stream);
293
+ }
294
+
295
+ // https://github.com/nodejs/node/blob/094b2a/lib/stream/consumers.js#L57
296
+ const dec = new TextDecoder(encoding === 'utf16le' ? 'utf-16le' : encoding);
297
+ let text = '';
298
+ for await (const chunk of this.stream) {
299
+ text += typeof chunk === 'string'
300
+ ? chunk
301
+ : dec.decode(chunk, { stream: true });
302
+ }
303
+ // Flush the streaming TextDecoder so that any pending
304
+ // incomplete multibyte characters are handled.
305
+ text += dec.decode(undefined, { stream: false });
306
+ return text;
307
+ } finally {
308
+ this.#bodyUsed = true;
309
+ }
310
+ }
311
+
312
+ /** @return {Promise<any>} */
313
+ async json() {
314
+ if (streamConsumers) {
315
+ this.#bodyUsed = true;
316
+ return await streamConsumers.json(this.stream);
317
+ }
318
+ const text = await this.text();
319
+ return JSON.parse(text);
320
+ }
321
+
322
+ get mediaType() {
323
+ if (!this.#mediaType) {
324
+ const contentType = this.headers['content-type'];
325
+ let type;
326
+ let tree;
327
+ let subtype;
328
+ let suffix;
329
+ /** @type {Record<string,string>} */
330
+ const parameters = {};
331
+ if (contentType) {
332
+ for (const directive of contentType.split(';')) {
333
+ let [key, value] = directive.split('=');
334
+ key = key.trim().toLowerCase();
335
+ if (value === undefined) {
336
+ let rest;
337
+ [type, rest] = key.split('/');
338
+ const treeEntries = rest.split('.');
339
+ const subtypeSuffix = treeEntries.pop();
340
+ tree = treeEntries.join('.');
341
+ [subtype, suffix] = subtypeSuffix.split('+');
342
+ continue;
343
+ }
344
+
345
+ value = value.trim();
346
+ const firstQuote = value.indexOf('"');
347
+ const lastQuote = value.lastIndexOf('"');
348
+ if (firstQuote !== -1 && lastQuote !== -1) {
349
+ if (firstQuote === lastQuote) {
350
+ throw new Error('ERR_CONTENT_TYPE');
351
+ }
352
+ value = value.slice(firstQuote + 1, lastQuote);
353
+ }
354
+ parameters[key] = value;
355
+ }
356
+ }
357
+ this.#mediaType = {
358
+ type, subtype, suffix, tree, parameters,
359
+ };
65
360
  }
66
- return this.#onPing();
361
+ return this.#mediaType;
362
+ }
363
+
364
+ /** @return {null|undefined|string} */
365
+ get charset() {
366
+ return this.mediaType.parameters.charset;
367
+ }
368
+
369
+ get bufferEncoding() {
370
+ const { charset } = this;
371
+ switch (charset?.toLowerCase()) {
372
+ case 'ucs-2':
373
+ case 'ucs2':
374
+ case 'utf-16le':
375
+ case 'utf16le':
376
+ return 'utf16le';
377
+ case 'utf-8':
378
+ case 'utf8':
379
+ return 'utf-8';
380
+ case 'base64':
381
+ case 'hex':
382
+ return /** @type {BufferEncoding} */ (charset);
383
+ case 'ascii': // Default
384
+ case 'binary':
385
+ case 'iso-8859-1':
386
+ case 'latin1':
387
+ default:
388
+ return 'latin1';
389
+ }
390
+ }
391
+
392
+ async formData() {
393
+ throw new Error('UNSUPPORTED_MEDIA_TYPE');
394
+ }
395
+
396
+ get searchParams() {
397
+ // eslint-disable-next-line no-return-assign
398
+ return this.#searchParams ??= new URLSearchParams(this.query);
399
+ }
400
+
401
+ toJSON() {
402
+ return this.href;
403
+ }
404
+
405
+ toString() {
406
+ return this.href;
407
+ }
408
+
409
+ get body() {
410
+ return this.readable;
67
411
  }
68
412
  }