@e-mc/request 0.10.9 → 0.10.11

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
@@ -9,7 +9,7 @@
9
9
 
10
10
  ## Interface
11
11
 
12
- * [View Source](https://www.unpkg.com/@e-mc/types@0.10.9/lib/index.d.ts)
12
+ * [View Source](https://www.unpkg.com/@e-mc/types@0.10.11/lib/index.d.ts)
13
13
 
14
14
  ```typescript
15
15
  import type { IModule, ModuleConstructor } from "./index";
@@ -205,9 +205,9 @@ instance.get("http://hostname/path/config.yml", options).then(data => {
205
205
 
206
206
  ## References
207
207
 
208
- - https://www.unpkg.com/@e-mc/types@0.10.9/lib/http.d.ts
209
- - https://www.unpkg.com/@e-mc/types@0.10.9/lib/request.d.ts
210
- - https://www.unpkg.com/@e-mc/types@0.10.9/lib/settings.d.ts
208
+ - https://www.unpkg.com/@e-mc/types@0.10.11/lib/http.d.ts
209
+ - https://www.unpkg.com/@e-mc/types@0.10.11/lib/request.d.ts
210
+ - https://www.unpkg.com/@e-mc/types@0.10.11/lib/settings.d.ts
211
211
 
212
212
  * https://www.npmjs.com/package/@types/node
213
213
 
package/index.js CHANGED
@@ -676,7 +676,7 @@ class Fetch {
676
676
  }
677
677
  dataLength = Buffer.byteLength(buffer, encoding);
678
678
  if (mibsTime) {
679
- messageUnit = (0, util_1.getTransferRate)(dataLength, (0, types_1.convertTime)(process.hrtime(mibsTime), false) * 1000);
679
+ messageUnit = this.formatMibs(dataLength, mibsTime);
680
680
  }
681
681
  if (contentLength > 0) {
682
682
  parent.updateProgress("request", progressId, dataLength, dataLength);
@@ -730,6 +730,9 @@ class Fetch {
730
730
  this.terminate("No data received");
731
731
  return;
732
732
  }
733
+ if (mibsTime && (contentLength > 0 || typeof pipeTo === 'string')) {
734
+ messageUnit = this.formatMibs(contentLength || (0, util_1.getSize)(pipeTo), mibsTime);
735
+ }
733
736
  result = encoding && !pipeline ? '' : null;
734
737
  titleBgColor = 'bgBlue';
735
738
  }
@@ -843,6 +846,11 @@ class Fetch {
843
846
  formatRetry(message) {
844
847
  return message + ` (${this.retries} / ${this.retryLimit})`;
845
848
  }
849
+ formatMibs(dataLength, mibsTime) {
850
+ if (dataLength > 0) {
851
+ return (0, util_1.getTransferRate)(dataLength, Math.max(1, (0, types_1.convertTime)(process.hrtime(mibsTime), false) * 1000));
852
+ }
853
+ }
846
854
  close() {
847
855
  if (this.timeout) {
848
856
  clearTimeout(this.timeout);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e-mc/request",
3
- "version": "0.10.9",
3
+ "version": "0.10.11",
4
4
  "description": "Request constructor for E-mc.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -20,8 +20,8 @@
20
20
  "license": "BSD-3-Clause",
21
21
  "homepage": "https://github.com/anpham6/e-mc#readme",
22
22
  "dependencies": {
23
- "@e-mc/module": "0.10.9",
24
- "@e-mc/types": "0.10.9",
23
+ "@e-mc/module": "0.10.11",
24
+ "@e-mc/types": "0.10.11",
25
25
  "combined-stream": "^1.0.8",
26
26
  "js-yaml": "^4.1.0",
27
27
  "picomatch": "^4.0.2",
@@ -1,559 +0,0 @@
1
- "use strict";
2
- const fs = require("node:fs");
3
- const http2 = require("node:http2");
4
- const yaml = require("js-yaml");
5
- const types_1 = require("@e-mc/types");
6
- const module_1 = require("@e-mc/module");
7
- const util_1 = require("@e-mc/request/util");
8
- let LOG_TIMEFORMAT = 'readable';
9
- class HttpAdapter {
10
- instance;
11
- state;
12
- uri;
13
- static isUnsupported(value) {
14
- return value === 421 || value === 505;
15
- }
16
- static isDowngrade(err) {
17
- return err instanceof Error && (err.code === 'ERR_HTTP2_ERROR' || this.isUnsupported(Math.abs(err.errno)));
18
- }
19
- static wasAborted(err) {
20
- return err instanceof Error && err.message.startsWith("Aborted");
21
- }
22
- static isConnectionError(err) {
23
- switch (err instanceof Error && err.code) {
24
- case 'ETIMEDOUT':
25
- case 'ECONNRESET':
26
- return true;
27
- default:
28
- return false;
29
- }
30
- }
31
- static defineHostConfig({ settings }) {
32
- const time_format = settings?.time_format;
33
- switch (time_format) {
34
- case 'readable':
35
- case 'relative':
36
- case 'none':
37
- LOG_TIMEFORMAT = time_format;
38
- break;
39
- }
40
- }
41
- contentLength = 0;
42
- retries = 0;
43
- redirects = 0;
44
- closed = false;
45
- aborted = false;
46
- timeout = null;
47
- dataTime = null;
48
- delayTime = undefined;
49
- opts;
50
- client;
51
- resolve;
52
- reject;
53
- startTime;
54
- #outStream = null;
55
- #options;
56
- constructor(instance, state, uri, options) {
57
- this.instance = instance;
58
- this.state = state;
59
- this.uri = uri;
60
- this.#options = options;
61
- this.startTime = state.log ? process.hrtime.bigint() : BigInt(0);
62
- this.setOpts();
63
- }
64
- async start() {
65
- return new Promise((resolve, reject) => {
66
- this.resolve = resolve;
67
- this.reject = reject;
68
- this.init();
69
- });
70
- }
71
- init() {
72
- this.aborted = false;
73
- this.setWriteStream();
74
- this.client = this.instance.open(this.uri, this.opts);
75
- if (this.opts.httpVersion === 2) {
76
- this.client
77
- .on('response', (headers, flags) => {
78
- if (this.destroyed) {
79
- return;
80
- }
81
- const statusCode = headers[':status'];
82
- if (statusCode < 300) {
83
- this.acceptResponse(headers);
84
- }
85
- else if (statusCode < 400) {
86
- this.redirectResponse(statusCode, headers.location);
87
- }
88
- else if (statusCode === 401 ||
89
- statusCode === 402 ||
90
- statusCode === 403 ||
91
- statusCode === 404 ||
92
- statusCode === 407 ||
93
- statusCode === 410) {
94
- this.terminate(this.formatStatus(statusCode));
95
- }
96
- else if (this.isRetry(statusCode)) {
97
- this.retryResponse(statusCode, headers['retry-after']);
98
- }
99
- else if (HttpAdapter.isUnsupported(statusCode)) {
100
- this.retryDownload(true, this.#formatNgFlags(http2.constants.NGHTTP2_PROTOCOL_ERROR, statusCode));
101
- }
102
- else {
103
- switch (flags) {
104
- case http2.constants.NGHTTP2_PROTOCOL_ERROR:
105
- case http2.constants.NGHTTP2_INADEQUATE_SECURITY:
106
- case http2.constants.NGHTTP2_HTTP_1_1_REQUIRED:
107
- this.retryDownload(true, this.#formatNgFlags(flags, statusCode, headers.location));
108
- break;
109
- default:
110
- this.retryDownload(false, this.formatStatus(statusCode));
111
- break;
112
- }
113
- }
114
- })
115
- .on('unknownProtocol', () => {
116
- if (this.aborted) {
117
- return;
118
- }
119
- this.retryDownload(true, 'Unknown protocol (HTTP/2)');
120
- })
121
- .on('aborted', () => {
122
- this.aborted = true;
123
- this.terminate((0, types_1.createAbortError)());
124
- })
125
- .on('error', async (err) => {
126
- if (this.aborted) {
127
- return;
128
- }
129
- if (HttpAdapter.wasAborted(err)) {
130
- this.errorResponse(err);
131
- }
132
- else {
133
- switch (!HttpAdapter.isDowngrade(err) && await this.host.hasProtocol(2)) {
134
- case 1:
135
- this.errorResponse(err);
136
- break;
137
- case 2:
138
- this.retryDownload(false, err);
139
- break;
140
- default:
141
- this.retryDownload(true, err);
142
- break;
143
- }
144
- }
145
- });
146
- }
147
- else {
148
- this.client
149
- .on('response', res => {
150
- if (this.destroyed) {
151
- return;
152
- }
153
- const statusCode = res.statusCode;
154
- if (statusCode < 300) {
155
- this.acceptResponse(res.headers);
156
- }
157
- else if (statusCode < 400) {
158
- this.redirectResponse(statusCode, res.headers.location);
159
- }
160
- else if (this.isRetry(statusCode)) {
161
- this.retryResponse(statusCode, res.headers['retry-after']);
162
- }
163
- else {
164
- this.terminate(this.formatStatus(statusCode));
165
- }
166
- })
167
- .on('abort', () => {
168
- this.aborted = true;
169
- this.terminate((0, types_1.createAbortError)());
170
- })
171
- .on('error', err => {
172
- if (this.aborted) {
173
- return;
174
- }
175
- this.errorResponse(err);
176
- });
177
- }
178
- this.client.on('timeout', () => {
179
- if (this.aborted) {
180
- return;
181
- }
182
- if (++this.retries <= this.retryLimit) {
183
- this.abortResponse();
184
- this.retryTimeout();
185
- }
186
- else {
187
- this.terminate(this.formatStatus(408));
188
- }
189
- });
190
- }
191
- setOpts(uri) {
192
- if (uri) {
193
- this.uri = uri;
194
- }
195
- this.opts = this.instance.opts(this.uri, this.#options);
196
- }
197
- setWriteStream() {
198
- const pipeTo = this.pipeTo;
199
- if (typeof pipeTo === 'string') {
200
- try {
201
- this.outStream = fs.createWriteStream(pipeTo, { emitClose: false, highWaterMark: this.host.streamSize });
202
- }
203
- catch (err) {
204
- this.terminate(err);
205
- }
206
- }
207
- else if (pipeTo) {
208
- this.outStream = pipeTo;
209
- }
210
- }
211
- retryDownload(downgrade, message) {
212
- if (this.aborted) {
213
- return;
214
- }
215
- this.abortResponse();
216
- if (downgrade) {
217
- const host = this.host;
218
- host.failed(2);
219
- if (host.version > 1) {
220
- if (this.state.verbose) {
221
- this.instance.formatMessage(1024, 'HTTP2', ["Unsupported protocol", host.origin], message, { failed: true });
222
- }
223
- host.version = 1;
224
- }
225
- }
226
- this.opts.httpVersion = 1;
227
- this.init();
228
- }
229
- acceptResponse(headers) {
230
- const opts = this.opts;
231
- if ('outHeaders' in opts) {
232
- opts.outHeaders = headers;
233
- }
234
- if ('outFilename' in opts) {
235
- opts.outFilename = (0, util_1.parseHeader)(headers, 'content-disposition');
236
- }
237
- const pipeline = this.pipeTo ? !(0, types_1.isString)(this.pipeTo) : false;
238
- const enabled = opts.connected?.call(this.client, headers) !== false && !pipeline;
239
- const maxBufferSize = opts.maxBufferSize ? (0, types_1.alignSize)(opts.maxBufferSize) : 0;
240
- this.contentLength = parseInt(headers['content-length'] || '0');
241
- const updating = opts.progressId !== undefined && !!this.instance.host && this.contentLength > 0;
242
- const readTimeout = this.instance.readTimeout;
243
- let log = this.state.log, buffer = null, dataLength = 0;
244
- this.client.once('readable', () => {
245
- if (readTimeout > 0) {
246
- this.timeout = setTimeout(() => {
247
- this.terminate((0, types_1.errorValue)("Timeout was exceeded", this.uri.toString()));
248
- }, readTimeout);
249
- }
250
- if (log) {
251
- switch (this.instance.settings?.time_format || LOG_TIMEFORMAT) {
252
- case 'readable':
253
- this.delayTime = process.hrtime.bigint() - this.startTime;
254
- break;
255
- case 'relative':
256
- this.delayTime = Date.now() - this.instance.startTime;
257
- break;
258
- case 'none':
259
- if (!this.silent) {
260
- log = false;
261
- }
262
- break;
263
- }
264
- }
265
- this.dataTime = process.hrtime.bigint();
266
- if (updating) {
267
- this.updateProgress(0, 0);
268
- }
269
- });
270
- if (enabled) {
271
- const encoding = opts.encoding;
272
- this.client.on('data', (chunk) => {
273
- if (buffer) {
274
- if (typeof buffer === 'string') {
275
- buffer += typeof chunk === 'string' ? chunk : chunk.toString(encoding);
276
- }
277
- else if (Array.isArray(buffer)) {
278
- buffer.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk);
279
- }
280
- else {
281
- buffer = Buffer.concat([buffer, typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk]);
282
- }
283
- }
284
- else {
285
- buffer = typeof chunk === 'string' ? chunk : [chunk];
286
- }
287
- if (updating) {
288
- dataLength += Buffer.byteLength(chunk, encoding);
289
- this.updateProgress(dataLength, this.contentLength);
290
- }
291
- if (maxBufferSize > 0) {
292
- if (!updating) {
293
- dataLength += Buffer.byteLength(chunk, encoding);
294
- }
295
- if (dataLength > maxBufferSize) {
296
- this.terminate((0, types_1.errorValue)("Size limit was exceeded", this.uri.toString()));
297
- }
298
- }
299
- });
300
- }
301
- this.client.once('end', () => {
302
- if (this.closed || this.aborted) {
303
- return;
304
- }
305
- this.close();
306
- const encoding = opts.encoding;
307
- let result;
308
- if (buffer) {
309
- if (Array.isArray(buffer)) {
310
- buffer = Buffer.concat(buffer);
311
- if (encoding) {
312
- buffer = buffer.toString(encoding);
313
- }
314
- }
315
- dataLength = Buffer.byteLength(buffer, encoding);
316
- if (updating) {
317
- this.updateProgress(dataLength, dataLength);
318
- }
319
- if (typeof buffer === 'string') {
320
- if (buffer.startsWith('\uFEFF') && encoding !== 'utf16le' && encoding !== 'utf-16le') {
321
- buffer = buffer.substring(1);
322
- }
323
- if (opts.outFormat) {
324
- const { out: format, parser } = opts.outFormat;
325
- let packageName;
326
- try {
327
- switch (format) {
328
- case 'yaml':
329
- result = yaml.load(buffer, parser);
330
- break;
331
- case 'json5':
332
- result = require(packageName = 'json5').parse(buffer);
333
- break;
334
- case 'xml':
335
- result = new (require(packageName = 'fast-xml-parser').XMLParser)(parser).parse(buffer);
336
- break;
337
- case 'toml':
338
- result = require(packageName = 'toml').parse(buffer);
339
- break;
340
- default:
341
- result = JSON.parse(buffer);
342
- break;
343
- }
344
- if (!(0, types_1.isObject)(result)) {
345
- result = null;
346
- }
347
- }
348
- catch (err) {
349
- if (this.state.verbose && !(packageName && this.instance.checkPackage(err, packageName))) {
350
- this.instance.writeFail(["Unable to parse URI response", format], err, 1024);
351
- }
352
- result = null;
353
- }
354
- }
355
- }
356
- if (result === undefined) {
357
- result = buffer;
358
- }
359
- }
360
- else {
361
- if (updating) {
362
- this.updateProgress(0, this.contentLength);
363
- }
364
- if (enabled && this.instance.readExpect === 'always') {
365
- this.terminate("No data received");
366
- return;
367
- }
368
- result = encoding && !pipeline ? '' : null;
369
- }
370
- this.endResponse(result, dataLength, log);
371
- });
372
- this.host.success(this.httpVersion);
373
- }
374
- updateProgress(dataLength, contentLength) {
375
- const { host, moduleName } = this.instance;
376
- host.updateProgress(moduleName, this.opts.progressId, dataLength, contentLength, this.dataTime);
377
- }
378
- endResponse(result, dataLength = 0, logging = this.state.log) {
379
- if (logging) {
380
- const messageUnit = this.dataTime && dataLength > 0 ? (0, util_1.getTransferRate)(dataLength, (0, types_1.convertTime)(process.hrtime.bigint() - this.dataTime, false) * 1000) : undefined;
381
- this.instance.writeTimeProcess('HTTP' + this.httpVersion, this.opts.statusMessage || this.uri.toString(), this.startTime, {
382
- type: 1024,
383
- queue: !!this.instance.host,
384
- titleBgColor: !result ? 'bgBlue' : undefined,
385
- messageUnit,
386
- messageUnitMinWidth: 9,
387
- delayTime: this.delayTime,
388
- bypassLog: module_1.hasLogType(32768)
389
- });
390
- }
391
- this.resolve(result);
392
- }
393
- redirectResponse(statusCode, location) {
394
- if (location) {
395
- if (this.opts.followRedirect === false) {
396
- this.terminate(this.formatStatus(statusCode, "Follow redirect was disabled"));
397
- }
398
- else if (++this.redirects <= this.redirectLimit) {
399
- this.abortResponse();
400
- this.setOpts((0, util_1.fromURL)(this.opts.url, location));
401
- this.init();
402
- }
403
- else {
404
- this.terminate(this.formatStatus(statusCode, "Exceeded redirect limit"));
405
- }
406
- }
407
- else {
408
- this.terminate(this.formatStatus(statusCode, "Missing redirect location"));
409
- }
410
- }
411
- abortResponse() {
412
- if (this.closed) {
413
- return;
414
- }
415
- this.aborted = true;
416
- this.client.destroy();
417
- this.instance.reset(this);
418
- this.cleanup();
419
- }
420
- errorResponse(err) {
421
- if (HttpAdapter.wasAborted(err)) {
422
- this.terminate(err);
423
- }
424
- else if ((0, util_1.checkRetryable)(err) && ++this.retries <= this.retryLimit) {
425
- this.abortResponse();
426
- if (HttpAdapter.isConnectionError(err)) {
427
- this.retryTimeout();
428
- }
429
- else {
430
- setTimeout(() => {
431
- this.init();
432
- }, this.retryWait);
433
- }
434
- }
435
- else {
436
- this.host.error(this.httpVersion);
437
- this.terminate(err);
438
- }
439
- }
440
- retryResponse(statusCode, retryAfter) {
441
- this.abortResponse();
442
- if (retryAfter && this.retryAfter > 0) {
443
- let offset = +retryAfter || new Date(retryAfter);
444
- if (offset instanceof Date) {
445
- offset = Math.max(0, offset.getTime() - Date.now());
446
- }
447
- else {
448
- offset *= 1000;
449
- }
450
- if (offset > 0) {
451
- if (offset <= this.retryAfter) {
452
- this.sendWarning(`Retry After (${retryAfter})`);
453
- setTimeout(() => {
454
- this.init();
455
- }, offset);
456
- }
457
- else {
458
- this.terminate(this.formatStatus(statusCode));
459
- }
460
- return;
461
- }
462
- }
463
- this.sendWarning(this.#formatRetry((0, util_1.fromStatusCode)(statusCode)));
464
- if ((0, util_1.isRetryable)(statusCode, true)) {
465
- setImmediate(this.init.bind(this));
466
- }
467
- else {
468
- setTimeout(() => {
469
- this.init();
470
- }, this.retryWait);
471
- }
472
- }
473
- isRetry(value) {
474
- return (0, util_1.isRetryable)(value) && ++this.retries <= this.retryLimit;
475
- }
476
- retryTimeout() {
477
- this.sendWarning(this.#formatRetry("HTTP connection timeout"));
478
- this.init();
479
- }
480
- terminate(err) {
481
- if (this.closed) {
482
- return;
483
- }
484
- this.cleanup();
485
- this.close();
486
- this.reject(typeof err === 'string' ? new Error(err) : err);
487
- }
488
- sendWarning(message) {
489
- if (this.state.verbose) {
490
- const { host, url } = this.opts;
491
- this.instance.formatMessage(1024, 'HTTP' + this.httpVersion, [message, host.origin], url.toString(), { ...module_1.LOG_STYLE_WARN });
492
- }
493
- }
494
- formatStatus(value, hint) {
495
- return value + ': ' + (hint || (0, util_1.fromStatusCode)(value)) + ` (${this.uri.toString()})`;
496
- }
497
- close() {
498
- this.closed = true;
499
- this.instance.reset(this);
500
- if (this.aborted && !this.client.aborted) {
501
- this.abortController?.abort();
502
- }
503
- }
504
- cleanup() {
505
- if ((0, types_1.isString)(this.pipeTo) && this.outStream) {
506
- (0, util_1.cleanupStream)(this.outStream, this.pipeTo);
507
- this.outStream = null;
508
- }
509
- }
510
- #formatNgFlags(value, statusCode, location) {
511
- return location ? `Using HTTP 1.1 for URL redirect (${location})` : this.formatStatus(statusCode, value ? 'NGHTTP2 Error ' + value : '');
512
- }
513
- #formatRetry(message) {
514
- return `${message} (${this.retries} / ${this.retryLimit})`;
515
- }
516
- set abortController(value) {
517
- this.opts.outAbort = value;
518
- }
519
- get abortController() {
520
- return this.opts.outAbort || null;
521
- }
522
- set outStream(value) {
523
- this.#outStream = value;
524
- if (value) {
525
- this.opts.outStream = value;
526
- }
527
- }
528
- get outStream() {
529
- return this.#outStream;
530
- }
531
- get destroyed() {
532
- return this.client.destroyed || this.httpVersion === 2 && this.client.aborted;
533
- }
534
- get host() {
535
- return this.opts.host;
536
- }
537
- get httpVersion() {
538
- return this.opts.httpVersion;
539
- }
540
- get pipeTo() {
541
- return this.opts.pipeTo;
542
- }
543
- get silent() {
544
- return this.opts.silent === false;
545
- }
546
- get retryLimit() {
547
- return this.state.config.retryLimit;
548
- }
549
- get retryWait() {
550
- return this.state.config.retryWait;
551
- }
552
- get retryAfter() {
553
- return this.state.config.retryAfter;
554
- }
555
- get redirectLimit() {
556
- return this.state.config.redirectLimit;
557
- }
558
- }
559
- module.exports = HttpAdapter;