@neuralegion/cypress-har-generator
Version:
The Cypress plugin for generating HTTP Archive (HAR) files is a tool that allows developers and QA engineers to capture detailed information about network requests made during the execution of Cypress tests.
2 lines • 47.8 kB
JavaScript
(()=>{"use strict";var e={330:e=>{e.exports=JSON.parse('{"name":"@neuralegion/cypress-har-generator","version":"5.17.1","private":false,"description":"The Cypress plugin for generating HTTP Archive (HAR) files is a tool that allows developers and QA engineers to capture detailed information about network requests made during the execution of Cypress tests.","repository":{"type":"git","url":"git+https://github.com/NeuraLegion/cypress-har-generator.git"},"main":"dist/index.js","typings":"dist/index.d.ts","files":["dist","commands.js","commands.js.map"],"author":{"name":"Artem Derevnjuk","email":"artem.derevnjuk@neuralegion.com"},"license":"MIT","bugs":{"url":"https://github.com/NeuraLegion/cypress-har-generator/issues"},"publishConfig":{"access":"public"},"keywords":["cypress","har","electron","cypress-plugin","chrome","http-archive","testing","qa","automation","typescript","chromium","qatools"],"scripts":{"semantic-release":"semantic-release","lint":"eslint -c .eslintrc.js \'src/**/*.ts\'","format":"prettier --check \'src/**/*.ts\'","test":"jest","test:watch":"jest --watch","test:cov":"jest --coverage","start":"node -r ts-node/register cypress/app --port 8080","e2e":"cypress run --browser chrome --headless","build":"webpack --config webpack.config.ts","prepublishOnly":"npm run build","prepare":"is-ci || husky install"},"homepage":"https://github.com/NeuraLegion/cypress-har-generator#readme","devDependencies":{"@commitlint/cli":"^17.1.2","@commitlint/config-conventional":"^17.1.0","@jest/globals":"^29.7.0","@semantic-release/exec":"^6.0.3","@semantic-release/git":"^10.0.1","@types/chai-like":"^1.1.1","@types/chai-things":"^0.0.35","@types/express":"^4.17.15","@types/har-format":"^1.2.8","@types/jest":"^29.5.12","@types/node":"~18.19.50","@types/webpack":"^5.28.0","@types/webpack-node-externals":"^2.5.3","@types/ws":"^8.5.4","@typescript-eslint/eslint-plugin":"^5.36.2","@typescript-eslint/parser":"^5.36.2","chai-like":"^1.1.1","chai-things":"^0.2.0","cypress":"^13.14.2","devtools-protocol":"~0.0.1040073","eslint":"^8.23.0","eslint-config-prettier":"^8.5.0","eslint-import-resolver-typescript":"^3.5.1","eslint-plugin-import":"^2.26.0","eslint-plugin-prettier":"^4.2.1","express":"^4.18.2","filemanager-webpack-plugin":"^7.0.0","hbs":"^4.2.0","husky":"^8.0.1","is-ci":"^3.0.1","jest":"^29.7.0","lint-staged":"^13.0.3","minimist":"^1.2.7","prettier":"~2.8.4","semantic-release":"^24.1.0","ts-jest":"^29.2.5","ts-loader":"^9.3.1","ts-mockito":"^2.6.1","ts-node":"~10.9.1","tsconfig-paths":"^4.1.0","typescript":"~4.8.2","webpack":"^5.74.0","webpack-cli":"^4.10.0","webpack-node-externals":"^3.0.0","ws":"^8.12.0"},"commitlint":{"extends":["@commitlint/config-conventional"]},"lint-staged":{"*.ts":["eslint --fix"],"*.{ts,js,json,md}":["prettier --write"]},"peerDependencies":{"cypress":">=4.4.1 <12.12.0 || >=12.17.0"},"dependencies":{"chalk":"^4.1.2","chrome-remote-interface":"~0.33.2","tslib":"^2.4.0"}}')}},t={};function s(r){var i=t[r];if(void 0!==i)return i.exports;var n=t[r]={exports:{}};return e[r](n,n.exports,s),n.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};s.r(r),s.d(r,{enableExperimentalLifecycle:()=>J,ensureBrowserFlags:()=>K,install:()=>X});const i=require("tslib");class n{constructor(e){this.request=e}build(){var e,t;return(0,i.__awaiter)(this,void 0,void 0,(function*(){let s=this.request.remoteAddress;const r=s.lastIndexOf(":");-1!==r&&(s=s.substr(0,r));const i=this.buildTimings(),n=Object.values(i).reduce(((e,t)=>e+Math.max(t,0)),0),o={startedDateTime:new Date(1e3*this.request.getWallTime(this.request.issueTime)).toJSON(),time:n,timings:i,request:yield this.buildRequest(),response:yield this.buildResponse(),cache:{},serverIPAddress:s.replace(/[[\]]/g,""),_priority:this.request.priority,_resourceType:this.request.resourceType,_webSocketMessages:null!==(e=this.request.frames)&&void 0!==e?e:[],_eventSourceMessages:null!==(t=this.request.eventSourceMessages)&&void 0!==t?t:[]};return"0"!==this.request.connectionId&&(o.connection=this.request.connectionId),o}))}getResponseBodySize(){return 304===this.request.statusCode?0:this.request.responseHeadersText?this.request.transferSize-this.request.responseHeadersText.length:-1}getResponseCompression(){if(304!==this.request.statusCode&&206!==this.request.statusCode&&this.request.responseHeadersText)return this.request.resourceSize-this.getResponseBodySize()}toMilliseconds(e){return-1===e?-1:1e3*e}buildRequest(){var e,t,s,r;return(0,i.__awaiter)(this,void 0,void 0,(function*(){const i={method:this.request.requestMethod,url:this.buildRequestURL(this.request.url),httpVersion:this.request.requestHttpVersion,headers:this.request.requestHeaders,queryString:[...null!==(e=this.request.queryParameters)&&void 0!==e?e:[]],cookies:this.buildCookies(null!==(t=this.request.requestCookies)&&void 0!==t?t:[]),headersSize:null!==(r=null===(s=this.request.requestHeadersText)||void 0===s?void 0:s.length)&&void 0!==r?r:-1,bodySize:yield this.requestBodySize()},n=yield this.buildPostData();return n&&(i.postData=n),i}))}buildResponse(){var e,t,s;return(0,i.__awaiter)(this,void 0,void 0,(function*(){return{status:this.request.statusCode,statusText:this.request.statusText,httpVersion:this.request.responseHttpVersion(),headers:this.request.responseHeaders,cookies:this.buildCookies(this.request.responseCookies||[]),content:yield this.buildContent(),redirectURL:null!==(e=this.request.responseHeaderValue("Location"))&&void 0!==e?e:"",headersSize:null!==(s=null===(t=this.request.responseHeadersText)||void 0===t?void 0:t.length)&&void 0!==s?s:-1,bodySize:this.getResponseBodySize(),_transferSize:this.request.transferSize}}))}buildContent(){var e;return(0,i.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.request.contentData();return Object.assign({size:this.request.resourceSize,mimeType:this.request.mimeType||"x-unknown",compression:null!==(e=this.getResponseCompression())&&void 0!==e?e:void 0},t)}))}buildTimings(){var e;const t=this.request.timing,s=this.request.issueTime,r=this.request.startTime,i={blocked:-1,dns:-1,ssl:-1,connect:-1,send:0,wait:0,receive:0},n=s<r?r-s:-1;i.blocked=this.toMilliseconds(n);let o=0;if(t){const e=this.leastNonNegative([t.dnsStart,t.connectStart,t.sendStart]);e!==1/0&&(i.blocked+=e);const s=t.dnsEnd>=0?e:0,r=t.dnsEnd>=0?t.dnsEnd:-1;i.dns=r-s;const n=t.sslEnd>0?t.sslStart:0,a=t.sslEnd>0?t.sslEnd:-1;i.ssl=a-n;const u=t.connectEnd>=0?this.leastNonNegative([r,e]):0,d=t.connectEnd>=0?t.connectEnd:-1;i.connect=d-u;const h=t.sendEnd>=0?Math.max(d,r,e):0,l=t.sendEnd>=0?t.sendEnd:0;i.send=l-h,i.send<0&&(i.send=0),o=Math.max(l,d,a,r,e,0)}else if(-1===this.request.responseReceivedTime)return i.blocked=this.request.endTime-s,i;const a=null!==(e=null==t?void 0:t.requestTime)&&void 0!==e?e:r,u=o,d=this.toMilliseconds(this.request.responseReceivedTime-a);i.wait=d-u;const h=d,l=this.toMilliseconds(this.request.endTime-a);return i.receive=Math.max(l-h,0),i}leastNonNegative(e){const t=e.find((e=>e>=0));return null!=t?t:-1}buildPostData(){var e;return(0,i.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.request.requestFormData();if(!t)return;const s={mimeType:null!==(e=this.request.requestContentType)&&void 0!==e?e:"",text:t},r=yield this.request.formParameters();return r&&(s.params=[...r]),s}))}buildRequestURL(e){return e.split("#",2)[0]}buildCookies(e){return e.map(this.buildCookie.bind(this))}buildCookie(e){var t;return{name:e.name,value:e.value,path:e.path,domain:e.domain,expires:null===(t=e.expiresDate(new Date(1e3*this.request.getWallTime(this.request.startTime))))||void 0===t?void 0:t.toJSON(),httpOnly:e.httpOnly,secure:e.secure}}requestBodySize(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){return(yield this.request.requestFormData())?this.request.contentLength:0}))}}class o{static isError(e){return e instanceof Error}}const a=require("os"),u=require("util");class d{constructor(e,t,s){this.logger=e,this.buffer=t,this.options=s}get path(){const{path:e}=this.buffer;return Buffer.isBuffer(e)?e.toString("utf-8"):e}get filter(){var e;return null===(e=this.options)||void 0===e?void 0:e.filter}get transform(){var e;return null===(e=this.options)||void 0===e?void 0:e.transform}write(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const t=yield new n(e).build();if(yield this.applyFilter(t))return;const s=yield this.serializeEntry(t);!this.buffer.closed&&s&&(yield(0,u.promisify)(this.buffer.write).call(this.buffer,`${s}${a.EOL}`))}))}serializeEntry(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{const t="function"==typeof this.transform?yield this.transform(e):e;return JSON.stringify(t)}catch(t){const s=o.isError(t)?t.stack:t;return this.logger.debug((0,u.format)("The entry has been filtered out due to an error: %j",e)),void this.logger.err(`The entry is missing as a result of an error in the 'transform' function.\n\nThe stack trace for this error is:\n${s}`)}}))}end(){this.buffer.end()}applyFilter(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{return"function"==typeof this.filter&&(yield this.filter(e))}catch(e){const t=o.isError(e)?e.message:e;return this.logger.debug(`The operation has encountered an error while processing the entry. ${t}`),!1}}))}}class h{static load(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){let t;try{t=require(e)}catch(s){if(!this.shouldUseDynamicImport(s))throw s;t=(yield import(e)).default}return this.interopRequireDefault(t)}))}static shouldUseDynamicImport(e){const t=o.isError(e)?e.stack:void 0;return!(!(null==t?void 0:t.includes("[ERR_REQUIRE_ESM]"))&&!(null==t?void 0:t.includes("SyntaxError: Cannot use import statement outside a module")))}static interopRequireDefault(e){return e&&e.__esModule&&e.default?e.default:e}}const l=require("path");var c,p;!function(e){e.NAME="name",e.VALUE="value",e.SIZE="size",e.DOMAIN="domain",e.PORT="port",e.PATH="path",e.EXPIRES="expires",e.HTTPONLY="httponly",e.SECURE="secure",e.SAMESITE="samesite",e.MAXAGE="max-age"}(c||(c={}));class m{constructor(e,t){this._attributes=new Map,this._size=0,this._name=e,this._value=t}get size(){return this._size}set size(e){this._size=e}get name(){return this._name}get value(){return this._value}get httpOnly(){return this._attributes.has(c.HTTPONLY)}get secure(){return this._attributes.has(c.SECURE)}get sameSite(){return this._attributes.get(c.SAMESITE)}get session(){return!(this._attributes.has(c.EXPIRES)||this._attributes.has(c.MAXAGE))}get path(){return this._attributes.get(c.PATH)}get port(){return this._attributes.get(c.PORT)}get domain(){return this._attributes.get(c.DOMAIN)}get expires(){return this._attributes.get(c.EXPIRES)}get maxAge(){var e;const t=null!==(e=this._attributes.get(c.MAXAGE))&&void 0!==e?e:"";return isNaN(+t)?void 0:+t}get url(){return(this.secure?"https://":"http://")+this.domain+this.path}expiresDate(e){if(this.maxAge){const t=null===e?new Date:e;return new Date(t.getTime()+1e3*this.maxAge)}if(this.expires)return new Date(this.expires)}addAttribute(e,t){this._attributes.set(e.toLowerCase(),t)}}class g{constructor(){this._lastCookiePosition=0}parseCookie(e){this._initialize(e);for(let e=this._extractKeyValue();e;e=this._extractKeyValue())"$"===e.key.charAt(0)&&this._lastCookie?this._lastCookie.addAttribute(e.key.slice(1),e.value):"$version"!==e.key.toLowerCase()&&"string"==typeof e.value&&this.addCookie(e),this.advanceAndCheckCookieDelimiter();return this.flushCookie(),this._cookies}parseSetCookie(e){this._initialize(e);for(let e=this._extractKeyValue();e;e=this._extractKeyValue())this._lastCookie?this._lastCookie.addAttribute(e.key,e.value):this.addCookie(e),this.advanceAndCheckCookieDelimiter()&&this.flushCookie();return this.flushCookie(),this._cookies}_initialize(e){this._input=e,this._cookies=[],this._lastCookie=void 0,this._originalInputLength=this._input.length}flushCookie(){this._lastCookie&&(this._lastCookie.size=this._originalInputLength-this._input.length-this._lastCookiePosition),delete this._lastCookie}_extractKeyValue(){var e,t;if(!(null===(e=this._input)||void 0===e?void 0:e.length))return;const s=/^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/i.exec(this._input);if(!s)return;const r={key:this.toCamelCase(s[1]),value:null===(t=s[2])||void 0===t?void 0:t.trim(),position:this._originalInputLength-this._input.length};return this._input=this._input.slice(s[0].length),r}toCamelCase(e){return e.replace(/\s(.)/g,(e=>e.toUpperCase())).replace(/\s/g,"").replace(/^(.)/,(e=>e.toLowerCase()))}advanceAndCheckCookieDelimiter(){const e=/^\s*[\n;]\s*/.exec(this._input);return!!e&&(this._input=this._input.slice(e[0].length),null!==e[0].match("\n"))}addCookie(e){this._lastCookie&&(this._lastCookie.size=e.position-this._lastCookiePosition),this._lastCookie="string"==typeof e.value?new m(e.key,e.value):new m("",e.key),this._lastCookiePosition=e.position,this._cookies.push(this._lastCookie)}}class f{static isString(e){return"string"==typeof e}static toRegexSource(e){return this.isString(e)?e:e.source}static toRegex(e){return this.isString(e)?new RegExp(e):e}static dirname(e){const t=this.removeTrailingSlash(e),s=this.fileNameIdx(t),r=t.substring(0,s);return this.removeTrailingSlash(r)}static normalizeName(e,t){var s;const r=this.fileNameIdx(e),i=this.removeLeadingSlash(e.substring(r)),n=i.lastIndexOf(".");let o,a=i;return n>=0&&(o=null!==(s=null==t?void 0:t.ext)&&void 0!==s?s:i.substring(n),a=i.substring(0,n)),`${a}${null!=o?o:".har"}`}static escapeCharacters(e,t="^[]{}()\\\\.$*+?|"){let s=!1;const r=t.length;for(let i=0;i<r;++i)if(-1!==e.indexOf(t.charAt(i))){s=!0;break}if(!s)return e;let i="";for(let s=0;s<e.length;++s)-1!==t.indexOf(e.charAt(s))&&(i+="\\"),i+=e.charAt(s);return i}static fileNameIdx(e){return e.indexOf("\\")>=0?e.lastIndexOf("\\"):e.lastIndexOf("/")}static removeLeadingSlash(e){return e.replace(/^\/|^\\/,"")}static removeTrailingSlash(e){return e.replace(/\/+$|\\+$/,"")}}!function(e){e.REQUEST="request",e.RESPONSE="response",e.ERROR="error"}(p||(p={}));class _{constructor(e,t,s,r,i,n=""){this._requestId=e,this.documentURL=s,this.loaderId=r,this.initiator=i,this.frameId=n,this._wallIssueTime=-1,this._requestHeaderValues=new Map,this._responseHeaderValues=new Map,this._requestFormData=Promise.resolve(void 0),this._hasExtraResponseInfo=!1,this._hasExtraRequestInfo=!1,this._connectionId="0",this._protocol="",this._requestTime=0,this._requestMethod="",this._statusText="",this._remoteAddress="",this._startTime=-1,this._issueTime=-1,this._endTime=-1,this._responseReceivedTime=-1,this._resourceSize=0,this._transferSize=0,this._resourceType="Other",this._requestHeaders=[],this._requestHeadersText="",this._connectionReused=!1,this._responseHeaders=[],this._responseHeadersText="",this._eventSourceMessages=[],this._frames=[],this._statusCode=0,this.url=t}get signedExchangeInfo(){return this._signedExchangeInfo}set signedExchangeInfo(e){this._signedExchangeInfo=e}get hasExtraResponseInfo(){return this._hasExtraResponseInfo}set hasExtraResponseInfo(e){this._hasExtraResponseInfo=e}get hasExtraRequestInfo(){return this._hasExtraRequestInfo}set hasExtraRequestInfo(e){this._hasExtraRequestInfo=e}get connectionId(){return this._connectionId}set connectionId(e){this._connectionId=e}get protocol(){return this._protocol}set protocol(e){this._protocol=null!=e?e:""}get requestTime(){return this._requestTime}set requestTime(e){this._requestTime=null!=e?e:0}get requestMethod(){return this._requestMethod}set requestMethod(e){this._requestMethod=null!=e?e:""}get statusText(){return this._statusText}set statusText(e){this._statusText=null!=e?e:""}get parsedURL(){return this._parsedURL}get url(){return this._url}set url(e){this._url!==e&&(this._url=e,this._parsedURL=new URL(e),delete this._queryString,delete this._parsedQueryParameters)}get remoteAddress(){return this._remoteAddress}get startTime(){return this._startTime||-1}get issueTime(){return this._issueTime}get endTime(){return this._endTime||-1}set endTime(e){this.timing&&this.timing.requestTime?this._endTime=Math.max(e,this.responseReceivedTime):(this._endTime=e,this._responseReceivedTime>e&&(this._responseReceivedTime=e))}get responseReceivedTime(){return this._responseReceivedTime||-1}set responseReceivedTime(e){this._responseReceivedTime=e}get resourceSize(){return this._resourceSize||0}set resourceSize(e){this._resourceSize=null!=e?e:0}get transferSize(){return this._transferSize||0}set transferSize(e){this._transferSize=null!=e?e:0}get timing(){return this._timing}set timing(e){if(!e)return;this._startTime=e.requestTime;const t=e.requestTime+e.receiveHeadersEnd/1e3;((this._responseReceivedTime||-1)<0||this._responseReceivedTime>t)&&(this._responseReceivedTime=t),this._startTime>this._responseReceivedTime&&(this._responseReceivedTime=this._startTime),this._timing=e}get mimeType(){return this._mimeType}set mimeType(e){this._mimeType=e}get resourceType(){return this._resourceType}set resourceType(e){this._resourceType=null!=e?e:"Other"}get redirectSource(){return this._redirectSource}set redirectSource(e){this._redirectSource=e}get requestHeaders(){return this._requestHeaders}set requestHeaders(e){this._requestHeaders=e,this._requestHeaderValues.clear(),delete this._requestCookies}get requestCookies(){if(!this._requestCookies){const e=this.requestHeaderValue("Cookie");this._requestCookies=e?(new g).parseCookie(e):void 0}return this._requestCookies}get contentLength(){const e=this.requestHeaderValue("Content-Length");return null==e||isNaN(+e)?0:parseInt(e,10)}get requestHeadersText(){return this._requestHeadersText}set requestHeadersText(e){this._requestHeadersText=e}get connectionReused(){return this._connectionReused}set connectionReused(e){this._connectionReused=e}get responseHeaders(){return this._responseHeaders||[]}set responseHeaders(e){this._responseHeaders=e,delete this._responseCookies,this._responseHeaderValues.clear()}get responseHeadersText(){return this._responseHeadersText}set responseHeadersText(e){this._responseHeadersText=e}get responseCookies(){if(!this._responseCookies){const e=this.responseHeaderValue("Set-Cookie");this._responseCookies=e?(new g).parseSetCookie(e):void 0}return this._responseCookies}get queryString(){if(this._queryString||!this.url)return this._queryString;let e;const t=this.url.indexOf("?");if(-1!==t){e=this.url.substring(t+1);const s=e.indexOf("#");-1!==s&&(e=e.substring(0,s))}return this._queryString=e,this._queryString}get initialPriority(){return this._initialPriority}set initialPriority(e){this._initialPriority=e}get eventSourceMessages(){return this._eventSourceMessages}get frames(){return this._frames}get statusCode(){return this._statusCode}set statusCode(e){this._statusCode=e}get requestId(){return this._requestId}get requestHttpVersion(){if(this.requestHeadersText){const e=this.requestHeadersText.split(/\r\n/)[0].match(/(HTTP\/\d+\.\d+)$/);return e?e[1]:"HTTP/0.9"}return this.requestHeaderValue("version")||this.requestHeaderValue(":version")||this.getFilteredProtocolName()}get queryParameters(){return this._parsedQueryParameters||this.queryString&&(this._parsedQueryParameters=this.parseParameters(this.queryString)),this._parsedQueryParameters}get requestContentType(){return this.requestHeaderValue("Content-Type")}get priority(){var e,t;return null!==(t=null!==(e=this._currentPriority)&&void 0!==e?e:this.initialPriority)&&void 0!==t?t:void 0}set priority(e){this._currentPriority=e}waitForCompletion(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){yield Promise.all([this._contentData,this._formParametersPromise])}))}isBlob(){return this._url.startsWith("blob:")}setRemoteAddress(e,t){this._remoteAddress=`${e}:${t}`}setIssueTime(e,t){this._issueTime=e,this._wallIssueTime=t,this._startTime=e}increaseTransferSize(e){this._transferSize=(this._transferSize||0)+e}requestFormData(){return this._requestFormData}setRequestFormData(e){this._requestFormData="string"==typeof e?Promise.resolve(e):e,this._formParametersPromise=void 0}getWallTime(e){return this._wallIssueTime?this._wallIssueTime-this._issueTime+e:e}formParameters(){return this._formParametersPromise||(this._formParametersPromise=this.parseFormParameters()),this._formParametersPromise}responseHttpVersion(){if(this._responseHeadersText){const e=this._responseHeadersText.split(/\r\n/)[0].match(/^(HTTP\/\d+\.\d+)/);return e?e[1]:"HTTP/0.9"}return this.responseHeaderValue("version")||this.responseHeaderValue(":version")||this.getFilteredProtocolName()}setContentData(e){"WebSocket"!==this.resourceType?this._contentData=e.then((({body:e,base64Encoded:t})=>({text:e,encoding:t?"base64":void 0}))).catch((e=>({error:e.message}))):this._contentData=Promise.resolve({error:"Content for WebSockets is currently not supported"})}contentData(){return this._contentData}addProtocolFrameError(e,t){this.addFrame({time:t,type:p.ERROR,data:e,opcode:-1,mask:!1})}addProtocolFrame(e,t,s){const r=s?p.REQUEST:p.RESPONSE;this.addFrame({type:r,time:t,data:e.payloadData,opcode:e.opcode,mask:e.mask})}addEventSourceMessage(e,t,s,r){const i={time:e,eventName:t,eventId:s,data:r};this._eventSourceMessages.push(i)}markAsRedirect(e){this._requestId=`${this.requestId}:redirected.${e}`}addExtraRequestInfo(e){this.requestHeaders=e.requestHeaders,this._hasExtraRequestInfo=!0,this.requestHeadersText=""}addExtraResponseInfo(e){if(this.responseHeaders=e.responseHeaders,e.responseHeadersText&&(this.responseHeadersText=e.responseHeadersText,this.requestHeadersText)){let e=`${this._requestMethod} ${this.parsedURL.pathname}`;this.parsedURL.search&&(e+=this.parsedURL.search),e+=" HTTP/1.1\r\n";for(const{name:t,value:s}of this.requestHeaders)e+=`${t}: ${s}\r\n`;this.requestHeadersText=e}this._hasExtraResponseInfo=!0}responseHeaderValue(e){if(!this._responseHeaderValues.has(e)){const t=this.computeHeaderValue(this.responseHeaders,e);t&&this._responseHeaderValues.set(e,t)}return this._responseHeaderValues.get(e)}parseFormParameters(){var e,t;return(0,i.__awaiter)(this,void 0,void 0,(function*(){if(null===(e=this.requestContentType)||void 0===e?void 0:e.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){const e=yield this.requestFormData();return e?this.parseParameters(e):[]}const s=null===(t=this.requestContentType)||void 0===t?void 0:t.match(/^multipart\/form-data\s*;\s*boundary\s*=\s*(\S+)\s*$/);if(!s)return[];const r=s[1],i=yield this.requestFormData();return r&&i?this.parseMultipartFormDataParameters(i,r):[]}))}parseMultipartFormDataParameters(e,t){const s=f.escapeCharacters(t),r=new RegExp('^\\r\\ncontent-disposition\\s*:\\s*form-data\\s*;\\s*name="([^"]*)"(?:\\s*;\\s*filename="([^"]*)")?(?:\\r\\ncontent-type\\s*:\\s*([^\\r\\n]*))?\\r\\n\\r\\n(.*)\\r\\n$',"is");return e.split(new RegExp(`--${s}(?:--s*$)?`,"g")).reduce(((e,t)=>{var s;const[i,n,o,a,u]=null!==(s=t.match(r))&&void 0!==s?s:[];return i?(e.push({name:n,value:u,fileName:o,contentType:a}),e):e}),[])}addFrame(e){this._frames.push(e)}requestHeaderValue(e){if(!this._requestHeaderValues.has(e)){const t=this.computeHeaderValue(this.requestHeaders,e);t&&this._requestHeaderValues.set(e,t)}return this._requestHeaderValues.get(e)}getFilteredProtocolName(){const e=this._protocol.toLowerCase();return"h2"===e?"http/2.0":e.replace(/^http\/2(\.0)?\+/,"http/2.0+")}parseParameters(e){return e.split("&").map((e=>{const t=e.indexOf("=");return-1===t?{name:e,value:""}:{name:e.substring(0,t),value:e.substring(t+1)}}))}computeHeaderValue(e,t){t=t.toLowerCase();const s=e.filter((({name:e})=>e.toLowerCase()===t)).map((({value:e})=>e));if(s.length)return"set-cookie"===t?s.join("\n"):s.join(", ")}}class v{constructor(e){this.deleteCallback=e,this._hasExtraInfo=!1,this._finished=!1,this._requests=[],this._requestExtraInfo=[],this._responseExtraInfo=[]}addRequest(e){this._requests.push(e),this.sync()}addRequestExtraInfo(e){this._requestExtraInfo.push(e),this._hasExtraInfo=!0,this.sync()}addResponseExtraInfo(e){this._responseExtraInfo.push(e),this.sync()}finished(){this._finished=!0,this.deleteIfComplete()}deleteIfComplete(){if(this._finished){if(this._hasExtraInfo){const e=this.getLastRequest();if(!(null==e?void 0:e.hasExtraResponseInfo))return}this.deleteCallback()}}getLastRequest(){return this._requests[this._requests.length-1]}getRequestIndex(e){return this._requests.indexOf(e)}sync(){const e=this.getLastRequest();if(!e)return;const t=this.getRequestIndex(e),s=this._requestExtraInfo[t];s&&(e.addExtraRequestInfo(s),delete this._requestExtraInfo[t]);const r=this._responseExtraInfo[t];r&&(e.addExtraResponseInfo(r),delete this._responseExtraInfo[t]),this.deleteIfComplete()}}class y{constructor(e,t,s,r){this.options=e,this.network=t,this.logger=s,this.requestFilter=r,this._entries=new Map,this._extraInfoBuilders=new Map}get empty(){return 0===this._entries.size}subscribe(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){this.destination=e,yield this.network.attachToTargets((e=>this.handleEvent(e)))}))}unsubscribe(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){yield this.network.detachFromTargets(),delete this.destination,this._entries.clear(),this._extraInfoBuilders.clear()}))}signedExchangeReceived(e){const t=this._entries.get(e.requestId);t&&(t.signedExchangeInfo=e.info,t.resourceType="SignedExchange",this.updateNetworkRequestWithResponse(t,e.info.outerResponse))}requestWillBeSent({type:e,loaderId:t,initiator:s,redirectResponse:r,documentURL:i,frameId:n,timestamp:o,requestId:a,request:u,wallTime:d}){let h=this._entries.get(a);if(h){if(!r)return;h.signedExchangeInfo||this.responseReceived({requestId:a,loaderId:t,timestamp:o,frameId:n,type:"Other",response:r}),h=this._appendRedirect(a,o,u.url)}else h=this.createRequest(a,n,t,u.url,i,s);this.updateNetworkRequestWithRequest(h,u),h.setIssueTime(o,d),h.resourceType=null!=e?e:"Other",this.getExtraInfoBuilder(a).addRequest(h),this.startRequest(h)}dataReceived({requestId:e,dataLength:t,encodedDataLength:s,timestamp:r}){const i=this._entries.get(e);i&&(i.resourceSize+=t,-1!==s&&i.increaseTransferSize(s),i.endTime=r)}responseReceived({requestId:e,response:t,timestamp:s,type:r}){const i=this._entries.get(e);i&&(i.responseReceivedTime=s,i.resourceType=r,this.updateNetworkRequestWithResponse(i,t))}resourceChangedPriority({requestId:e,newPriority:t}){const s=this._entries.get(e);s&&(s.priority=t)}loadingFinished({requestId:e,timestamp:t,encodedDataLength:s}){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const r=this._entries.get(e);r&&this.finishRequest(r,t,s)}))}loadingFailed({requestId:e,errorText:t,canceled:s,type:r,timestamp:i}){const n=this._entries.get(e);if(!n)return;n.resourceType=r,this.finishRequest(n,i,-1);const o=t||s&&"Canceled";this.logger.debug(`Failed request: ${e}. Reason: ${o}`)}webSocketCreated({initiator:e,requestId:t,url:s}){const r=this.createRequest(t,"","",s,"",e);this.startRequest(r)}eventSourceMessageReceived({requestId:e,timestamp:t,eventName:s,eventId:r,data:i}){const n=this._entries.get(e);n&&n.addEventSourceMessage(t,s,r,i)}webSocketWillSendHandshakeRequest({request:e,requestId:t,timestamp:s,wallTime:r}){const i=this._entries.get(t);i&&(i.requestMethod="GET",i.requestHeaders=this.headersMapToHeadersArray(e.headers),i.setIssueTime(s,r))}webSocketHandshakeResponseReceived({timestamp:e,response:t,requestId:s}){const r=this._entries.get(s);r&&(r.statusCode=t.status,r.statusText=t.statusText,r.responseHeaders=this.headersMapToHeadersArray(t.headers),r.responseHeadersText=t.headersText||"",t.requestHeaders&&(r.requestHeaders=this.headersMapToHeadersArray(t.requestHeaders)),t.requestHeadersText&&(r.requestHeadersText=t.requestHeadersText),r.responseReceivedTime=e,r.protocol="websocket")}webSocketFrameSent({requestId:e,timestamp:t,response:s}){const r=this._entries.get(e);r&&(r.addProtocolFrame(s,t,!0),r.responseReceivedTime=t)}webSocketFrameReceived({requestId:e,timestamp:t,response:s}){const r=this._entries.get(e);r&&(r.addProtocolFrame(s,t,!1),r.responseReceivedTime=t)}webSocketFrameError({errorMessage:e,requestId:t,timestamp:s}){const r=this._entries.get(t);r&&(r.addProtocolFrameError(e,s),r.responseReceivedTime=s)}webSocketClosed({requestId:e,timestamp:t}){const s=this._entries.get(e);s&&this.finishRequest(s,t,-1)}requestWillBeSentExtraInfo({requestId:e,headers:t}){this.getExtraInfoBuilder(e).addRequestExtraInfo({requestHeaders:this.headersMapToHeadersArray(t)})}responseReceivedExtraInfo({requestId:e,headers:t,headersText:s}){this.getExtraInfoBuilder(e).addResponseExtraInfo({responseHeaders:this.headersMapToHeadersArray(t),responseHeadersText:s})}getExtraInfoBuilder(e){return this._extraInfoBuilders.has(e)||this._extraInfoBuilders.set(e,new v((()=>{this._extraInfoBuilders.delete(e)}))),this._extraInfoBuilders.get(e)}_appendRedirect(e,t,s){const r=this._entries.get(e);let i=0,n=r.redirectSource;for(;n;)i++,n=n.redirectSource;r.markAsRedirect(i),this.finishRequest(r,t,-1);const o=this.createRequest(e,r.frameId,r.loaderId,s,r.documentURL,r.initiator);return o.redirectSource=r,o}finishRequest(e,t,s){if(e.endTime=t,s>=0){const t=e.redirectSource;(null==t?void 0:t.signedExchangeInfo)?(e.transferSize=0,t.transferSize=s):e.transferSize=s}this.loadContent(e),this.getExtraInfoBuilder(e.requestId).finished(),this.shouldExcludeRequest(e)||e.waitForCompletion().then((()=>{var t;return null===(t=this.destination)||void 0===t?void 0:t.call(this,e)})).finally((()=>this._entries.delete(e.requestId)))}loadContent(e){e.mimeType&&this.options.content&&e.setContentData(this.network.getResponseBody(e.requestId))}startRequest(e){this._entries.set(e.requestId,e)}updateNetworkRequestWithRequest(e,t){e.requestMethod=t.method,e.requestHeaders=this.headersMapToHeadersArray(t.headers),e.setRequestFormData(t.hasPostData?this.getRequestPostData(e,t):Promise.resolve(void 0)),e.initialPriority=t.initialPriority}getRequestPostData(e,t){return void 0!==t.postData?Promise.resolve(t.postData):this.network.getRequestBody(e.requestId).then((({postData:e})=>e)).catch((()=>{}))}createRequest(e,t,s,r,i,n){return new _(e,r,i,s,n,t)}updateNetworkRequestWithResponse(e,t){var s,r;t.url&&e.url!==t.url&&(e.url=t.url),e.mimeType=t.mimeType,e.statusCode=t.status,e.statusText=t.statusText,e.hasExtraResponseInfo||(e.responseHeaders=this.headersMapToHeadersArray(t.headers)),t.encodedDataLength>=0&&(e.transferSize=t.encodedDataLength),t.requestHeaders&&!e.hasExtraRequestInfo&&(e.requestHeaders=this.headersMapToHeadersArray(t.requestHeaders),e.requestHeadersText=null!==(s=t.requestHeadersText)&&void 0!==s?s:""),e.connectionReused=t.connectionReused,e.connectionId=String(t.connectionId),t.remoteIPAddress&&e.setRemoteAddress(t.remoteIPAddress,t.remotePort||-1),t.timing&&(e.timing=t.timing),e.protocol=null!==(r=t.protocol)&&void 0!==r?r:""}headersMapToHeadersArray(e){return Object.keys(e).reduce(((t,s)=>{const r=e[s].split("\n");return t.push(...r.map((e=>({name:s,value:e})))),t}),[])}shouldExcludeRequest(e){var t;return!!(null===(t=this.requestFilter)||void 0===t?void 0:t.wouldApply(this.options))&&!this.requestFilter.apply(e,this.options)}handleEvent({method:e,params:t,sessionId:s}){const r=e.substring(e.indexOf(".")+1);"function"==typeof this[r]&&this[r](t,s)}}class w{apply(e,{includeHosts:t}){const{host:s}=e.parsedURL;return!!(null==t?void 0:t.some((e=>f.toRegex(e).test(s))))}wouldApply(e){return Array.isArray(e.includeHosts)&&e.includeHosts.length>0}}class T{apply(e,{excludePaths:t}){const{pathname:s="/"}=e.parsedURL;return!(null==t?void 0:t.some((e=>f.toRegex(e).test(s))))}wouldApply(e){return Array.isArray(e.excludePaths)&&e.excludePaths.length>0}}class q{apply(e,{includeMimes:t}){return!(!e.mimeType||!(null==t?void 0:t.includes(e.mimeType)))}wouldApply(e){return Array.isArray(e.includeMimes)&&e.includeMimes.length>0}}class b{apply(e,{minStatusCodeToInclude:t}){var s;const r=null!==(s=this.normalizeThreshold(t))&&void 0!==s?s:0;return e.statusCode>=r}wouldApply(e){return"number"==typeof this.normalizeThreshold(e.minStatusCodeToInclude)}normalizeThreshold(e){return null==e||isNaN(+e)?void 0:Math.round(Math.abs(+e))}}class x{apply(e,t){return!e.isBlob()}wouldApply({includeBlobs:e}){return!(null==e||e)}}class R{apply(e,{excludeStatusCodes:t}){return!(null==t?void 0:t.includes(e.statusCode))}wouldApply(e){return Array.isArray(e.excludeStatusCodes)&&e.excludeStatusCodes.length>0}}class k{constructor(e=[new w,new T,new q,new x,new b,new R]){this.children=e}apply(e,t){return this.children.filter((e=>e.wouldApply(t))).every((s=>s.apply(e,t)))}wouldApply(e){return this.children.some((t=>t.wouldApply(e)))}}class I{constructor(e){this.entries=e}build(){const{name:e,version:t,homepage:r}=s(330);return{log:{version:"1.2",pages:[],creator:{name:e,version:t,comment:r},entries:this.entries}}}}class E{constructor(e){this.networkObservable=e}waitForIdle(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){for(;;){if(this.startIdleTime=this.networkObservable.empty?this.startIdleTimer():void 0,this.shouldResolve(e))return;yield(0,u.promisify)(setTimeout)(e)}}))}startIdleTimer(){return this.startIdleTime||(this.startIdleTime=Date.now()),this.startIdleTime}shouldResolve(e){return!!(this.startIdleTime&&Date.now()-this.startIdleTime>=e)}}const S="--remote-debugging-port",C="--remote-debugging-address",H=["chromium"],P=100,A=5e3,M=require("chalk");var D=s.n(M);class F{constructor(){this._debug=(0,u.debuglog)("cypress-har-generator")}static get Instance(){return this._instance||(this._instance=new F),this._instance}info(e){this.log(D().blue(`ℹ️ ${e}`))}err(e){this.log(D().red(`🍑 ${e}`))}warn(e){this.log(D().yellow(`⚠ ${e}`))}debug(e){this._debug(e)}log(e){console.log(e)}}const N=require("fs"),O=require("crypto");class L{static get Instance(){return this._instance||(this._instance=new L),this._instance}readFile(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{return yield(0,u.promisify)(N.readFile)(e,{encoding:"utf-8"})}catch(e){return void F.Instance.err(e)}}))}writeFile(e,t){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{yield this.removeFile(e),yield(0,u.promisify)(N.writeFile)(e,t)}catch(e){F.Instance.err(e)}}))}createFolder(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{if(yield this.exists(e))return;yield(0,u.promisify)(N.mkdir)(e)}catch(e){F.Instance.err(e)}}))}removeFile(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{(yield this.exists(e))&&(yield(0,u.promisify)(N.unlink)(e))}catch(e){F.Instance.err(e)}}))}exists(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{return yield(0,u.promisify)(N.access)(e,N.constants.F_OK),!0}catch(e){return!1}}))}createTmpWriteStream(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const{fd:e,path:t}=yield this.openTmpFd(),s=(0,N.createWriteStream)(t,{fd:e,flags:"w",mode:438,encoding:"utf-8"});return s.path=t,s}))}openTmpFd(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const e=(0,O.randomBytes)(16).toString("hex").substring(16),t=(0,l.join)((0,a.tmpdir)(),e);return{path:t,fd:yield(0,u.promisify)(N.open)(t,"w",384)}}))}}const z="Failed to connect to Chrome Debugging Protocol",B="Chrome Debugging Protocol disconnected",$=`${z}\n\nPossible reasons for failure:\n - Chrome not running in headless mode\n - Using Chrome version 58 or earlier\n - Inconsistent RDP configuration settings.\n \nThe stack trace for this error is:`;class V{constructor(e,t,s){this.cdp=e,this.logger=t,this.options=s,this.DOMAIN="Network",this.ALLOWED_TARGETS=new Set(["service_worker","page","worker","background_page","webview","shared_worker"]),this.sessions=new Map,this.networkEventListener=e=>{this.matchNetworkEvents(e)&&setImmediate((()=>{var t;return null===(t=this.listener)||void 0===t?void 0:t.call(this,e)}))},this.certificateErrorListener=({eventId:e})=>this.cdp.send("Security.handleCertificateError",{eventId:e,action:"continue"}),this.sessionListener=({requestId:e},t)=>{this.sessions.set(e,t),this.logger.debug(`Session ${null!=t?t:"N/A"} associated with request: ${e}`)},this.attachedToTargetListener=({sessionId:e,targetInfo:t,waitingForDebugger:s})=>(0,i.__awaiter)(this,void 0,void 0,(function*(){try{yield this.recursivelyAttachToTargets({sessionId:e,type:t.type}),s&&(yield this.cdp.send("Runtime.runIfWaitingForDebugger",void 0,e))}catch(s){const r=o.isError(s)?s.stack:s;this.logger.debug(`We encountered an issue while initializing the target for the session: ${e}.`),this.logger.debug(`The information about the target is as follows: ${JSON.stringify(t)}`),this.logger.warn(`Unable to attach to the target (e.g. page, worker, etc). \n\nPossible reasons for the failure include:\n - Chrome not running in headless mode.\n - The target may have closed during initialization.\n - The target may have crashed due to memory issues.\n\nPlease open an issue on the repository: https://github.com/NeuraLegion/cypress-har-generator/issues for assistance.\n\nThe stack trace for this error is:\n${r}`)}}))}attachToTargets(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){this.listener=e,this.cdp.on("event",this.networkEventListener),this.cdp.on("Target.attachedToTarget",this.attachedToTargetListener),this.cdp.on("Network.requestWillBeSent",this.sessionListener),this.cdp.on("Network.webSocketCreated",this.sessionListener),yield this.ignoreCertificateError(),yield this.recursivelyAttachToTargets({type:"browser"})}))}detachFromTargets(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){this.listener&&(this.cdp.off("event",this.networkEventListener),this.cdp.off("Security.certificateError",this.certificateErrorListener),this.cdp.off("Target.attachedToTarget",this.attachedToTargetListener),this.cdp.off("Network.requestWillBeSent",this.sessionListener),this.cdp.off("Network.webSocketCreated",this.sessionListener),delete this.listener);try{yield Promise.all([this.cdp.send("Security.disable"),this.enableAutoAttach(!1)])}catch(e){this.logger.debug(`Unexpected error while detaching from targets: ${e}`)}this.sessions.clear()}))}getRequestBody(e){return this.cdp.send("Network.getRequestPostData",{requestId:e},this.sessions.get(e))}getResponseBody(e){return this.cdp.send("Network.getResponseBody",{requestId:e},this.sessions.get(e))}ignoreCertificateError(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){this.cdp.on("Security.certificateError",this.certificateErrorListener);try{yield this.cdp.send("Security.enable"),yield this.cdp.send("Security.setOverrideCertificateErrors",{override:!0})}catch(e){this.logger.debug(o.isError(e)?e.message:`Something went wrong: ${e}`)}}))}matchNetworkEvents(e){const[t]=e.method.split(".");return t===this.DOMAIN}recursivelyAttachToTargets(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){yield this.enableAutoAttach(!0,e.sessionId),this.ALLOWED_TARGETS.has(e.type)&&(yield this.trackNetworkEvents(e.sessionId))}))}enableAutoAttach(e,t){return this.cdp.send("Target.setAutoAttach",{autoAttach:e,flatten:!0,waitForDebuggerOnStart:!0},t)}trackNetworkEvents(e){var t;return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{yield Promise.all([this.cdp.send("Network.enable",null!==(t=this.options)&&void 0!==t?t:{},e),this.cdp.send("Network.setCacheDisabled",{cacheDisabled:!0},e)])}catch(e){if(this.targetClosedError(e))return void this.logger.debug("The target or browser may have closed before completion of initialization");throw e}}))}targetClosedError(e){return o.isError(e)&&(e.message.includes("Target closed")||e.message.includes("Session closed"))}}const j=require("chrome-remote-interface");var U=s.n(j);class W{constructor(e,t,s){this.options=e,this.logger=t,this.retryStrategy=s}get cdp(){return this._cdp}open(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){try{this.logger.debug("Attempting to connect to Chrome Debugging Protocol");const e=yield this.populateBrowserTarget(),t=yield U()({target:e});this.logger.debug("Connected to Chrome Debugging Protocol"),t.once("disconnect",(()=>this.logger.debug(B))),this._cdp=t}catch(e){const t=o.isError(e)?e.message:e;if(this.logger.debug(`${z}: ${t}`),!(yield this.retryStrategy.execute((()=>this.open()))))throw new Error($)}}))}close(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){this._cdp&&(yield this._cdp.close(),this._cdp.removeAllListeners(),delete this._cdp,this.logger.debug(B))}))}discoverNetwork(e){if(!this.cdp)throw new Error("Chrome Debugging Protocol connection has not been established.");return this._network||(this._network=new V(this.cdp,this.logger,e)),this._network}populateBrowserTarget(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const{port:e,host:t}=this.options,{webSocketDebuggerUrl:s}=yield(0,j.Version)({host:t,port:e});return null!=s?s:`ws://${t}:${e}/devtools/browser`}))}}class G{constructor(e=3,t=5,s=25){this._times=0,this.maxRetries=e,this.backoffTime=t,this.maximumBackoff=s}execute(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const t=this.nextTime();return t&&(yield this.delay(t),yield e()),this.maxRetries-this._times}))}delay(e){return new Promise((t=>setTimeout(t,e)))}nextTime(){if(this._times<this.maxRetries)return this.increaseBackoffTime()}increaseBackoffTime(){return this.backoffTime*=Math.pow(2,++this._times-1),Math.min(this.backoffTime,this.maximumBackoff)}}const Q=new class{constructor(e,t,s,r,i){this.logger=e,this.fileManager=t,this.connectionFactory=s,this.observerFactory=r,this.exporterFactory=i}ensureBrowserFlags(e,t){this.supported=this.isSupportedBrowser(e),this.supported||this.logger.warn(`HAR recording is not supported in this browser: ${e.name}`);const s="electron"===e.name;s&&(t=this.parseElectronSwitches(e));const r=this.ensureRdpAddrArgs(t);return s?[]:r.filter((e=>!t.includes(e)))}recordHar(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){if(!this.addr)throw new Error("Please call the 'ensureBrowserFlags' before attempting to start the recording.");this.supported&&(yield this.closeConnection(),this.exporter=yield this.exporterFactory.create(e),this._connection=this.connectionFactory.create(Object.assign(Object.assign({},this.addr),{maxRetries:20,maximumBackoff:100,initialBackoff:5})),yield this._connection.open(),yield this.listenNetworkEvents(e))}))}saveHar(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){if(!this.supported)return;const t=(0,l.join)(e.outDir,e.fileName);if(this._connection)try{yield this.fileManager.createFolder(e.outDir),e.waitForIdle&&(yield this.waitForNetworkIdle(e));const s=yield this.buildHar();s&&(yield this.fileManager.writeFile(t,s))}catch(e){const t=o.isError(e)?e.message:e;this.logger.err(`An error occurred while attempting to save the HAR file. Error details: ${t}`)}finally{yield this.disposeOfHar()}else this.logger.err("Failed to save HAR. First you should start recording.")}))}disposeOfHar(){var e;return(0,i.__awaiter)(this,void 0,void 0,(function*(){this.supported&&(yield null===(e=this.networkObservable)||void 0===e?void 0:e.unsubscribe(),delete this.networkObservable,this.exporter&&(this.exporter.end(),yield this.fileManager.removeFile(this.exporter.path),delete this.exporter))}))}parseElectronSwitches(e){var t;if(!(null===(t=process.env.ELECTRON_EXTRA_LAUNCH_ARGS)||void 0===t?void 0:t.includes(S)))throw this.logger.err(`The '${e.name}' browser was detected, however, the required '${S}' command line switch was not provided. \nThis switch is necessary to enable remote debugging over HTTP on the specified port. \n\nPlease refer to the documentation:\n - https://www.electronjs.org/docs/latest/api/command-line-switches#--remote-debugging-portport\n - https://docs.cypress.io/api/plugins/browser-launch-api#Modify-Electron-app-switches`),new Error(`Missing '${S}' command line switch for Electron browser`);return process.env.ELECTRON_EXTRA_LAUNCH_ARGS.split(" ")}buildHar(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){if(this.exporter){const e=yield this.fileManager.readFile(this.exporter.path);if(e){const t=e.split(a.EOL).filter(Boolean).map((e=>JSON.parse(e))),s=new I(t).build();return JSON.stringify(s,null,2)}}}))}waitForNetworkIdle(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const{minIdleDuration:t=P,maxWaitDuration:s=A}=e,r=(0,u.promisify)(setTimeout)(s);return Promise.race([new E(this.networkObservable).waitForIdle(t),r])}))}listenNetworkEvents(e){var t;return(0,i.__awaiter)(this,void 0,void 0,(function*(){const s=null===(t=this._connection)||void 0===t?void 0:t.discoverNetwork(e);return this.networkObservable=this.observerFactory.createNetworkObserver(s,e),this.networkObservable.subscribe((e=>{var t;return null===(t=this.exporter)||void 0===t?void 0:t.write(e)}))}))}closeConnection(){return(0,i.__awaiter)(this,void 0,void 0,(function*(){this._connection&&(yield this._connection.close(),delete this._connection)}))}isSupportedBrowser(e){return H.includes(null==e?void 0:e.family)}ensureRdpAddrArgs(e){const{host:t="localhost",port:s=4e4+Math.round(25e3*Math.random())}=this.extractAddrFromArgs(e);return this.addr={host:t,port:s},[...e,`${S}=${s}`,`${C}=${t}`]}extractAddrFromArgs(e){const t=this.findAndParseIfPossible(e,S),s=this.findAndParseIfPossible(e,C);let r={};return t&&!isNaN(+t)&&(r={port:+t}),s&&(r=Object.assign(Object.assign({},r),{host:s})),r}findAndParseIfPossible(e,t){var s;const r=e.find((e=>e.startsWith(t))),[,i]=null!==(s=null==r?void 0:r.split("=",2))&&void 0!==s?s:[];return i}}(F.Instance,L.Instance,new class{constructor(e){this.logger=e}create(e){var{maxRetries:t,initialBackoff:s,maximumBackoff:r}=e,n=(0,i.__rest)(e,["maxRetries","initialBackoff","maximumBackoff"]);const o=new G(t,s,r);return new W(n,this.logger,o)}}(F.Instance),new class{constructor(e){this.logger=e,this.defaultRequestFilter=new k}createNetworkObserver(e,t){return new y(t,e,this.logger,this.defaultRequestFilter)}}(F.Instance),new class{constructor(e,t){this.fileManager=e,this.logger=t}create(e){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.createSettings(e),s=yield this.fileManager.createTmpWriteStream();return new d(this.logger,s,t)}))}createSettings({filter:e,transform:t,rootDir:s}){return(0,i.__awaiter)(this,void 0,void 0,(function*(){const[r,i]=yield Promise.all([e,t].map((e=>this.loadCustomProcessor(e,s))));return{filter:r,transform:i}}))}loadCustomProcessor(e,t){return(0,i.__awaiter)(this,void 0,void 0,(function*(){let s;if(e){const r=(0,l.resolve)(t,e);s=yield h.load(r)}return s}))}}(L.Instance,F.Instance)),X=e=>{e("task",{saveHar:e=>(0,i.__awaiter)(void 0,void 0,void 0,(function*(){return yield Q.saveHar(e),null})),recordHar:e=>(0,i.__awaiter)(void 0,void 0,void 0,(function*(){return yield Q.recordHar(e),null})),disposeOfHar:()=>(0,i.__awaiter)(void 0,void 0,void 0,(function*(){return yield Q.disposeOfHar(),null}))}),e("before:browser:launch",((e,t)=>(K(null!=e?e:{},t),t)))},J=(e,t)=>{t.isTextTerminal||t.experimentalInteractiveRunEvents?(e("before:spec",(e=>Q.recordHar({content:!0,includeBlobs:!0,rootDir:f.dirname(Cypress.spec.absolute)}))),e("after:spec",((e,s)=>{var r;return Q.saveHar({fileName:f.normalizeName(e.name,{ext:".har"}),outDir:null!==(r=t.env.hars_folders)&&void 0!==r?r:"."})}))):F.Instance.warn('To activate the experimental mechanism for setting up lifecycle, you must either disable the interactive mode or activate the "experimentalInteractiveRunEvents" feature. For further information, please refer to: https://docs.cypress.io/guides/references/experiments#Configuration')},K=(e,t)=>{t.args.push(...Q.ensureBrowserFlags(e,t.args))};var Y=exports;for(var Z in r)Y[Z]=r[Z];r.__esModule&&Object.defineProperty(Y,"__esModule",{value:!0})})();
//# sourceMappingURL=index.js.map