local-traffic 0.0.78 → 0.0.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/local-traffic.js +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ That is a secure http/2 (or insecure http1.1) reverse-proxy installed on your ma
|
|
|
5
5
|
- with 0 transitive dependency
|
|
6
6
|
- with 1 install step
|
|
7
7
|
- with a startup time of a few milliseconds
|
|
8
|
-
- with one
|
|
8
|
+
- with one 46kb index.js file
|
|
9
9
|
|
|
10
10
|
How simple is that ?
|
|
11
11
|
|
|
@@ -32,6 +32,7 @@ npx local-traffic
|
|
|
32
32
|
"/my-static-webapp/": "file:///home/user/projects/my-static-webapp/",
|
|
33
33
|
"/config/": "config://",
|
|
34
34
|
"/logs/": "logs://",
|
|
35
|
+
"/recorder/": "recorder://",
|
|
35
36
|
"/jquery-local/jquery.js": {
|
|
36
37
|
"replaceBody": "https://mycdn.net/jquery/jquery-3.6.4.js",
|
|
37
38
|
"downstreamUrl": "file:///home/user/projects/zepto/dist/zepto.js"
|
|
@@ -48,9 +49,10 @@ npx local-traffic
|
|
|
48
49
|
4. Go to [http://localhost:8080/my-static-webapp/index.html](http://localhost:8080/my-static-webapp/index.html) with your browser (given your project name is my-static-webapp, but I am not 100% sure)
|
|
49
50
|
5. Go to [http://localhost:8080/logs/](http://localhost:8080/logs/) to watch the request logs
|
|
50
51
|
6. Go to [http://localhost:8080/config/](http://localhost:8080/config/) to change the config in a web editor
|
|
51
|
-
7.
|
|
52
|
-
8.
|
|
53
|
-
9. Your
|
|
52
|
+
7. You can use the [http://localhost:8080/recorder/](recorder) to turn your proxy into a mock server.
|
|
53
|
+
8. From the web config editor, create a SSL keypair and start working with a self signed SSL certificate right away
|
|
54
|
+
9. Your page will use /jquery-local/jquery.js instead of the CDN asset, and will serve the file from your hard drive
|
|
55
|
+
10. Your server now proxies the mapping that you have configured
|
|
54
56
|
|
|
55
57
|
## usage
|
|
56
58
|
|
|
@@ -90,3 +92,5 @@ All boolean settings default to false when unspecified.
|
|
|
90
92
|
- `simpleLogs`: (`boolean`) disable colored logs for text terminals
|
|
91
93
|
- `websocket`: (`boolean`) true to activate websocket connections proxying via sockets. Required for logs UI.
|
|
92
94
|
- `disableWebSecurity`: (`boolean`) true for easygoing values in cross origin requests or content security policy headers
|
|
95
|
+
- `connectTimeout`: (`number`) max time before aborting the connection (defaults to 3000ms)
|
|
96
|
+
- `socketTimeout`: (`number`) max time waiting for a response (defaults to 3000ms)
|
package/dist/local-traffic.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const n=require("http2"),o=require("http"),r=require("https"),s=require("url"),i=require("fs"),a=require("zlib"),l=require("path"),c=require("crypto"),d=require("process"),p=require("os");var u,g,h;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(u||(u={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(g||(g={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={}));const f=(0,l.resolve)((0,p.homedir)(),".local-traffic.json"),m=(0,l.resolve)((0,d.cwd)(),d.argv.slice(-1)[0].endsWith(".json")?d.argv.slice(-1)[0]:f),v={mapping:{"/config/":"config://","/logs/":"logs://"},port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1},y=()=>{var e,t;return null!==(t=null===(e=d.hrtime.bigint)||void 0===e?void 0:e.call(d.hrtime))&&void 0!==t?t:(()=>{const e=(0,d.hrtime)();return 1e3*e[0]+e[1]/1e6})()},b=e=>e===u.ERROR?"error":e===u.WARNING?"warning":"info",R=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(g.INBOUND,"g"),"inbound:").replace(new RegExp(g.PORT,"g"),"port:").replace(new RegExp(g.OUTBOUND,"g"),"outbound:").replace(new RegExp(g.RULES,"g"),"rules:").replace(new RegExp(g.NO,"g"),"").replace(new RegExp(g.REWRITE,"g"),"+rewrite").replace(new RegExp(g.WEBSOCKET,"g"),"websocket").replace(new RegExp(g.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${d.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹[0m`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:b(n)})},O=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=[...e.substring(0,65536)].map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=Math.min(65535,e.length),s=e.length<126?Buffer.from(Uint8Array.from([129,(t?128:0)+r]).buffer):Buffer.concat([Buffer.from(Uint8Array.from([129,126|(t?128:0)]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]),i=Buffer.from(Int8Array.from(n).buffer),a=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[s,i,a]:[s,a])};exports.createWebsocketBufferFrom=O;const w=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=w;const $=(e,t)=>{const n=(0,c.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`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`)};exports.acknowledgeWebsocket=$;const E=function(e){return L(this,e,this.configListeners)},x=function(e){return L(this,e,this.logsListeners)},L=(e,t,n)=>{if(!n.length)return;const o=JSON.stringify(t),r=new Set(n.map((e=>e.wantsMask))),s=r.has(!1)&&O(o,!1),i=r.has(!0)&&O(o,!0),a=e=>{e.stream.errored&&e.stream.destroy()};n.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(i,"ascii",(()=>a(e))):e.stream.write(s,"ascii",(()=>a(e))))}))},S=function(){this.log(`[48;5;52m⎸${g.PORT} ${this.config.port.toString().padStart(5)} [48;5;53m⎸${g.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?g.REWRITE:" "}⎹⎸${g.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?g.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}⎹[48;5;56m⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹[48;5;57m⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹[48;5;93m⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹[0m`),this.notifyConfigListeners(this.config)};exports.quickStatus=S;const N=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,i.readFile)(m,((n,o)=>{n&&!e&&R(null,"config error. Using default value",u.ERROR,g.ERROR_1);let r=null;try{r=Object.assign({},v,JSON.parse((o||"{}").toString()))}catch(e){return R({config:r},"config syntax incorrect, aborting",u.ERROR,g.ERROR_2),r=null!=r?r:Object.assign({},v),void t(r)}r.mapping[""]||R({config:r},'default mapping "" not provided.',u.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&m===f?(0,i.writeFile)(m,JSON.stringify(v,null,2),(e=>{e?R(null,"config file NOT created",u.ERROR,g.ERROR_4):R(null,"config file created",u.INFO,g.COLORED),t(r)})):t(r)}))))}));exports.load=N;const B=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),j="https://cdn.jsdelivr.net/npm/",k=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],T=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="${j}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${j}jquery/dist/jquery.min.js"><\/script>\n<script src="${j}bootstrap/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,C=e=>{const t=(0,l.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,i.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,i.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,i.lstat)((0,l.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${T(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}},I=e=>({error:null,data:null,run:function(){return new Promise((t=>{this.data=e,t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{"response"===e&&this.events.response({Server:"local","Content-Type":"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this}}),U=(e,t,n,o)=>`${T(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\nⓘ This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</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>${o||"<no-target-url>"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,H=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?a.gunzip:"deflate"===t?a.inflate:"br"===t?a.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\x7F]/.test(e.toString()))?P(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.port}&pathname=${encodeURIComponent(o.key.replace(/\/+$/,""))}`):e})).then((e=>{var t,o;return(null!==(o=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==o?o:"").split(",").reverse().reduce(((e,t)=>{const n=t.trim().toLowerCase(),o="gzip"===n||"x-gzip"===n?a.gzip:"deflate"===n?a.deflate:"br"===n?a.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>o(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))}));exports.replaceBody=H;const P=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>s.startsWith("logs:")||s.startsWith("config:")||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(s.replace(/^(file|logs):\/\//,"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=P;const q=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=q;const A=(e,t)=>{var n,o,r,i,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(i=t.port)&&void 0!==i?i:8080}`:""}`,d=new s.URL(`http${t.ssl?"s":""}://${c}${e.url}`),p=d.href.substring(d.origin.length),u=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new s.URL(B("string"==typeof t?t:t.downstreamUrl))}))))),[g,h]=null!==(a=Object.entries(u).find((([e])=>p.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:p,key:g,target:h}};exports.determineMapping=A;const D=function(e,t,n){var i,a,l,c;if(!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:d,target:p,path:h}=A(t,e.config);if("/local-traffic-logs"===h)return $(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(i=t.headers["user-agent"])||void 0===i?void 0:i.toString())&&void 0!==a?a:"").includes("Chrome")})};if("/local-traffic-config"===h){$(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=w(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",u.WARNING,g.ERROR_4)}_(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const f=new s.URL(`${p.protocol}//${p.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),m={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},v="https:"===f.protocol?(0,r.request)(m):(0,o.request)(m);v.end(),v.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),u.WARNING,g.WEBSOCKET)})),v.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),u.WARNING,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),u.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=D;const W=function(e,i,a){var l,d,p,f,b;return t(this,void 0,void 0,(function*(){if(!i.headers.host&&!i.headers[":authority"])return void q(400,a,Buffer.from(U(new Error("client must supply a 'host' header"),"proxy",new s.URL(`http${e.config.ssl?"s":""}://unknowndomain${i.url}`))));const{proxyHostname:t,proxyHostnameAndPort:R,url:O,path:w,key:$,target:E}=A(i,e.config);if(!E)return void q(502,a,Buffer.from(U(new Error(`No mapping found in config file ${m}`),"proxy",O)));const x=E.host.replace(RegExp(/\/+$/),""),L=`${E.href.substring(8+E.host.length)}${B(w.replace(RegExp(B($)),""))}`.replace(/^\/*/,"/"),S=new s.URL(`${E.protocol}//${x}${L}`);let N=!e.config.dontUseHttp2Downstream;const D=(0,c.randomBytes)(20).toString("hex");e.notifyLogsListeners({level:"info",protocol:N?"HTTP/2":"HTTP1.1",method:i.method,upstreamPath:w,downstreamPath:S.href,randomId:D,uniqueHash:"N/A"});const W=y();let M=null;const F="file:"===E.protocol?C(S):"logs:"===E.protocol?((e,t)=>I(`${T(128250,"logs","")}\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${t?"s":""}://${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"' : '') + '>🔁</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">⏱</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>`))(R,!!e.config.ssl):"config:"===E.protocol?((e,t)=>I(`${T(127899,"config","")}\n<link href="${j}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${j}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${j}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(Object.assign(Object.assign({},v),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n")}\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(t)}\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="🔒";\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="💾";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`))(R,e.config):N?yield Promise.race([new Promise((e=>{const t=(0,n.connect)(S,{timeout:3e3,sessionTimeout:3e3,rejectUnauthorized:!1,protocol:E.protocol},((n,o)=>{N=N&&!!o.alpnProtocol,e(N?t:null)}));t.on("error",(e=>{M=N&&Buffer.from(U(e,"connection",O,S))}))})),new Promise((e=>setTimeout((()=>{N=!1,e(null)}),3e3)))]):null;M instanceof Buffer||(M=null);const _=null==i?void 0:i.readableLength,J=null===(l=null==i?void 0:i.stream)||void 0===l?void 0:l.readableLength;let K=null;const z=e.config.replaceRequestBodyUrls||e.logsListeners.length,G=!((e.config.ssl&&0===J||!e.config.ssl&&0===_)&&("0"===i.headers["content-length"]||void 0===i.headers["content-length"]));if(z){const n=null!==(d=null==i?void 0:i.stream)&&void 0!==d?d:i;let o=Buffer.from([]);yield Promise.race([new Promise((e=>setTimeout(e,1e4))),new Promise((e=>{G?(n.on("data",(e=>{o=Buffer.concat([o,e])})),n.on("end",e),n.on("error",e)):e(void 0)}))]),G&&!o.length&&e.log(`body replacement error ${w.slice(-17)}`,u.WARNING,g.ERROR_4),K=e.config.replaceRequestBodyUrls?yield H(o,i.headers,{proxyHostnameAndPort:R,proxyHostname:t,key:$,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):o}const Y=Object.assign(Object.assign({},[...Object.entries(i.headers)].filter((([e])=>!k.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(O.hostname,x))).join(", "),e)),{})),{origin:E.href,referer:S.toString(),"content-length":null!==(f=null!==(p=null==K?void 0:K.length)&&void 0!==p?p:i.headers["content-length"])&&void 0!==f?f:0,":authority":x,":method":i.method,":path":L,":scheme":E.protocol.replace(":","")}),Z=F&&!M&&F.request(Y,{endStream:e.config.ssl?!(null==J||J):!_});null==Z||Z.on("error",(e=>{const t=-505===e.errno;M=Buffer.from(U(e,"stream"+(t?" (error -505 usually means that the downstream service does not support this http version)":""),O,S))}));const V={hostname:E.hostname,path:L,port:E.port,protocol:E.protocol,rejectUnauthorized:!1,method:i.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(Y).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},Q=!M&&!N&&!["file:","logs:","config:"].includes(E.protocol)&&(yield new Promise((e=>{const t="https:"===E.protocol?(0,r.request)(V,e):(0,o.request)(V,e);t.on("error",(t=>{M=Buffer.from(U(t,"request",O,S)),e(null)})),z&&(t.write(K),t.end()),z||(i.on("data",(e=>t.write(e))),i.on("end",(()=>t.end())))})));if(M)return void q(502,a,M);M=null,J&&Z&&!z?(i.stream.on("data",(e=>{Z.write(e)})),i.stream.on("end",(()=>Z.end()))):_&&Z&&!z?(i.on("data",(e=>{Z.write(e)})),i.on("end",(()=>Z.end()))):Z&&z&&G&&(Z.write(K),Z.end());const{outboundResponseHeaders:X}=yield new Promise((e=>Z?Z.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!Z&&Q?{outboundResponseHeaders:Q.headers}:{outboundResponseHeaders:{}})));let ee=null;try{X.location&&(ee=new s.URL(X.location.startsWith("/")?`${E.origin}${X.location.replace(/^\/+/,"/")}`:X.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=X.location)&&void 0!==b?b:"").slice(-13)}`,u.WARNING,g.ERROR_4)}const te=e.config.replaceResponseBodyUrls&&ee?new s.URL(P(ee.href,{direction:h.INBOUND,proxyHostnameAndPort:R,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(/^(config:|logs:|file:)\/+/,"")):ee,ne=ee?te.origin!==ee.origin||e.config.dontTranslateLocationHeader?te:`${O.origin}${te.href.substring(te.origin.length)}`:ee,oe=Z||Q,re=null!=M?M:yield new Promise((e=>{let t=Buffer.alloc(0);oe?(oe.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),oe.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?"config:"===E.protocol?n:H(n,X,{proxyHostnameAndPort:R,proxyHostname:t,key:$,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((e=>(q(502,a,Buffer.from(U(e,"stream",O,S))),Buffer.from("")))):n)),se=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},X),e.config.replaceResponseBodyUrls?{"content-length":`${re.byteLength}`}:{}),e.config.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&!k.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=x.split("").map(((e,t)=>x.substring(t).startsWith(".")&&x.substring(t))).filter((e=>e)),r=[x].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${O.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),ne?{location:[ne]}:{});try{Object.entries(se).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ie=X[":status"]||Q.statusCode||200;a.writeHead(ie,e.config.ssl?void 0:Q.statusMessage||"Status read from http/2",se),re?a.end(re):a.end();const ae=y();e.notifyLogsListeners({randomId:D,statusCode:ie,protocol:N?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ae-W)/1e6),uniqueHash:Buffer.from(JSON.stringify({method:i.method,url:i.url,headers:Object.assign({},...Object.entries(i.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==K?void 0:K.toJSON()})).toString("base64")})}))};exports.serve=W;const M=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",u.ERROR,g.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",u.ERROR,g.ERROR_6)};exports.errorListener=M;const F=e=>_({config:Object.assign(Object.assign({},v),e)},{});exports.start=F;const _=(e,r)=>t(void 0,void 0,void 0,(function*(){var s,a,l,c,d,p,h,f,v;if(0===Object.keys(null!=r?r:{}).length&&e.server)return;if(r.pendingConfigSave)return void(0,i.writeFile)(m,JSON.stringify(r.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",u.ERROR,g.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",u.INFO,g.COLORED)}));if(null===r.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===r.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",u.WARNING,g.RESTART)}(null!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(a=e.logsListeners)&&void 0!==a?a:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const y=null!==(l=r.config)&&void 0!==l?l:e.config,b=(null===r.configListeners?[]:null!==(d=null!==(c=r.configListeners)&&void 0!==c?c:e.configListeners)&&void 0!==d?d:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),O=(null===r.logsListeners?[]:null!==(h=null!==(p=r.logsListeners)&&void 0!==p?p:e.logsListeners)&&void 0!==h?h:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),w=e;return Object.assign(w,{config:y,logsListeners:O,configListeners:b,configFileWatcher:void 0===w.configFileWatcher?(0,i.watchFile)(m,(()=>t(void 0,void 0,void 0,(function*(){return _(w,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield N(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",u.ERROR,g.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",u.ERROR,g.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,u.INFO,g.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,u.INFO,g.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,u.INFO,g.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,u.INFO,g.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,u.INFO,g.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,u.INFO,g.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),u.INFO,g.COLORED),Object.keys(n.mapping).join("\n")!==Object.keys(t.mapping).join("\n")&&e.log(`${Object.keys(n.mapping).length.toString().padStart(5)} loaded mapping rules`,u.INFO,g.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,u.INFO,g.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",u.INFO,g.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",u.INFO,g.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",u.INFO,g.RESTART),S.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(S.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(w))})))):w.configFileWatcher,log:R.bind(w,w),notifyConfigListeners:E.bind(w),notifyLogsListeners:x.bind(w),quickStatus:S.bind(w),server:null!==r.server&&w.server||(null!==(v=null===(f=r.config)||void 0===f?void 0:f.port)&&void 0!==v?v:0)<0?null===r.server?null:w.server:(y.ssl?n.createSecureServer.bind(null,Object.assign(Object.assign({},y.ssl),{allowHTTP1:!0})):o.createServer)(((e,t)=>W(w,e,t))).addListener("error",(e=>M(w,e))).addListener("listening",(()=>w.quickStatus())).on("upgrade",((e,t)=>_(w,D(w,e,t)))).listen(y.port)}),w}));exports.update=_;const J=null!==(e=d.argv.filter((e=>!["ts-node","node","npx","npm","exec"].some((t=>e.includes(t)&&!e.match(/npm-cache/)&&!e.match(/_npx/)))))[0])&&void 0!==e?e:"",K=J.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!J.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),z=d.argv.some((e=>"--crash-test"===e));if(z){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,o.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();_({config:Object.assign(Object.assign({},v),{port:e}),configFileWatcher:null},{}).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,response:t})=>200!==t.statusCode?Promise.reject("Crash test has failed"):_(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):R(e,"Crash test successful",u.INFO,g.COLORED))).then((()=>(0,d.exit)(0))).catch((()=>(0,d.exit)(1)))}!z&&K&&N().then(F);
|
|
2
|
+
"use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))},n=this&&this.__rest||function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.cleanEntropy=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const o=require("http2"),r=require("http"),s=require("https"),i=require("url"),a=require("fs"),c=require("zlib"),l=require("path"),d=require("crypto"),u=require("process"),p=require("os");var m,f,h,g;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(m||(m={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.MOCKS="🌐",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(f||(f={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={})),function(e){e.PROXY="proxy",e.MOCK="mock"}(g||(g={}));const v=(0,l.resolve)((0,p.homedir)(),".local-traffic.json"),y=(0,l.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:v),b=()=>{var e,t;return null!==(t=null===(e=u.hrtime.bigint)||void 0===e?void 0:e.call(u.hrtime))&&void 0!==t?t:(()=>{const e=(0,u.hrtime)();return 1e3*e[0]+e[1]/1e6})()},O=e=>e===m.ERROR?"error":e===m.WARNING?"warning":"info",k=function(e,t,n,o){var r,s,i,a,c;const l=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(f.INBOUND,"g"),"inbound:").replace(new RegExp(f.PORT,"g"),"port:").replace(new RegExp(f.OUTBOUND,"g"),"outbound:").replace(new RegExp(f.RULES,"g"),"rules:").replace(new RegExp(f.NO,"g"),"").replace(new RegExp(f.REWRITE,"g"),"+rewrite").replace(new RegExp(f.WEBSOCKET,"g"),"websocket").replace(new RegExp(f.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?l:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹[0m`:t}`),null===(c=null==e?void 0:e.notifyLogsListeners)||void 0===c||c.call(e,{event:l,level:O(n)})},w=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=e.split("").map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=e.length,s=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,s+r]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|s]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|s]).buffer),Buffer.concat(Number(r).toString(16).padStart(16,"0").match(/.{2}/g).map((e=>parseInt(e,16))).map((e=>Buffer.from(Uint8Array.from([e]).buffer))))]),a=Buffer.from(Int8Array.from(n).buffer),c=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,c]:[i,c])};exports.createWebsocketBufferFrom=w;const R=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],c=t?0:r?8:4,l=Array(e.length-c).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+c)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(l)}};exports.readWebsocketBuffer=R;const S=(e,t)=>{const n=(0,d.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`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`)};exports.acknowledgeWebsocket=S;const E=function(e){return x(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([x(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),x(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},x=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),r=o.has(!1)&&w(n,!1),s=o.has(!0)&&w(n,!0),i=e=>{e.stream.errored&&e.stream.destroy()};t.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(s,"ascii",(()=>i(e))):e.stream.write(r,"ascii",(()=>i(e))))}))},L=function(){this.log(`[48;5;52m⎸${f.PORT} ${this.config.port.toString().padStart(5)} [48;5;53m⎸${f.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?f.REWRITE:" "}⎹⎸${f.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?f.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${this.mode===g.PROXY?`${f.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${f.MOCKS}${this.mocks.size.toString().padStart(3)}`}⎹[48;5;56m⎸${this.config.websocket?f.WEBSOCKET:f.NO}⎹[48;5;57m⎸${this.config.simpleLogs?f.NO:f.COLORED}⎹[48;5;93m⎸${this.config.disableWebSecurity?f.NO:f.SHIELD}⎹[0m`),this.notifyConfigListeners(this.config)};exports.quickStatus=L;const B=(e,t,n,o,r)=>`${q(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\nⓘ This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n<tbody>\n<tr>\n<td>server mode</td>\n<td>${t}</td>\n</tr>\n<tr>\n<td>phase</td>\n<td>${n}</td>\n</tr>\n<tr>\n<td>requested URL</td>\n<td>${o}</td>\n</tr>\n<tr>\n<td>downstream URL</td>\n<td>${r||"<no-target-url>"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,N=(e,t,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"${!0===n.captureResponseBody?' style="min-width: 110px"':""}>...</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${t.ssl?"s":""}://${e}/local-traffic-logs${n.captureResponseBody?"?wantsResponseMessage=true":""}");\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) { }\nif (document.getElementById('mock-mode')?.checked) return;\nif (${!0===n.captureResponseBody} && \ndata?.downstreamPath?.startsWith('recorder://'))\nreturn;\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst remove = ${!0===n.captureResponseBody} && uniqueHash\n? '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">❌</button>'\n: ''\nconst replay = uniqueHash ? '<button data-response="' + \nbtoa(JSON.stringify(data.response ?? {})) +\n'" data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary">🔁</button>' : '';\nif(data.statusCode && uniqueHash) {\nconst color = getColorFromStatusCode(data.statusCode);\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 + remove;\n}\n} else if (uniqueHash) {\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + data.randomId + '">' +\n'<td scope="col" class="replay">' + replay + remove + '</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">⏱</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] \${JSON.stringify(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 remove(event) {\nevent.target.closest('tr').remove();\nif (window.updateState) window.updateState();\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}\nfunction getColorFromStatusCode(statusCode) {\nreturn Math.floor(statusCode / 100) === 1 ? "info" :\nMath.floor(statusCode / 100) === 2 ? "success" :\nMath.floor(statusCode / 100) === 3 ? "dark" :\nMath.floor(statusCode / 100) === 4 ? "warning" :\nMath.floor(statusCode / 100) === 5 ? "danger" :\n"secondary";\n}\nwindow.addEventListener("DOMContentLoaded", start);\n<\/script>`,j={logs:(e,t)=>W(`${q(128250,"logs","")}\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${N(e,t.config,{captureResponseBody:!1})}\n</body></html>`),config:(e,t)=>W(`${q(127899,"config","")}\n<link href="${P}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${P}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${P}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 increase 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(Object.assign(Object.assign({},C),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n")}\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(t.config)}\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="🔒";\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="💾";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.config.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`),recorder:(e,t,n)=>{var o,r,s;return["PUT","POST","DELETE"].includes(n.method)?W('{"status": "acknowledged"}',{contentType:"application/json; charset=utf-8",onOutboundWrite:e=>{let o={};try{o=JSON.parse(e.toString("ascii"))}catch(e){}if("object"!=typeof o||Object.keys(o).filter((e=>!["strictMock","mode","mocks"].includes(e))).length||!Array.isArray(o.mocks)&&void 0!==o.mocks)return void t.log("invalid mocks update received",m.WARNING,f.MOCKS);const{mocks:r,mode:s,strictMock:i}=o,a=new Map(r.map((({response:e,uniqueHash:t})=>[_(t),e]))),c=s!==t.mode&&s===g.PROXY,l=s!==t.mode&&s===g.MOCK||t.mocks.size!==a.size,d=!!i!=!!t.strictMock,u="DELETE"===n.method;c&&t.log(`${Object.keys(t.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,f.RULES),l&&t.log(`${(null!=a?a:t.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,f.MOCKS),d&&t.log(`mocks strict mode : ${null!=i?i:t.strictMock}`,m.INFO,f.MOCKS),V(t,u?{strictMock:i,mode:s,mocks:new Map}:{strictMock:i,mode:s,mocks:null!=a?a:t.mocks}),(c||l||d||u)&&t.quickStatus()}}):W(`${q(9210,"recorder","")}\n<span>Mode : </span>\n<div class="btn-group" role="group" aria-label="Server Mode">\n<input type="radio" class="btn-check" name="server-mode" id="record-mode" autocomplete="off"${t.mode===g.PROXY?" checked":""}>\n<label class="btn btn-outline-primary" for="record-mode">⏺ Record</label>\n<input type="radio" class="btn-check" name="server-mode" id="mock-mode" autocomplete="off"${t.mode===g.MOCK?" checked":""}>\n<label class="btn btn-outline-primary" for="mock-mode">🌐 Mock</label>\n</div>\n<span>Actions : </span>\n<button type="button" class="btn btn-light" id="upload-mocks">📥 Upload mocks</button>\n<button type="button" class="btn btn-light" id="download-mocks">📦 Download mocks</button>\n<button type="button" class="btn btn-light" id="delete-mocks">🗑 Delete mocks</button>\n<div class="form-check form-switch">\n<input class="form-check-input" type="checkbox" id="strict-mock-mode"${t.strictMock?" checked":""}>\n<label class="form-check-label" for="strict-mock-mode">Strict mock mode</label>\n</div>\n<input type="hidden" id="limit" value="0"/>\n<script>\nfunction getMocksData () {\nreturn JSON.stringify(\n[...document.querySelectorAll('button[data-uniqueHash]')].map(button => ({\nresponse: button.attributes['data-response']?.value,\nuniqueHash: button.attributes['data-uniqueHash']?.value}))\n)\n}\nfunction updateState () {\nfetch("http${t.config.ssl?"s":""}://${e}${null!==(s=null===(r=Object.entries(null!==(o=t.config.mapping)&&void 0!==o?o:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===r?void 0:r[0])&&void 0!==s?s:"/recorder/"}", {\nmethod: 'PUT',\nheaders: { 'Content-Type': 'application/json' },\nbody: '{"strictMock":' + document.getElementById('strict-mock-mode').checked +\n',"mode":"' + \n(document.getElementById('mock-mode').checked ? "mock" : "proxy") + '"' +\n',"mocks":' + getMocksData() + '}'\n})\n}\nfunction loadMocks(mocksHashes) {\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nlet mocks = [];\ntry {\nmocks = mocksHashes.map(mock => ({...mock, \nrequest: JSON.parse(atob(mock.uniqueHash)),\nresponse: JSON.parse(atob(mock.response))\n}));\n} catch(e) { }\nmocks.forEach(mock => {\nconst randomId = window.crypto.randomUUID();\nconst remove = '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">❌</button>';\nconst replay = mock.uniqueHash ? '<button data-response="' + \nbtoa(JSON.stringify(mock.response ?? {})) +\n'" data-uniquehash="' + mock.uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary">🔁</button>' : '';\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + randomId + '">' +\n'<td scope="col" class="replay">' + replay + remove + '</td>' +\n'<td scope="col">' + time + '</td>' +\n'<td scope="col">info</td>' + \n'<td scope="col" class="protocol">HTTP/2</td>' + \n'<td scope="col">' + mock.request.method + '</td>' + \n'<td scope="col" class="statusCode"><span class="badge bg-' + \ngetColorFromStatusCode(mock.response.status) + '">' + mock.response.status + '</span></td>' +\n'<td scope="col" class="duration">0ms</td>' +\n'<td scope="col">' + mock.request.url + '</td>' + \n'<td scope="col">N/A</td>' + \n'</tr>');\n});\n}\ndocument.getElementById('upload-mocks').addEventListener('click', () => {\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst fileInput = document.createElement('input');\nfileInput.type = "file";\nfileInput.multiple = "multiple";\nfileInput.onchange = function() {\nconst fileReader = new FileReader();\n[...fileInput.files].reduce((promise, file) =>\npromise.then(result => new Promise(resolve => {\nfileReader.readAsText(file);\nfileReader.onload = function(){\nresolve(result.concat(fileReader.result));\n};\n})), Promise.resolve([]))\n.then(files => files.flatMap(file => JSON.parse(file)))\n.catch(e => [])\n.then(mocks => loadMocks(mocks))\n.then(() => updateState());\n}\nfileInput.click();\n});\ndocument.getElementById('download-mocks').addEventListener('click', () => {\nconst link = document.createElement('a');\nlink.href = URL.createObjectURL(new Blob([getMocksData()], {\ntype: "application/json",\n}));\nlink.download = "mocks-" + new Date().toISOString() + ".json";\nlink.click();\nURL.revokeObjectURL(link.href);\n})\ndocument.getElementById('delete-mocks').addEventListener('click', () => {\ndocument.getElementById('limit').value = -1;\ncleanup();\nupdateState();\ndocument.getElementById('limit').value = 0;\n})\ndocument.getElementById('record-mode').addEventListener('change', () => {\ndocument.getElementById('limit').value = 0;\ncleanup();\nupdateState();\n})\ndocument.getElementById('mock-mode').addEventListener('change', () => {\nupdateState();\n})\ndocument.getElementById('strict-mock-mode').addEventListener('change', (e) => { \nupdateState();\n})\nsetTimeout(() => {\nloadMocks(${JSON.stringify([...t.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t}))))});\nupdateState();\n}, 10)\n<\/script>\n${N(e,t.config,{captureResponseBody:!0})}\n</body></html>`)}},I=Object.keys(j),T=I.map((e=>`${e}:`)),C={mapping:Object.assign({},...I.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},U=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(y,((n,o)=>{n&&!e&&k(null,"config error. Using default value",m.ERROR,f.ERROR_1);let r=null;try{r=Object.assign({},C,JSON.parse((o||"{}").toString()))}catch(e){return k({config:r},"config syntax incorrect, aborting",m.ERROR,f.ERROR_2),r=null!=r?r:Object.assign({},C),void t(r)}r.mapping[""]||k({config:r},'default mapping "" not provided.',m.WARNING,f.ERROR_3),n&&"ENOENT"===n.code&&e&&y===v?(0,a.writeFile)(y,JSON.stringify(C,null,2),(e=>{e?k(null,"config file NOT created",m.ERROR,f.ERROR_4):k(null,"config file created",m.INFO,f.COLORED),t(r)})):t(r)}))))}));exports.load=U;const H=e=>""==e?"":(0,l.normalize)(e).replace(/\\/g,"/"),P="https://cdn.jsdelivr.net/npm/",M=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],q=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="${P}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${P}jquery/dist/jquery.min.js"><\/script>\n<script src="${P}bootstrap/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,D=({response:e})=>({error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((t=>{try{this.data=JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}catch(e){this.data={}}t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{var t;"response"===e&&this.events.response(Object.assign(Object.assign({},this.data.headers),{"X-LocalTraffic-Mock":"1"}),this.data.status),"data"===e&&this.data&&(this.events.data(Buffer.from(null!==(t=this.data.body)&&void 0!==t?t:"","base64")),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}),A=e=>{const t=(0,l.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,a.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,a.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,a.lstat)((0,l.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${q(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}},W=(e,t)=>({error:null,data:null,outboundData:null,run:function(){return new Promise((t=>{this.data=e,t(void 0)}))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{var n;"response"===e&&this.events.response({Server:"local","Content-Type":null!==(n=null==t?void 0:t.contentType)&&void 0!==n?n:"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},write:function(e){return this.outboundData=e,e instanceof Buffer&&(null==t||t.onOutboundWrite(e)),this},end:function(){return this},request:function(){return this}}),F=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?c.gunzip:"deflate"===t?c.inflate:"br"===t?c.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\xFF]/.test(e.toString()))?J(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.port}&pathname=${encodeURIComponent(o.key.replace(/\/+$/,""))}`):e})).then((e=>{var t,o;return(null!==(o=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==o?o:"").split(",").reverse().reduce(((e,t)=>{const n=t.trim().toLowerCase(),o="gzip"===n||"x-gzip"===n?c.gzip:"deflate"===n?c.deflate:"br"===n?c.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>o(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))}));exports.replaceBody=F;const J=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>T.some((e=>s.startsWith(e)))||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(s.replace(new RegExp(`^(file|${I.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=J;const _=e=>{try{const t=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));return["authorization","cache-control","date","proxy-authenticate","proxy-authorization","expires","last-modified","if-modified-since","if-unmodified-since","keep-alive","cookie","access-control-max-age","retry-after","signed-headers","server-timing","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform","user-agent","sec-fetch-site","referer"].forEach((e=>{var n;null===(n=null==t?void 0:t.headers)||void 0===n||delete n[e]})),t.headers=Object.keys(t.headers).sort().reduce(((e,n)=>(e[n]=t.headers[n],e)),{}),Buffer.from(JSON.stringify(t),"utf-8").toString("base64")}catch(t){return e}};exports.cleanEntropy=_;const K=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=K;const z=(e,t)=>{var n,o,r,s,a;const c=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),l=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(s=t.port)&&void 0!==s?s:8080}`:""}`,d=new i.URL(`http${t.ssl?"s":""}://${l}${e.url}`),u=d.href.substring(d.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(H("string"==typeof t?t:t.downstreamUrl))}))))),[m,f]=null!==(a=Object.entries(p).find((([e])=>u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:c,proxyHostnameAndPort:l,url:d,path:u,key:m,target:f}};exports.determineMapping=z;const G=function(e,t,n){var o,a,c,l;if(n.on("error",(()=>{e.log("websocket connection reset",m.WARNING,f.WEBSOCKET)})),!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:d,target:u,path:p,url:h}=z(t,e.config);if(p.startsWith("/local-traffic-logs"))return S(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(o=t.headers["user-agent"])||void 0===o?void 0:o.toString())&&void 0!==a?a:"").includes("Chrome"),wantsResponseMessage:[...h.searchParams.entries()].some((([e,t])=>"wantsResponseMessage"===e&&"true"===t))})};if("/local-traffic-config"===p){S(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=R(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",m.WARNING,f.ERROR_4)}V(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(l=null===(c=t.headers["user-agent"])||void 0===c?void 0:c.toString())&&void 0!==l?l:"").includes("Chrome")})}}const g=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),v={hostname:g.hostname,path:g.pathname,port:g.port,protocol:g.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:g.hostname},y="https:"===g.protocol?(0,s.request)(v):(0,r.request)(v);y.end(),y.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,f.WEBSOCKET)})),y.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,f.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,f.WEBSOCKET)}))}))};exports.websocketServe=G;const Y=function(e,n,a){var c,l,u,p,v;return t(this,void 0,void 0,(function*(){if(!n.headers.host&&!n.headers[":authority"])return void K(400,a,Buffer.from(B(new Error("client must supply a 'host' header"),e.mode,"proxy",new i.URL(`http${e.config.ssl?"s":""}://unknowndomain${n.url}`))));const{proxyHostname:t,proxyHostnameAndPort:O,url:k,path:w,key:R,target:S}=z(n,e.config);if(!S)return void K(502,a,Buffer.from(B(new Error(`No mapping found in config file ${y}`),e.mode,"proxy",k)));const E=S.host.replace(RegExp(/\/+$/),""),$=`${S.href.substring(8+S.host.length)}${H(w.replace(RegExp(H(R)),""))}`.replace(/^\/*/,"/"),x=new i.URL(`${S.protocol}//${E}${$}`),L=T.some((e=>S.protocol===e));let N=null,I=!e.config.dontUseHttp2Downstream;const C=I&&!L&&"file:"!==S.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(x,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:S.protocol},((e,o)=>{I=I&&!!o.alpnProtocol,t(I?n:null)}));n.on("error",(t=>{N=I&&Buffer.from(B(t,e.mode,"connection",k,x))}))})),new Promise((t=>setTimeout((()=>{I=!1,t(null)}),e.config.connectTimeout)))])),U=(0,d.randomBytes)(20).toString("hex");let P=null;const q=e.config.replaceRequestBodyUrls||e.logsListeners.length,W=null==n?void 0:n.readableLength,G=null===(c=null==n?void 0:n.stream)||void 0===c?void 0:c.readableLength,Y=!((e.config.ssl&&0===G||!e.config.ssl&&0===W)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(q){const o=null!==(l=null==n?void 0:n.stream)&&void 0!==l?l:n;let r=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{Y?(o.on("data",(e=>{r=Buffer.concat([r,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),Y&&!r.length&&e.log(`body replacement error ${w.slice(-17)}`,m.WARNING,f.ERROR_4),P=e.config.replaceRequestBodyUrls?yield F(r,n.headers,{proxyHostnameAndPort:O,proxyHostname:t,key:R,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):r}const X=Buffer.from(JSON.stringify({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==P?void 0:P.toJSON()})).toString("base64"),Z="file:"===S.protocol;e.notifyLogsListeners({level:"info",protocol:I?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:w,downstreamPath:x.href,randomId:U,uniqueHash:X});const V=e.mode===g.MOCK?_(X):"",Q=e.mode===g.MOCK&&(!L||Z),ee=e.mocks.get(V);if(Q&&!ee&&e.strictMock)return void K(502,a,Buffer.from(B(new Error("No corresponding mock found in the server. \nTry switching back to the proxy mode"),e.mode,"mock",k)));const te=b(),ne=Q&&ee?D({response:ee}):Z?A(x):L?j[S.protocol.replace(/:$/,"")](O,e,n):I?C:null;N instanceof Buffer||(N=null);const oe=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!M.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(k.hostname,E))).join(", "),e)),{})),{origin:S.href,referer:x.toString(),"content-length":null!==(p=null!==(u=null==P?void 0:P.length)&&void 0!==u?u:n.headers["content-length"])&&void 0!==p?p:0,":authority":E,":method":n.method,":path":$,":scheme":S.protocol.replace(":","")}),re=ne&&!N&&ne.request(oe,{endStream:e.config.ssl?!(null==G||G):!W});"object"==typeof re&&(null==re||re.on("error",(t=>{const n=-505===t.errno;N=Buffer.from(B(t,e.mode,"stream"+(n?" (error -505 usually means that the downstream service does not support this http version)":""),k,x))})));const se={hostname:S.hostname,path:$,port:S.port,protocol:S.protocol,rejectUnauthorized:!1,method:n.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(oe).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:S.hostname})},ie=!N&&!I&&!["file:",...T].includes(S.protocol)&&(yield new Promise((t=>{const o="https:"===S.protocol?(0,s.request)(se,t):(0,r.request)(se,t);o.on("error",(n=>{N=Buffer.from(B(n,e.mode,"request",k,x)),t(null)})),q&&(o.write(P),o.end()),q||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(N)return void K(502,a,N);N=null,G&&re&&!q?(n.stream.on("data",(e=>{re.write(e)})),n.stream.on("end",(()=>re.end()))):W&&re&&!q?(n.on("data",(e=>{re.write(e)})),n.on("end",(()=>re.end()))):re&&q&&Y&&(re.write(P),re.end());const{outboundResponseHeaders:ae}=yield new Promise((e=>re?re.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!re&&ie?{outboundResponseHeaders:ie.headers}:{outboundResponseHeaders:{}})));let ce=null;try{ae.location&&(ce=new i.URL(ae.location.startsWith("/")?`${S.origin}${ae.location.replace(/^\/+/,"/")}`:ae.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(v=ae.location)&&void 0!==v?v:"").slice(-13)}`,m.WARNING,f.ERROR_4)}const le=e.config.replaceResponseBodyUrls&&ce?new i.URL(J(ce.href,{direction:h.INBOUND,proxyHostnameAndPort:O,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${T.join("|")}|file:)/+`),"")):ce,de=ce?le.origin!==ce.origin||e.config.dontTranslateLocationHeader?le:`${k.origin}${le.href.substring(le.origin.length)}`:ce,ue=re||ie,pe=null!=N?N:yield new Promise((e=>{let t=Buffer.alloc(0);ue?(ue.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),ue.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?T.some((e=>S.protocol===e))?n:F(n,ae,{proxyHostnameAndPort:O,proxyHostname:t,key:R,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((t=>(K(502,a,Buffer.from(B(t,e.mode,"stream",k,x))),Buffer.from("")))):n)),me=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},ae),e.config.replaceResponseBodyUrls?{"content-length":`${pe.byteLength}`}:{}),e.config.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&!M.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=E.split("").map(((e,t)=>E.substring(t).startsWith(".")&&E.substring(t))).filter((e=>e)),r=[E].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${k.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),de?{location:[de]}:{});try{Object.entries(me).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const fe=ae[":status"]||ie.statusCode||200;try{a.writeHead(fe,e.config.ssl?void 0:ie.statusMessage||"Status read from http/2",me)}catch(e){}pe?a.end(pe):a.end();const he=b();e.notifyLogsListeners({randomId:U,statusCode:fe,protocol:I?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(he-te)/1e6),uniqueHash:X,response:e.logsListeners.some((e=>e.wantsResponseMessage))?{body:pe.toString("base64"),headers:ae,status:fe}:{}})}))};exports.serve=Y;const X=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",m.ERROR,f.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",m.ERROR,f.ERROR_6)};exports.errorListener=X;const Z=e=>V({config:Object.assign(Object.assign({},C),e)},{});exports.start=Z;const V=(e,n)=>t(void 0,void 0,void 0,(function*(){var s,i,c,l,d,u,p,h,v,b,O,w,R,S,x;if(0===Object.keys(null!=n?n:{}).length&&e.server)return;if(n.pendingConfigSave)return void(0,a.writeFile)(y,JSON.stringify(n.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",m.ERROR,f.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",m.INFO,f.COLORED)}));if(null===n.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===n.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===n.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",m.WARNING,f.RESTART)}(null!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(i=e.logsListeners)&&void 0!==i?i:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const B=null!==(c=n.config)&&void 0!==c?c:e.config,N=null!==(d=null!==(l=n.mode)&&void 0!==l?l:e.mode)&&void 0!==d?d:g.PROXY,j=null!==(p=null!==(u=n.strictMock)&&void 0!==u?u:e.strictMock)&&void 0!==p&&p,I=null!==(v=null!==(h=n.mocks)&&void 0!==h?h:e.mocks)&&void 0!==v?v:new Map,T=(null===n.configListeners?[]:null!==(O=null!==(b=n.configListeners)&&void 0!==b?b:e.configListeners)&&void 0!==O?O:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),C=(null===n.logsListeners?[]:null!==(R=null!==(w=n.logsListeners)&&void 0!==w?w:e.logsListeners)&&void 0!==R?R:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),H=e;return Object.assign(H,{config:B,logsListeners:C,configListeners:T,mode:N,mocks:I,strictMock:j,configFileWatcher:void 0===H.configFileWatcher?(0,a.watchFile)(y,(()=>t(void 0,void 0,void 0,(function*(){return V(H,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield U(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",m.ERROR,f.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",m.ERROR,f.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,m.INFO,f.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,m.INFO,f.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,m.INFO,f.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,m.INFO,f.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,m.INFO,f.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,m.INFO,f.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),m.INFO,f.COLORED),Object.keys(n.mapping).join("\n")!==Object.keys(t.mapping).join("\n")&&e.log(`${Object.keys(n.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,f.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,m.INFO,f.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",m.INFO,f.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",m.INFO,f.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",m.INFO,f.RESTART),L.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(L.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(H))})))):H.configFileWatcher,log:k.bind(H,H),notifyConfigListeners:E.bind(H),notifyLogsListeners:$.bind(H),quickStatus:L.bind(H),server:null!==n.server&&H.server||(null!==(x=null===(S=n.config)||void 0===S?void 0:S.port)&&void 0!==x?x:0)<0?null===n.server?null:H.server:(B.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},B.ssl),{allowHTTP1:!0})):r.createServer)(((e,t)=>Y(H,e,t))).addListener("error",(e=>X(H,e))).addListener("listening",(()=>H.quickStatus())).on("upgrade",((e,t)=>V(H,G(H,e,t)))).listen(B.port)}),H}));exports.update=V;const Q=null!==(e=u.argv.map((e=>e.trim())).filter((e=>e&&!["ts-node","node","npx","npm","exec"].some((t=>e.includes(t)&&!e.match(/npm-cache/)&&!e.match(/_npx/)))))[0])&&void 0!==e?e:"",ee=Q.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!Q.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),te=u.argv.some((e=>"--crash-test"===e));if(te){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,r.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();V({config:Object.assign(Object.assign({},C),{port:e}),configFileWatcher:null},{}).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,response:t})=>200!==t.statusCode?Promise.reject("Crash test has failed"):V(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):k(e,"Crash test successful",m.INFO,f.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!te&&ee&&U().then(Z);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-traffic",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.80",
|
|
4
4
|
"main": "./dist/local-traffic.js",
|
|
5
5
|
"private": false,
|
|
6
6
|
"keywords": [
|
|
@@ -27,9 +27,9 @@
|
|
|
27
27
|
"test": "node ./test/tests.spec.mjs"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@types/node": "^20.
|
|
31
|
-
"terser": "^5.
|
|
32
|
-
"typescript": "^5.
|
|
30
|
+
"@types/node": "^20.5.9",
|
|
31
|
+
"terser": "^5.19.4",
|
|
32
|
+
"typescript": "^5.2.2"
|
|
33
33
|
},
|
|
34
34
|
"bin": {
|
|
35
35
|
"local-traffic": "./dist/local-traffic.js"
|