-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphn.js
More file actions
344 lines (284 loc) · 9.88 KB
/
phn.js
File metadata and controls
344 lines (284 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const path = require("node:path");
const http = require("node:http");
const https = require("node:https");
const http2 = require("node:http2");
const tls = require("node:tls");
const transformStream = require("node:stream").Transform;
const qs = require("node:querystring");
const zlib = require("node:zlib");
const { URL } = require("node:url");
// shim for zstd, uses fzstd if installed
const createZstdDecompress = zlib.createZstdDecompress || (()=>{
try {
const fzstd = require("fzstd");
return ()=>{
return new transformStream({
transform(chunk, encoding, fn) {
try {
if (!this.zstd) this.zstd = new fzstd.Decompress((ch, end) => {
this.push(ch);
if (end) this.push(null);
});
this.zstd.push(chunk);
fn();
} catch (err) {
fn(err);
};
},
flush() {
this.zstd.push(Buffer.alloc(0), true);
}
});
};
} catch (err) {
return null;
};
})();
// shim for iconv-lite
const iconv = (()=>{
try {
return require("iconv-lite");
} catch (err) {
return null;
};
})();
// find available encodings
const supportedCompression = [
(!!createZstdDecompress && "zstd"),
(!!zlib.createBrotliDecompress && "br"),
(!!zlib.createGunzip && "gzip"),
(!!zlib.createInflate && "deflate")
].filter(Boolean).join(", ");
// helper: alpn request
const alpnCache = {};
async function alpn(url) {
return new Promise((resolve) => {
if (alpnCache[url.origin]) return resolve(alpnCache[url.origin]);
const socket = tls.connect({
host: url.hostname,
port: url.port || 443,
servername: url.hostname,
ALPNProtocols: ["h2", "http/1.1"],
});
const settle = (proto) => {
if (!alpnCache[url.origin]) alpnCache[url.origin] = proto || "http/1.1";
try { socket.destroy(); } catch {}
resolve(alpnCache[url.origin]);
};
socket.setTimeout?.(5000, () => settle("http/1.1"));
socket.once("secureConnect", () => settle(socket.alpnProtocol));
socket.once("error", () => settle("http/1.1"));
});
};
// helper: http2 sessions
const http2Sessions = {};
async function http2Session(url, opts){
if (url.origin in http2Sessions && !http2Sessions[url.origin].destroyed && !http2Sessions[url.origin].closed && !http2Sessions[url.origin].destroying) return http2Sessions[url.origin];
return (http2Sessions[url.origin] = http2.connect(`${url.origin}`, opts));
};
// helper: http(s) sessions
const agents = {};
function httpAgent(p){
if (!agents[p] || agents[p].destroyed) agents[p] = new (p === "http:" ? http : https).Agent({ keepAlive: true });
return agents[p];
};
// clean up sessions on exit
process.on("exit", ()=>{
for (const client of Object.values(http2Sessions)) client.close();
});
// phn
const phn = async (opts, fn)=>{
// callback compat
if (typeof fn === "function") return await phn(opts).then(data=>(fn(null, data))).catch(fn);
if (typeof opts === "string") opts = { url: opts };
if (!("url" in opts) || !opts.url) throw new Error("Missing url option from options for request method.");
this.url = (typeof opts.url === "string") ? new URL(opts.url) : opts.url;
this.method = (opts.method || "get").toUpperCase();
this.data = null;
// maximum buffer size
this.maxBuffer = parseInt(opts.maxBuffer,10) || Infinity;
// max redirects
this.maxRedirects = (typeof opts?.maxRedirects === "number") ? opts.maxRedirects : (typeof opts?.follow === "number") ? opts.follow : 20;
opts.redirected = opts.redirected || 0;
// http2 options
this.http2core = (typeof opts.http2 === "object") ? opts.http2 : {};
// headers
this.headers = {};
if (opts.headers) for (const [k,v] of Object.entries(opts.headers)) this.headers[k.toLowerCase()] = v;
// query
if (opts.query) for (const [k,v] of Object.entries(opts.headers)) this.url.searchParams.append(k,v);
// form
if (opts.form) {
this.data = qs.stringify(opts.form);
this.headers["content-type"] = "application/x-www-form-urlencoded";
};
// data
if (opts.data) {
if (typeof opts.data === "object" && !Buffer.isBuffer(opts.data) && !ArrayBuffer.isView(opts.data)) { // json
this.data = JSON.stringify(opts.data);
this.headers["content-type"] = "application/json";
} else {
this.data = opts.data;
if (!this.headers["content-type"]) this.headers["content-type"] = "application/octet-stream";
}
};
// set content-length
if (this.data && !this.headers["content-length"]) this.headers["content-length"] = Buffer.byteLength(this.data);
// compression, set unless explicitly off
if ((!("compression" in opts) || !!opts.compression) && !this.headers["accept-encoding"]) this.headers["accept-encoding"] = (typeof opts.compression === "string") ? opts.compression : supportedCompression;
// send request
let { transport, req, res, stream, client } = await new Promise(async (resolve, reject)=>{
// assemble options for http1
const options = {
protocol: this.url.protocol,
host: this.url.hostname.replace("[", "").replace("]", ""),
port: this.url.port,
path: this.url.pathname + (this.url.search ?? ""),
method: this.method,
headers: this.headers,
agent: httpAgent(this.url.protocol),
...opts.core,
};
let req;
switch (this.url.protocol) {
case "http:":
req = http.request(options, res=>resolve({ transport: "http", req, res, stream: res }));
break;
case "https:":
// use http2 if module is loaded, http2 not explicitly off and available on host
if (http2 && (!("http2" in opts) || !!opts.http2) && ("h2" === await alpn(this.url))) {
// new http2 session
const client = await http2Session(this.url, this.coreOptions);
// reference socket
client.socket.ref();
req = client.request({ ":method": options.method, ":path": options.path, ...options.headers, ...this.http2core });
req.on("response", (headers) => {
const res = { headers, statusCode: headers[":status"] };
resolve({ transport: "http2", req, res, stream: req, client });
});
} else {
req = https.request(options, res=>{
resolve({ transport: "https", req, res, stream: res })
});
};
break;
default:
return reject(new Error(`Bad protocol: ${this.url.protocol}`));
break;
};
// handle timeout
if (opts.timeout) req.setTimeout(opts.timeout);
req.on("timeout", ()=>{
reject(new Error("Timeout reached"));
req.abort?.();
});
// handle error
req.on("error", reject);
// send data
if (this.data) req.write(this.data);
// end request
req.end();
});
// handle aborts
stream.on("aborted", ()=>reject(new Error("Server aborted request")));
// follow redirects
if (res.headers?.location && (opts.follow || opts.followRedirects)) {
// limit the number of redirects
if (this.maxRedirects && ++opts.redirected > this.maxRedirects) throw new Error("Exceeded the maximum number of redirects");
const redirectedUrl = new URL(res.headers["location"], this.url);
if (redirectedUrl.protocol === this.url.protocol && redirectedUrl.host === this.url.host) { // keep cookies
if (res.headers["set-cookie"]) opts.headers = { ...opts.headers, cookie: res.headers["set-cookie"] };
} else { // remove spicy request headers
opts.headers = Object.entries({ ...opts.headers }).reduce((h,[k,v])=>{
if (!["authorization","cookie","proxy-authorization"].includes(k.toLowerCase())) h[k] = v;
return h;
},{});
};
client?.socket?.unref?.();
opts.url = redirectedUrl.toString();
return phn(opts, fn);
};
// check content-length header against maxBuffer
if (res.headers["content-length"] && parseInt(res.headers["content-length"],10) > this.maxBuffer) {
throw new Error(`Content length exceeds maxBuffer: ${res.headers["content-length"]}b`);
};
// decompress
switch (res.headers["content-encoding"]) {
case "zstd":
stream = stream.pipe(createZstdDecompress());
break;
case "br":
stream = stream.pipe(zlib.createBrotliDecompress());
break;
case "gzip":
stream = stream.pipe(zlib.createGunzip());
break;
case "deflate":
stream = stream.pipe(zlib.createInflate());
break;
};
// iconv decode via iconv-lite if available
if (iconv && opts.decode) { // iconv.encodingExists("us-ascii")
const charset = (typeof opts.decode === "string") ? opts.decode : res.headers?.['content-type']?.match(/charset=([^;]+)/i)?.[1].trim();
if (charset) {
if (!iconv.encodingExists(charset)) throw new Error(`Unknown Charset ${charset}`);
stream = stream.pipe(iconv.decodeStream(charset)).pipe(new transformStream({
transform(c, _, f) { f(null, Buffer.from(c)); }
}));
};
};
// deliver stream if requested
if (opts.stream) {
client?.socket?.unref?.();
return { ...res, req, transport, stream, statusCode: res.statusCode, headers: res.headers };
};
// assemble body
let body = await new Promise((resolve,reject)=>{
let b = Buffer.alloc(0);
stream.on("error", err=>reject(err));
stream.on("data", chunk=>{
b = Buffer.concat([b, chunk]);
if (b.length > opts.maxBuffer) {
reject(new Error(`Content length exceeds maxBuffer: ${res.headers["content-length"]}b`));
stream.destroy();
};
});
stream.on("end", ()=>{
client?.socket?.unref?.();
resolve(b);
});
});
// parse body
switch (typeof opts.parse) {
case "string":
switch (opts.parse) {
case "string":
body = body.toString()
break;
case "json":
body = (res.statusCode === 204) ? null : JSON.parse(body);
break;
};
break;
case "function":
body = opts.parse(body);
break;
};
// deliver
return { ...res, req, transport, body, statusCode: res.statusCode, headers: res.headers };
};
// defaults
phn.defaults = (defaults)=>(opts,fn)=>{
if (typeof opts === "string") opts = { url: opts };
for (const k of Object.keys(defaults)) if (!(k in opts)) opts[k] = defaults[k];
return phn(opts,fn);
};
// compat
phn.promisified = phn;
phn.unpromisified = phn;
module.exports = phn;
// clean sessions and agents on exit
process.on("beforeExit", ()=>{
for (const s of Object.values(http2Sessions)) try { s.close(); } catch {};
for (const a of Object.values(agents)) try { a.destroy(); } catch {};
});