@e-mc/request 0.10.1 → 0.10.2

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/LICENSE CHANGED
@@ -1,11 +1,11 @@
1
- Copyright 2024 An Pham
2
-
3
- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
-
5
- 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
-
7
- 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
-
9
- 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
-
1
+ Copyright 2024 An Pham
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
11
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,215 +1,215 @@
1
- # @e-mc/request
2
-
3
- * NodeJS 16
4
- * ES2020
5
-
6
- ## General Usage
7
-
8
- * [Read the Docs](https://e-mc.readthedocs.io)
9
-
10
- ## Interface
11
-
12
- * [View Source](https://www.unpkg.com/@e-mc/types@0.10.1/lib/index.d.ts)
13
-
14
- ```typescript
15
- import type { IModule, ModuleConstructor } from "./index";
16
- import type { HttpAgentSettings, HttpProtocolVersion, HttpRequestClient, InternetProtocolVersion } from "./http";
17
- import type { ApplyOptions, Aria2Options, FormDataPart, HeadersOnCallback, HostConfig, OpenOptions, PostOptions, ProxySettings, ReadExpectType, RequestInit, StatusOnCallback } from "./request";
18
- import type { DnsLookupSettings, RequestModule, RequestSettings } from "./settings";
19
-
20
- import type { ClientRequest, OutgoingHttpHeaders } from "http";
21
- import type { LookupFunction } from "net";
22
- import type { Writable } from "stream";
23
-
24
- interface IRequest extends IModule {
25
- module: RequestModule;
26
- startTime: number;
27
- acceptEncoding: boolean;
28
- keepAlive: boolean | null;
29
- readTimeout: number;
30
- readExpect: ReadExpectType;
31
- proxy: ProxySettings | null;
32
- init(config?: RequestInit): this;
33
- apply(options: ApplyOptions): this;
34
- addDns(hostname: string, address: string, timeout: number): void;
35
- addDns(hostname: string, address: string, family?: string, timeout?: number): void;
36
- lookupDns(hostname: string): LookupFunction;
37
- proxyOf(uri: string, localhost?: boolean): ProxySettings | undefined;
38
- statusOn(name: number | number[], callback: StatusOnCallback): void;
39
- statusOn(name: number | number[], globUrl: string, callback: StatusOnCallback): void;
40
- headersOn(name: string | string[], callback: HeadersOnCallback): void;
41
- headersOn(name: string | string[], globUrl: string, callback: HeadersOnCallback): void;
42
- headersOf(uri: string): OutgoingHttpHeaders | undefined;
43
- aria2c(uri: string | URL, pathname: string): Promise<string[]>;
44
- aria2c(uri: string | URL, options?: Aria2Options): Promise<string[]>;
45
- json(uri: string | URL, options?: OpenOptions): Promise<object | null>;
46
- pipe(uri: string | URL, to: Writable, options?: OpenOptions): Promise<null>;
47
- opts(url: string | URL, options?: OpenOptions): HostConfig;
48
- open(uri: string | URL, options: OpenOptions): HttpRequestClient;
49
- head(uri: string | URL, options?: OpenOptions): ClientRequest;
50
- post(uri: string | URL, data: unknown, contentType: string): Promise<Buffer | string | null>;
51
- post(uri: string | URL, parts: FormDataPart[]): Promise<Buffer | string | null>;
52
- post(uri: string | URL, form: Record<string, unknown>, parts: FormDataPart[]): Promise<Buffer | string | null>;
53
- post(uri: string | URL, data: unknown, options: PostOptions): Promise<Buffer | string | null>;
54
- post(uri: string | URL, data: unknown, contentType?: string, options?: PostOptions): Promise<Buffer | string | null>;
55
- get(uri: string | URL, options?: OpenOptions): Promise<Buffer | object | string | null>;
56
- detach(singleton?: boolean): void;
57
- reset(): void;
58
- close(): void;
59
- set agentTimeout(value);
60
- get agentTimeout(): number;
61
- set httpVersion(value);
62
- get httpVersion(): HttpProtocolVersion | null;
63
- set ipVersion(value);
64
- get ipVersion(): InternetProtocolVersion;
65
- get settings(): RequestSettings;
66
- }
67
-
68
- interface RequestConstructor extends ModuleConstructor {
69
- readCACert(value: string, cache?: boolean): string;
70
- readTLSKey(value: string, cache?: boolean): string;
71
- readTLSCert(value: string, cache?: boolean): string;
72
- isCert(value: string): boolean;
73
- fromURL(url: URL, value: string): string;
74
- fromStatusCode(value: number | string): string;
75
- defineHttpAgent(options: HttpAgentSettings): void;
76
- defineDnsLookup(options: DnsLookupSettings, clear?: boolean): void;
77
- getAria2Path(): string;
78
- readonly prototype: IRequest;
79
- new(module?: RequestModule): IRequest;
80
- }
81
- ```
82
-
83
- ## Settings
84
-
85
- ```typescript
86
- import type { PermittedDirectories } from "./core";
87
- import type { SecureConfig } from "./http";
88
- import type { PurgeComponent } from "./settings";
89
-
90
- import type { LookupAddress } from "dns";
91
- import type { OutgoingHttpHeaders } from "http";
92
-
93
- interface RequestModule {
94
- handler: "@e-mc/request";
95
- timeout?: number | string;
96
- read_timeout?: number | string;
97
- agent?: {
98
- keep_alive?: boolean;
99
- timeout?: number | string;
100
- };
101
- connect?: {
102
- timeout?: number | string;
103
- retry_wait?: number | string;
104
- retry_after?: number | string;
105
- retry_limit?: number;
106
- redirect_limit?: number;
107
- };
108
- dns?: {
109
- family?: number;
110
- expires?: number | string;
111
- resolve?: Record<string, Partial<LookupAddress>>;
112
- };
113
- use?: {
114
- http_version?: 1 | 2;
115
- accept_encoding?: boolean;
116
- };
117
- proxy?: {
118
- address?: string;
119
- port?: number;
120
- origin?: string;
121
- username?: string;
122
- password?: string;
123
- include?: string[];
124
- exclude?: string[];
125
- keep_alive?: boolean;
126
- };
127
- headers: Record<string, OutgoingHttpHeaders>;
128
- certs?: Record<string, SecureConfig<string | string[]>>;
129
- localhost?: string[];
130
- protocol?: {
131
- "http/1.1"?: string[];
132
- h2c?: string[];
133
- h2?: string[];
134
- };
135
- write_stream?: Record<string, number | string>;
136
- post_limit?: number | string;
137
- settings?: {
138
- broadcast_id?: string | string[];
139
- time_format?: "readable" | "relative" | "none";
140
- purge?: PurgeComponent;
141
- }
142
- }
143
-
144
- interface DownloadModule {
145
- expires?: number | string;
146
- aria2?: {
147
- bin?: string | false;
148
- exec?: {
149
- uid?: number;
150
- gid?: number;
151
- };
152
- update_status?: number | { interval?: number; broadcast_only?: boolean };
153
- max_concurrent_downloads?: number;
154
- max_connection_per_server?: number;
155
- check_integrity?: boolean;
156
- bt_stop_timeout?: number;
157
- bt_tracker_connect_timeout?: number;
158
- bt_tracker_timeout?: number;
159
- min_split_size?: string;
160
- disk_cache?: number | string;
161
- lowest_speed_limit?: number | string;
162
- always_resume?: boolean;
163
- file_allocation?: "none" | "prealloc" | "trunc" | "falloc";
164
- conf_path?: string;
165
- };
166
- }
167
- ```
168
-
169
- ### Example usage
170
-
171
- ```javascript
172
- const Request = require("@e-mc/request");
173
-
174
- const instance = new Request({
175
- read_timeout: 30,
176
- connect: {
177
- timeout: 20, // Seconds
178
- retry_wait: 1,
179
- retry_after: 30,
180
- retry_limit: 3, // Max attempts
181
- redirect_limit: 10
182
- },
183
- use: {
184
- http_version: 2,
185
- accept_encoding: true
186
- },
187
- dns: {
188
- family: 4 // ipVersion
189
- },
190
- agent: { keep_alive: true }
191
- });
192
- request.init({ ipVersion: 6 });
193
-
194
- const options = {
195
- format: "yaml",
196
- httpVersion: 1,
197
- silent: true,
198
- headers: { "x-goog-user-project": "project-1" }
199
- };
200
- instance.get("http://hostname/path/config.yml", options).then(data => {
201
- console.log(data.property);
202
- });
203
- ```
204
-
205
- ## References
206
-
207
- - https://www.unpkg.com/@e-mc/types@0.10.1/lib/http.d.ts
208
- - https://www.unpkg.com/@e-mc/types@0.10.1/lib/request.d.ts
209
- - https://www.unpkg.com/@e-mc/types@0.10.1/lib/settings.d.ts
210
-
211
- * https://www.npmjs.com/package/@types/node
212
-
213
- ## LICENSE
214
-
1
+ # @e-mc/request
2
+
3
+ * NodeJS 16
4
+ * ES2020
5
+
6
+ ## General Usage
7
+
8
+ * [Read the Docs](https://e-mc.readthedocs.io)
9
+
10
+ ## Interface
11
+
12
+ * [View Source](https://www.unpkg.com/@e-mc/types@0.10.2/lib/index.d.ts)
13
+
14
+ ```typescript
15
+ import type { IModule, ModuleConstructor } from "./index";
16
+ import type { HttpAgentSettings, HttpProtocolVersion, HttpRequestClient, InternetProtocolVersion } from "./http";
17
+ import type { ApplyOptions, Aria2Options, FormDataPart, HeadersOnCallback, HostConfig, OpenOptions, PostOptions, ProxySettings, ReadExpectType, RequestInit, StatusOnCallback } from "./request";
18
+ import type { DnsLookupSettings, RequestModule, RequestSettings } from "./settings";
19
+
20
+ import type { ClientRequest, OutgoingHttpHeaders } from "http";
21
+ import type { LookupFunction } from "net";
22
+ import type { Writable } from "stream";
23
+
24
+ interface IRequest extends IModule {
25
+ module: RequestModule;
26
+ startTime: number;
27
+ acceptEncoding: boolean;
28
+ keepAlive: boolean | null;
29
+ readTimeout: number;
30
+ readExpect: ReadExpectType;
31
+ proxy: ProxySettings | null;
32
+ init(config?: RequestInit): this;
33
+ apply(options: ApplyOptions): this;
34
+ addDns(hostname: string, address: string, timeout: number): void;
35
+ addDns(hostname: string, address: string, family?: string, timeout?: number): void;
36
+ lookupDns(hostname: string): LookupFunction;
37
+ proxyOf(uri: string, localhost?: boolean): ProxySettings | undefined;
38
+ statusOn(name: number | number[], callback: StatusOnCallback): void;
39
+ statusOn(name: number | number[], globUrl: string, callback: StatusOnCallback): void;
40
+ headersOn(name: string | string[], callback: HeadersOnCallback): void;
41
+ headersOn(name: string | string[], globUrl: string, callback: HeadersOnCallback): void;
42
+ headersOf(uri: string): OutgoingHttpHeaders | undefined;
43
+ aria2c(uri: string | URL, pathname: string): Promise<string[]>;
44
+ aria2c(uri: string | URL, options?: Aria2Options): Promise<string[]>;
45
+ json(uri: string | URL, options?: OpenOptions): Promise<object | null>;
46
+ pipe(uri: string | URL, to: Writable, options?: OpenOptions): Promise<null>;
47
+ opts(url: string | URL, options?: OpenOptions): HostConfig;
48
+ open(uri: string | URL, options: OpenOptions): HttpRequestClient;
49
+ head(uri: string | URL, options?: OpenOptions): ClientRequest;
50
+ post(uri: string | URL, data: unknown, contentType: string): Promise<Buffer | string | null>;
51
+ post(uri: string | URL, parts: FormDataPart[]): Promise<Buffer | string | null>;
52
+ post(uri: string | URL, form: Record<string, unknown>, parts: FormDataPart[]): Promise<Buffer | string | null>;
53
+ post(uri: string | URL, data: unknown, options: PostOptions): Promise<Buffer | string | null>;
54
+ post(uri: string | URL, data: unknown, contentType?: string, options?: PostOptions): Promise<Buffer | string | null>;
55
+ get(uri: string | URL, options?: OpenOptions): Promise<Buffer | object | string | null>;
56
+ detach(singleton?: boolean): void;
57
+ reset(): void;
58
+ close(): void;
59
+ set agentTimeout(value);
60
+ get agentTimeout(): number;
61
+ set httpVersion(value);
62
+ get httpVersion(): HttpProtocolVersion | null;
63
+ set ipVersion(value);
64
+ get ipVersion(): InternetProtocolVersion;
65
+ get settings(): RequestSettings;
66
+ }
67
+
68
+ interface RequestConstructor extends ModuleConstructor {
69
+ readCACert(value: string, cache?: boolean): string;
70
+ readTLSKey(value: string, cache?: boolean): string;
71
+ readTLSCert(value: string, cache?: boolean): string;
72
+ isCert(value: string): boolean;
73
+ fromURL(url: URL, value: string): string;
74
+ fromStatusCode(value: number | string): string;
75
+ defineHttpAgent(options: HttpAgentSettings): void;
76
+ defineDnsLookup(options: DnsLookupSettings, clear?: boolean): void;
77
+ getAria2Path(): string;
78
+ readonly prototype: IRequest;
79
+ new(module?: RequestModule): IRequest;
80
+ }
81
+ ```
82
+
83
+ ## Settings
84
+
85
+ ```typescript
86
+ import type { PermittedDirectories } from "./core";
87
+ import type { SecureConfig } from "./http";
88
+ import type { PurgeComponent } from "./settings";
89
+
90
+ import type { LookupAddress } from "dns";
91
+ import type { OutgoingHttpHeaders } from "http";
92
+
93
+ interface RequestModule {
94
+ handler: "@e-mc/request";
95
+ timeout?: number | string;
96
+ read_timeout?: number | string;
97
+ agent?: {
98
+ keep_alive?: boolean;
99
+ timeout?: number | string;
100
+ };
101
+ connect?: {
102
+ timeout?: number | string;
103
+ retry_wait?: number | string;
104
+ retry_after?: number | string;
105
+ retry_limit?: number;
106
+ redirect_limit?: number;
107
+ };
108
+ dns?: {
109
+ family?: number;
110
+ expires?: number | string;
111
+ resolve?: Record<string, Partial<LookupAddress>>;
112
+ };
113
+ use?: {
114
+ http_version?: 1 | 2;
115
+ accept_encoding?: boolean;
116
+ };
117
+ proxy?: {
118
+ address?: string;
119
+ port?: number;
120
+ origin?: string;
121
+ username?: string;
122
+ password?: string;
123
+ include?: string[];
124
+ exclude?: string[];
125
+ keep_alive?: boolean;
126
+ };
127
+ headers: Record<string, OutgoingHttpHeaders>;
128
+ certs?: Record<string, SecureConfig<string | string[]>>;
129
+ localhost?: string[];
130
+ protocol?: {
131
+ "http/1.1"?: string[];
132
+ h2c?: string[];
133
+ h2?: string[];
134
+ };
135
+ write_stream?: Record<string, number | string>;
136
+ post_limit?: number | string;
137
+ settings?: {
138
+ broadcast_id?: string | string[];
139
+ time_format?: "readable" | "relative" | "none";
140
+ purge?: PurgeComponent;
141
+ }
142
+ }
143
+
144
+ interface DownloadModule {
145
+ expires?: number | string;
146
+ aria2?: {
147
+ bin?: string | false;
148
+ exec?: {
149
+ uid?: number;
150
+ gid?: number;
151
+ };
152
+ update_status?: number | { interval?: number; broadcast_only?: boolean };
153
+ max_concurrent_downloads?: number;
154
+ max_connection_per_server?: number;
155
+ check_integrity?: boolean;
156
+ bt_stop_timeout?: number;
157
+ bt_tracker_connect_timeout?: number;
158
+ bt_tracker_timeout?: number;
159
+ min_split_size?: string;
160
+ disk_cache?: number | string;
161
+ lowest_speed_limit?: number | string;
162
+ always_resume?: boolean;
163
+ file_allocation?: "none" | "prealloc" | "trunc" | "falloc";
164
+ conf_path?: string;
165
+ };
166
+ }
167
+ ```
168
+
169
+ ### Example usage
170
+
171
+ ```javascript
172
+ const Request = require("@e-mc/request");
173
+
174
+ const instance = new Request({
175
+ read_timeout: 30,
176
+ connect: {
177
+ timeout: 20, // Seconds
178
+ retry_wait: 1,
179
+ retry_after: 30,
180
+ retry_limit: 3, // Max attempts
181
+ redirect_limit: 10
182
+ },
183
+ use: {
184
+ http_version: 2,
185
+ accept_encoding: true
186
+ },
187
+ dns: {
188
+ family: 4 // ipVersion
189
+ },
190
+ agent: { keep_alive: true }
191
+ });
192
+ request.init({ ipVersion: 6 });
193
+
194
+ const options = {
195
+ format: "yaml",
196
+ httpVersion: 1,
197
+ silent: true,
198
+ headers: { "x-goog-user-project": "project-1" }
199
+ };
200
+ instance.get("http://hostname/path/config.yml", options).then(data => {
201
+ console.log(data.property);
202
+ });
203
+ ```
204
+
205
+ ## References
206
+
207
+ - https://www.unpkg.com/@e-mc/types@0.10.2/lib/http.d.ts
208
+ - https://www.unpkg.com/@e-mc/types@0.10.2/lib/request.d.ts
209
+ - https://www.unpkg.com/@e-mc/types@0.10.2/lib/settings.d.ts
210
+
211
+ * https://www.npmjs.com/package/@types/node
212
+
213
+ ## LICENSE
214
+
215
215
  BSD 3-Clause
@@ -120,7 +120,7 @@ class HttpHost {
120
120
  case 1:
121
121
  return status;
122
122
  default:
123
- return this._tlsConnect || (this._tlsConnect = new Promise(resolve => {
123
+ return this._tlsConnect ||= new Promise(resolve => {
124
124
  const alpn = 'h' + version;
125
125
  const socket = tls.connect(+this.port, this.hostname, { ALPNProtocols: [alpn], requestCert: true, rejectUnauthorized: false }, () => {
126
126
  this._tlsConnect = null;
@@ -147,7 +147,7 @@ class HttpHost {
147
147
  resolve(data[3] = 0);
148
148
  })
149
149
  .end();
150
- }));
150
+ });
151
151
  }
152
152
  }
153
153
  return 1;
package/index.js CHANGED
@@ -11,7 +11,7 @@ const dns = require("dns");
11
11
  const net = require("net");
12
12
  const stream = require("stream");
13
13
  const zlib = require("zlib");
14
- const qs = require("querystring");
14
+ const qs = require("node:querystring");
15
15
  const combined = require("combined-stream");
16
16
  const pm = require("picomatch");
17
17
  const yaml = require("js-yaml");
@@ -96,7 +96,7 @@ function getBaseHeaders(uri, headers) {
96
96
  let result;
97
97
  for (const pathname in headers) {
98
98
  if (pathname === uri || uri.startsWith(pathname + '/')) {
99
- (result || (result = [])).push([pathname, headers[pathname]]);
99
+ (result ||= []).push([pathname, headers[pathname]]);
100
100
  }
101
101
  }
102
102
  if (result) {
@@ -107,7 +107,7 @@ function getBaseHeaders(uri, headers) {
107
107
  }
108
108
  }
109
109
  function setDnsCache(hostname, value, expires) {
110
- expires ?? (expires = DNS.EXPIRES);
110
+ expires ??= DNS.EXPIRES;
111
111
  if (expires > 0 && !DNS.CACHE[hostname]) {
112
112
  DNS.CACHE[hostname] = value;
113
113
  if (expires !== Infinity) {
@@ -759,7 +759,7 @@ class Fetch {
759
759
  redirectResponse(statusCode, location) {
760
760
  this.abortResponse();
761
761
  if (location) {
762
- if (this.config.follow_redirect === false) {
762
+ if (this.config.follow_redirect === false || this.config.followRedirect === false) {
763
763
  this.rejectError(this.formatStatus(statusCode, "Follow redirect was disabled"));
764
764
  }
765
765
  else if (++this.redirects <= this.redirectLimit) {
@@ -1342,7 +1342,6 @@ class Request extends module_1 {
1342
1342
  const output = [];
1343
1343
  let count = 0;
1344
1344
  this[kConnectHttp].forEach((protocol, index) => {
1345
- var _p;
1346
1345
  const title = 'HTTP' + (index + 1);
1347
1346
  for (const origin in protocol) {
1348
1347
  const value = protocol[origin];
@@ -1352,7 +1351,7 @@ class Request extends module_1 {
1352
1351
  if (item[1] === title && Array.isArray(item[2]) && item[2][0].startsWith(origin)) {
1353
1352
  item[1] = '';
1354
1353
  item[2][0] = item[2][0].substring(origin.length);
1355
- (_p = item[4]).titleBgColor && (_p.titleBgColor = undefined);
1354
+ item[4].titleBgColor &&= undefined;
1356
1355
  item[4].titleJustify = 'right';
1357
1356
  args.push(item);
1358
1357
  log.splice(i--, 1);
@@ -1414,7 +1413,7 @@ class Request extends module_1 {
1414
1413
  if (config) {
1415
1414
  const { headers, httpVersion, ipVersion, readTimeout } = config;
1416
1415
  if ((0, types_1.isObject)(headers)) {
1417
- setOutgoingHeaders(this[kHeaders] || (this[kHeaders] = {}), headers);
1416
+ setOutgoingHeaders(this[kHeaders] ||= {}, headers);
1418
1417
  }
1419
1418
  if (httpVersion !== undefined) {
1420
1419
  this.httpVersion = httpVersion;
@@ -1504,7 +1503,6 @@ class Request extends module_1 {
1504
1503
  setDnsCache(hostname, this[kConnectDns][hostname] = [{ address, family }], timeout);
1505
1504
  }
1506
1505
  lookupDns(hostname) {
1507
- var _p;
1508
1506
  const resolved = this[kConnectDns][hostname] || DNS.CACHE[hostname];
1509
1507
  if (resolved) {
1510
1508
  return (...args) => {
@@ -1516,7 +1514,7 @@ class Request extends module_1 {
1516
1514
  }
1517
1515
  };
1518
1516
  }
1519
- const pending = (_p = this[kPendingDns])[hostname] || (_p[hostname] = []);
1517
+ const pending = this[kPendingDns][hostname] ||= [];
1520
1518
  return (value, options, callback) => {
1521
1519
  if (pending.push(callback) === 1) {
1522
1520
  let ipVersion = this.ipVersion;
@@ -1576,7 +1574,7 @@ class Request extends module_1 {
1576
1574
  globUrl = '*';
1577
1575
  }
1578
1576
  if ((0, types_1.isString)(globUrl) && typeof callback === 'function') {
1579
- const on = this[kStatusOn] || (this[kStatusOn] = new Map());
1577
+ const on = this[kStatusOn] ||= new Map();
1580
1578
  for (const item of !Array.isArray(code) ? [code] : code) {
1581
1579
  let status = on.get(item);
1582
1580
  if (!status) {
@@ -1592,7 +1590,7 @@ class Request extends module_1 {
1592
1590
  globUrl = '*';
1593
1591
  }
1594
1592
  if ((0, types_1.isString)(globUrl) && typeof callback === 'function') {
1595
- const on = this[kHeadersOn] || (this[kHeadersOn] = new Map());
1593
+ const on = this[kHeadersOn] ||= new Map();
1596
1594
  for (const item of !Array.isArray(name) ? [name] : name) {
1597
1595
  let headers = on.get(item);
1598
1596
  if (!headers) {
@@ -1681,7 +1679,7 @@ class Request extends module_1 {
1681
1679
  if (!module_1.createDir(pathname)) {
1682
1680
  return Promise.reject((0, types_1.errorMessage)("aria2", "Path is not a directory", pathname));
1683
1681
  }
1684
- silent ?? (silent = this[kSingleton]);
1682
+ silent ??= this[kSingleton];
1685
1683
  return new Promise((resolve, reject) => {
1686
1684
  let protocol, origin, username, password;
1687
1685
  if (uri instanceof URL) {
@@ -1886,7 +1884,7 @@ class Request extends module_1 {
1886
1884
  if (match[3] === '100') {
1887
1885
  result.push(file);
1888
1886
  }
1889
- messageUnit || (messageUnit = match[2]);
1887
+ messageUnit ||= match[2];
1890
1888
  break;
1891
1889
  case 'INPR':
1892
1890
  if (ARIA2.ALWAYS_RESUME) {
@@ -1962,7 +1960,6 @@ class Request extends module_1 {
1962
1960
  return this.get(uri, options);
1963
1961
  }
1964
1962
  opts(url, options) {
1965
- var _p, _q, _r, _s;
1966
1963
  const base = this[kBaseURL];
1967
1964
  if (base) {
1968
1965
  if (typeof url === 'string') {
@@ -1977,15 +1974,14 @@ class Request extends module_1 {
1977
1974
  }
1978
1975
  let host;
1979
1976
  if (this.host) {
1980
- host = (_p = HTTP.HOST)[_q = url.origin] || (_p[_q] = new host_1(url, HTTP.VERSION));
1977
+ host = HTTP.HOST[url.origin] ||= new host_1(url, HTTP.VERSION);
1981
1978
  }
1982
1979
  else {
1983
- host = (_r = this[kHostInfo])[_s = url.origin] || (_r[_s] = new host_1(url, this.httpVersion || 1));
1980
+ host = this[kHostInfo][url.origin] ||= new host_1(url, this.httpVersion || 1);
1984
1981
  }
1985
1982
  return { ...options, host, url };
1986
1983
  }
1987
1984
  open(uri, options) {
1988
- var _p, _q;
1989
1985
  let { host, url, httpVersion, method = 'GET', search, encoding, format, headers, postData, keepAlive, agentTimeout, socketPath, timeout = this._config.connectTimeout, outStream } = options;
1990
1986
  const getting = method === 'GET';
1991
1987
  const posting = method === 'POST';
@@ -1997,7 +1993,7 @@ class Request extends module_1 {
1997
1993
  if (format.includes('/')) {
1998
1994
  format = format.split('/').pop().split('-').pop();
1999
1995
  }
2000
- headers || (headers = {});
1996
+ headers ||= {};
2001
1997
  switch (format = format.trim().toLowerCase()) {
2002
1998
  case 'yaml':
2003
1999
  headers.accept = 'application/yaml, application/x-yaml, text/yaml, text/x-yaml';
@@ -2046,7 +2042,7 @@ class Request extends module_1 {
2046
2042
  this[kBaseURL] = [url, httpVersion, headers];
2047
2043
  }
2048
2044
  else if (base) {
2049
- httpVersion ?? (httpVersion = base[1]);
2045
+ httpVersion ??= base[1];
2050
2046
  if (base[2]) {
2051
2047
  headers = { ...base[2], ...headers };
2052
2048
  }
@@ -2063,7 +2059,7 @@ class Request extends module_1 {
2063
2059
  const version = this.httpVersion;
2064
2060
  let request, ca, cert, key, ciphers, minVersion, baseHeaders = this.headersOf(uri);
2065
2061
  if (getting && this.acceptEncoding && !localhost && !baseHeaders?.['accept-encoding']) {
2066
- (_p = (headers || (headers = {})))['accept-encoding'] || (_p['accept-encoding'] = 'gzip, deflate, br' + (LIB_ZSTD ? ', zstd' : ''));
2062
+ (headers ||= {})['accept-encoding'] ||= 'gzip, deflate, br' + (LIB_ZSTD ? ', zstd' : '');
2067
2063
  }
2068
2064
  if (secure) {
2069
2065
  const certs = this[kCerts]?.[0][origin] || this.host && TLS.TEXT[origin];
@@ -2072,7 +2068,7 @@ class Request extends module_1 {
2072
2068
  }
2073
2069
  }
2074
2070
  if (!proxy && httpVersion !== 1 && ((httpVersion || host.version) === 2 && version !== 1 || secure && version === 2 && host.failed(2, true) === 0)) {
2075
- request = ((_q = this[kSession][0])[origin] || (_q[origin] = http2.connect(origin, { lookup: this.lookupDns(hostname), ca, cert, key, ciphers, minVersion, settings: localhost ? { maxFrameSize: 16777215, enablePush: false } : { enablePush: false } }))).request({ ...baseHeaders, ...host_1.getBasicAuth(url), ...headers, ':path': pathname, ':method': method });
2071
+ request = (this[kSession][0][origin] ||= http2.connect(origin, { lookup: this.lookupDns(hostname), ca, cert, key, ciphers, minVersion, settings: localhost ? { maxFrameSize: 16777215, enablePush: false } : { enablePush: false } })).request({ ...baseHeaders, ...host_1.getBasicAuth(url), ...headers, ':path': pathname, ':method': method });
2076
2072
  if (getting) {
2077
2073
  const listenerMap = {};
2078
2074
  const onEvent = request.on.bind(request);
@@ -2113,7 +2109,6 @@ class Request extends module_1 {
2113
2109
  this.matchHeaders(url, response, request, options);
2114
2110
  });
2115
2111
  request.on = function (event, listener) {
2116
- var _p;
2117
2112
  switch (event) {
2118
2113
  case 'data':
2119
2114
  case 'error':
@@ -2123,7 +2118,7 @@ class Request extends module_1 {
2123
2118
  break;
2124
2119
  }
2125
2120
  if (!connected) {
2126
- (listenerMap[_p = event + '-on'] || (listenerMap[_p] = [])).push(listener);
2121
+ (listenerMap[event + '-on'] ||= []).push(listener);
2127
2122
  }
2128
2123
  default:
2129
2124
  onEvent(event, listener);
@@ -2132,7 +2127,6 @@ class Request extends module_1 {
2132
2127
  return this;
2133
2128
  };
2134
2129
  request.once = function (event, listener) {
2135
- var _p;
2136
2130
  switch (event) {
2137
2131
  case 'data':
2138
2132
  case 'error':
@@ -2142,7 +2136,7 @@ class Request extends module_1 {
2142
2136
  break;
2143
2137
  }
2144
2138
  if (!connected) {
2145
- (listenerMap[_p = event + '-once'] || (listenerMap[_p] = [])).push(listener);
2139
+ (listenerMap[event + '-once'] ||= []).push(listener);
2146
2140
  }
2147
2141
  default:
2148
2142
  onceEvent(event, listener);
@@ -2159,8 +2153,8 @@ class Request extends module_1 {
2159
2153
  if (proxy) {
2160
2154
  const pkg = secure ? 'https-proxy-agent' : 'http-proxy-agent';
2161
2155
  try {
2162
- keepAlive ?? (keepAlive = proxy.keepAlive);
2163
- agentTimeout ?? (agentTimeout = proxy.agentTimeout);
2156
+ keepAlive ??= proxy.keepAlive;
2157
+ agentTimeout ??= proxy.agentTimeout;
2164
2158
  const proxyHeaders = this[kHeaders] && getBaseHeaders(proxy.host.href, this[kHeaders]) || getBaseHeaders(proxy.host.href, HTTP.HEADERS);
2165
2159
  agent = require(pkg)(proxy.host, typeof keepAlive === 'boolean' || agentTimeout > 0 || proxyHeaders ? { keepAlive: keepAlive ?? true, timeout: agentTimeout, headers: proxyHeaders } : undefined);
2166
2160
  if (proxyHeaders) {
@@ -2178,7 +2172,7 @@ class Request extends module_1 {
2178
2172
  agent = new (secure ? https.Agent : http.Agent)({ keepAlive: true, timeout: agentTimeout });
2179
2173
  }
2180
2174
  else if (agentTimeout !== 0) {
2181
- agentTimeout ?? (agentTimeout = this.agentTimeout);
2175
+ agentTimeout ??= this.agentTimeout;
2182
2176
  if (this.keepAlive !== null || agentTimeout > 0) {
2183
2177
  agent = new (secure ? https.Agent : http.Agent)({ keepAlive: this.keepAlive ?? true, timeout: agentTimeout });
2184
2178
  }
@@ -2327,16 +2321,16 @@ class Request extends module_1 {
2327
2321
  let formData;
2328
2322
  ({ formData, dataEncoding } = options);
2329
2323
  if (formData) {
2330
- (parts || (parts = [])).push(...Array.isArray(formData) ? formData : [formData]);
2324
+ (parts ||= []).push(...Array.isArray(formData) ? formData : [formData]);
2331
2325
  }
2332
2326
  else {
2333
- contentType || (contentType = options.contentType);
2327
+ contentType ||= options.contentType;
2334
2328
  }
2335
2329
  }
2336
2330
  else {
2337
2331
  options = {};
2338
2332
  }
2339
- const headers = options.headers || (options.headers = {});
2333
+ const headers = options.headers ||= {};
2340
2334
  for (const attr in headers) {
2341
2335
  const name = attr.toLowerCase();
2342
2336
  if (name === 'content-type' || name === 'content-length') {
@@ -2375,8 +2369,8 @@ class Request extends module_1 {
2375
2369
  }
2376
2370
  if (target) {
2377
2371
  if (typeof target === 'string') {
2378
- filename || (filename = path.basename(target));
2379
- type || (type = module_1.lookupMime(filename));
2372
+ filename ||= path.basename(target);
2373
+ type ||= module_1.lookupMime(filename);
2380
2374
  target = fs.readFileSync(target);
2381
2375
  }
2382
2376
  else if (target instanceof stream.Readable) {
@@ -2393,7 +2387,7 @@ class Request extends module_1 {
2393
2387
  const result = await module_1.resolveMime(target);
2394
2388
  let ext;
2395
2389
  if (result) {
2396
- type || (type = result.mime);
2390
+ type ||= result.mime;
2397
2391
  ext = result.ext;
2398
2392
  }
2399
2393
  else if (type) {
@@ -2436,7 +2430,7 @@ class Request extends module_1 {
2436
2430
  }
2437
2431
  else {
2438
2432
  data = JSON.stringify(data);
2439
- contentType || (contentType = "application/json");
2433
+ contentType ||= "application/json";
2440
2434
  }
2441
2435
  headers['content-length'] = Buffer.byteLength(data, (0, types_1.getEncoding)(dataEncoding)).toString();
2442
2436
  }
@@ -2526,11 +2520,11 @@ class Request extends module_1 {
2526
2520
  set agentTimeout(value) {
2527
2521
  if (value > 0) {
2528
2522
  this[kAgentTimeout] = value;
2529
- this.keepAlive ?? (this.keepAlive = true);
2523
+ this.keepAlive ??= true;
2530
2524
  }
2531
2525
  else {
2532
2526
  this[kAgentTimeout] = 0;
2533
- this.keepAlive ?? (this.keepAlive = false);
2527
+ this.keepAlive ??= false;
2534
2528
  }
2535
2529
  }
2536
2530
  get agentTimeout() {
@@ -2560,8 +2554,7 @@ class Request extends module_1 {
2560
2554
  return this[kIpVersion];
2561
2555
  }
2562
2556
  get settings() {
2563
- var _p;
2564
- return (_p = this.module).settings || (_p.settings = {});
2557
+ return this.module.settings ||= {};
2565
2558
  }
2566
2559
  }
2567
2560
  _a = kSingleton, _b = kHttpVersion, _c = kHeaders, _d = kCerts, _e = kBaseURL, _f = kConnectDns, _g = kPendingDns, _h = kConnectHttp, _j = kStatusOn, _k = kHeadersOn, _l = kDownloading, _m = kHostInfo, _o = kSession;
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
- {
2
- "name": "@e-mc/request",
3
- "version": "0.10.1",
4
- "description": "Request constructor for E-mc.",
5
- "main": "index.js",
6
- "types": "index.d.ts",
7
- "publishConfig": {
8
- "access": "public"
9
- },
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/anpham6/e-mc.git",
13
- "directory": "src/request"
14
- },
15
- "keywords": [
16
- "squared",
17
- "squared-functions"
18
- ],
19
- "author": "An Pham <anpham6@gmail.com>",
20
- "license": "BSD 3-Clause",
21
- "homepage": "https://github.com/anpham6/e-mc#readme",
22
- "dependencies": {
23
- "@e-mc/module": "0.10.1",
24
- "@e-mc/types": "0.10.1",
25
- "combined-stream": "^1.0.8",
26
- "js-yaml": "^4.1.0",
27
- "picomatch": "^4.0.2",
28
- "which": "^2.0.2"
29
- }
30
- }
1
+ {
2
+ "name": "@e-mc/request",
3
+ "version": "0.10.2",
4
+ "description": "Request constructor for E-mc.",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/anpham6/e-mc.git",
13
+ "directory": "src/request"
14
+ },
15
+ "keywords": [
16
+ "squared",
17
+ "squared-functions"
18
+ ],
19
+ "author": "An Pham <anpham6@gmail.com>",
20
+ "license": "BSD 3-Clause",
21
+ "homepage": "https://github.com/anpham6/e-mc#readme",
22
+ "dependencies": {
23
+ "@e-mc/module": "0.10.2",
24
+ "@e-mc/types": "0.10.2",
25
+ "combined-stream": "^1.0.8",
26
+ "js-yaml": "^4.1.0",
27
+ "picomatch": "^4.0.2",
28
+ "which": "^2.0.2"
29
+ }
30
+ }
package/util.d.ts CHANGED
@@ -1,28 +1,28 @@
1
- import type { AuthValue } from '../types/lib/http';
2
- import type { HttpProxySettings } from '../types/lib/settings';
3
-
4
- import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
5
- import type { Readable, Writable } from 'stream';
6
-
7
- declare namespace util {
8
- function parseHeader<T = unknown>(headers: IncomingHttpHeaders, name: string): T | undefined;
9
- function normalizeHeaders(headers: OutgoingHttpHeaders): OutgoingHttpHeaders;
10
- function getBasicAuth(auth: AuthValue): string;
11
- function getBasicAuth(username: unknown, password?: unknown): string;
12
- function hasBasicAuth(value: string): boolean;
13
- function checkRetryable(err: unknown): boolean;
14
- function isRetryable(value: number, timeout?: boolean): boolean;
15
- function parseHttpProxy(value?: string): HttpProxySettings | undefined;
16
- function trimPath(value: string): string;
17
- function asInt(value: unknown): number;
18
- function asFloat(value: unknown): number;
19
- function fromSeconds(value: unknown): number;
20
- function getTransferRate(length: number, timeMs: number, unitSeparator?: string): string;
21
- function hasSameStat(src: string, dest: string, keepEmpty?: boolean): boolean;
22
- function hasSize(value: string, keepEmpty?: boolean): boolean;
23
- function getSize(value: string, diskUsed?: boolean): number;
24
- function byteLength(value: Bufferable, encoding?: BufferEncoding): number;
25
- function cleanupStream(target: Readable | Writable, pathname?: string): void;
26
- }
27
-
1
+ import type { AuthValue } from '../types/lib/http';
2
+ import type { HttpProxySettings } from '../types/lib/settings';
3
+
4
+ import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
5
+ import type { Readable, Writable } from 'stream';
6
+
7
+ declare namespace util {
8
+ function parseHeader<T = unknown>(headers: IncomingHttpHeaders, name: string): T | undefined;
9
+ function normalizeHeaders(headers: OutgoingHttpHeaders): OutgoingHttpHeaders;
10
+ function getBasicAuth(auth: AuthValue): string;
11
+ function getBasicAuth(username: unknown, password?: unknown): string;
12
+ function hasBasicAuth(value: string): boolean;
13
+ function checkRetryable(err: unknown): boolean;
14
+ function isRetryable(value: number, timeout?: boolean): boolean;
15
+ function parseHttpProxy(value?: string, ignoreEnv?: boolean): HttpProxySettings | undefined;
16
+ function trimPath(value: string): string;
17
+ function asInt(value: unknown): number;
18
+ function asFloat(value: unknown): number;
19
+ function fromSeconds(value: unknown): number;
20
+ function getTransferRate(length: number, timeMs: number, unitSeparator?: string): string;
21
+ function hasSameStat(src: string, dest: string, keepEmpty?: boolean): boolean;
22
+ function hasSize(value: string, keepEmpty?: boolean): boolean;
23
+ function getSize(value: string, diskUsed?: boolean): number;
24
+ function byteLength(value: Bufferable, encoding?: BufferEncoding): number;
25
+ function cleanupStream(target: Readable | Writable, pathname?: string): void;
26
+ }
27
+
28
28
  export = util;
package/util.js CHANGED
@@ -113,28 +113,36 @@ function isRetryable(value, timeout) {
113
113
  case 502:
114
114
  case 503:
115
115
  case 521:
116
- if (!timeout) {
117
- return true;
118
- }
116
+ return !timeout;
119
117
  default:
120
118
  return false;
121
119
  }
122
120
  }
123
- function parseHttpProxy(value) {
124
- value || (value = process.env.HTTP_PROXY || process.env.HTTPS_PROXY);
121
+ function parseHttpProxy(value, ignoreEnv) {
122
+ if (!ignoreEnv) {
123
+ value ||= process.env.HTTP_PROXY || process.env.HTTPS_PROXY;
124
+ }
125
125
  if (value) {
126
126
  try {
127
127
  const url = new URL(value);
128
128
  if (url.port) {
129
129
  let exclude;
130
- if (process.env.NO_PROXY) {
130
+ if (process.env.NO_PROXY && !ignoreEnv) {
131
131
  exclude = [];
132
- for (const item of process.env.NO_PROXY.trim().split(/\s*,\s*/)) {
132
+ for (let item of process.env.NO_PROXY.trim().split(/\s*,\s*/)) {
133
+ if (item === '*') {
134
+ exclude = ['**'];
135
+ break;
136
+ }
133
137
  if (module_1.isURL(item)) {
134
138
  exclude.push(item);
135
139
  }
136
140
  else {
137
- exclude.push(`https://${item}`, `http://${item}`);
141
+ const negate = item.startsWith('!') ? (item = item.substring(1), '!') : '';
142
+ if (!/^(?:[^.]+|(?:\d+\.){3}\d+)$/.test(item) && !item.includes('*')) {
143
+ item = '*' + item;
144
+ }
145
+ exclude.push(`${negate}http?(s)://${item}?(/)**`);
138
146
  }
139
147
  }
140
148
  }