local-traffic 0.0.72 → 0.0.73

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.
@@ -0,0 +1,1446 @@
1
+ "use strict";
2
+ var e,
3
+ t =
4
+ (this && this.__awaiter) ||
5
+ function (e, t, n, o) {
6
+ return new (n || (n = Promise))(function (r, s) {
7
+ function i(e) {
8
+ try {
9
+ l(o.next(e));
10
+ } catch (e) {
11
+ s(e);
12
+ }
13
+ }
14
+ function a(e) {
15
+ try {
16
+ l(o.throw(e));
17
+ } catch (e) {
18
+ s(e);
19
+ }
20
+ }
21
+ function l(e) {
22
+ var t;
23
+ e.done
24
+ ? r(e.value)
25
+ : ((t = e.value),
26
+ t instanceof n
27
+ ? t
28
+ : new n(function (e) {
29
+ e(t);
30
+ })).then(i, a);
31
+ }
32
+ l((o = o.apply(e, t || [])).next());
33
+ });
34
+ };
35
+ Object.defineProperty(exports, "__esModule", { value: !0 }),
36
+ (exports.update =
37
+ exports.serve =
38
+ exports.determineMapping =
39
+ exports.send =
40
+ exports.replaceTextUsingMapping =
41
+ exports.replaceBody =
42
+ exports.acknowledgeWebsocket =
43
+ exports.readWebsocketBuffer =
44
+ exports.createWebsocketBufferFrom =
45
+ exports.websocketServe =
46
+ exports.quickStatus =
47
+ exports.errorListener =
48
+ exports.load =
49
+ exports.start =
50
+ void 0);
51
+ const n = require("http2"),
52
+ o = require("http"),
53
+ r = require("https"),
54
+ s = require("url"),
55
+ i = require("fs"),
56
+ a = require("zlib"),
57
+ l = require("path"),
58
+ c = require("crypto"),
59
+ d = require("process");
60
+ var p, u, g;
61
+ !(function (e) {
62
+ (e[(e.ERROR = 124)] = "ERROR"),
63
+ (e[(e.INFO = 93)] = "INFO"),
64
+ (e[(e.WARNING = 172)] = "WARNING");
65
+ })(p || (p = {})),
66
+ (function (e) {
67
+ (e.INBOUND = "↘️ "),
68
+ (e.PORT = "☎️ "),
69
+ (e.OUTBOUND = "↗️ "),
70
+ (e.RULES = "🔗"),
71
+ (e.REWRITE = "✒️ "),
72
+ (e.RESTART = "🔄"),
73
+ (e.WEBSOCKET = "☄️ "),
74
+ (e.COLORED = "✨"),
75
+ (e.SHIELD = "🛡️ "),
76
+ (e.NO = "⛔"),
77
+ (e.ERROR_1 = "❌"),
78
+ (e.ERROR_2 = "⛈️ "),
79
+ (e.ERROR_3 = "☢️ "),
80
+ (e.ERROR_4 = "⁉️ "),
81
+ (e.ERROR_5 = "⚡"),
82
+ (e.ERROR_6 = "☠️ ");
83
+ })(u || (u = {})),
84
+ (function (e) {
85
+ (e.INBOUND = "INBOUND"), (e.OUTBOUND = "OUTBOUND");
86
+ })(g || (g = {}));
87
+ const h = (0, l.resolve)(d.env.HOME, ".local-traffic.json"),
88
+ f = (0, l.resolve)(
89
+ (0, d.cwd)(),
90
+ d.argv.slice(-1)[0].endsWith(".json") ? d.argv.slice(-1)[0] : h,
91
+ ),
92
+ m = {
93
+ mapping: { "/config/": "config://", "/logs/": "logs://" },
94
+ port: 8080,
95
+ replaceRequestBodyUrls: !1,
96
+ replaceResponseBodyUrls: !1,
97
+ dontUseHttp2Downstream: !1,
98
+ dontTranslateLocationHeader: !1,
99
+ simpleLogs: !1,
100
+ websocket: !0,
101
+ disableWebSecurity: !1,
102
+ },
103
+ v = e => (e === p.ERROR ? "error" : e === p.WARNING ? "warning" : "info"),
104
+ y = function (e, t, n, o) {
105
+ var r, s, i, a, l;
106
+ const c =
107
+ (null === (r = null == e ? void 0 : e.config) || void 0 === r
108
+ ? void 0
109
+ : r.simpleLogs) ||
110
+ (null === (s = null == e ? void 0 : e.logsListeners) || void 0 === s
111
+ ? void 0
112
+ : s.length)
113
+ ? t
114
+ .replace(/⎸/g, "|")
115
+ .replace(/⎹/g, "|")
116
+ .replace(/\u001b\[[^m]*m/g, "")
117
+ .replace(new RegExp(u.INBOUND, "g"), "inbound:")
118
+ .replace(new RegExp(u.PORT, "g"), "port:")
119
+ .replace(new RegExp(u.OUTBOUND, "g"), "outbound:")
120
+ .replace(new RegExp(u.RULES, "g"), "rules:")
121
+ .replace(new RegExp(u.NO, "g"), "")
122
+ .replace(new RegExp(u.REWRITE, "g"), "+rewrite")
123
+ .replace(new RegExp(u.WEBSOCKET, "g"), "websocket")
124
+ .replace(new RegExp(u.SHIELD, "g"), "web-security")
125
+ .replace(/\|+/g, "|")
126
+ : t;
127
+ console.log(
128
+ `${(e => {
129
+ const t = new Date();
130
+ return `${e ? "" : ""}${`${t.getHours()}`.padStart(2, "0")}${
131
+ e ? ":" : ":"
132
+ }${`${t.getMinutes()}`.padStart(2, "0")}${
133
+ e ? ":" : ":"
134
+ }${`${t.getSeconds()}`.padStart(2, "0")}${e ? "" : ""}`;
135
+ })(
136
+ null === (i = null == e ? void 0 : e.config) || void 0 === i
137
+ ? void 0
138
+ : i.simpleLogs,
139
+ )} ${
140
+ (
141
+ null === (a = null == e ? void 0 : e.config) || void 0 === a
142
+ ? void 0
143
+ : a.simpleLogs
144
+ )
145
+ ? c
146
+ : n
147
+ ? `[48;5;${n}m⎸ ${(d.stdout.isTTY && o) || ""} ${t.padEnd(40)} ⎹`
148
+ : t
149
+ }`,
150
+ ),
151
+ null === (l = null == e ? void 0 : e.notifyLogsListeners) ||
152
+ void 0 === l ||
153
+ l.call(e, { event: c, level: v(n) });
154
+ },
155
+ b = (e, t) => {
156
+ const n = Array(4)
157
+ .fill(0)
158
+ .map(() => (t ? Math.floor(256 * Math.random()) : 0)),
159
+ o = [...e.substring(0, 65536)].map((e, t) => e.charCodeAt(0) ^ n[3 & t]),
160
+ r = Math.min(65535, e.length),
161
+ s =
162
+ e.length < 126
163
+ ? Buffer.from(Uint8Array.from([129, (t ? 128 : 0) + r]).buffer)
164
+ : Buffer.concat([
165
+ Buffer.from(Uint8Array.from([129, 126 | (t ? 128 : 0)]).buffer),
166
+ Buffer.from(Uint8Array.from([r >> 8]).buffer),
167
+ Buffer.from(Uint8Array.from([255 & r]).buffer),
168
+ ]),
169
+ i = Buffer.from(Int8Array.from(n).buffer),
170
+ a = Buffer.from(Int8Array.from(o).buffer);
171
+ return Buffer.concat(t ? [s, i, a] : [s, a]);
172
+ };
173
+ exports.createWebsocketBufferFrom = b;
174
+ const R = (e, t) => {
175
+ var n;
176
+ if (!t && 0 == (1 & e.readUInt8(0)))
177
+ return { payloadLength: 0, mask: [0, 0, 0, 0], body: "" };
178
+ const o = t ? 0 : e.readUInt8(1),
179
+ r = o >> 7,
180
+ s = 127 & o,
181
+ i = t
182
+ ? t.payloadLength
183
+ : 127 !== s
184
+ ? s
185
+ : e.readUInt8(2) << (8 + e.readUInt8(3)),
186
+ a = t
187
+ ? t.mask
188
+ : r
189
+ ? Array(4)
190
+ .fill(0)
191
+ .map((t, n) => e.readUInt8(n + 4))
192
+ : [0, 0, 0, 0],
193
+ l = t ? 0 : r ? 8 : 4,
194
+ c = Array(e.length - l)
195
+ .fill(0)
196
+ .map((t, n) => String.fromCharCode(e.readUInt8(n + l) ^ a[3 & n]))
197
+ .join("");
198
+ return {
199
+ payloadLength: i,
200
+ mask: a,
201
+ body: (null !== (n = null == t ? void 0 : t.body) && void 0 !== n
202
+ ? n
203
+ : ""
204
+ ).concat(c),
205
+ };
206
+ };
207
+ exports.readWebsocketBuffer = R;
208
+ const w = (e, t) => {
209
+ const n = (0, c.createHash)("sha1");
210
+ n.update(t + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
211
+ const o = n.digest("base64");
212
+ (e.allowHalfOpen = !0),
213
+ e.write(
214
+ `HTTP/1.1 101 Switching Protocols\r\ndate: ${new Date().toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${o}\r\n\r\n`,
215
+ );
216
+ };
217
+ exports.acknowledgeWebsocket = w;
218
+ const O = function (e) {
219
+ return E(this, e, this.configListeners);
220
+ },
221
+ $ = function (e) {
222
+ return E(this, e, this.logsListeners);
223
+ },
224
+ E = (e, t, n) => {
225
+ if (!n.length) return;
226
+ const o = JSON.stringify(t),
227
+ r = new Set(n.map(e => e.wantsMask)),
228
+ s = r.has(!1) && b(o, !1),
229
+ i = r.has(!0) && b(o, !0),
230
+ a = e => {
231
+ e.stream.errored && e.stream.destroy();
232
+ };
233
+ n.forEach(e => {
234
+ e.stream.closed ||
235
+ e.stream.errored ||
236
+ (e.wantsMask
237
+ ? e.stream.write(i, "ascii", () => a(e))
238
+ : e.stream.write(s, "ascii", () => a(e)));
239
+ });
240
+ },
241
+ x = function () {
242
+ this.log(
243
+ `⎸${u.PORT} ${this.config.port.toString().padStart(5)} ⎸${u.OUTBOUND} ${
244
+ this.config.dontUseHttp2Downstream ? "H1.1" : "H/2 "
245
+ }${this.config.replaceRequestBodyUrls ? u.REWRITE : " "}⎹⎸${u.INBOUND} ${
246
+ this.config.ssl ? "H/2 " : "H1.1"
247
+ }${this.config.replaceResponseBodyUrls ? u.REWRITE : " "}⎹⎸${
248
+ u.RULES
249
+ }${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹⎸${
250
+ this.config.websocket ? u.WEBSOCKET : u.NO
251
+ }⎹⎸${this.config.simpleLogs ? u.NO : u.COLORED}⎹⎸${
252
+ this.config.disableWebSecurity ? u.NO : u.SHIELD
253
+ }⎹`,
254
+ ),
255
+ this.notifyConfigListeners(this.config);
256
+ };
257
+ exports.quickStatus = x;
258
+ const L = (e = !0) =>
259
+ t(void 0, void 0, void 0, function* () {
260
+ return new Promise(t =>
261
+ (0, i.readFile)(f, (n, o) => {
262
+ n &&
263
+ !e &&
264
+ y(null, "config error. Using default value", p.ERROR, u.ERROR_1);
265
+ let r = null;
266
+ try {
267
+ r = Object.assign({}, m, JSON.parse((o || "{}").toString()));
268
+ } catch (e) {
269
+ return (
270
+ y(
271
+ { config: r },
272
+ "config syntax incorrect, aborting",
273
+ p.ERROR,
274
+ u.ERROR_2,
275
+ ),
276
+ (r = null != r ? r : Object.assign({}, m)),
277
+ void t(r)
278
+ );
279
+ }
280
+ r.mapping[""] ||
281
+ y(
282
+ { config: r },
283
+ 'default mapping "" not provided.',
284
+ p.WARNING,
285
+ u.ERROR_3,
286
+ ),
287
+ n && "ENOENT" === n.code && e && f === h
288
+ ? (0, i.writeFile)(f, JSON.stringify(m, null, 2), e => {
289
+ e
290
+ ? y(null, "config file NOT created", p.ERROR, u.ERROR_4)
291
+ : y(null, "config file created", p.INFO, u.COLORED),
292
+ t(r);
293
+ })
294
+ : t(r);
295
+ }),
296
+ );
297
+ });
298
+ exports.load = L;
299
+ const S = e => ("" == e ? "" : (0, l.normalize)(e).replace(/\\/g, "/")),
300
+ N = "https://cdn.jsdelivr.net/npm/",
301
+ B = (e, t, n) =>
302
+ `<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(
303
+ 16,
304
+ )}; local-traffic ${t} | ${n}</title>\n<link href="${N}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${N}jquery/dist/jquery.min.js"><\/script>\n<script src="${N}bootstrap/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(
305
+ 16,
306
+ )}; local-traffic ${t}</h1>\n<br/>`,
307
+ k = e => {
308
+ const t = (0, l.resolve)(
309
+ "/",
310
+ e.hostname,
311
+ ...e.pathname
312
+ .replace(/[?#].*$/, "")
313
+ .replace(/^\/+/, "")
314
+ .split("/"),
315
+ );
316
+ return {
317
+ error: null,
318
+ data: null,
319
+ hasRun: !1,
320
+ run: function () {
321
+ return this.hasRun
322
+ ? Promise.resolve()
323
+ : new Promise(n =>
324
+ (0, i.readFile)(t, (o, r) => {
325
+ if (((this.hasRun = !0), !o || "EISDIR" !== o.code))
326
+ return (this.error = o), (this.data = r), void n(void 0);
327
+ (0, i.readdir)(t, (t, o) => {
328
+ (this.error = t),
329
+ (this.data = o),
330
+ t
331
+ ? n(void 0)
332
+ : Promise.all(
333
+ o.map(
334
+ t =>
335
+ new Promise(n =>
336
+ (0, i.lstat)(
337
+ (0, l.resolve)(e.pathname, t),
338
+ (e, o) => n([t, o, e]),
339
+ ),
340
+ ),
341
+ ),
342
+ ).then(t => {
343
+ const o = t
344
+ .filter(e => !e[2] && e[1].isDirectory())
345
+ .concat(t.filter(e => !e[2] && e[1].isFile()));
346
+ (this.data = `${B(
347
+ 128194,
348
+ "directory",
349
+ e.href,
350
+ )}<p>Directory content of <i>${e.href.replace(
351
+ /\//g,
352
+ "&#x002F;",
353
+ )}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${
354
+ e.pathname.endsWith("/") ? ".." : "."
355
+ }">&lt;parent&gt;</a></li>${o
356
+ .filter(e => !e[2])
357
+ .map(
358
+ t =>
359
+ `<li class="list-group-item">&#x${(t[1].isDirectory()
360
+ ? 128193
361
+ : 128196
362
+ ).toString(16)};<a href="${
363
+ e.pathname.endsWith("/")
364
+ ? ""
365
+ : `${e.pathname.split("/").slice(-1)[0]}/`
366
+ }${t[0]}">${t[0]}</a></li>`,
367
+ )
368
+ .join("\n")}</li></ul></body></html>`),
369
+ n(void 0);
370
+ });
371
+ });
372
+ }),
373
+ );
374
+ },
375
+ events: {},
376
+ on: function (e, n) {
377
+ return (
378
+ (this.events[e] = n),
379
+ this.run().then(() => {
380
+ "response" === e &&
381
+ this.events.response(
382
+ t.endsWith(".svg")
383
+ ? { Server: "local", "Content-Type": "image/svg+xml" }
384
+ : { Server: "local" },
385
+ 0,
386
+ ),
387
+ "data" === e &&
388
+ this.data &&
389
+ (this.events.data(this.data), this.events.end()),
390
+ "error" === e && this.error && this.events.error(this.error);
391
+ }),
392
+ this
393
+ );
394
+ },
395
+ end: function () {
396
+ return this;
397
+ },
398
+ request: function () {
399
+ return this;
400
+ },
401
+ };
402
+ },
403
+ j = e => ({
404
+ error: null,
405
+ data: null,
406
+ run: function () {
407
+ return new Promise(t => {
408
+ (this.data = e), t(void 0);
409
+ });
410
+ },
411
+ events: {},
412
+ on: function (e, t) {
413
+ return (
414
+ (this.events[e] = t),
415
+ this.run().then(() => {
416
+ "response" === e &&
417
+ this.events.response(
418
+ { Server: "local", "Content-Type": "text/html" },
419
+ 0,
420
+ ),
421
+ "data" === e &&
422
+ this.data &&
423
+ (this.events.data(this.data), this.events.end()),
424
+ "error" === e && this.error && this.events.error(this.error);
425
+ }),
426
+ this
427
+ );
428
+ },
429
+ end: function () {
430
+ return this;
431
+ },
432
+ request: function () {
433
+ return this;
434
+ },
435
+ }),
436
+ I = (e, t, n, o) =>
437
+ `${B(
438
+ 128163,
439
+ "error",
440
+ e.message,
441
+ )}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n&#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${
442
+ e.stack || `<i>${e.name} : ${e.message}</i>`
443
+ }${
444
+ e.errno ? `<br/>(code : ${e.errno})` : ""
445
+ }</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n<tbody>\n<tr>\n<td>phase</td>\n<td>${t}</td>\n</tr>\n<tr>\n<td>requested URL</td>\n<td>${n}</td>\n</tr>\n<tr>\n<td>downstream URL</td>\n<td>${
446
+ o || "&lt;no-target-url&gt;"
447
+ }</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,
448
+ T = (e, n, o) =>
449
+ t(void 0, void 0, void 0, function* () {
450
+ var r, s;
451
+ return (
452
+ null !==
453
+ (s =
454
+ null === (r = n["content-encoding"]) || void 0 === r
455
+ ? void 0
456
+ : r.toString()) && void 0 !== s
457
+ ? s
458
+ : ""
459
+ )
460
+ .split(",")
461
+ .reduce(
462
+ (e, n) =>
463
+ t(void 0, void 0, void 0, function* () {
464
+ const t = n.trim().toLowerCase(),
465
+ o =
466
+ "gzip" === t || "x-gzip" === t
467
+ ? a.gunzip
468
+ : "deflate" === t
469
+ ? a.inflate
470
+ : "br" === t
471
+ ? a.brotliDecompress
472
+ : "identity" === t || "" === t
473
+ ? (e, t) => {
474
+ t(null, e);
475
+ }
476
+ : null;
477
+ if (null === o)
478
+ throw new Error(`${t} compression not supported by the proxy`);
479
+ const r = yield e;
480
+ return yield new Promise((e, t) =>
481
+ o(r, (n, o) => {
482
+ n && t(n), e(o);
483
+ }),
484
+ );
485
+ }),
486
+ Promise.resolve(e),
487
+ )
488
+ .then(e => {
489
+ const t = e.length > 1e7,
490
+ r = [
491
+ "text/html",
492
+ "application/javascript",
493
+ "application/json",
494
+ ].some(e => {
495
+ var t;
496
+ return (null !== (t = n["content-type"]) && void 0 !== t ? t : "")
497
+ .toString()
498
+ .includes(e);
499
+ });
500
+ return !t && (r || !/[^\x00-\x7F]/.test(e.toString()))
501
+ ? C(e.toString(), {
502
+ direction: o.direction,
503
+ proxyHostnameAndPort: o.proxyHostnameAndPort,
504
+ ssl: o.ssl,
505
+ mapping: o.mapping,
506
+ }).replace(
507
+ /\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,
508
+ `?protocol=ws${o.ssl ? "s" : ""}%3A&hostname=${
509
+ o.proxyHostname
510
+ }&port=${o.port}&pathname=${encodeURIComponent(
511
+ o.key.replace(/\/+$/, ""),
512
+ )}`,
513
+ )
514
+ : e;
515
+ })
516
+ .then(e => {
517
+ var t, o;
518
+ return (
519
+ null !==
520
+ (o =
521
+ null === (t = n["content-encoding"]) || void 0 === t
522
+ ? void 0
523
+ : t.toString()) && void 0 !== o
524
+ ? o
525
+ : ""
526
+ )
527
+ .split(",")
528
+ .reverse()
529
+ .reduce((e, t) => {
530
+ const n = t.trim().toLowerCase(),
531
+ o =
532
+ "gzip" === n || "x-gzip" === n
533
+ ? a.gzip
534
+ : "deflate" === n
535
+ ? a.deflate
536
+ : "br" === n
537
+ ? a.brotliCompress
538
+ : "identity" === n || "" === n
539
+ ? (e, t) => {
540
+ t(null, e);
541
+ }
542
+ : null;
543
+ if (null === o)
544
+ throw new Error(`${n} compression not supported by the proxy`);
545
+ return e.then(
546
+ e =>
547
+ new Promise(t =>
548
+ o(e, (e, n) => {
549
+ if (e) throw e;
550
+ t(n);
551
+ }),
552
+ ),
553
+ );
554
+ }, Promise.resolve(Buffer.from(e)));
555
+ });
556
+ });
557
+ exports.replaceBody = T;
558
+ const C = (e, { direction: t, proxyHostnameAndPort: n, ssl: o, mapping: r }) =>
559
+ Object.entries(r)
560
+ .map(([e, t]) => [e, "string" == typeof t ? t : t.replaceBody])
561
+ .reduce(
562
+ (e, [r, s]) =>
563
+ s.startsWith("logs:") ||
564
+ s.startsWith("config:") ||
565
+ ("" !== r && !r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/))
566
+ ? e
567
+ : t === g.INBOUND
568
+ ? e.replace(
569
+ new RegExp(
570
+ s
571
+ .replace(/^(file|logs):\/\//, "")
572
+ .replace(/[*+?^${}()|[\]\\]/g, "")
573
+ .replace(/^https/, "https?") + "/*",
574
+ "ig",
575
+ ),
576
+ `http${o ? "s" : ""}://${n}${r.replace(/\/+$/, "")}/`,
577
+ )
578
+ : e
579
+ .split(`http${o ? "s" : ""}://${n}${r.replace(/\/+$/, "")}`)
580
+ .join(s),
581
+ e,
582
+ )
583
+ .split(`${n}/:`)
584
+ .join(`${n}:`);
585
+ exports.replaceTextUsingMapping = C;
586
+ const U = (e, t, n) => {
587
+ t.writeHead(e, void 0, {
588
+ "content-type": "text/html",
589
+ "content-length": n.length,
590
+ }),
591
+ t.end(n);
592
+ };
593
+ exports.send = U;
594
+ const H = (e, t) => {
595
+ var n, o, r, i, a;
596
+ const l = (
597
+ null !==
598
+ (r =
599
+ null !==
600
+ (o =
601
+ null === (n = e.headers[":authority"]) || void 0 === n
602
+ ? void 0
603
+ : n.toString()) && void 0 !== o
604
+ ? o
605
+ : e.headers.host) && void 0 !== r
606
+ ? r
607
+ : "localhost"
608
+ ).replace(/:.*/, ""),
609
+ c =
610
+ e.headers[":authority"] ||
611
+ `${e.headers.host}${
612
+ e.headers.host.match(/:[0-9]+$/)
613
+ ? ""
614
+ : 80 !== t.port || t.ssl
615
+ ? 443 === t.port && t.ssl
616
+ ? ""
617
+ : `:${null !== (i = t.port) && void 0 !== i ? i : 8080}`
618
+ : ""
619
+ }`,
620
+ d = new s.URL(`http${t.ssl ? "s" : ""}://${c}${e.url}`),
621
+ p = d.href.substring(d.origin.length),
622
+ u = Object.assign(
623
+ {},
624
+ Object.assign(
625
+ {},
626
+ ...Object.entries(t.mapping).map(([e, t]) => ({
627
+ [e]: new s.URL(S("string" == typeof t ? t : t.downstreamUrl)),
628
+ })),
629
+ ),
630
+ ),
631
+ [g, h] =
632
+ null !==
633
+ (a = Object.entries(u).find(([e]) =>
634
+ p.match(RegExp(e.replace(/^\//, "^/"))),
635
+ )) && void 0 !== a
636
+ ? a
637
+ : [];
638
+ return {
639
+ proxyHostname: l,
640
+ proxyHostnameAndPort: c,
641
+ url: d,
642
+ path: p,
643
+ key: g,
644
+ target: h,
645
+ };
646
+ };
647
+ exports.determineMapping = H;
648
+ const P = function (e, t, n) {
649
+ var i, a, l, c;
650
+ if (!e.config.websocket)
651
+ return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"), {};
652
+ const { key: d, target: g, path: h } = H(t, e.config);
653
+ if ("/local-traffic-logs" === h)
654
+ return (
655
+ w(n, t.headers["sec-websocket-key"]),
656
+ {
657
+ logsListeners: e.logsListeners.concat({
658
+ stream: n,
659
+ wantsMask: !(
660
+ null !==
661
+ (a =
662
+ null === (i = t.headers["user-agent"]) || void 0 === i
663
+ ? void 0
664
+ : i.toString()) && void 0 !== a
665
+ ? a
666
+ : ""
667
+ ).includes("Chrome"),
668
+ }),
669
+ }
670
+ );
671
+ if ("/local-traffic-config" === h) {
672
+ w(n, t.headers["sec-websocket-key"]);
673
+ let o = null;
674
+ return (
675
+ n.on("data", t => {
676
+ const n = R(t, o);
677
+ if (null === o && n.body.length < n.payloadLength) o = n;
678
+ else {
679
+ if (n.body.length >= n.payloadLength && 0 === n.body.length) return;
680
+ if (n.body.length >= n.payloadLength) {
681
+ let t;
682
+ o = null;
683
+ try {
684
+ t = JSON.parse(n.body);
685
+ } catch (t) {
686
+ return void e.log(
687
+ "config file NOT read, try again later",
688
+ p.WARNING,
689
+ u.ERROR_4,
690
+ );
691
+ }
692
+ W(e, { pendingConfigSave: t });
693
+ }
694
+ }
695
+ }),
696
+ {
697
+ configListeners: e.configListeners.concat({
698
+ stream: n,
699
+ wantsMask: !(
700
+ null !==
701
+ (c =
702
+ null === (l = t.headers["user-agent"]) || void 0 === l
703
+ ? void 0
704
+ : l.toString()) && void 0 !== c
705
+ ? c
706
+ : ""
707
+ ).includes("Chrome"),
708
+ }),
709
+ }
710
+ );
711
+ }
712
+ const f = new s.URL(
713
+ `${g.protocol}//${g.host}${
714
+ t.url.endsWith("/_next/webpack-hmr")
715
+ ? t.url
716
+ : t.url.replace(new RegExp(`^${d}`, "g"), "").replace(/^\/*/, "/")
717
+ }`,
718
+ ),
719
+ m = {
720
+ hostname: f.hostname,
721
+ path: f.pathname,
722
+ port: f.port,
723
+ protocol: f.protocol,
724
+ rejectUnauthorized: !1,
725
+ method: t.method,
726
+ headers: t.headers,
727
+ host: f.hostname,
728
+ },
729
+ v = "https:" === f.protocol ? (0, r.request)(m) : (0, o.request)(m);
730
+ v.end(),
731
+ v.on("error", t => {
732
+ e.log(
733
+ "websocket request has errored " + (t.errno ? `(${t.errno})` : ""),
734
+ p.WARNING,
735
+ u.WEBSOCKET,
736
+ );
737
+ }),
738
+ v.on("upgrade", (t, o) => {
739
+ const r = `HTTP/${t.httpVersion} ${t.statusCode} ${
740
+ t.statusMessage
741
+ }\r\n${Object.entries(t.headers)
742
+ .flatMap(([e, t]) => (Array.isArray(t) ? t : [t]).map(t => [e, t]))
743
+ .map(([e, t]) => `${e}: ${t}\r\n`)
744
+ .join("")}\r\n`;
745
+ n.write(r),
746
+ (n.allowHalfOpen = !0),
747
+ (o.allowHalfOpen = !0),
748
+ o.on("data", e => n.write(e)),
749
+ n.on("data", e => o.write(e)),
750
+ o.on("error", t => {
751
+ e.log(
752
+ "downstream socket has errored " + (t.errno ? `(${t.errno})` : ""),
753
+ p.WARNING,
754
+ u.WEBSOCKET,
755
+ );
756
+ }),
757
+ n.on("error", t => {
758
+ e.log(
759
+ "upstream socket has errored " + (t.errno ? `(${t.errno})` : ""),
760
+ p.WARNING,
761
+ u.WEBSOCKET,
762
+ );
763
+ });
764
+ });
765
+ };
766
+ exports.websocketServe = P;
767
+ const q = function (e, i, a) {
768
+ var l, h, v, y, b;
769
+ return t(this, void 0, void 0, function* () {
770
+ if (!i.headers.host && !i.headers[":authority"])
771
+ return void U(
772
+ 400,
773
+ a,
774
+ Buffer.from(
775
+ I(
776
+ new Error("client must supply a 'host' header"),
777
+ "proxy",
778
+ new s.URL(`http${e.config.ssl ? "s" : ""}://unknowndomain${i.url}`),
779
+ ),
780
+ ),
781
+ );
782
+ const {
783
+ proxyHostname: t,
784
+ proxyHostnameAndPort: R,
785
+ url: w,
786
+ path: O,
787
+ key: $,
788
+ target: E,
789
+ } = H(i, e.config);
790
+ if (!E)
791
+ return void U(
792
+ 502,
793
+ a,
794
+ Buffer.from(
795
+ I(new Error(`No mapping found in config file ${f}`), "proxy", w),
796
+ ),
797
+ );
798
+ const x = E.host.replace(RegExp(/\/+$/), ""),
799
+ L = `${E.href.substring(8 + E.host.length)}${S(
800
+ O.replace(RegExp(S($)), ""),
801
+ )}`.replace(/^\/*/, "/"),
802
+ P = new s.URL(`${E.protocol}//${x}${L}`);
803
+ let q = !e.config.dontUseHttp2Downstream;
804
+ const A = (0, c.randomBytes)(20).toString("hex");
805
+ e.notifyLogsListeners({
806
+ level: "info",
807
+ protocol: q ? "HTTP/2" : "HTTP1.1",
808
+ method: i.method,
809
+ upstreamPath: O,
810
+ downstreamPath: P.href,
811
+ randomId: A,
812
+ uniqueHash: "N/A",
813
+ });
814
+ const D = d.hrtime.bigint();
815
+ let W = null;
816
+ const M =
817
+ "file:" === E.protocol
818
+ ? k(P)
819
+ : "logs:" === E.protocol
820
+ ? ((e, t) =>
821
+ j(
822
+ `${B(
823
+ 128250,
824
+ "logs",
825
+ "",
826
+ )}\n<nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">\n<div class="container-fluid">\n<ul class="navbar-nav">\n<li class="nav-item">\n<a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>\n</li>\n<li class="nav-item">\n<a class="nav-link" href="javascript:show(1)">Proxy</a>\n</li>\n</ul>\n<span class="navbar-text">\nLimit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>\n<option value="50">50</option><option value="100">100</option><option value="200">200</option>\n<option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n</select> rows\n</span>\n</div>\n</nav>\n<table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n<thead>\n<tr>\n<th scope="col">...</th>\n<th scope="col">Date</th>\n<th scope="col">Level</th>\n<th scope="col">Protocol</th>\n<th scope="col">Method</th>\n<th scope="col">Status</th>\n<th scope="col">Duration</th>\n<th scope="col">Upstream Path</th>\n<th scope="col">Downstream Path</th>\n</tr>\n</thead>\n<tbody id="access">\n</tbody>\n</table>\n<table id="table-proxy" class="table table-striped" style="display: none; width: 100%; overflow-y: auto">\n<thead>\n<tr>\n<th scope="col">Date</th>\n<th scope="col">Level</th>\n<th scope="col">Message</th>\n</tr>\n</thead>\n<tbody id="proxy">\n</tbody>\n</table>\n<script type="text/javascript">\nfunction start() {\ndocument.getElementById('table-access').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\nconst socket = new WebSocket("ws${
827
+ t ? "s" : ""
828
+ }://${e}/local-traffic-logs");\nsocket.onmessage = function(event) {\nlet data = event.data\nlet uniqueHash;\ntry {\nconst { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\ndata = data1;\nuniqueHash = uniqueHash1;\n} catch(e) { }\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst replay = uniqueHash ? '<button data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary"' +\n(uniqueHash === 'N/A' ? ' disabled="disabled"' : '') + '>&#x1F501;</button>' : '';\nif(data.statusCode && uniqueHash) {\nconst color = Math.floor(data.statusCode / 100) === 1 ? "info" :\nMath.floor(data.statusCode / 100) === 2 ? "success" :\nMath.floor(data.statusCode / 100) === 3 ? "dark" :\nMath.floor(data.statusCode / 100) === 4 ? "warning" :\nMath.floor(data.statusCode / 100) === 5 ? "danger" :\n"secondary";\nconst statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\nif (statusCodeColumn)\nstatusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\nconst durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\nif (durationColumn) {\nconst duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\ndata.duration + 'ms';\ndurationColumn.innerHTML = duration;\n}\n\nconst protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\nif (protocolColumn) {\nprotocolColumn.innerHTML = data.protocol;\n}\n\nconst replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\nif (replayColumn) {\nreplayColumn.innerHTML = replay;\n}\n} else if (uniqueHash) {\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +\n'<td scope="col" class="replay">' + replay + '</td>' +\n'<td scope="col">' + time + '</td>' +\n'<td scope="col">' + (data.level || 'info')+ '</td>' + \n'<td scope="col" class="protocol">' + data.protocol + '</td>' + \n'<td scope="col">' + data.method + '</td>' + \n'<td scope="col" class="statusCode"><span class="badge bg-secondary">...</span></td>' +\n'<td scope="col" class="duration">&#x23F1;</td>' +\n'<td scope="col">' + data.upstreamPath + '</td>' + \n'<td scope="col">' + data.downstreamPath + '</td>' + \n'</tr>');\n} else if(data.event) {\ndocument.getElementById("proxy")\n.insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + time + '</td>' +\n'<td scope="col">' + (data.level || 'info')+ '</td>' + \n'<td scope="col">' + data.event + '</td></tr>');\n}\ncleanup();\n};\nsocket.onerror = function(error) {\nconsole.log(\`[error] \${error}\`);\nsetTimeout(start, 5000);\n};\n};\nfunction show(id) {\n[...document.querySelectorAll('table')].forEach((table, index) => {\ntable.style.display = index === id ? 'block': 'none'\n});\n[...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\nif (index === id) { link.classList.add('active') } else link.classList.remove('active');\n});\n}\nfunction cleanup() {\nconst currentLimit = parseInt(document.getElementById('limit').value)\nfor (let table of ['access', 'proxy']) {\nwhile (currentLimit && document.getElementById(table).childNodes.length && \ndocument.getElementById(table).childNodes.length > currentLimit) {\n[...document.getElementById(table).childNodes].slice(-1)[0].remove();\n}\n}\n}\nfunction replay(event) {\nconst uniqueHash = event.target.dataset.uniquehash;\nconst { method, url, headers, body } = JSON.parse(atob(uniqueHash));\nfetch(url, {\nmethod,\nheaders,\nbody: !body.data || !body.data.length \n? undefined\n: new TextDecoder().decode(new Int8Array(body.data))\n});\n}\nwindow.addEventListener("DOMContentLoaded", start);\n<\/script>\n</body></html>`,
829
+ ))(R, !!e.config.ssl)
830
+ : "config:" === E.protocol
831
+ ? ((e, t) =>
832
+ j(
833
+ `${B(
834
+ 127899,
835
+ "config",
836
+ "",
837
+ )}\n<link href="${N}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${N}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${N}node-forge/dist/forge.min.js"><\/script>\n<div id="ssl-modal" class="modal" tabindex="-1" role="dialog">\n<div class="modal-dialog" role="document">\n<div class="modal-content">\n<div class="modal-header">\n<h5 class="modal-title">SSL keypair generation in progress</h5>\n</div>\n<div class="modal-body">\n<p>Wait a few seconds or move your mouse to improve the entropy.</p>\n</div>\n</div>\n</div>\n</div>\n<div id="jsoneditor" style="width: 400px; height: 400px;"></div>\n<script>\n// create the editor\nconst container = document.getElementById("jsoneditor")\nconst options = {mode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\n${Object.entries(
838
+ Object.assign(Object.assign({}, m), {
839
+ ssl: { cert: "", key: "" },
840
+ }),
841
+ )
842
+ .map(
843
+ ([e, t]) =>
844
+ `${e}: {type: "${
845
+ "number" == typeof t
846
+ ? "integer"
847
+ : "string" == typeof t
848
+ ? "string"
849
+ : "boolean" == typeof t
850
+ ? "boolean"
851
+ : "object"
852
+ }"}`,
853
+ )
854
+ .join(
855
+ ",\n",
856
+ )}\n},\nrequired: [],\nadditionalProperties: false\n}}\n\nfunction save() {\nsocket.send(JSON.stringify(editor.get()));\n}\n\nfunction generateSslCertificate() {\nconst sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\nsslModal.show()\nsetTimeout(function() {\nconst keypair = forge.pki.rsa.generateKeyPair(2048);\nconst certificate = forge.pki.createCertificate();\nconst now = new Date();\nconst fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\nObject.assign(certificate, {\npublicKey: keypair.publicKey,\nserialNumber: "01",\nvalidity: {\nnotBefore: now,\nnotAfter: fiveYears,\n},\n});\ncertificate.sign(keypair.privateKey, forge.md.sha256.create());\nconst key = forge.pki.privateKeyToPem(keypair.privateKey);\nconst cert = forge.pki.certificateToPem(certificate);\nconst existingConfig = editor.get();\neditor.set({ ...existingConfig, ssl: { key, cert },\nport: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n});\nsslModal.hide();\n}, 100);\n}\n\nconst editor = new JSONEditor(container, options);\nlet socket;\nconst initialJson = ${JSON.stringify(
857
+ t,
858
+ )}\neditor.set(initialJson)\neditor.validate();\neditor.aceEditor.commands.addCommand({\nname: 'save',\nbindKey: {win: 'Ctrl-S', mac: 'Command-S'},\nexec: save,\n});\n\nwindow.addEventListener("DOMContentLoaded", function() {\ndocument.getElementById('jsoneditor').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\ndocument.getElementById('jsoneditor').style.width =\nparseInt(window.getComputedStyle(\ndocument.querySelector('.container')).maxWidth) + 'px';\nconst sslButton = document.createElement('button');\nsslButton.addEventListener("click", generateSslCertificate);\nsslButton.type="button";\nsslButton.classList.add("btn");\nsslButton.classList.add("btn-primary");\nsslButton.innerHTML="&#x1F512;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(sslButton);\nconst saveButton = document.createElement('button');\nsaveButton.addEventListener("click", save);\nsaveButton.type="button";\nsaveButton.classList.add("btn");\nsaveButton.classList.add("btn-primary");\nsaveButton.innerHTML="&#x1F4BE;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${
859
+ t.ssl ? "s" : ""
860
+ }://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`,
861
+ ))(R, e.config)
862
+ : q
863
+ ? yield Promise.race([
864
+ new Promise(e => {
865
+ const t = (0, n.connect)(
866
+ P,
867
+ { rejectUnauthorized: !1, protocol: E.protocol },
868
+ (n, o) => {
869
+ (q = q && !!o.alpnProtocol), e(q ? t : null);
870
+ },
871
+ );
872
+ t.on("error", e => {
873
+ W = q && Buffer.from(I(e, "connection", w, P));
874
+ });
875
+ }),
876
+ new Promise(e =>
877
+ setTimeout(() => {
878
+ (q = !1), e(null);
879
+ }, 3e3),
880
+ ),
881
+ ])
882
+ : null;
883
+ W instanceof Buffer || (W = null);
884
+ const F = null == i ? void 0 : i.readableLength,
885
+ _ =
886
+ null === (l = null == i ? void 0 : i.stream) || void 0 === l
887
+ ? void 0
888
+ : l.readableLength;
889
+ let J = null;
890
+ const K = e.config.replaceRequestBodyUrls || e.logsListeners.length,
891
+ z = !(
892
+ ((e.config.ssl && 0 === _) || (!e.config.ssl && 0 === F)) &&
893
+ ("0" === i.headers["content-length"] ||
894
+ void 0 === i.headers["content-length"])
895
+ );
896
+ if (K) {
897
+ const n =
898
+ null !== (h = null == i ? void 0 : i.stream) && void 0 !== h ? h : i;
899
+ let o = Buffer.from([]);
900
+ yield Promise.race([
901
+ new Promise(e => setTimeout(e, 1e4)),
902
+ new Promise(e => {
903
+ z
904
+ ? (n.on("data", e => {
905
+ o = Buffer.concat([o, e]);
906
+ }),
907
+ n.on("end", e),
908
+ n.on("error", e))
909
+ : e(void 0);
910
+ }),
911
+ ]),
912
+ z &&
913
+ !o.length &&
914
+ e.log(`body replacement error ${O.slice(-17)}`, p.WARNING, u.ERROR_4),
915
+ (J = e.config.replaceRequestBodyUrls
916
+ ? yield T(o, i.headers, {
917
+ proxyHostnameAndPort: R,
918
+ proxyHostname: t,
919
+ key: $,
920
+ mapping: e.config.mapping,
921
+ port: e.config.port,
922
+ ssl: !!e.config.ssl,
923
+ direction: g.OUTBOUND,
924
+ })
925
+ : o);
926
+ }
927
+ const G = Object.assign(
928
+ Object.assign(
929
+ {},
930
+ [...Object.entries(i.headers)]
931
+ .filter(
932
+ ([e]) =>
933
+ !["host", "connection", "keep-alive"].includes(e.toLowerCase()),
934
+ )
935
+ .reduce(
936
+ (e, [t, n]) => (
937
+ (e[t] =
938
+ (e[t] || "") +
939
+ (Array.isArray(n) ? n : [n])
940
+ .map(e => e.replace(w.hostname, x))
941
+ .join(", ")),
942
+ e
943
+ ),
944
+ {},
945
+ ),
946
+ ),
947
+ {
948
+ origin: E.href,
949
+ referer: P.toString(),
950
+ "content-length":
951
+ null !==
952
+ (y =
953
+ null !== (v = null == J ? void 0 : J.length) && void 0 !== v
954
+ ? v
955
+ : i.headers["content-length"]) && void 0 !== y
956
+ ? y
957
+ : 0,
958
+ ":authority": x,
959
+ ":method": i.method,
960
+ ":path": L,
961
+ ":scheme": E.protocol.replace(":", ""),
962
+ },
963
+ ),
964
+ Y =
965
+ M &&
966
+ !W &&
967
+ M.request(G, { endStream: e.config.ssl ? !(null == _ || _) : !F });
968
+ null == Y ||
969
+ Y.on("error", e => {
970
+ const t = -505 === e.errno;
971
+ W = Buffer.from(
972
+ I(
973
+ e,
974
+ "stream" +
975
+ (t
976
+ ? " (error -505 usually means that the downstream service does not support this http version)"
977
+ : ""),
978
+ w,
979
+ P,
980
+ ),
981
+ );
982
+ });
983
+ const Z = {
984
+ hostname: E.hostname,
985
+ path: L,
986
+ port: E.port,
987
+ protocol: E.protocol,
988
+ rejectUnauthorized: !1,
989
+ method: i.method,
990
+ headers: Object.assign(
991
+ Object.assign(
992
+ {},
993
+ Object.assign(
994
+ {},
995
+ ...Object.entries(G)
996
+ .filter(
997
+ ([e]) =>
998
+ !e.startsWith(":") &&
999
+ "transfer-encoding" !== e.toLowerCase(),
1000
+ )
1001
+ .map(([e, t]) => ({ [e]: t })),
1002
+ ),
1003
+ ),
1004
+ { host: E.hostname },
1005
+ ),
1006
+ },
1007
+ V =
1008
+ !W &&
1009
+ !q &&
1010
+ !["file:", "logs:", "config:"].includes(E.protocol) &&
1011
+ (yield new Promise(e => {
1012
+ const t =
1013
+ "https:" === E.protocol
1014
+ ? (0, r.request)(Z, e)
1015
+ : (0, o.request)(Z, e);
1016
+ t.on("error", t => {
1017
+ (W = Buffer.from(I(t, "request", w, P))), e(null);
1018
+ }),
1019
+ K && (t.write(J), t.end()),
1020
+ K || (i.on("data", e => t.write(e)), i.on("end", () => t.end()));
1021
+ }));
1022
+ if (W) return void U(502, a, W);
1023
+ (W = null),
1024
+ _ && Y && !K
1025
+ ? (i.stream.on("data", e => {
1026
+ Y.write(e);
1027
+ }),
1028
+ i.stream.on("end", () => Y.end()))
1029
+ : F && Y && !K
1030
+ ? (i.on("data", e => {
1031
+ Y.write(e);
1032
+ }),
1033
+ i.on("end", () => Y.end()))
1034
+ : Y && K && z && (Y.write(J), Y.end());
1035
+ const { outboundResponseHeaders: Q } = yield new Promise(e =>
1036
+ Y
1037
+ ? Y.on("response", t => {
1038
+ e({ outboundResponseHeaders: t });
1039
+ })
1040
+ : e(
1041
+ !Y && V
1042
+ ? { outboundResponseHeaders: V.headers }
1043
+ : { outboundResponseHeaders: {} },
1044
+ ),
1045
+ );
1046
+ let X = null;
1047
+ try {
1048
+ Q.location &&
1049
+ (X = new s.URL(
1050
+ Q.location.startsWith("/")
1051
+ ? `${E.href}${Q.location.replace(/^\/+/, "")}`
1052
+ : Q.location
1053
+ .replace(/^file:\/+/, "file:///")
1054
+ .replace(/^(http)(s?):\/+/, "$1$2://"),
1055
+ ));
1056
+ } catch (t) {
1057
+ e.log(
1058
+ `location replacement error ${(null !== (b = Q.location) && void 0 !== b
1059
+ ? b
1060
+ : ""
1061
+ ).slice(-13)}`,
1062
+ p.WARNING,
1063
+ u.ERROR_4,
1064
+ );
1065
+ }
1066
+ const ee =
1067
+ e.config.replaceResponseBodyUrls && X
1068
+ ? new s.URL(
1069
+ C(X.href, {
1070
+ direction: g.INBOUND,
1071
+ proxyHostnameAndPort: R,
1072
+ ssl: !!e.config.ssl,
1073
+ mapping: e.config.mapping,
1074
+ }).replace(/^(config:|logs:|file:)\/+/, ""),
1075
+ )
1076
+ : X,
1077
+ te = X
1078
+ ? ee.origin !== X.origin || e.config.dontTranslateLocationHeader
1079
+ ? ee
1080
+ : `${w.origin}${ee.href.substring(ee.origin.length)}`
1081
+ : X,
1082
+ ne = Y || V,
1083
+ oe =
1084
+ null != W
1085
+ ? W
1086
+ : yield new Promise(e => {
1087
+ let t = Buffer.alloc(0);
1088
+ ne
1089
+ ? (ne.on(
1090
+ "data",
1091
+ e =>
1092
+ (t = Buffer.concat([
1093
+ t,
1094
+ "string" == typeof e ? Buffer.from(e) : e,
1095
+ ])),
1096
+ ),
1097
+ ne.on("end", () => {
1098
+ e(t);
1099
+ }))
1100
+ : e(t);
1101
+ }).then(n =>
1102
+ e.config.replaceResponseBodyUrls && n.length
1103
+ ? "config:" === E.protocol
1104
+ ? n
1105
+ : T(n, Q, {
1106
+ proxyHostnameAndPort: R,
1107
+ proxyHostname: t,
1108
+ key: $,
1109
+ direction: g.INBOUND,
1110
+ mapping: e.config.mapping,
1111
+ port: e.config.port,
1112
+ ssl: !!e.config.ssl,
1113
+ }).catch(
1114
+ e => (
1115
+ U(502, a, Buffer.from(I(e, "stream", w, P))),
1116
+ Buffer.from("")
1117
+ ),
1118
+ )
1119
+ : n,
1120
+ ),
1121
+ re = Object.assign(
1122
+ Object.assign(
1123
+ {},
1124
+ Object.entries(
1125
+ Object.assign(
1126
+ Object.assign(
1127
+ Object.assign({}, Q),
1128
+ e.config.replaceResponseBodyUrls
1129
+ ? { "content-length": `${oe.byteLength}` }
1130
+ : {},
1131
+ ),
1132
+ e.config.disableWebSecurity
1133
+ ? {
1134
+ "content-security-policy": "report only",
1135
+ "access-control-allow-headers": "*",
1136
+ "access-control-allow-method": "*",
1137
+ "access-control-allow-origin": "*",
1138
+ }
1139
+ : {},
1140
+ ),
1141
+ )
1142
+ .filter(
1143
+ ([e]) =>
1144
+ !e.startsWith(":") &&
1145
+ "transfer-encoding" !== e.toLowerCase() &&
1146
+ "connection" !== e.toLowerCase() &&
1147
+ "keep-alive" !== e.toLowerCase(),
1148
+ )
1149
+ .reduce((e, [t, n]) => {
1150
+ const o = x
1151
+ .split("")
1152
+ .map(
1153
+ (e, t) => x.substring(t).startsWith(".") && x.substring(t),
1154
+ )
1155
+ .filter(e => e),
1156
+ r = [x]
1157
+ .concat(o)
1158
+ .reduce(
1159
+ (e, t) =>
1160
+ (Array.isArray(e) ? e : [e]).map(e =>
1161
+ "string" == typeof e
1162
+ ? e.replace(`Domain=${t}`, `Domain=${w.hostname}`)
1163
+ : e,
1164
+ ),
1165
+ n,
1166
+ );
1167
+ return (e[t] = (e[t] || []).concat(r)), e;
1168
+ }, {}),
1169
+ ),
1170
+ te ? { location: [te] } : {},
1171
+ );
1172
+ try {
1173
+ Object.entries(re).forEach(([e, t]) => t && a.setHeader(e, t));
1174
+ } catch (e) {}
1175
+ const se = Q[":status"] || V.statusCode || 200;
1176
+ a.writeHead(
1177
+ se,
1178
+ e.config.ssl ? void 0 : V.statusMessage || "Status read from http/2",
1179
+ re,
1180
+ ),
1181
+ oe ? a.end(oe) : a.end();
1182
+ const ie = d.hrtime.bigint();
1183
+ e.notifyLogsListeners({
1184
+ randomId: A,
1185
+ statusCode: se,
1186
+ protocol: q ? "HTTP/2" : "HTTP1.1",
1187
+ duration: Math.floor(Number(ie - D) / 1e6),
1188
+ uniqueHash: Buffer.from(
1189
+ JSON.stringify({
1190
+ method: i.method,
1191
+ url: i.url,
1192
+ headers: Object.assign(
1193
+ {},
1194
+ ...Object.entries(i.headers)
1195
+ .filter(([e]) => !e.startsWith(":"))
1196
+ .map(([e, t]) => ({ [e]: t })),
1197
+ ),
1198
+ body: null == J ? void 0 : J.toJSON(),
1199
+ }),
1200
+ ).toString("base64"),
1201
+ });
1202
+ });
1203
+ };
1204
+ exports.serve = q;
1205
+ const A = (e, t) => {
1206
+ "EACCES" === t.code &&
1207
+ e.log("permission denied for this port", p.ERROR, u.NO),
1208
+ "EADDRINUSE" === t.code &&
1209
+ e.log("port is already used. NOT started", p.ERROR, u.ERROR_6);
1210
+ };
1211
+ exports.errorListener = A;
1212
+ const D = e => W({ config: Object.assign(Object.assign({}, m), e) }, {});
1213
+ exports.start = D;
1214
+ const W = (e, r) =>
1215
+ t(void 0, void 0, void 0, function* () {
1216
+ var s, a, l, c, d, g, h, m;
1217
+ if (0 === Object.keys(null != r ? r : {}).length && e.server) return;
1218
+ if (r.pendingConfigSave)
1219
+ return void (0, i.writeFile)(
1220
+ f,
1221
+ JSON.stringify(r.pendingConfigSave, null, 2),
1222
+ t => {
1223
+ var n, o;
1224
+ t
1225
+ ? null === (n = e.log) ||
1226
+ void 0 === n ||
1227
+ n.call(e, "config file NOT saved", p.ERROR, u.ERROR_4)
1228
+ : null === (o = e.log) ||
1229
+ void 0 === o ||
1230
+ o.call(e, "config file saved... will reload", p.INFO, u.COLORED);
1231
+ },
1232
+ );
1233
+ if (
1234
+ (null === r.configListeners &&
1235
+ (yield Promise.all(
1236
+ e.configListeners.map(e => new Promise(t => e.stream.end(t))),
1237
+ )),
1238
+ null === r.logsListeners &&
1239
+ (yield Promise.all(
1240
+ e.logsListeners.map(e => new Promise(t => e.stream.end(t))),
1241
+ )),
1242
+ null === r.server)
1243
+ ) {
1244
+ (yield Promise.race([
1245
+ new Promise(t => e.server.close(t)).then(() => !0),
1246
+ new Promise(e => setTimeout(e, 5e3)).then(() => !1),
1247
+ ])) || e.log("error during restart (websockets ?)", p.WARNING, u.RESTART);
1248
+ }
1249
+ (null !== (s = e.configListeners) && void 0 !== s ? s : [])
1250
+ .concat(null !== (a = e.logsListeners) && void 0 !== a ? a : [])
1251
+ .filter(e => e.stream.errored || e.stream.closed)
1252
+ .forEach(e => e.stream.destroy());
1253
+ const v = null !== (l = r.config) && void 0 !== l ? l : e.config,
1254
+ b = (
1255
+ null === r.configListeners
1256
+ ? []
1257
+ : null !==
1258
+ (d =
1259
+ null !== (c = r.configListeners) && void 0 !== c
1260
+ ? c
1261
+ : e.configListeners) && void 0 !== d
1262
+ ? d
1263
+ : []
1264
+ ).filter(e => !e.stream.errored && !e.stream.closed),
1265
+ R = (
1266
+ null === r.logsListeners
1267
+ ? []
1268
+ : null !==
1269
+ (h =
1270
+ null !== (g = r.logsListeners) && void 0 !== g
1271
+ ? g
1272
+ : e.logsListeners) && void 0 !== h
1273
+ ? h
1274
+ : []
1275
+ ).filter(e => !e.stream.errored && !e.stream.closed),
1276
+ w = e;
1277
+ return (
1278
+ Object.assign(w, {
1279
+ config: v,
1280
+ logsListeners: R,
1281
+ configListeners: b,
1282
+ configFileWatcher:
1283
+ null !== (m = w.configFileWatcher) && void 0 !== m
1284
+ ? m
1285
+ : (0, i.watchFile)(f, () =>
1286
+ t(void 0, void 0, void 0, function* () {
1287
+ return W(
1288
+ w,
1289
+ yield (function (e) {
1290
+ return t(this, void 0, void 0, function* () {
1291
+ const t = e.config,
1292
+ n = yield L(!1);
1293
+ return isNaN(n.port) || n.port > 65535 || n.port < 0
1294
+ ? (e.log(
1295
+ "port number invalid. Not refreshing",
1296
+ p.ERROR,
1297
+ u.PORT,
1298
+ ),
1299
+ {})
1300
+ : "object" != typeof n.mapping
1301
+ ? (e.log(
1302
+ "mapping should be an object. Aborting",
1303
+ p.ERROR,
1304
+ u.ERROR_5,
1305
+ ),
1306
+ {})
1307
+ : (n.replaceRequestBodyUrls !==
1308
+ t.replaceRequestBodyUrls &&
1309
+ e.log(
1310
+ `request body url ${
1311
+ n.replaceRequestBodyUrls ? "" : "NO "
1312
+ }rewriting`,
1313
+ p.INFO,
1314
+ u.REWRITE,
1315
+ ),
1316
+ n.replaceResponseBodyUrls !==
1317
+ t.replaceResponseBodyUrls &&
1318
+ e.log(
1319
+ `response body url ${
1320
+ n.replaceResponseBodyUrls ? "" : "NO "
1321
+ }rewriting`,
1322
+ p.INFO,
1323
+ u.REWRITE,
1324
+ ),
1325
+ n.dontTranslateLocationHeader !==
1326
+ t.dontTranslateLocationHeader &&
1327
+ e.log(
1328
+ `response location header ${
1329
+ n.dontTranslateLocationHeader ? "NO " : ""
1330
+ }translation`,
1331
+ p.INFO,
1332
+ u.REWRITE,
1333
+ ),
1334
+ n.dontUseHttp2Downstream !==
1335
+ t.dontUseHttp2Downstream &&
1336
+ e.log(
1337
+ `http/2 ${
1338
+ n.dontUseHttp2Downstream ? "de" : ""
1339
+ }activated downstream`,
1340
+ p.INFO,
1341
+ u.OUTBOUND,
1342
+ ),
1343
+ n.disableWebSecurity !== t.disableWebSecurity &&
1344
+ e.log(
1345
+ `web security ${
1346
+ n.disableWebSecurity ? "de" : ""
1347
+ }activated`,
1348
+ p.INFO,
1349
+ u.SHIELD,
1350
+ ),
1351
+ n.websocket !== t.websocket &&
1352
+ e.log(
1353
+ `websocket ${n.websocket ? "" : "de"}activated`,
1354
+ p.INFO,
1355
+ u.WEBSOCKET,
1356
+ ),
1357
+ n.simpleLogs !== t.simpleLogs &&
1358
+ e.log(
1359
+ "simple logs " + (n.simpleLogs ? "on" : "off"),
1360
+ p.INFO,
1361
+ u.COLORED,
1362
+ ),
1363
+ Object.keys(n.mapping).join("\n") !==
1364
+ Object.keys(t.mapping).join("\n") &&
1365
+ e.log(
1366
+ `${Object.keys(n.mapping)
1367
+ .length.toString()
1368
+ .padStart(5)} loaded mapping rules`,
1369
+ p.INFO,
1370
+ u.RULES,
1371
+ ),
1372
+ n.port !== t.port &&
1373
+ e.log(
1374
+ `port changed from ${t.port} to ${n.port}`,
1375
+ p.INFO,
1376
+ u.PORT,
1377
+ ),
1378
+ n.ssl &&
1379
+ !t.ssl &&
1380
+ e.log(
1381
+ "ssl configuration added",
1382
+ p.INFO,
1383
+ u.INBOUND,
1384
+ ),
1385
+ !n.ssl &&
1386
+ t.ssl &&
1387
+ e.log(
1388
+ "ssl configuration removed",
1389
+ p.INFO,
1390
+ u.INBOUND,
1391
+ ),
1392
+ n.port !== t.port ||
1393
+ JSON.stringify(n.ssl) !== JSON.stringify(t.ssl)
1394
+ ? (e.log("restarting server", p.INFO, u.RESTART),
1395
+ x.apply(
1396
+ Object.assign(Object.assign({}, e), {
1397
+ config: n,
1398
+ }),
1399
+ ),
1400
+ { config: n, server: null })
1401
+ : (x.apply(
1402
+ Object.assign(Object.assign({}, e), {
1403
+ config: n,
1404
+ }),
1405
+ ),
1406
+ { config: n }));
1407
+ });
1408
+ })(w),
1409
+ );
1410
+ }),
1411
+ ),
1412
+ log: y.bind(w, w),
1413
+ notifyConfigListeners: O.bind(w),
1414
+ notifyLogsListeners: $.bind(w),
1415
+ quickStatus: x.bind(w),
1416
+ server:
1417
+ null !== r.server && w.server
1418
+ ? w.server
1419
+ : (v.ssl
1420
+ ? n.createSecureServer.bind(
1421
+ null,
1422
+ Object.assign(Object.assign({}, v.ssl), { allowHTTP1: !0 }),
1423
+ )
1424
+ : o.createServer)((e, t) => q(w, e, t))
1425
+ .addListener("error", e => A(w, e))
1426
+ .addListener("listening", () => w.quickStatus())
1427
+ .on("upgrade", (e, t) => W(w, P(w, e, t)))
1428
+ .listen(v.port),
1429
+ }),
1430
+ w
1431
+ );
1432
+ });
1433
+ exports.update = W;
1434
+ const M =
1435
+ null !==
1436
+ (e = d.argv.filter(
1437
+ e =>
1438
+ !["ts-node", "node", "npx", "npm", "exec"].some(
1439
+ t => e.includes(t) && !e.match(/npm-cache/) && !e.match(/_npx/),
1440
+ ),
1441
+ )[0]) && void 0 !== e
1442
+ ? e
1443
+ : "";
1444
+ M.toLowerCase().replace(/[-_]/g, "").includes("localtraffic") &&
1445
+ !M.match(/(.|-)?(test|spec)\.m?[jt]sx?$/) &&
1446
+ L().then(D);