urllib 2.37.4 → 3.0.0-alpha.1

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 (47) hide show
  1. package/README.md +117 -212
  2. package/package.json +58 -57
  3. package/src/HttpClient.ts +295 -0
  4. package/src/Request.ts +121 -0
  5. package/src/Response.ts +40 -0
  6. package/src/cjs/HttpClient.d.ts +12 -0
  7. package/src/cjs/HttpClient.js +293 -0
  8. package/src/cjs/HttpClient.js.map +1 -0
  9. package/src/cjs/Request.d.ts +121 -0
  10. package/src/cjs/Request.js +3 -0
  11. package/src/cjs/Request.js.map +1 -0
  12. package/src/cjs/Response.d.ts +35 -0
  13. package/src/cjs/Response.js +3 -0
  14. package/src/cjs/Response.js.map +1 -0
  15. package/src/cjs/index.d.ts +7 -0
  16. package/src/cjs/index.js +18 -0
  17. package/src/cjs/index.js.map +1 -0
  18. package/src/cjs/package.json +3 -0
  19. package/src/cjs/utils.d.ts +2 -0
  20. package/src/cjs/utils.js +50 -0
  21. package/src/cjs/utils.js.map +1 -0
  22. package/src/esm/HttpClient.d.ts +12 -0
  23. package/src/esm/HttpClient.js +289 -0
  24. package/src/esm/HttpClient.js.map +1 -0
  25. package/src/esm/Request.d.ts +121 -0
  26. package/src/esm/Request.js +2 -0
  27. package/src/esm/Request.js.map +1 -0
  28. package/src/esm/Response.d.ts +35 -0
  29. package/src/esm/Response.js +2 -0
  30. package/src/esm/Response.js.map +1 -0
  31. package/src/esm/index.d.ts +7 -0
  32. package/src/esm/index.js +13 -0
  33. package/src/esm/index.js.map +1 -0
  34. package/src/esm/package.json +3 -0
  35. package/src/esm/utils.d.ts +2 -0
  36. package/src/esm/utils.js +46 -0
  37. package/src/esm/utils.js.map +1 -0
  38. package/src/index.ts +17 -0
  39. package/src/utils.ts +47 -0
  40. package/History.md +0 -785
  41. package/lib/detect_proxy_agent.js +0 -31
  42. package/lib/get_proxy_from_uri.js +0 -81
  43. package/lib/httpclient.js +0 -61
  44. package/lib/httpclient2.js +0 -83
  45. package/lib/index.d.ts +0 -267
  46. package/lib/index.js +0 -21
  47. package/lib/urllib.js +0 -1305
@@ -0,0 +1,289 @@
1
+ var _BlobFromStream_stream, _BlobFromStream_type;
2
+ import { __classPrivateFieldGet, __classPrivateFieldSet } from "tslib";
3
+ import { EventEmitter } from 'events';
4
+ import { debuglog } from 'util';
5
+ import { Readable, isReadable } from 'stream';
6
+ import { pipeline } from 'stream/promises';
7
+ import { Blob } from 'buffer';
8
+ import { createReadStream } from 'fs';
9
+ import { basename } from 'path';
10
+ import { fetch, Headers, FormData, } from 'undici';
11
+ import createUserAgent from 'default-user-agent';
12
+ import mime from 'mime-types';
13
+ import { parseJSON } from './utils.js';
14
+ const debug = debuglog('urllib');
15
+ // https://github.com/octet-stream/form-data
16
+ class BlobFromStream {
17
+ constructor(stream, type) {
18
+ _BlobFromStream_stream.set(this, void 0);
19
+ _BlobFromStream_type.set(this, void 0);
20
+ __classPrivateFieldSet(this, _BlobFromStream_stream, stream, "f");
21
+ __classPrivateFieldSet(this, _BlobFromStream_type, type, "f");
22
+ }
23
+ stream() {
24
+ return __classPrivateFieldGet(this, _BlobFromStream_stream, "f");
25
+ }
26
+ get type() {
27
+ return __classPrivateFieldGet(this, _BlobFromStream_type, "f");
28
+ }
29
+ get [(_BlobFromStream_stream = new WeakMap(), _BlobFromStream_type = new WeakMap(), Symbol.toStringTag)]() {
30
+ return 'Blob';
31
+ }
32
+ }
33
+ class HttpClientRequestTimeoutError extends Error {
34
+ constructor(timeout, options) {
35
+ const message = `Request timeout for ${timeout} ms`;
36
+ super(message, options);
37
+ this.name = this.constructor.name;
38
+ Error.captureStackTrace(this, this.constructor);
39
+ }
40
+ }
41
+ const HEADER_USER_AGENT = createUserAgent('node-urllib', '3.0.0');
42
+ function getFileName(stream) {
43
+ const filePath = stream.path;
44
+ if (filePath) {
45
+ return basename(filePath);
46
+ }
47
+ return '';
48
+ }
49
+ export class HttpClient extends EventEmitter {
50
+ constructor(clientOptions) {
51
+ super();
52
+ this.defaultArgs = clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.defaultArgs;
53
+ }
54
+ async request(url, options) {
55
+ var _a, _b, _c, _d;
56
+ const requestUrl = typeof url === 'string' ? new URL(url) : url;
57
+ const args = {
58
+ ...this.defaultArgs,
59
+ ...options,
60
+ emitter: this,
61
+ };
62
+ const requestStartTime = Date.now();
63
+ // keep urllib createCallbackResponse style
64
+ const resHeaders = {};
65
+ const res = {
66
+ status: -1,
67
+ statusCode: -1,
68
+ statusMessage: '',
69
+ headers: resHeaders,
70
+ size: 0,
71
+ aborted: false,
72
+ rt: 0,
73
+ keepAliveSocket: true,
74
+ requestUrls: [url.toString()],
75
+ timing: {
76
+ contentDownload: 0,
77
+ },
78
+ };
79
+ let requestTimeout = 5000;
80
+ if (args.timeout) {
81
+ if (Array.isArray(args.timeout)) {
82
+ requestTimeout = (_a = args.timeout[args.timeout.length - 1]) !== null && _a !== void 0 ? _a : requestTimeout;
83
+ }
84
+ else {
85
+ requestTimeout = args.timeout;
86
+ }
87
+ }
88
+ const requestTimeoutController = new AbortController();
89
+ const requestTimerId = setTimeout(() => requestTimeoutController.abort(), requestTimeout);
90
+ const method = ((_b = args.method) !== null && _b !== void 0 ? _b : 'GET').toUpperCase();
91
+ try {
92
+ const headers = new Headers((_c = args.headers) !== null && _c !== void 0 ? _c : {});
93
+ if (!headers.has('user-agent')) {
94
+ // need to set user-agent
95
+ headers.set('user-agent', HEADER_USER_AGENT);
96
+ }
97
+ if (args.dataType === 'json' && !headers.has('accept')) {
98
+ headers.set('accept', 'application/json');
99
+ }
100
+ const requestOptions = {
101
+ method,
102
+ keepalive: true,
103
+ signal: requestTimeoutController.signal,
104
+ };
105
+ if (args.followRedirect === false) {
106
+ requestOptions.redirect = 'manual';
107
+ }
108
+ const isGETOrHEAD = requestOptions.method === 'GET' || requestOptions.method === 'HEAD';
109
+ // alias to args.content
110
+ if (args.stream && !args.content) {
111
+ args.content = args.stream;
112
+ }
113
+ if (args.files) {
114
+ if (isGETOrHEAD) {
115
+ requestOptions.method = 'POST';
116
+ }
117
+ const formData = new FormData();
118
+ const uploadFiles = [];
119
+ if (Array.isArray(args.files)) {
120
+ for (const [index, file] of args.files.entries()) {
121
+ const field = index === 0 ? 'file' : `file${index}`;
122
+ uploadFiles.push([field, file]);
123
+ }
124
+ }
125
+ else if (args.files instanceof Readable || isReadable(args.files)) {
126
+ uploadFiles.push(['file', args.files]);
127
+ }
128
+ else if (typeof args.files === 'string' || Buffer.isBuffer(args.files)) {
129
+ uploadFiles.push(['file', args.files]);
130
+ }
131
+ else if (typeof args.files === 'object') {
132
+ for (const field in args.files) {
133
+ uploadFiles.push([field, args.files[field]]);
134
+ }
135
+ }
136
+ // set normal fields first
137
+ if (args.data) {
138
+ for (const field in args.data) {
139
+ formData.append(field, args.data[field]);
140
+ }
141
+ }
142
+ for (const [index, [field, file]] of uploadFiles.entries()) {
143
+ if (typeof file === 'string') {
144
+ // FIXME: support non-ascii filename
145
+ // const fileName = encodeURIComponent(basename(file));
146
+ // formData.append(field, await fileFromPath(file, `utf-8''${fileName}`, { type: mime.lookup(fileName) || '' }));
147
+ const fileName = basename(file);
148
+ const fileReader = createReadStream(file);
149
+ formData.append(field, new BlobFromStream(fileReader, mime.lookup(fileName) || ''), fileName);
150
+ }
151
+ else if (Buffer.isBuffer(file)) {
152
+ formData.append(field, new Blob([file]), `bufferfile${index}`);
153
+ }
154
+ else if (file instanceof Readable || isReadable(file)) {
155
+ const fileName = getFileName(file) || `streamfile${index}`;
156
+ formData.append(field, new BlobFromStream(file, mime.lookup(fileName) || ''), fileName);
157
+ }
158
+ }
159
+ requestOptions.body = formData;
160
+ }
161
+ else if (args.content) {
162
+ if (!isGETOrHEAD) {
163
+ if (isReadable(args.content)) {
164
+ // disable keepalive
165
+ requestOptions.keepalive = false;
166
+ }
167
+ // handle content
168
+ requestOptions.body = args.content;
169
+ if (args.contentType) {
170
+ headers.set('content-type', args.contentType);
171
+ }
172
+ }
173
+ }
174
+ else if (args.data) {
175
+ const isStringOrBufferOrReadable = typeof args.data === 'string'
176
+ || Buffer.isBuffer(args.data)
177
+ || isReadable(args.data);
178
+ if (isGETOrHEAD) {
179
+ if (!isStringOrBufferOrReadable) {
180
+ for (const field in args.data) {
181
+ requestUrl.searchParams.append(field, args.data[field]);
182
+ }
183
+ }
184
+ }
185
+ else {
186
+ if (isStringOrBufferOrReadable) {
187
+ if (isReadable(args.data)) {
188
+ // disable keepalive
189
+ requestOptions.keepalive = false;
190
+ }
191
+ requestOptions.body = args.data;
192
+ }
193
+ else {
194
+ if (args.contentType === 'json'
195
+ || args.contentType === 'application/json'
196
+ || ((_d = headers.get('content-type')) === null || _d === void 0 ? void 0 : _d.startsWith('application/json'))) {
197
+ requestOptions.body = JSON.stringify(args.data);
198
+ if (!headers.has('content-type')) {
199
+ headers.set('content-type', 'application/json');
200
+ }
201
+ }
202
+ else {
203
+ requestOptions.body = new URLSearchParams(args.data);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ debug('%s %s, headers: %j, timeout: %s', requestOptions.method, url, headers, requestTimeout);
209
+ requestOptions.headers = headers;
210
+ const response = await fetch(requestUrl, requestOptions);
211
+ for (const [name, value] of response.headers) {
212
+ res.headers[name] = value;
213
+ }
214
+ res.status = res.statusCode = response.status;
215
+ res.statusMessage = response.statusText;
216
+ if (response.redirected) {
217
+ res.requestUrls.push(response.url);
218
+ }
219
+ if (res.headers['content-length']) {
220
+ res.size = parseInt(res.headers['content-length']);
221
+ }
222
+ let data = null;
223
+ let responseBodyStream;
224
+ if (args.streaming || args.dataType === 'stream') {
225
+ const meta = {
226
+ status: res.status,
227
+ statusCode: res.statusCode,
228
+ statusMessage: res.statusMessage,
229
+ headers: res.headers,
230
+ };
231
+ if (typeof Readable.fromWeb === 'function') {
232
+ responseBodyStream = Object.assign(Readable.fromWeb(response.body), meta);
233
+ }
234
+ else {
235
+ responseBodyStream = Object.assign(response.body, meta);
236
+ }
237
+ }
238
+ else if (args.writeStream) {
239
+ await pipeline(response.body, args.writeStream);
240
+ }
241
+ else if (args.dataType === 'text') {
242
+ data = await response.text();
243
+ }
244
+ else if (args.dataType === 'json') {
245
+ if (requestOptions.method === 'HEAD') {
246
+ data = {};
247
+ }
248
+ else {
249
+ data = await response.text();
250
+ if (data.length === 0) {
251
+ data = null;
252
+ }
253
+ else {
254
+ data = parseJSON(data, args.fixJSONCtlChars);
255
+ }
256
+ }
257
+ }
258
+ else {
259
+ // buffer
260
+ data = Buffer.from(await response.arrayBuffer());
261
+ }
262
+ res.rt = res.timing.contentDownload = Date.now() - requestStartTime;
263
+ const clientResponse = {
264
+ status: res.status,
265
+ data,
266
+ headers: res.headers,
267
+ url: response.url,
268
+ redirected: response.redirected,
269
+ res: responseBodyStream !== null && responseBodyStream !== void 0 ? responseBodyStream : res,
270
+ };
271
+ return clientResponse;
272
+ }
273
+ catch (e) {
274
+ let err = e;
275
+ if (requestTimeoutController.signal.aborted) {
276
+ err = new HttpClientRequestTimeoutError(requestTimeout, { cause: e });
277
+ }
278
+ err.res = res;
279
+ err.status = res.status;
280
+ err.headers = res.headers;
281
+ // console.error(err);
282
+ throw err;
283
+ }
284
+ finally {
285
+ clearTimeout(requestTimerId);
286
+ }
287
+ }
288
+ }
289
+ //# sourceMappingURL=HttpClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpClient.js","sourceRoot":"","sources":["../HttpClient.ts"],"names":[],"mappings":";;AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,IAAI,CAAC;AACtC,OAAO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C,GAAG,EAAE,GAAG,gBAAgB,CAAC;YAEpE,MAAM,cAAc,GAAuB;gBACzC,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,IAAI;gBACJ,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,GAAG,EAAE,QAAQ,CAAC,GAAG;gBACjB,UAAU,EAAE,QAAQ,CAAC,UAAU;gBAC/B,GAAG,EAAE,kBAAkB,aAAlB,kBAAkB,cAAlB,kBAAkB,GAAI,GAAG;aAC/B,CAAC;YACF,OAAO,cAAc,CAAC;SACvB;QAAC,OAAO,CAAM,EAAE;YACf,IAAI,GAAG,GAAG,CAAC,CAAC;YACZ,IAAI,wBAAwB,CAAC,MAAM,CAAC,OAAO,EAAE;gBAC3C,GAAG,GAAG,IAAI,6BAA6B,CAAC,cAAc,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;aACvE;YACD,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC;YACd,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;YACxB,GAAG,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;YAC1B,sBAAsB;YACtB,MAAM,GAAG,CAAC;SACX;gBAAS;YACR,YAAY,CAAC,cAAc,CAAC,CAAC;SAC9B;IACH,CAAC;CACF"}
@@ -0,0 +1,121 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ /// <reference types="node" />
5
+ import { Readable, Writable } from 'stream';
6
+ import { LookupFunction } from 'net';
7
+ export declare type HttpMethod = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'TRACE' | 'CONNECT';
8
+ export declare type RequestURL = string | URL;
9
+ export declare type FixJSONCtlCharsHandler = (data: string) => string;
10
+ export declare type FixJSONCtlChars = boolean | FixJSONCtlCharsHandler;
11
+ export declare type RequestOptions = {
12
+ /** Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'. */
13
+ method?: HttpMethod | Lowercase<HttpMethod>;
14
+ /** Data to be sent. Will be stringify automatically. */
15
+ data?: any;
16
+ /** Force convert data to query string. */
17
+ dataAsQueryString?: boolean;
18
+ /** Manually set the content of payload. If set, data will be ignored. */
19
+ content?: string | Buffer | Readable;
20
+ /** Stream to be pipe to the remote. If set, data and content will be ignored.
21
+ * Alias to `content` on Readable
22
+ */
23
+ stream?: Readable;
24
+ /**
25
+ * A writable stream to be piped by the response stream.
26
+ * Responding data will be write to this stream and callback
27
+ * will be called with data set null after finished writing.
28
+ */
29
+ writeStream?: Writable;
30
+ /** consume the writeStream, invoke the callback after writeStream close. */
31
+ consumeWriteStream?: boolean;
32
+ /**
33
+ * The files will send with multipart/form-data format, base on formstream.
34
+ * If method not set, will use POST method by default.
35
+ */
36
+ files?: Array<Readable | Buffer | string> | Record<string, Readable | Buffer | string> | Readable | Buffer | string;
37
+ /** Type of request data, could be 'json'. If it's 'json', will auto set Content-Type: 'application/json' header. */
38
+ contentType?: string;
39
+ /**
40
+ * Type of response data. Could be text or json.
41
+ * If it's text, the callbacked data would be a String.
42
+ * If it's json, the data of callback would be a parsed JSON Object
43
+ * and will auto set Accept: 'application/json' header.
44
+ * Default is buffer.
45
+ */
46
+ dataType?: 'text' | 'json' | 'buffer' | 'stream';
47
+ /**
48
+ * Let you get the res object when request connected, default false.
49
+ * If set to true, `data` will be response readable stream.
50
+ * Equal to `dataType = 'stream'`
51
+ */
52
+ streaming?: boolean;
53
+ /** Fix the control characters (U+0000 through U+001F) before JSON parse response. Default is false. */
54
+ fixJSONCtlChars?: FixJSONCtlChars;
55
+ /** Request headers. */
56
+ headers?: Record<string, string>;
57
+ /**
58
+ * Request timeout in milliseconds for connecting phase and response receiving phase.
59
+ * Defaults to exports.
60
+ * TIMEOUT, both are 5s. You can use timeout: 5000 to tell urllib use same timeout on two phase or set them seperately such as
61
+ * timeout: [3000, 5000], which will set connecting timeout to 3s and response 5s.
62
+ */
63
+ timeout?: number | number[];
64
+ /** username:password used in HTTP Basic Authorization. */
65
+ auth?: string;
66
+ /** username:password used in HTTP Digest Authorization. */
67
+ digestAuth?: string;
68
+ /**
69
+ * An array of strings or Buffers of trusted certificates.
70
+ * If this is omitted several well known "root" CAs will be used, like VeriSign.
71
+ * These are used to authorize connections.
72
+ * Notes: This is necessary only if the server uses the self - signed certificate
73
+ */
74
+ ca?: string | Buffer | string[] | Buffer[];
75
+ /**
76
+ * If true, the server certificate is verified against the list of supplied CAs.
77
+ * An 'error' event is emitted if verification fails.Default: true.
78
+ */
79
+ rejectUnauthorized?: boolean;
80
+ /** A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. */
81
+ pfx?: string | Buffer;
82
+ /**
83
+ * A string or Buffer containing the private key of the client in PEM format.
84
+ * Notes: This is necessary only if using the client certificate authentication
85
+ */
86
+ key?: string | Buffer;
87
+ /**
88
+ * A string or Buffer containing the certificate key of the client in PEM format.
89
+ * Notes: This is necessary only if using the client certificate authentication
90
+ */
91
+ cert?: string | Buffer;
92
+ /** A string of passphrase for the private key or pfx. */
93
+ passphrase?: string;
94
+ /** A string describing the ciphers to use or exclude. */
95
+ ciphers?: string;
96
+ /** The SSL method to use, e.g.SSLv3_method to force SSL version 3. */
97
+ secureProtocol?: string;
98
+ /** follow HTTP 3xx responses as redirects. defaults to false. */
99
+ followRedirect?: boolean;
100
+ /** The maximum number of redirects to follow, defaults to 10. */
101
+ maxRedirects?: number;
102
+ /** Format the redirect url by your self. Default is url.resolve(from, to). */
103
+ formatRedirectUrl?: (a: any, b: any) => void;
104
+ /** Before request hook, you can change every thing here. */
105
+ beforeRequest?: (...args: any[]) => void;
106
+ /** Accept gzip response content and auto decode it, default is false. */
107
+ gzip?: boolean;
108
+ /** Enable timing or not, default is false. */
109
+ timing?: boolean;
110
+ /**
111
+ * Custom DNS lookup function, default is dns.lookup.
112
+ * Require node >= 4.0.0(for http protocol) and node >=8(for https protocol)
113
+ */
114
+ lookup?: LookupFunction;
115
+ /**
116
+ * check request address to protect from SSRF and similar attacks.
117
+ * It receive two arguments(ip and family) and should return true or false to identified the address is legal or not.
118
+ * It rely on lookup and have the same version requirement.
119
+ */
120
+ checkAddress?: (ip: string, family: number | string) => boolean;
121
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Request.js","sourceRoot":"","sources":["../Request.ts"],"names":[],"mappings":""}
@@ -0,0 +1,35 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { ReadableStream } from 'stream/web';
4
+ import { Readable } from 'stream';
5
+ export declare type HttpClientResponseMeta = {
6
+ status: number;
7
+ statusCode: number;
8
+ statusMessage: string;
9
+ headers: Record<string, string>;
10
+ size: number;
11
+ aborted: boolean;
12
+ rt: number;
13
+ keepAliveSocket: boolean;
14
+ requestUrls: string[];
15
+ /**
16
+ * https://eggjs.org/en/core/httpclient.html#timing-boolean
17
+ */
18
+ timing: {
19
+ contentDownload: number;
20
+ };
21
+ };
22
+ export declare type ReadableStreamWithMeta = (Readable | ReadableStream) & {
23
+ status: number;
24
+ statusCode: number;
25
+ statusMessage: string;
26
+ headers: Record<string, string>;
27
+ };
28
+ export declare type HttpClientResponse = {
29
+ data: any;
30
+ status: number;
31
+ headers: Record<string, string>;
32
+ url: string;
33
+ redirected: boolean;
34
+ res: ReadableStreamWithMeta | HttpClientResponseMeta;
35
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Response.js","sourceRoot":"","sources":["../Response.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ import { RequestOptions, RequestURL } from './Request';
2
+ export declare function request(url: RequestURL, options?: RequestOptions): Promise<import("./Response").HttpClientResponse>;
3
+ export { HttpClient } from './HttpClient';
4
+ declare const _default: {
5
+ request: typeof request;
6
+ };
7
+ export default _default;
@@ -0,0 +1,13 @@
1
+ import { HttpClient } from './HttpClient.js';
2
+ let httpclient;
3
+ export async function request(url, options) {
4
+ if (!httpclient) {
5
+ httpclient = new HttpClient();
6
+ }
7
+ return await httpclient.request(url, options);
8
+ }
9
+ export { HttpClient } from './HttpClient.js';
10
+ export default {
11
+ request,
12
+ };
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C,IAAI,UAAsB,CAAC;AAC3B,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,GAAe,EAAE,OAAwB;IACrE,IAAI,CAAC,UAAU,EAAE;QACf,UAAU,GAAG,IAAI,UAAU,EAAE,CAAC;KAC/B;IACD,OAAO,MAAM,UAAU,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC;AAED,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,eAAe;IACb,OAAO;CACR,CAAC"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,2 @@
1
+ import { FixJSONCtlChars } from './Request';
2
+ export declare function parseJSON(data: string, fixJSONCtlChars?: FixJSONCtlChars): string;
@@ -0,0 +1,46 @@
1
+ const JSONCtlCharsMap = {
2
+ '"': '\\"',
3
+ '\\': '\\\\',
4
+ '\b': '\\b',
5
+ '\f': '\\f',
6
+ '\n': '\\n',
7
+ '\r': '\\r',
8
+ '\t': '\\t', // \u0009
9
+ };
10
+ /* eslint no-control-regex: "off"*/
11
+ const JSONCtlCharsRE = /[\u0000-\u001F\u005C]/g;
12
+ function replaceOneChar(c) {
13
+ return JSONCtlCharsMap[c] || '\\u' + (c.charCodeAt(0) + 0x10000).toString(16).substring(1);
14
+ }
15
+ function replaceJSONCtlChars(value) {
16
+ return value.replace(JSONCtlCharsRE, replaceOneChar);
17
+ }
18
+ export function parseJSON(data, fixJSONCtlChars) {
19
+ if (typeof fixJSONCtlChars === 'function') {
20
+ data = fixJSONCtlChars(data);
21
+ }
22
+ else if (fixJSONCtlChars) {
23
+ // https://github.com/node-modules/urllib/pull/77
24
+ // remote the control characters (U+0000 through U+001F)
25
+ data = replaceJSONCtlChars(data);
26
+ }
27
+ try {
28
+ data = JSON.parse(data);
29
+ }
30
+ catch (err) {
31
+ if (err.name === 'SyntaxError') {
32
+ err.name = 'JSONResponseFormatError';
33
+ }
34
+ if (data.length > 1024) {
35
+ // show 0~512 ... -512~end data
36
+ err.message += ' (data json format: ' +
37
+ JSON.stringify(data.slice(0, 512)) + ' ...skip... ' + JSON.stringify(data.slice(data.length - 512)) + ')';
38
+ }
39
+ else {
40
+ err.message += ' (data json format: ' + JSON.stringify(data) + ')';
41
+ }
42
+ throw err;
43
+ }
44
+ return data;
45
+ }
46
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../utils.ts"],"names":[],"mappings":"AAEA,MAAM,eAAe,GAAG;IACtB,GAAG,EAAE,KAAK;IACV,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK;IACX,IAAI,EAAE,KAAK,EAAE,SAAS;CACvB,CAAC;AACF,mCAAmC;AACnC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEhD,SAAS,cAAc,CAAC,CAAS;IAC/B,OAAO,eAAe,CAAC,CAAC,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC7F,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,eAAiC;IACvE,IAAI,OAAO,eAAe,KAAK,UAAU,EAAE;QACzC,IAAI,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;KAC9B;SAAM,IAAI,eAAe,EAAE;QAC1B,iDAAiD;QACjD,wDAAwD;QACxD,IAAI,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAC;KAClC;IACD,IAAI;QACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;KACzB;IAAC,OAAO,GAAQ,EAAE;QACjB,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,EAAE;YAC9B,GAAG,CAAC,IAAI,GAAG,yBAAyB,CAAC;SACtC;QACD,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE;YACtB,+BAA+B;YAC/B,GAAG,CAAC,OAAO,IAAI,sBAAsB;gBACnC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,cAAc,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;SAC7G;aAAM;YACL,GAAG,CAAC,OAAO,IAAI,sBAAsB,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;SACpE;QACD,MAAM,GAAG,CAAC;KACX;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { HttpClient } from './HttpClient';
2
+ import { RequestOptions, RequestURL } from './Request';
3
+
4
+ let httpclient: HttpClient;
5
+ export async function request(url: RequestURL, options?: RequestOptions) {
6
+ if (!httpclient) {
7
+ httpclient = new HttpClient();
8
+ }
9
+ return await httpclient.request(url, options);
10
+ }
11
+
12
+ export { HttpClient } from './HttpClient';
13
+
14
+ export default {
15
+ request,
16
+ };
17
+
package/src/utils.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { FixJSONCtlChars } from './Request';
2
+
3
+ const JSONCtlCharsMap = {
4
+ '"': '\\"', // \u0022
5
+ '\\': '\\\\', // \u005c
6
+ '\b': '\\b', // \u0008
7
+ '\f': '\\f', // \u000c
8
+ '\n': '\\n', // \u000a
9
+ '\r': '\\r', // \u000d
10
+ '\t': '\\t', // \u0009
11
+ };
12
+ /* eslint no-control-regex: "off"*/
13
+ const JSONCtlCharsRE = /[\u0000-\u001F\u005C]/g;
14
+
15
+ function replaceOneChar(c: string) {
16
+ return JSONCtlCharsMap[c] || '\\u' + (c.charCodeAt(0) + 0x10000).toString(16).substring(1);
17
+ }
18
+
19
+ function replaceJSONCtlChars(value: string) {
20
+ return value.replace(JSONCtlCharsRE, replaceOneChar);
21
+ }
22
+
23
+ export function parseJSON(data: string, fixJSONCtlChars?: FixJSONCtlChars) {
24
+ if (typeof fixJSONCtlChars === 'function') {
25
+ data = fixJSONCtlChars(data);
26
+ } else if (fixJSONCtlChars) {
27
+ // https://github.com/node-modules/urllib/pull/77
28
+ // remote the control characters (U+0000 through U+001F)
29
+ data = replaceJSONCtlChars(data);
30
+ }
31
+ try {
32
+ data = JSON.parse(data);
33
+ } catch (err: any) {
34
+ if (err.name === 'SyntaxError') {
35
+ err.name = 'JSONResponseFormatError';
36
+ }
37
+ if (data.length > 1024) {
38
+ // show 0~512 ... -512~end data
39
+ err.message += ' (data json format: ' +
40
+ JSON.stringify(data.slice(0, 512)) + ' ...skip... ' + JSON.stringify(data.slice(data.length - 512)) + ')';
41
+ } else {
42
+ err.message += ' (data json format: ' + JSON.stringify(data) + ')';
43
+ }
44
+ throw err;
45
+ }
46
+ return data;
47
+ }