mockforme 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,9 +14,9 @@ mockforme npm package can be used to intercept APIs and return mock responses cr
14
14
  #### Installation ####
15
15
  Install the package using npm or yarn:
16
16
  ```
17
- npm install mockforme --save
17
+ npm install mockforme --save-dev
18
18
  OR
19
- yarn add mockforme
19
+ yarn add mockforme -D
20
20
  ```
21
21
 
22
22
 
@@ -1 +1 @@
1
- (()=>{"use strict";var e={d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{mockforme:()=>H});const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},n=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let s=[];function i(e){s=e}function a(){return s}function c(e,t="get"){for(const r of s)if(o(r.apiMethod)===o(t)&&(r.apiEndpoint===e||n(r.apiEndpoint,e))){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}return null}const d="JAVASCRIPT",l="CHROME_EXTENSION",u="mfmver",h="mockforme",m="4.2.8",p="https://api.mockforme.com",f=`${p}/mockforme`,_=`${p}/gateway/3f4eae522b`;let y=null,g=null,w=null,b=[];function x({_o:e,mk:t,_mck:r,_rules:o}){y=e,g=t,w=r,b=o}function v(){return b}function k(){return`${f}/${y}/${g}`}function E(){return w}const R=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}};function T({url:e,method:t}){try{const t=v();if(!Array.isArray(t)||0===t.length)return null;const r=globalThis.location?.origin||"http://localhost";for(const o of t){const t=o.rule?.URL;if(!t)continue;const{condition:n}=t;if(!n)continue;let s="";switch(t.type){case"URL":{let t;try{t=new URL(e,r),s=t.pathname}catch{s=e}break}case"QUERY":{let t;try{t=new URL(e,r)}catch{t=null}t&&(s=t.searchParams.get(n.key)||"");break}case"BODY":case"HEADERS":s="";break;default:continue}let i=!1;switch(n.operator){case"contains":i=s.includes(n.value);break;case"equal":case"equals":i=s===n.value;break;case"regexp":try{let e=n.value;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);i=new RegExp(r,o).test(s)}else i=new RegExp(e).test(s)}catch{i=!1}}if(i){const e=n.activeAction;return{action:e,config:n.actions?.[e]||{}}}}return null}catch(e){return console.error("[mockforme] checkIfRulesToBeApplied error",e),null}}function S(e,t){!function(e,t){const r=window.fetch;window.fetch=function(o,n={}){const s="string"==typeof o?o:o.url;try{const i=new URL(s,window.location.origin),{pathname:a,search:d}=i;let p="get";n&&n.method?p=n.method:o instanceof Request&&o.method&&(p=o.method),p=p.toLowerCase();const f=T({url:s,method:p});if(t!==l&&f){if("delay"===f.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(o,n))}),1e3*f.config.value)}));if("delay_and_redirect"===f.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(f.config.redirectUrl,n))}),1e3*f.config.value)}));if("delay_and_timeout"===f.action){if(0===f.config.value){const e=new AbortController,t=r(o,{...n,signal:e.signal});return e.abort(),t.catch((()=>Promise.reject(new Error("Fetch aborted by rules"))))}return new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Fetch timed out by rules"))}),1e3*f.config.value)}))}}const _=c(a,p);if(!_&&!f)return r(o,n);let y=s;f||(y=`${k()}${_.url}${d}`);let g={};if(!f){g={[h]:e,[u]:m,"x-mfm-adaptor":t};const r=E();r&&_._ack&&(g["x-mfm-key"]=`${r}-${_._ack}`),_?._ri_&&(g._ri_=_._ri_)}const w=o instanceof Request?o.headers:n.headers,b=new Headers(w||{});Object.entries(g).forEach((([e,t])=>{b.set(e,t)}));let x=n.body;if(!x&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(x=e.text())}let v={method:p,headers:b,credentials:"include",mode:"cors"};f&&(v.credentials=o instanceof Request&&o.credentials||n.credentials||"same-origin",v.mode=o instanceof Request&&o.mode||n.mode||"cors");const S=e=>(e&&(v.body=e),t===l?(({actualUrl:e,url:t,method:r,headers:o,body:n,credentials:s,mode:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(r){if(r.source!==window)return;const o=r.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===c){if(window.removeEventListener("message",e),o?.response?.error)return l(new Error(o.response.message));const{status:r,headers:n,body:s}=o.response;t(new Response(s,{status:r,headers:n}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:s,url:y,method:p,headers:Object.fromEntries(b.entries()),body:e,credentials:v.credentials,mode:v.mode,rule:f}):fetch(y,v).then((e=>{const t=e.clone();return(t.headers.get("content-type")||"").includes("application/json")?t.json().then((r=>new Response(JSON.stringify(r),{status:e.status,headers:t.headers}))):t.text().then((r=>new Response(r,{status:e.status,headers:t.headers})))})).catch((e=>(console.warn("mockforme fetch interceptor error",e),r(o,n)))));return x instanceof Promise?x.then((e=>S(e))):S(x)}catch(e){return console.warn("mockforme fetch interceptor error",e),r(o,n)}}}(e,t),function(e,t){const r=window.XMLHttpRequest;window.XMLHttpRequest=class{constructor(){this._xhr=new r,this._headers={},this._method=null,this._url=null,this._body=null,this._setupEventHandlers()}_setupEventHandlers(){const e=["onload","onerror","onabort","ontimeout","onreadystatechange"];for(const t of e)Object.defineProperty(this,t,{get:()=>this._xhr[t],set:e=>{this._xhr[t]=e}})}open(e,t,r=!0,o=null,n=null){return this._method=e.toUpperCase(),this._url=new URL(t,window.location.href).toString(),this._xhr._mockOriginalUrl=this._url,this._xhr._mockMethod=this._method,this._xhr.open(e,t,r,o,n)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(o){this._body=o;try{const n=new URL(this._url),{pathname:s,search:i}=n,a=T({url:this._url,method:this._method});if(t!==l&&a){if("delay"===a.action)return setTimeout((()=>this._xhr.send(o)),1e3*a.config.value);if("delay_and_redirect"===a.action)return setTimeout((()=>{this._xhr.open(this._method,a.config.redirectUrl,!0),this._xhr.send(o)}),1e3*a.config.value);if("delay_and_timeout"===a.action)return 0===a.config.value?(this._xhr.open(this._method,this._url,!0),this._xhr.send(o),this._xhr.abort(),void("function"==typeof this.onerror&&this.onerror(new Error("XHR aborted by rules")))):setTimeout((()=>{this._xhr.abort(),"function"==typeof this.onerror&&this.onerror(new Error("XHR timed out by rules"))}),1e3*a.config.value)}const d=c(s,this._method);if(!d&&!a)return this._xhr.send(o);let p=this._url;a||(p=`${k()}${d.url}${i}`);let f={};if(!a){f={[h]:e,[u]:m,"x-mfm-adaptor":t};const r=E();r&&d._ack&&(f["x-mfm-key"]=`${r}-${d._ack}`),d?._ri_&&(f._ri_=d._ri_)}const _={...this._headers,...f};if(t===l)(({actualUrl:e,url:t,method:r,headers:o,body:n,onSuccess:s,onError:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const r=t.data;if("INTERCEPTED_RESPONSE"===r.type&&r.requestId===c){if(window.removeEventListener("message",e),r.response?.error)return i?.(r.response.message);const{body:t,status:o,headers:n}=r.response;s?.({body:t,status:o,headers:n})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:this._url,url:p,method:this._method,headers:_,body:this._body,rule:a,onSuccess:({body:e,status:t})=>{Object.defineProperty(this,"responseText",{value:e}),Object.defineProperty(this,"status",{value:t}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.()},onError:e=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(new Error(e.message||"XHR mock error"))}});else{const e=new r;e.open(this._method,p,!0);for(const t in _)e.setRequestHeader(t,_[t]);e.withCredentials=this.withCredentials,e.onload=()=>{Object.defineProperty(this,"responseText",{value:e.responseText}),Object.defineProperty(this,"status",{value:e.status}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.()},e.onerror=()=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.()},e.send(this._body)}}catch(e){console.error("[mockforme][XHR] interception error",e)}}addEventListener(...e){return this._xhr.addEventListener(...e)}removeEventListener(...e){return this._xhr.removeEventListener(...e)}dispatchEvent(...e){return this._xhr.dispatchEvent(...e)}abort(){return this._xhr.abort()}getAllResponseHeaders(){return this._xhr.getAllResponseHeaders()}getResponseHeader(e){return this._xhr.getResponseHeader(e)}overrideMimeType(e){return this._xhr.overrideMimeType(e)}get readyState(){return this._xhr.readyState}get responseText(){return this._xhr.responseText}get status(){return this._xhr.status}get response(){return this._xhr.response}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get withCredentials(){return this._xhr.withCredentials}set withCredentials(e){this._xhr.withCredentials=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}get upload(){return this._xhr.upload}}}(e,t)}const O=function(e,t,o){const n=r();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var r=e.split(";");try{return"application/json"===r[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();t.call(this,e,s)}else o.call(this,s.responseText,s)}function a(e,t){var r=[];for(var o in e)if(e.hasOwnProperty(o)){var n=t?t+"["+o+"]":o,s=e[o];r.push("object"==typeof s?a(s,n):encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}return n||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!n){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var t=a(e.params);if("get"==e.method.toLowerCase()&&"object"==typeof e.params){if(-1==e.url.indexOf("?"))e.url+="?";else{var r=e.url.split("?");r[1]&&r[1].split("=")[1]&&(e.url+="&")}e.url+=t}e.hasOwnProperty("async")||(e.async=!0),s.open(e.method,e.url,e.async),e.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(e.headers),s.send(t)}}}};function j({di:e,iv:t},r){var o;const n=function(e,t){const r=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(n)}const P=(e,t=null,o=d)=>{if(r())return;if(o===d)try{!function(){if(!window.mockforme)return;const e=JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"),t=document.createElement("div");t.id="mockforme-dot",Object.assign(t.style,{position:"fixed",bottom:(e.bottom??20)+"px",right:(e.right??20)+"px",width:"42px",height:"42px",borderRadius:"50%",overflow:"hidden",cursor:"grab",zIndex:999999,boxShadow:"0 0 10px rgba(0,0,0,0.25)",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center"});const r=document.createElement("img");r.src="https://dashboard.mockforme.com/public/assets/images/icon.png",r.style.objectFit="cover",t.appendChild(r),document.body.appendChild(t);const o=document.createElement("div");o.id="mockforme-widget",o.innerText="MockForMe Enabled",Object.assign(o.style,{position:"fixed",padding:"8px 12px",background:"#2563eb",color:"#fff",fontSize:"13px",fontFamily:"Inter, sans-serif",borderRadius:"8px",bottom:(e.bottom??20)+50+"px",right:(e.right??20)+"px",boxShadow:"0 4px 10px rgba(0,0,0,0.2)",zIndex:999999,display:"none",whiteSpace:"nowrap"}),document.body.appendChild(o),t.addEventListener("click",(e=>{e.stopPropagation(),o.style.display="none"===o.style.display?"block":"none"})),document.addEventListener("click",(()=>{o.style.display="none"}));let n=!1,s=0,i=0;t.addEventListener("mousedown",(e=>{n=!0,t.style.cursor="grabbing";const r=t.getBoundingClientRect();s=e.clientX-r.left,i=e.clientY-r.top,e.preventDefault()})),document.addEventListener("mousemove",(e=>{if(!n)return;const r=e.clientX-s,a=e.clientY-i,c=window.innerHeight-(a+t.offsetHeight),d=window.innerWidth-(r+t.offsetWidth);t.style.bottom=c+"px",t.style.right=d+"px",o.style.bottom=c+50+"px",o.style.right=d+"px"})),document.addEventListener("mouseup",(()=>{if(!n)return;n=!1,t.style.cursor="grab";const e=parseInt(t.style.bottom),r=parseInt(t.style.right);localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:e,right:r}))}))}()}catch(e){console.log("Error in showing mockforme widget")}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:n=[],_o:s,mk:l,_mck:p,_rules:f=[]}=t;return i(n),x({_o:s,mk:l,_mck:p,_rules:f}),{run:(t,r=()=>{})=>{S(e,o),s&&l?t(a(),{_o:s,mk:l,_mck:p,_rules:f}):function(e,r,o,n){O({method:"get",url:_,async:!1,headers:{[h]:e,[u]:m,"x-mfm-adaptor":r}},(e=>{if(e)try{const{di:n,iv:s,_o:a,_mck:c,mk:d,r:l}=e,u=j({di:n,iv:s},a);x({_o:a,mk:d,_mck:c,_rules:l}),u&&(i(u),r=u,o={_o:a,mk:d,_mck:c,_rules:l},t?.(r,o))}catch(e){return void n(new Error("Unable to fetch mocked apis"))}var r,o}),(e=>{console.log("Error in loading mocked apis"),n(e)})).request()}(e,o,0,r)},checkIfApiToBeMocked:c,getMappings:a,doFetchMappings:(t,r)=>{!function(e,t,r,o){fetch(_,{method:"GET",headers:{[h]:e,[u]:m,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:n,_mck:s,mk:a,r:c}=e,d=j({di:t,iv:o},n);x({_o:n,mk:a,_mck:s,_rules:c}),d&&(i(d),r(d,{_o:n,mk:a,_mck:s,_rules:c}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}(e,o,((e,r)=>{t?.(e,r)}),r)}}},C=r();C||(globalThis.mockforme=P);let L=P;C&&(L=e=>({run:()=>{}}));const H=L;module.exports=t})();
1
+ (()=>{"use strict";var e={d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{mockforme:()=>L});const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},n=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let s=[];function i(e){s=e}function a(){return s}function c(e,t="get"){for(const r of s)if(o(r.apiMethod)===o(t)&&(r.apiEndpoint===e||n(r.apiEndpoint,e))){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}return null}const d="JAVASCRIPT",l="CHROME_EXTENSION",u="mfmver",h="mockforme",f="4.2.8",m="https://api.mockforme.com",p=`${m}/mockforme`,y=`${m}/gateway/3f4eae522b`;let _=null,g=null,w=null,b=[];function v({_o:e,mk:t,_mck:r,_rules:o}){_=e,g=t,w=r,b=o}function E(){return b}function x(){return`${p}/${_}/${g}`}function k(){return w}const R=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}};function S({url:e,method:t}){try{const t=E();if(!Array.isArray(t)||0===t.length)return null;const r=globalThis.location?.origin||"http://localhost";for(const o of t){const t=o.rule?.URL;if(!t)continue;const{condition:n}=t;if(!n)continue;let s="";switch(t.type){case"URL":{let t;try{t=new URL(e,r),s=t.pathname}catch{s=e}break}case"QUERY":{let t;try{t=new URL(e,r)}catch{t=null}t&&(s=t.searchParams.get(n.key)||"");break}case"BODY":case"HEADERS":s="";break;default:continue}let i=!1;switch(n.operator){case"contains":i=s.includes(n.value);break;case"equal":case"equals":i=s===n.value;break;case"regexp":try{let e=n.value;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);i=new RegExp(r,o).test(s)}else i=new RegExp(e).test(s)}catch{i=!1}}if(i){const e=n.activeAction;return{action:e,config:n.actions?.[e]||{}}}}return null}catch(e){return console.error("[mockforme] checkIfRulesToBeApplied error",e),null}}function O(e,t){!function(e,t){const r=window.fetch;window.fetch=function(o,n={}){const s="string"==typeof o?o:o.url;try{const i=new URL(s,window.location.origin),{pathname:a,search:d}=i;let m="get";n&&n.method?m=n.method:o instanceof Request&&o.method&&(m=o.method),m=m.toLowerCase();const p=S({url:s,method:m});if(t!==l&&p){if("delay"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(o,n))}),1e3*p.config.value)}));if("delay_and_redirect"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(p.config.redirectUrl,n))}),1e3*p.config.value)}));if("delay_and_timeout"===p.action){if(0===p.config.value){const e=new AbortController,t=r(o,{...n,signal:e.signal});return e.abort(),t.catch((()=>Promise.reject(new Error("Fetch aborted by rules"))))}return new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Fetch timed out by rules"))}),1e3*p.config.value)}))}}const y=c(a,m);if(!y&&!p)return r(o,n);let _=s;p||(_=`${x()}${y.url}${d}`);let g={};if(!p){g={[h]:e,[u]:f,"x-mfm-adaptor":t};const r=k();r&&y._ack&&(g["x-mfm-key"]=`${r}-${y._ack}`),y?._ri_&&(g._ri_=y._ri_)}const w=o instanceof Request?o.headers:n.headers,b=new Headers(w||{});Object.entries(g).forEach((([e,t])=>{b.set(e,t)}));let v=n.body;if(!v&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(v=e.text())}let E={method:m,headers:b,credentials:"include",mode:"cors"};p&&(E.credentials=o instanceof Request&&o.credentials||n.credentials||"same-origin",E.mode=o instanceof Request&&o.mode||n.mode||"cors");const O=e=>(e&&(E.body=e),t===l?(({actualUrl:e,url:t,method:r,headers:o,body:n,credentials:s,mode:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(r){if(r.source!==window)return;const o=r.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===c){if(window.removeEventListener("message",e),o?.response?.error)return l(new Error(o.response.message));const{status:r,headers:n,body:s}=o.response;t(new Response(s,{status:r,headers:n}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:s,url:_,method:m,headers:Object.fromEntries(b.entries()),body:e,credentials:E.credentials,mode:E.mode,rule:p}):fetch(_,E).then((e=>{const t=e.clone();return(t.headers.get("content-type")||"").includes("application/json")?t.json().then((r=>new Response(JSON.stringify(r),{status:e.status,headers:t.headers}))):t.text().then((r=>new Response(r,{status:e.status,headers:t.headers})))})).catch((e=>(console.warn("mockforme fetch interceptor error",e),r(o,n)))));return v instanceof Promise?v.then((e=>O(e))):O(v)}catch(e){return console.warn("mockforme fetch interceptor error",e),r(o,n)}}}(e,t),function(e,t){const r=window.XMLHttpRequest;window.XMLHttpRequest=class{constructor(){return this._xhr=new r,this._headers={},this._method=null,this._url=null,this._body=null,new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const r=e._xhr[t];return"function"==typeof r?r.bind(e._xhr):r},set:(e,t,r)=>t in e?(e[t]=r,!0):(e._xhr[t]=r,!0)})}open(e,t,r=!0,o=null,n=null){return this._method=e.toUpperCase(),this._url=new URL(t,window.location.href).toString(),this._xhr._mockOriginalUrl=this._url,this._xhr._mockMethod=this._method,this._xhr.open(e,t,r,o,n)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(o){this._body=o;try{const n=new URL(this._url),{pathname:s,search:i}=n,a=S({url:this._url,method:this._method});if(t!==l&&a){if("delay"===a.action)return setTimeout((()=>this._xhr.send(o)),1e3*a.config.value);if("delay_and_redirect"===a.action)return setTimeout((()=>{this._xhr.open(this._method,a.config.redirectUrl,!0),this._xhr.send(o)}),1e3*a.config.value);if("delay_and_timeout"===a.action)return 0===a.config.value?(this._xhr.open(this._method,this._url,!0),this._xhr.send(o),this._xhr.abort(),void("function"==typeof this.onerror&&this.onerror(new Error("XHR aborted by rules")))):setTimeout((()=>{this._xhr.abort(),"function"==typeof this.onerror&&this.onerror(new Error("XHR timed out by rules"))}),1e3*a.config.value)}const d=c(s,this._method);if(!d&&!a)return this._xhr.send(o);let m=this._url;a||(m=`${x()}${d.url}${i}`);let p={};if(!a){p={[h]:e,[u]:f,"x-mfm-adaptor":t};const r=k();r&&d._ack&&(p["x-mfm-key"]=`${r}-${d._ack}`),d?._ri_&&(p._ri_=d._ri_)}const y={...this._headers,...p};if(t===l)(({actualUrl:e,url:t,method:r,headers:o,body:n,onSuccess:s,onError:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const r=t.data;if("INTERCEPTED_RESPONSE"===r.type&&r.requestId===c){if(window.removeEventListener("message",e),r.response?.error)return i?.(r.response.message);const{body:t,status:o,headers:n}=r.response;s?.({body:t,status:o,headers:n})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:this._url,url:m,method:this._method,headers:y,body:this._body,rule:a,onSuccess:({body:e,status:t})=>{Object.defineProperty(this,"responseText",{value:e}),Object.defineProperty(this,"status",{value:t}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("load"))},onError:e=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(new Error(e.message||"XHR mock error")),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("error"))}});else{const e=new r;e.open(this._method,m,!0);for(const t in y)e.setRequestHeader(t,y[t]);e.withCredentials=this.withCredentials,e.onload=()=>{Object.defineProperty(this,"responseText",{value:e.responseText}),Object.defineProperty(this,"status",{value:e.status}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("load"))},e.onerror=()=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("error"))},e.send(this._body)}}catch(e){console.error("[mockforme][XHR] interception error",e)}}}}(e,t)}const T=function(e,t,o){const n=r();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var r=e.split(";");try{return"application/json"===r[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();t.call(this,e,s)}else o.call(this,s.responseText,s)}function a(e,t){var r=[];for(var o in e)if(e.hasOwnProperty(o)){var n=t?t+"["+o+"]":o,s=e[o];r.push("object"==typeof s?a(s,n):encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}return n||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!n){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var t=a(e.params);if("get"==e.method.toLowerCase()&&"object"==typeof e.params){if(-1==e.url.indexOf("?"))e.url+="?";else{var r=e.url.split("?");r[1]&&r[1].split("=")[1]&&(e.url+="&")}e.url+=t}e.hasOwnProperty("async")||(e.async=!0),s.open(e.method,e.url,e.async),e.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(e.headers),s.send(t)}}}};function P({di:e,iv:t},r){var o;const n=function(e,t){const r=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(n)}const j=(e,t=null,o=d)=>{if(r())return;if(o===d)try{!function(){if(!window.mockforme)return;const e=JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"),t=document.createElement("div");t.id="mockforme-dot",Object.assign(t.style,{position:"fixed",bottom:(e.bottom??20)+"px",right:(e.right??20)+"px",width:"42px",height:"42px",borderRadius:"50%",overflow:"hidden",cursor:"grab",zIndex:999999,boxShadow:"0 0 10px rgba(0,0,0,0.25)",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center"});const r=document.createElement("img");r.src="https://dashboard.mockforme.com/public/assets/images/icon.png",r.style.objectFit="cover",t.appendChild(r),document.body.appendChild(t);const o=document.createElement("div");o.id="mockforme-widget",o.innerText="MockForMe Enabled",Object.assign(o.style,{position:"fixed",padding:"8px 12px",background:"#2563eb",color:"#fff",fontSize:"13px",fontFamily:"Inter, sans-serif",borderRadius:"8px",bottom:(e.bottom??20)+50+"px",right:(e.right??20)+"px",boxShadow:"0 4px 10px rgba(0,0,0,0.2)",zIndex:999999,display:"none",whiteSpace:"nowrap"}),document.body.appendChild(o),t.addEventListener("click",(e=>{e.stopPropagation(),o.style.display="none"===o.style.display?"block":"none"})),document.addEventListener("click",(()=>{o.style.display="none"}));let n=!1,s=0,i=0;t.addEventListener("mousedown",(e=>{n=!0,t.style.cursor="grabbing";const r=t.getBoundingClientRect();s=e.clientX-r.left,i=e.clientY-r.top,e.preventDefault()})),document.addEventListener("mousemove",(e=>{if(!n)return;const r=e.clientX-s,a=e.clientY-i,c=window.innerHeight-(a+t.offsetHeight),d=window.innerWidth-(r+t.offsetWidth);t.style.bottom=c+"px",t.style.right=d+"px",o.style.bottom=c+50+"px",o.style.right=d+"px"})),document.addEventListener("mouseup",(()=>{if(!n)return;n=!1,t.style.cursor="grab";const e=parseInt(t.style.bottom),r=parseInt(t.style.right);localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:e,right:r}))}))}()}catch(e){console.log("Error in showing mockforme widget")}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:n=[],_o:s,mk:l,_mck:m,_rules:p=[]}=t;return i(n),v({_o:s,mk:l,_mck:m,_rules:p}),{run:(t,r=()=>{})=>{O(e,o),s&&l?t(a(),{_o:s,mk:l,_mck:m,_rules:p}):function(e,r,o,n){T({method:"get",url:y,async:!1,headers:{[h]:e,[u]:f,"x-mfm-adaptor":r}},(e=>{if(e)try{const{di:n,iv:s,_o:a,_mck:c,mk:d,r:l}=e,u=P({di:n,iv:s},a);v({_o:a,mk:d,_mck:c,_rules:l}),u&&(i(u),r=u,o={_o:a,mk:d,_mck:c,_rules:l},t?.(r,o))}catch(e){return void n(new Error("Unable to fetch mocked apis"))}var r,o}),(e=>{console.log("Error in loading mocked apis"),n(e)})).request()}(e,o,0,r)},checkIfApiToBeMocked:c,getMappings:a,doFetchMappings:(t,r)=>{!function(e,t,r,o){fetch(y,{method:"GET",headers:{[h]:e,[u]:f,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:n,_mck:s,mk:a,r:c}=e,d=P({di:t,iv:o},n);v({_o:n,mk:a,_mck:s,_rules:c}),d&&(i(d),r(d,{_o:n,mk:a,_mck:s,_rules:c}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}(e,o,((e,r)=>{t?.(e,r)}),r)}}},C=r();C||(globalThis.mockforme=j);let I=j;C&&(I=e=>({run:()=>{}}));const L=I;module.exports=t})();
@@ -1 +1 @@
1
- const e=()=>"undefined"!=typeof process&&null!=process.versions?.node,t=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},r=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let o=[];function n(e){o=e}function s(){return o}function i(e,n="get"){for(const s of o)if(t(s.apiMethod)===t(n)&&(s.apiEndpoint===e||r(s.apiEndpoint,e))){const t={url:e,method:s.apiMethod,_ack:s._ack||null};return s._ri_&&(t._ri_=s._ri_),t}return null}const a="JAVASCRIPT",c="CHROME_EXTENSION",d="mfmver",l="mockforme",u="4.2.8",h="https://api.mockforme.com",m=`${h}/mockforme`,p=`${h}/gateway/3f4eae522b`;let f=null,_=null,y=null,g=[];function w({_o:e,mk:t,_mck:r,_rules:o}){f=e,_=t,y=r,g=o}function b(){return g}function x(){return`${m}/${f}/${_}`}function v(){return y}const E=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}};function k({url:e,method:t}){try{const t=b();if(!Array.isArray(t)||0===t.length)return null;const r=globalThis.location?.origin||"http://localhost";for(const o of t){const t=o.rule?.URL;if(!t)continue;const{condition:n}=t;if(!n)continue;let s="";switch(t.type){case"URL":{let t;try{t=new URL(e,r),s=t.pathname}catch{s=e}break}case"QUERY":{let t;try{t=new URL(e,r)}catch{t=null}t&&(s=t.searchParams.get(n.key)||"");break}case"BODY":case"HEADERS":s="";break;default:continue}let i=!1;switch(n.operator){case"contains":i=s.includes(n.value);break;case"equal":case"equals":i=s===n.value;break;case"regexp":try{let e=n.value;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);i=new RegExp(r,o).test(s)}else i=new RegExp(e).test(s)}catch{i=!1}}if(i){const e=n.activeAction;return{action:e,config:n.actions?.[e]||{}}}}return null}catch(e){return console.error("[mockforme] checkIfRulesToBeApplied error",e),null}}function R(e,t){!function(e,t){const r=window.fetch;window.fetch=function(o,n={}){const s="string"==typeof o?o:o.url;try{const a=new URL(s,window.location.origin),{pathname:h,search:m}=a;let p="get";n&&n.method?p=n.method:o instanceof Request&&o.method&&(p=o.method),p=p.toLowerCase();const f=k({url:s,method:p});if(t!==c&&f){if("delay"===f.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(o,n))}),1e3*f.config.value)}));if("delay_and_redirect"===f.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(f.config.redirectUrl,n))}),1e3*f.config.value)}));if("delay_and_timeout"===f.action){if(0===f.config.value){const e=new AbortController,t=r(o,{...n,signal:e.signal});return e.abort(),t.catch((()=>Promise.reject(new Error("Fetch aborted by rules"))))}return new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Fetch timed out by rules"))}),1e3*f.config.value)}))}}const _=i(h,p);if(!_&&!f)return r(o,n);let y=s;f||(y=`${x()}${_.url}${m}`);let g={};if(!f){g={[l]:e,[d]:u,"x-mfm-adaptor":t};const r=v();r&&_._ack&&(g["x-mfm-key"]=`${r}-${_._ack}`),_?._ri_&&(g._ri_=_._ri_)}const w=o instanceof Request?o.headers:n.headers,b=new Headers(w||{});Object.entries(g).forEach((([e,t])=>{b.set(e,t)}));let R=n.body;if(!R&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(R=e.text())}let T={method:p,headers:b,credentials:"include",mode:"cors"};f&&(T.credentials=o instanceof Request&&o.credentials||n.credentials||"same-origin",T.mode=o instanceof Request&&o.mode||n.mode||"cors");const S=e=>(e&&(T.body=e),t===c?(({actualUrl:e,url:t,method:r,headers:o,body:n,credentials:s,mode:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=E(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(r){if(r.source!==window)return;const o=r.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===c){if(window.removeEventListener("message",e),o?.response?.error)return l(new Error(o.response.message));const{status:r,headers:n,body:s}=o.response;t(new Response(s,{status:r,headers:n}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:s,url:y,method:p,headers:Object.fromEntries(b.entries()),body:e,credentials:T.credentials,mode:T.mode,rule:f}):fetch(y,T).then((e=>{const t=e.clone();return(t.headers.get("content-type")||"").includes("application/json")?t.json().then((r=>new Response(JSON.stringify(r),{status:e.status,headers:t.headers}))):t.text().then((r=>new Response(r,{status:e.status,headers:t.headers})))})).catch((e=>(console.warn("mockforme fetch interceptor error",e),r(o,n)))));return R instanceof Promise?R.then((e=>S(e))):S(R)}catch(e){return console.warn("mockforme fetch interceptor error",e),r(o,n)}}}(e,t),function(e,t){const r=window.XMLHttpRequest;window.XMLHttpRequest=class{constructor(){this._xhr=new r,this._headers={},this._method=null,this._url=null,this._body=null,this._setupEventHandlers()}_setupEventHandlers(){const e=["onload","onerror","onabort","ontimeout","onreadystatechange"];for(const t of e)Object.defineProperty(this,t,{get:()=>this._xhr[t],set:e=>{this._xhr[t]=e}})}open(e,t,r=!0,o=null,n=null){return this._method=e.toUpperCase(),this._url=new URL(t,window.location.href).toString(),this._xhr._mockOriginalUrl=this._url,this._xhr._mockMethod=this._method,this._xhr.open(e,t,r,o,n)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(o){this._body=o;try{const n=new URL(this._url),{pathname:s,search:a}=n,h=k({url:this._url,method:this._method});if(t!==c&&h){if("delay"===h.action)return setTimeout((()=>this._xhr.send(o)),1e3*h.config.value);if("delay_and_redirect"===h.action)return setTimeout((()=>{this._xhr.open(this._method,h.config.redirectUrl,!0),this._xhr.send(o)}),1e3*h.config.value);if("delay_and_timeout"===h.action)return 0===h.config.value?(this._xhr.open(this._method,this._url,!0),this._xhr.send(o),this._xhr.abort(),void("function"==typeof this.onerror&&this.onerror(new Error("XHR aborted by rules")))):setTimeout((()=>{this._xhr.abort(),"function"==typeof this.onerror&&this.onerror(new Error("XHR timed out by rules"))}),1e3*h.config.value)}const m=i(s,this._method);if(!m&&!h)return this._xhr.send(o);let p=this._url;h||(p=`${x()}${m.url}${a}`);let f={};if(!h){f={[l]:e,[d]:u,"x-mfm-adaptor":t};const r=v();r&&m._ack&&(f["x-mfm-key"]=`${r}-${m._ack}`),m?._ri_&&(f._ri_=m._ri_)}const _={...this._headers,...f};if(t===c)(({actualUrl:e,url:t,method:r,headers:o,body:n,onSuccess:s,onError:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=E(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const r=t.data;if("INTERCEPTED_RESPONSE"===r.type&&r.requestId===c){if(window.removeEventListener("message",e),r.response?.error)return i?.(r.response.message);const{body:t,status:o,headers:n}=r.response;s?.({body:t,status:o,headers:n})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:this._url,url:p,method:this._method,headers:_,body:this._body,rule:h,onSuccess:({body:e,status:t})=>{Object.defineProperty(this,"responseText",{value:e}),Object.defineProperty(this,"status",{value:t}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.()},onError:e=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(new Error(e.message||"XHR mock error"))}});else{const e=new r;e.open(this._method,p,!0);for(const t in _)e.setRequestHeader(t,_[t]);e.withCredentials=this.withCredentials,e.onload=()=>{Object.defineProperty(this,"responseText",{value:e.responseText}),Object.defineProperty(this,"status",{value:e.status}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.()},e.onerror=()=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.()},e.send(this._body)}}catch(e){console.error("[mockforme][XHR] interception error",e)}}addEventListener(...e){return this._xhr.addEventListener(...e)}removeEventListener(...e){return this._xhr.removeEventListener(...e)}dispatchEvent(...e){return this._xhr.dispatchEvent(...e)}abort(){return this._xhr.abort()}getAllResponseHeaders(){return this._xhr.getAllResponseHeaders()}getResponseHeader(e){return this._xhr.getResponseHeader(e)}overrideMimeType(e){return this._xhr.overrideMimeType(e)}get readyState(){return this._xhr.readyState}get responseText(){return this._xhr.responseText}get status(){return this._xhr.status}get response(){return this._xhr.response}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get withCredentials(){return this._xhr.withCredentials}set withCredentials(e){this._xhr.withCredentials=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}get upload(){return this._xhr.upload}}}(e,t)}const T=function(t,r,o){const n=e();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var r=e.split(";");try{return"application/json"===r[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();r.call(this,e,s)}else o.call(this,s.responseText,s)}function a(e,t){var r=[];for(var o in e)if(e.hasOwnProperty(o)){var n=t?t+"["+o+"]":o,s=e[o];r.push("object"==typeof s?a(s,n):encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}return n||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!n){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var e=a(t.params);if("get"==t.method.toLowerCase()&&"object"==typeof t.params){if(-1==t.url.indexOf("?"))t.url+="?";else{var r=t.url.split("?");r[1]&&r[1].split("=")[1]&&(t.url+="&")}t.url+=e}t.hasOwnProperty("async")||(t.async=!0),s.open(t.method,t.url,t.async),t.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(t.headers),s.send(e)}}}};function S({di:e,iv:t},r){var o;const n=function(e,t){const r=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(n)}const O=(t,r=null,o=a)=>{if(e())return;if(o===a)try{!function(){if(!window.mockforme)return;const e=JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"),t=document.createElement("div");t.id="mockforme-dot",Object.assign(t.style,{position:"fixed",bottom:(e.bottom??20)+"px",right:(e.right??20)+"px",width:"42px",height:"42px",borderRadius:"50%",overflow:"hidden",cursor:"grab",zIndex:999999,boxShadow:"0 0 10px rgba(0,0,0,0.25)",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center"});const r=document.createElement("img");r.src="https://dashboard.mockforme.com/public/assets/images/icon.png",r.style.objectFit="cover",t.appendChild(r),document.body.appendChild(t);const o=document.createElement("div");o.id="mockforme-widget",o.innerText="MockForMe Enabled",Object.assign(o.style,{position:"fixed",padding:"8px 12px",background:"#2563eb",color:"#fff",fontSize:"13px",fontFamily:"Inter, sans-serif",borderRadius:"8px",bottom:(e.bottom??20)+50+"px",right:(e.right??20)+"px",boxShadow:"0 4px 10px rgba(0,0,0,0.2)",zIndex:999999,display:"none",whiteSpace:"nowrap"}),document.body.appendChild(o),t.addEventListener("click",(e=>{e.stopPropagation(),o.style.display="none"===o.style.display?"block":"none"})),document.addEventListener("click",(()=>{o.style.display="none"}));let n=!1,s=0,i=0;t.addEventListener("mousedown",(e=>{n=!0,t.style.cursor="grabbing";const r=t.getBoundingClientRect();s=e.clientX-r.left,i=e.clientY-r.top,e.preventDefault()})),document.addEventListener("mousemove",(e=>{if(!n)return;const r=e.clientX-s,a=e.clientY-i,c=window.innerHeight-(a+t.offsetHeight),d=window.innerWidth-(r+t.offsetWidth);t.style.bottom=c+"px",t.style.right=d+"px",o.style.bottom=c+50+"px",o.style.right=d+"px"})),document.addEventListener("mouseup",(()=>{if(!n)return;n=!1,t.style.cursor="grab";const e=parseInt(t.style.bottom),r=parseInt(t.style.right);localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:e,right:r}))}))}()}catch(e){console.log("Error in showing mockforme widget")}r||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:c=[],_o:h,mk:m,_mck:f,_rules:_=[]}=r;return n(c),w({_o:h,mk:m,_mck:f,_rules:_}),{run:(e,r=()=>{})=>{R(t,o),h&&m?e(s(),{_o:h,mk:m,_mck:f,_rules:_}):function(t,r,o,s){T({method:"get",url:p,async:!1,headers:{[l]:t,[d]:u,"x-mfm-adaptor":r}},(t=>{if(t)try{const{di:s,iv:i,_o:a,_mck:c,mk:d,r:l}=t,u=S({di:s,iv:i},a);w({_o:a,mk:d,_mck:c,_rules:l}),u&&(n(u),r=u,o={_o:a,mk:d,_mck:c,_rules:l},e?.(r,o))}catch(e){return void s(new Error("Unable to fetch mocked apis"))}var r,o}),(e=>{console.log("Error in loading mocked apis"),s(e)})).request()}(t,o,0,r)},checkIfApiToBeMocked:i,getMappings:s,doFetchMappings:(e,r)=>{!function(e,t,r,o){fetch(p,{method:"GET",headers:{[l]:e,[d]:u,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:s,_mck:i,mk:a,r:c}=e,d=S({di:t,iv:o},s);w({_o:s,mk:a,_mck:i,_rules:c}),d&&(n(d),r(d,{_o:s,mk:a,_mck:i,_rules:c}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}(t,o,((t,r)=>{e?.(t,r)}),r)}}},C=e();C||(globalThis.mockforme=O);let L=O;C&&(L=e=>({run:()=>{}}));const j=L;export{j as mockforme};
1
+ const e=()=>"undefined"!=typeof process&&null!=process.versions?.node,t=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},r=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let o=[];function n(e){o=e}function s(){return o}function i(e,n="get"){for(const s of o)if(t(s.apiMethod)===t(n)&&(s.apiEndpoint===e||r(s.apiEndpoint,e))){const t={url:e,method:s.apiMethod,_ack:s._ack||null};return s._ri_&&(t._ri_=s._ri_),t}return null}const a="JAVASCRIPT",c="CHROME_EXTENSION",d="mfmver",l="mockforme",u="4.2.8",h="https://api.mockforme.com",f=`${h}/mockforme`,m=`${h}/gateway/3f4eae522b`;let p=null,_=null,y=null,w=[];function g({_o:e,mk:t,_mck:r,_rules:o}){p=e,_=t,y=r,w=o}function b(){return w}function v(){return`${f}/${p}/${_}`}function E(){return y}const x=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}};function k({url:e,method:t}){try{const t=b();if(!Array.isArray(t)||0===t.length)return null;const r=globalThis.location?.origin||"http://localhost";for(const o of t){const t=o.rule?.URL;if(!t)continue;const{condition:n}=t;if(!n)continue;let s="";switch(t.type){case"URL":{let t;try{t=new URL(e,r),s=t.pathname}catch{s=e}break}case"QUERY":{let t;try{t=new URL(e,r)}catch{t=null}t&&(s=t.searchParams.get(n.key)||"");break}case"BODY":case"HEADERS":s="";break;default:continue}let i=!1;switch(n.operator){case"contains":i=s.includes(n.value);break;case"equal":case"equals":i=s===n.value;break;case"regexp":try{let e=n.value;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);i=new RegExp(r,o).test(s)}else i=new RegExp(e).test(s)}catch{i=!1}}if(i){const e=n.activeAction;return{action:e,config:n.actions?.[e]||{}}}}return null}catch(e){return console.error("[mockforme] checkIfRulesToBeApplied error",e),null}}function R(e,t){!function(e,t){const r=window.fetch;window.fetch=function(o,n={}){const s="string"==typeof o?o:o.url;try{const a=new URL(s,window.location.origin),{pathname:h,search:f}=a;let m="get";n&&n.method?m=n.method:o instanceof Request&&o.method&&(m=o.method),m=m.toLowerCase();const p=k({url:s,method:m});if(t!==c&&p){if("delay"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(o,n))}),1e3*p.config.value)}));if("delay_and_redirect"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(p.config.redirectUrl,n))}),1e3*p.config.value)}));if("delay_and_timeout"===p.action){if(0===p.config.value){const e=new AbortController,t=r(o,{...n,signal:e.signal});return e.abort(),t.catch((()=>Promise.reject(new Error("Fetch aborted by rules"))))}return new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Fetch timed out by rules"))}),1e3*p.config.value)}))}}const _=i(h,m);if(!_&&!p)return r(o,n);let y=s;p||(y=`${v()}${_.url}${f}`);let w={};if(!p){w={[l]:e,[d]:u,"x-mfm-adaptor":t};const r=E();r&&_._ack&&(w["x-mfm-key"]=`${r}-${_._ack}`),_?._ri_&&(w._ri_=_._ri_)}const g=o instanceof Request?o.headers:n.headers,b=new Headers(g||{});Object.entries(w).forEach((([e,t])=>{b.set(e,t)}));let R=n.body;if(!R&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(R=e.text())}let T={method:m,headers:b,credentials:"include",mode:"cors"};p&&(T.credentials=o instanceof Request&&o.credentials||n.credentials||"same-origin",T.mode=o instanceof Request&&o.mode||n.mode||"cors");const S=e=>(e&&(T.body=e),t===c?(({actualUrl:e,url:t,method:r,headers:o,body:n,credentials:s,mode:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=x(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(r){if(r.source!==window)return;const o=r.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===c){if(window.removeEventListener("message",e),o?.response?.error)return l(new Error(o.response.message));const{status:r,headers:n,body:s}=o.response;t(new Response(s,{status:r,headers:n}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:s,url:y,method:m,headers:Object.fromEntries(b.entries()),body:e,credentials:T.credentials,mode:T.mode,rule:p}):fetch(y,T).then((e=>{const t=e.clone();return(t.headers.get("content-type")||"").includes("application/json")?t.json().then((r=>new Response(JSON.stringify(r),{status:e.status,headers:t.headers}))):t.text().then((r=>new Response(r,{status:e.status,headers:t.headers})))})).catch((e=>(console.warn("mockforme fetch interceptor error",e),r(o,n)))));return R instanceof Promise?R.then((e=>S(e))):S(R)}catch(e){return console.warn("mockforme fetch interceptor error",e),r(o,n)}}}(e,t),function(e,t){const r=window.XMLHttpRequest;window.XMLHttpRequest=class{constructor(){return this._xhr=new r,this._headers={},this._method=null,this._url=null,this._body=null,new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const r=e._xhr[t];return"function"==typeof r?r.bind(e._xhr):r},set:(e,t,r)=>t in e?(e[t]=r,!0):(e._xhr[t]=r,!0)})}open(e,t,r=!0,o=null,n=null){return this._method=e.toUpperCase(),this._url=new URL(t,window.location.href).toString(),this._xhr._mockOriginalUrl=this._url,this._xhr._mockMethod=this._method,this._xhr.open(e,t,r,o,n)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(o){this._body=o;try{const n=new URL(this._url),{pathname:s,search:a}=n,h=k({url:this._url,method:this._method});if(t!==c&&h){if("delay"===h.action)return setTimeout((()=>this._xhr.send(o)),1e3*h.config.value);if("delay_and_redirect"===h.action)return setTimeout((()=>{this._xhr.open(this._method,h.config.redirectUrl,!0),this._xhr.send(o)}),1e3*h.config.value);if("delay_and_timeout"===h.action)return 0===h.config.value?(this._xhr.open(this._method,this._url,!0),this._xhr.send(o),this._xhr.abort(),void("function"==typeof this.onerror&&this.onerror(new Error("XHR aborted by rules")))):setTimeout((()=>{this._xhr.abort(),"function"==typeof this.onerror&&this.onerror(new Error("XHR timed out by rules"))}),1e3*h.config.value)}const f=i(s,this._method);if(!f&&!h)return this._xhr.send(o);let m=this._url;h||(m=`${v()}${f.url}${a}`);let p={};if(!h){p={[l]:e,[d]:u,"x-mfm-adaptor":t};const r=E();r&&f._ack&&(p["x-mfm-key"]=`${r}-${f._ack}`),f?._ri_&&(p._ri_=f._ri_)}const _={...this._headers,...p};if(t===c)(({actualUrl:e,url:t,method:r,headers:o,body:n,onSuccess:s,onError:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=x(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const r=t.data;if("INTERCEPTED_RESPONSE"===r.type&&r.requestId===c){if(window.removeEventListener("message",e),r.response?.error)return i?.(r.response.message);const{body:t,status:o,headers:n}=r.response;s?.({body:t,status:o,headers:n})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:this._url,url:m,method:this._method,headers:_,body:this._body,rule:h,onSuccess:({body:e,status:t})=>{Object.defineProperty(this,"responseText",{value:e}),Object.defineProperty(this,"status",{value:t}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("load"))},onError:e=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(new Error(e.message||"XHR mock error")),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("error"))}});else{const e=new r;e.open(this._method,m,!0);for(const t in _)e.setRequestHeader(t,_[t]);e.withCredentials=this.withCredentials,e.onload=()=>{Object.defineProperty(this,"responseText",{value:e.responseText}),Object.defineProperty(this,"status",{value:e.status}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("load"))},e.onerror=()=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("error"))},e.send(this._body)}}catch(e){console.error("[mockforme][XHR] interception error",e)}}}}(e,t)}const T=function(t,r,o){const n=e();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var r=e.split(";");try{return"application/json"===r[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();r.call(this,e,s)}else o.call(this,s.responseText,s)}function a(e,t){var r=[];for(var o in e)if(e.hasOwnProperty(o)){var n=t?t+"["+o+"]":o,s=e[o];r.push("object"==typeof s?a(s,n):encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}return n||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!n){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var e=a(t.params);if("get"==t.method.toLowerCase()&&"object"==typeof t.params){if(-1==t.url.indexOf("?"))t.url+="?";else{var r=t.url.split("?");r[1]&&r[1].split("=")[1]&&(t.url+="&")}t.url+=e}t.hasOwnProperty("async")||(t.async=!0),s.open(t.method,t.url,t.async),t.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(t.headers),s.send(e)}}}};function S({di:e,iv:t},r){var o;const n=function(e,t){const r=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(n)}const O=(t,r=null,o=a)=>{if(e())return;if(o===a)try{!function(){if(!window.mockforme)return;const e=JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"),t=document.createElement("div");t.id="mockforme-dot",Object.assign(t.style,{position:"fixed",bottom:(e.bottom??20)+"px",right:(e.right??20)+"px",width:"42px",height:"42px",borderRadius:"50%",overflow:"hidden",cursor:"grab",zIndex:999999,boxShadow:"0 0 10px rgba(0,0,0,0.25)",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center"});const r=document.createElement("img");r.src="https://dashboard.mockforme.com/public/assets/images/icon.png",r.style.objectFit="cover",t.appendChild(r),document.body.appendChild(t);const o=document.createElement("div");o.id="mockforme-widget",o.innerText="MockForMe Enabled",Object.assign(o.style,{position:"fixed",padding:"8px 12px",background:"#2563eb",color:"#fff",fontSize:"13px",fontFamily:"Inter, sans-serif",borderRadius:"8px",bottom:(e.bottom??20)+50+"px",right:(e.right??20)+"px",boxShadow:"0 4px 10px rgba(0,0,0,0.2)",zIndex:999999,display:"none",whiteSpace:"nowrap"}),document.body.appendChild(o),t.addEventListener("click",(e=>{e.stopPropagation(),o.style.display="none"===o.style.display?"block":"none"})),document.addEventListener("click",(()=>{o.style.display="none"}));let n=!1,s=0,i=0;t.addEventListener("mousedown",(e=>{n=!0,t.style.cursor="grabbing";const r=t.getBoundingClientRect();s=e.clientX-r.left,i=e.clientY-r.top,e.preventDefault()})),document.addEventListener("mousemove",(e=>{if(!n)return;const r=e.clientX-s,a=e.clientY-i,c=window.innerHeight-(a+t.offsetHeight),d=window.innerWidth-(r+t.offsetWidth);t.style.bottom=c+"px",t.style.right=d+"px",o.style.bottom=c+50+"px",o.style.right=d+"px"})),document.addEventListener("mouseup",(()=>{if(!n)return;n=!1,t.style.cursor="grab";const e=parseInt(t.style.bottom),r=parseInt(t.style.right);localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:e,right:r}))}))}()}catch(e){console.log("Error in showing mockforme widget")}r||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:c=[],_o:h,mk:f,_mck:p,_rules:_=[]}=r;return n(c),g({_o:h,mk:f,_mck:p,_rules:_}),{run:(e,r=()=>{})=>{R(t,o),h&&f?e(s(),{_o:h,mk:f,_mck:p,_rules:_}):function(t,r,o,s){T({method:"get",url:m,async:!1,headers:{[l]:t,[d]:u,"x-mfm-adaptor":r}},(t=>{if(t)try{const{di:s,iv:i,_o:a,_mck:c,mk:d,r:l}=t,u=S({di:s,iv:i},a);g({_o:a,mk:d,_mck:c,_rules:l}),u&&(n(u),r=u,o={_o:a,mk:d,_mck:c,_rules:l},e?.(r,o))}catch(e){return void s(new Error("Unable to fetch mocked apis"))}var r,o}),(e=>{console.log("Error in loading mocked apis"),s(e)})).request()}(t,o,0,r)},checkIfApiToBeMocked:i,getMappings:s,doFetchMappings:(e,r)=>{!function(e,t,r,o){fetch(m,{method:"GET",headers:{[l]:e,[d]:u,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:s,_mck:i,mk:a,r:c}=e,d=S({di:t,iv:o},s);g({_o:s,mk:a,_mck:i,_rules:c}),d&&(n(d),r(d,{_o:s,mk:a,_mck:i,_rules:c}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}(t,o,((t,r)=>{e?.(t,r)}),r)}}},P=e();P||(globalThis.mockforme=O);let j=O;P&&(j=e=>({run:()=>{}}));const C=j;export{C as mockforme};
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mockforme=t():e.mockforme=t()}(this,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{mockforme:()=>H});const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},n=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let s=[];function i(e){s=e}function a(){return s}function c(e,t="get"){for(const r of s)if(o(r.apiMethod)===o(t)&&(r.apiEndpoint===e||n(r.apiEndpoint,e))){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}return null}const d="JAVASCRIPT",l="CHROME_EXTENSION",u="mfmver",h="mockforme",m="4.2.8",f="https://api.mockforme.com",p=`${f}/mockforme`,_=`${f}/gateway/3f4eae522b`;let y=null,g=null,w=null,b=[];function x({_o:e,mk:t,_mck:r,_rules:o}){y=e,g=t,w=r,b=o}function v(){return b}function k(){return`${p}/${y}/${g}`}function E(){return w}const R=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}};function T({url:e,method:t}){try{const t=v();if(!Array.isArray(t)||0===t.length)return null;const r=globalThis.location?.origin||"http://localhost";for(const o of t){const t=o.rule?.URL;if(!t)continue;const{condition:n}=t;if(!n)continue;let s="";switch(t.type){case"URL":{let t;try{t=new URL(e,r),s=t.pathname}catch{s=e}break}case"QUERY":{let t;try{t=new URL(e,r)}catch{t=null}t&&(s=t.searchParams.get(n.key)||"");break}case"BODY":case"HEADERS":s="";break;default:continue}let i=!1;switch(n.operator){case"contains":i=s.includes(n.value);break;case"equal":case"equals":i=s===n.value;break;case"regexp":try{let e=n.value;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);i=new RegExp(r,o).test(s)}else i=new RegExp(e).test(s)}catch{i=!1}}if(i){const e=n.activeAction;return{action:e,config:n.actions?.[e]||{}}}}return null}catch(e){return console.error("[mockforme] checkIfRulesToBeApplied error",e),null}}function O(e,t){!function(e,t){const r=window.fetch;window.fetch=function(o,n={}){const s="string"==typeof o?o:o.url;try{const i=new URL(s,window.location.origin),{pathname:a,search:d}=i;let f="get";n&&n.method?f=n.method:o instanceof Request&&o.method&&(f=o.method),f=f.toLowerCase();const p=T({url:s,method:f});if(t!==l&&p){if("delay"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(o,n))}),1e3*p.config.value)}));if("delay_and_redirect"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(r(p.config.redirectUrl,n))}),1e3*p.config.value)}));if("delay_and_timeout"===p.action){if(0===p.config.value){const e=new AbortController,t=r(o,{...n,signal:e.signal});return e.abort(),t.catch((()=>Promise.reject(new Error("Fetch aborted by rules"))))}return new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Fetch timed out by rules"))}),1e3*p.config.value)}))}}const _=c(a,f);if(!_&&!p)return r(o,n);let y=s;p||(y=`${k()}${_.url}${d}`);let g={};if(!p){g={[h]:e,[u]:m,"x-mfm-adaptor":t};const r=E();r&&_._ack&&(g["x-mfm-key"]=`${r}-${_._ack}`),_?._ri_&&(g._ri_=_._ri_)}const w=o instanceof Request?o.headers:n.headers,b=new Headers(w||{});Object.entries(g).forEach((([e,t])=>{b.set(e,t)}));let x=n.body;if(!x&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(x=e.text())}let v={method:f,headers:b,credentials:"include",mode:"cors"};p&&(v.credentials=o instanceof Request&&o.credentials||n.credentials||"same-origin",v.mode=o instanceof Request&&o.mode||n.mode||"cors");const O=e=>(e&&(v.body=e),t===l?(({actualUrl:e,url:t,method:r,headers:o,body:n,credentials:s,mode:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(r){if(r.source!==window)return;const o=r.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===c){if(window.removeEventListener("message",e),o?.response?.error)return l(new Error(o.response.message));const{status:r,headers:n,body:s}=o.response;t(new Response(s,{status:r,headers:n}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:s,url:y,method:f,headers:Object.fromEntries(b.entries()),body:e,credentials:v.credentials,mode:v.mode,rule:p}):fetch(y,v).then((e=>{const t=e.clone();return(t.headers.get("content-type")||"").includes("application/json")?t.json().then((r=>new Response(JSON.stringify(r),{status:e.status,headers:t.headers}))):t.text().then((r=>new Response(r,{status:e.status,headers:t.headers})))})).catch((e=>(console.warn("mockforme fetch interceptor error",e),r(o,n)))));return x instanceof Promise?x.then((e=>O(e))):O(x)}catch(e){return console.warn("mockforme fetch interceptor error",e),r(o,n)}}}(e,t),function(e,t){const r=window.XMLHttpRequest;window.XMLHttpRequest=class{constructor(){this._xhr=new r,this._headers={},this._method=null,this._url=null,this._body=null,this._setupEventHandlers()}_setupEventHandlers(){const e=["onload","onerror","onabort","ontimeout","onreadystatechange"];for(const t of e)Object.defineProperty(this,t,{get:()=>this._xhr[t],set:e=>{this._xhr[t]=e}})}open(e,t,r=!0,o=null,n=null){return this._method=e.toUpperCase(),this._url=new URL(t,window.location.href).toString(),this._xhr._mockOriginalUrl=this._url,this._xhr._mockMethod=this._method,this._xhr.open(e,t,r,o,n)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(o){this._body=o;try{const n=new URL(this._url),{pathname:s,search:i}=n,a=T({url:this._url,method:this._method});if(t!==l&&a){if("delay"===a.action)return setTimeout((()=>this._xhr.send(o)),1e3*a.config.value);if("delay_and_redirect"===a.action)return setTimeout((()=>{this._xhr.open(this._method,a.config.redirectUrl,!0),this._xhr.send(o)}),1e3*a.config.value);if("delay_and_timeout"===a.action)return 0===a.config.value?(this._xhr.open(this._method,this._url,!0),this._xhr.send(o),this._xhr.abort(),void("function"==typeof this.onerror&&this.onerror(new Error("XHR aborted by rules")))):setTimeout((()=>{this._xhr.abort(),"function"==typeof this.onerror&&this.onerror(new Error("XHR timed out by rules"))}),1e3*a.config.value)}const d=c(s,this._method);if(!d&&!a)return this._xhr.send(o);let f=this._url;a||(f=`${k()}${d.url}${i}`);let p={};if(!a){p={[h]:e,[u]:m,"x-mfm-adaptor":t};const r=E();r&&d._ack&&(p["x-mfm-key"]=`${r}-${d._ack}`),d?._ri_&&(p._ri_=d._ri_)}const _={...this._headers,...p};if(t===l)(({actualUrl:e,url:t,method:r,headers:o,body:n,onSuccess:s,onError:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const r=t.data;if("INTERCEPTED_RESPONSE"===r.type&&r.requestId===c){if(window.removeEventListener("message",e),r.response?.error)return i?.(r.response.message);const{body:t,status:o,headers:n}=r.response;s?.({body:t,status:o,headers:n})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:r,headers:o,body:n,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:this._url,url:f,method:this._method,headers:_,body:this._body,rule:a,onSuccess:({body:e,status:t})=>{Object.defineProperty(this,"responseText",{value:e}),Object.defineProperty(this,"status",{value:t}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.()},onError:e=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(new Error(e.message||"XHR mock error"))}});else{const e=new r;e.open(this._method,f,!0);for(const t in _)e.setRequestHeader(t,_[t]);e.withCredentials=this.withCredentials,e.onload=()=>{Object.defineProperty(this,"responseText",{value:e.responseText}),Object.defineProperty(this,"status",{value:e.status}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.()},e.onerror=()=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.()},e.send(this._body)}}catch(e){console.error("[mockforme][XHR] interception error",e)}}addEventListener(...e){return this._xhr.addEventListener(...e)}removeEventListener(...e){return this._xhr.removeEventListener(...e)}dispatchEvent(...e){return this._xhr.dispatchEvent(...e)}abort(){return this._xhr.abort()}getAllResponseHeaders(){return this._xhr.getAllResponseHeaders()}getResponseHeader(e){return this._xhr.getResponseHeader(e)}overrideMimeType(e){return this._xhr.overrideMimeType(e)}get readyState(){return this._xhr.readyState}get responseText(){return this._xhr.responseText}get status(){return this._xhr.status}get response(){return this._xhr.response}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get withCredentials(){return this._xhr.withCredentials}set withCredentials(e){this._xhr.withCredentials=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}get upload(){return this._xhr.upload}}}(e,t)}const S=function(e,t,o){const n=r();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var r=e.split(";");try{return"application/json"===r[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();t.call(this,e,s)}else o.call(this,s.responseText,s)}function a(e,t){var r=[];for(var o in e)if(e.hasOwnProperty(o)){var n=t?t+"["+o+"]":o,s=e[o];r.push("object"==typeof s?a(s,n):encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}return n||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!n){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var t=a(e.params);if("get"==e.method.toLowerCase()&&"object"==typeof e.params){if(-1==e.url.indexOf("?"))e.url+="?";else{var r=e.url.split("?");r[1]&&r[1].split("=")[1]&&(e.url+="&")}e.url+=t}e.hasOwnProperty("async")||(e.async=!0),s.open(e.method,e.url,e.async),e.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(e.headers),s.send(t)}}}};function j({di:e,iv:t},r){var o;const n=function(e,t){const r=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(n)}const C=(e,t=null,o=d)=>{if(r())return;if(o===d)try{!function(){if(!window.mockforme)return;const e=JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"),t=document.createElement("div");t.id="mockforme-dot",Object.assign(t.style,{position:"fixed",bottom:(e.bottom??20)+"px",right:(e.right??20)+"px",width:"42px",height:"42px",borderRadius:"50%",overflow:"hidden",cursor:"grab",zIndex:999999,boxShadow:"0 0 10px rgba(0,0,0,0.25)",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center"});const r=document.createElement("img");r.src="https://dashboard.mockforme.com/public/assets/images/icon.png",r.style.objectFit="cover",t.appendChild(r),document.body.appendChild(t);const o=document.createElement("div");o.id="mockforme-widget",o.innerText="MockForMe Enabled",Object.assign(o.style,{position:"fixed",padding:"8px 12px",background:"#2563eb",color:"#fff",fontSize:"13px",fontFamily:"Inter, sans-serif",borderRadius:"8px",bottom:(e.bottom??20)+50+"px",right:(e.right??20)+"px",boxShadow:"0 4px 10px rgba(0,0,0,0.2)",zIndex:999999,display:"none",whiteSpace:"nowrap"}),document.body.appendChild(o),t.addEventListener("click",(e=>{e.stopPropagation(),o.style.display="none"===o.style.display?"block":"none"})),document.addEventListener("click",(()=>{o.style.display="none"}));let n=!1,s=0,i=0;t.addEventListener("mousedown",(e=>{n=!0,t.style.cursor="grabbing";const r=t.getBoundingClientRect();s=e.clientX-r.left,i=e.clientY-r.top,e.preventDefault()})),document.addEventListener("mousemove",(e=>{if(!n)return;const r=e.clientX-s,a=e.clientY-i,c=window.innerHeight-(a+t.offsetHeight),d=window.innerWidth-(r+t.offsetWidth);t.style.bottom=c+"px",t.style.right=d+"px",o.style.bottom=c+50+"px",o.style.right=d+"px"})),document.addEventListener("mouseup",(()=>{if(!n)return;n=!1,t.style.cursor="grab";const e=parseInt(t.style.bottom),r=parseInt(t.style.right);localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:e,right:r}))}))}()}catch(e){console.log("Error in showing mockforme widget")}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:n=[],_o:s,mk:l,_mck:f,_rules:p=[]}=t;return i(n),x({_o:s,mk:l,_mck:f,_rules:p}),{run:(t,r=()=>{})=>{O(e,o),s&&l?t(a(),{_o:s,mk:l,_mck:f,_rules:p}):function(e,r,o,n){S({method:"get",url:_,async:!1,headers:{[h]:e,[u]:m,"x-mfm-adaptor":r}},(e=>{if(e)try{const{di:n,iv:s,_o:a,_mck:c,mk:d,r:l}=e,u=j({di:n,iv:s},a);x({_o:a,mk:d,_mck:c,_rules:l}),u&&(i(u),r=u,o={_o:a,mk:d,_mck:c,_rules:l},t?.(r,o))}catch(e){return void n(new Error("Unable to fetch mocked apis"))}var r,o}),(e=>{console.log("Error in loading mocked apis"),n(e)})).request()}(e,o,0,r)},checkIfApiToBeMocked:c,getMappings:a,doFetchMappings:(t,r)=>{!function(e,t,r,o){fetch(_,{method:"GET",headers:{[h]:e,[u]:m,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:n,_mck:s,mk:a,r:c}=e,d=j({di:t,iv:o},n);x({_o:n,mk:a,_mck:s,_rules:c}),d&&(i(d),r(d,{_o:n,mk:a,_mck:s,_rules:c}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}(e,o,((e,r)=>{t?.(e,r)}),r)}}},L=r();L||(globalThis.mockforme=C);let P=C;L&&(P=e=>({run:()=>{}}));const H=P;return t.mockforme})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mockforme=t():e.mockforme=t()}(this,(()=>(()=>{"use strict";var e={d:(t,o)=>{for(var r in o)e.o(o,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:o[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{mockforme:()=>L});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,r=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},n=(e,t)=>{const o=e.split("/"),r=t.split("/");if(o.length!==r.length)return!1;for(let e=0;e<o.length;e++){const t=o[e];if(t!==r[e]&&":any"!==t)return!1}return!0};let s=[];function i(e){s=e}function a(){return s}function c(e,t="get"){for(const o of s)if(r(o.apiMethod)===r(t)&&(o.apiEndpoint===e||n(o.apiEndpoint,e))){const t={url:e,method:o.apiMethod,_ack:o._ack||null};return o._ri_&&(t._ri_=o._ri_),t}return null}const d="JAVASCRIPT",l="CHROME_EXTENSION",u="mfmver",h="mockforme",f="4.2.8",m="https://api.mockforme.com",p=`${m}/mockforme`,y=`${m}/gateway/3f4eae522b`;let _=null,w=null,g=null,b=[];function v({_o:e,mk:t,_mck:o,_rules:r}){_=e,w=t,g=o,b=r}function E(){return b}function x(){return`${p}/${_}/${w}`}function k(){return g}const R=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}};function O({url:e,method:t}){try{const t=E();if(!Array.isArray(t)||0===t.length)return null;const o=globalThis.location?.origin||"http://localhost";for(const r of t){const t=r.rule?.URL;if(!t)continue;const{condition:n}=t;if(!n)continue;let s="";switch(t.type){case"URL":{let t;try{t=new URL(e,o),s=t.pathname}catch{s=e}break}case"QUERY":{let t;try{t=new URL(e,o)}catch{t=null}t&&(s=t.searchParams.get(n.key)||"");break}case"BODY":case"HEADERS":s="";break;default:continue}let i=!1;switch(n.operator){case"contains":i=s.includes(n.value);break;case"equal":case"equals":i=s===n.value;break;case"regexp":try{let e=n.value;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),o=e.slice(1,t),r=e.slice(t+1);i=new RegExp(o,r).test(s)}else i=new RegExp(e).test(s)}catch{i=!1}}if(i){const e=n.activeAction;return{action:e,config:n.actions?.[e]||{}}}}return null}catch(e){return console.error("[mockforme] checkIfRulesToBeApplied error",e),null}}function T(e,t){!function(e,t){const o=window.fetch;window.fetch=function(r,n={}){const s="string"==typeof r?r:r.url;try{const i=new URL(s,window.location.origin),{pathname:a,search:d}=i;let m="get";n&&n.method?m=n.method:r instanceof Request&&r.method&&(m=r.method),m=m.toLowerCase();const p=O({url:s,method:m});if(t!==l&&p){if("delay"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(o(r,n))}),1e3*p.config.value)}));if("delay_and_redirect"===p.action)return new Promise(((e,t)=>{setTimeout((()=>{e(o(p.config.redirectUrl,n))}),1e3*p.config.value)}));if("delay_and_timeout"===p.action){if(0===p.config.value){const e=new AbortController,t=o(r,{...n,signal:e.signal});return e.abort(),t.catch((()=>Promise.reject(new Error("Fetch aborted by rules"))))}return new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Fetch timed out by rules"))}),1e3*p.config.value)}))}}const y=c(a,m);if(!y&&!p)return o(r,n);let _=s;p||(_=`${x()}${y.url}${d}`);let w={};if(!p){w={[h]:e,[u]:f,"x-mfm-adaptor":t};const o=k();o&&y._ack&&(w["x-mfm-key"]=`${o}-${y._ack}`),y?._ri_&&(w._ri_=y._ri_)}const g=r instanceof Request?r.headers:n.headers,b=new Headers(g||{});Object.entries(w).forEach((([e,t])=>{b.set(e,t)}));let v=n.body;if(!v&&r instanceof Request){const e=r.clone();"GET"!==e.method&&"HEAD"!==e.method&&(v=e.text())}let E={method:m,headers:b,credentials:"include",mode:"cors"};p&&(E.credentials=r instanceof Request&&r.credentials||n.credentials||"same-origin",E.mode=r instanceof Request&&r.mode||n.mode||"cors");const T=e=>(e&&(E.body=e),t===l?(({actualUrl:e,url:t,method:o,headers:r,body:n,credentials:s,mode:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(o){if(o.source!==window)return;const r=o.data;if("INTERCEPTED_RESPONSE"===r?.type&&r?.requestId===c){if(window.removeEventListener("message",e),r?.response?.error)return l(new Error(r.response.message));const{status:o,headers:n,body:s}=r.response;t(new Response(s,{status:o,headers:n}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:o,headers:r,body:n,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:s,url:_,method:m,headers:Object.fromEntries(b.entries()),body:e,credentials:E.credentials,mode:E.mode,rule:p}):fetch(_,E).then((e=>{const t=e.clone();return(t.headers.get("content-type")||"").includes("application/json")?t.json().then((o=>new Response(JSON.stringify(o),{status:e.status,headers:t.headers}))):t.text().then((o=>new Response(o,{status:e.status,headers:t.headers})))})).catch((e=>(console.warn("mockforme fetch interceptor error",e),o(r,n)))));return v instanceof Promise?v.then((e=>T(e))):T(v)}catch(e){return console.warn("mockforme fetch interceptor error",e),o(r,n)}}}(e,t),function(e,t){const o=window.XMLHttpRequest;window.XMLHttpRequest=class{constructor(){return this._xhr=new o,this._headers={},this._method=null,this._url=null,this._body=null,new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const o=e._xhr[t];return"function"==typeof o?o.bind(e._xhr):o},set:(e,t,o)=>t in e?(e[t]=o,!0):(e._xhr[t]=o,!0)})}open(e,t,o=!0,r=null,n=null){return this._method=e.toUpperCase(),this._url=new URL(t,window.location.href).toString(),this._xhr._mockOriginalUrl=this._url,this._xhr._mockMethod=this._method,this._xhr.open(e,t,o,r,n)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(r){this._body=r;try{const n=new URL(this._url),{pathname:s,search:i}=n,a=O({url:this._url,method:this._method});if(t!==l&&a){if("delay"===a.action)return setTimeout((()=>this._xhr.send(r)),1e3*a.config.value);if("delay_and_redirect"===a.action)return setTimeout((()=>{this._xhr.open(this._method,a.config.redirectUrl,!0),this._xhr.send(r)}),1e3*a.config.value);if("delay_and_timeout"===a.action)return 0===a.config.value?(this._xhr.open(this._method,this._url,!0),this._xhr.send(r),this._xhr.abort(),void("function"==typeof this.onerror&&this.onerror(new Error("XHR aborted by rules")))):setTimeout((()=>{this._xhr.abort(),"function"==typeof this.onerror&&this.onerror(new Error("XHR timed out by rules"))}),1e3*a.config.value)}const d=c(s,this._method);if(!d&&!a)return this._xhr.send(r);let m=this._url;a||(m=`${x()}${d.url}${i}`);let p={};if(!a){p={[h]:e,[u]:f,"x-mfm-adaptor":t};const o=k();o&&d._ack&&(p["x-mfm-key"]=`${o}-${d._ack}`),d?._ri_&&(p._ri_=d._ri_)}const y={...this._headers,...p};if(t===l)(({actualUrl:e,url:t,method:o,headers:r,body:n,onSuccess:s,onError:i,rule:a})=>{const c=`${Date.now()}-${Math.random()}`,d=R(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const o=t.data;if("INTERCEPTED_RESPONSE"===o.type&&o.requestId===c){if(window.removeEventListener("message",e),o.response?.error)return i?.(o.response.message);const{body:t,status:r,headers:n}=o.response;s?.({body:t,status:r,headers:n})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:c,payload:{actualUrl:e,url:d,method:o,headers:r,body:n,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:this._url,url:m,method:this._method,headers:y,body:this._body,rule:a,onSuccess:({body:e,status:t})=>{Object.defineProperty(this,"responseText",{value:e}),Object.defineProperty(this,"status",{value:t}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("load"))},onError:e=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(new Error(e.message||"XHR mock error")),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("error"))}});else{const e=new o;e.open(this._method,m,!0);for(const t in y)e.setRequestHeader(t,y[t]);e.withCredentials=this.withCredentials,e.onload=()=>{Object.defineProperty(this,"responseText",{value:e.responseText}),Object.defineProperty(this,"status",{value:e.status}),Object.defineProperty(this,"readyState",{value:4}),this.onreadystatechange?.(),this.onload?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("load"))},e.onerror=()=>{Object.defineProperty(this,"readyState",{value:4}),this.onerror?.(),this._xhr.dispatchEvent(new Event("readystatechange")),this._xhr.dispatchEvent(new Event("error"))},e.send(this._body)}}catch(e){console.error("[mockforme][XHR] interception error",e)}}}}(e,t)}const j=function(e,t,r){const n=o();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var o=e.split(";");try{return"application/json"===o[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();t.call(this,e,s)}else r.call(this,s.responseText,s)}function a(e,t){var o=[];for(var r in e)if(e.hasOwnProperty(r)){var n=t?t+"["+r+"]":r,s=e[r];o.push("object"==typeof s?a(s,n):encodeURIComponent(n)+"="+encodeURIComponent(s))}return o.join("&")}return n||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!n){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var t=a(e.params);if("get"==e.method.toLowerCase()&&"object"==typeof e.params){if(-1==e.url.indexOf("?"))e.url+="?";else{var o=e.url.split("?");o[1]&&o[1].split("=")[1]&&(e.url+="&")}e.url+=t}e.hasOwnProperty("async")||(e.async=!0),s.open(e.method,e.url,e.async),e.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(e.headers),s.send(t)}}}};function S({di:e,iv:t},o){var r;const n=function(e,t){const o=t.length;return e.split("").map(((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%o)))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),o+t);return JSON.parse(n)}const P=(e,t=null,r=d)=>{if(o())return;if(r===d)try{!function(){if(!window.mockforme)return;const e=JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"),t=document.createElement("div");t.id="mockforme-dot",Object.assign(t.style,{position:"fixed",bottom:(e.bottom??20)+"px",right:(e.right??20)+"px",width:"42px",height:"42px",borderRadius:"50%",overflow:"hidden",cursor:"grab",zIndex:999999,boxShadow:"0 0 10px rgba(0,0,0,0.25)",backgroundColor:"#fff",display:"flex",alignItems:"center",justifyContent:"center"});const o=document.createElement("img");o.src="https://dashboard.mockforme.com/public/assets/images/icon.png",o.style.objectFit="cover",t.appendChild(o),document.body.appendChild(t);const r=document.createElement("div");r.id="mockforme-widget",r.innerText="MockForMe Enabled",Object.assign(r.style,{position:"fixed",padding:"8px 12px",background:"#2563eb",color:"#fff",fontSize:"13px",fontFamily:"Inter, sans-serif",borderRadius:"8px",bottom:(e.bottom??20)+50+"px",right:(e.right??20)+"px",boxShadow:"0 4px 10px rgba(0,0,0,0.2)",zIndex:999999,display:"none",whiteSpace:"nowrap"}),document.body.appendChild(r),t.addEventListener("click",(e=>{e.stopPropagation(),r.style.display="none"===r.style.display?"block":"none"})),document.addEventListener("click",(()=>{r.style.display="none"}));let n=!1,s=0,i=0;t.addEventListener("mousedown",(e=>{n=!0,t.style.cursor="grabbing";const o=t.getBoundingClientRect();s=e.clientX-o.left,i=e.clientY-o.top,e.preventDefault()})),document.addEventListener("mousemove",(e=>{if(!n)return;const o=e.clientX-s,a=e.clientY-i,c=window.innerHeight-(a+t.offsetHeight),d=window.innerWidth-(o+t.offsetWidth);t.style.bottom=c+"px",t.style.right=d+"px",r.style.bottom=c+50+"px",r.style.right=d+"px"})),document.addEventListener("mouseup",(()=>{if(!n)return;n=!1,t.style.cursor="grab";const e=parseInt(t.style.bottom),o=parseInt(t.style.right);localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:e,right:o}))}))}()}catch(e){console.log("Error in showing mockforme widget")}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:n=[],_o:s,mk:l,_mck:m,_rules:p=[]}=t;return i(n),v({_o:s,mk:l,_mck:m,_rules:p}),{run:(t,o=()=>{})=>{T(e,r),s&&l?t(a(),{_o:s,mk:l,_mck:m,_rules:p}):function(e,o,r,n){j({method:"get",url:y,async:!1,headers:{[h]:e,[u]:f,"x-mfm-adaptor":o}},(e=>{if(e)try{const{di:n,iv:s,_o:a,_mck:c,mk:d,r:l}=e,u=S({di:n,iv:s},a);v({_o:a,mk:d,_mck:c,_rules:l}),u&&(i(u),o=u,r={_o:a,mk:d,_mck:c,_rules:l},t?.(o,r))}catch(e){return void n(new Error("Unable to fetch mocked apis"))}var o,r}),(e=>{console.log("Error in loading mocked apis"),n(e)})).request()}(e,r,0,o)},checkIfApiToBeMocked:c,getMappings:a,doFetchMappings:(t,o)=>{!function(e,t,o,r){fetch(y,{method:"GET",headers:{[h]:e,[u]:f,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:r,_o:n,_mck:s,mk:a,r:c}=e,d=S({di:t,iv:r},n);v({_o:n,mk:a,_mck:s,_rules:c}),d&&(i(d),o(d,{_o:n,mk:a,_mck:s,_rules:c}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),r(e)}))}(e,r,((e,o)=>{t?.(e,o)}),o)}}},C=o();C||(globalThis.mockforme=P);let I=P;C&&(I=e=>({run:()=>{}}));const L=I;return t.mockforme})()));
@@ -1 +1 @@
1
- (()=>{var e={56:e=>{"use strict";e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:e=>{"use strict";e.exports=require("os")},896:e=>{"use strict";e.exports=require("fs")},928:e=>{"use strict";e.exports=require("path")},982:e=>{"use strict";e.exports=require("crypto")},998:(e,t,r)=>{const n=r(896),o=r(928),s=r(857),i=r(982),a=r(56).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${a}][DEBUG] ${e}`)}function p(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function u(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const n=r.password;if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const o=r.searchParams.get("environment");if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const s=`DOTENV_VAULT_${o.toUpperCase()}`,i=e.parsed[s];if(!i){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:i,key:n}}function h(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)n.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=o.resolve(process.cwd(),".env.vault");return n.existsSync(t)?t:null}function d(e){return"~"===e[0]?o.join(s.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=o.resolve(process.cwd(),".env");let r="utf8";const s=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:s&&l("No encoding is specified. UTF-8 is used by default");let i,a=[t];if(e&&e.path)if(Array.isArray(e.path)){a=[];for(const t of e.path)a.push(d(t))}else a=[d(e.path)];const c={};for(const t of a)try{const o=f.parse(n.readFileSync(t,{encoding:r}));f.populate(c,o,e)}catch(e){s&&l(`Failed to load ${t} ${e.message}`),i=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),i?{parsed:c,error:i}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=h(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const n=p(e).split(","),o=n.length;let s;for(let e=0;e<o;e++)try{const t=u(r,n[e].trim());s=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=o)throw t}return f.parse(s)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=h(e);return t?f._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${a}][WARN] ${r}`),f.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let n=Buffer.from(e,"base64");const o=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{const e=i.createDecipheriv("aes-256-gcm",r,o);return e.setAuthTag(s),`${e.update(n)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,n="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,n=e.toString();for(n=n.replace(/\r\n?/gm,"\n");null!=(r=c.exec(n));){const e=r[1];let n=r[2]||"";n=n.trim();const o=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===o&&(n=n.replace(/\\n/g,"\n"),n=n.replace(/\\r/g,"\r")),t[e]=n}return t},populate:function(e,t,r={}){const n=Boolean(r&&r.debug),o=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===o&&(e[r]=t[r]),n&&l(!0===o?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{"use strict";r.r(n),r.d(n,{mockforme:()=>y});const e=require("http");var t=r.n(e);const o=require("https");var s=r.n(o);const i=require("child_process");var a=r(998);const c=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},l=(e,t)=>{const r=e.split("/"),n=t.split("/");if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==n[e]&&":any"!==t)return!1}return!0},p=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};r.n(a)().config("../../.env");const u="https://api.mockforme.com",h=`${u}/mockforme`,d="mfmver",f="4.2.8";let g=`${u}/gateway/3f4eae522b`;class m{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=t().request,this.originalHttpGet=t().get,this.originalHttpsRequest=s().request,this.originalHttpsGet=s().get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}fetchApiMappings(){try{const e=`curl -s -H "mockforme: ${this.token}" "${g}"`,t=(0,i.execSync)(e,{encoding:"utf8"});if(t){const{di:e,iv:r,_o:n,_mck:o,mk:s,r:i}=JSON.parse(t);this.organisationId=n,this.memberKey=s,this.memberCacheKey=o;const a=function({di:e,iv:t},r){var n;const o=function(e,t){const r=t.length;return e.split("").map(((e,n)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(n%r)))).join("")}((n=e,"undefined"!=typeof Buffer?Buffer.from(n,"base64").toString("utf8"):decodeURIComponent(escape(atob(n)))),r+t);return JSON.parse(o)}({di:e,iv:r},n);a&&(this.apiMappings=a),i&&(this.rules=i)}this.isReady=!0}catch(e){console.error("Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${h}/${this.organisationId}/${this.memberKey}`}checkRules(e){return this.rules&&this.rules.length&&this.rules.find((t=>{const r=t.rule.URL.condition,{operator:n,value:o}=r;return"equals"===n?e.pathname===o:"contains"===n&&e.pathname.includes(o)}))||null}async applyRuleBehavior(e,t,r){if(!e)return null;const{activeAction:n,actions:o}=e.rule.URL.condition;if("delay"===n&&o.delay.value>=0)return await new Promise((e=>setTimeout(e,1e3*o.delay.value))),{type:"passThrough"};if("delay_and_redirect"===n){const{value:e,redirectUrl:t}=o.delay_and_redirect;return e>0&&await new Promise((t=>setTimeout(t,1e3*e))),{type:"redirect",redirectUrl:t}}return"delay_and_timeout"===n&&o.delay_and_timeout.value>=0&&await new Promise(((e,t)=>setTimeout((()=>t(new Error("Request timed out by rule"))),1e3*o.delay_and_timeout.value))),null}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),n=this.apiMappings.find((t=>{const n=c(t.apiMethod)===c(r),o=t.apiEndpoint===e.pathname||l(t.apiEndpoint,e.pathname);return n&&o}));if(n){console.log("[mockforme] [api intercepted]: ",n);const r={mockforme:this.token,[d]:f},o=n?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(s+=e.search),{url:s,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const n=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),o=e.checkRules(n);if(o){console.log("[mockforme] [fetch] [rule matched]: ",p(o));try{const t=await e.applyRuleBehavior(o,n,r);if("redirect"===t?.type)return e.originalFetch(t.redirectUrl,r);if("passThrough"===t?.type)return e.originalFetch(n.href,r)}catch(e){throw e}}const{url:s,init:i}=e.interceptFetch(n,r);try{const t=await e.originalFetch(s,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const r=(t,r)=>async function(...n){let o=n[0];if("string"==typeof o&&(o=new URL(o)),!e.isReady)return t.apply(null,[o,...n.slice(1)]);const s=e.checkRules(o);if(s){console.log(`[mockforme] [${r}] [rule matched]: `,p(s));try{const r=await e.applyRuleBehavior(s,o,{});if("passThrough"===r?.type)return t.apply(null,[o,...n.slice(1)])}catch(e){throw e}}const i=e.interceptRequest(o);try{return t.apply(null,[i,...n.slice(1)])}catch(e){throw e}};t().request=r(this.originalHttpRequest,"http.request"),s().request=r(this.originalHttpsRequest,"https.request"),t().get=r(this.originalHttpGet,"http.get"),s().get=r(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find((t=>{if(c(t.apiMethod)===c(e.method))return t.apiEndpoint===e.path||l(t.apiEndpoint,e.path)}));if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[d]:f},n=t?._ack||null;this.memberCacheKey&&n&&(r["x-mfm-key"]=`${this.memberCacheKey}-${n}`);let o=`${this.getProxyUrl()}${e.path}`;e.search&&(o+=e.search);const s=new URL(o);return{...e,hostname:s.hostname,path:s.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function y(e){return new m(e)}})(),module.exports=n})();
1
+ (()=>{var e={56:e=>{"use strict";e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:e=>{"use strict";e.exports=require("os")},896:e=>{"use strict";e.exports=require("fs")},928:e=>{"use strict";e.exports=require("path")},982:e=>{"use strict";e.exports=require("crypto")},998:(e,t,r)=>{const n=r(896),o=r(928),s=r(857),i=r(982),a=r(56).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${a}][DEBUG] ${e}`)}function p(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function u(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const n=r.password;if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const o=r.searchParams.get("environment");if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const s=`DOTENV_VAULT_${o.toUpperCase()}`,i=e.parsed[s];if(!i){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:i,key:n}}function h(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)n.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=o.resolve(process.cwd(),".env.vault");return n.existsSync(t)?t:null}function d(e){return"~"===e[0]?o.join(s.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=o.resolve(process.cwd(),".env");let r="utf8";const s=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:s&&l("No encoding is specified. UTF-8 is used by default");let i,a=[t];if(e&&e.path)if(Array.isArray(e.path)){a=[];for(const t of e.path)a.push(d(t))}else a=[d(e.path)];const c={};for(const t of a)try{const o=f.parse(n.readFileSync(t,{encoding:r}));f.populate(c,o,e)}catch(e){s&&l(`Failed to load ${t} ${e.message}`),i=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),i?{parsed:c,error:i}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=h(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const n=p(e).split(","),o=n.length;let s;for(let e=0;e<o;e++)try{const t=u(r,n[e].trim());s=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=o)throw t}return f.parse(s)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=h(e);return t?f._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${a}][WARN] ${r}`),f.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let n=Buffer.from(e,"base64");const o=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{const e=i.createDecipheriv("aes-256-gcm",r,o);return e.setAuthTag(s),`${e.update(n)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,n="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,n=e.toString();for(n=n.replace(/\r\n?/gm,"\n");null!=(r=c.exec(n));){const e=r[1];let n=r[2]||"";n=n.trim();const o=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===o&&(n=n.replace(/\\n/g,"\n"),n=n.replace(/\\r/g,"\r")),t[e]=n}return t},populate:function(e,t,r={}){const n=Boolean(r&&r.debug),o=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===o&&(e[r]=t[r]),n&&l(!0===o?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{"use strict";r.r(n),r.d(n,{mockforme:()=>v});const e=require("http");var t=r.n(e);const o=require("https");var s=r.n(o);const i=require("child_process");var a=r(998);const c=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},l=(e,t)=>{const r=e.split("/"),n=t.split("/");if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==n[e]&&":any"!==t)return!1}return!0},p=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};r.n(a)().config("../../.env");const u="https://api.mockforme.com",h=`${u}/mockforme`,d="mfmver",f="4.2.8";let m=`${u}/gateway/3f4eae522b`,g=null;class y{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=t().request,this.originalHttpGet=t().get,this.originalHttpsRequest=s().request,this.originalHttpsGet=s().get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}checkIsErrorInFetchMappings(e){try{const t=JSON.parse(e);if(0==t?.status)throw new Error(t?.message||"Failed to fetch mockforme mappings")}catch(e){throw new Error(e.message||"Failed to fetch mockforme mappings")}}fetchApiMappings(){this.apiMappings=[],this.rules=[],this.isReady=!1;try{const e=`curl -s -H "mockforme: ${this.token}" "${m}"`,t=(0,i.execSync)(e,{encoding:"utf8"});if(t&&this.checkIsErrorInFetchMappings(t),!t)throw new Error("Failed to fetch mockforme mappings: No response");{const{di:e,iv:r,_o:n,_mck:o,mk:s,r:i}=JSON.parse(t);this.organisationId=n,this.memberKey=s,this.memberCacheKey=o;const a=function({di:e,iv:t},r){var n;const o=function(e,t){const r=t.length;return e.split("").map(((e,n)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(n%r)))).join("")}((n=e,"undefined"!=typeof Buffer?Buffer.from(n,"base64").toString("utf8"):decodeURIComponent(escape(atob(n)))),r+t);return JSON.parse(o)}({di:e,iv:r},n);a&&(this.apiMappings=a),i&&(this.rules=i)}this.isReady=!0}catch(e){console.error("[mockforme] Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${h}/${this.organisationId}/${this.memberKey}`}checkRules(e){return this.rules&&this.rules.length&&this.rules.find((t=>{const r=t.rule.URL.condition,{operator:n,value:o}=r;return"equals"===n?e.pathname===o:"contains"===n&&e.pathname.includes(o)}))||null}async applyRuleBehavior(e,t,r){if(!e)return null;const{activeAction:n,actions:o}=e.rule.URL.condition;if("delay"===n&&o.delay.value>=0)return await new Promise((e=>setTimeout(e,1e3*o.delay.value))),{type:"passThrough"};if("delay_and_redirect"===n){const{value:e,redirectUrl:t}=o.delay_and_redirect;return e>0&&await new Promise((t=>setTimeout(t,1e3*e))),{type:"redirect",redirectUrl:t}}return"delay_and_timeout"===n&&o.delay_and_timeout.value>=0&&await new Promise(((e,t)=>setTimeout((()=>t(new Error("Request timed out by rule"))),1e3*o.delay_and_timeout.value))),null}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),n=this.apiMappings.find((t=>{const n=c(t.apiMethod)===c(r),o=t.apiEndpoint===e.pathname||l(t.apiEndpoint,e.pathname);return n&&o}));if(n){console.log("[mockforme] [api intercepted]: ",n);const r={mockforme:this.token,[d]:f},o=n?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(s+=e.search),{url:s,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const n=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),o=e.checkRules(n);if(o){console.log("[mockforme] [fetch] [rule matched]: ",p(o));try{const t=await e.applyRuleBehavior(o,n,r);if("redirect"===t?.type)return e.originalFetch(t.redirectUrl,r);if("passThrough"===t?.type)return e.originalFetch(n.href,r)}catch(e){throw e}}const{url:s,init:i}=e.interceptFetch(n,r);try{const t=await e.originalFetch(s,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const r=(t,r)=>async function(...n){let o=n[0];if("string"==typeof o&&(o=new URL(o)),!e.isReady)return t.apply(null,[o,...n.slice(1)]);const s=e.checkRules(o);if(s){console.log(`[mockforme] [${r}] [rule matched]: `,p(s));try{const r=await e.applyRuleBehavior(s,o,{});if("passThrough"===r?.type)return t.apply(null,[o,...n.slice(1)])}catch(e){throw e}}const i=e.interceptRequest(o);try{return t.apply(null,[i,...n.slice(1)])}catch(e){throw e}};t().request=r(this.originalHttpRequest,"http.request"),s().request=r(this.originalHttpsRequest,"https.request"),t().get=r(this.originalHttpGet,"http.get"),s().get=r(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find((t=>{if(c(t.apiMethod)===c(e.method))return t.apiEndpoint===e.path||l(t.apiEndpoint,e.path)}));if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[d]:f},n=t?._ack||null;this.memberCacheKey&&n&&(r["x-mfm-key"]=`${this.memberCacheKey}-${n}`);let o=`${this.getProxyUrl()}${e.path}`;e.search&&(o+=e.search);const s=new URL(o);return{...e,hostname:s.hostname,path:s.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function v(e){return g?(g.token=e,g.fetchApiMappings()):g=new y(e),g}})(),module.exports=n})();
@@ -1 +1 @@
1
- import{createRequire as e}from"node:module";var t={56:e=>{e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:t=>{t.exports=e(import.meta.url)("os")},896:t=>{t.exports=e(import.meta.url)("fs")},928:t=>{t.exports=e(import.meta.url)("path")},982:t=>{t.exports=e(import.meta.url)("crypto")},998:(e,t,r)=>{const n=r(896),o=r(928),s=r(857),i=r(982),a=r(56).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${a}][DEBUG] ${e}`)}function p(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function u(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const n=r.password;if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const o=r.searchParams.get("environment");if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const s=`DOTENV_VAULT_${o.toUpperCase()}`,i=e.parsed[s];if(!i){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:i,key:n}}function h(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)n.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=o.resolve(process.cwd(),".env.vault");return n.existsSync(t)?t:null}function d(e){return"~"===e[0]?o.join(s.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=o.resolve(process.cwd(),".env");let r="utf8";const s=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:s&&l("No encoding is specified. UTF-8 is used by default");let i,a=[t];if(e&&e.path)if(Array.isArray(e.path)){a=[];for(const t of e.path)a.push(d(t))}else a=[d(e.path)];const c={};for(const t of a)try{const o=f.parse(n.readFileSync(t,{encoding:r}));f.populate(c,o,e)}catch(e){s&&l(`Failed to load ${t} ${e.message}`),i=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),i?{parsed:c,error:i}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=h(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const n=p(e).split(","),o=n.length;let s;for(let e=0;e<o;e++)try{const t=u(r,n[e].trim());s=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=o)throw t}return f.parse(s)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=h(e);return t?f._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${a}][WARN] ${r}`),f.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let n=Buffer.from(e,"base64");const o=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{const e=i.createDecipheriv("aes-256-gcm",r,o);return e.setAuthTag(s),`${e.update(n)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,n="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,n=e.toString();for(n=n.replace(/\r\n?/gm,"\n");null!=(r=c.exec(n));){const e=r[1];let n=r[2]||"";n=n.trim();const o=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===o&&(n=n.replace(/\\n/g,"\n"),n=n.replace(/\\r/g,"\r")),t[e]=n}return t},populate:function(e,t,r={}){const n=Boolean(r&&r.debug),o=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===o&&(e[r]=t[r]),n&&l(!0===o?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var s=r[e]={exports:{}};return t[e](s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const o=e(import.meta.url)("http");var s=n.n(o);const i=e(import.meta.url)("https");var a=n.n(i);const c=e(import.meta.url)("child_process");var l=n(998);const p=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},u=(e,t)=>{const r=e.split("/"),n=t.split("/");if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==n[e]&&":any"!==t)return!1}return!0},h=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};n.n(l)().config("../../.env");const d="https://api.mockforme.com",f=`${d}/mockforme`,m="mfmver",g="4.2.8";let v=`${d}/gateway/3f4eae522b`;class y{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=s().request,this.originalHttpGet=s().get,this.originalHttpsRequest=a().request,this.originalHttpsGet=a().get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}fetchApiMappings(){try{const e=`curl -s -H "mockforme: ${this.token}" "${v}"`,t=(0,c.execSync)(e,{encoding:"utf8"});if(t){const{di:e,iv:r,_o:n,_mck:o,mk:s,r:i}=JSON.parse(t);this.organisationId=n,this.memberKey=s,this.memberCacheKey=o;const a=function({di:e,iv:t},r){var n;const o=function(e,t){const r=t.length;return e.split("").map(((e,n)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(n%r)))).join("")}((n=e,"undefined"!=typeof Buffer?Buffer.from(n,"base64").toString("utf8"):decodeURIComponent(escape(atob(n)))),r+t);return JSON.parse(o)}({di:e,iv:r},n);a&&(this.apiMappings=a),i&&(this.rules=i)}this.isReady=!0}catch(e){console.error("Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${f}/${this.organisationId}/${this.memberKey}`}checkRules(e){return this.rules&&this.rules.length&&this.rules.find((t=>{const r=t.rule.URL.condition,{operator:n,value:o}=r;return"equals"===n?e.pathname===o:"contains"===n&&e.pathname.includes(o)}))||null}async applyRuleBehavior(e,t,r){if(!e)return null;const{activeAction:n,actions:o}=e.rule.URL.condition;if("delay"===n&&o.delay.value>=0)return await new Promise((e=>setTimeout(e,1e3*o.delay.value))),{type:"passThrough"};if("delay_and_redirect"===n){const{value:e,redirectUrl:t}=o.delay_and_redirect;return e>0&&await new Promise((t=>setTimeout(t,1e3*e))),{type:"redirect",redirectUrl:t}}return"delay_and_timeout"===n&&o.delay_and_timeout.value>=0&&await new Promise(((e,t)=>setTimeout((()=>t(new Error("Request timed out by rule"))),1e3*o.delay_and_timeout.value))),null}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),n=this.apiMappings.find((t=>{const n=p(t.apiMethod)===p(r),o=t.apiEndpoint===e.pathname||u(t.apiEndpoint,e.pathname);return n&&o}));if(n){console.log("[mockforme] [api intercepted]: ",n);const r={mockforme:this.token,[m]:g},o=n?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(s+=e.search),{url:s,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const n=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),o=e.checkRules(n);if(o){console.log("[mockforme] [fetch] [rule matched]: ",h(o));try{const t=await e.applyRuleBehavior(o,n,r);if("redirect"===t?.type)return e.originalFetch(t.redirectUrl,r);if("passThrough"===t?.type)return e.originalFetch(n.href,r)}catch(e){throw e}}const{url:s,init:i}=e.interceptFetch(n,r);try{const t=await e.originalFetch(s,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const t=(t,r)=>async function(...n){let o=n[0];if("string"==typeof o&&(o=new URL(o)),!e.isReady)return t.apply(null,[o,...n.slice(1)]);const s=e.checkRules(o);if(s){console.log(`[mockforme] [${r}] [rule matched]: `,h(s));try{const r=await e.applyRuleBehavior(s,o,{});if("passThrough"===r?.type)return t.apply(null,[o,...n.slice(1)])}catch(e){throw e}}const i=e.interceptRequest(o);try{return t.apply(null,[i,...n.slice(1)])}catch(e){throw e}};s().request=t(this.originalHttpRequest,"http.request"),a().request=t(this.originalHttpsRequest,"https.request"),s().get=t(this.originalHttpGet,"http.get"),a().get=t(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find((t=>{if(p(t.apiMethod)===p(e.method))return t.apiEndpoint===e.path||u(t.apiEndpoint,e.path)}));if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[m]:g},n=t?._ack||null;this.memberCacheKey&&n&&(r["x-mfm-key"]=`${this.memberCacheKey}-${n}`);let o=`${this.getProxyUrl()}${e.path}`;e.search&&(o+=e.search);const s=new URL(o);return{...e,hostname:s.hostname,path:s.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function E(e){return new y(e)}export{E as mockforme};
1
+ import{createRequire as e}from"node:module";var t={56:e=>{e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:t=>{t.exports=e(import.meta.url)("os")},896:t=>{t.exports=e(import.meta.url)("fs")},928:t=>{t.exports=e(import.meta.url)("path")},982:t=>{t.exports=e(import.meta.url)("crypto")},998:(e,t,r)=>{const o=r(896),n=r(928),s=r(857),i=r(982),a=r(56).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){console.log(`[dotenv@${a}][DEBUG] ${e}`)}function l(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function u(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const o=r.password;if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const n=r.searchParams.get("environment");if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const s=`DOTENV_VAULT_${n.toUpperCase()}`,i=e.parsed[s];if(!i){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:i,key:o}}function h(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)o.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=n.resolve(process.cwd(),".env.vault");return o.existsSync(t)?t:null}function d(e){return"~"===e[0]?n.join(s.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=n.resolve(process.cwd(),".env");let r="utf8";const s=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:s&&p("No encoding is specified. UTF-8 is used by default");let i,a=[t];if(e&&e.path)if(Array.isArray(e.path)){a=[];for(const t of e.path)a.push(d(t))}else a=[d(e.path)];const c={};for(const t of a)try{const n=f.parse(o.readFileSync(t,{encoding:r}));f.populate(c,n,e)}catch(e){s&&p(`Failed to load ${t} ${e.message}`),i=e}let l=process.env;return e&&null!=e.processEnv&&(l=e.processEnv),f.populate(l,c,e),i?{parsed:c,error:i}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&p("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=h(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=l(e).split(","),n=o.length;let s;for(let e=0;e<n;e++)try{const t=u(r,o[e].trim());s=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=n)throw t}return f.parse(s)},config:function(e){if(0===l(e).length)return f.configDotenv(e);const t=h(e);return t?f._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${a}][WARN] ${r}`),f.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let o=Buffer.from(e,"base64");const n=o.subarray(0,12),s=o.subarray(-16);o=o.subarray(12,-16);try{const e=i.createDecipheriv("aes-256-gcm",r,n);return e.setAuthTag(s),`${e.update(o)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,o="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(o){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,o=e.toString();for(o=o.replace(/\r\n?/gm,"\n");null!=(r=c.exec(o));){const e=r[1];let o=r[2]||"";o=o.trim();const n=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===n&&(o=o.replace(/\\n/g,"\n"),o=o.replace(/\\r/g,"\r")),t[e]=o}return t},populate:function(e,t,r={}){const o=Boolean(r&&r.debug),n=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===n&&(e[r]=t[r]),o&&p(!0===n?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},r={};function o(e){var n=r[e];if(void 0!==n)return n.exports;var s=r[e]={exports:{}};return t[e](s,s.exports,o),s.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const n=e(import.meta.url)("http");var s=o.n(n);const i=e(import.meta.url)("https");var a=o.n(i);const c=e(import.meta.url)("child_process");var p=o(998);const l=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},u=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t)return!1}return!0},h=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};o.n(p)().config("../../.env");const d="https://api.mockforme.com",f=`${d}/mockforme`,m="mfmver",g="4.2.8";let v=`${d}/gateway/3f4eae522b`,y=null;class E{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=s().request,this.originalHttpGet=s().get,this.originalHttpsRequest=a().request,this.originalHttpsGet=a().get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}checkIsErrorInFetchMappings(e){try{const t=JSON.parse(e);if(0==t?.status)throw new Error(t?.message||"Failed to fetch mockforme mappings")}catch(e){throw new Error(e.message||"Failed to fetch mockforme mappings")}}fetchApiMappings(){this.apiMappings=[],this.rules=[],this.isReady=!1;try{const e=`curl -s -H "mockforme: ${this.token}" "${v}"`,t=(0,c.execSync)(e,{encoding:"utf8"});if(t&&this.checkIsErrorInFetchMappings(t),!t)throw new Error("Failed to fetch mockforme mappings: No response");{const{di:e,iv:r,_o:o,_mck:n,mk:s,r:i}=JSON.parse(t);this.organisationId=o,this.memberKey=s,this.memberCacheKey=n;const a=function({di:e,iv:t},r){var o;const n=function(e,t){const r=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(n)}({di:e,iv:r},o);a&&(this.apiMappings=a),i&&(this.rules=i)}this.isReady=!0}catch(e){console.error("[mockforme] Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${f}/${this.organisationId}/${this.memberKey}`}checkRules(e){return this.rules&&this.rules.length&&this.rules.find((t=>{const r=t.rule.URL.condition,{operator:o,value:n}=r;return"equals"===o?e.pathname===n:"contains"===o&&e.pathname.includes(n)}))||null}async applyRuleBehavior(e,t,r){if(!e)return null;const{activeAction:o,actions:n}=e.rule.URL.condition;if("delay"===o&&n.delay.value>=0)return await new Promise((e=>setTimeout(e,1e3*n.delay.value))),{type:"passThrough"};if("delay_and_redirect"===o){const{value:e,redirectUrl:t}=n.delay_and_redirect;return e>0&&await new Promise((t=>setTimeout(t,1e3*e))),{type:"redirect",redirectUrl:t}}return"delay_and_timeout"===o&&n.delay_and_timeout.value>=0&&await new Promise(((e,t)=>setTimeout((()=>t(new Error("Request timed out by rule"))),1e3*n.delay_and_timeout.value))),null}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find((t=>{const o=l(t.apiMethod)===l(r),n=t.apiEndpoint===e.pathname||u(t.apiEndpoint,e.pathname);return o&&n}));if(o){console.log("[mockforme] [api intercepted]: ",o);const r={mockforme:this.token,[m]:g},n=o?._ack||null;this.memberCacheKey&&n&&(r["x-mfm-key"]=`${this.memberCacheKey}-${n}`);let s=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(s+=e.search),{url:s,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const o=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),n=e.checkRules(o);if(n){console.log("[mockforme] [fetch] [rule matched]: ",h(n));try{const t=await e.applyRuleBehavior(n,o,r);if("redirect"===t?.type)return e.originalFetch(t.redirectUrl,r);if("passThrough"===t?.type)return e.originalFetch(o.href,r)}catch(e){throw e}}const{url:s,init:i}=e.interceptFetch(o,r);try{const t=await e.originalFetch(s,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const t=(t,r)=>async function(...o){let n=o[0];if("string"==typeof n&&(n=new URL(n)),!e.isReady)return t.apply(null,[n,...o.slice(1)]);const s=e.checkRules(n);if(s){console.log(`[mockforme] [${r}] [rule matched]: `,h(s));try{const r=await e.applyRuleBehavior(s,n,{});if("passThrough"===r?.type)return t.apply(null,[n,...o.slice(1)])}catch(e){throw e}}const i=e.interceptRequest(n);try{return t.apply(null,[i,...o.slice(1)])}catch(e){throw e}};s().request=t(this.originalHttpRequest,"http.request"),a().request=t(this.originalHttpsRequest,"https.request"),s().get=t(this.originalHttpGet,"http.get"),a().get=t(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find((t=>{if(l(t.apiMethod)===l(e.method))return t.apiEndpoint===e.path||u(t.apiEndpoint,e.path)}));if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[m]:g},o=t?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let n=`${this.getProxyUrl()}${e.path}`;e.search&&(n+=e.search);const s=new URL(n);return{...e,hostname:s.hostname,path:s.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function _(e){return y?(y.token=e,y.fetchApiMappings()):y=new E(e),y}export{_ as mockforme};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mockforme",
3
- "version": "4.3.0",
3
+ "version": "4.4.0",
4
4
  "description": "MockForMe is a fast and simple mock API solution for CSR and SSR apps. Create mock APIs in 2 minutes with support for delays, conditional responses, public URLs, random data, variables, Faker, and postFunctions — all designed to boost developer productivity.",
5
5
  "main": "dist/mockforme.client.cjs.js",
6
6
  "module": "dist/mockforme.client.esm.js",