@wiajs/request 3.0.33 → 3.0.36

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.
@@ -1,19 +1,19 @@
1
- import stream from 'node:stream';
1
+ import stream from 'stream';
2
2
  let ZlibTransform = class ZlibTransform extends stream.Transform {
3
3
  /**
4
- *
5
- * @param {*} chunk
6
- * @param {*} encoding
7
- * @param {*} callback
4
+ *
5
+ * @param {*} chunk
6
+ * @param {*} encoding
7
+ * @param {*} callback
8
8
  */ __transform(chunk, encoding, callback) {
9
9
  this.push(chunk);
10
10
  callback();
11
11
  }
12
12
  /**
13
- *
14
- * @param {*} chunk
15
- * @param {*} encoding
16
- * @param {*} callback
13
+ *
14
+ * @param {*} chunk
15
+ * @param {*} encoding
16
+ * @param {*} callback
17
17
  */ _transform(chunk, encoding, callback) {
18
18
  if (chunk.length !== 0) {
19
19
  this._transform = this.__transform;
package/lib/caseless.js CHANGED
@@ -1,9 +1,4 @@
1
- export default class Caseless {
2
- /**
3
- * @param {*} dict
4
- */ constructor(dict){
5
- this.dict = dict || {};
6
- }
1
+ let Caseless = class Caseless {
7
2
  /**
8
3
  *
9
4
  * @param {*} name
@@ -62,9 +57,9 @@ export default class Caseless {
62
57
  delete this.dict[has];
63
58
  }
64
59
  /**
65
- *
66
- * @param {string} name
67
- * @returns
60
+ *
61
+ * @param {string} name
62
+ * @returns
68
63
  */ del(name) {
69
64
  name = String(name).toLowerCase();
70
65
  let deleted = false;
@@ -78,7 +73,13 @@ export default class Caseless {
78
73
  }
79
74
  return changed === 0 ? true : deleted;
80
75
  }
81
- }
76
+ /**
77
+ * @param {*} dict
78
+ */ constructor(dict){
79
+ this.dict = dict || {};
80
+ }
81
+ };
82
+ export { Caseless as default };
82
83
  /**
83
84
  *
84
85
  * @param {*} resp
@@ -87,32 +88,32 @@ export default class Caseless {
87
88
  */ export function httpify(resp, headers) {
88
89
  const c = new Caseless(headers);
89
90
  /**
90
- *
91
- * @param {string} key
92
- * @param {*} value
93
- * @param {*} clobber
94
- * @returns
91
+ *
92
+ * @param {string} key
93
+ * @param {*} value
94
+ * @param {*} clobber
95
+ * @returns
95
96
  */ resp.setHeader = (key, value, clobber)=>{
96
97
  if (typeof value === 'undefined') return;
97
98
  return c.set(key, value, clobber);
98
99
  };
99
100
  /**
100
- *
101
- * @param {string} key
101
+ *
102
+ * @param {string} key
102
103
  * @returns {boolean|string}
103
104
  */ resp.hasHeader = (key)=>{
104
105
  return c.has(key);
105
106
  };
106
107
  /**
107
- *
108
- * @param {string} key
108
+ *
109
+ * @param {string} key
109
110
  * @returns {*}
110
111
  */ resp.getHeader = (key)=>{
111
112
  return c.get(key);
112
113
  };
113
114
  /**
114
- *
115
- * @param {string} key
115
+ *
116
+ * @param {string} key
116
117
  * @returns {boolean}
117
118
  */ resp.removeHeader = (key)=>{
118
119
  return c.del(key);
package/lib/index.js CHANGED
@@ -3,8 +3,8 @@
3
3
  * used by axios
4
4
  * 修改以支持http、https 代理服务器
5
5
  * 代理模式下,http or https 请求,取决于 proxy 代理服务器,而不是目的服务器。
6
- */ import stream from 'node:stream';
7
- import { log as Log, name } from '@wiajs/log';
6
+ */ import { log as Log, name } from '@wiajs/log';
7
+ import stream from 'stream';
8
8
  import Request from './request.js';
9
9
  import utils from './utils.js';
10
10
  const log = Log({
@@ -91,12 +91,16 @@ const log = Log({
91
91
  ...opts
92
92
  };
93
93
  if (!utils.isString(opt.host) && !utils.isString(opt.hostname)) opt.hostname = '::1';
94
- opt.method = (opt.method ?? 'get').toUpperCase();
94
+ var _opt_method;
95
+ opt.method = ((_opt_method = opt.method) != null ? _opt_method : 'get').toUpperCase();
96
+ var _opt_maxBodyLength;
95
97
  // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
96
- opt.maxBodyLength = opt.maxBodyLength ?? Number.POSITIVE_INFINITY;
97
- opt.maxRedirects = opt.maxRedirects ?? 21;
98
+ opt.maxBodyLength = (_opt_maxBodyLength = opt.maxBodyLength) != null ? _opt_maxBodyLength : Number.POSITIVE_INFINITY;
99
+ var _opt_maxRedirects;
100
+ opt.maxRedirects = (_opt_maxRedirects = opt.maxRedirects) != null ? _opt_maxRedirects : 21;
98
101
  if (opt.maxRedirects === 0) opt.followRedirects = false;
99
- opt.headers = opt.headers ?? {
102
+ var _opt_headers;
103
+ opt.headers = (_opt_headers = opt.headers) != null ? _opt_headers : {
100
104
  Accept: 'application/json, text/plain, */*',
101
105
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
102
106
  'Accept-Encoding': 'gzip, compress, deflate, br'
@@ -128,7 +132,7 @@ const log = Log({
128
132
  try {
129
133
  // @ts-ignore
130
134
  const { opt, cb } = init(uri, opts, callback);
131
- // log.error({uri, options, opts}, 'request')
135
+ // log({uri, opt, opts}, 'request')
132
136
  const { data, stream } = opt;
133
137
  // data 在本函数完成处理,不传递到 request
134
138
  opt.data = undefined;
package/lib/request.js CHANGED
@@ -1,18 +1,17 @@
1
1
  /**
2
2
  * fork from follow-redirects
3
3
  * https://github.com/follow-redirects/follow-redirects
4
- */ import http from 'node:http';
5
- import https from 'node:https';
6
- import assert from 'node:assert';
7
- import url from 'node:url';
8
- import stream from 'node:stream';
9
- import { Duplex } from 'node:stream'; // Writable 流改为读写双工
10
- import zlib from 'node:zlib';
4
+ */ import { log as Log, name } from '@wiajs/log';
5
+ import assert from 'assert';
6
+ import http from 'http';
7
+ import https from 'https';
11
8
  import mime from 'mime-types';
12
- import { log as Log, name } from '@wiajs/log';
9
+ import stream, { Duplex } from 'node:stream';
10
+ import url from 'url';
11
+ import zlib from 'zlib';
13
12
  import ZlibTransform from './ZlibTransform.js';
14
- import utils from './utils.js';
15
13
  import Caseless from './caseless.js';
14
+ import utils from './utils.js';
16
15
  const log = Log({
17
16
  env: `wia:req:${name(import.meta.url)}`
18
17
  }) // __filename
@@ -136,96 +135,7 @@ const HostNotfoundError = utils.createErrorType('ERR_HOSTNOTFOUND', 'DNS 解析
136
135
  const ConnRefusedError = utils.createErrorType('ERR_CONNREFUSED', '连接被拒绝,目标服务器可能不可用');
137
136
  const ConnTimedoutError = utils.createErrorType('ERR_CONNTIMEDOUT', '请求超时,请检查网络连接或服务器负载');
138
137
  const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置,可能是网络问题或服务器关闭了连接');
139
- /**
140
- * An HTTP(S) request that can be redirected
141
- * wrap http.ClientRequest
142
- */ export default class Request extends Duplex {
143
- /**
144
- * responseCallback 原消息处理回调
145
- * @param {Opts} opts
146
- * @param {*} resCallback
147
- */ constructor(opts, resCallback){
148
- super(), /** @type {NodeJS.Timeout} */ this._timeout = null, /** @type {*} */ this.socket = null, /** @type {http.ClientRequest} */ this._currentRequest = null, /** @type {Response} */ this.response = null, /** @type {stream.Readable} */ this.responseStream = null, this.timing = false, this.responseStarted = false, this.responseStartTime = 0, this._destdata = false, this._paused = false, this._respended = false, /** @type {stream.Readable} */ this.pipesrc = null // 被 pipe 时的 src stream
149
- , /** @type {stream.Writable[]} */ this.pipedests = [] // pipe dest
150
- , /** @type {*} */ this.startTimer = null;
151
- const m = this;
152
- // log({opts}, 'new Request')
153
- // Initialize the request
154
- m.sanitizeOptions(opts);
155
- m.opt = opts;
156
- m.headers = opts.headers;
157
- // log({opts}, 'constructor')
158
- m._ended = false;
159
- m._ending = false;
160
- m._redirectCount = 0;
161
- /** @type {any[]} */ m._redirects = [];
162
- m._requestBodyLength = 0;
163
- /** @type {any[]} */ m._requestBodyBuffers = [];
164
- // save the callback if passed
165
- m.resCallback = resCallback;
166
- /**
167
- * React to responses of native requests
168
- * 接管 response 事件,非重定向,触发 response 事件
169
- * @param {Response} res
170
- */ m._onResponse = (res)=>{
171
- try {
172
- m.processResponse(res);
173
- } catch (cause) {
174
- m.emit('error', cause instanceof RedirectionError ? cause : new RedirectionError({
175
- cause: cause
176
- }));
177
- }
178
- };
179
- // Proxy all other public ClientRequest methods 'getHeader'
180
- for (const method of writeMethods){
181
- // @ts-ignore
182
- m[method] = (a, b)=>{
183
- // log(method, {a, b})
184
- // @ts-ignore
185
- m._currentRequest?.[method](a, b);
186
- };
187
- }
188
- // Proxy all public ClientRequest properties
189
- // 'aborted', 'connection' 弃用
190
- for (const property of writeProps){
191
- Object.defineProperty(m, property, {
192
- get () {
193
- // @ts-ignore
194
- const val = m._currentRequest?.[property];
195
- // log('get property', {property})
196
- return val;
197
- }
198
- });
199
- }
200
- // 流模式
201
- if (opts.stream) {
202
- // 被 pipe 作为目标时触发,拷贝 src headers
203
- m.on('pipe', /** @param {stream.Readable & {headers?: Object.<string, string>}} src */ (src)=>{
204
- // m.ntick &&
205
- if (m._currentRequest) {
206
- m.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'));
207
- }
208
- m.pipesrc = src;
209
- if (utils.isReadStream(src)) {
210
- // @ts-ignore
211
- if (!m.hasHeader('content-type')) m.setHeader('content-type', mime.lookup(src.path));
212
- } else {
213
- // 拷贝请求头
214
- if (src.headers) {
215
- for (const k of Object.keys(src.headers)){
216
- if (!m.hasHeader(k)) {
217
- m.setHeader(k, src.headers[k]);
218
- }
219
- }
220
- }
221
- // @ts-ignore
222
- if (src.opt.method && !m.opt.method) m.opt.method = src.opt.method;
223
- }
224
- });
225
- }
226
- // Perform the first request
227
- // m.request(); // 创建时不连接,写入数据时连接,否则 pipe 时无法写入header
228
- }
138
+ let Request = class Request extends Duplex {
229
139
  /**
230
140
  * Executes the next native request (initial or redirect)
231
141
  * @returns http(s) 实例
@@ -259,12 +169,17 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
259
169
  if (protocol === 'http:' && agents.http) {
260
170
  protocol = agents.http.proxy && !agents.http.tunnel ? agents.http.proxy.protocol : protocol;
261
171
  }
172
+ // log({scheme, agents, protocol}, 'request')
262
173
  }
263
174
  const httpModule = httpModules[protocol];
264
175
  if (!httpModule) throw TypeError(`Unsupported protocol: ${protocol}`);
265
176
  // log({opt, protocol}, 'request')
266
177
  // Create the native request and set up its event handlers
267
178
  // @ts-ignore
179
+ log({
180
+ httpModule,
181
+ opt
182
+ }, 'request');
268
183
  const req = httpModule.request(opt, m._onResponse);
269
184
  m._currentRequest = req;
270
185
  // @ts-ignore
@@ -283,10 +198,10 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
283
198
  ;
284
199
  // @ts-ignore
285
200
  log.error({
286
- errcode: err?.code
201
+ errcode: err == null ? void 0 : err.code
287
202
  }, 'request');
288
203
  // @ts-ignore
289
- switch(err?.code){
204
+ switch(err == null ? void 0 : err.code){
290
205
  case 'ENOTFOUND':
291
206
  m.emit('error', new HostNotfoundError());
292
207
  break;
@@ -486,21 +401,24 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
486
401
  * @param {string} name
487
402
  * @param {string} value
488
403
  */ setHeader(name, value) {
404
+ var _this__currentRequest;
489
405
  this.opt.headers[name] = value;
490
- this._currentRequest?.setHeader(name, value);
406
+ (_this__currentRequest = this._currentRequest) == null ? void 0 : _this__currentRequest.setHeader(name, value);
491
407
  }
492
408
  /**
493
409
  * Clears a header value on the current native request
494
410
  * @param {string} name
495
411
  */ removeHeader(name) {
412
+ var _this__currentRequest;
496
413
  delete this.opt.headers[name];
497
- this._currentRequest?.removeHeader(name);
414
+ (_this__currentRequest = this._currentRequest) == null ? void 0 : _this__currentRequest.removeHeader(name);
498
415
  }
499
416
  /**
500
417
  * 标头是否已发送
501
418
  * @returns
502
419
  */ get headersSent() {
503
- return this._currentRequest?.headersSent;
420
+ var _this__currentRequest;
421
+ return (_this__currentRequest = this._currentRequest) == null ? void 0 : _this__currentRequest.headersSent;
504
422
  }
505
423
  /**
506
424
  * Global timeout for all underlying requests
@@ -633,7 +551,7 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
633
551
  // NOTE: responseStartTime is deprecated in favor of .timings
634
552
  response.responseStartTime = m.responseStartTime;
635
553
  // 触发原回调函数
636
- m.resCallback?.(response, responseStream);
554
+ m.resCallback == null ? void 0 : m.resCallback.call(m, response, responseStream);
637
555
  // 类似 ClientRequest,触发 response 事件
638
556
  m.emit('response', response, responseStream);
639
557
  // Clean up
@@ -884,7 +802,7 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
884
802
  const m = this;
885
803
  const { response } = m;
886
804
  // Called after the response is received
887
- if (response?.headers && dest.headers && !dest.headersSent) {
805
+ if ((response == null ? void 0 : response.headers) && dest.headers && !dest.headersSent) {
888
806
  const caseless = new Caseless(response.headers);
889
807
  if (caseless.has('content-type')) {
890
808
  const ctname = /** @type {string} */ caseless.has('content-type');
@@ -903,7 +821,7 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
903
821
  }
904
822
  }
905
823
  }
906
- if (response?.headers && dest.setHeader && !dest.headersSent) {
824
+ if ((response == null ? void 0 : response.headers) && dest.setHeader && !dest.headersSent) {
907
825
  for (const k of Object.keys(response.headers))dest.setHeader(k, response.headers[k]);
908
826
  dest.statusCode = response.statusCode;
909
827
  }
@@ -929,7 +847,99 @@ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置
929
847
  isPaused() {
930
848
  return this._paused;
931
849
  }
932
- }
850
+ /**
851
+ * responseCallback 原消息处理回调
852
+ * @param {Opts} opts
853
+ * @param {*} resCallback
854
+ */ constructor(opts, resCallback){
855
+ super(), /** @type {NodeJS.Timeout} */ this._timeout = null, /** @type {*} */ this.socket = null, /** @type {http.ClientRequest} */ this._currentRequest = null, /** @type {Response} */ this.response = null, /** @type {stream.Readable} */ this.responseStream = null, this.timing = false, this.responseStarted = false, this.responseStartTime = 0, this._destdata = false, this._paused = false, this._respended = false, /** @type {stream.Readable} */ this.pipesrc = null // 被 pipe 时的 src stream
856
+ , /** @type {stream.Writable[]} */ this.pipedests = [] // pipe dest
857
+ , /** @type {*} */ this.startTimer = null;
858
+ const m = this;
859
+ // log({opts}, 'new Request')
860
+ // Initialize the request
861
+ m.sanitizeOptions(opts);
862
+ m.opt = opts;
863
+ m.headers = opts.headers;
864
+ // log({opts}, 'constructor')
865
+ m._ended = false;
866
+ m._ending = false;
867
+ m._redirectCount = 0;
868
+ /** @type {any[]} */ m._redirects = [];
869
+ m._requestBodyLength = 0;
870
+ /** @type {any[]} */ m._requestBodyBuffers = [];
871
+ // save the callback if passed
872
+ m.resCallback = resCallback;
873
+ /**
874
+ * React to responses of native requests
875
+ * 接管 response 事件,非重定向,触发 response 事件
876
+ * @param {Response} res
877
+ */ m._onResponse = (res)=>{
878
+ try {
879
+ m.processResponse(res);
880
+ } catch (cause) {
881
+ m.emit('error', cause instanceof RedirectionError ? cause : new RedirectionError({
882
+ cause: cause
883
+ }));
884
+ }
885
+ };
886
+ // Proxy all other public ClientRequest methods 'getHeader'
887
+ for (const method of writeMethods){
888
+ // @ts-ignore
889
+ m[method] = (a, b)=>{
890
+ var // log(method, {a, b})
891
+ // @ts-ignore
892
+ _m__currentRequest;
893
+ (_m__currentRequest = m._currentRequest) == null ? void 0 : _m__currentRequest[method](a, b);
894
+ };
895
+ }
896
+ // Proxy all public ClientRequest properties
897
+ // 'aborted', 'connection' 弃用
898
+ for (const property of writeProps){
899
+ Object.defineProperty(m, property, {
900
+ get () {
901
+ var _m__currentRequest;
902
+ // @ts-ignore
903
+ const val = (_m__currentRequest = m._currentRequest) == null ? void 0 : _m__currentRequest[property];
904
+ // log('get property', {property})
905
+ return val;
906
+ }
907
+ });
908
+ }
909
+ // 流模式
910
+ if (opts.stream) {
911
+ // 被 pipe 作为目标时触发,拷贝 src headers
912
+ m.on('pipe', /** @param {stream.Readable & {headers?: Object.<string, string>}} src */ (src)=>{
913
+ // m.ntick &&
914
+ if (m._currentRequest) {
915
+ m.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'));
916
+ }
917
+ m.pipesrc = src;
918
+ if (utils.isReadStream(src)) {
919
+ // @ts-ignore
920
+ if (!m.hasHeader('content-type')) m.setHeader('content-type', mime.lookup(src.path));
921
+ } else {
922
+ // 拷贝请求头
923
+ if (src.headers) {
924
+ for (const k of Object.keys(src.headers)){
925
+ if (!m.hasHeader(k)) {
926
+ m.setHeader(k, src.headers[k]);
927
+ }
928
+ }
929
+ }
930
+ // @ts-ignore
931
+ if (src.opt.method && !m.opt.method) m.opt.method = src.opt.method;
932
+ }
933
+ });
934
+ }
935
+ // Perform the first request
936
+ // m.request(); // 创建时不连接,写入数据时连接,否则 pipe 时无法写入header
937
+ }
938
+ };
939
+ /**
940
+ * An HTTP(S) request that can be redirected
941
+ * wrap http.ClientRequest
942
+ */ export { Request as default };
933
943
  /**
934
944
  * 释放请求,触发error事件
935
945
  * 'error' event, and emit a 'close' event.
package/lib/utils.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * utils for request
3
- */ import url from 'node:url';
4
- import assert from 'node:assert';
3
+ */ import assert from 'assert';
4
+ import url from 'url';
5
5
  const { URL } = url;
6
6
  // Whether to use the native URL object or the legacy url module
7
7
  let useNativeURL = false;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@wiajs/request",
3
3
  "description": "Stream HTTP request client.",
4
4
  "keywords": ["http", "simple", "util", "utility"],
5
- "version": "3.0.33",
5
+ "version": "3.0.36",
6
6
  "type": "module",
7
7
  "main": "index.js",
8
8
  "types": "types/index.d.ts",
@@ -26,7 +26,6 @@
26
26
  },
27
27
  "scripts": {
28
28
  "build": "cross-env NODE_ENV=production gulp build -f gulpfile.js",
29
- "lib": "swc --config-file ./.swcrc ./src -d lib -w --strip-leading-paths",
30
29
  "test": "npm run lint && npm run test-ci && npm run test-browser",
31
30
  "test-ci": "taper tests/test-*.js",
32
31
  "test-cov": "nyc --reporter=lcov tape tests/test-*.js",
@@ -37,7 +36,7 @@
37
36
  "contributors": ["Mikeal Rogers <mikeal.rogers@gmail.com>"],
38
37
  "repository": {
39
38
  "type": "git",
40
- "url": "https://github.com/request/request.git"
39
+ "url": "https://github.com/@wiajs/request.git"
41
40
  },
42
41
  "license": "MIT",
43
42
  "publishConfig": {