mockforme 14.0.0 → 14.2.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.
@@ -17,4 +17,4 @@
17
17
  0% { transform: translateX(-100%) scaleX(0.4); }
18
18
  50% { transform: translateX(20%) scaleX(0.6); }
19
19
  100% { transform: translateX(100%) scaleX(0.4); }
20
- `;function lA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function cA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function dA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function uA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=fn();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function fA(){const{analyticsEnabled:e}=nr(),{token:t,organisationId:n}=mn();return u.useEffect(()=>{on.setEnabled(e)},[e]),u.useEffect(()=>{on.setToken(t)},[t]),u.useEffect(()=>{on.setOrganisationId(n)},[n]),null}function hA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(pA,{}),xt(Mt,{children:xt(un,{clientType:e,version:t,children:xt(gn,{children:xt(wn,{children:xt(Tn,{children:xt(jn,{children:xt(tr,{children:xt(Wn,{children:Ct(sr,{children:[xt(fA,{}),xt(Qo,{}),xt(gA,{})]})})})})})})})})})]})}function pA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function gA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=fn(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=mn(),{debugRules:f,editRules:h}=$n(),{globalDelay:p}=nr();if(!A&&(l||a))return Ct(Bt,{children:[xt(Mo,{children:xt(vA,{children:xt(yA,{})})}),xt(Ja,{})]});if(!a)return Ct(Bt,{children:[xt(Mo,{children:Ct(vA,{children:[xt(ga,{}),xt(uA,{})]})}),xt(Ja,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(Mo,{children:[xt(Ro,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(zo,{}),Ct(vA,{children:[xt(ua,{}),xt(ma,{}),xt(ba,{}),xt(xa,{}),xt(Ta,{}),xt(ja,{}),xt(uA,{}),xt(wA,{})]})]}),xt(Ja,{})]})}var mA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function yA(){const e=Ut();return Ct("div",{css:mA,children:[xt(wi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function wA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=mn(),n=Ut();return null==e?null:xt(oi,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var kA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},bA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function vA({children:e}){const{fullscreenSlotRef:t}=fn();return Ct("div",{css:bA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:kA})]})}class BA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Rr(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const xA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-DDAwMiHY.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function CA(e,t){return!(!xA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(xA)}catch{return!1}}()||!(e&&e.startsWith(xA)||t&&-1!==t.indexOf(xA)))}let EA=null;const FA="data-mfm-mount";function SA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function QA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{on.init(),on.setClientType(e);const t=nn().read("MFM_TOKEN");t&&on.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${FA}]`);s||(s=document.createElement("div"),s.setAttribute(FA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(BA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(hA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;CA(e.filename,t?.stack)&&(Rr(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;CA(void 0,t?.stack??(t?String(t):void 0))&&(Rr(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(Or>0)){if(xA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(xA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}EA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Gr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else on.track("widget_destroyed");qr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const UA={run(e,t={}){if(EA)return EA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=SA(e);r&&(EA=QA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),EA&&EA.destroy()}}}const n=SA(e);return n?(EA=QA(n,t),EA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=UA),n.d(t,["M",0,UA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let r={};n.r(r),n.d(r,{mockforme:()=>he});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),o=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const r of n){if(i(r.apiMethod)!==i(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(o)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${o.url}`),o;for(const o of A)if(i(o.apiMethod)===i(t)){const i=n(o.apiEndpoint);if(i===r||s(i,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${o.apiEndpoint}`);const n={url:e,method:o.apiMethod,apiEndpoint:o.apiEndpoint,_ack:o._ack||null};return o._ri_&&(n._ri_=o._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:r}){m=e,y=t,w=n,k=r}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,r){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.0.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);b({_o:o,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.0.0","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,r)))},o);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,r))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())});var W,$,X=n(232);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const Y="MFM_TOKEN",Z="MFM_CACHED_MAPPINGS",ee="MFM_INTERCEPTION_ENABLED",te=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Y):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(ee);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(ee,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case $.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case $.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case $.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&a.set(String(r),Array.isArray(o)?o:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||X.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.0.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem(Y,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(r)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)},e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")?(this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Z,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Z);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage($.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,r=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===r&&e.apiEndpoint===t)),A.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const o=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${o} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach(e=>{const n=e.split(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ne(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class re{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class oe{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class ie{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach(t=>{e.searchParams.delete(t),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class se{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&re.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,r=ie.applyRequestModifications(t,n.modificationActions);return{...await oe.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return ie.applyResponseModifications(e,t)}}class ae{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ae.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=se.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,c)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class Ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,r={}){if(this._captured)return;this._captured=!0;const o=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:Ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=se.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const le=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function ce(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return le.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const de=(e,t=null,n=u)=>{if(o())return;let r="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),te.token=r,te.isAuthenticated=!0),!r&&te.token&&(r=te.token),te.onAuthSuccess=(e,t,n)=>{l(t),b(n),te.updateMappings(t,n)},i?te.setWidgetKey(i):te.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>te.token||e;ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();te.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await se.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&te.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw te.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ae.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=se.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return te.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(te.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();te.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.0.0","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;ne(t.headers)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(te.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(te.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();te.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){te.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){te.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);te.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw te.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return te.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),Ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();te.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await se.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&te.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=se.applyResponseModifications(e,s.rule.modificationActions),r=e}te.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&te.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach(([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}}),n._xhr.addEventListener("abort",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.0.0","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};te.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;ne(i)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),te.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=B(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();te.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;te.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;te.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(r,n),a&&A)te.mappings=s,te.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(r){const t=te.getSavedMappings(r,n);if(t&&Array.isArray(t.mappings))return te.mappings=t.mappings,te.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),te.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);te.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(r||te.token,n,(t,o)=>{te.saveMappings(t,o,r||te.token,n),te.updateMappings(t,o),e?.(t,o)},t)},recheckWidgetVisibility:()=>{te.init()}}},ue=o();ue||(globalThis.mockforme=de);let fe=de;ue&&(fe=e=>({run:()=>{}}));const he=fe;module.exports=r})();
20
+ `;function lA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function cA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function dA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function uA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=fn();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function fA(){const{analyticsEnabled:e}=nr(),{token:t,organisationId:n}=mn();return u.useEffect(()=>{on.setEnabled(e)},[e]),u.useEffect(()=>{on.setToken(t)},[t]),u.useEffect(()=>{on.setOrganisationId(n)},[n]),null}function hA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(pA,{}),xt(Mt,{children:xt(un,{clientType:e,version:t,children:xt(gn,{children:xt(wn,{children:xt(Tn,{children:xt(jn,{children:xt(tr,{children:xt(Wn,{children:Ct(sr,{children:[xt(fA,{}),xt(Qo,{}),xt(gA,{})]})})})})})})})})})]})}function pA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function gA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=fn(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=mn(),{debugRules:f,editRules:h}=$n(),{globalDelay:p}=nr();if(!A&&(l||a))return Ct(Bt,{children:[xt(Mo,{children:xt(vA,{children:xt(yA,{})})}),xt(Ja,{})]});if(!a)return Ct(Bt,{children:[xt(Mo,{children:Ct(vA,{children:[xt(ga,{}),xt(uA,{})]})}),xt(Ja,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(Mo,{children:[xt(Ro,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(zo,{}),Ct(vA,{children:[xt(ua,{}),xt(ma,{}),xt(ba,{}),xt(xa,{}),xt(Ta,{}),xt(ja,{}),xt(uA,{}),xt(wA,{})]})]}),xt(Ja,{})]})}var mA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function yA(){const e=Ut();return Ct("div",{css:mA,children:[xt(wi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function wA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=mn(),n=Ut();return null==e?null:xt(oi,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var kA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},bA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function vA({children:e}){const{fullscreenSlotRef:t}=fn();return Ct("div",{css:bA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:kA})]})}class BA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Rr(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const xA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-DDAwMiHY.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function CA(e,t){return!(!xA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(xA)}catch{return!1}}()||!(e&&e.startsWith(xA)||t&&-1!==t.indexOf(xA)))}let EA=null;const FA="data-mfm-mount";function SA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function QA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{on.init(),on.setClientType(e);const t=nn().read("MFM_TOKEN");t&&on.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${FA}]`);s||(s=document.createElement("div"),s.setAttribute(FA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(BA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(hA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;CA(e.filename,t?.stack)&&(Rr(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;CA(void 0,t?.stack??(t?String(t):void 0))&&(Rr(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(Or>0)){if(xA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(xA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}EA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Gr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else on.track("widget_destroyed");qr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const UA={run(e,t={}){if(EA)return EA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=SA(e);r&&(EA=QA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),EA&&EA.destroy()}}}const n=SA(e);return n?(EA=QA(n,t),EA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=UA),n.d(t,["M",0,UA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let r={};n.r(r),n.d(r,{mockforme:()=>he});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),o=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const r of n){if(i(r.apiMethod)!==i(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(o)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${o.url}`),o;for(const o of A)if(i(o.apiMethod)===i(t)){const i=n(o.apiEndpoint);if(i===r||s(i,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${o.apiEndpoint}`);const n={url:e,method:o.apiMethod,apiEndpoint:o.apiEndpoint,_ack:o._ack||null};return o._ri_&&(n._ri_=o._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:r}){m=e,y=t,w=n,k=r}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,r){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.2.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);b({_o:o,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.2.0","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,r)))},o);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,r))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())});var W,$,X=n(232);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const Y="MFM_TOKEN",Z="MFM_CACHED_MAPPINGS",ee="MFM_INTERCEPTION_ENABLED",te=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Y):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(ee);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(ee,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case $.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case $.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case $.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&a.set(String(r),Array.isArray(o)?o:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||X.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.2.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem(Y,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(r)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)},e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")?(this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Z,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Z);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage($.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,r=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===r&&e.apiEndpoint===t)),A.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const o=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${o} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach(e=>{const n=e.split(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ne(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class re{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class oe{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class ie{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach(t=>{e.searchParams.delete(t),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class se{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&re.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,r=ie.applyRequestModifications(t,n.modificationActions);return{...await oe.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return ie.applyResponseModifications(e,t)}}class ae{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ae.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=se.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,c)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class Ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,r={}){if(this._captured)return;this._captured=!0;const o=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:Ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=se.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const le=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function ce(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return le.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const de=(e,t=null,n=u)=>{if(o())return;let r="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),te.token=r,te.isAuthenticated=!0),!r&&te.token&&(r=te.token),te.onAuthSuccess=(e,t,n)=>{l(t),b(n),te.updateMappings(t,n)},i?te.setWidgetKey(i):te.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>te.token||e;ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();te.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await se.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&te.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw te.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ae.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=se.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return te.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(te.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();te.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.2.0","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;ne(t.headers)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(te.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(te.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();te.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){te.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){te.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);te.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw te.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return te.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),Ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();te.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await se.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&te.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=se.applyResponseModifications(e,s.rule.modificationActions),r=e}te.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&te.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach(([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}}),n._xhr.addEventListener("abort",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.2.0","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};te.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;ne(i)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),te.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=B(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();te.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;te.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;te.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(r,n),a&&A)te.mappings=s,te.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(r){const t=te.getSavedMappings(r,n);if(t&&Array.isArray(t.mappings))return te.mappings=t.mappings,te.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),te.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);te.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(r||te.token,n,(t,o)=>{te.saveMappings(t,o,r||te.token,n),te.updateMappings(t,o),e?.(t,o)},t)},recheckWidgetVisibility:()=>{te.init()}}},ue=o();ue||(globalThis.mockforme=de);let fe=de;ue&&(fe=e=>({run:()=>{}}));const he=fe;module.exports=r})();
@@ -17,4 +17,4 @@ var e={492(e,t,n){n.r(t),n.d(t,{default:()=>k});var r,o=n(232),i={exports:{}},s=
17
17
  0% { transform: translateX(-100%) scaleX(0.4); }
18
18
  50% { transform: translateX(20%) scaleX(0.6); }
19
19
  100% { transform: translateX(100%) scaleX(0.4); }
20
- `;function lA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function cA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function dA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function uA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=fn();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function fA(){const{analyticsEnabled:e}=nr(),{token:t,organisationId:n}=mn();return u.useEffect(()=>{on.setEnabled(e)},[e]),u.useEffect(()=>{on.setToken(t)},[t]),u.useEffect(()=>{on.setOrganisationId(n)},[n]),null}function hA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(pA,{}),xt(Mt,{children:xt(un,{clientType:e,version:t,children:xt(gn,{children:xt(wn,{children:xt(Tn,{children:xt(jn,{children:xt(tr,{children:xt(Wn,{children:Ct(sr,{children:[xt(fA,{}),xt(Qo,{}),xt(gA,{})]})})})})})})})})})]})}function pA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function gA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=fn(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=mn(),{debugRules:f,editRules:h}=$n(),{globalDelay:p}=nr();if(!A&&(l||a))return Ct(Bt,{children:[xt(Mo,{children:xt(vA,{children:xt(yA,{})})}),xt(Ja,{})]});if(!a)return Ct(Bt,{children:[xt(Mo,{children:Ct(vA,{children:[xt(ga,{}),xt(uA,{})]})}),xt(Ja,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(Mo,{children:[xt(Ro,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(zo,{}),Ct(vA,{children:[xt(ua,{}),xt(ma,{}),xt(ba,{}),xt(xa,{}),xt(Ta,{}),xt(ja,{}),xt(uA,{}),xt(wA,{})]})]}),xt(Ja,{})]})}var mA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function yA(){const e=Ut();return Ct("div",{css:mA,children:[xt(wi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function wA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=mn(),n=Ut();return null==e?null:xt(oi,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var kA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},bA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function vA({children:e}){const{fullscreenSlotRef:t}=fn();return Ct("div",{css:bA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:kA})]})}class BA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Rr(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const xA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-DDAwMiHY.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function CA(e,t){return!(!xA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(xA)}catch{return!1}}()||!(e&&e.startsWith(xA)||t&&-1!==t.indexOf(xA)))}let EA=null;const FA="data-mfm-mount";function SA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function QA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{on.init(),on.setClientType(e);const t=nn().read("MFM_TOKEN");t&&on.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${FA}]`);s||(s=document.createElement("div"),s.setAttribute(FA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(BA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(hA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;CA(e.filename,t?.stack)&&(Rr(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;CA(void 0,t?.stack??(t?String(t):void 0))&&(Rr(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(Or>0)){if(xA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(xA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}EA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Gr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else on.track("widget_destroyed");qr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const UA={run(e,t={}){if(EA)return EA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=SA(e);r&&(EA=QA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),EA&&EA.destroy()}}}const n=SA(e);return n?(EA=QA(n,t),EA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=UA),n.d(t,["M",0,UA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},i=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},s=new Map;let a=[];function A(e){a=e}function l(){return a}function c(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),A=function(e,t){if(0===s.size)return null;for(const n of s.values())for(const r of n){if(o(r.apiMethod)!==o(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||i(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(A)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${A.url}`),A;for(const s of a)if(o(s.apiMethod)===o(t)){const o=n(s.apiEndpoint);if(o===r||i(o,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${s.apiEndpoint}`);const n={url:e,method:s.apiMethod,apiEndpoint:s.apiEndpoint,_ack:s._ack||null};return s._ri_&&(n._ri_=s._ri_),n}}return null}const d="JAVASCRIPT",u="mockforme",f="https://api.mockforme.com",h=`${f}/mockforme`,p=`${f}/gateway/3f4eae522b`;let g=null,m=null,y=null,w=[];function k({_o:e,mk:t,_mck:n,_rules:r}){g=e,m=t,y=n,w=r}function b(){return w}function v(){return`${h}/${g}/${m}`}function B(){return y}function x(e,t,n,r){fetch(p,{method:"GET",headers:{[u]:e,mfmver:"14.0.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,l=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);k({_o:o,mk:s,_mck:i,_rules:a}),l&&(A(l),n(l,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const C=`${f}/mockforme/mfm_op_3f4eae522b/manage`,E=e=>({[u]:e,mfmver:"14.0.0","Content-Type":"application/json"}),F=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},S="MFM_INTERCEPTOR_RULES";let Q=[];const U=new Map;function T(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(S);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function I(e){Q=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function _(e,t){if(!e||!t)return null;if(!Q.length&&(Q=T(),!Q.length))return null;const n=String(e).toUpperCase();return Q.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function M({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{U.has(e)&&(U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);U.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}Q=T(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&I(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===S&&(Q=T())});const H="MFM_REQUEST_EDITOR_RULES";let L=[];const D=new Map;function N(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(H);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function j(e){L=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function O(e,t){if(!e||!t)return null;if(!L.length&&(L=N(),!L.length))return null;const n=String(e).toUpperCase();return L.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function R(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function P({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{D.has(e)&&(D.delete(e),i(R(e,n,r)))},o);D.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),D.delete(e),i(R(e,n,r))}})}L=N(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&j(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===H&&(L=N())});const z="MFM_GLOBAL_DELAY";let K={enabled:!1,seconds:0},V=0;function G(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(z);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function q(){const e=Date.now();return e-V>500&&(K=G(),V=e),K.enabled&&K.seconds>0?Math.round(1e3*K.seconds):0}K=G(),V=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===z&&(K=G(),V=Date.now())});var J,W,$=n(232);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(J||(J={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}(W||(W={}));const X="MFM_TOKEN",Y="MFM_CACHED_MAPPINGS",Z="MFM_INTERCEPTION_ENABLED",ee=new class{constructor(e={}){r()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(X):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(Z);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Z,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case W.MFM_REQ_MAPPINGS:this.refreshMappings();break;case W.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case W.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case W.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case W.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case W.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case W.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case W.MFM_DEBUG_RULES_UPDATE:I(n?.rules||[]);break;case W.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=U.get(e.requestId);t&&(clearTimeout(t.timer),U.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_REQUEST_EDIT_RULES_UPDATE:j(n?.rules||[]);break;case W.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=D.get(e.requestId);t&&(clearTimeout(t.timer),D.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return K={enabled:!1,seconds:0},void(V=Date.now());K={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},V=Date.now()}(n);break;case W.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&s.set(String(r),Array.isArray(o)?o:[]);break;case W.MFM_FLOW_MOCK_CLEAR:!function(e){e&&s.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||$.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.0.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem(X,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${C}/apis`,{method:"GET",headers:E(e)});return F(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage(W.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${C}/api/${t}/toggle-state`,{method:"PUT",headers:E(e),body:JSON.stringify({enabled:!!n})});return F(r)})(this.token,e,t).then(n=>{this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&x(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)},e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")?(this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage(W.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage(W.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Y,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Y);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage(W.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage(W.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=a.length,r=o(e||"");return a=a.filter(e=>!(o(e.apiMethod)===r&&e.apiEndpoint===t)),a.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const i=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage(W.MFM_MOCK_DISABLED,{method:e,url:t,message:`${i} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach(e=>{const n=e.split(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage(W.MFM_REQ,a);else if(this.sendMessage(W.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage(W.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function te(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class ne{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class oe{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach(t=>{e.searchParams.delete(t),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class ie{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&ne.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,r=oe.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return oe.applyResponseModifications(e,t)}}class se{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:se.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=ie.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,c)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,r={}){if(this._captured)return;this._captured=!0;const o=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=ie.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const Ae=[p,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function le(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Ae.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const ce=(e,t=null,n=d)=>{if(r())return;let o="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===d)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),ee.token=o,ee.isAuthenticated=!0),!o&&ee.token&&(o=ee.token),ee.onAuthSuccess=(e,t,n)=>{A(t),k(n),ee.updateMappings(t,n)},i?ee.setWidgetKey(i):ee.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:f,_mck:h,_rules:p=[]}=t;return A(s),k({_o:a,mk:f,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>ee.token||e;se.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();ee.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await ie.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&ee.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw ee.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:se.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=ie.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return ee.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(ee.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();ee.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${v()}${e.url}${c}`,f={[u]:l,mfmver:"14.0.0","x-mfm-adaptor":t};const h=B();h&&e._ack&&(f["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(f._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(f).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;te(t.headers)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(ee.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(ee.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=v();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();ee.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=O(e.method,e.url),c=_(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await P({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){ee.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=q();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await M({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){ee.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);ee.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw ee.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return ee.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),ae.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();ee.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await ie.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&ee.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=ie.applyResponseModifications(e,s.rule.modificationActions),r=e}ee.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&ee.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach(([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}}),n._xhr.addEventListener("abort",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${v()}${e.url}${l.search}`,d={[u]:A,mfmver:"14.0.0","x-mfm-adaptor":t};const f=B();f&&e._ack&&(d["x-mfm-key"]=`${f}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};ee.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;te(i)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),ee.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=v(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();ee.addRequest("other",{...e,pending:!0,startTime:s});const a=O(e.method,e.url),A=_(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;ee.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await M({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;ee.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await P({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=q();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=q();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&f)ee.mappings=s,ee.rules=p,e?.(s,{_o:a,mk:f,_mck:h,_rules:p});else if(o){const t=ee.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return ee.mappings=t.mappings,ee.rules=t.meta?._rules||[],A(t.mappings),k(t.meta),ee.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);ee.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:c,getMappings:l,doFetchMappings:(e,t)=>{x(o||ee.token,n,(t,r)=>{ee.saveMappings(t,r,o||ee.token,n),ee.updateMappings(t,r),e?.(t,r)},t)},recheckWidgetVisibility:()=>{ee.init()}}},de=r();de||(globalThis.mockforme=ce);let ue=ce;de&&(ue=e=>({run:()=>{}}));const fe=ue;export{fe as mockforme};
20
+ `;function lA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function cA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function dA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function uA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=fn();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function fA(){const{analyticsEnabled:e}=nr(),{token:t,organisationId:n}=mn();return u.useEffect(()=>{on.setEnabled(e)},[e]),u.useEffect(()=>{on.setToken(t)},[t]),u.useEffect(()=>{on.setOrganisationId(n)},[n]),null}function hA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(pA,{}),xt(Mt,{children:xt(un,{clientType:e,version:t,children:xt(gn,{children:xt(wn,{children:xt(Tn,{children:xt(jn,{children:xt(tr,{children:xt(Wn,{children:Ct(sr,{children:[xt(fA,{}),xt(Qo,{}),xt(gA,{})]})})})})})})})})})]})}function pA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function gA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=fn(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=mn(),{debugRules:f,editRules:h}=$n(),{globalDelay:p}=nr();if(!A&&(l||a))return Ct(Bt,{children:[xt(Mo,{children:xt(vA,{children:xt(yA,{})})}),xt(Ja,{})]});if(!a)return Ct(Bt,{children:[xt(Mo,{children:Ct(vA,{children:[xt(ga,{}),xt(uA,{})]})}),xt(Ja,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(Mo,{children:[xt(Ro,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(zo,{}),Ct(vA,{children:[xt(ua,{}),xt(ma,{}),xt(ba,{}),xt(xa,{}),xt(Ta,{}),xt(ja,{}),xt(uA,{}),xt(wA,{})]})]}),xt(Ja,{})]})}var mA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function yA(){const e=Ut();return Ct("div",{css:mA,children:[xt(wi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function wA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=mn(),n=Ut();return null==e?null:xt(oi,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var kA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},bA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function vA({children:e}){const{fullscreenSlotRef:t}=fn();return Ct("div",{css:bA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:kA})]})}class BA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Rr(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const xA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-DDAwMiHY.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function CA(e,t){return!(!xA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(xA)}catch{return!1}}()||!(e&&e.startsWith(xA)||t&&-1!==t.indexOf(xA)))}let EA=null;const FA="data-mfm-mount";function SA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function QA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{on.init(),on.setClientType(e);const t=nn().read("MFM_TOKEN");t&&on.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${FA}]`);s||(s=document.createElement("div"),s.setAttribute(FA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(BA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(hA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;CA(e.filename,t?.stack)&&(Rr(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;CA(void 0,t?.stack??(t?String(t):void 0))&&(Rr(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(Or>0)){if(xA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(xA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}EA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Gr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else on.track("widget_destroyed");qr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const UA={run(e,t={}){if(EA)return EA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=SA(e);r&&(EA=QA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),EA&&EA.destroy()}}}const n=SA(e);return n?(EA=QA(n,t),EA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=UA),n.d(t,["M",0,UA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},i=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},s=new Map;let a=[];function A(e){a=e}function l(){return a}function c(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),A=function(e,t){if(0===s.size)return null;for(const n of s.values())for(const r of n){if(o(r.apiMethod)!==o(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||i(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(A)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${A.url}`),A;for(const s of a)if(o(s.apiMethod)===o(t)){const o=n(s.apiEndpoint);if(o===r||i(o,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${s.apiEndpoint}`);const n={url:e,method:s.apiMethod,apiEndpoint:s.apiEndpoint,_ack:s._ack||null};return s._ri_&&(n._ri_=s._ri_),n}}return null}const d="JAVASCRIPT",u="mockforme",f="https://api.mockforme.com",h=`${f}/mockforme`,p=`${f}/gateway/3f4eae522b`;let g=null,m=null,y=null,w=[];function k({_o:e,mk:t,_mck:n,_rules:r}){g=e,m=t,y=n,w=r}function b(){return w}function v(){return`${h}/${g}/${m}`}function B(){return y}function x(e,t,n,r){fetch(p,{method:"GET",headers:{[u]:e,mfmver:"14.2.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,l=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);k({_o:o,mk:s,_mck:i,_rules:a}),l&&(A(l),n(l,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const C=`${f}/mockforme/mfm_op_3f4eae522b/manage`,E=e=>({[u]:e,mfmver:"14.2.0","Content-Type":"application/json"}),F=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},S="MFM_INTERCEPTOR_RULES";let Q=[];const U=new Map;function T(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(S);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function I(e){Q=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function _(e,t){if(!e||!t)return null;if(!Q.length&&(Q=T(),!Q.length))return null;const n=String(e).toUpperCase();return Q.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function M({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{U.has(e)&&(U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);U.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}Q=T(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&I(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===S&&(Q=T())});const H="MFM_REQUEST_EDITOR_RULES";let L=[];const D=new Map;function N(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(H);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function j(e){L=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function O(e,t){if(!e||!t)return null;if(!L.length&&(L=N(),!L.length))return null;const n=String(e).toUpperCase();return L.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function R(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function P({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{D.has(e)&&(D.delete(e),i(R(e,n,r)))},o);D.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),D.delete(e),i(R(e,n,r))}})}L=N(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&j(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===H&&(L=N())});const z="MFM_GLOBAL_DELAY";let K={enabled:!1,seconds:0},V=0;function G(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(z);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function q(){const e=Date.now();return e-V>500&&(K=G(),V=e),K.enabled&&K.seconds>0?Math.round(1e3*K.seconds):0}K=G(),V=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===z&&(K=G(),V=Date.now())});var J,W,$=n(232);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(J||(J={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}(W||(W={}));const X="MFM_TOKEN",Y="MFM_CACHED_MAPPINGS",Z="MFM_INTERCEPTION_ENABLED",ee=new class{constructor(e={}){r()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(X):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(Z);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Z,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case W.MFM_REQ_MAPPINGS:this.refreshMappings();break;case W.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case W.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case W.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case W.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case W.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case W.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case W.MFM_DEBUG_RULES_UPDATE:I(n?.rules||[]);break;case W.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=U.get(e.requestId);t&&(clearTimeout(t.timer),U.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_REQUEST_EDIT_RULES_UPDATE:j(n?.rules||[]);break;case W.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=D.get(e.requestId);t&&(clearTimeout(t.timer),D.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return K={enabled:!1,seconds:0},void(V=Date.now());K={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},V=Date.now()}(n);break;case W.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&s.set(String(r),Array.isArray(o)?o:[]);break;case W.MFM_FLOW_MOCK_CLEAR:!function(e){e&&s.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||$.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.2.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem(X,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${C}/apis`,{method:"GET",headers:E(e)});return F(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage(W.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${C}/api/${t}/toggle-state`,{method:"PUT",headers:E(e),body:JSON.stringify({enabled:!!n})});return F(r)})(this.token,e,t).then(n=>{this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&x(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)},e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")?(this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage(W.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage(W.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Y,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Y);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage(W.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage(W.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=a.length,r=o(e||"");return a=a.filter(e=>!(o(e.apiMethod)===r&&e.apiEndpoint===t)),a.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const i=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage(W.MFM_MOCK_DISABLED,{method:e,url:t,message:`${i} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach(e=>{const n=e.split(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage(W.MFM_REQ,a);else if(this.sendMessage(W.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage(W.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function te(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class ne{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class oe{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach(t=>{e.searchParams.delete(t),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class ie{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&ne.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,r=oe.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return oe.applyResponseModifications(e,t)}}class se{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:se.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=ie.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,c)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,r={}){if(this._captured)return;this._captured=!0;const o=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=ie.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const Ae=[p,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function le(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Ae.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const ce=(e,t=null,n=d)=>{if(r())return;let o="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===d)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),ee.token=o,ee.isAuthenticated=!0),!o&&ee.token&&(o=ee.token),ee.onAuthSuccess=(e,t,n)=>{A(t),k(n),ee.updateMappings(t,n)},i?ee.setWidgetKey(i):ee.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:f,_mck:h,_rules:p=[]}=t;return A(s),k({_o:a,mk:f,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>ee.token||e;se.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();ee.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await ie.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&ee.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw ee.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:se.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=ie.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return ee.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(ee.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();ee.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${v()}${e.url}${c}`,f={[u]:l,mfmver:"14.2.0","x-mfm-adaptor":t};const h=B();h&&e._ack&&(f["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(f._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(f).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;te(t.headers)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(ee.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(ee.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=v();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();ee.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=O(e.method,e.url),c=_(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await P({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){ee.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=q();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await M({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){ee.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);ee.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw ee.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return ee.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),ae.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();ee.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await ie.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&ee.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=ie.applyResponseModifications(e,s.rule.modificationActions),r=e}ee.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&ee.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach(([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}}),n._xhr.addEventListener("abort",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${v()}${e.url}${l.search}`,d={[u]:A,mfmver:"14.2.0","x-mfm-adaptor":t};const f=B();f&&e._ack&&(d["x-mfm-key"]=`${f}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};ee.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;te(i)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),ee.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=v(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();ee.addRequest("other",{...e,pending:!0,startTime:s});const a=O(e.method,e.url),A=_(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;ee.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await M({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;ee.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await P({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=q();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=q();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&f)ee.mappings=s,ee.rules=p,e?.(s,{_o:a,mk:f,_mck:h,_rules:p});else if(o){const t=ee.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return ee.mappings=t.mappings,ee.rules=t.meta?._rules||[],A(t.mappings),k(t.meta),ee.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);ee.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:c,getMappings:l,doFetchMappings:(e,t)=>{x(o||ee.token,n,(t,r)=>{ee.saveMappings(t,r,o||ee.token,n),ee.updateMappings(t,r),e?.(t,r)},t)},recheckWidgetVisibility:()=>{ee.init()}}},de=r();de||(globalThis.mockforme=ce);let ue=ce;de&&(ue=e=>({run:()=>{}}));const fe=ue;export{fe as mockforme};
@@ -17,4 +17,4 @@
17
17
  0% { transform: translateX(-100%) scaleX(0.4); }
18
18
  50% { transform: translateX(20%) scaleX(0.6); }
19
19
  100% { transform: translateX(100%) scaleX(0.4); }
20
- `;function lA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function cA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function dA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function uA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=fn();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:o,message:r,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":o??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[o?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:o}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:r}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function fA(){const{analyticsEnabled:e}=no(),{token:t,organisationId:n}=mn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function hA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(pA,{}),xt(Mt,{children:xt(un,{clientType:e,version:t,children:xt(gn,{children:xt(wn,{children:xt(Tn,{children:xt(jn,{children:xt(to,{children:xt(Wn,{children:Ct(so,{children:[xt(fA,{}),xt(Qr,{}),xt(gA,{})]})})})})})})})})})]})}function pA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function gA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:o,openSettings:r,startSnipping:i,requestConfirm:s}=fn(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=mn(),{debugRules:f,editRules:h}=$n(),{globalDelay:p}=no();if(!A&&(l||a))return Ct(Bt,{children:[xt(Mr,{children:xt(vA,{children:xt(yA,{})})}),xt(Ja,{})]});if(!a)return Ct(Bt,{children:[xt(Mr,{children:Ct(vA,{children:[xt(ga,{}),xt(uA,{})]})}),xt(Ja,{})]});const g=o||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(Mr,{children:[xt(Rr,{onSnip:i,onReload:d,onOpenSettings:r,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(zr,{}),Ct(vA,{children:[xt(ua,{}),xt(ma,{}),xt(ba,{}),xt(xa,{}),xt(Ta,{}),xt(ja,{}),xt(uA,{}),xt(wA,{})]})]}),xt(Ja,{})]})}var mA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function yA(){const e=Ut();return Ct("div",{css:mA,children:[xt(wi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function wA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=mn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var kA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},bA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function vA({children:e}){const{fullscreenSlotRef:t}=fn();return Ct("div",{css:bA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:kA})]})}class BA extends u.Component{constructor(){super(...arguments),r(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Po(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const xA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-DDAwMiHY.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function CA(e,t){return!(!xA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(xA)}catch{return!1}}()||!(e&&e.startsWith(xA)||t&&-1!==t.indexOf(xA)))}let EA=null;const FA="data-mfm-mount";function SA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function QA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=nn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const o=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],r=e=>e.stopPropagation();for(const e of o){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,r,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${FA}]`);s||(s=document.createElement("div"),s.setAttribute(FA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(ot,{value:a},u.createElement(BA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(hA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;CA(e.filename,t?.stack)&&(Po(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;CA(void 0,t?.stack??(t?String(t):void 0))&&(Po(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(Ro>0)){if(xA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(xA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}EA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),o=t&&"string"==typeof t.stack?t.stack:"";qo("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:o.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Jo()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const o=document.createElement("div");o.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const r=document.createElement("div");r.textContent="MockForMe is unable to load.",r.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),o.appendChild(r),o.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(o),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const UA={run(e,t={}){if(EA)return EA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const o=()=>{if(n)return;const o=SA(e);o&&(EA=QA(o,t))};return document.addEventListener("DOMContentLoaded",o,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",o),EA&&EA.destroy()}}}const n=SA(e);return n?(EA=QA(n,t),EA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=UA),n.d(t,["M",0,UA])}};const t={};function n(o){const r=t[o];if(void 0!==r)return r.exports;const i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var o=0;o<t.length;){var r=t[o++],i=t[o++];n.o(e,r)?0===i&&o++:0===i?Object.defineProperty(e,r,{enumerable:!0,value:t[o++]}):Object.defineProperty(e,r,{enumerable:!0,get:i})}else 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),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let o={};n.d(o,{mockforme:()=>he});const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),o=t.split("/");if(n.length!==o.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==o[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,o=n(e),r=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const o of n){if(i(o.apiMethod)!==i(t))continue;const n=o.apiEndpoint.startsWith("/")?o.apiEndpoint:`/${o.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:o.apiMethod,_ack:o._ack||null};return o._ri_&&(t._ri_=o._ri_),t}}return null}(o,t);if(r)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${r.url}`),r;for(const r of A)if(i(r.apiMethod)===i(t)){const i=n(r.apiEndpoint);if(i===o||s(i,o)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${r.apiEndpoint}`);const n={url:e,method:r.apiMethod,apiEndpoint:r.apiEndpoint,_ack:r._ack||null};return r._ri_&&(n._ri_=r._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:o}){m=e,y=t,w=n,k=o}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,o){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.0.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:o,_o:r,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var o;const r=function(e,t){const n=t.length;return e.split("").map((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%n))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),n+t);return JSON.parse(r)}({di:t,iv:o},r);b({_o:r,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:r,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),o(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.0.0","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:o,timeoutMs:r=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body}))},r);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:o,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const o={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{o[e]=String(t??"")}),{requestId:e,cancel:!1,headers:o,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:o,timeoutMs:r=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,o)))},r);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:o,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,o))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())});var W,$,X=n(232);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const Y="MFM_TOKEN",Z="MFM_CACHED_MAPPINGS",ee="MFM_INTERCEPTION_ENABLED",te=new class{constructor(e={}){r()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Y):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(ee);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(ee,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var o,r;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case $.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case $.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case $.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:o=n?.runId,r=n?.apis||[],o&&a.set(String(o),Array.isArray(r)?r:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||X.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.0.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem(Y,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const o=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(o)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)},e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")?(this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,o="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Z,JSON.stringify({token:n,adaptor:o,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Z);if(!n)return null;const o=JSON.parse(n);return o?.token&&e&&o.token!==e||o?.adaptor&&t&&o.adaptor!==t?null:o}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage($.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},o=n.timingAction||{},r=o.activeAction||"MODIFY";let i="MODIFY";"delay"===r?i="DELAY":"delay_and_timeout"===r?i="TIMEOUT":"delay_and_redirect"===r&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||o.activeAction)&&(s.timingAction=o),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,o=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===o&&e.apiEndpoint===t)),A.length!==n}(e,t),o=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===o)return;this.updateMappings(this.mappings,{_rules:this.rules});const r=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${r} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach(e=>{const n=e.split(": "),o=n.shift();o&&(t[o]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let o,r,i;if(void 0===t.status||null===t.status)o=void 0;else if("number"==typeof t.status)o=t.status;else{const e=Number(t.status);Number.isFinite(e)?o=e:(o=0,r=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===r)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:o,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...r?{statusText:r}:{},...i?{errorReason:i,failed:!0}:{}},a={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,o="string"==typeof n?JSON.parse(n):n;o&&"string"==typeof o.message&&o.message.trim()&&(e=o.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ne(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class oe{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:o,queryParams:r,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(r&&void 0!==r[A])t=String(r[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",o){const n=Object.keys(o).find(t=>t.toLowerCase()===e);t=n?String(o[n]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const o=t?.toLowerCase(),r=String(e),i=String(n);switch(o){case"contains":return r.includes(i);case"equal":case"equals":return r===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),o=e.slice(t+1);return new RegExp(n,o).test(r)}return new RegExp(e).test(r)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,o=n?.[t];if(!o)return{type:"passThrough",delay:0};const r={type:"passThrough",delay:0},i=Number(o.value||0);switch(t){case"delay":r.delay=i,r.delay>0&&await new Promise(e=>setTimeout(e,1e3*r.delay));break;case"redirect":case"delay_and_redirect":r.type="redirect",r.delay=i,r.redirectUrl=o.redirectUrl,r.delay>0&&await new Promise(e=>setTimeout(e,1e3*r.delay));break;case"delay_and_timeout":r.type="timeout",r.delay=i,r.delay>0&&await new Promise(e=>setTimeout(e,1e3*r.delay))}return r}}class ie{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:o,headers:r,queryParams:i,body:s}={...e};r&&(r={...r}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach(t=>{e.searchParams.delete(t),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(r={...r},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{r[e]=t}));const c=String(o||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:r,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,o={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{o[e]=t}),o}}class se{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&oe.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,o=ie.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:o,rule:n}}static applyResponseModifications(e,t){return ie.applyResponseModifications(e,t)}}class ae{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:i=async(e,t,n,o,r)=>null,onMockMatch:s=async(e,t,n,o,r)=>null,onOtherRequest:a=async(e,t,n,o)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,o=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:o,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ae.getQueryParams(n)},l(d))return t(e,c);r(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const r=n(),A=se.match(d,r);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=o(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,c)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class Ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:i=(e,t,n,o)=>{o.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,o)=>{o.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,o={}){if(this._captured)return;this._captured=!0;const r=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),r("readystatechange"),"Aborted"===e||o.aborted?r("abort"):0===e||"Error"===e||o.error?r("error"):"Timeout"===e||o.timeout?r("timeout"):r("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,o=null,r=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,o,r)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:Ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);r(t);const c=n(),d=se.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=o(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const le=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function ce(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return le.some(e=>{const o=new URL(e,t);return n.origin===o.origin&&n.pathname===o.pathname})}catch{return!1}}const de=(e,t=null,n=u)=>{if(r())return;let o="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),te.token=o,te.isAuthenticated=!0),!o&&te.token&&(o=te.token),te.onAuthSuccess=(e,t,n)=>{l(t),b(n),te.updateMappings(t,n)},i?te.setWidgetKey(i):te.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>te.token||e;ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o,r)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();te.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await se.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&te.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw te.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...o};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ae.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}return r(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=se.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),o=t.headers.get("content-type")||"",r=Date.now()-s;try{let i;i=o.includes("application/json")?await t.json():await t.text(),te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:r,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:r,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return te.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(te.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,o,r,i,s)=>{const a=o.requestId||Math.random().toString(36).substring(7),A=Date.now();te.addRequest("mocked",{...o,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(o.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.0.0","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=r instanceof Request?r.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&r instanceof Request){const e=r.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:o.method,headers:g,credentials:r instanceof Request&&r.credentials||i.credentials||"include",mode:r instanceof Request&&r.mode||i.mode||"cors",signal:r instanceof Request&&r.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),r=n.headers.get("content-type")||"",i=Date.now()-A;ne(t.headers)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(te.addRequest("mocked",{...o,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return r.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(te.addRequest("mocked",{...o,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(r,i)})},onOtherRequest:async(e,t,n,o)=>{const r=n?.headers||(t instanceof Request?t.headers:{});let i=!1;r instanceof Headers?i="true"===r.get("x-mfm-internal"):"object"==typeof r&&(i="true"===r["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return o(t,n);const a=e.requestId,A=Date.now();te.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const o=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(o.cancel){te.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let r=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),r="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:o.headers||{},body:s?null==o.body?void 0:o.body:void 0},d=r,f={...e,url:r,headers:o.headers||{},body:s?o.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await o(d,u)}catch(e){g=e}if(c){let t="",n=0,o={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,o=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const r=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:o,body:t}});if(r.simulateTimeout){te.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}r.delayMs>0&&await new Promise(e=>setTimeout(e,r.delayMs));const i=Number(r.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=r.headers&&"object"==typeof r.headers?r.headers:o,d="string"==typeof r.body?r.body:null==r.body?"":JSON.stringify(r.body);te.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw te.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),o=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=o===n?void 0:o}catch(e){w=void 0}return te.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),Ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o)=>{const r=t.requestId,i=Date.now();te.addRequest("mocked",{...t,requestId:r,pending:!0,startTime:i,rule:e});const s=await se.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&te.addRequest("mocked",{...a,requestId:r,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}const d=(e,t,o,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof o?Object.fromEntries(o.split("\r\n").filter(e=>e).map(e=>e.split(": "))):o;e=se.applyResponseModifications(e,s.rule.modificationActions),o=e}te.addRequest("mocked",{...a,requestId:r,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&te.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,o,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach(([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}}),n._xhr.addEventListener("abort",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),o(a.body)},onMockMatch:(e,o,r,i)=>{const s=o.requestId,a=Date.now(),A=n(),l=new URL(o.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.0.0","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...o.headers,...d};te.addRequest("mocked",{...o,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(r._captured)return;const l=Date.now()-a;ne(i)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),te.addRequest("mocked",{...o,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),r._capture(t,n,i,A)};r._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),r._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),r._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(o.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=r.proxy.withCredentials,r._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(o.body)},onOtherRequest:(e,t,n)=>{const o="true"===e.headers?.["x-mfm-internal"],r=B(),i=e.url.startsWith(r);if("OPTIONS"===e.method||o||i)return n(e.body);const s=Date.now();te.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,o,r,i={})=>{const a=Date.now()-s;te.addRequest("other",{...e,status:n,responseBody:o,responseHeaders:r,pending:!1,duration:a,...i}),t._capture(n,o,r,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,o=t._xhr.responseText,r=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof r&&r.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:o}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,o,r)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const o=Date.now()-s;te.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:o})}}}),a)return void(async()=>{const o={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{o[t]=e})}catch(e){}const r=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:o});if(r.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(r.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:r.headers||{},body:r.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==r.body?null:r.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&A)te.mappings=s,te.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(o){const t=te.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return te.mappings=t.mappings,te.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),te.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);te.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(o||te.token,n,(t,r)=>{te.saveMappings(t,r,o||te.token,n),te.updateMappings(t,r),e?.(t,r)},t)},recheckWidgetVisibility:()=>{te.init()}}},ue=r();ue||(globalThis.mockforme=de);let fe=de;ue&&(fe=e=>({run:()=>{}}));const he=fe;return o=o.mockforme,o})());
20
+ `;function lA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function cA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function dA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function uA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=fn();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:o,message:r,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":o??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[o?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:o}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:r}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function fA(){const{analyticsEnabled:e}=no(),{token:t,organisationId:n}=mn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function hA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(pA,{}),xt(Mt,{children:xt(un,{clientType:e,version:t,children:xt(gn,{children:xt(wn,{children:xt(Tn,{children:xt(jn,{children:xt(to,{children:xt(Wn,{children:Ct(so,{children:[xt(fA,{}),xt(Qr,{}),xt(gA,{})]})})})})})})})})})]})}function pA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function gA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:o,openSettings:r,startSnipping:i,requestConfirm:s}=fn(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=mn(),{debugRules:f,editRules:h}=$n(),{globalDelay:p}=no();if(!A&&(l||a))return Ct(Bt,{children:[xt(Mr,{children:xt(vA,{children:xt(yA,{})})}),xt(Ja,{})]});if(!a)return Ct(Bt,{children:[xt(Mr,{children:Ct(vA,{children:[xt(ga,{}),xt(uA,{})]})}),xt(Ja,{})]});const g=o||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(Mr,{children:[xt(Rr,{onSnip:i,onReload:d,onOpenSettings:r,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(zr,{}),Ct(vA,{children:[xt(ua,{}),xt(ma,{}),xt(ba,{}),xt(xa,{}),xt(Ta,{}),xt(ja,{}),xt(uA,{}),xt(wA,{})]})]}),xt(Ja,{})]})}var mA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function yA(){const e=Ut();return Ct("div",{css:mA,children:[xt(wi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function wA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=mn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var kA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},bA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function vA({children:e}){const{fullscreenSlotRef:t}=fn();return Ct("div",{css:bA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:kA})]})}class BA extends u.Component{constructor(){super(...arguments),r(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Po(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const xA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-DDAwMiHY.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function CA(e,t){return!(!xA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(xA)}catch{return!1}}()||!(e&&e.startsWith(xA)||t&&-1!==t.indexOf(xA)))}let EA=null;const FA="data-mfm-mount";function SA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function QA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=nn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const o=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],r=e=>e.stopPropagation();for(const e of o){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,r,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${FA}]`);s||(s=document.createElement("div"),s.setAttribute(FA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(ot,{value:a},u.createElement(BA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(hA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;CA(e.filename,t?.stack)&&(Po(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;CA(void 0,t?.stack??(t?String(t):void 0))&&(Po(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(Ro>0)){if(xA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(xA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}EA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),o=t&&"string"==typeof t.stack?t.stack:"";qo("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:o.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Jo()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const o=document.createElement("div");o.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const r=document.createElement("div");r.textContent="MockForMe is unable to load.",r.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),o.appendChild(r),o.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(o),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const UA={run(e,t={}){if(EA)return EA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const o=()=>{if(n)return;const o=SA(e);o&&(EA=QA(o,t))};return document.addEventListener("DOMContentLoaded",o,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",o),EA&&EA.destroy()}}}const n=SA(e);return n?(EA=QA(n,t),EA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=UA),n.d(t,["M",0,UA])}};const t={};function n(o){const r=t[o];if(void 0!==r)return r.exports;const i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var o=0;o<t.length;){var r=t[o++],i=t[o++];n.o(e,r)?0===i&&o++:0===i?Object.defineProperty(e,r,{enumerable:!0,value:t[o++]}):Object.defineProperty(e,r,{enumerable:!0,get:i})}else 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),n.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let o={};n.d(o,{mockforme:()=>he});const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),o=t.split("/");if(n.length!==o.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==o[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,o=n(e),r=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const o of n){if(i(o.apiMethod)!==i(t))continue;const n=o.apiEndpoint.startsWith("/")?o.apiEndpoint:`/${o.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:o.apiMethod,_ack:o._ack||null};return o._ri_&&(t._ri_=o._ri_),t}}return null}(o,t);if(r)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${r.url}`),r;for(const r of A)if(i(r.apiMethod)===i(t)){const i=n(r.apiEndpoint);if(i===o||s(i,o)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${r.apiEndpoint}`);const n={url:e,method:r.apiMethod,apiEndpoint:r.apiEndpoint,_ack:r._ack||null};return r._ri_&&(n._ri_=r._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:o}){m=e,y=t,w=n,k=o}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,o){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.2.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:o,_o:r,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var o;const r=function(e,t){const n=t.length;return e.split("").map((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%n))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),n+t);return JSON.parse(r)}({di:t,iv:o},r);b({_o:r,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:r,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),o(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.2.0","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:o,timeoutMs:r=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body}))},r);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:o,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const o={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{o[e]=String(t??"")}),{requestId:e,cancel:!1,headers:o,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:o,timeoutMs:r=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,o)))},r);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:o,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,o))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())});var W,$,X=n(232);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const Y="MFM_TOKEN",Z="MFM_CACHED_MAPPINGS",ee="MFM_INTERCEPTION_ENABLED",te=new class{constructor(e={}){r()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Y):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(ee);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(ee,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var o,r;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case $.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case $.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case $.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:o=n?.runId,r=n?.apis||[],o&&a.set(String(o),Array.isArray(r)?r:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||X.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.2.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem(Y,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const o=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(o)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)},e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")?(this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,o="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Z,JSON.stringify({token:n,adaptor:o,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Z);if(!n)return null;const o=JSON.parse(n);return o?.token&&e&&o.token!==e||o?.adaptor&&t&&o.adaptor!==t?null:o}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage($.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},o=n.timingAction||{},r=o.activeAction||"MODIFY";let i="MODIFY";"delay"===r?i="DELAY":"delay_and_timeout"===r?i="TIMEOUT":"delay_and_redirect"===r&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||o.activeAction)&&(s.timingAction=o),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,o=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===o&&e.apiEndpoint===t)),A.length!==n}(e,t),o=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===o)return;this.updateMappings(this.mappings,{_rules:this.rules});const r=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${r} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach(e=>{const n=e.split(": "),o=n.shift();o&&(t[o]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let o,r,i;if(void 0===t.status||null===t.status)o=void 0;else if("number"==typeof t.status)o=t.status;else{const e=Number(t.status);Number.isFinite(e)?o=e:(o=0,r=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===r)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:o,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...r?{statusText:r}:{},...i?{errorReason:i,failed:!0}:{}},a={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,o="string"==typeof n?JSON.parse(n):n;o&&"string"==typeof o.message&&o.message.trim()&&(e=o.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ne(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class oe{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:o,queryParams:r,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(r&&void 0!==r[A])t=String(r[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",o){const n=Object.keys(o).find(t=>t.toLowerCase()===e);t=n?String(o[n]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const o=t?.toLowerCase(),r=String(e),i=String(n);switch(o){case"contains":return r.includes(i);case"equal":case"equals":return r===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),o=e.slice(t+1);return new RegExp(n,o).test(r)}return new RegExp(e).test(r)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,o=n?.[t];if(!o)return{type:"passThrough",delay:0};const r={type:"passThrough",delay:0},i=Number(o.value||0);switch(t){case"delay":r.delay=i,r.delay>0&&await new Promise(e=>setTimeout(e,1e3*r.delay));break;case"redirect":case"delay_and_redirect":r.type="redirect",r.delay=i,r.redirectUrl=o.redirectUrl,r.delay>0&&await new Promise(e=>setTimeout(e,1e3*r.delay));break;case"delay_and_timeout":r.type="timeout",r.delay=i,r.delay>0&&await new Promise(e=>setTimeout(e,1e3*r.delay))}return r}}class ie{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:o,headers:r,queryParams:i,body:s}={...e};r&&(r={...r}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach(t=>{e.searchParams.delete(t),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(r={...r},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{r[e]=t}));const c=String(o||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:r,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,o={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{o[e]=t}),o}}class se{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&oe.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,o=ie.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:o,rule:n}}static applyResponseModifications(e,t){return ie.applyResponseModifications(e,t)}}class ae{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:i=async(e,t,n,o,r)=>null,onMockMatch:s=async(e,t,n,o,r)=>null,onOtherRequest:a=async(e,t,n,o)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,o=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:o,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ae.getQueryParams(n)},l(d))return t(e,c);r(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const r=n(),A=se.match(d,r);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=o(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,c)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class Ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:i=(e,t,n,o)=>{o.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,o)=>{o.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,o={}){if(this._captured)return;this._captured=!0;const r=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),r("readystatechange"),"Aborted"===e||o.aborted?r("abort"):0===e||"Error"===e||o.error?r("error"):"Timeout"===e||o.timeout?r("timeout"):r("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,o=null,r=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,o,r)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:Ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);r(t);const c=n(),d=se.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=o(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const le=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function ce(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return le.some(e=>{const o=new URL(e,t);return n.origin===o.origin&&n.pathname===o.pathname})}catch{return!1}}const de=(e,t=null,n=u)=>{if(r())return;let o="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),te.token=o,te.isAuthenticated=!0),!o&&te.token&&(o=te.token),te.onAuthSuccess=(e,t,n)=>{l(t),b(n),te.updateMappings(t,n)},i?te.setWidgetKey(i):te.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>te.token||e;ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o,r)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();te.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await se.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&te.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw te.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...o};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ae.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}return r(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=se.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),o=t.headers.get("content-type")||"",r=Date.now()-s;try{let i;i=o.includes("application/json")?await t.json():await t.text(),te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:r,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:r,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return te.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(te.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,o,r,i,s)=>{const a=o.requestId||Math.random().toString(36).substring(7),A=Date.now();te.addRequest("mocked",{...o,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(o.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.2.0","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=r instanceof Request?r.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&r instanceof Request){const e=r.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:o.method,headers:g,credentials:r instanceof Request&&r.credentials||i.credentials||"include",mode:r instanceof Request&&r.mode||i.mode||"cors",signal:r instanceof Request&&r.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),r=n.headers.get("content-type")||"",i=Date.now()-A;ne(t.headers)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(te.addRequest("mocked",{...o,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return r.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(te.addRequest("mocked",{...o,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(r,i)})},onOtherRequest:async(e,t,n,o)=>{const r=n?.headers||(t instanceof Request?t.headers:{});let i=!1;r instanceof Headers?i="true"===r.get("x-mfm-internal"):"object"==typeof r&&(i="true"===r["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return o(t,n);const a=e.requestId,A=Date.now();te.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const o=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(o.cancel){te.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let r=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),r="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:o.headers||{},body:s?null==o.body?void 0:o.body:void 0},d=r,f={...e,url:r,headers:o.headers||{},body:s?o.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await o(d,u)}catch(e){g=e}if(c){let t="",n=0,o={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,o=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const r=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:o,body:t}});if(r.simulateTimeout){te.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}r.delayMs>0&&await new Promise(e=>setTimeout(e,r.delayMs));const i=Number(r.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=r.headers&&"object"==typeof r.headers?r.headers:o,d="string"==typeof r.body?r.body:null==r.body?"":JSON.stringify(r.body);te.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw te.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),o=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=o===n?void 0:o}catch(e){w=void 0}return te.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),Ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o)=>{const r=t.requestId,i=Date.now();te.addRequest("mocked",{...t,requestId:r,pending:!0,startTime:i,rule:e});const s=await se.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&te.addRequest("mocked",{...a,requestId:r,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}const d=(e,t,o,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof o?Object.fromEntries(o.split("\r\n").filter(e=>e).map(e=>e.split(": "))):o;e=se.applyResponseModifications(e,s.rule.modificationActions),o=e}te.addRequest("mocked",{...a,requestId:r,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&te.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,o,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach(([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}}),n._xhr.addEventListener("abort",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),o(a.body)},onMockMatch:(e,o,r,i)=>{const s=o.requestId,a=Date.now(),A=n(),l=new URL(o.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.2.0","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...o.headers,...d};te.addRequest("mocked",{...o,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(r._captured)return;const l=Date.now()-a;ne(i)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),te.addRequest("mocked",{...o,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),r._capture(t,n,i,A)};r._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),r._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),r._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(o.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=r.proxy.withCredentials,r._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(o.body)},onOtherRequest:(e,t,n)=>{const o="true"===e.headers?.["x-mfm-internal"],r=B(),i=e.url.startsWith(r);if("OPTIONS"===e.method||o||i)return n(e.body);const s=Date.now();te.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,o,r,i={})=>{const a=Date.now()-s;te.addRequest("other",{...e,status:n,responseBody:o,responseHeaders:r,pending:!1,duration:a,...i}),t._capture(n,o,r,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,o=t._xhr.responseText,r=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof r&&r.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:o}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,o,r)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const o=Date.now()-s;te.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:o})}}}),a)return void(async()=>{const o={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{o[t]=e})}catch(e){}const r=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:o});if(r.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(r.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:r.headers||{},body:r.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==r.body?null:r.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&A)te.mappings=s,te.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(o){const t=te.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return te.mappings=t.mappings,te.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),te.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);te.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(o||te.token,n,(t,r)=>{te.saveMappings(t,r,o||te.token,n),te.updateMappings(t,r),e?.(t,r)},t)},recheckWidgetVisibility:()=>{te.init()}}},ue=r();ue||(globalThis.mockforme=de);let fe=de;ue&&(fe=e=>({run:()=>{}}));const he=fe;return o=o.mockforme,o})());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mockforme",
3
- "version": "14.0.0",
3
+ "version": "14.2.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",