local-traffic 0.0.89 → 0.0.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/local-traffic.js +1 -1
- package/package.json +4 -4
package/dist/local-traffic.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))},n=this&&this.__rest||function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.cleanEntropy=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.recorderHandler=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const o=require("http2"),r=require("http"),s=require("https"),i=require("url"),a=require("fs"),l=require("zlib"),c=require("path"),d=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.STRICT_MOCKS="🕸️\b ",e.AUTO_RECORD="📼",e.REWRITE="✒️ ",e.LOGS="📝",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 y=(0,c.resolve)((0,p.homedir)(),".local-traffic.json"),b=(0,c.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:y),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",k=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(g.INBOUND,"g"),"inbound:").replace(new RegExp(g.PORT,"g"),"port:").replace(new RegExp(g.OUTBOUND,"g"),"outbound:").replace(new RegExp(g.RULES,"g"),"rules:").replace(new RegExp(g.NO,"g"),"").replace(new RegExp(g.REWRITE,"g"),"+rewrite").replace(new RegExp(g.WEBSOCKET,"g"),"websocket").replace(new RegExp(g.SHIELD,"g"),"web-security").replace(new RegExp(g.MOCKS,"g"),"mocks").replace(new RegExp(g.STRICT_MOCKS,"g"),"mocks (strict)").replace(new RegExp(g.AUTO_RECORD,"g"),"auto record").replace(new RegExp(g.LOGS,"g"),"logs").replace(new RegExp(g.RESTART,"g"),"restart").replace(new RegExp(g.COLORED,"g"),"colored").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹[0m`:t}${null===n&&e.mode===f.PROXY&&e.mockConfig.autoRecord&&!e.config.logAccessInTerminal?"\n":""}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,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])),r=e.length,s=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,s+r]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|s]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|s]).buffer),Buffer.concat(Number(r).toString(16).padStart(16,"0").match(/.{2}/g).map((e=>parseInt(e,16))).map((e=>Buffer.from(Uint8Array.from([e]).buffer))))]),a=Buffer.from(Int8Array.from(n).buffer),l=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,l]:[i,l])};exports.createWebsocketBufferFrom=R;const w=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=w;const E=(e,t)=>{const n=(0,d.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${o}\r\n\r\n`)};exports.acknowledgeWebsocket=E;const S=function(e){return C(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([C(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),C(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},C=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),r=o.has(!1)&&R(n,!1),s=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(s,"ascii",(()=>i(e))):e.stream.write(r,"ascii",(()=>i(e))))}))},x=function(){this.log(`[48;5;52m⎸${g.PORT} ${this.config.port.toString().padStart(5)} [48;5;53m⎸${g.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?g.REWRITE:" "}⎹⎸${g.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?g.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${this.mode===f.PROXY&&this.mockConfig.autoRecord?`${g.AUTO_RECORD}${this.mockConfig.mocks.size.toString().padStart(3)}`:this.mode===f.PROXY?`${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${this.mockConfig.strict?g.STRICT_MOCKS:g.MOCKS}${this.mockConfig.mocks.size.toString().padStart(3)}`}⎹[48;5;56m⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹[48;5;57m⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹[48;5;93m⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹[0m`),this.notifyConfigListeners(this.config)};exports.quickStatus=x;const q=(e,t,n,o,r)=>`${D(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\nⓘ This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n<tbody>\n<tr>\n<td>server mode</td>\n<td>${t}</td>\n</tr>\n<tr>\n<td>phase</td>\n<td>${n}</td>\n</tr>\n<tr>\n<td>requested URL</td>\n<td>${o}</td>\n</tr>\n<tr>\n<td>downstream URL</td>\n<td>${r||"<no-target-url>"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,I=(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>', '⏱',\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="' + (response ?? "") +\n'" data-uniquehash="' + uniqueHash + \n'" data-bs-toggle="modal" data-bs-target="#edit-request" type="button" ' +\n'class="btn btn-primary">📝</button>'\n: ''\nconst remove = ${!0===n.captureResponseBody} && uniqueHash\n? '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">❌</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">🔁</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>`,B=(e,t,n)=>{let o={};try{o=JSON.parse(t.toString("ascii"))}catch(e){}if("object"!=typeof o||Object.keys(o).filter((e=>!["strict","mode","mocks","autoRecord"].includes(e))).length||!Array.isArray(o.mocks)&&void 0!==o.mocks)return void e.log("invalid mocks update received",m.WARNING,g.MOCKS);const{mocks:r,mode:s,strict:i,autoRecord:a}=o,l=r?new Map(r.map((({response:e,uniqueHash:t})=>[K(t),e]))):null,c=s!==e.mode&&s===f.PROXY,d=(!c||!0===a)&&(null!=a?a:e.mockConfig.autoRecord),u=void 0!==d&&d!=e.mockConfig.autoRecord,p=s!==e.mode&&s===f.MOCK||null!==l&&e.mockConfig.mocks.size!==l.size,h=null!=i?i:e.mockConfig.strict,y=null!=s?s:e.mode,b=!!h!=!!e.mockConfig.strict,v=n;c&&e.log(`${Object.keys(e.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),p&&e.log(`${(null!=l?l:e.mockConfig.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,h?g.STRICT_MOCKS:g.MOCKS),b&&e.log(`mocks strict mode : ${null!=h?h:e.mockConfig.strict}`,m.INFO,h?g.STRICT_MOCKS:g.MOCKS),u&&e.log(`mocks auto-record : ${d}`,m.INFO,y===f.PROXY?g.AUTO_RECORD:h?g.STRICT_MOCKS:g.MOCKS),Q(e,v?{mode:y,mockConfig:{autoRecord:!1,strict:h,mocks:new Map}}:{mode:y,mockConfig:{strict:h,autoRecord:d,mocks:null!=l?l:e.mockConfig.mocks}}),(c||p||b||v)&&e.quickStatus()};exports.recorderHandler=B;const T={logs:(e,t)=>F(`${D(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${I(e,t.config,{captureResponseBody:!1})}\n</body></html>`),config:(e,t)=>F(`${D(127899,"config","")}\n<link href="${H}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${H}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${H}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({},j),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n")}\n},\nrequired: [],\nadditionalProperties: false\n}}\n\nfunction save() {\nsocket.send(JSON.stringify(editor.get()));\n}\n\nfunction generateSslCertificate() {\nconst sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\nsslModal.show()\nsetTimeout(function() {\nconst keypair = forge.pki.rsa.generateKeyPair(2048);\nconst certificate = forge.pki.createCertificate();\nconst now = new Date();\nconst fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\nObject.assign(certificate, {\npublicKey: keypair.publicKey,\nserialNumber: "01",\nvalidity: {\nnotBefore: now,\nnotAfter: fiveYears,\n},\n});\ncertificate.sign(keypair.privateKey, forge.md.sha256.create());\nconst key = forge.pki.privateKeyToPem(keypair.privateKey);\nconst cert = forge.pki.certificateToPem(certificate);\nconst existingConfig = editor.get();\neditor.set({ ...existingConfig, ssl: { key, cert },\nport: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n});\nsslModal.hide();\n}, 100);\n}\n\nconst editor = new JSONEditor(container, options);\nlet socket;\nconst initialJson = ${JSON.stringify(t.config)}\neditor.set(initialJson)\neditor.validate();\neditor.aceEditor.commands.addCommand({\nname: 'save',\nbindKey: {win: 'Ctrl-S', mac: 'Command-S'},\nexec: save,\n});\n\nwindow.addEventListener("DOMContentLoaded", function() {\ndocument.getElementById('jsoneditor').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\ndocument.getElementById('jsoneditor').style.width =\nparseInt(window.getComputedStyle(\ndocument.querySelector('.container')).maxWidth) + 'px';\nconst sslButton = document.createElement('button');\nsslButton.addEventListener("click", generateSslCertificate);\nsslButton.type="button";\nsslButton.classList.add("btn");\nsslButton.classList.add("btn-primary");\nsslButton.innerHTML="🔒";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(sslButton);\nconst saveButton = document.createElement('button');\nsaveButton.addEventListener("click", save);\nsaveButton.type="button";\nsaveButton.classList.add("btn");\nsaveButton.classList.add("btn-primary");\nsaveButton.innerHTML="💾";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.config.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`),recorder:(e,t,n)=>{var o,r,s,i,a,l,c,d,u;return(null===(o=n.url)||void 0===o?void 0:o.endsWith("?forceLogInRecorderPage=true"))?F('{"ping":"pong"}',{contentType:"application/json; charset=utf-8"}):"GET"===n.method&&(null===(s=null===(r=n.headers)||void 0===r?void 0:r.accept)||void 0===s?void 0:s.includes("application/json"))?F(JSON.stringify(Object.assign(Object.assign({},t.mockConfig),{mode:t.mode,mocks:[...t.mockConfig.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t})))})),{contentType:"application/json; charset=utf-8"}):["PUT","POST","DELETE"].includes(n.method)?F('{"status": "acknowledged"}',{contentType:"application/json; charset=utf-8",onOutboundWrite:e=>B(t,e,"DELETE"===n.method)}):F(`${D(9210,"recorder","")}\n<link href="${H}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${H}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${H}pako/dist/pako.min.js"><\/script>\n<form>\n<div id="commands"${t.mockConfig.autoRecord?' style="filter:blur(8px)"':""}>\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">⏺ 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">🌐 Mock</label>\n</div>\n<span>Actions : </span>\n<button type="button" class="btn btn-light" id="add-mock">➕ Mock from dummy request</button>\n<button type="button" class="btn btn-light" id="upload-mocks">📥 Upload mocks</button>\n<button type="button" class="btn btn-light" id="download-mocks">📦 Download mocks</button>\n<button type="button" class="btn btn-light" id="delete-mocks">🗑 Delete mocks</button>\n</div>\n<div class="row">\n<div class="col-lg" style="max-width: 200px">\n<div class="form-check form-switch" id="strict-mock-mode-form-control">\n<input class="form-check-input" type="checkbox" id="strict-mock-mode"${t.mockConfig.strict?' checked="checked"':""}>\n<label class="form-check-label" for="strict-mock-mode">Strict mock mode</label>\n</div>\n</div>\n<div class="col-lg" style="max-width: 200px">\n<div class="form-check form-switch">\n<input class="form-check-input" type="checkbox" id="auto-record-mode"${t.mockConfig.autoRecord?' checked="checked"':""}>\n<label class="form-check-label" for="auto-record-mode">Auto record mode</label>\n</div>\n</div>\n<div class="col-lg"> </div>\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!==(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/"}", {\nmethod: 'PUT',\nheaders: { 'Content-Type': 'application/json' },\nbody: '{"strict":' + document.getElementById('strict-mock-mode').checked +\n',"autoRecord":' + document.getElementById('auto-record-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!==(u=null===(d=Object.entries(null!==(c=t.config.mapping)&&void 0!==c?c:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===d?void 0:d[0])&&void 0!==u?u:"/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('auto-record-mode').addEventListener('change', (e) => { \nupdateState();\ndocument.getElementById('table-access').style.filter = \ndocument.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\ndocument.getElementById('commands').style.filter = \ndocument.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\ndocument.getElementById('alert-about-auto-record-mode').style.display = \ndocument.getElementById('auto-record-mode').checked ? 'block' : 'none';\ndocument.getElementById('strict-mock-mode-form-control').style.filter = \ndocument.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\n\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.mockConfig.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"},{type:"array"}]},\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"},{type:"array"}]},\nheaders: {type: "object"},\nstatus: {type: "integer"}\n},\nrequired: [],\nadditionalProperties: false\n}});\n${t.mockConfig.autoRecord?";document.getElementById('strict-mock-mode-form-control').style.filter='blur(8px)';;document.getElementById('table-access').style.filter='blur(8px)';":""}\ndocument.forms[0].reset();\n}, 10)\n<\/script>\n</form>\n<div class="alert alert-warning" role="alert"\nstyle="display:${t.mockConfig.autoRecord?"block":"none"};left:20%;right:20%;position:absolute;z-index:1;" id="alert-about-auto-record-mode">\nⓘ Auto-record mode and recorder webapp are known to be mutually exclusive.\n<br/><br/>Changing the mocks on both sides is somehow hard to sort out.\n<br/>This is triggering concurrent modifications in the mock config.\n<hr/>\nHere is what you can do :\n<ul>\n<li>If you want to record mocks using a frontend app, turn off the auto-record mode.</li>\n<li>If you want to record mocks with the recorder API only, close this app.</li>\n</ul>\n</div>\n${I(e,t.config,{captureResponseBody:!0})}\n</body>\n</html>`)}},N=Object.keys(T),L=N.map((e=>`${e}:`)),j={mapping:Object.assign({},...N.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,logAccessInTerminal:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},A=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(b,((n,o)=>{n&&!e&&k(null,"config error. Using default value",m.ERROR,g.ERROR_1);let r=null;try{r=Object.assign({},j,JSON.parse((o||"{}").toString()))}catch(e){return k({config:r},"config syntax incorrect, aborting",m.ERROR,g.ERROR_2),r=null!=r?r:Object.assign({},j),void t(r)}r.mapping[""]||k({config:r},'default mapping "" not provided.',m.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&b===y?(0,a.writeFile)(b,JSON.stringify(j,null,2),(e=>{e?k(null,"config file NOT created",m.ERROR,g.ERROR_4):k(null,"config file created",m.INFO,g.COLORED),t(r)})):t(r)}))))}));exports.load=A;const P=e=>""==e?"":(0,c.normalize)(e).replace(/\\/g,"/"),H="https://cdn.jsdelivr.net/npm/",U=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],D=(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="${H}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${H}jquery/dist/jquery.min.js"><\/script>\n<script src="${H}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,c.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,a.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,a.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,a.lstat)((0,c.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=`${D(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}},F=(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}}),J=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?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 r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\xFF]/.test(e.toString()))?_(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=J;const _=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>L.some((e=>s.startsWith(e)))||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(s.replace(new RegExp(`^(file|${N.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=_;const K=e=>{try{const t="object"==typeof e?e:JSON.parse(Buffer.from(e,"base64").toString("utf-8"));return["access-control-max-age","authorization","cache-control","cookie","date","dnt","expires","if-modified-since","if-unmodified-since","keep-alive","last-modified","pragma","proxy-authenticate","proxy-authorization","referer","retry-after","signed-headers","server-timing","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform","sec-fetch-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","upgrade-insecure-requests","user-agent"].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=K;const z=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=z;const G=(e,t)=>{var n,o,r,s,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(s=t.port)&&void 0!==s?s:8080}`:""}`,d=new i.URL(`http${t.ssl?"s":""}://${c}${e.url}`),u=d.href.substring(d.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(P("string"==typeof t?t:t.downstreamUrl))})))));let m;const[g,h]=null!==(a=Object.entries(p).find((([e])=>m=u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[],f=m?new i.URL(h.href.replace(/\$\$(\d+)/g,((e,t)=>m[parseInt(t)]))):null;return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:u,key:g,target:f}};exports.determineMapping=G;const Y=function(e,t,n){var o,a,l,c;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:d,target:u,path:p,url:h}=G(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=w(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",m.WARNING,g.ERROR_4)}Q(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const f=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),y={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},b="https:"===f.protocol?(0,s.request)(y):(0,r.request)(y);b.end(),b.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),b.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=Y;const X=function(e,n,a){var l,c,p,y,O;return t(this,void 0,void 0,(function*(){if(!n.headers.host&&!n.headers[":authority"])return void z(400,a,Buffer.from(q(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:k,url:R,path:w,key:E,target:S}=G(n,e.config);if(!S)return void z(502,a,Buffer.from(q(new Error(`No mapping found in config file ${b}`),e.mode,"proxy",R)));const $=S.host.replace(RegExp(/\/+$/),""),C=`${S.href.substring(8+S.host.length)}${P(w.replace(RegExp(P(E)),""))}`.replace(/^\/*/,"/"),x=new i.URL(`${S.protocol}//${$}${C}`),I=L.some((e=>S.protocol===e));let B=null,N=!e.config.dontUseHttp2Downstream;const j=N&&!I&&"file:"!==S.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(x,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:S.protocol},((e,o)=>{N=N&&!!o.alpnProtocol,t(N?n:null)}));n.on("error",(t=>{B=N&&Buffer.from(q(t,e.mode,"connection",R,x))}))})),new Promise((t=>setTimeout((()=>{N=!1,t(null)}),e.config.connectTimeout)))])),A=(0,d.randomBytes)(20).toString("hex");let H=null;const D=e.config.replaceRequestBodyUrls||e.logsListeners.length,F=null==n?void 0:n.readableLength,Y=null===(l=null==n?void 0:n.stream)||void 0===l?void 0:l.readableLength,X=!((e.config.ssl&&0===Y||!e.config.ssl&&0===F)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(D){const o=null!==(c=null==n?void 0:n.stream)&&void 0!==c?c:n;let r=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{X?(o.on("data",(e=>{r=Buffer.concat([r,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),X&&!r.length&&e.log(`body replacement error ${w.slice(-17)}`,m.WARNING,g.ERROR_4),H=e.config.replaceRequestBodyUrls?yield J(r,n.headers,{proxyHostnameAndPort:k,proxyHostname:t,key:E,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):r}const Z=e.logsListeners.some((e=>e.wantsResponseMessage)),V=e.mockConfig.autoRecord&&e.mode===f.PROXY,Q=e.mode===f.MOCK||Z||V?K({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==H?void 0:H.toString("base64")}):"",ee="file:"===S.protocol;e.notifyLogsListeners({level:"info",protocol:N?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:w,downstreamPath:x.href,randomId:A,uniqueHash:Q}),e.config.logAccessInTerminal&&!x.pathname.startsWith("/:/")&&e.log(e.config.simpleLogs?`${n.method} ${x.pathname}`:`[48;5;${"GET"===n.method?"22":"POST"===n.method?"52":"PUT"===n.method?"94":"DELETE"===n.method?"244":"OPTIONS"===n.method?"19":"PATCH"===n.method?"162":"HEAD"===n.method?"53":"TRACE"===n.method?"6":"CONNECT"===n.method?"2":"0"}m⎸${n.method.toString().padStart(7)} [48;5;8m⎸${x.pathname.toString().padStart(40).substring(0,40)}⎹[0m`);const te=e.mode===f.MOCK&&(!I||ee),ne=e.mockConfig.mocks.get(Q);if(te&&!ne&&e.mockConfig.strict)return void z(502,a,Buffer.from(q(new Error("No corresponding mock found in the server. \nTry switching back to the proxy mode"),e.mode,"mock",R)));const oe=v(),re=te&&ne?M({response:ne}):ee?W(x):I?T[S.protocol.replace(/:$/,"")](k,e,n):N?j:null;B instanceof Buffer||(B=null);const se=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!U.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(R.hostname,$))).join(", "),e)),{})),{origin:S.href,referer:x.toString(),"content-length":null!==(y=null!==(p=null==H?void 0:H.length)&&void 0!==p?p:n.headers["content-length"])&&void 0!==y?y:0,":authority":$,":method":n.method,":path":C,":scheme":S.protocol.replace(":","")}),ie=re&&!B&&re.request(se,{endStream:e.config.ssl?!(null==Y||Y):!F});"object"==typeof ie&&(null==ie||ie.on("error",(t=>{const n=-505===t.errno;B=Buffer.from(q(t,e.mode,"stream"+(n?" (error -505 usually means that the downstream service does not support this http version)":""),R,x))})));const ae={hostname:S.hostname,path:C,port:S.port,protocol:S.protocol,rejectUnauthorized:!1,method:n.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(se).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:S.hostname})},le=!B&&!N&&!["file:",...L].includes(S.protocol)&&(yield new Promise((t=>{const o="https:"===S.protocol?(0,s.request)(ae,t):(0,r.request)(ae,t);o.on("error",(n=>{B=Buffer.from(q(n,e.mode,"request",R,x)),t(null)})),D&&(o.write(H),o.end()),D||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(B)return void z(502,a,B);B=null,Y&&ie&&!D?(n.stream.on("data",(e=>{ie.write(e)})),n.stream.on("end",(()=>ie.end()))):F&&ie&&!D?(n.on("data",(e=>{ie.write(e)})),n.on("end",(()=>ie.end()))):ie&&D&&X&&(ie.write(H),ie.end());const{outboundResponseHeaders:ce}=yield new Promise((e=>ie?ie.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!ie&&le?{outboundResponseHeaders:le.headers}:{outboundResponseHeaders:{}})));let de=null;try{ce.location&&(de=new i.URL(ce.location.startsWith("/")?`${S.origin}${ce.location.replace(/^\/+/,"/")}`:ce.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(O=ce.location)&&void 0!==O?O:"").slice(-13)}`,m.WARNING,g.ERROR_4)}const ue=e.config.replaceResponseBodyUrls&&de?new i.URL(_(de.href,{direction:h.INBOUND,proxyHostnameAndPort:k,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${L.join("|")}|file:)/+`),"")):de,pe=de?ue.origin!==de.origin||e.config.dontTranslateLocationHeader?ue:`${R.origin}${ue.href.substring(ue.origin.length)}`:de,me=ie||le,ge=null!=B?B:yield new Promise((e=>{let t=Buffer.alloc(0);me?(me.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),me.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?L.some((e=>S.protocol===e))?n:J(n,ce,{proxyHostnameAndPort:k,proxyHostname:t,key:E,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((t=>(z(502,a,Buffer.from(q(t,e.mode,"stream",R,x))),Buffer.from("")))):n)),he=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},ce),e.config.replaceResponseBodyUrls?{"content-length":`${ge.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(":")&&!U.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=$.split("").map(((e,t)=>$.substring(t).startsWith(".")&&$.substring(t))).filter((e=>e)),r=[$].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${R.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),pe?{location:[pe]}:{});try{Object.entries(he).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const fe=ce[":status"]||le.statusCode||200;try{a.writeHead(fe,e.config.ssl?void 0:le.statusMessage||"Status read from http/2",he)}catch(e){}ge?a.end(ge):a.end();const ye=v(),be=Z||V?Buffer.from(JSON.stringify({body:null==ge?void 0:ge.toString("base64"),headers:ce,status:fe})).toString("base64"):"";e.notifyLogsListeners({randomId:A,statusCode:fe,protocol:N?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ye-oe)/1e6),uniqueHash:Q,response:be}),!V||e.config.logAccessInTerminal||I||(e.mockConfig.mocks.set(Q,be),u.stdout.moveCursor(0,-1,(()=>u.stdout.clearLine(-1,e.quickStatus))))}))};exports.serve=X;const Z=(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=Z;const V=e=>Q({config:Object.assign(Object.assign({},j),e)},{});exports.start=V;const Q=(e,n)=>t(void 0,void 0,void 0,(function*(){var s,i,l,c,d,u,p,h,y,v,O,R,w,E,C,q,I,B,T,N,L,j,P;if(0===Object.keys(null!=n?n:{}).length&&e.server)return;if(n.pendingConfigSave)return void(0,a.writeFile)(b,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!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(i=e.logsListeners)&&void 0!==i?i:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const H=null!==(l=n.config)&&void 0!==l?l:e.config,U=null!==(d=null!==(c=n.mode)&&void 0!==c?c:e.mode)&&void 0!==d?d:f.PROXY,D=null!==(y=null!==(p=null===(u=n.mockConfig)||void 0===u?void 0:u.autoRecord)&&void 0!==p?p:null===(h=e.mockConfig)||void 0===h?void 0:h.autoRecord)&&void 0!==y&&y,M=null!==(w=null!==(O=null===(v=n.mockConfig)||void 0===v?void 0:v.strict)&&void 0!==O?O:null===(R=e.mockConfig)||void 0===R?void 0:R.strict)&&void 0!==w&&w,W=null!==(I=null!==(C=null===(E=n.mockConfig)||void 0===E?void 0:E.mocks)&&void 0!==C?C:null===(q=e.mockConfig)||void 0===q?void 0:q.mocks)&&void 0!==I?I:new Map,F=(null===n.configListeners?[]:null!==(T=null!==(B=n.configListeners)&&void 0!==B?B:e.configListeners)&&void 0!==T?T:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),J=(null===n.logsListeners?[]:null!==(L=null!==(N=n.logsListeners)&&void 0!==N?N:e.logsListeners)&&void 0!==L?L:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),_=e;return Object.assign(_,{config:H,logsListeners:J,configListeners:F,mode:U,mockConfig:{mocks:W,strict:M,autoRecord:D},configFileWatcher:void 0===_.configFileWatcher?(0,a.watchFile)(b,(()=>t(void 0,void 0,void 0,(function*(){return Q(_,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield A(!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.logAccessInTerminal!==t.logAccessInTerminal&&e.log("access terminal logging "+(n.logAccessInTerminal?"on":"off"),m.INFO,g.LOGS),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}))}))}(_))})))):_.configFileWatcher,log:k.bind(_,_),notifyConfigListeners:S.bind(_),notifyLogsListeners:$.bind(_),quickStatus:x.bind(_),server:null!==n.server&&_.server||(null!==(P=null===(j=n.config)||void 0===j?void 0:j.port)&&void 0!==P?P:0)<0?null===n.server?null:_.server:(H.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},H.ssl),{allowHTTP1:!0})):r.createServer)(((e,t)=>X(_,e,t))).addListener("error",(e=>Z(_,e))).addListener("listening",(()=>_.quickStatus())).on("upgrade",((e,t)=>Q(_,Y(_,e,t)))).listen(H.port)}),_}));exports.update=Q;const ee=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:"",te=ee.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!ee.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),ne=u.argv.some((e=>"--crash-test"===e));if(ne){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,r.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();Q({config:Object.assign(Object.assign({},j),{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"):Q(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):k(e,"Crash test successful",m.INFO,g.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!ne&&te&&A().then(V);
|
|
2
|
+
"use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))},n=this&&this.__rest||function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.cleanEntropy=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.recorderHandler=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const o=require("http2"),r=require("http"),s=require("https"),i=require("url"),a=require("fs"),l=require("zlib"),c=require("path"),d=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.STRICT_MOCKS="🕸️\b ",e.AUTO_RECORD="📼",e.REWRITE="✒️ ",e.LOGS="📝",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 y=(0,c.resolve)((0,p.homedir)(),".local-traffic.json"),b=(0,c.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:y),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",k=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(g.INBOUND,"g"),"inbound:").replace(new RegExp(g.PORT,"g"),"port:").replace(new RegExp(g.OUTBOUND,"g"),"outbound:").replace(new RegExp(g.RULES,"g"),"rules:").replace(new RegExp(g.NO,"g"),"").replace(new RegExp(g.REWRITE,"g"),"+rewrite").replace(new RegExp(g.WEBSOCKET,"g"),"websocket").replace(new RegExp(g.SHIELD,"g"),"web-security").replace(new RegExp(g.MOCKS,"g"),"mocks").replace(new RegExp(g.STRICT_MOCKS,"g"),"mocks (strict)").replace(new RegExp(g.AUTO_RECORD,"g"),"auto record").replace(new RegExp(g.LOGS,"g"),"logs").replace(new RegExp(g.RESTART,"g"),"restart").replace(new RegExp(g.COLORED,"g"),"colored").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":"[36m"}${`${t.getHours()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":"[33m:[36m"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":"[0m"}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹[0m`:t}${null===n&&e.mode===f.PROXY&&e.mockConfig.autoRecord&&!e.config.logAccessInTerminal?"\n":""}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,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])),r=e.length,s=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,s+r]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|s]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|s]).buffer),Buffer.concat(Number(r).toString(16).padStart(16,"0").match(/.{2}/g).map((e=>parseInt(e,16))).map((e=>Buffer.from(Uint8Array.from([e]).buffer))))]),a=Buffer.from(Int8Array.from(n).buffer),l=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,l]:[i,l])};exports.createWebsocketBufferFrom=R;const w=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=w;const E=(e,t)=>{const n=(0,d.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nerver: local\r\nec-websocket-accept: ${o}\r\n\r\n`)};exports.acknowledgeWebsocket=E;const S=function(e){return C(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([C(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),C(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},C=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),r=o.has(!1)&&R(n,!1),s=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(s,"ascii",(()=>i(e))):e.stream.write(r,"ascii",(()=>i(e))))}))},x=function(){this.log(`[48;5;52m⎸${g.PORT} ${this.config.port.toString().padStart(5)} [48;5;53m⎸${g.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?g.REWRITE:" "}⎹⎸${g.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?g.REWRITE:" "}⎹[48;5;54m[48;5;55m⎸${this.mode===f.PROXY&&this.mockConfig.autoRecord?`${g.AUTO_RECORD}${this.mockConfig.mocks.size.toString().padStart(3)}`:this.mode===f.PROXY?`${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${this.mockConfig.strict?g.STRICT_MOCKS:g.MOCKS}${this.mockConfig.mocks.size.toString().padStart(3)}`}⎹[48;5;56m⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹[48;5;57m⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹[48;5;93m⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹[0m`),this.notifyConfigListeners(this.config)};exports.quickStatus=x;const q=(e,t,n,o,r)=>`${D(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n ⓘ This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n <tbody>\n <tr>\n <td>server mode</td>\n <td>${t}</td>\n </tr>\n <tr>\n <td>phase</td>\n <td>${n}</td>\n </tr>\n <tr>\n <td>requested URL</td>\n <td>${o}</td>\n </tr>\n <tr>\n <td>downstream URL</td>\n <td>${r||"<no-target-url>"}</td>\n </tr>\n </tbody>\n</table>\n</div></body></html>`,I=(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">\n function start() {\n document.getElementById('table-access').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n const socket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-logs${n.captureResponseBody?"?wantsResponseMessage=true":""}");\n socket.onmessage = function(event) {\n let data = event.data\n let uniqueHash;\n try {\n const { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\n data = data1;\n uniqueHash = uniqueHash1;\n } catch(e) { }\n if (document.getElementById('mock-mode')?.checked) return;\n if (${!0===n.captureResponseBody} && \n data?.downstreamPath?.startsWith('recorder://') &&\n !data?.upstreamPath?.endsWith('?forceLogInRecorderPage=true'))\n return;\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n const actions = getActionsHtmlText(uniqueHash, data.response);\n if(data.statusCode && uniqueHash) {\n const color = getColorFromStatusCode(data.statusCode);\n const statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\n if (statusCodeColumn)\n statusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\n const durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\n if (durationColumn) {\n const duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\n data.duration + 'ms';\n durationColumn.innerHTML = duration;\n }\n\n const protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\n if (protocolColumn) {\n protocolColumn.innerHTML = data.protocol;\n }\n\n const replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\n if (replayColumn) {\n replayColumn.innerHTML = actions;\n }\n } else if (uniqueHash) {\n addNewRequest(data.randomId, actions, time, data.level, data.protocol, data.method, \n '<span class="badge bg-secondary">...</span>', '⏱',\n data.upstreamPath, data.downstreamPath);\n } else if(data.event) {\n document.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 }\n cleanup();\n };\n socket.onerror = function(error) {\n console.log(\`[error] \${JSON.stringify(error)}\`);\n setTimeout(start, 5000);\n };\n };\n function show(id) {\n [...document.querySelectorAll('table')].forEach((table, index) => {\n table.style.display = index === id ? 'block': 'none'\n });\n [...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\n if (index === id) { link.classList.add('active') } else link.classList.remove('active');\n });\n }\n function remove(event) {\n event.target.closest('tr').remove();\n if (window.updateState) window.updateState();\n }\n function cleanup() {\n const currentLimit = parseInt(document.getElementById('limit').value)\n for (let table of ['access', 'proxy']) {\n while (currentLimit && document.getElementById(table).childNodes.length && \n document.getElementById(table).childNodes.length > currentLimit) {\n [...document.getElementById(table).childNodes].slice(-1)[0].remove();\n }\n }\n }\n function replay(event) {\n const uniqueHash = event.target.dataset.uniquehash;\n const { method, url, headers, body } = JSON.parse(atob(uniqueHash));\n fetch(url, {\n method,\n headers,\n body: !body || !body.length ? undefined : atob(body)\n });\n }\n function getActionsHtmlText(uniqueHash, response) {\n const edit = ${!0===n.captureResponseBody} && uniqueHash\n ? '<button data-response="' + (response ?? "") +\n '" data-uniquehash="' + uniqueHash + \n '" data-bs-toggle="modal" data-bs-target="#edit-request" type="button" ' +\n 'class="btn btn-primary">📝</button>'\n : ''\n const remove = ${!0===n.captureResponseBody} && uniqueHash\n ? '<button onclick="javascript:remove(event)" type="button" ' +\n 'class="btn btn-primary">❌</button>'\n : ''\n const replay = ${!1===n.captureResponseBody} && uniqueHash ? '<button data-response="' + \n btoa(JSON.stringify(response ?? {})) +\n '" data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n 'type="button" class="btn btn-primary">🔁</button>' : '';\n return edit + replay + remove\n }\n function addNewRequest(\n randomId, actions, time, level, protocol, method, \n statusCode, duration, upstreamPath, downstreamPath\n ) {\n document.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 }\n function getColorFromStatusCode(statusCode) {\n return Math.floor(statusCode / 100) === 1 ? "info" :\n Math.floor(statusCode / 100) === 2 ? "success" :\n Math.floor(statusCode / 100) === 3 ? "dark" :\n Math.floor(statusCode / 100) === 4 ? "warning" :\n Math.floor(statusCode / 100) === 5 ? "danger" :\n "secondary";\n }\n window.addEventListener("DOMContentLoaded", start);\n<\/script>`,B=(e,t,n)=>{let o={};try{o=JSON.parse(t.toString("ascii"))}catch(e){}if("object"!=typeof o||Object.keys(o).filter((e=>!["strict","mode","mocks","autoRecord"].includes(e))).length||!Array.isArray(o.mocks)&&void 0!==o.mocks)return void e.log("invalid mocks update received",m.WARNING,g.MOCKS);const{mocks:r,mode:s,strict:i,autoRecord:a}=o,l=r?new Map(r.map((({response:e,uniqueHash:t})=>[K(t),e]))):null,c=s!==e.mode&&s===f.PROXY,d=(!c||!0===a)&&(null!=a?a:e.mockConfig.autoRecord),u=void 0!==d&&d!=e.mockConfig.autoRecord,p=s!==e.mode&&s===f.MOCK||null!==l&&e.mockConfig.mocks.size!==l.size,h=null!=i?i:e.mockConfig.strict,y=null!=s?s:e.mode,b=!!h!=!!e.mockConfig.strict,v=n;c&&e.log(`${Object.keys(e.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),p&&e.log(`${(null!=l?l:e.mockConfig.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,h?g.STRICT_MOCKS:g.MOCKS),b&&e.log(`mocks strict mode : ${null!=h?h:e.mockConfig.strict}`,m.INFO,h?g.STRICT_MOCKS:g.MOCKS),u&&e.log(`mocks auto-record : ${d}`,m.INFO,y===f.PROXY?g.AUTO_RECORD:h?g.STRICT_MOCKS:g.MOCKS),Q(e,v?{mode:y,mockConfig:{autoRecord:!1,strict:h,mocks:new Map}}:{mode:y,mockConfig:{strict:h,autoRecord:d,mocks:null!=l?l:e.mockConfig.mocks}}),(c||p||b||v)&&e.quickStatus()};exports.recorderHandler=B;const T={logs:(e,t)=>F(`${D(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">\n Limit : <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${I(e,t.config,{captureResponseBody:!1})}\n</body></html>`),config:(e,t)=>F(`${D(127899,"config","")}\n <link href="${H}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n <script src="${H}jsoneditor/dist/jsoneditor.min.js"><\/script>\n <script src="${H}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\n const container = document.getElementById("jsoneditor")\n const options = {mode: "code", allowSchemaSuggestions: true, schema: {\n type: "object",\n properties: {\n ${Object.entries(Object.assign(Object.assign({},j),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n ")}\n },\n required: [],\n additionalProperties: false\n }}\n\n function save() {\n socket.send(JSON.stringify(editor.get()));\n }\n\n function generateSslCertificate() {\n const sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\n sslModal.show()\n setTimeout(function() {\n const keypair = forge.pki.rsa.generateKeyPair(2048);\n const certificate = forge.pki.createCertificate();\n const now = new Date();\n const fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\n Object.assign(certificate, {\n publicKey: keypair.publicKey,\n serialNumber: "01",\n validity: {\n notBefore: now,\n notAfter: fiveYears,\n },\n });\n certificate.sign(keypair.privateKey, forge.md.sha256.create());\n const key = forge.pki.privateKeyToPem(keypair.privateKey);\n const cert = forge.pki.certificateToPem(certificate);\n const existingConfig = editor.get();\n editor.set({ ...existingConfig, ssl: { key, cert },\n port: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n });\n sslModal.hide();\n }, 100);\n }\n\n const editor = new JSONEditor(container, options);\n let socket;\n const initialJson = ${JSON.stringify(t.config)}\n editor.set(initialJson)\n editor.validate();\n editor.aceEditor.commands.addCommand({\n name: 'save',\n bindKey: {win: 'Ctrl-S', mac: 'Command-S'},\n exec: save,\n });\n\n window.addEventListener("DOMContentLoaded", function() {\n document.getElementById('jsoneditor').style.height =\n (document.documentElement.clientHeight - 150) + 'px';\n document.getElementById('jsoneditor').style.width =\n parseInt(window.getComputedStyle(\n document.querySelector('.container')).maxWidth) + 'px';\n const sslButton = document.createElement('button');\n sslButton.addEventListener("click", generateSslCertificate);\n sslButton.type="button";\n sslButton.classList.add("btn");\n sslButton.classList.add("btn-primary");\n sslButton.innerHTML="🔒";\n document.querySelector('.jsoneditor-menu')\n .appendChild(sslButton);\n const saveButton = document.createElement('button');\n saveButton.addEventListener("click", save);\n saveButton.type="button";\n saveButton.classList.add("btn");\n saveButton.classList.add("btn-primary");\n saveButton.innerHTML="💾";\n document.querySelector('.jsoneditor-menu')\n .appendChild(saveButton);\n socket = new WebSocket("ws${t.config.ssl?"s":""}://${e}/local-traffic-config");\n socket.onmessage = function(event) {\n editor.set(JSON.parse(event.data))\n editor.validate()\n }\n });\n <\/script>\n </body></html>`),recorder:(e,t,n)=>{var o,r,s,i,a,l,c,d,u;return(null===(o=n.url)||void 0===o?void 0:o.endsWith("?forceLogInRecorderPage=true"))?F('{"ping":"pong"}',{contentType:"application/json; charset=utf-8"}):"GET"===n.method&&(null===(s=null===(r=n.headers)||void 0===r?void 0:r.accept)||void 0===s?void 0:s.includes("application/json"))?F(JSON.stringify(Object.assign(Object.assign({},t.mockConfig),{mode:t.mode,mocks:[...t.mockConfig.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t})))})),{contentType:"application/json; charset=utf-8"}):["PUT","POST","DELETE"].includes(n.method)?F('{"status": "acknowledged"}',{contentType:"application/json; charset=utf-8",onOutboundWrite:e=>B(t,e,"DELETE"===n.method)}):F(`${D(9210,"recorder","")}\n<link href="${H}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${H}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${H}pako/dist/pako.min.js"><\/script>\n<form>\n <div id="commands"${t.mockConfig.autoRecord?' style="filter:blur(8px)"':""}>\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">⏺ 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">🌐 Mock</label>\n </div>\n <span>Actions : </span>\n <button type="button" class="btn btn-light" id="add-mock">➕ Mock from dummy request</button>\n <button type="button" class="btn btn-light" id="upload-mocks">📥 Upload mocks</button>\n <button type="button" class="btn btn-light" id="download-mocks">📦 Download mocks</button>\n <button type="button" class="btn btn-light" id="delete-mocks">🗑 Delete mocks</button>\n </div>\n <div class="row">\n <div class="col-lg" style="max-width: 200px">\n <div class="form-check form-switch" id="strict-mock-mode-form-control">\n <input class="form-check-input" type="checkbox" id="strict-mock-mode"${t.mockConfig.strict?' checked="checked"':""}>\n <label class="form-check-label" for="strict-mock-mode">Strict mock mode</label>\n </div>\n </div>\n <div class="col-lg" style="max-width: 200px">\n <div class="form-check form-switch">\n <input class="form-check-input" type="checkbox" id="auto-record-mode"${t.mockConfig.autoRecord?' checked="checked"':""}>\n <label class="form-check-label" for="auto-record-mode">Auto record mode</label>\n </div>\n </div>\n <div class="col-lg"> </div>\n </div>\n <input type="hidden" id="limit" value="0"/>\n <div class="modal fade" id="edit-request" tabindex="-1" \n aria-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 () {\n return JSON.stringify(\n [...document.querySelectorAll('button[data-uniqueHash]')].map(button => ({\n response: button.attributes['data-response']?.value,\n uniqueHash: button.attributes['data-uniqueHash']?.value}))\n )\n}\nfunction updateState () {\n fetch("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/"}", {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: '{"strict":' + document.getElementById('strict-mock-mode').checked +\n ',"autoRecord":' + document.getElementById('auto-record-mode').checked +\n ',"mode":"' + \n (document.getElementById('mock-mode').checked ? "mock" : "proxy") + '"' +\n ',"mocks":' + getMocksData() + '}'\n })\n}\nfunction loadMocks(mocksHashes) {\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n let mocks = [];\n try {\n mocks = mocksHashes.map(mock => ({...mock, \n request: JSON.parse(atob(mock.uniqueHash)),\n response: JSON.parse(atob(mock.response))\n }));\n } catch(e) { }\n mocks.forEach(mock => {\n const randomId = window.crypto.randomUUID();\n const actions = getActionsHtmlText(mock.uniqueHash, mock.response);\n addNewRequest(randomId, actions, time, 'info', 'HTTP/2', mock.request.method, \n '<span class="badge bg-' + \n getColorFromStatusCode(mock.response.status) + '">' + \n mock.response.status + \n '</span>', \n '0ms', mock.request.url, \n 'N/A');\n });\n}\ndocument.getElementById('add-mock').addEventListener('click', () => {\n const iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n iframe.onload = function() { iframe.parentNode.removeChild(iframe); };\n iframe.src = "http${t.config.ssl?"s":""}://${e}${null!==(u=null===(d=Object.entries(null!==(c=t.config.mapping)&&void 0!==c?c:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===d?void 0:d[0])&&void 0!==u?u:"/recorder/"}?forceLogInRecorderPage=true";\n document.body.appendChild(iframe);\n});\ndocument.getElementById('upload-mocks').addEventListener('click', () => {\n const time = new Date().toISOString().split('T')[1].replace('Z', '');\n const fileInput = document.createElement('input');\n fileInput.type = "file";\n fileInput.multiple = "multiple";\n fileInput.onchange = function() {\n const fileReader = new FileReader();\n [...fileInput.files].reduce((promise, file) =>\n promise.then(result => new Promise(resolve => {\n fileReader.readAsText(file);\n fileReader.onload = function(){\n resolve(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 }\n fileInput.click();\n});\ndocument.getElementById('download-mocks').addEventListener('click', () => {\n const link = document.createElement('a');\n link.href = URL.createObjectURL(new Blob([getMocksData()], {\n type: "application/json",\n }));\n link.download = "mocks-" + new Date().toISOString() + ".json";\n link.click();\n URL.revokeObjectURL(link.href);\n})\ndocument.getElementById('delete-mocks').addEventListener('click', () => {\n document.getElementById('limit').value = -1;\n cleanup();\n updateState();\n document.getElementById('limit').value = 0;\n})\ndocument.getElementById('record-mode').addEventListener('change', () => {\n document.getElementById('limit').value = 0;\n cleanup();\n updateState();\n})\ndocument.getElementById('mock-mode').addEventListener('change', () => {\n updateState();\n})\ndocument.getElementById('auto-record-mode').addEventListener('change', (e) => { \n updateState();\n document.getElementById('table-access').style.filter = \n document.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\n document.getElementById('commands').style.filter = \n document.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\n document.getElementById('alert-about-auto-record-mode').style.display = \n document.getElementById('auto-record-mode').checked ? 'block' : 'none';\n document.getElementById('strict-mock-mode-form-control').style.filter = \n document.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\n \n})\ndocument.getElementById('strict-mock-mode').addEventListener('change', (e) => { \n updateState();\n})\nfunction saveRequest () {\n $('#edit-request').modal("hide");\n \n const requestBeingEdited = window.requestBeingEdited;\n let request = uniqueHashEditor.get();\n let response = responseEditor.get();\n if (typeof request.body === "object") {\n request.body = JSON.stringify(request.body);\n }\n if (typeof response.body === "object") {\n response.body = JSON.stringify(response.body);\n }\n const oldRequest = JSON.parse(atob(requestBeingEdited.attributes['data-uniqueHash'].value));\n const oldResponse = JSON.parse(atob(requestBeingEdited.attributes['data-response'].value));\n const requestProlog = requestBeingEdited.attributes['data-requestProlog']?.value;\n const responseProlog = requestBeingEdited.attributes['data-responseProlog']?.value;\n const requestPrologHasChanged = request.body.substring(0, 10) !== oldRequest.body.substring(0, 10);\n const responsePrologHasChanged = response.body.substring(0, 10) !== response.body.substring(0, 10);\n if (requestProlog === "H4sIAAAAAAAA" && !requestPrologHasChanged) {\n request.body =\n btoa([...pako.gzip(request.body)].map(e => String.fromCharCode(e)).join(""));\n } else if ((requestProlog === null || !request.body.startsWith(requestProlog ?? "")) && \n request.body.substring(0, 10) !== oldRequest.body.substring(0, 10)) {\n request.body = btoa(request.body);\n }\n if (responseProlog === "H4sIAAAAAAAA" && !responsePrologHasChanged) {\n response.body =\n btoa([...pako.gzip(response.body)].map(e => String.fromCharCode(e)).join(""));\n } else if ((responseProlog === null || !response.body.startsWith(responseProlog ?? "")) && \n response.body.substring(0, 10) !== oldResponse.body.substring(0, 10)) {\n response.body = btoa(response.body);\n }\n request = btoa(JSON.stringify(request));\n response = btoa(JSON.stringify(response));\n requestBeingEdited.setAttribute('data-uniqueHash', request);\n requestBeingEdited.setAttribute('data-response', response);\n const row = requestBeingEdited.closest('tr');\n row.querySelector("td.method").innerHTML = uniqueHashEditor.get().method;\n row.querySelector("td.upstream-path").innerHTML = uniqueHashEditor.get().url;\n window.requestBeingEdited = undefined;\n updateState();\n}\ndocument.getElementById('edit-request').addEventListener('show.bs.modal', event => {\n const request = JSON.parse(atob(event.relatedTarget.attributes['data-uniqueHash'].value));\n const response = JSON.parse(atob(event.relatedTarget.attributes['data-response'].value));\n const requestProlog = xmlOrJsonPrologsInBase64.find(prolog => request.body?.startsWith(prolog));\n const responseProlog = xmlOrJsonPrologsInBase64.find(prolog => response.body?.startsWith(prolog));\n if (requestProlog) {\n event.relatedTarget.setAttribute('data-requestProlog', requestProlog);\n request.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);\n request.body = request.body.startsWith("{\\"") || request.body.startsWith("[{\\"")\n ? JSON.parse(request.body) : request.body;\n }\n if (responseProlog) {\n event.relatedTarget.setAttribute('data-responseProlog', responseProlog);\n response.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);\n response.body = response.body.startsWith("{\\"") || response.body.startsWith("[{\\"")\n ? JSON.parse(response.body) : response.body;\n }\n window.requestBeingEdited = event.relatedTarget;\n window.uniqueHashEditor.set(request);\n window.responseEditor.set(response);\n document.getElementById('edit-request-label').innerText = "Edit request to " + request.url;\n})\n\netTimeout(() => {\n loadMocks(${JSON.stringify([...t.mockConfig.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t}))))});\n window.uniqueHashEditor = new JSONEditor(document.getElementById("uniqueHash-editor"), {\n mode: "code", allowSchemaSuggestions: true, schema: {\n type: "object",\n properties: {\n method: {type: "string"},\n url: {type: "string"},\n body: {oneOf: [{type:"string"},{type:"object"},{type:"array"}]},\n headers: {type: "object"},\n },\n required: [],\n additionalProperties: false\n }});\n window.responseEditor = new JSONEditor(document.getElementById("response-editor"), {\n mode: "code", allowSchemaSuggestions: true, schema: {\n type: "object",\n properties: {\n body: {oneOf: [{type:"string"},{type:"object"},{type:"array"}]},\n headers: {type: "object"},\n status: {type: "integer"}\n },\n required: [],\n additionalProperties: false\n }});\n ${t.mockConfig.autoRecord?";document.getElementById('strict-mock-mode-form-control').style.filter='blur(8px)';;document.getElementById('table-access').style.filter='blur(8px)';":""}\n document.forms[0].reset();\n}, 10)\n<\/script>\n</form>\n<div class="alert alert-warning" role="alert"\n style="display:${t.mockConfig.autoRecord?"block":"none"};left:20%;right:20%;position:absolute;z-index:1;" id="alert-about-auto-record-mode">\n ⓘ Auto-record mode and recorder webapp are known to be mutually exclusive.\n <br/><br/>Changing the mocks on both sides is somehow hard to sort out.\n <br/>This is triggering concurrent modifications in the mock config.\n <hr/>\n Here is what you can do :\n <ul>\n <li>If you want to record mocks using a frontend app, turn off the auto-record mode.</li>\n <li>If you want to record mocks with the recorder API only, close this app.</li>\n </ul>\n</div>\n${I(e,t.config,{captureResponseBody:!0})}\n</body>\n</html>`)}},N=Object.keys(T),L=N.map((e=>`${e}:`)),j={mapping:Object.assign({},...N.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,logAccessInTerminal:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},A=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(b,((n,o)=>{n&&!e&&k(null,"config error. Using default value",m.ERROR,g.ERROR_1);let r=null;try{r=Object.assign({},j,JSON.parse((o||"{}").toString()))}catch(e){return k({config:r},"config syntax incorrect, aborting",m.ERROR,g.ERROR_2),r=null!=r?r:Object.assign({},j),void t(r)}r.mapping[""]||k({config:r},'default mapping "" not provided.',m.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&b===y?(0,a.writeFile)(b,JSON.stringify(j,null,2),(e=>{e?k(null,"config file NOT created",m.ERROR,g.ERROR_4):k(null,"config file created",m.INFO,g.COLORED),t(r)})):t(r)}))))}));exports.load=A;const P=e=>""==e?"":(0,c.normalize)(e).replace(/\\/g,"/"),H="https://cdn.jsdelivr.net/npm/",U=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],D=(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="${H}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${H}jquery/dist/jquery.min.js"><\/script>\n<script src="${H}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,c.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,a.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,a.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,a.lstat)((0,c.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=`${D(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"/")}</i></p><ul class="list-group"><li class="list-group-item">📁<a href="${e.pathname.endsWith("/")?"..":"."}"><parent></a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}},F=(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}}),J=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?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 r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\xFF]/.test(e.toString()))?_(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=J;const _=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>L.some((e=>s.startsWith(e)))||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(s.replace(new RegExp(`^(file|${N.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=_;const K=e=>{try{const t="object"==typeof e?e:JSON.parse(Buffer.from(e,"base64").toString("utf-8"));return["access-control-max-age","authorization","cache-control","cookie","date","dnt","expires","if-modified-since","if-unmodified-since","keep-alive","last-modified","pragma","proxy-authenticate","proxy-authorization","referer","retry-after","signed-headers","server-timing","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform","sec-fetch-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","upgrade-insecure-requests","user-agent"].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=K;const z=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=z;const G=(e,t)=>{var n,o,r,s,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(s=t.port)&&void 0!==s?s:8080}`:""}`,d=new i.URL(`http${t.ssl?"s":""}://${c}${e.url}`),u=d.href.substring(d.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(P("string"==typeof t?t:t.downstreamUrl))})))));let m;const[g,h]=null!==(a=Object.entries(p).find((([e])=>m=u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[],f=m?new i.URL(h.href.replace(/\$\$(\d+)/g,((e,t)=>m[parseInt(t)]))):null;return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:u,key:g,target:f}};exports.determineMapping=G;const Y=function(e,t,n){var o,a,l,c;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:d,target:u,path:p,url:h}=G(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=w(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",m.WARNING,g.ERROR_4)}Q(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const f=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),y={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},b="https:"===f.protocol?(0,s.request)(y):(0,r.request)(y);b.end(),b.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),b.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=Y;const X=function(e,n,a){var l,c,p,y,O;return t(this,void 0,void 0,(function*(){if(!n.headers.host&&!n.headers[":authority"])return void z(400,a,Buffer.from(q(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:k,url:R,path:w,key:E,target:S}=G(n,e.config);if(!S)return void z(502,a,Buffer.from(q(new Error(`No mapping found in config file ${b}`),e.mode,"proxy",R)));const $=S.host.replace(RegExp(/\/+$/),""),C=`${S.href.substring(8+S.host.length)}${P(w.replace(RegExp(P(E)),""))}`.replace(/^\/*/,"/"),x=new i.URL(`${S.protocol}//${$}${C}`),I=L.some((e=>S.protocol===e));let B=null,N=!e.config.dontUseHttp2Downstream;const j=N&&!I&&"file:"!==S.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(x,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:S.protocol},((e,o)=>{N=N&&!!o.alpnProtocol,t(N?n:null)}));n.on("error",(t=>{B=N&&Buffer.from(q(t,e.mode,"connection",R,x))}))})),new Promise((t=>setTimeout((()=>{N=!1,t(null)}),e.config.connectTimeout)))])),A=(0,d.randomBytes)(20).toString("hex");let H=null;const D=e.config.replaceRequestBodyUrls||e.logsListeners.length,F=null==n?void 0:n.readableLength,Y=null===(l=null==n?void 0:n.stream)||void 0===l?void 0:l.readableLength,X=!((e.config.ssl&&0===Y||!e.config.ssl&&0===F)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(D){const o=null!==(c=null==n?void 0:n.stream)&&void 0!==c?c:n;let r=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{X?(o.on("data",(e=>{r=Buffer.concat([r,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),X&&!r.length&&e.log(`body replacement error ${w.slice(-17)}`,m.WARNING,g.ERROR_4),H=e.config.replaceRequestBodyUrls?yield J(r,n.headers,{proxyHostnameAndPort:k,proxyHostname:t,key:E,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):r}const Z=e.logsListeners.some((e=>e.wantsResponseMessage)),V=e.mockConfig.autoRecord&&e.mode===f.PROXY,Q=K({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:e.mode===f.MOCK||Z||V?null==H?void 0:H.toString("base64"):""}),ee="file:"===S.protocol;e.notifyLogsListeners({level:"info",protocol:N?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:w,downstreamPath:x.href,randomId:A,uniqueHash:Q}),e.config.logAccessInTerminal&&!x.pathname.startsWith("/:/")&&e.log(e.config.simpleLogs?`${n.method} ${x.pathname}`:`[48;5;${"GET"===n.method?"22":"POST"===n.method?"52":"PUT"===n.method?"94":"DELETE"===n.method?"244":"OPTIONS"===n.method?"19":"PATCH"===n.method?"162":"HEAD"===n.method?"53":"TRACE"===n.method?"6":"CONNECT"===n.method?"2":"0"}m⎸${n.method.toString().padStart(7)} [48;5;8m⎸${x.pathname.toString().padStart(40).substring(0,40)}⎹[0m`);const te=e.mode===f.MOCK&&(!I||ee),ne=e.mockConfig.mocks.get(Q);if(te&&!ne&&e.mockConfig.strict)return void z(502,a,Buffer.from(q(new Error("No corresponding mock found in the server. \n Try switching back to the proxy mode"),e.mode,"mock",R)));const oe=v(),re=te&&ne?M({response:ne}):ee?W(x):I?T[S.protocol.replace(/:$/,"")](k,e,n):N?j:null;B instanceof Buffer||(B=null);const se=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!U.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(R.hostname,$))).join(", "),e)),{})),{origin:S.href,referer:x.toString(),"content-length":null!==(y=null!==(p=null==H?void 0:H.length)&&void 0!==p?p:n.headers["content-length"])&&void 0!==y?y:0,":authority":$,":method":n.method,":path":C,":scheme":S.protocol.replace(":","")}),ie=re&&!B&&re.request(se,{endStream:e.config.ssl?!(null==Y||Y):!F});"object"==typeof ie&&(null==ie||ie.on("error",(t=>{const n=-505===t.errno;B=Buffer.from(q(t,e.mode,"stream"+(n?" (error -505 usually means that the downstream service does not support this http version)":""),R,x))})));const ae={hostname:S.hostname,path:C,port:S.port,protocol:S.protocol,rejectUnauthorized:!1,method:n.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(se).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:S.hostname})},le=!B&&!N&&!["file:",...L].includes(S.protocol)&&(yield new Promise((t=>{const o="https:"===S.protocol?(0,s.request)(ae,t):(0,r.request)(ae,t);o.on("error",(n=>{B=Buffer.from(q(n,e.mode,"request",R,x)),t(null)})),D&&(o.write(H),o.end()),D||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(B)return void z(502,a,B);B=null,Y&&ie&&!D?(n.stream.on("data",(e=>{ie.write(e)})),n.stream.on("end",(()=>ie.end()))):F&&ie&&!D?(n.on("data",(e=>{ie.write(e)})),n.on("end",(()=>ie.end()))):ie&&D&&X&&(ie.write(H),ie.end());const{outboundResponseHeaders:ce}=yield new Promise((e=>ie?ie.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!ie&&le?{outboundResponseHeaders:le.headers}:{outboundResponseHeaders:{}})));let de=null;try{ce.location&&(de=new i.URL(ce.location.startsWith("/")?`${S.origin}${ce.location.replace(/^\/+/,"/")}`:ce.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(O=ce.location)&&void 0!==O?O:"").slice(-13)}`,m.WARNING,g.ERROR_4)}const ue=e.config.replaceResponseBodyUrls&&de?new i.URL(_(de.href,{direction:h.INBOUND,proxyHostnameAndPort:k,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${L.join("|")}|file:)/+`),"")):de,pe=de?ue.origin!==de.origin||e.config.dontTranslateLocationHeader?ue:`${R.origin}${ue.href.substring(ue.origin.length)}`:de,me=ie||le,ge=null!=B?B:yield new Promise((e=>{let t=Buffer.alloc(0);me?(me.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),me.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?L.some((e=>S.protocol===e))?n:J(n,ce,{proxyHostnameAndPort:k,proxyHostname:t,key:E,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((t=>(z(502,a,Buffer.from(q(t,e.mode,"stream",R,x))),Buffer.from("")))):n)),he=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},ce),e.config.replaceResponseBodyUrls?{"content-length":`${ge.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(":")&&!U.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=$.split("").map(((e,t)=>$.substring(t).startsWith(".")&&$.substring(t))).filter((e=>e)),r=[$].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${R.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),pe?{location:[pe]}:{});try{Object.entries(he).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const fe=ce[":status"]||le.statusCode||200;try{a.writeHead(fe,e.config.ssl?void 0:le.statusMessage||"Status read from http/2",he)}catch(e){}ge?a.end(ge):a.end();const ye=v(),be=Z||V?Buffer.from(JSON.stringify({body:null==ge?void 0:ge.toString("base64"),headers:ce,status:fe})).toString("base64"):"";e.notifyLogsListeners({randomId:A,statusCode:fe,protocol:N?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(ye-oe)/1e6),uniqueHash:Q,response:be}),!V||e.config.logAccessInTerminal||I||(e.mockConfig.mocks.set(Q,be),u.stdout.moveCursor(0,-1,(()=>u.stdout.clearLine(-1,e.quickStatus))))}))};exports.serve=X;const Z=(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=Z;const V=e=>Q({config:Object.assign(Object.assign({},j),e)},{});exports.start=V;const Q=(e,n)=>t(void 0,void 0,void 0,(function*(){var s,i,l,c,d,u,p,h,y,v,O,R,w,E,C,q,I,B,T,N,L,j,P;if(0===Object.keys(null!=n?n:{}).length&&e.server)return;if(n.pendingConfigSave)return void(0,a.writeFile)(b,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!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(i=e.logsListeners)&&void 0!==i?i:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const H=null!==(l=n.config)&&void 0!==l?l:e.config,U=null!==(d=null!==(c=n.mode)&&void 0!==c?c:e.mode)&&void 0!==d?d:f.PROXY,D=null!==(y=null!==(p=null===(u=n.mockConfig)||void 0===u?void 0:u.autoRecord)&&void 0!==p?p:null===(h=e.mockConfig)||void 0===h?void 0:h.autoRecord)&&void 0!==y&&y,M=null!==(w=null!==(O=null===(v=n.mockConfig)||void 0===v?void 0:v.strict)&&void 0!==O?O:null===(R=e.mockConfig)||void 0===R?void 0:R.strict)&&void 0!==w&&w,W=null!==(I=null!==(C=null===(E=n.mockConfig)||void 0===E?void 0:E.mocks)&&void 0!==C?C:null===(q=e.mockConfig)||void 0===q?void 0:q.mocks)&&void 0!==I?I:new Map,F=(null===n.configListeners?[]:null!==(T=null!==(B=n.configListeners)&&void 0!==B?B:e.configListeners)&&void 0!==T?T:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),J=(null===n.logsListeners?[]:null!==(L=null!==(N=n.logsListeners)&&void 0!==N?N:e.logsListeners)&&void 0!==L?L:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),_=e;return Object.assign(_,{config:H,logsListeners:J,configListeners:F,mode:U,mockConfig:{mocks:W,strict:M,autoRecord:D},configFileWatcher:void 0===_.configFileWatcher?(0,a.watchFile)(b,(()=>t(void 0,void 0,void 0,(function*(){return Q(_,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield A(!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.logAccessInTerminal!==t.logAccessInTerminal&&e.log("access terminal logging "+(n.logAccessInTerminal?"on":"off"),m.INFO,g.LOGS),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}))}))}(_))})))):_.configFileWatcher,log:k.bind(_,_),notifyConfigListeners:S.bind(_),notifyLogsListeners:$.bind(_),quickStatus:x.bind(_),server:null!==n.server&&_.server||(null!==(P=null===(j=n.config)||void 0===j?void 0:j.port)&&void 0!==P?P:0)<0?null===n.server?null:_.server:(H.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},H.ssl),{allowHTTP1:!0})):r.createServer)(((e,t)=>X(_,e,t))).addListener("error",(e=>Z(_,e))).addListener("listening",(()=>_.quickStatus())).on("upgrade",((e,t)=>Q(_,Y(_,e,t)))).listen(H.port)}),_}));exports.update=Q;const ee=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:"",te=ee.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!ee.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),ne=u.argv.some((e=>"--crash-test"===e));if(ne){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,r.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();Q({config:Object.assign(Object.assign({},j),{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"):Q(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):k(e,"Crash test successful",m.INFO,g.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!ne&&te&&A().then(V);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-traffic",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.90",
|
|
4
4
|
"main": "./dist/local-traffic.js",
|
|
5
5
|
"private": false,
|
|
6
6
|
"keywords": [
|
|
@@ -30,9 +30,9 @@
|
|
|
30
30
|
"test": "node ./test/tests.spec.mjs"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@types/node": "^20.
|
|
34
|
-
"terser": "^5.
|
|
35
|
-
"typescript": "^5.
|
|
33
|
+
"@types/node": "^20.10.3",
|
|
34
|
+
"terser": "^5.25.0",
|
|
35
|
+
"typescript": "^5.3.2"
|
|
36
36
|
},
|
|
37
37
|
"bin": {
|
|
38
38
|
"local-traffic": "dist/local-traffic.js"
|