local-traffic 0.0.82 → 0.0.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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(s,r){function i(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(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())}))},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 s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(n[o[s]]=e[o[s]])}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"),s=require("http"),r=require("https"),i=require("url"),a=require("fs"),l=require("zlib"),d=require("path"),c=require("crypto"),u=require("process"),p=require("os");var m,g,h,f;!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="☠️ "}(g||(g={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={})),function(e){e.PROXY="proxy",e.MOCK="mock"}(f||(f={}));const b=(0,d.resolve)((0,p.homedir)(),".local-traffic.json"),y=(0,d.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:b),v=()=>{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",w=function(e,t,n,o){var s,r,i,a,l;const d=(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.simpleLogs)||(null===(r=null==e?void 0:e.logsListeners)||void 0===r?void 0:r.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?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(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)?d:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:d,level:O(n)})},R=(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])),s=e.length,r=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,r+s]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|r]).buffer),Buffer.from(Uint8Array.from([s>>8]).buffer),Buffer.from(Uint8Array.from([255&s]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|r]).buffer),Buffer.concat(Number(s).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),l=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,l]:[i,l])};exports.createWebsocketBufferFrom=R;const k=(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),s=o>>7,r=127&o,i=t?t.payloadLength:127!==r?r:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:s?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:s?8:4,d=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(d)}};exports.readWebsocketBuffer=k;const E=(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=E;const S=function(e){return q(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([q(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),q(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},q=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),s=o.has(!1)&&R(n,!1),r=o.has(!0)&&R(n,!0),i=e=>{e.stream.errored&&e.stream.destroy()};t.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(r,"ascii",(()=>i(e))):e.stream.write(s,"ascii",(()=>i(e))))}))},x=function(){this.log(`⎸${g.PORT} ${this.config.port.toString().padStart(5)} ⎸${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:" "}⎹⎸${this.mode===f.PROXY?`${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${g.MOCKS}${this.mocks.size.toString().padStart(3)}`}⎹⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=x;const B=(e,t,n,o,s)=>`${U(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&#x24D8;&nbsp;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>${s||"&lt;no-target-url&gt;"}</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: 120px"':""}>...</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://') &&\n!data?.upstreamPath?.endsWith('?forceLogInRecorderPage=true'))\nreturn;\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst actions = getActionsHtmlText(uniqueHash, data.response);\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 = actions;\n}\n} else if (uniqueHash) {\naddNewRequest(data.randomId, actions, time, data.level, data.protocol, data.method, \n'<span class="badge bg-secondary">...</span>', '&#x23F1;',\ndata.upstreamPath, data.downstreamPath);\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 || !body.length ? undefined : atob(body)\n});\n}\nfunction getActionsHtmlText(uniqueHash, response) {\nconst edit = ${!0===n.captureResponseBody} && uniqueHash\n? '<button data-response="' + btoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + \n'" data-bs-toggle="modal" data-bs-target="#edit-request" type="button" ' +\n'class="btn btn-primary">&#x1F4DD;</button>'\n: ''\nconst remove = ${!0===n.captureResponseBody} && uniqueHash\n? '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">&#x274C;</button>'\n: ''\nconst replay = ${!1===n.captureResponseBody} && uniqueHash ? '<button data-response="' + \nbtoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary">&#x1F501;</button>' : '';\nreturn edit + replay + remove\n}\nfunction addNewRequest(\nrandomId, actions, time, level, protocol, method, \nstatusCode, duration, upstreamPath, downstreamPath\n) {\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + randomId + '">' +\n'<td scope="col" class="replay">' + actions + '</td>' +\n'<td scope="col">' + time + '</td>' +\n'<td scope="col">' + (level || 'info')+ '</td>' + \n'<td scope="col" class="protocol">' + protocol + '</td>' + \n'<td scope="col" class="method">' + method + '</td>' + \n'<td scope="col" class="statusCode">' + statusCode + '</td>' +\n'<td scope="col" class="duration text-end">' + duration + '</td>' +\n'<td scope="col" class="upstream-path">' + upstreamPath + '</td>' + \n'<td scope="col">' + downstreamPath + '</td>' + \n'</tr>');\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>`,L={logs:(e,t)=>D(`${U(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)=>D(`${U(127899,"config","")}\n<link href="${T}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${T}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${T}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({},P),{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="&#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${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,s,r,i,a,l;return["PUT","POST","DELETE"].includes(n.method)?D('{"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,g.MOCKS);const{mocks:s,mode:r,strictMock:i}=o,a=s?new Map(s.map((({response:e,uniqueHash:t})=>[_(t),e]))):null,l=r!==t.mode&&r===f.PROXY,d=r!==t.mode&&r===f.MOCK||null!==a&&t.mocks.size!==a.size,c=!!i!=!!t.strictMock,u="DELETE"===n.method;l&&t.log(`${Object.keys(t.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),d&&t.log(`${(null!=a?a:t.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,g.MOCKS),c&&t.log(`mocks strict mode : ${null!=i?i:t.strictMock}`,m.INFO,g.MOCKS),V(t,u?{strictMock:i,mode:r,mocks:new Map}:{strictMock:i,mode:r,mocks:null!=a?a:t.mocks}),(l||d||c||u)&&t.quickStatus()}}):D(`${U(9210,"recorder","")}\n<link href="${T}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${T}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${T}pako/dist/pako.min.js"><\/script>\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===f.PROXY?" checked":""}>\n<label class="btn btn-outline-primary" for="record-mode">&#9210; Record</label>\n<input type="radio" class="btn-check" name="server-mode" id="mock-mode" autocomplete="off"${t.mode===f.MOCK?" checked":""}>\n<label class="btn btn-outline-primary" for="mock-mode">&#x1F310; Mock</label>\n</div>\n<span>Actions : </span>\n<button type="button" class="btn btn-light" id="add-mock">&#x2795; Mock from dummy request</button>\n<button type="button" class="btn btn-light" id="upload-mocks">&#x1F4E5; Upload mocks</button>\n<button type="button" class="btn btn-light" id="download-mocks">&#x1F4E6; Download mocks</button>\n<button type="button" class="btn btn-light" id="delete-mocks">&#x1F5D1; 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<div class="modal fade" id="edit-request" tabindex="-1" \naria-labelledby="edit-request-label" aria-hidden="true">\n<div class="modal-dialog" style="max-width: 900px">\n<div class="modal-content">\n<div class="modal-header">\n<h1 class="modal-title fs-5" id="edit-request-label">Edit request to /</h1>\n<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>\n</div>\n<div class="modal-body">\n<div class="container">\n<div class="row">\n<div class="col-lg">\n<h2>Request :</h2>\n<div id="uniqueHash-editor" style="width: 400px; height: 400px;"></div>\n</div>\n<div class="col-lg">\n<h2>Response : </h2>\n<div id="response-editor" style="width: 400px; height: 400px;"></div>\n</div>\n</div>\n</div>\n</div>\n<div class="modal-footer">\n<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>\n<button type="button" class="btn btn-primary" onclick="javascript:saveRequest()">Save changes</button>\n</div>\n</div>\n</div>\n</div>\n<script>\nconst xmlOrJsonPrologsInBase64 = [\n"eyJ","PD94bWw=","PCFET0NUWVBF","PCFkb2N0eXBl","PGh0bWw","PEhUTUw","H4sIAAAAAAAAA", "W3tc"\n];\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!==(r=null===(s=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===s?void 0:s[0])&&void 0!==r?r:"/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 actions = getActionsHtmlText(mock.uniqueHash, mock.response);\naddNewRequest(randomId, actions, time, 'info', 'HTTP/2', mock.request.method, \n'<span class="badge bg-' + \ngetColorFromStatusCode(mock.response.status) + '">' + \nmock.response.status + \n'</span>', \n'0ms', mock.request.url, \n'N/A');\n});\n}\ndocument.getElementById('add-mock').addEventListener('click', () => {\nconst iframe = document.createElement('iframe');\niframe.style.display = 'none';\niframe.onload = function() { i.parentNode.removeChild(i); };\niframe.src = "http${t.config.ssl?"s":""}://${e}${null!==(l=null===(a=Object.entries(null!==(i=t.config.mapping)&&void 0!==i?i:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===a?void 0:a[0])&&void 0!==l?l:"/recorder/"}?forceLogInRecorderPage=true";\ndocument.body.appendChild(iframe);\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})\nfunction saveRequest () {\n$('#edit-request').modal("hide");\n\nconst requestBeingEdited = window.requestBeingEdited;\nlet request = uniqueHashEditor.get();\nlet response = responseEditor.get();\nif (typeof request.body === "object") {\nrequest.body = JSON.stringify(request.body);\n}\nif (typeof response.body === "object") {\nresponse.body = JSON.stringify(response.body);\n}\nconst oldRequest = JSON.parse(atob(requestBeingEdited.attributes['data-uniqueHash'].value));\nconst oldResponse = JSON.parse(atob(requestBeingEdited.attributes['data-response'].value));\nconst requestProlog = requestBeingEdited.attributes['data-requestProlog']?.value;\nconst responseProlog = requestBeingEdited.attributes['data-responseProlog']?.value;\nconst requestPrologHasChanged = request.body.substring(0, 10) !== oldRequest.body.substring(0, 10);\nconst responsePrologHasChanged = response.body.substring(0, 10) !== response.body.substring(0, 10);\nif (requestProlog === "H4sIAAAAAAAAA" && !requestPrologHasChanged) {\nrequest.body =\nbtoa([...pako.gzip(request.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((requestProlog === null || !request.body.startsWith(requestProlog ?? "")) && \nrequest.body.substring(0, 10) !== oldRequest.body.substring(0, 10)) {\nrequest.body = btoa(request.body);\n}\nif (responseProlog === "H4sIAAAAAAAAA" && !responsePrologHasChanged) {\nresponse.body =\nbtoa([...pako.gzip(response.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((responseProlog === null || !response.body.startsWith(responseProlog ?? "")) && \nresponse.body.substring(0, 10) !== oldResponse.body.substring(0, 10)) {\nresponse.body = btoa(response.body);\n}\nrequest = btoa(JSON.stringify(request));\nresponse = btoa(JSON.stringify(response));\nrequestBeingEdited.setAttribute('data-uniqueHash', request);\nrequestBeingEdited.setAttribute('data-response', response);\nconst row = requestBeingEdited.closest('tr');\nrow.querySelector("td.method").innerHTML = uniqueHashEditor.get().method;\nrow.querySelector("td.upstream-path").innerHTML = uniqueHashEditor.get().url;\nwindow.requestBeingEdited = undefined;\nupdateState();\n}\ndocument.getElementById('edit-request').addEventListener('show.bs.modal', event => {\nconst request = JSON.parse(atob(event.relatedTarget.attributes['data-uniqueHash'].value));\nconst response = JSON.parse(atob(event.relatedTarget.attributes['data-response'].value));\nconst requestProlog = xmlOrJsonPrologsInBase64.find(prolog => request.body?.startsWith(prolog));\nconst responseProlog = xmlOrJsonPrologsInBase64.find(prolog => response.body?.startsWith(prolog));\nif (requestProlog) {\nevent.relatedTarget.setAttribute('data-requestProlog', requestProlog);\nrequest.body = request.body.startsWith("H4sIAAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(request.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(request.body);\nrequest.body = request.body.startsWith("{\\"") || request.body.startsWith("[{\\"")\n? JSON.parse(request.body) : request.body;\n}\nif (responseProlog) {\nevent.relatedTarget.setAttribute('data-responseProlog', responseProlog);\nresponse.body = response.body.startsWith("H4sIAAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(response.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(response.body);\nresponse.body = response.body.startsWith("{\\"") || response.body.startsWith("[{\\"")\n? JSON.parse(response.body) : response.body;\n}\nwindow.requestBeingEdited = event.relatedTarget;\nwindow.uniqueHashEditor.set(request);\nwindow.responseEditor.set(response);\ndocument.getElementById('edit-request-label').innerText = "Edit request to " + request.url;\n})\n\nsetTimeout(() => {\nloadMocks(${JSON.stringify([...t.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t}))))});\nwindow.uniqueHashEditor = new JSONEditor(document.getElementById("uniqueHash-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nmethod: {type: "string"},\nurl: {type: "string"},\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\n},\nrequired: [],\nadditionalProperties: false\n}});\nwindow.responseEditor = new JSONEditor(document.getElementById("response-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\nstatus: {type: "integer"}\n},\nrequired: [],\nadditionalProperties: false\n}});\nupdateState();\n}, 10)\n<\/script>\n${N(e,t.config,{captureResponseBody:!0})}\n</body>\n</html>`)}},j=Object.keys(L),I=j.map((e=>`${e}:`)),P={mapping:Object.assign({},...j.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},C=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(y,((n,o)=>{n&&!e&&w(null,"config error. Using default value",m.ERROR,g.ERROR_1);let s=null;try{s=Object.assign({},P,JSON.parse((o||"{}").toString()))}catch(e){return w({config:s},"config syntax incorrect, aborting",m.ERROR,g.ERROR_2),s=null!=s?s:Object.assign({},P),void t(s)}s.mapping[""]||w({config:s},'default mapping "" not provided.',m.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&y===b?(0,a.writeFile)(y,JSON.stringify(P,null,2),(e=>{e?w(null,"config file NOT created",m.ERROR,g.ERROR_4):w(null,"config file created",m.INFO,g.COLORED),t(s)})):t(s)}))))}));exports.load=C;const A=e=>""==e?"":(0,d.normalize)(e).replace(/\\/g,"/"),T="https://cdn.jsdelivr.net/npm/",H=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],U=(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="${T}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${T}jquery/dist/jquery.min.js"><\/script>\n<script src="${T}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/>`,M=({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}}),W=e=>{const t=(0,d.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,s)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=s,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,d.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=`${U(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</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}}},D=(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 s,r;return(null!==(r=null===(s=n["content-encoding"])||void 0===s?void 0:s.toString())&&void 0!==r?r:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?l.gunzip:"deflate"===t?l.inflate:"br"===t?l.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const s=yield e;return yield new Promise(((e,t)=>o(s,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,s=["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&&(s||!/[^\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?l.gzip:"deflate"===n?l.deflate:"br"===n?l.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:s})=>Object.entries(s).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[s,r])=>I.some((e=>r.startsWith(e)))||""!==s&&!s.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(r.replace(new RegExp(`^(file|${j.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${s.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${s.replace(/\/+$/,"")}`).join(r)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=J;const _=e=>{try{const t="object"==typeof e?e: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-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","referer","upgrade-insecure-requests"].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,s,r,a;const l=(null!==(s=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==s?s:"localhost").replace(/:.*/,""),d=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(r=t.port)&&void 0!==r?r:8080}`:""}`,c=new i.URL(`http${t.ssl?"s":""}://${d}${e.url}`),u=c.href.substring(c.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(A("string"==typeof t?t:t.downstreamUrl))}))))),[m,g]=null!==(a=Object.entries(p).find((([e])=>u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:d,url:c,path:u,key:m,target:g}};exports.determineMapping=z;const G=function(e,t,n){var o,a,l,d;if(n.on("error",(()=>{e.log("websocket connection reset",m.WARNING,g.WEBSOCKET)})),!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:c,target:u,path:p,url:h}=z(t,e.config);if(p.startsWith("/local-traffic-logs"))return E(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){E(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=k(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,g.ERROR_4)}V(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(d=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==d?d:"").includes("Chrome")})}}const f=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${c}`,"g"),"").replace(/^\/*/,"/")}`),b={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},y="https:"===f.protocol?(0,r.request)(b):(0,s.request)(b);y.end(),y.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),y.on("upgrade",((t,o)=>{const s=`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(s),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,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=G;const Y=function(e,n,a){var l,d,u,p,b;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:w,path:R,key:k,target:E}=z(n,e.config);if(!E)return void K(502,a,Buffer.from(B(new Error(`No mapping found in config file ${y}`),e.mode,"proxy",w)));const S=E.host.replace(RegExp(/\/+$/),""),$=`${E.href.substring(8+E.host.length)}${A(R.replace(RegExp(A(k)),""))}`.replace(/^\/*/,"/"),q=new i.URL(`${E.protocol}//${S}${$}`),x=I.some((e=>E.protocol===e));let N=null,j=!e.config.dontUseHttp2Downstream;const P=j&&!x&&"file:"!==E.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(q,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:E.protocol},((e,o)=>{j=j&&!!o.alpnProtocol,t(j?n:null)}));n.on("error",(t=>{N=j&&Buffer.from(B(t,e.mode,"connection",w,q))}))})),new Promise((t=>setTimeout((()=>{j=!1,t(null)}),e.config.connectTimeout)))])),C=(0,c.randomBytes)(20).toString("hex");let T=null;const U=e.config.replaceRequestBodyUrls||e.logsListeners.length,D=null==n?void 0:n.readableLength,G=null===(l=null==n?void 0:n.stream)||void 0===l?void 0:l.readableLength,Y=!((e.config.ssl&&0===G||!e.config.ssl&&0===D)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(U){const o=null!==(d=null==n?void 0:n.stream)&&void 0!==d?d:n;let s=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{Y?(o.on("data",(e=>{s=Buffer.concat([s,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),Y&&!s.length&&e.log(`body replacement error ${R.slice(-17)}`,m.WARNING,g.ERROR_4),T=e.config.replaceRequestBodyUrls?yield F(s,n.headers,{proxyHostnameAndPort:O,proxyHostname:t,key:k,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):s}const X=_({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==T?void 0:T.toString("base64")}),Z="file:"===E.protocol;e.notifyLogsListeners({level:"info",protocol:j?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:R,downstreamPath:q.href,randomId:C,uniqueHash:X});const V=e.mode===f.MOCK?_(X):"",Q=e.mode===f.MOCK&&(!x||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",w)));const te=v(),ne=Q&&ee?M({response:ee}):Z?W(q):x?L[E.protocol.replace(/:$/,"")](O,e,n):j?P:null;N instanceof Buffer||(N=null);const oe=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!H.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(w.hostname,S))).join(", "),e)),{})),{origin:E.href,referer:q.toString(),"content-length":null!==(p=null!==(u=null==T?void 0:T.length)&&void 0!==u?u:n.headers["content-length"])&&void 0!==p?p:0,":authority":S,":method":n.method,":path":$,":scheme":E.protocol.replace(":","")}),se=ne&&!N&&ne.request(oe,{endStream:e.config.ssl?!(null==G||G):!D});"object"==typeof se&&(null==se||se.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)":""),w,q))})));const re={hostname:E.hostname,path:$,port:E.port,protocol:E.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:E.hostname})},ie=!N&&!j&&!["file:",...I].includes(E.protocol)&&(yield new Promise((t=>{const o="https:"===E.protocol?(0,r.request)(re,t):(0,s.request)(re,t);o.on("error",(n=>{N=Buffer.from(B(n,e.mode,"request",w,q)),t(null)})),U&&(o.write(T),o.end()),U||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(N)return void K(502,a,N);N=null,G&&se&&!U?(n.stream.on("data",(e=>{se.write(e)})),n.stream.on("end",(()=>se.end()))):D&&se&&!U?(n.on("data",(e=>{se.write(e)})),n.on("end",(()=>se.end()))):se&&U&&Y&&(se.write(T),se.end());const{outboundResponseHeaders:ae}=yield new Promise((e=>se?se.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!se&&ie?{outboundResponseHeaders:ie.headers}:{outboundResponseHeaders:{}})));let le=null;try{ae.location&&(le=new i.URL(ae.location.startsWith("/")?`${E.origin}${ae.location.replace(/^\/+/,"/")}`:ae.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=ae.location)&&void 0!==b?b:"").slice(-13)}`,m.WARNING,g.ERROR_4)}const de=e.config.replaceResponseBodyUrls&&le?new i.URL(J(le.href,{direction:h.INBOUND,proxyHostnameAndPort:O,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${I.join("|")}|file:)/+`),"")):le,ce=le?de.origin!==le.origin||e.config.dontTranslateLocationHeader?de:`${w.origin}${de.href.substring(de.origin.length)}`:le,ue=se||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?I.some((e=>E.protocol===e))?n:F(n,ae,{proxyHostnameAndPort:O,proxyHostname:t,key:k,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",w,q))),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(":")&&!H.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=S.split("").map(((e,t)=>S.substring(t).startsWith(".")&&S.substring(t))).filter((e=>e)),s=[S].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${w.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(s),e}),{})),ce?{location:[ce]}:{});try{Object.entries(me).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ge=ae[":status"]||ie.statusCode||200;try{a.writeHead(ge,e.config.ssl?void 0:ie.statusMessage||"Status read from http/2",me)}catch(e){}pe?a.end(pe):a.end();const he=v();e.notifyLogsListeners({randomId:C,statusCode:ge,protocol:j?"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:ge}:{}})}))};exports.serve=Y;const X=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",m.ERROR,g.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",m.ERROR,g.ERROR_6)};exports.errorListener=X;const Z=e=>V({config:Object.assign(Object.assign({},P),e)},{});exports.start=Z;const V=(e,n)=>t(void 0,void 0,void 0,(function*(){var r,i,l,d,c,u,p,h,b,v,O,R,k,E,q;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,g.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",m.INFO,g.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,g.RESTART)}(null!==(r=e.configListeners)&&void 0!==r?r:[]).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!==(l=n.config)&&void 0!==l?l:e.config,N=null!==(c=null!==(d=n.mode)&&void 0!==d?d:e.mode)&&void 0!==c?c:f.PROXY,L=null!==(p=null!==(u=n.strictMock)&&void 0!==u?u:e.strictMock)&&void 0!==p&&p,j=null!==(b=null!==(h=n.mocks)&&void 0!==h?h:e.mocks)&&void 0!==b?b:new Map,I=(null===n.configListeners?[]:null!==(O=null!==(v=n.configListeners)&&void 0!==v?v:e.configListeners)&&void 0!==O?O:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),P=(null===n.logsListeners?[]:null!==(k=null!==(R=n.logsListeners)&&void 0!==R?R:e.logsListeners)&&void 0!==k?k:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),A=e;return Object.assign(A,{config:B,logsListeners:P,configListeners:I,mode:N,mocks:j,strictMock:L,configFileWatcher:void 0===A.configFileWatcher?(0,a.watchFile)(y,(()=>t(void 0,void 0,void 0,(function*(){return V(A,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield C(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",m.ERROR,g.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",m.ERROR,g.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,m.INFO,g.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,m.INFO,g.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,m.INFO,g.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,m.INFO,g.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),m.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`,m.INFO,g.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,m.INFO,g.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",m.INFO,g.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",m.INFO,g.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",m.INFO,g.RESTART),x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(A))})))):A.configFileWatcher,log:w.bind(A,A),notifyConfigListeners:S.bind(A),notifyLogsListeners:$.bind(A),quickStatus:x.bind(A),server:null!==n.server&&A.server||(null!==(q=null===(E=n.config)||void 0===E?void 0:E.port)&&void 0!==q?q:0)<0?null===n.server?null:A.server:(B.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},B.ssl),{allowHTTP1:!0})):s.createServer)(((e,t)=>Y(A,e,t))).addListener("error",(e=>X(A,e))).addListener("listening",(()=>A.quickStatus())).on("upgrade",((e,t)=>V(A,G(A,e,t)))).listen(B.port)}),A}));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,s.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({},P),{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"):w(e,"Crash test successful",m.INFO,g.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!te&&ee&&C().then(Z);
2
+ "use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(s,r){function i(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(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())}))},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 s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(n[o[s]]=e[o[s]])}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"),s=require("http"),r=require("https"),i=require("url"),a=require("fs"),l=require("zlib"),d=require("path"),c=require("crypto"),u=require("process"),p=require("os");var m,g,h,f;!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="☠️ "}(g||(g={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={})),function(e){e.PROXY="proxy",e.MOCK="mock"}(f||(f={}));const b=(0,d.resolve)((0,p.homedir)(),".local-traffic.json"),y=(0,d.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:b),v=()=>{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",w=function(e,t,n,o){var s,r,i,a,l;const d=(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.simpleLogs)||(null===(r=null==e?void 0:e.logsListeners)||void 0===r?void 0:r.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?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(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)?d:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:d,level:O(n)})},R=(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])),s=e.length,r=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,r+s]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|r]).buffer),Buffer.from(Uint8Array.from([s>>8]).buffer),Buffer.from(Uint8Array.from([255&s]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|r]).buffer),Buffer.concat(Number(s).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),l=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,l]:[i,l])};exports.createWebsocketBufferFrom=R;const k=(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),s=o>>7,r=127&o,i=t?t.payloadLength:127!==r?r:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:s?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:s?8:4,d=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(d)}};exports.readWebsocketBuffer=k;const E=(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=E;const S=function(e){return q(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([q(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),q(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},q=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),s=o.has(!1)&&R(n,!1),r=o.has(!0)&&R(n,!0),i=e=>{e.stream.errored&&e.stream.destroy()};t.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(r,"ascii",(()=>i(e))):e.stream.write(s,"ascii",(()=>i(e))))}))},x=function(){this.log(`⎸${g.PORT} ${this.config.port.toString().padStart(5)} ⎸${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:" "}⎹⎸${this.mode===f.PROXY?`${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${g.MOCKS}${this.mocks.size.toString().padStart(3)}`}⎹⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=x;const B=(e,t,n,o,s)=>`${U(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&#x24D8;&nbsp;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>${s||"&lt;no-target-url&gt;"}</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: 120px"':""}>...</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://') &&\n!data?.upstreamPath?.endsWith('?forceLogInRecorderPage=true'))\nreturn;\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst actions = getActionsHtmlText(uniqueHash, data.response);\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 = actions;\n}\n} else if (uniqueHash) {\naddNewRequest(data.randomId, actions, time, data.level, data.protocol, data.method, \n'<span class="badge bg-secondary">...</span>', '&#x23F1;',\ndata.upstreamPath, data.downstreamPath);\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 || !body.length ? undefined : atob(body)\n});\n}\nfunction getActionsHtmlText(uniqueHash, response) {\nconst edit = ${!0===n.captureResponseBody} && uniqueHash\n? '<button data-response="' + btoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + \n'" data-bs-toggle="modal" data-bs-target="#edit-request" type="button" ' +\n'class="btn btn-primary">&#x1F4DD;</button>'\n: ''\nconst remove = ${!0===n.captureResponseBody} && uniqueHash\n? '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">&#x274C;</button>'\n: ''\nconst replay = ${!1===n.captureResponseBody} && uniqueHash ? '<button data-response="' + \nbtoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary">&#x1F501;</button>' : '';\nreturn edit + replay + remove\n}\nfunction addNewRequest(\nrandomId, actions, time, level, protocol, method, \nstatusCode, duration, upstreamPath, downstreamPath\n) {\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + randomId + '">' +\n'<td scope="col" class="replay">' + actions + '</td>' +\n'<td scope="col">' + time + '</td>' +\n'<td scope="col">' + (level || 'info')+ '</td>' + \n'<td scope="col" class="protocol">' + protocol + '</td>' + \n'<td scope="col" class="method">' + method + '</td>' + \n'<td scope="col" class="statusCode">' + statusCode + '</td>' +\n'<td scope="col" class="duration text-end">' + duration + '</td>' +\n'<td scope="col" class="upstream-path">' + upstreamPath + '</td>' + \n'<td scope="col">' + downstreamPath + '</td>' + \n'</tr>');\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>`,L={logs:(e,t)=>D(`${U(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)=>D(`${U(127899,"config","")}\n<link href="${A}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${A}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${A}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({},P),{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="&#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${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,s,r,i,a,l,d;return(null===(o=n.url)||void 0===o?void 0:o.endsWith("?forceLogInRecorderPage=true"))?D('{"ping":"pong"}',{contentType:"application/json; charset=utf-8"}):["PUT","POST","DELETE"].includes(n.method)?D('{"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,g.MOCKS);const{mocks:s,mode:r,strictMock:i}=o,a=s?new Map(s.map((({response:e,uniqueHash:t})=>[_(t),e]))):null,l=r!==t.mode&&r===f.PROXY,d=r!==t.mode&&r===f.MOCK||null!==a&&t.mocks.size!==a.size,c=!!i!=!!t.strictMock,u="DELETE"===n.method;l&&t.log(`${Object.keys(t.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),d&&t.log(`${(null!=a?a:t.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,g.MOCKS),c&&t.log(`mocks strict mode : ${null!=i?i:t.strictMock}`,m.INFO,g.MOCKS),V(t,u?{strictMock:i,mode:r,mocks:new Map}:{strictMock:i,mode:r,mocks:null!=a?a:t.mocks}),(l||d||c||u)&&t.quickStatus()}}):D(`${U(9210,"recorder","")}\n<link href="${A}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${A}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${A}pako/dist/pako.min.js"><\/script>\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===f.PROXY?" checked":""}>\n<label class="btn btn-outline-primary" for="record-mode">&#9210; Record</label>\n<input type="radio" class="btn-check" name="server-mode" id="mock-mode" autocomplete="off"${t.mode===f.MOCK?" checked":""}>\n<label class="btn btn-outline-primary" for="mock-mode">&#x1F310; Mock</label>\n</div>\n<span>Actions : </span>\n<button type="button" class="btn btn-light" id="add-mock">&#x2795; Mock from dummy request</button>\n<button type="button" class="btn btn-light" id="upload-mocks">&#x1F4E5; Upload mocks</button>\n<button type="button" class="btn btn-light" id="download-mocks">&#x1F4E6; Download mocks</button>\n<button type="button" class="btn btn-light" id="delete-mocks">&#x1F5D1; 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<div class="modal fade" id="edit-request" tabindex="-1" \naria-labelledby="edit-request-label" aria-hidden="true">\n<div class="modal-dialog" style="max-width: 900px">\n<div class="modal-content">\n<div class="modal-header">\n<h1 class="modal-title fs-5" id="edit-request-label">Edit request to /</h1>\n<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>\n</div>\n<div class="modal-body">\n<div class="container">\n<div class="row">\n<div class="col-lg">\n<h2>Request :</h2>\n<div id="uniqueHash-editor" style="width: 400px; height: 400px;"></div>\n</div>\n<div class="col-lg">\n<h2>Response : </h2>\n<div id="response-editor" style="width: 400px; height: 400px;"></div>\n</div>\n</div>\n</div>\n</div>\n<div class="modal-footer">\n<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>\n<button type="button" class="btn btn-primary" onclick="javascript:saveRequest()">Save changes</button>\n</div>\n</div>\n</div>\n</div>\n<script>\nconst xmlOrJsonPrologsInBase64 = [\n"eyJ","PD94bWw=","PCFET0NUWVBF","PCFkb2N0eXBl","PGh0bWw","PEhUTUw","H4sIAAAAAAAA", "W3tc"\n];\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!==(i=null===(r=Object.entries(null!==(s=t.config.mapping)&&void 0!==s?s:{}).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!==i?i:"/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 actions = getActionsHtmlText(mock.uniqueHash, mock.response);\naddNewRequest(randomId, actions, time, 'info', 'HTTP/2', mock.request.method, \n'<span class="badge bg-' + \ngetColorFromStatusCode(mock.response.status) + '">' + \nmock.response.status + \n'</span>', \n'0ms', mock.request.url, \n'N/A');\n});\n}\ndocument.getElementById('add-mock').addEventListener('click', () => {\nconst iframe = document.createElement('iframe');\niframe.style.display = 'none';\niframe.onload = function() { iframe.parentNode.removeChild(iframe); };\niframe.src = "http${t.config.ssl?"s":""}://${e}${null!==(d=null===(l=Object.entries(null!==(a=t.config.mapping)&&void 0!==a?a:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===l?void 0:l[0])&&void 0!==d?d:"/recorder/"}?forceLogInRecorderPage=true";\ndocument.body.appendChild(iframe);\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})\nfunction saveRequest () {\n$('#edit-request').modal("hide");\n\nconst requestBeingEdited = window.requestBeingEdited;\nlet request = uniqueHashEditor.get();\nlet response = responseEditor.get();\nif (typeof request.body === "object") {\nrequest.body = JSON.stringify(request.body);\n}\nif (typeof response.body === "object") {\nresponse.body = JSON.stringify(response.body);\n}\nconst oldRequest = JSON.parse(atob(requestBeingEdited.attributes['data-uniqueHash'].value));\nconst oldResponse = JSON.parse(atob(requestBeingEdited.attributes['data-response'].value));\nconst requestProlog = requestBeingEdited.attributes['data-requestProlog']?.value;\nconst responseProlog = requestBeingEdited.attributes['data-responseProlog']?.value;\nconst requestPrologHasChanged = request.body.substring(0, 10) !== oldRequest.body.substring(0, 10);\nconst responsePrologHasChanged = response.body.substring(0, 10) !== response.body.substring(0, 10);\nif (requestProlog === "H4sIAAAAAAAA" && !requestPrologHasChanged) {\nrequest.body =\nbtoa([...pako.gzip(request.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((requestProlog === null || !request.body.startsWith(requestProlog ?? "")) && \nrequest.body.substring(0, 10) !== oldRequest.body.substring(0, 10)) {\nrequest.body = btoa(request.body);\n}\nif (responseProlog === "H4sIAAAAAAAA" && !responsePrologHasChanged) {\nresponse.body =\nbtoa([...pako.gzip(response.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((responseProlog === null || !response.body.startsWith(responseProlog ?? "")) && \nresponse.body.substring(0, 10) !== oldResponse.body.substring(0, 10)) {\nresponse.body = btoa(response.body);\n}\nrequest = btoa(JSON.stringify(request));\nresponse = btoa(JSON.stringify(response));\nrequestBeingEdited.setAttribute('data-uniqueHash', request);\nrequestBeingEdited.setAttribute('data-response', response);\nconst row = requestBeingEdited.closest('tr');\nrow.querySelector("td.method").innerHTML = uniqueHashEditor.get().method;\nrow.querySelector("td.upstream-path").innerHTML = uniqueHashEditor.get().url;\nwindow.requestBeingEdited = undefined;\nupdateState();\n}\ndocument.getElementById('edit-request').addEventListener('show.bs.modal', event => {\nconst request = JSON.parse(atob(event.relatedTarget.attributes['data-uniqueHash'].value));\nconst response = JSON.parse(atob(event.relatedTarget.attributes['data-response'].value));\nconst requestProlog = xmlOrJsonPrologsInBase64.find(prolog => request.body?.startsWith(prolog));\nconst responseProlog = xmlOrJsonPrologsInBase64.find(prolog => response.body?.startsWith(prolog));\nif (requestProlog) {\nevent.relatedTarget.setAttribute('data-requestProlog', requestProlog);\nrequest.body = request.body.startsWith("H4sIAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(request.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(request.body);\nrequest.body = request.body.startsWith("{\\"") || request.body.startsWith("[{\\"")\n? JSON.parse(request.body) : request.body;\n}\nif (responseProlog) {\nevent.relatedTarget.setAttribute('data-responseProlog', responseProlog);\nresponse.body = response.body.startsWith("H4sIAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(response.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(response.body);\nresponse.body = response.body.startsWith("{\\"") || response.body.startsWith("[{\\"")\n? JSON.parse(response.body) : response.body;\n}\nwindow.requestBeingEdited = event.relatedTarget;\nwindow.uniqueHashEditor.set(request);\nwindow.responseEditor.set(response);\ndocument.getElementById('edit-request-label').innerText = "Edit request to " + request.url;\n})\n\nsetTimeout(() => {\nloadMocks(${JSON.stringify([...t.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t}))))});\nwindow.uniqueHashEditor = new JSONEditor(document.getElementById("uniqueHash-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nmethod: {type: "string"},\nurl: {type: "string"},\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\n},\nrequired: [],\nadditionalProperties: false\n}});\nwindow.responseEditor = new JSONEditor(document.getElementById("response-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\nstatus: {type: "integer"}\n},\nrequired: [],\nadditionalProperties: false\n}});\nupdateState();\n}, 10)\n<\/script>\n${N(e,t.config,{captureResponseBody:!0})}\n</body>\n</html>`)}},j=Object.keys(L),I=j.map((e=>`${e}:`)),P={mapping:Object.assign({},...j.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},C=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(y,((n,o)=>{n&&!e&&w(null,"config error. Using default value",m.ERROR,g.ERROR_1);let s=null;try{s=Object.assign({},P,JSON.parse((o||"{}").toString()))}catch(e){return w({config:s},"config syntax incorrect, aborting",m.ERROR,g.ERROR_2),s=null!=s?s:Object.assign({},P),void t(s)}s.mapping[""]||w({config:s},'default mapping "" not provided.',m.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&y===b?(0,a.writeFile)(y,JSON.stringify(P,null,2),(e=>{e?w(null,"config file NOT created",m.ERROR,g.ERROR_4):w(null,"config file created",m.INFO,g.COLORED),t(s)})):t(s)}))))}));exports.load=C;const T=e=>""==e?"":(0,d.normalize)(e).replace(/\\/g,"/"),A="https://cdn.jsdelivr.net/npm/",H=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],U=(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="${A}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${A}jquery/dist/jquery.min.js"><\/script>\n<script src="${A}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/>`,M=({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}}),W=e=>{const t=(0,d.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,s)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=s,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,d.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=`${U(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</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}}},D=(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 s,r;return(null!==(r=null===(s=n["content-encoding"])||void 0===s?void 0:s.toString())&&void 0!==r?r:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?l.gunzip:"deflate"===t?l.inflate:"br"===t?l.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const s=yield e;return yield new Promise(((e,t)=>o(s,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,s=["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&&(s||!/[^\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?l.gzip:"deflate"===n?l.deflate:"br"===n?l.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:s})=>Object.entries(s).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[s,r])=>I.some((e=>r.startsWith(e)))||""!==s&&!s.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(r.replace(new RegExp(`^(file|${j.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${s.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${s.replace(/\/+$/,"")}`).join(r)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=J;const _=e=>{try{const t="object"==typeof e?e: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-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","referer","upgrade-insecure-requests"].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,s,r,a;const l=(null!==(s=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==s?s:"localhost").replace(/:.*/,""),d=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(r=t.port)&&void 0!==r?r:8080}`:""}`,c=new i.URL(`http${t.ssl?"s":""}://${d}${e.url}`),u=c.href.substring(c.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(T("string"==typeof t?t:t.downstreamUrl))}))))),[m,g]=null!==(a=Object.entries(p).find((([e])=>u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:d,url:c,path:u,key:m,target:g}};exports.determineMapping=z;const G=function(e,t,n){var o,a,l,d;if(n.on("error",(()=>{e.log("websocket connection reset",m.WARNING,g.WEBSOCKET)})),!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:c,target:u,path:p,url:h}=z(t,e.config);if(p.startsWith("/local-traffic-logs"))return E(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){E(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=k(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,g.ERROR_4)}V(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(d=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==d?d:"").includes("Chrome")})}}const f=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${c}`,"g"),"").replace(/^\/*/,"/")}`),b={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},y="https:"===f.protocol?(0,r.request)(b):(0,s.request)(b);y.end(),y.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),y.on("upgrade",((t,o)=>{const s=`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(s),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,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=G;const Y=function(e,n,a){var l,d,u,p,b;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:w,path:R,key:k,target:E}=z(n,e.config);if(!E)return void K(502,a,Buffer.from(B(new Error(`No mapping found in config file ${y}`),e.mode,"proxy",w)));const S=E.host.replace(RegExp(/\/+$/),""),$=`${E.href.substring(8+E.host.length)}${T(R.replace(RegExp(T(k)),""))}`.replace(/^\/*/,"/"),q=new i.URL(`${E.protocol}//${S}${$}`),x=I.some((e=>E.protocol===e));let N=null,j=!e.config.dontUseHttp2Downstream;const P=j&&!x&&"file:"!==E.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(q,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:E.protocol},((e,o)=>{j=j&&!!o.alpnProtocol,t(j?n:null)}));n.on("error",(t=>{N=j&&Buffer.from(B(t,e.mode,"connection",w,q))}))})),new Promise((t=>setTimeout((()=>{j=!1,t(null)}),e.config.connectTimeout)))])),C=(0,c.randomBytes)(20).toString("hex");let A=null;const U=e.config.replaceRequestBodyUrls||e.logsListeners.length,D=null==n?void 0:n.readableLength,G=null===(l=null==n?void 0:n.stream)||void 0===l?void 0:l.readableLength,Y=!((e.config.ssl&&0===G||!e.config.ssl&&0===D)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(U){const o=null!==(d=null==n?void 0:n.stream)&&void 0!==d?d:n;let s=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{Y?(o.on("data",(e=>{s=Buffer.concat([s,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),Y&&!s.length&&e.log(`body replacement error ${R.slice(-17)}`,m.WARNING,g.ERROR_4),A=e.config.replaceRequestBodyUrls?yield F(s,n.headers,{proxyHostnameAndPort:O,proxyHostname:t,key:k,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):s}const X=_({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==A?void 0:A.toString("base64")}),Z="file:"===E.protocol;e.notifyLogsListeners({level:"info",protocol:j?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:R,downstreamPath:q.href,randomId:C,uniqueHash:X});const V=e.mode===f.MOCK?_(X):"",Q=e.mode===f.MOCK&&(!x||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",w)));const te=v(),ne=Q&&ee?M({response:ee}):Z?W(q):x?L[E.protocol.replace(/:$/,"")](O,e,n):j?P:null;N instanceof Buffer||(N=null);const oe=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!H.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(w.hostname,S))).join(", "),e)),{})),{origin:E.href,referer:q.toString(),"content-length":null!==(p=null!==(u=null==A?void 0:A.length)&&void 0!==u?u:n.headers["content-length"])&&void 0!==p?p:0,":authority":S,":method":n.method,":path":$,":scheme":E.protocol.replace(":","")}),se=ne&&!N&&ne.request(oe,{endStream:e.config.ssl?!(null==G||G):!D});"object"==typeof se&&(null==se||se.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)":""),w,q))})));const re={hostname:E.hostname,path:$,port:E.port,protocol:E.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:E.hostname})},ie=!N&&!j&&!["file:",...I].includes(E.protocol)&&(yield new Promise((t=>{const o="https:"===E.protocol?(0,r.request)(re,t):(0,s.request)(re,t);o.on("error",(n=>{N=Buffer.from(B(n,e.mode,"request",w,q)),t(null)})),U&&(o.write(A),o.end()),U||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(N)return void K(502,a,N);N=null,G&&se&&!U?(n.stream.on("data",(e=>{se.write(e)})),n.stream.on("end",(()=>se.end()))):D&&se&&!U?(n.on("data",(e=>{se.write(e)})),n.on("end",(()=>se.end()))):se&&U&&Y&&(se.write(A),se.end());const{outboundResponseHeaders:ae}=yield new Promise((e=>se?se.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!se&&ie?{outboundResponseHeaders:ie.headers}:{outboundResponseHeaders:{}})));let le=null;try{ae.location&&(le=new i.URL(ae.location.startsWith("/")?`${E.origin}${ae.location.replace(/^\/+/,"/")}`:ae.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=ae.location)&&void 0!==b?b:"").slice(-13)}`,m.WARNING,g.ERROR_4)}const de=e.config.replaceResponseBodyUrls&&le?new i.URL(J(le.href,{direction:h.INBOUND,proxyHostnameAndPort:O,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${I.join("|")}|file:)/+`),"")):le,ce=le?de.origin!==le.origin||e.config.dontTranslateLocationHeader?de:`${w.origin}${de.href.substring(de.origin.length)}`:le,ue=se||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?I.some((e=>E.protocol===e))?n:F(n,ae,{proxyHostnameAndPort:O,proxyHostname:t,key:k,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",w,q))),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(":")&&!H.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=S.split("").map(((e,t)=>S.substring(t).startsWith(".")&&S.substring(t))).filter((e=>e)),s=[S].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${w.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(s),e}),{})),ce?{location:[ce]}:{});try{Object.entries(me).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ge=ae[":status"]||ie.statusCode||200;try{a.writeHead(ge,e.config.ssl?void 0:ie.statusMessage||"Status read from http/2",me)}catch(e){}pe?a.end(pe):a.end();const he=v();e.notifyLogsListeners({randomId:C,statusCode:ge,protocol:j?"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:ge}:{}})}))};exports.serve=Y;const X=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",m.ERROR,g.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",m.ERROR,g.ERROR_6)};exports.errorListener=X;const Z=e=>V({config:Object.assign(Object.assign({},P),e)},{});exports.start=Z;const V=(e,n)=>t(void 0,void 0,void 0,(function*(){var r,i,l,d,c,u,p,h,b,v,O,R,k,E,q;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,g.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",m.INFO,g.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,g.RESTART)}(null!==(r=e.configListeners)&&void 0!==r?r:[]).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!==(l=n.config)&&void 0!==l?l:e.config,N=null!==(c=null!==(d=n.mode)&&void 0!==d?d:e.mode)&&void 0!==c?c:f.PROXY,L=null!==(p=null!==(u=n.strictMock)&&void 0!==u?u:e.strictMock)&&void 0!==p&&p,j=null!==(b=null!==(h=n.mocks)&&void 0!==h?h:e.mocks)&&void 0!==b?b:new Map,I=(null===n.configListeners?[]:null!==(O=null!==(v=n.configListeners)&&void 0!==v?v:e.configListeners)&&void 0!==O?O:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),P=(null===n.logsListeners?[]:null!==(k=null!==(R=n.logsListeners)&&void 0!==R?R:e.logsListeners)&&void 0!==k?k:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),T=e;return Object.assign(T,{config:B,logsListeners:P,configListeners:I,mode:N,mocks:j,strictMock:L,configFileWatcher:void 0===T.configFileWatcher?(0,a.watchFile)(y,(()=>t(void 0,void 0,void 0,(function*(){return V(T,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield C(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",m.ERROR,g.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",m.ERROR,g.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,m.INFO,g.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,m.INFO,g.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,m.INFO,g.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,m.INFO,g.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),m.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`,m.INFO,g.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,m.INFO,g.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",m.INFO,g.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",m.INFO,g.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",m.INFO,g.RESTART),x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(T))})))):T.configFileWatcher,log:w.bind(T,T),notifyConfigListeners:S.bind(T),notifyLogsListeners:$.bind(T),quickStatus:x.bind(T),server:null!==n.server&&T.server||(null!==(q=null===(E=n.config)||void 0===E?void 0:E.port)&&void 0!==q?q:0)<0?null===n.server?null:T.server:(B.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},B.ssl),{allowHTTP1:!0})):s.createServer)(((e,t)=>Y(T,e,t))).addListener("error",(e=>X(T,e))).addListener("listening",(()=>T.quickStatus())).on("upgrade",((e,t)=>V(T,G(T,e,t)))).listen(B.port)}),T}));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,s.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({},P),{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"):w(e,"Crash test successful",m.INFO,g.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!te&&ee&&C().then(Z);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-traffic",
3
- "version": "0.0.82",
3
+ "version": "0.0.84",
4
4
  "main": "./dist/local-traffic.js",
5
5
  "private": false,
6
6
  "keywords": [
@@ -19,7 +19,7 @@
19
19
  "typescript": "tsc",
20
20
  "shebang": "echo '#!/usr/bin/env node' | cat - ./dist/minified.js > ./dist/local-traffic.js",
21
21
  "terser": "terser ./dist/index.js -c -m --toplevel > ./dist/terser.js",
22
- "remove-useless-whitespaces": "cat ./dist/terser.js | sed -r -s 's/\\\\n\\s*/\\\\n/g' > ./dist/minified.js",
22
+ "remove-useless-whitespaces": "cat ./dist/terser.js | sed -r 's/\\\\n\\s*/\\\\n/g' > ./dist/minified.js",
23
23
  "chmod": "chmod a+x ./dist/local-traffic.js",
24
24
  "clean": "rm -rf dist",
25
25
  "build": "npm run clean && npm run typescript && npm run terser && npm run remove-useless-whitespaces && npm run shebang && npm run chmod",
@@ -27,7 +27,7 @@
27
27
  "test": "node ./test/tests.spec.mjs"
28
28
  },
29
29
  "devDependencies": {
30
- "@types/node": "^20.5.9",
30
+ "@types/node": "^20.6.0",
31
31
  "terser": "^5.19.4",
32
32
  "typescript": "^5.2.2"
33
33
  },