mockforme 15.4.0 → 15.7.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 Td({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:[Bt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),Bt("span",{children:e})]})}function Md(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function Id(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function _d(){const e=Ut(),{confirmState:t,dismissConfirm:n}=Sn();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:i,confirmLabel:r,cancelLabel:s,danger:a,onConfirm:l}=t;return Bt("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?Bt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:o}):null,Bt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:i}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[Bt("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"}),Bt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),l()},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:r??"Confirm"})]})]})})}function Dd(){const{analyticsEnabled:e}=wo(),{token:t,organisationId:n}=Tn();return u.useEffect(()=>{yn.setEnabled(e)},[e]),u.useEffect(()=>{yn.setToken(t)},[t]),u.useEffect(()=>{yn.setOrganisationId(n)},[n]),null}function Ld({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[Bt(Hd,{}),Bt(_t,{children:Bt(En,{clientType:e,version:t,children:Bt(Un,{children:Bt(In,{children:Bt(qn,{children:Bt(ur,{children:Bt(to,{children:Bt(yo,{children:Bt(uo,{children:Ct(xo,{children:[Bt(Dd,{}),Bt(jr,{}),Ct(Pi,{children:[Bt(Nd,{}),Bt(la,{})]})]})})})})})})})})})})]})}function Hd(){const e=Ut();return Bt(ht,{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 Nd(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:o,openSettings:i,startSnipping:r,requestConfirm:s}=Sn(),{token:a,isTokenValidated:l,isValidating:A,isLoading:c,reloadMappings:d,deleteToken:u}=Tn(),{debugRules:p,editRules:f}=po(),{globalDelay:h}=wo();if(!l&&(A||a))return Ct(xt,{children:[Bt(Xr,{children:Bt(Kd,{children:Bt(zd,{})})}),Bt(gd,{})]});if(!a)return Ct(xt,{children:[Bt(Xr,{children:Ct(Kd,{children:[Bt(jA,{}),Bt(_d,{})]})}),Bt(gd,{})]});const g=o||p.length>0||f.length>0||h.enabled;return Ct(xt,{children:[Ct(Xr,{children:[Bt(ca,{}),Bt(is,{onSnip:r,onReload:d,onOpenSettings:i,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. 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}),Bt(ss,{}),Bt(ls,{}),Bt(fs,{}),Ct(Kd,{children:[Bt(OA,{}),Bt(KA,{}),Bt(WA,{}),Bt(XA,{}),Bt(ic,{}),Bt(uc,{}),Bt(yc,{}),Bt(_d,{}),Bt(Pd,{})]})]}),Bt(gd,{})]})}var Od={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 zd(){const e=Ut();return Ct("div",{css:Od,children:[Bt(za,{size:26,color:e.color.primary,label:"Validating token"}),Bt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),Bt("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 Pd(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=Tn(),n=Ut();return null==e?null:Bt(As,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:Bt("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:Bt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var Rd={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},jd={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function Kd({children:e}){const{fullscreenSlotRef:t}=Sn();return Ct("div",{css:jd,children:[e,Bt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:Rd})]})}class Vd extends u.Component{constructor(){super(...arguments),i(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const Gd=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-BOh3ubDn.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function qd(){if(!Gd)return!1;try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(Gd)}catch{return!1}}function Wd(e,t){return!(!Gd||!qd()||!(e&&e.startsWith(Gd)||t&&-1!==t.indexOf(Gd)))}const Jd=Wd;let $d=null;const Xd="data-mfm-mount";function Yd(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function Zd(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{yn.init(),yn.setClientType(e);const t=gn().read("MFM_TOKEN");t&&yn.setToken(t)}catch{}}(t.clientType);const o=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],i=e=>e.stopPropagation();for(const e of o){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,i,{passive:t})}const r=n.shadowRoot??n.attachShadow({mode:"open"});let s=r.querySelector(`[${Xd}]`);s||(s=document.createElement("div"),s.setAttribute(Xd,""),r.appendChild(s));const a=Ue({key:"mfm",container:r,prepend:!0}),l={run:()=>{}},A=S.createRoot(s);A.render(u.createElement(u.StrictMode,null,u.createElement(ot,{value:a},u.createElement(Vd,{onError:e=>{setTimeout(()=>l.run(e),0)}},u.createElement(Ld,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;Jd(e.filename,t?.stack)&&(e.preventDefault(),l.run(e.error))},d=e=>{const t=e.reason,n=t?.stack??(t?String(t):void 0);Jd(void 0,n)&&(e.preventDefault(),l.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const p=console.error;console.error=function(...e){if(Gd&&qd())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(Gd))return}p.apply(console,e)};let f=!1,h=null;const g=e=>{if(!f){if(f=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==p)try{console.error=p}catch{}try{A.unmount()}catch{}try{n.remove()}catch{}$d=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:"";Ci("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 yn.track("widget_destroyed");Ei()}catch{}if(void 0!==e)try{h=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 i=document.createElement("div");i.textContent="MockForMe is unable to load.",i.style.cssText="font-weight: 500";const r=document.createElement("div");r.textContent="The issue has been reported.",r.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),o.appendChild(i),o.appendChild(r);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 l=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",l),n.appendChild(o),n.appendChild(s),t.appendChild(n),{dismiss:l}}()}catch{}}};return l.run=g,{destroy(){if(g(),h){try{h.dismiss()}catch{}h=null}}}}const eu={run(e,t={}){if($d)return $d;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const o=()=>{if(n)return;const o=Yd(e);o&&($d=Zd(o,t))};return document.addEventListener("DOMContentLoaded",o,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",o),$d&&$d.destroy()}}}const n=Yd(e);return n?($d=Zd(n,t),$d):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=eu),n.d(t,["M",0,eu])},435(e,t,n){n.d(t,{MockForMeWidget:()=>o.M});var o=n(158)}};const t={};function n(o){const i=t[o];if(void 0!==i)return i.exports;const r=t[o]={exports:{}};return e[o](r,r.exports,n),r.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var o=0;o<t.length;){var i=t[o++],r=t[o++];n.o(e,i)?0===r&&o++:0===r?Object.defineProperty(e,i,{enumerable:!0,value:t[o++]}):Object.defineProperty(e,i,{enumerable:!0,get:r})}else for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},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.r(o),n.d(o,{mockforme:()=>et});const i=()=>"undefined"!=typeof process&&null!=process.versions?.node,r=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,l=/\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/i,A=/^\s*(?:#[^\n]*\n\s*)*\b(query|mutation|subscription)\b/i;function c(e){if(null==e)return null;if("object"==typeof e)return e;if("string"==typeof e){const t=e.trim();if(!t||"{"!==t[0])return null;try{return JSON.parse(t)}catch{return null}}return null}const d="GRAPHQL",u=e=>e&&e.requestType===d;let p=[];function f(e){p=e}function h(){return p}function g(e,t="get",n=null){const o=e=>e.startsWith("/")?e:`/${e}`,i=o(e),f=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const o of n){if(r(o.apiMethod)!==r(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}(i,t);if(f)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${f.url}`),f;const h=function(e,t,n,o){if("post"!==r(t))return null;if(!p.some(u))return null;if(!function(e){const t=c(e);return!!(t&&"string"==typeof t.query&&t.query.trim().length>0)}(n))return null;const{operationName:i,operationType:a}=function(e){const t=c(e)||{},n="string"==typeof t.query?t.query:"";let o=t.operationName?String(t.operationName).trim():"";if(!o){const e=n.match(l);o=e?e[1]:""}let i="";if(o){const e=n.match(new RegExp(`\\b(query|mutation|subscription)\\s+${s=o,String(s).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"));e&&(i=r(e[1]))}var s;if(!i){const e=n.match(A);i=e?r(e[1]):"query"}return{operationName:o,operationType:i}}(n);if(!i)return null;for(const t of p){if(!u(t))continue;const n=o(t.apiEndpoint);if(n!==e&&!s(n,e))continue;if(t.graphqlOperationName!==i)continue;if(r(t.graphqlOperationType)!==r(a))continue;console.log(`[MockForMe] GraphQL Match Found: ${a} ${i} @ ${t.apiEndpoint}`);const l={url:n===e?e:t.apiEndpoint,method:t.apiMethod,apiEndpoint:t.apiEndpoint,_ack:t._ack||null,requestType:d,graphqlOperationName:i,graphqlOperationType:a};return t._ri_&&(l._ri_=t._ri_),l}return null}(i,t,n,o);if(h)return h;for(const n of p)if(!u(n)&&r(n.apiMethod)===r(t)){const r=o(n.apiEndpoint);if(r===i||s(r,i)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${n.apiEndpoint}`);const o={url:e,method:n.apiMethod,apiEndpoint:n.apiEndpoint,_ack:n._ack||null};return n._ri_&&(o._ri_=n._ri_),o}}return null}const m="JAVASCRIPT",y="mockforme",w="https://api.mockforme.com",k=`${w}/mockforme`,b=`${w}/gateway/3f4eae522b`;let v=null,x=null,B=null,C=[];function E({_o:e,mk:t,_mck:n,_rules:o}){v=e,x=t,B=n,C=o}function S(){return C}function F(){return`${k}/${v}/${x}`}function Q(){return B}function U(e,t,n,o){fetch(b,{method:"GET",headers:{[y]:e,mfmver:"15.4.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:i,_mck:r,mk:s,r:a}=e,l=function({di:e,iv:t},n){var o;const i=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(i)}({di:t,iv:o},i);E({_o:i,mk:s,_mck:r,_rules:a}),l&&(f(l),n(l,{_o:i,mk:s,_mck:r,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),o(e)})}const T="mfm_op_3f4eae522b",M=`${w}/mockforme/${T}/manage`,I=e=>({[y]:e,mfmver:"15.4.0","Content-Type":"application/json"}),_=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}},D=[T],L="MFM_INTERCEPTOR_RULES";let H=[];const N=new Map;function O(){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 z(e){H=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function P(e,t){if(!e||!t)return null;if(!H.length&&(H=O(),!H.length))return null;const n=String(e).toUpperCase();return H.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({requestId:e,ruleId:t,request:n,response:o,timeoutMs:i=3e5}){return new Promise(r=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),r({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body}))},i);N.set(e,{resolve:r,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),N.delete(e),r({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body})}})}H=O(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&z(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(H=O())});const j="MFM_REQUEST_EDITOR_RULES";let K=[];const V=new Map;function G(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(j);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function q(e){K=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function W(e,t){if(!e||!t)return null;if(!K.length&&(K=G(),!K.length))return null;const n=String(e).toUpperCase();return K.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 J(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 $({requestId:e,ruleId:t,request:n,queryParams:o,timeoutMs:i=3e5}){return new Promise(r=>{const s=setTimeout(()=>{V.has(e)&&(V.delete(e),r(J(e,n,o)))},i);V.set(e,{resolve:r,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),V.delete(e),r(J(e,n,o))}})}K=G(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&q(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===j&&(K=G())});const X="MFM_GLOBAL_DELAY";let Y={enabled:!1,seconds:0},Z=0;function ee(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(X);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 te(){const e=Date.now();return e-Z>500&&(Y=ee(),Z=e),Y.enabled&&Y.seconds>0?Math.round(1e3*Y.seconds):0}var ne,oe;function ie(){const e="undefined"!=typeof window?window:void 0;return e?(e.__MOCKFORME__||(e.__MOCKFORME__={adapters:[]}),e.__MOCKFORME__):null}function re(){const e=ie();return!!e&&new Set(e.adapters).size>1}function se(e){return`MockForMe detected more than one integration active on this page (${e.length?e.join(" + "):"multiple adapters"}). Or NPM Mocking is paused to avoid conflicts. Use only ONE: remove "import statement" and mockforme().run() from your app, OR disable the MockForMe Chrome extension on this host.`}Y=ee(),Z=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===X&&(Y=ee(),Z=Date.now())}),function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(ne||(ne={})),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_REQ_IMAGE_ANALYSIS="MFM_REQ_IMAGE_ANALYSIS",e.MFM_REQ_LOCATE_IMAGE="MFM_REQ_LOCATE_IMAGE",e.MFM_REQ_APPLY_IMAGE="MFM_REQ_APPLY_IMAGE",e.MFM_REQ_REVERT_IMAGE="MFM_REQ_REVERT_IMAGE",e.MFM_REQ_REVERT_ALL_IMAGES="MFM_REQ_REVERT_ALL_IMAGES",e.MFM_REQ_MEASURE_IMAGE="MFM_REQ_MEASURE_IMAGE",e.MFM_REQ_CLEAR_HIGHLIGHT="MFM_REQ_CLEAR_HIGHLIGHT",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_RES_IMAGE_ANALYSIS="MFM_RES_IMAGE_ANALYSIS",e.MFM_RES_IMAGE_ACTION="MFM_RES_IMAGE_ACTION",e.MFM_RES_MEASURE_IMAGE="MFM_RES_MEASURE_IMAGE",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_CONFLICT="MFM_CONFLICT",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",e.MFM_DEVICE_SIM_TOGGLE="MFM_DEVICE_SIM_TOGGLE",e.MFM_DEVICE_CATALOG_REQ="MFM_DEVICE_CATALOG_REQ",e.MFM_DEVICE_CATALOG_SET="MFM_DEVICE_CATALOG_SET",e.MFM_DEVICE_CREATE="MFM_DEVICE_CREATE",e.MFM_DEVICE_CREATE_CUSTOM="MFM_DEVICE_CREATE_CUSTOM",e.MFM_DEVICE_DESTROY="MFM_DEVICE_DESTROY",e.MFM_DEVICE_ROTATE="MFM_DEVICE_ROTATE",e.MFM_DEVICE_SET_UA="MFM_DEVICE_SET_UA",e.MFM_DEVICE_SIM_READY="MFM_DEVICE_SIM_READY",e.MFM_DEVICE_SIM_OFF="MFM_DEVICE_SIM_OFF",e.MFM_DEVICE_INSTANCES_SET="MFM_DEVICE_INSTANCES_SET",e.MFM_DEVICE_ERROR="MFM_DEVICE_ERROR",e.MFM_ANNOUNCEMENTS_SET="MFM_ANNOUNCEMENTS_SET",e.MFM_ANNOUNCEMENT_DISMISS="MFM_ANNOUNCEMENT_DISMISS"}(oe||(oe={}));const ae="Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",le="Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36",Ae="Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36",ce=(e,t,n,o,i,r)=>({id:e,name:t,category:"phone",platform:"ios",strategy:"iphone",viewport:{width:n,height:o},devicePixelRatio:i,orientation:"portrait",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",capabilities:{touch:!0},accessRule:{plan:"free"},frame:r,source:"built-in"}),de=(e,t,n,o,i,r="Mozilla/5.0 (Linux; Android 14; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36")=>({id:e,name:t,category:"phone",platform:"android",strategy:"android",viewport:{width:n,height:o},devicePixelRatio:i,orientation:"portrait",userAgent:r,capabilities:{touch:!0},accessRule:{plan:"free"},frame:"android-punch",source:"built-in"}),ue=(e,t,n,o,i,r,s)=>({id:e,name:t,category:"tablet",platform:r,strategy:"tablet",viewport:{width:n,height:o},devicePixelRatio:i,orientation:"portrait",userAgent:s,capabilities:{touch:!0},accessRule:{plan:"free"},frame:"ios"===r?"ios-tablet":"android-tablet",source:"built-in"});function pe(e,t=1){if(!Number.isFinite(e)||e<=0)return"0 B";const n=["B","KB","MB","GB","TB"],o=Math.min(n.length-1,Math.floor(Math.log(e)/Math.log(1024))),i=0===o?0:t;return`${(e/Math.pow(1024,o)).toFixed(i)} ${n[o]}`}function fe(e,t,n=0){return!t||t<=0?0:he(e/t*100,n)}function he(e,t=0){if(!Number.isFinite(e))return 0;const n=Math.pow(10,t);return Math.round(e*n)/n}function ge(e,t){const n=function(e){if(!e)return"";switch(e.toLowerCase().split(";")[0].trim()){case"image/jpeg":case"image/jpg":return"JPEG";case"image/png":return"PNG";case"image/webp":return"WebP";case"image/avif":return"AVIF";case"image/gif":return"GIF";case"image/svg+xml":return"SVG";case"image/bmp":return"BMP";case"image/tiff":return"TIFF";default:return""}}(t);return n||function(e){switch(function(e){try{const t=e.split(/[?#]/)[0],n=t.lastIndexOf("."),o=t.lastIndexOf("/");return-1===n||n<o?"":t.slice(n).toLowerCase()}catch{return""}}(e)){case".jpg":case".jpeg":return"JPEG";case".png":return"PNG";case".webp":return"WebP";case".avif":return"AVIF";case".gif":return"GIF";case".svg":return"SVG";case".bmp":return"BMP";case".tiff":case".tif":return"TIFF";default:return"—"}}(e)}ce("iphone-se","iPhone SE",375,667,2,"ios-home"),ce("iphone-x","iPhone X",375,812,3,"ios-notch"),ce("iphone-xr","iPhone XR",414,896,2,"ios-notch"),ce("iphone-11","iPhone 11",414,896,2,"ios-notch"),ce("iphone-11-pro","iPhone 11 Pro",375,812,3,"ios-notch"),ce("iphone-12-mini","iPhone 12 mini",360,780,3,"ios-notch"),ce("iphone-12","iPhone 12",390,844,3,"ios-notch"),ce("iphone-12-pro-max","iPhone 12 Pro Max",428,926,3,"ios-notch"),ce("iphone-13","iPhone 13",390,844,3,"ios-notch"),ce("iphone-13-pro","iPhone 13 Pro",390,844,3,"ios-notch"),ce("iphone-14","iPhone 14",390,844,3,"ios-notch"),ce("iphone-14-plus","iPhone 14 Plus",428,926,3,"ios-notch"),ce("iphone-14-pro","iPhone 14 Pro",393,852,3,"ios-island"),ce("iphone-14-pro-max","iPhone 14 Pro Max",430,932,3,"ios-island"),ce("iphone-15","iPhone 15",393,852,3,"ios-island"),ce("iphone-15-pro","iPhone 15 Pro",393,852,3,"ios-island"),ce("iphone-15-pro-max","iPhone 15 Pro Max",430,932,3,"ios-island"),ce("iphone-16","iPhone 16",393,852,3,"ios-island"),ce("iphone-16-pro","iPhone 16 Pro",402,874,3,"ios-island"),ce("iphone-16-pro-max","iPhone 16 Pro Max",440,956,3,"ios-island"),de("pixel-5","Pixel 5",393,851,3),de("pixel-6-pro","Pixel 6 Pro",412,892,3),de("pixel-7","Pixel 7",412,915,3,le),de("pixel-8","Pixel 8",412,915,3,le),de("pixel-8-pro","Pixel 8 Pro",448,998,3,le),de("galaxy-s20","Galaxy S20",360,800,3,Ae),de("galaxy-s21-ultra","Galaxy S21 Ultra",384,854,3,Ae),de("galaxy-s22","Galaxy S22",360,780,3,Ae),de("galaxy-s23","Galaxy S23",360,780,3,Ae),de("galaxy-s24-ultra","Galaxy S24 Ultra",384,832,3,Ae),de("oneplus-nord-2","OnePlus Nord 2",412,915,3),de("xiaomi-12","Xiaomi 12",390,844,3),ue("ipad-mini","iPad mini",768,1024,2,"ios",ae),ue("ipad-air","iPad Air",820,1180,2,"ios",ae),ue("ipad-pro-11",'iPad Pro 11"',834,1194,2,"ios",ae),ue("galaxy-tab-s7","Galaxy Tab S7",800,1280,2,"android","Mozilla/5.0 (Linux; Android 14; SM-X700) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");const me=new Set(["JPEG","PNG","BMP","TIFF"]);function ye(e,t){const n=ge(e,t);return"—"!==n&&me.has(n)}function we(e,t){const n=function(e){try{const t=e.split(/[?#]/)[0];return t.slice(t.lastIndexOf("/")+1)||e}catch{return e}}(e)||"image.jpg",o=n.lastIndexOf("."),i=o>0?n.slice(0,o):n,r=o>0?n.slice(o):".jpg",s=Math.max(1,Math.round(t||600)),a=2*s;return["<img",` src="${i}-${s}${r}"`,` srcset="${i}-${s}${r} ${s}w, ${i}-${a}${r} ${a}w"`,` sizes="(max-width: ${s}px) 100vw, ${s}px"`,' alt="…"',' loading="lazy" />'].join("\n")}const ke={monthlyPageViews:1e5,avgImagesPerPage:0,costPerGb:.1};function be(e){return e.transferSize>0?e.transferSize:e.encodedBodySize>0?e.encodedBodySize:e.contentLength&&e.contentLength>0?e.contentLength:0}function ve(e){return e.transferSize<=0&&e.encodedBodySize<=0&&!(e.contentLength&&e.contentLength>0)}function xe(e,t){return e*Math.min(Math.max(t||1,1),2)}function Be(e,t){return!(e.displayedWidth<24||e.displayedHeight<24)&&!(!e.naturalWidth||!e.naturalHeight)&&e.naturalWidth>1.15*xe(e.displayedWidth,t)}function Ce(e,t){if(!Be(e,t))return 1;const n=xe(e.displayedWidth,t)*xe(e.displayedHeight,t),o=e.naturalWidth*e.naturalHeight;return o<=0?1:Math.min(1,n/o)}function Ee(e,t,n,o,i){if(e<=0)return{mid:0,low:0,high:0};const r=t?e*Ce(t,o):e;return ye(n,i)?{mid:.65*r,low:.55*r,high:.75*r}:{mid:r,low:r,high:r}}function Se(e){return e>=1048576?"HIGH":e>=204800?"MEDIUM":"LOW"}const Fe={HIGH:0,MEDIUM:1,LOW:2};new class{constructor(){this.kind="image"}analyze(e,t=ke){const n=e&&e.devicePixelRatio>0?e.devicePixelRatio:1;if(!e||e.unsupported)return this.emptyResult(!1,t);const o=function(e){const t=new Set,n=[];for(const o of e)o&&o.url&&!t.has(o.url)&&(t.add(o.url),n.push(o));return n}(e.resources||[]),i=new Map;for(const t of e.images||[])t.url&&!i.has(t.url)&&i.set(t.url,t);if(0===o.length&&0===i.size)return this.emptyResult(!0,t);let r=0,s=0,a=0,l=0,A=0,c=0,d=0,u=0,p=0;const f=[];for(const e of o){const t=be(e),o=i.get(e.url);ve(e)?s+=1:(r+=t,e.transferSize<=0&&e.encodedBodySize>0&&(a+=1),t>l&&(l=t));const h=Ee(t,o,e.url,n,e.contentType);A+=h.mid,c+=h.low,d+=h.high,ye(e.url,e.contentType)&&t>0&&(u+=1,p+=.35*(o?t*Ce(o,n):t)),f.push({url:e.url,bytes:t,saving:Math.max(0,t-h.mid),img:o})}let h=0,g=0,m=0;for(const e of i.values()){Be(e,n)&&(h+=1);const t=(f.find(t=>t.url===e.url)?.bytes||0)>204800||Be(e,n);!e.hasSrcset&&t&&(g+=1),e.inViewport||"lazy"===e.loading||(m+=1)}const y=o.length||i.size,w=this.buildDetails(o,i,n),k=this.buildRecommendations(f,n,w,{legacyFormatCount:u,legacyFormatSaving:p,missingResponsiveCount:g,lazyCandidateCount:m}),b=e.nav?.loadEvent||e.nav?.domContentLoaded||o.reduce((e,t)=>Math.max(e,t.responseEnd),0),v=function(e,t){const n=e.filter(e=>e.startTime>=0&&e.startTime<t),o=n.reduce((e,t)=>e+be(t),0),i=n.filter(e=>be(e)>204800).length;return n.length>=6&&o>=1048576?{concurrentInCriticalWindow:n.length,bytesInCriticalWindow:Math.round(o),criticalWindowEndMs:Math.round(t),largeNonCriticalCount:i}:null}(o,b);v&&k.push(this.contentionRecommendation(v)),k.sort((e,t)=>Fe[e.priority]-Fe[t.priority]||t.estimatedSavingBytes-e.estimatedSavingBytes);const x=Math.max(0,Math.round(A)),B=Math.max(0,r-x);return{supported:!0,empty:!1,current:{imageCount:y,totalBytes:Math.round(r),unknownByteCount:s,cachedCount:a,largestBytes:Math.round(l),oversizedCount:h,legacyFormatCount:u,missingResponsiveCount:g,lazyCandidateCount:m},optimised:{estimatedBytes:x,estimatedBytesLow:Math.max(0,Math.round(c)),estimatedBytesHigh:Math.max(0,Math.round(d)),estimatedSavedBytes:B,estimatedSavedPct:fe(B,r)},recommendations:k,imageDetails:w,cost:this.estimateCost(r,x,y,t),loading:this.analyzeLoading(e,f),contention:v}}buildDetails(e,t,n){const o=new Map(e.map(e=>[e.url,e])),i=new Set;e.forEach(e=>i.add(e.url)),t.forEach((e,t)=>i.add(t));const r=[];for(const e of i){const i=o.get(e),s=t.get(e),a=i?be(i):0,l=i?.contentType,A=Ee(a,s,e,n,l),c=!(!s||!Be(s,n)),d=ye(e,l),u=a>204800||c,p=!(!s||s.hasSrcset||!u),f=!(!s||s.inViewport||"lazy"===s.loading),h=[];c&&h.push("oversized"),d&&h.push("legacy-format"),p&&h.push("missing-responsive"),f&&h.push("lazy-candidate");const g=h.length>0,m=(s?Ce(s,n):1)*(d?.65:1),y=Math.max(0,Math.min(1,1-m)),w=s?c?Math.round(xe(s.displayedWidth,n)):s.naturalWidth:0,k=s?c?Math.round(xe(s.displayedHeight,n)):s.naturalHeight:0;r.push({url:e,domIndex:s?s.index:-1,bytes:Math.round(a),estimatedBytes:g?Math.round(A.mid):Math.round(a),savingBytes:g?Math.max(0,Math.round(a-A.mid)):0,savingPct:g?y:0,currentFormat:ge(e,l),contentType:l,suggestedFormat:d?"WebP / AVIF":null,naturalWidth:s?.naturalWidth||0,naturalHeight:s?.naturalHeight||0,displayedWidth:s?.displayedWidth||0,displayedHeight:s?.displayedHeight||0,suggestedWidth:w,suggestedHeight:k,issues:h,hasSrcset:!!s?.hasSrcset,srcsetExample:p&&s?we(e,s.displayedWidth):null})}return r.sort((e,t)=>{const n=e.issues.length>0?1:0,o=t.issues.length>0?1:0;return n!==o?o-n:t.savingBytes-e.savingBytes||t.bytes-e.bytes}),r}buildRecommendations(e,t,n,o){const i=[],r=e=>n.filter(t=>t.issues.includes(e)),s=e.filter(e=>e.img&&Be(e.img,t)&&e.saving>=20480).sort((e,t)=>t.saving-e.saving).slice(0,5);for(const e of s){const t=e.img;i.push({id:`oversized:${e.url}`,priority:Se(e.saving),issueType:"oversized",title:`Oversized image — ${pe(e.bytes)}`,why:"A much larger image than needed is downloaded, wasting bytes and delaying paint.",currentValue:`Downloaded ${t.naturalWidth}×${t.naturalHeight}, shown ${t.displayedWidth}×${t.displayedHeight}`,recommendedAction:"Serve a responsive, appropriately-sized image (srcset/sizes).",estimatedSavingBytes:Math.round(e.saving),affectedCount:1,details:n.filter(t=>t.url===e.url)})}return o.legacyFormatCount>0&&i.push({id:"legacy-format",priority:Se(o.legacyFormatSaving),issueType:"legacy-format",title:`${o.legacyFormatCount} image${o.legacyFormatCount>1?"s":""} use JPEG/PNG`,why:"Modern formats cut bytes at equal quality.",currentValue:"Legacy raster formats (JPEG/PNG).",recommendedAction:"Serve WebP/AVIF where the browser supports it.",estimatedSavingBytes:Math.round(o.legacyFormatSaving),affectedCount:o.legacyFormatCount,details:r("legacy-format")}),o.missingResponsiveCount>0&&i.push({id:"missing-responsive",priority:"MEDIUM",issueType:"missing-responsive",title:`${o.missingResponsiveCount} image${o.missingResponsiveCount>1?"s":""} missing responsive loading`,why:"Without srcset/sizes every device downloads the same large file.",currentValue:"No srcset/sizes on large images.",recommendedAction:"Add srcset + sizes so browsers pick the right resolution.",estimatedSavingBytes:0,affectedCount:o.missingResponsiveCount,details:r("missing-responsive")}),o.lazyCandidateCount>0&&i.push({id:"lazy-candidate",priority:"LOW",issueType:"lazy-candidate",title:`${o.lazyCandidateCount} below-the-fold image${o.lazyCandidateCount>1?"s":""} could lazy-load`,why:"Off-screen images loaded eagerly compete with critical content.",currentValue:"Below-the-fold images load eagerly.",recommendedAction:'Add loading="lazy" to off-screen images.',estimatedSavingBytes:0,affectedCount:o.lazyCandidateCount,details:r("lazy-candidate")}),i}contentionRecommendation(e){return{id:"contention",priority:e.largeNonCriticalCount>0?"HIGH":"MEDIUM",issueType:"contention",title:`${e.concurrentInCriticalWindow} images loaded during initial page load`,why:"Many concurrent image downloads can starve critical CSS/JS/fonts of bandwidth.",currentValue:`${pe(e.bytesInCriticalWindow)} requested in the critical window`,recommendedAction:"Prioritise critical assets and defer/lazy-load non-critical images.",estimatedSavingBytes:0,affectedCount:e.concurrentInCriticalWindow,details:[]}}estimateCost(e,t,n,o){const i=o.avgImagesPerPage>0?o.avgImagesPerPage:n,r=(n>0?e/n:0)*i,s=r*(e>0?t/e:1),a=r*o.monthlyPageViews/1e9,l=s*o.monthlyPageViews/1e9,A=Math.max(0,a-l);return{assumptions:{...o,avgImagesPerPage:i},currentGbPerMonth:he(a,1),optimisedGbPerMonth:he(l,1),savedGbPerMonth:he(A,1),savedCostPerMonth:he(A*o.costPerGb,2)}}analyzeLoading(e,t){const n=e.nav||{},o=n.lcpUrl,i=o?t.find(e=>e.url===o):void 0,r=!!i;let s;if(i&&i.bytes>0&&i.saving>0){const t=(e.resources||[]).find(e=>e.url===i.url),n=(t?Math.max(0,t.responseEnd-t.startTime):0)*(i.saving/i.bytes);n>=1&&(s=Math.round(n))}return{domContentLoadedMs:n.domContentLoaded||void 0,loadEventMs:n.loadEvent||void 0,lcpMs:n.lcp||void 0,lcpIsImage:r,estimatedLcpGainMs:s}}emptyResult(e,t){return{supported:e,empty:e,current:{imageCount:0,totalBytes:0,unknownByteCount:0,cachedCount:0,largestBytes:0,oversizedCount:0,legacyFormatCount:0,missingResponsiveCount:0,lazyCandidateCount:0},optimised:{estimatedBytes:0,estimatedBytesLow:0,estimatedBytesHigh:0,estimatedSavedBytes:0,estimatedSavedPct:0},recommendations:[],imageDetails:[],cost:{assumptions:t,currentGbPerMonth:0,optimisedGbPerMonth:0,savedGbPerMonth:0,savedCostPerMonth:0},loading:{lcpIsImage:!1},contention:null}}};const Qe=/\.(jpe?g|png|gif|webp|avif|svg|bmp|tiff?)(\?|#|$)/i;const Ue=120,Te=8,Me=2500;function Ie(e){return e.transferSize<=0&&e.encodedBodySize<=0}async function _e(e){const t="undefined"!=typeof AbortController?new AbortController:null,n=t?setTimeout(()=>t.abort(),Me):null;try{const n=await fetch(e,{method:"HEAD",cache:"force-cache",signal:t?t.signal:void 0});if(!n.ok)return;const o=(n.headers.get("content-type")||"").split(";")[0].trim().toLowerCase(),i=Number(n.headers.get("content-length")||""),r={};return o.startsWith("image/")&&(r.contentType=o),Number.isFinite(i)&&i>0&&(r.bytes=i),r.contentType||r.bytes?r:void 0}catch{return}finally{n&&clearTimeout(n)}}function De(e){return"number"==typeof e&&Number.isFinite(e)?e:0}const Le="MFM_TOKEN",He="MFM_CACHED_MAPPINGS",Ne="MFM_INTERCEPTION_ENABLED",Oe="MFM_ANNOUNCEMENT_NEXT_CHECK",ze="MFM_ANNOUNCEMENT_CACHE",Pe=new class{constructor(e={}){i()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Le):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(Ne);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Ne,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var o,i;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case oe.MFM_REQ_MAPPINGS:this.refreshMappings(),this.syncInterceptionToggleToWidget(),this.syncAnnouncementsToWidget();break;case oe.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings(),this.syncInterceptionToggleToWidget(),this.syncAnnouncementsToWidget();break;case oe.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case oe.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case oe.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case oe.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case oe.MFM_REQ_IMAGE_ANALYSIS:this.handleReqImageAnalysis();break;case oe.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case oe.MFM_DEBUG_RULES_UPDATE:z(n?.rules||[]);break;case oe.MFM_DEBUG_INTERCEPT_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 oe.MFM_REQUEST_EDIT_RULES_UPDATE:q(n?.rules||[]);break;case oe.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=V.get(e.requestId);t&&(clearTimeout(t.timer),V.delete(e.requestId),t.resolve(e))}(n);break;case oe.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return Y={enabled:!1,seconds:0},void(Z=Date.now());Y={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},Z=Date.now()}(n);break;case oe.MFM_FLOW_MOCK_SET:o=n?.runId,i=n?.apis||[],o&&a.set(String(o),Array.isArray(i)?i:[]);break;case oe.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId);break;case oe.MFM_ANNOUNCEMENT_DISMISS:this.handleAnnouncementDismiss(n?.id)}})}getCachedAnnouncements(){if("undefined"==typeof localStorage)return[];try{const e=localStorage.getItem(ze),t=e?JSON.parse(e):[];return Array.isArray(t)?t:[]}catch(e){return[]}}setCachedAnnouncements(e){if("undefined"!=typeof localStorage)try{localStorage.setItem(ze,JSON.stringify(e||[]))}catch(e){}}syncAnnouncementsToWidget(){if(!this.token)return;const e=this.getCachedAnnouncements();e.length&&this.sendMessage(oe.MFM_ANNOUNCEMENTS_SET,{announcements:e}),this.maybeFetchAnnouncements()}maybeFetchAnnouncements(){if(!this.token||"undefined"==typeof localStorage)return;const e=Date.now(),t=parseInt(localStorage.getItem(Oe)||"0",10);t&&e<t||(localStorage.setItem(Oe,String(e+9e5)),(async e=>{if(!e)return{ok:!1,message:"Missing token",result:{announcements:[]}};const t=`${M}/announcements?surface=DEVTOOL&version=${encodeURIComponent("15.4.0")}`,n=await fetch(t,{method:"GET",headers:I(e)});return _(n)})(this.token).then(e=>{if(!e||!e.ok)return;const t=e.result&&e.result.announcements||[];this.setCachedAnnouncements(t),this.sendMessage(oe.MFM_ANNOUNCEMENTS_SET,{announcements:t})}).catch(()=>{}))}handleAnnouncementDismiss(e){e&&(this.setCachedAnnouncements(this.getCachedAnnouncements().filter(t=>t&&t.id!==e)),this.token&&(async(e,t)=>{if(!e||!t)return{ok:!1,message:"Missing token or id",result:null};const n=await fetch(`${M}/announcements/${t}/dismiss`,{method:"POST",headers:I(e)});return _(n)})(this.token,e).catch(()=>{}))}init(){if("undefined"!=typeof document&&this.checkVisibility()&&("undefined"!=typeof window&&Promise.resolve().then(n.bind(n,435)).then(e=>{const t=window.MockForMeWidget||e.MockForMeWidget;t&&"function"==typeof t.run&&(t.run(null,{clientType:"NPM",version:"15.4.0"}),this.syncInterceptionToggleToWidget(),this.maybeAnnounceConflict())}).catch(e=>{console.error("[MockForMe] Failed to load mfm-widget",e)}),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(Le,e),localStorage.removeItem(Oe),localStorage.removeItem(ze)),this.refreshMappings(),this.syncAnnouncementsToWidget())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Le),localStorage.removeItem(He),localStorage.removeItem(Oe),localStorage.removeItem(ze)),this.sendMessage(oe.MFM_ANNOUNCEMENTS_SET,{announcements:[]}),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(`${M}/apis`,{method:"GET",headers:I(e)});return _(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage(oe.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage(oe.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage(oe.MFM_RES_ALL_APIS,{apis:[]})}handleReqImageAnalysis(){Promise.resolve().then(()=>async function(e={},t){if("undefined"==typeof performance||"undefined"==typeof document||"function"!=typeof performance.getEntriesByType)return{resources:[],images:[],nav:{domContentLoaded:0,loadEvent:0},devicePixelRatio:1,viewportWidth:0,viewportHeight:0,collectedAt:Date.now(),unsupported:!0};const n="undefined"!=typeof window&&window.innerWidth||document.documentElement.clientWidth||0,o="undefined"!=typeof window&&window.innerHeight||document.documentElement.clientHeight||0,i="undefined"!=typeof window&&window.devicePixelRatio||1,r=function(){const e=[];let t=[];try{t=performance.getEntriesByType("resource")}catch{return e}for(const n of t){if(e.length>=600)break;const t=n,o=t.initiatorType,i="img"===o,r="css"===o&&Qe.test(t.name);(i||r)&&e.push({url:t.name,initiatorType:o,transferSize:De(t.transferSize),encodedBodySize:De(t.encodedBodySize),decodedBodySize:De(t.decodedBodySize),fromCache:0===De(t.transferSize)&&De(t.encodedBodySize)>0,responseEnd:Math.round(De(t.responseEnd)),startTime:Math.round(De(t.startTime))})}return e}(),s=function(e,t){const n=[];let o=[];try{o=Array.prototype.slice.call(document.images||document.querySelectorAll("img"))}catch{return n}for(let i=0;i<o.length;i++){const r=o[i];if(n.length>=600)break;let s={width:0,height:0,top:0,bottom:0,left:0,right:0};try{s=r.getBoundingClientRect()}catch{}const a=r.currentSrc||r.src||"";if(!a)continue;const l=s.top<t&&s.bottom>0&&s.left<e&&s.right>0;n.push({index:i,url:a,naturalWidth:De(r.naturalWidth),naturalHeight:De(r.naturalHeight),displayedWidth:Math.round(s.width),displayedHeight:Math.round(s.height),hasSrcset:!!(r.getAttribute("srcset")||"").trim(),hasSizes:!!(r.getAttribute("sizes")||"").trim(),loading:r.getAttribute("loading")||"",inViewport:l})}return n}(n,o),a=function(){const e={domContentLoaded:0,loadEvent:0};try{const[t]=performance.getEntriesByType("navigation");t&&(e.domContentLoaded=Math.round(De(t.domContentLoadedEventEnd)),e.loadEvent=Math.round(De(t.loadEventEnd)))}catch{}try{const t=performance.getEntriesByType("largest-contentful-paint"),n=t[t.length-1];n&&(e.lcp=Math.round(De(n.renderTime||n.loadTime||n.startTime)),n.url&&(e.lcpUrl=n.url))}catch{}return e}();for(const t of r){const n=e[t.url];n&&(t.contentType=n)}const l=function(e,t){const n=[],o=[],i=new Set;for(const r of e){if(i.has(r.url))continue;const e=!r.contentType,s=Ie(r);(e||s)&&/^https?:/i.test(r.url)&&(i.add(r.url),(t.has(r.url)?n:o).push(r.url))}return n.concat(o).slice(0,Ue)}(r,new Set(s.map(e=>e.url)));if(l.length>0){let e={};try{e=await(t?t(l):async function(e){const t={};if("function"!=typeof fetch)return t;let n=0;const o=async()=>{for(;n<e.length;){const o=e[n++],i=await _e(o);i&&(t[o]=i)}},i=[];for(let t=0;t<Math.min(Te,e.length);t++)i.push(o());return await Promise.all(i),t}(l))}catch{e={}}for(const t of r){const n=e[t.url];n&&(n.contentType&&!t.contentType&&(t.contentType=n.contentType),"number"==typeof n.bytes&&n.bytes>0&&Ie(t)&&(t.contentLength=n.bytes))}}return{resources:r,images:s,nav:a,devicePixelRatio:i,viewportWidth:n,viewportHeight:o,collectedAt:Date.now()}}()).then(e=>this.sendMessage(oe.MFM_RES_IMAGE_ANALYSIS,e)).catch(()=>{this.sendMessage(oe.MFM_RES_IMAGE_ANALYSIS,{resources:[],images:[],nav:{domContentLoaded:0,loadEvent:0},devicePixelRatio:1,viewportWidth:0,viewportHeight:0,collectedAt:Date.now(),unsupported:!0})})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const o=await fetch(`${M}/api/${t}/toggle-state`,{method:"PUT",headers:I(e),body:JSON.stringify({enabled:!!n})});return _(o)})(this.token,e,t).then(n=>{this.sendMessage(oe.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage(oe.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage(oe.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&U(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(Le),localStorage.removeItem(He)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage(oe.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage(oe.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(He,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(He);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(oe.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage(oe.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||{},i=o.activeAction||"MODIFY";let r="MODIFY";"delay"===i?r="DELAY":"delay_and_timeout"===i?r="TIMEOUT":"delay_and_redirect"===i&&(r="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:r,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==r||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=p.length,o=r(e||"");return p=p.filter(e=>!(r(e.apiMethod)===o&&e.apiEndpoint===t)),p.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 i=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage(oe.MFM_MOCK_DISABLED,{method:e,url:t,message:`${i} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;if((e=>{if(!e)return!1;const t=String(e);return D.some(e=>e&&t.includes(e))})(t&&t.url))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,i,r;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,i=String(t.status))}t.aborted||"Aborted"===t.status?r="aborted":t.timeout||"Timeout"===t.status?r="timeout":"Cancelled"===t.status?r="cancelled":(t.error||"Error"===i)&&(r="error");const s=t.pending&&void 0===t.status?null:{statusCode:o,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...i?{statusText:i}:{},...r?{errorReason:r,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,..."GRAPHQL"===t.requestType?{requestType:"GRAPHQL",graphqlOperationName:t.graphqlOperationName,graphqlOperationType:t.graphqlOperationType}:{}},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage(oe.MFM_REQ,a);else if(this.sendMessage(oe.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(oe.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}maybeAnnounceConflict(){try{if(!re())return;const e=function(){const e=ie();return e?e.adapters.slice():[]}();this.sendMessage(oe.MFM_CONFLICT,{adapters:e,message:se(e)}),console.warn("[MockForMe] "+se(e))}catch{}}};function Re(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 je{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:o,queryParams:i,body:r}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:l,operator:A,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(i&&void 0!==i[l])t=String(i[l]);else try{t=new URL(n,s).searchParams.get(l)||""}catch{t=""}break;case"REQUEST_BODY":if(l){if("object"==typeof r&&null!==r)t=void 0!==r[l]?String(r[l]):"";else if("string"==typeof r)try{const e=JSON.parse(r);t=void 0!==e[l]?String(e[l]):""}catch{t=""}}else t="object"==typeof r?JSON.stringify(r):String(r||"");break;case"REQUEST_HEADER":if(l){const e=l?.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,A,c))return!1}return!0}static evaluate(e,t,n){const o=t?.toLowerCase(),i=String(e),r=String(n);switch(o){case"contains":return i.includes(r);case"equal":case"equals":return i===r;case"regexp":try{let e=r;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(i)}return new RegExp(e).test(i)}catch{return!1}default:return!1}}}class Ke{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 i={type:"passThrough",delay:0},r=Number(o.value||0);switch(t){case"delay":i.delay=r,i.delay>0&&await new Promise(e=>setTimeout(e,1e3*i.delay));break;case"redirect":case"delay_and_redirect":i.type="redirect",i.delay=r,i.redirectUrl=o.redirectUrl,i.delay>0&&await new Promise(e=>setTimeout(e,1e3*i.delay));break;case"delay_and_timeout":i.type="timeout",i.delay=r,i.delay>0&&await new Promise(e=>setTimeout(e,1e3*i.delay))}return i}}class Ve{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:o,headers:i,queryParams:r,body:s}={...e};i&&(i={...i}),r&&(r={...r});const{modifyQueryParams:a,modifyRequestBody:l,modifyRequestHeaders:A}=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),r&&delete r[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),r&&(r[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}A?.enabled&&(i={...i},Array.isArray(A.remove)&&A.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(i).find(e=>e.toLowerCase()===t);n&&delete i[n]}),Array.isArray(A.add)&&A.add.forEach(({key:e,value:t})=>{i[e]=t}));const c=String(o||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(l?.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(l.add)&&l.add.length>0||Array.isArray(l.update)&&l.update.length>0)&&(e={});e&&(Array.isArray(l.remove)&&l.remove.forEach(t=>delete e[t]),Array.isArray(l.add)&&l.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(l.update)&&l.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:i,queryParams:r,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 Ge{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)&&je.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=Ve.applyRequestModifications(t,n.modificationActions);return{...await Ke.apply(n.timingAction),modifiedRequest:o,rule:n}}static applyResponseModifications(e,t){return Ve.applyResponseModifications(e,t)}}class qe{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:i=e=>{},onRuleMatch:r=async(e,t,n,o,i)=>null,onMockMatch:s=async(e,t,n,o,i)=>null,onOtherRequest:a=async(e,t,n,o)=>null,isEnabled:l=()=>!0,shouldBypassRequest:A=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!l())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(),r=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:r,queryParams:qe.getQueryParams(n)},e instanceof Request&&null==c.body&&"GET"!==o&&"HEAD"!==o)try{d.body=await e.clone().text()}catch{}if(A(d))return t(e,c);i(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const i=n(),l=Ge.match(d,i);if(l){const n=await r(l,d,e,c,t);if(n)return n}const A=o(d);if(A){const n=await s(A,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 We{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:i=e=>{},onRuleMatch:r=(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:l=()=>!0,shouldBypassRequest:A=()=>!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 i=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}),i("readystatechange"),"Aborted"===e||o.aborted?i("abort"):0===e||"Error"===e||o.error?i("error"):"Timeout"===e||o.timeout?i("timeout"):i("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,o=null,i=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,i)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!l())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:We.getQueryParams(this._url)};if(A(t))return this._xhr.send(e);i(t);const c=n(),d=Ge.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,r(d,t,this,u);const p=o(t);return p?(this._isMocked=!0,s(p,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 Je=[b,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function $e(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Je.some(e=>{const o=new URL(e,t);return n.origin===o.origin&&n.pathname===o.pathname})}catch{return!1}}const Xe=(e,t=null,n=m)=>{if(i())return;let o="string"==typeof e?e:e?.token,r="object"==typeof e?e?.widgetKey:null;if(n===m)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),Pe.token=o,Pe.isAuthenticated=!0),!o&&Pe.token&&(o=Pe.token),Pe.onAuthSuccess=(e,t,n)=>{f(t),E(n),Pe.updateMappings(t,n)},r?Pe.setWidgetKey(r):Pe.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:l,_mck:A,_rules:c=[]}=t;return f(s),E({_o:a,mk:l,_mck:A,_rules:c}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}!function(e){const t=ie();t&&(t.adapters.includes(e)||t.adapters.push(e))}(t||"JAVASCRIPT"),Pe.maybeAnnounceConflict();const n=()=>Pe.token||e;qe.apply({isEnabled:()=>Pe.interceptionEnabled&&!re(),shouldBypassRequest:$e,ruleProvider:()=>S(),mappingProvider:e=>{try{return g(new URL(e.url,window.location.origin).pathname,e.method,e.body)}catch{return null}},onRuleMatch:async(e,t,n,o,i)=>{const r=t.requestId||Math.random().toString(36).substring(7),s=Date.now();Pe.addRequest("mocked",{...t,requestId:r,pending:!0,startTime:s,rule:e});const a=await Ge.apply(e,t),{modifiedRequest:l,type:A,delay:c,redirectUrl:d}=a;if("timeout"!==A&&Pe.addRequest("mocked",{...l,requestId:r,pending:!0,startTime:s,rule:e}),"timeout"===A){const t=Date.now()-s;throw Pe.addRequest("mocked",{...l,requestId:r,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===A&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===A?d:l.url,p={...o};l.headers&&(p.headers=l.headers),l.body&&(p.body=l.body);let f=null;if("redirect"===A){f=Math.random().toString(36).substring(7);const e={url:d,method:l.method,headers:p.headers||{},body:p.body,requestId:f,queryParams:qe.getQueryParams(d),requestHeaders:p.headers||{},requestBody:p.body,pending:!0,startTime:Date.now()};Pe.addRequest("mocked",e)}return i(u,p).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=Ge.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===A&&f){const t=e.clone(),o=t.headers.get("content-type")||"",i=Date.now()-s;try{let r;r=o.includes("application/json")?await t.json():await t.text(),Pe.addRequest("mocked",{url:d,method:l.method,requestId:f,status:e.status,pending:!1,duration:i,responseHeaders:n,responseBody:r,requestHeaders:p.headers||{},requestBody:p.body})}catch(t){Pe.addRequest("mocked",{url:d,method:l.method,requestId:f,status:e.status,pending:!1,duration:i,responseHeaders:n,requestHeaders:p.headers||{},requestBody:p.body})}}return Pe.addRequest("mocked",{...l,requestId:r,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(Pe.addRequest("mocked",{...l,requestId:r,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===A&&f&&Pe.addRequest("mocked",{url:d,method:l.method,requestId:f,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===A){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,o,i,r,s)=>{const a=o.requestId||Math.random().toString(36).substring(7),l=Date.now();e&&"GRAPHQL"===e.requestType&&(o.requestType="GRAPHQL",o.graphqlOperationName=e.graphqlOperationName,o.graphqlOperationType=e.graphqlOperationType),Pe.addRequest("mocked",{...o,requestId:a,pending:!0,startTime:l});const A=n(),c=new URL(o.url,window.location.origin).search;let d=`${F()}${e.url}${c}`,u={[y]:A,mfmver:"15.4.0","x-mfm-adaptor":t};const p=Q();p&&e._ack&&(u["x-mfm-key"]=`${p}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const f=i instanceof Request?i.headers:r.headers,h=new Headers(f||{});Object.entries(u).forEach(([e,t])=>h.set(e,t)),h.set("x-mfm-internal","true");let g=r.body;if(!g&&i instanceof Request){const e=i.clone();"GET"!==e.method&&"HEAD"!==e.method&&(g=await e.text())}const m={method:o.method,headers:h,credentials:i instanceof Request&&i.credentials||r.credentials||"include",mode:i instanceof Request&&i.mode||r.mode||"cors",signal:i instanceof Request&&i.signal||r.signal};return g&&(m.body=g),s(d,m).then(async t=>{const n=t.clone(),i=n.headers.get("content-type")||"",r=Date.now()-l;Re(t.headers)&&Pe.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(Pe.addRequest("mocked",{...o,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:r}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return i.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-l,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(Pe.addRequest("mocked",{...o,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(i,r)})},onOtherRequest:async(e,t,n,o)=>{const i=n?.headers||(t instanceof Request?t.headers:{});let r=!1;i instanceof Headers?r="true"===i.get("x-mfm-internal"):"object"==typeof i&&(r="true"===i["x-mfm-internal"]);const s=F();if(e.url.startsWith(s)&&(r=!0),"OPTIONS"===e.method||r)return o(t,n);const a=e.requestId,l=Date.now();Pe.addRequest("other",{...e,requestId:a,pending:!0,startTime:l});const A=W(e.method,e.url),c=P(e.method,e.url);let d=t,u=n,p=e;if(A){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 $({requestId:a,ruleId:A.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(o.cancel){Pe.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-l,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}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){}const r=String(e.method||"GET").toUpperCase(),s="GET"!==r&&"HEAD"!==r;u={...n,method:e.method,headers:o.headers||{},body:s?null==o.body?void 0:o.body:void 0},d=i,p={...e,url:i,headers:o.headers||{},body:s?o.body:null}}const f=te();f>0&&await new Promise(e=>setTimeout(e,f));let h=null,g=null;try{h=await o(d,u)}catch(e){g=e}if(c){let t="",n=0,o={};if(h){try{t=await h.clone().text()}catch(e){}n=h.status,o=Object.fromEntries(h.headers.entries())}else g&&(t=g.message||"Network error",n=0);const i=await R({requestId:a,ruleId:c.id,request:{method:p.method,url:p.url,headers:p.headers,body:p.body},response:{statusCode:n,headers:o,body:t}});if(i.simulateTimeout){Pe.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-l,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const r=Number(i.statusCode),s=Number.isFinite(r)&&r>=200&&r<=599?r:n>=200?n:200,A=i.headers&&"object"==typeof i.headers?i.headers:o,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);Pe.addRequest("other",{...e,requestId:a,status:s,responseHeaders:A,responseBody:d,pending:!1,duration:Date.now()-l});const u={};return Object.entries(A).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:h?h.statusText:"",headers:new Headers(u)})}const m=Date.now()-l;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw Pe.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(h.headers.entries());let w;try{const e=h.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 Pe.addRequest("other",{...e,requestId:a,status:h.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),h}}),We.apply({isEnabled:()=>Pe.interceptionEnabled&&!re(),shouldBypassRequest:$e,ruleProvider:()=>S(),mappingProvider:e=>{try{return g(new URL(e.url,window.location.origin).pathname,e.method,e.body)}catch{return null}},onRuleMatch:async(e,t,n,o)=>{const i=t.requestId,r=Date.now();Pe.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:r,rule:e});const s=await Ge.apply(e,t),{modifiedRequest:a,type:l,redirectUrl:A}=s;"timeout"!==l&&Pe.addRequest("mocked",{...a,requestId:i,pending:!0,startTime:r,rule:e});let c=null;if("redirect"===l){c=Math.random().toString(36).substring(7);const e={url:A,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(A,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};Pe.addRequest("mocked",e)}const d=(e,t,o,d={})=>{const u=Date.now()-r;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=Ge.applyResponseModifications(e,s.rule.modificationActions),o=e}Pe.addRequest("mocked",{...a,requestId:i,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===l&&c&&Pe.addRequest("mocked",{url:A,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"===l)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===l){if(!A)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,A,!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,i,r)=>{const s=o.requestId,a=Date.now(),l=n(),A=new URL(o.url,window.location.origin);e&&"GRAPHQL"===e.requestType&&(o.requestType="GRAPHQL",o.graphqlOperationName=e.graphqlOperationName,o.graphqlOperationType=e.graphqlOperationType);let c=`${F()}${e.url}${A.search}`,d={[y]:l,mfmver:"15.4.0","x-mfm-adaptor":t};const u=Q();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const p={...o.headers,...d};Pe.addRequest("mocked",{...o,requestId:s,pending:!0,startTime:a});const f=(t,n,r,l={})=>{if(i._captured)return;const A=Date.now()-a;Re(r)&&Pe.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),Pe.addRequest("mocked",{...o,requestId:s,status:t,responseBody:n,responseHeaders:r,pending:!1,duration:A,...l}),i._capture(t,n,r,l)};i._xhr.addEventListener("abort",()=>f("Aborted","Aborted",{},{aborted:!0}),{once:!0}),i._xhr.addEventListener("error",()=>f(0,"Error",{},{error:!0}),{once:!0}),i._xhr.addEventListener("timeout",()=>f("Timeout","Timeout",{},{timeout:!0}),{once:!0});const h=new window.XMLHttpRequest;h.open(o.method,c,!0);for(const e in p)h.setRequestHeader(e,p[e]);h.withCredentials=i.proxy.withCredentials,i._onAbort=()=>{try{h.abort()}catch(e){}f("Aborted","Aborted",{},{aborted:!0})},h.onload=()=>f(h.status,h.responseText,h.getAllResponseHeaders()),h.onerror=()=>f(0,"Network Error",{},{error:!0}),h.ontimeout=()=>f("Timeout","Request timed out",{},{timeout:!0}),h.send(o.body)},onOtherRequest:(e,t,n)=>{const o="true"===e.headers?.["x-mfm-internal"],i=F(),r=e.url.startsWith(i);if("OPTIONS"===e.method||o||r)return n(e.body);const s=Date.now();Pe.addRequest("other",{...e,pending:!0,startTime:s});const a=W(e.method,e.url),l=P(e.method,e.url);let A=e;const c=(n,o,i,r={})=>{const a=Date.now()-s;Pe.addRequest("other",{...e,status:n,responseBody:o,responseHeaders:i,pending:!1,duration:a,...r}),t._capture(n,o,i,r)};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,i=t._xhr.getAllResponseHeaders();if(l){const t={};"string"==typeof i&&i.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const r=await R({requestId:e.requestId,ruleId:l.id,request:{method:A.method,url:A.url,headers:A.headers,body:A.body},response:{statusCode:n,headers:t,body:o}});if(r.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});r.delayMs>0&&await new Promise(e=>setTimeout(e,r.delayMs));const s=Number(r.statusCode)||n,a=r.headers&&"object"==typeof r.headers?r.headers:t,d="string"==typeof r.body?r.body:null==r.body?"":JSON.stringify(r.body);return void c(s,d,a)}c(n,o,i)},{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;Pe.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 i=await $({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:o});if(i.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}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(i.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){}if(r!==e.url)try{t._xhr.open(e.method,r,!0)}catch(e){}Object.entries(i.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),A={...e,url:r,headers:i.headers||{},body:i.body};const s=String(e.method||"GET").toUpperCase(),l="GET"!==s&&"HEAD"!==s?null==i.body?null:i.body:null,d=te();d>0?setTimeout(()=>{try{n(l)}catch(e){}},d):n(l)})();const d=te();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&l)Pe.mappings=s,Pe.rules=c,e?.(s,{_o:a,mk:l,_mck:A,_rules:c});else if(o){const t=Pe.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return Pe.mappings=t.mappings,Pe.rules=t.meta?._rules||[],f(t.mappings),E(t.meta),Pe.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);Pe.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:g,getMappings:h,doFetchMappings:(e,t)=>{U(o||Pe.token,n,(t,i)=>{Pe.saveMappings(t,i,o||Pe.token,n),Pe.updateMappings(t,i),e?.(t,i)},t)},recheckWidgetVisibility:()=>{Pe.init()}}},Ye=i();Ye||(globalThis.mockforme=Xe);let Ze=Xe;Ye&&(Ze=e=>({run:()=>{}}));const et=Ze;module.exports=o})();
20
+ `;function Td({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:[Bt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),Bt("span",{children:e})]})}function Md(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function Id(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function _d(){const e=Ut(),{confirmState:t,dismissConfirm:n}=Sn();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:i,confirmLabel:r,cancelLabel:s,danger:a,onConfirm:l}=t;return Bt("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?Bt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:o}):null,Bt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:i}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[Bt("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"}),Bt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),l()},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:r??"Confirm"})]})]})})}function Dd(){const{analyticsEnabled:e}=wo(),{token:t,organisationId:n}=Tn();return u.useEffect(()=>{yn.setEnabled(e)},[e]),u.useEffect(()=>{yn.setToken(t)},[t]),u.useEffect(()=>{yn.setOrganisationId(n)},[n]),null}function Ld({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[Bt(Hd,{}),Bt(_t,{children:Bt(En,{clientType:e,version:t,children:Bt(Un,{children:Bt(In,{children:Bt(qn,{children:Bt(ur,{children:Bt(to,{children:Bt(yo,{children:Bt(uo,{children:Ct(xo,{children:[Bt(Dd,{}),Bt(jr,{}),Ct(Pi,{children:[Bt(Nd,{}),Bt(la,{})]})]})})})})})})})})})})]})}function Hd(){const e=Ut();return Bt(ht,{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 Nd(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:o,openSettings:i,startSnipping:r,requestConfirm:s}=Sn(),{token:a,isTokenValidated:l,isValidating:A,isLoading:c,reloadMappings:d,deleteToken:u}=Tn(),{debugRules:p,editRules:f}=po(),{globalDelay:h}=wo();if(!l&&(A||a))return Ct(xt,{children:[Bt(Xr,{children:Bt(Kd,{children:Bt(zd,{})})}),Bt(gd,{})]});if(!a)return Ct(xt,{children:[Bt(Xr,{children:Ct(Kd,{children:[Bt(jA,{}),Bt(_d,{})]})}),Bt(gd,{})]});const g=o||p.length>0||f.length>0||h.enabled;return Ct(xt,{children:[Ct(Xr,{children:[Bt(ca,{}),Bt(is,{onSnip:r,onReload:d,onOpenSettings:i,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. 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}),Bt(ss,{}),Bt(ls,{}),Bt(fs,{}),Ct(Kd,{children:[Bt(OA,{}),Bt(KA,{}),Bt(WA,{}),Bt(XA,{}),Bt(ic,{}),Bt(uc,{}),Bt(yc,{}),Bt(_d,{}),Bt(Pd,{})]})]}),Bt(gd,{})]})}var Od={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 zd(){const e=Ut();return Ct("div",{css:Od,children:[Bt(za,{size:26,color:e.color.primary,label:"Validating token"}),Bt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),Bt("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 Pd(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=Tn(),n=Ut();return null==e?null:Bt(As,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:Bt("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:Bt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var Rd={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},jd={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function Kd({children:e}){const{fullscreenSlotRef:t}=Sn();return Ct("div",{css:jd,children:[e,Bt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:Rd})]})}class Vd extends u.Component{constructor(){super(...arguments),i(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const Gd=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-BOh3ubDn.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function qd(){if(!Gd)return!1;try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(Gd)}catch{return!1}}function Wd(e,t){return!(!Gd||!qd()||!(e&&e.startsWith(Gd)||t&&-1!==t.indexOf(Gd)))}const Jd=Wd;let $d=null;const Xd="data-mfm-mount";function Yd(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function Zd(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{yn.init(),yn.setClientType(e);const t=gn().read("MFM_TOKEN");t&&yn.setToken(t)}catch{}}(t.clientType);const o=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],i=e=>e.stopPropagation();for(const e of o){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,i,{passive:t})}const r=n.shadowRoot??n.attachShadow({mode:"open"});let s=r.querySelector(`[${Xd}]`);s||(s=document.createElement("div"),s.setAttribute(Xd,""),r.appendChild(s));const a=Ue({key:"mfm",container:r,prepend:!0}),l={run:()=>{}},A=S.createRoot(s);A.render(u.createElement(u.StrictMode,null,u.createElement(ot,{value:a},u.createElement(Vd,{onError:e=>{setTimeout(()=>l.run(e),0)}},u.createElement(Ld,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;Jd(e.filename,t?.stack)&&(e.preventDefault(),l.run(e.error))},d=e=>{const t=e.reason,n=t?.stack??(t?String(t):void 0);Jd(void 0,n)&&(e.preventDefault(),l.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const p=console.error;console.error=function(...e){if(Gd&&qd())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(Gd))return}p.apply(console,e)};let f=!1,h=null;const g=e=>{if(!f){if(f=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==p)try{console.error=p}catch{}try{A.unmount()}catch{}try{n.remove()}catch{}$d=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:"";Ci("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 yn.track("widget_destroyed");Ei()}catch{}if(void 0!==e)try{h=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 i=document.createElement("div");i.textContent="MockForMe is unable to load.",i.style.cssText="font-weight: 500";const r=document.createElement("div");r.textContent="The issue has been reported.",r.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),o.appendChild(i),o.appendChild(r);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 l=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",l),n.appendChild(o),n.appendChild(s),t.appendChild(n),{dismiss:l}}()}catch{}}};return l.run=g,{destroy(){if(g(),h){try{h.dismiss()}catch{}h=null}}}}const eu={run(e,t={}){if($d)return $d;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const o=()=>{if(n)return;const o=Yd(e);o&&($d=Zd(o,t))};return document.addEventListener("DOMContentLoaded",o,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",o),$d&&$d.destroy()}}}const n=Yd(e);return n?($d=Zd(n,t),$d):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=eu),n.d(t,["M",0,eu])},435(e,t,n){n.d(t,{MockForMeWidget:()=>o.M});var o=n(158)}};const t={};function n(o){const i=t[o];if(void 0!==i)return i.exports;const r=t[o]={exports:{}};return e[o](r,r.exports,n),r.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var o=0;o<t.length;){var i=t[o++],r=t[o++];n.o(e,i)?0===r&&o++:0===r?Object.defineProperty(e,i,{enumerable:!0,value:t[o++]}):Object.defineProperty(e,i,{enumerable:!0,get:r})}else for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},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.r(o),n.d(o,{mockforme:()=>et});const i=()=>"undefined"!=typeof process&&null!=process.versions?.node,r=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,l=/\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/i,A=/^\s*(?:#[^\n]*\n\s*)*\b(query|mutation|subscription)\b/i;function c(e){if(null==e)return null;if("object"==typeof e)return e;if("string"==typeof e){const t=e.trim();if(!t||"{"!==t[0])return null;try{return JSON.parse(t)}catch{return null}}return null}const d="GRAPHQL",u=e=>e&&e.requestType===d;let p=[];function f(e){p=e}function h(){return p}function g(e,t="get",n=null){const o=e=>e.startsWith("/")?e:`/${e}`,i=o(e),f=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const o of n){if(r(o.apiMethod)!==r(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}(i,t);if(f)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${f.url}`),f;const h=function(e,t,n,o){if("post"!==r(t))return null;if(!p.some(u))return null;if(!function(e){const t=c(e);return!!(t&&"string"==typeof t.query&&t.query.trim().length>0)}(n))return null;const{operationName:i,operationType:a}=function(e){const t=c(e)||{},n="string"==typeof t.query?t.query:"";let o=t.operationName?String(t.operationName).trim():"";if(!o){const e=n.match(l);o=e?e[1]:""}let i="";if(o){const e=n.match(new RegExp(`\\b(query|mutation|subscription)\\s+${s=o,String(s).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"));e&&(i=r(e[1]))}var s;if(!i){const e=n.match(A);i=e?r(e[1]):"query"}return{operationName:o,operationType:i}}(n);if(!i)return null;for(const t of p){if(!u(t))continue;const n=o(t.apiEndpoint);if(n!==e&&!s(n,e))continue;if(t.graphqlOperationName!==i)continue;if(r(t.graphqlOperationType)!==r(a))continue;console.log(`[MockForMe] GraphQL Match Found: ${a} ${i} @ ${t.apiEndpoint}`);const l={url:n===e?e:t.apiEndpoint,method:t.apiMethod,apiEndpoint:t.apiEndpoint,_ack:t._ack||null,requestType:d,graphqlOperationName:i,graphqlOperationType:a};return t._ri_&&(l._ri_=t._ri_),l}return null}(i,t,n,o);if(h)return h;for(const n of p)if(!u(n)&&r(n.apiMethod)===r(t)){const r=o(n.apiEndpoint);if(r===i||s(r,i)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${n.apiEndpoint}`);const o={url:e,method:n.apiMethod,apiEndpoint:n.apiEndpoint,_ack:n._ack||null};return n._ri_&&(o._ri_=n._ri_),o}}return null}const m="JAVASCRIPT",y="mockforme",w="https://api.mockforme.com",k=`${w}/mockforme`,b=`${w}/gateway/3f4eae522b`;let v=null,x=null,B=null,C=[];function E({_o:e,mk:t,_mck:n,_rules:o}){v=e,x=t,B=n,C=o}function S(){return C}function F(){return`${k}/${v}/${x}`}function Q(){return B}function U(e,t,n,o){fetch(b,{method:"GET",headers:{[y]:e,mfmver:"15.7.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:i,_mck:r,mk:s,r:a}=e,l=function({di:e,iv:t},n){var o;const i=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(i)}({di:t,iv:o},i);E({_o:i,mk:s,_mck:r,_rules:a}),l&&(f(l),n(l,{_o:i,mk:s,_mck:r,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),o(e)})}const T="mfm_op_3f4eae522b",M=`${w}/mockforme/${T}/manage`,I=e=>({[y]:e,mfmver:"15.7.0","Content-Type":"application/json"}),_=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}},D=[T],L="MFM_INTERCEPTOR_RULES";let H=[];const N=new Map;function O(){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 z(e){H=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function P(e,t){if(!e||!t)return null;if(!H.length&&(H=O(),!H.length))return null;const n=String(e).toUpperCase();return H.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({requestId:e,ruleId:t,request:n,response:o,timeoutMs:i=3e5}){return new Promise(r=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),r({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body}))},i);N.set(e,{resolve:r,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),N.delete(e),r({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:o?.statusCode??200,headers:o?.headers||{},body:o?.body})}})}H=O(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&z(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(H=O())});const j="MFM_REQUEST_EDITOR_RULES";let K=[];const V=new Map;function G(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(j);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function q(e){K=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function W(e,t){if(!e||!t)return null;if(!K.length&&(K=G(),!K.length))return null;const n=String(e).toUpperCase();return K.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 J(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 $({requestId:e,ruleId:t,request:n,queryParams:o,timeoutMs:i=3e5}){return new Promise(r=>{const s=setTimeout(()=>{V.has(e)&&(V.delete(e),r(J(e,n,o)))},i);V.set(e,{resolve:r,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),V.delete(e),r(J(e,n,o))}})}K=G(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&q(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===j&&(K=G())});const X="MFM_GLOBAL_DELAY";let Y={enabled:!1,seconds:0},Z=0;function ee(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(X);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 te(){const e=Date.now();return e-Z>500&&(Y=ee(),Z=e),Y.enabled&&Y.seconds>0?Math.round(1e3*Y.seconds):0}var ne,oe;function ie(){const e="undefined"!=typeof window?window:void 0;return e?(e.__MOCKFORME__||(e.__MOCKFORME__={adapters:[]}),e.__MOCKFORME__):null}function re(){const e=ie();return!!e&&new Set(e.adapters).size>1}function se(e){return`MockForMe detected more than one integration active on this page (${e.length?e.join(" + "):"multiple adapters"}). Or NPM Mocking is paused to avoid conflicts. Use only ONE: remove "import statement" and mockforme().run() from your app, OR disable the MockForMe Chrome extension on this host.`}Y=ee(),Z=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===X&&(Y=ee(),Z=Date.now())}),function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(ne||(ne={})),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_REQ_IMAGE_ANALYSIS="MFM_REQ_IMAGE_ANALYSIS",e.MFM_REQ_LOCATE_IMAGE="MFM_REQ_LOCATE_IMAGE",e.MFM_REQ_APPLY_IMAGE="MFM_REQ_APPLY_IMAGE",e.MFM_REQ_REVERT_IMAGE="MFM_REQ_REVERT_IMAGE",e.MFM_REQ_REVERT_ALL_IMAGES="MFM_REQ_REVERT_ALL_IMAGES",e.MFM_REQ_MEASURE_IMAGE="MFM_REQ_MEASURE_IMAGE",e.MFM_REQ_CLEAR_HIGHLIGHT="MFM_REQ_CLEAR_HIGHLIGHT",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_RES_IMAGE_ANALYSIS="MFM_RES_IMAGE_ANALYSIS",e.MFM_RES_IMAGE_ACTION="MFM_RES_IMAGE_ACTION",e.MFM_RES_MEASURE_IMAGE="MFM_RES_MEASURE_IMAGE",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_CONFLICT="MFM_CONFLICT",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",e.MFM_DEVICE_SIM_TOGGLE="MFM_DEVICE_SIM_TOGGLE",e.MFM_DEVICE_CATALOG_REQ="MFM_DEVICE_CATALOG_REQ",e.MFM_DEVICE_CATALOG_SET="MFM_DEVICE_CATALOG_SET",e.MFM_DEVICE_CREATE="MFM_DEVICE_CREATE",e.MFM_DEVICE_CREATE_CUSTOM="MFM_DEVICE_CREATE_CUSTOM",e.MFM_DEVICE_DESTROY="MFM_DEVICE_DESTROY",e.MFM_DEVICE_ROTATE="MFM_DEVICE_ROTATE",e.MFM_DEVICE_SET_UA="MFM_DEVICE_SET_UA",e.MFM_DEVICE_SIM_READY="MFM_DEVICE_SIM_READY",e.MFM_DEVICE_SIM_OFF="MFM_DEVICE_SIM_OFF",e.MFM_DEVICE_INSTANCES_SET="MFM_DEVICE_INSTANCES_SET",e.MFM_DEVICE_ERROR="MFM_DEVICE_ERROR",e.MFM_ANNOUNCEMENTS_SET="MFM_ANNOUNCEMENTS_SET",e.MFM_ANNOUNCEMENT_DISMISS="MFM_ANNOUNCEMENT_DISMISS"}(oe||(oe={}));const ae="Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",le="Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36",Ae="Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36",ce=(e,t,n,o,i,r)=>({id:e,name:t,category:"phone",platform:"ios",strategy:"iphone",viewport:{width:n,height:o},devicePixelRatio:i,orientation:"portrait",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",capabilities:{touch:!0},accessRule:{plan:"free"},frame:r,source:"built-in"}),de=(e,t,n,o,i,r="Mozilla/5.0 (Linux; Android 14; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36")=>({id:e,name:t,category:"phone",platform:"android",strategy:"android",viewport:{width:n,height:o},devicePixelRatio:i,orientation:"portrait",userAgent:r,capabilities:{touch:!0},accessRule:{plan:"free"},frame:"android-punch",source:"built-in"}),ue=(e,t,n,o,i,r,s)=>({id:e,name:t,category:"tablet",platform:r,strategy:"tablet",viewport:{width:n,height:o},devicePixelRatio:i,orientation:"portrait",userAgent:s,capabilities:{touch:!0},accessRule:{plan:"free"},frame:"ios"===r?"ios-tablet":"android-tablet",source:"built-in"});function pe(e,t=1){if(!Number.isFinite(e)||e<=0)return"0 B";const n=["B","KB","MB","GB","TB"],o=Math.min(n.length-1,Math.floor(Math.log(e)/Math.log(1024))),i=0===o?0:t;return`${(e/Math.pow(1024,o)).toFixed(i)} ${n[o]}`}function fe(e,t,n=0){return!t||t<=0?0:he(e/t*100,n)}function he(e,t=0){if(!Number.isFinite(e))return 0;const n=Math.pow(10,t);return Math.round(e*n)/n}function ge(e,t){const n=function(e){if(!e)return"";switch(e.toLowerCase().split(";")[0].trim()){case"image/jpeg":case"image/jpg":return"JPEG";case"image/png":return"PNG";case"image/webp":return"WebP";case"image/avif":return"AVIF";case"image/gif":return"GIF";case"image/svg+xml":return"SVG";case"image/bmp":return"BMP";case"image/tiff":return"TIFF";default:return""}}(t);return n||function(e){switch(function(e){try{const t=e.split(/[?#]/)[0],n=t.lastIndexOf("."),o=t.lastIndexOf("/");return-1===n||n<o?"":t.slice(n).toLowerCase()}catch{return""}}(e)){case".jpg":case".jpeg":return"JPEG";case".png":return"PNG";case".webp":return"WebP";case".avif":return"AVIF";case".gif":return"GIF";case".svg":return"SVG";case".bmp":return"BMP";case".tiff":case".tif":return"TIFF";default:return"—"}}(e)}ce("iphone-se","iPhone SE",375,667,2,"ios-home"),ce("iphone-x","iPhone X",375,812,3,"ios-notch"),ce("iphone-xr","iPhone XR",414,896,2,"ios-notch"),ce("iphone-11","iPhone 11",414,896,2,"ios-notch"),ce("iphone-11-pro","iPhone 11 Pro",375,812,3,"ios-notch"),ce("iphone-12-mini","iPhone 12 mini",360,780,3,"ios-notch"),ce("iphone-12","iPhone 12",390,844,3,"ios-notch"),ce("iphone-12-pro-max","iPhone 12 Pro Max",428,926,3,"ios-notch"),ce("iphone-13","iPhone 13",390,844,3,"ios-notch"),ce("iphone-13-pro","iPhone 13 Pro",390,844,3,"ios-notch"),ce("iphone-14","iPhone 14",390,844,3,"ios-notch"),ce("iphone-14-plus","iPhone 14 Plus",428,926,3,"ios-notch"),ce("iphone-14-pro","iPhone 14 Pro",393,852,3,"ios-island"),ce("iphone-14-pro-max","iPhone 14 Pro Max",430,932,3,"ios-island"),ce("iphone-15","iPhone 15",393,852,3,"ios-island"),ce("iphone-15-pro","iPhone 15 Pro",393,852,3,"ios-island"),ce("iphone-15-pro-max","iPhone 15 Pro Max",430,932,3,"ios-island"),ce("iphone-16","iPhone 16",393,852,3,"ios-island"),ce("iphone-16-pro","iPhone 16 Pro",402,874,3,"ios-island"),ce("iphone-16-pro-max","iPhone 16 Pro Max",440,956,3,"ios-island"),de("pixel-5","Pixel 5",393,851,3),de("pixel-6-pro","Pixel 6 Pro",412,892,3),de("pixel-7","Pixel 7",412,915,3,le),de("pixel-8","Pixel 8",412,915,3,le),de("pixel-8-pro","Pixel 8 Pro",448,998,3,le),de("galaxy-s20","Galaxy S20",360,800,3,Ae),de("galaxy-s21-ultra","Galaxy S21 Ultra",384,854,3,Ae),de("galaxy-s22","Galaxy S22",360,780,3,Ae),de("galaxy-s23","Galaxy S23",360,780,3,Ae),de("galaxy-s24-ultra","Galaxy S24 Ultra",384,832,3,Ae),de("oneplus-nord-2","OnePlus Nord 2",412,915,3),de("xiaomi-12","Xiaomi 12",390,844,3),ue("ipad-mini","iPad mini",768,1024,2,"ios",ae),ue("ipad-air","iPad Air",820,1180,2,"ios",ae),ue("ipad-pro-11",'iPad Pro 11"',834,1194,2,"ios",ae),ue("galaxy-tab-s7","Galaxy Tab S7",800,1280,2,"android","Mozilla/5.0 (Linux; Android 14; SM-X700) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");const me=new Set(["JPEG","PNG","BMP","TIFF"]);function ye(e,t){const n=ge(e,t);return"—"!==n&&me.has(n)}function we(e,t){const n=function(e){try{const t=e.split(/[?#]/)[0];return t.slice(t.lastIndexOf("/")+1)||e}catch{return e}}(e)||"image.jpg",o=n.lastIndexOf("."),i=o>0?n.slice(0,o):n,r=o>0?n.slice(o):".jpg",s=Math.max(1,Math.round(t||600)),a=2*s;return["<img",` src="${i}-${s}${r}"`,` srcset="${i}-${s}${r} ${s}w, ${i}-${a}${r} ${a}w"`,` sizes="(max-width: ${s}px) 100vw, ${s}px"`,' alt="…"',' loading="lazy" />'].join("\n")}const ke={monthlyPageViews:1e5,avgImagesPerPage:0,costPerGb:.1};function be(e){return e.transferSize>0?e.transferSize:e.encodedBodySize>0?e.encodedBodySize:e.contentLength&&e.contentLength>0?e.contentLength:0}function ve(e){return e.transferSize<=0&&e.encodedBodySize<=0&&!(e.contentLength&&e.contentLength>0)}function xe(e,t){return e*Math.min(Math.max(t||1,1),2)}function Be(e,t){return!(e.displayedWidth<24||e.displayedHeight<24)&&!(!e.naturalWidth||!e.naturalHeight)&&e.naturalWidth>1.15*xe(e.displayedWidth,t)}function Ce(e,t){if(!Be(e,t))return 1;const n=xe(e.displayedWidth,t)*xe(e.displayedHeight,t),o=e.naturalWidth*e.naturalHeight;return o<=0?1:Math.min(1,n/o)}function Ee(e,t,n,o,i){if(e<=0)return{mid:0,low:0,high:0};const r=t?e*Ce(t,o):e;return ye(n,i)?{mid:.65*r,low:.55*r,high:.75*r}:{mid:r,low:r,high:r}}function Se(e){return e>=1048576?"HIGH":e>=204800?"MEDIUM":"LOW"}const Fe={HIGH:0,MEDIUM:1,LOW:2};new class{constructor(){this.kind="image"}analyze(e,t=ke){const n=e&&e.devicePixelRatio>0?e.devicePixelRatio:1;if(!e||e.unsupported)return this.emptyResult(!1,t);const o=function(e){const t=new Set,n=[];for(const o of e)o&&o.url&&!t.has(o.url)&&(t.add(o.url),n.push(o));return n}(e.resources||[]),i=new Map;for(const t of e.images||[])t.url&&!i.has(t.url)&&i.set(t.url,t);if(0===o.length&&0===i.size)return this.emptyResult(!0,t);let r=0,s=0,a=0,l=0,A=0,c=0,d=0,u=0,p=0;const f=[];for(const e of o){const t=be(e),o=i.get(e.url);ve(e)?s+=1:(r+=t,e.transferSize<=0&&e.encodedBodySize>0&&(a+=1),t>l&&(l=t));const h=Ee(t,o,e.url,n,e.contentType);A+=h.mid,c+=h.low,d+=h.high,ye(e.url,e.contentType)&&t>0&&(u+=1,p+=.35*(o?t*Ce(o,n):t)),f.push({url:e.url,bytes:t,saving:Math.max(0,t-h.mid),img:o})}let h=0,g=0,m=0;for(const e of i.values()){Be(e,n)&&(h+=1);const t=(f.find(t=>t.url===e.url)?.bytes||0)>204800||Be(e,n);!e.hasSrcset&&t&&(g+=1),e.inViewport||"lazy"===e.loading||(m+=1)}const y=o.length||i.size,w=this.buildDetails(o,i,n),k=this.buildRecommendations(f,n,w,{legacyFormatCount:u,legacyFormatSaving:p,missingResponsiveCount:g,lazyCandidateCount:m}),b=e.nav?.loadEvent||e.nav?.domContentLoaded||o.reduce((e,t)=>Math.max(e,t.responseEnd),0),v=function(e,t){const n=e.filter(e=>e.startTime>=0&&e.startTime<t),o=n.reduce((e,t)=>e+be(t),0),i=n.filter(e=>be(e)>204800).length;return n.length>=6&&o>=1048576?{concurrentInCriticalWindow:n.length,bytesInCriticalWindow:Math.round(o),criticalWindowEndMs:Math.round(t),largeNonCriticalCount:i}:null}(o,b);v&&k.push(this.contentionRecommendation(v)),k.sort((e,t)=>Fe[e.priority]-Fe[t.priority]||t.estimatedSavingBytes-e.estimatedSavingBytes);const x=Math.max(0,Math.round(A)),B=Math.max(0,r-x);return{supported:!0,empty:!1,current:{imageCount:y,totalBytes:Math.round(r),unknownByteCount:s,cachedCount:a,largestBytes:Math.round(l),oversizedCount:h,legacyFormatCount:u,missingResponsiveCount:g,lazyCandidateCount:m},optimised:{estimatedBytes:x,estimatedBytesLow:Math.max(0,Math.round(c)),estimatedBytesHigh:Math.max(0,Math.round(d)),estimatedSavedBytes:B,estimatedSavedPct:fe(B,r)},recommendations:k,imageDetails:w,cost:this.estimateCost(r,x,y,t),loading:this.analyzeLoading(e,f),contention:v}}buildDetails(e,t,n){const o=new Map(e.map(e=>[e.url,e])),i=new Set;e.forEach(e=>i.add(e.url)),t.forEach((e,t)=>i.add(t));const r=[];for(const e of i){const i=o.get(e),s=t.get(e),a=i?be(i):0,l=i?.contentType,A=Ee(a,s,e,n,l),c=!(!s||!Be(s,n)),d=ye(e,l),u=a>204800||c,p=!(!s||s.hasSrcset||!u),f=!(!s||s.inViewport||"lazy"===s.loading),h=[];c&&h.push("oversized"),d&&h.push("legacy-format"),p&&h.push("missing-responsive"),f&&h.push("lazy-candidate");const g=h.length>0,m=(s?Ce(s,n):1)*(d?.65:1),y=Math.max(0,Math.min(1,1-m)),w=s?c?Math.round(xe(s.displayedWidth,n)):s.naturalWidth:0,k=s?c?Math.round(xe(s.displayedHeight,n)):s.naturalHeight:0;r.push({url:e,domIndex:s?s.index:-1,bytes:Math.round(a),estimatedBytes:g?Math.round(A.mid):Math.round(a),savingBytes:g?Math.max(0,Math.round(a-A.mid)):0,savingPct:g?y:0,currentFormat:ge(e,l),contentType:l,suggestedFormat:d?"WebP / AVIF":null,naturalWidth:s?.naturalWidth||0,naturalHeight:s?.naturalHeight||0,displayedWidth:s?.displayedWidth||0,displayedHeight:s?.displayedHeight||0,suggestedWidth:w,suggestedHeight:k,issues:h,hasSrcset:!!s?.hasSrcset,srcsetExample:p&&s?we(e,s.displayedWidth):null})}return r.sort((e,t)=>{const n=e.issues.length>0?1:0,o=t.issues.length>0?1:0;return n!==o?o-n:t.savingBytes-e.savingBytes||t.bytes-e.bytes}),r}buildRecommendations(e,t,n,o){const i=[],r=e=>n.filter(t=>t.issues.includes(e)),s=e.filter(e=>e.img&&Be(e.img,t)&&e.saving>=20480).sort((e,t)=>t.saving-e.saving).slice(0,5);for(const e of s){const t=e.img;i.push({id:`oversized:${e.url}`,priority:Se(e.saving),issueType:"oversized",title:`Oversized image — ${pe(e.bytes)}`,why:"A much larger image than needed is downloaded, wasting bytes and delaying paint.",currentValue:`Downloaded ${t.naturalWidth}×${t.naturalHeight}, shown ${t.displayedWidth}×${t.displayedHeight}`,recommendedAction:"Serve a responsive, appropriately-sized image (srcset/sizes).",estimatedSavingBytes:Math.round(e.saving),affectedCount:1,details:n.filter(t=>t.url===e.url)})}return o.legacyFormatCount>0&&i.push({id:"legacy-format",priority:Se(o.legacyFormatSaving),issueType:"legacy-format",title:`${o.legacyFormatCount} image${o.legacyFormatCount>1?"s":""} use JPEG/PNG`,why:"Modern formats cut bytes at equal quality.",currentValue:"Legacy raster formats (JPEG/PNG).",recommendedAction:"Serve WebP/AVIF where the browser supports it.",estimatedSavingBytes:Math.round(o.legacyFormatSaving),affectedCount:o.legacyFormatCount,details:r("legacy-format")}),o.missingResponsiveCount>0&&i.push({id:"missing-responsive",priority:"MEDIUM",issueType:"missing-responsive",title:`${o.missingResponsiveCount} image${o.missingResponsiveCount>1?"s":""} missing responsive loading`,why:"Without srcset/sizes every device downloads the same large file.",currentValue:"No srcset/sizes on large images.",recommendedAction:"Add srcset + sizes so browsers pick the right resolution.",estimatedSavingBytes:0,affectedCount:o.missingResponsiveCount,details:r("missing-responsive")}),o.lazyCandidateCount>0&&i.push({id:"lazy-candidate",priority:"LOW",issueType:"lazy-candidate",title:`${o.lazyCandidateCount} below-the-fold image${o.lazyCandidateCount>1?"s":""} could lazy-load`,why:"Off-screen images loaded eagerly compete with critical content.",currentValue:"Below-the-fold images load eagerly.",recommendedAction:'Add loading="lazy" to off-screen images.',estimatedSavingBytes:0,affectedCount:o.lazyCandidateCount,details:r("lazy-candidate")}),i}contentionRecommendation(e){return{id:"contention",priority:e.largeNonCriticalCount>0?"HIGH":"MEDIUM",issueType:"contention",title:`${e.concurrentInCriticalWindow} images loaded during initial page load`,why:"Many concurrent image downloads can starve critical CSS/JS/fonts of bandwidth.",currentValue:`${pe(e.bytesInCriticalWindow)} requested in the critical window`,recommendedAction:"Prioritise critical assets and defer/lazy-load non-critical images.",estimatedSavingBytes:0,affectedCount:e.concurrentInCriticalWindow,details:[]}}estimateCost(e,t,n,o){const i=o.avgImagesPerPage>0?o.avgImagesPerPage:n,r=(n>0?e/n:0)*i,s=r*(e>0?t/e:1),a=r*o.monthlyPageViews/1e9,l=s*o.monthlyPageViews/1e9,A=Math.max(0,a-l);return{assumptions:{...o,avgImagesPerPage:i},currentGbPerMonth:he(a,1),optimisedGbPerMonth:he(l,1),savedGbPerMonth:he(A,1),savedCostPerMonth:he(A*o.costPerGb,2)}}analyzeLoading(e,t){const n=e.nav||{},o=n.lcpUrl,i=o?t.find(e=>e.url===o):void 0,r=!!i;let s;if(i&&i.bytes>0&&i.saving>0){const t=(e.resources||[]).find(e=>e.url===i.url),n=(t?Math.max(0,t.responseEnd-t.startTime):0)*(i.saving/i.bytes);n>=1&&(s=Math.round(n))}return{domContentLoadedMs:n.domContentLoaded||void 0,loadEventMs:n.loadEvent||void 0,lcpMs:n.lcp||void 0,lcpIsImage:r,estimatedLcpGainMs:s}}emptyResult(e,t){return{supported:e,empty:e,current:{imageCount:0,totalBytes:0,unknownByteCount:0,cachedCount:0,largestBytes:0,oversizedCount:0,legacyFormatCount:0,missingResponsiveCount:0,lazyCandidateCount:0},optimised:{estimatedBytes:0,estimatedBytesLow:0,estimatedBytesHigh:0,estimatedSavedBytes:0,estimatedSavedPct:0},recommendations:[],imageDetails:[],cost:{assumptions:t,currentGbPerMonth:0,optimisedGbPerMonth:0,savedGbPerMonth:0,savedCostPerMonth:0},loading:{lcpIsImage:!1},contention:null}}};const Qe=/\.(jpe?g|png|gif|webp|avif|svg|bmp|tiff?)(\?|#|$)/i;const Ue=120,Te=8,Me=2500;function Ie(e){return e.transferSize<=0&&e.encodedBodySize<=0}async function _e(e){const t="undefined"!=typeof AbortController?new AbortController:null,n=t?setTimeout(()=>t.abort(),Me):null;try{const n=await fetch(e,{method:"HEAD",cache:"force-cache",signal:t?t.signal:void 0});if(!n.ok)return;const o=(n.headers.get("content-type")||"").split(";")[0].trim().toLowerCase(),i=Number(n.headers.get("content-length")||""),r={};return o.startsWith("image/")&&(r.contentType=o),Number.isFinite(i)&&i>0&&(r.bytes=i),r.contentType||r.bytes?r:void 0}catch{return}finally{n&&clearTimeout(n)}}function De(e){return"number"==typeof e&&Number.isFinite(e)?e:0}const Le="MFM_TOKEN",He="MFM_CACHED_MAPPINGS",Ne="MFM_INTERCEPTION_ENABLED",Oe="MFM_ANNOUNCEMENT_NEXT_CHECK",ze="MFM_ANNOUNCEMENT_CACHE",Pe=new class{constructor(e={}){i()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Le):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(Ne);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Ne,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var o,i;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case oe.MFM_REQ_MAPPINGS:this.refreshMappings(),this.syncInterceptionToggleToWidget(),this.syncAnnouncementsToWidget();break;case oe.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings(),this.syncInterceptionToggleToWidget(),this.syncAnnouncementsToWidget();break;case oe.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case oe.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case oe.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case oe.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case oe.MFM_REQ_IMAGE_ANALYSIS:this.handleReqImageAnalysis();break;case oe.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case oe.MFM_DEBUG_RULES_UPDATE:z(n?.rules||[]);break;case oe.MFM_DEBUG_INTERCEPT_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 oe.MFM_REQUEST_EDIT_RULES_UPDATE:q(n?.rules||[]);break;case oe.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=V.get(e.requestId);t&&(clearTimeout(t.timer),V.delete(e.requestId),t.resolve(e))}(n);break;case oe.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return Y={enabled:!1,seconds:0},void(Z=Date.now());Y={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},Z=Date.now()}(n);break;case oe.MFM_FLOW_MOCK_SET:o=n?.runId,i=n?.apis||[],o&&a.set(String(o),Array.isArray(i)?i:[]);break;case oe.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId);break;case oe.MFM_ANNOUNCEMENT_DISMISS:this.handleAnnouncementDismiss(n?.id)}})}getCachedAnnouncements(){if("undefined"==typeof localStorage)return[];try{const e=localStorage.getItem(ze),t=e?JSON.parse(e):[];return Array.isArray(t)?t:[]}catch(e){return[]}}setCachedAnnouncements(e){if("undefined"!=typeof localStorage)try{localStorage.setItem(ze,JSON.stringify(e||[]))}catch(e){}}syncAnnouncementsToWidget(){if(!this.token)return;const e=this.getCachedAnnouncements();e.length&&this.sendMessage(oe.MFM_ANNOUNCEMENTS_SET,{announcements:e}),this.maybeFetchAnnouncements()}maybeFetchAnnouncements(){if(!this.token||"undefined"==typeof localStorage)return;const e=Date.now(),t=parseInt(localStorage.getItem(Oe)||"0",10);t&&e<t||(localStorage.setItem(Oe,String(e+9e5)),(async e=>{if(!e)return{ok:!1,message:"Missing token",result:{announcements:[]}};const t=`${M}/announcements?surface=DEVTOOL&version=${encodeURIComponent("15.7.0")}`,n=await fetch(t,{method:"GET",headers:I(e)});return _(n)})(this.token).then(e=>{if(!e||!e.ok)return;const t=e.result&&e.result.announcements||[];this.setCachedAnnouncements(t),this.sendMessage(oe.MFM_ANNOUNCEMENTS_SET,{announcements:t})}).catch(()=>{}))}handleAnnouncementDismiss(e){e&&(this.setCachedAnnouncements(this.getCachedAnnouncements().filter(t=>t&&t.id!==e)),this.token&&(async(e,t)=>{if(!e||!t)return{ok:!1,message:"Missing token or id",result:null};const n=await fetch(`${M}/announcements/${t}/dismiss`,{method:"POST",headers:I(e)});return _(n)})(this.token,e).catch(()=>{}))}init(){if("undefined"!=typeof document&&this.checkVisibility()&&("undefined"!=typeof window&&Promise.resolve().then(n.bind(n,435)).then(e=>{const t=window.MockForMeWidget||e.MockForMeWidget;t&&"function"==typeof t.run&&(t.run(null,{clientType:"NPM",version:"15.7.0"}),this.syncInterceptionToggleToWidget(),this.maybeAnnounceConflict())}).catch(e=>{console.error("[MockForMe] Failed to load mfm-widget",e)}),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(Le,e),localStorage.removeItem(Oe),localStorage.removeItem(ze)),this.refreshMappings(),this.syncAnnouncementsToWidget())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Le),localStorage.removeItem(He),localStorage.removeItem(Oe),localStorage.removeItem(ze)),this.sendMessage(oe.MFM_ANNOUNCEMENTS_SET,{announcements:[]}),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(`${M}/apis`,{method:"GET",headers:I(e)});return _(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage(oe.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage(oe.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage(oe.MFM_RES_ALL_APIS,{apis:[]})}handleReqImageAnalysis(){Promise.resolve().then(()=>async function(e={},t){if("undefined"==typeof performance||"undefined"==typeof document||"function"!=typeof performance.getEntriesByType)return{resources:[],images:[],nav:{domContentLoaded:0,loadEvent:0},devicePixelRatio:1,viewportWidth:0,viewportHeight:0,collectedAt:Date.now(),unsupported:!0};const n="undefined"!=typeof window&&window.innerWidth||document.documentElement.clientWidth||0,o="undefined"!=typeof window&&window.innerHeight||document.documentElement.clientHeight||0,i="undefined"!=typeof window&&window.devicePixelRatio||1,r=function(){const e=[];let t=[];try{t=performance.getEntriesByType("resource")}catch{return e}for(const n of t){if(e.length>=600)break;const t=n,o=t.initiatorType,i="img"===o,r="css"===o&&Qe.test(t.name);(i||r)&&e.push({url:t.name,initiatorType:o,transferSize:De(t.transferSize),encodedBodySize:De(t.encodedBodySize),decodedBodySize:De(t.decodedBodySize),fromCache:0===De(t.transferSize)&&De(t.encodedBodySize)>0,responseEnd:Math.round(De(t.responseEnd)),startTime:Math.round(De(t.startTime))})}return e}(),s=function(e,t){const n=[];let o=[];try{o=Array.prototype.slice.call(document.images||document.querySelectorAll("img"))}catch{return n}for(let i=0;i<o.length;i++){const r=o[i];if(n.length>=600)break;let s={width:0,height:0,top:0,bottom:0,left:0,right:0};try{s=r.getBoundingClientRect()}catch{}const a=r.currentSrc||r.src||"";if(!a)continue;const l=s.top<t&&s.bottom>0&&s.left<e&&s.right>0;n.push({index:i,url:a,naturalWidth:De(r.naturalWidth),naturalHeight:De(r.naturalHeight),displayedWidth:Math.round(s.width),displayedHeight:Math.round(s.height),hasSrcset:!!(r.getAttribute("srcset")||"").trim(),hasSizes:!!(r.getAttribute("sizes")||"").trim(),loading:r.getAttribute("loading")||"",inViewport:l})}return n}(n,o),a=function(){const e={domContentLoaded:0,loadEvent:0};try{const[t]=performance.getEntriesByType("navigation");t&&(e.domContentLoaded=Math.round(De(t.domContentLoadedEventEnd)),e.loadEvent=Math.round(De(t.loadEventEnd)))}catch{}try{const t=performance.getEntriesByType("largest-contentful-paint"),n=t[t.length-1];n&&(e.lcp=Math.round(De(n.renderTime||n.loadTime||n.startTime)),n.url&&(e.lcpUrl=n.url))}catch{}return e}();for(const t of r){const n=e[t.url];n&&(t.contentType=n)}const l=function(e,t){const n=[],o=[],i=new Set;for(const r of e){if(i.has(r.url))continue;const e=!r.contentType,s=Ie(r);(e||s)&&/^https?:/i.test(r.url)&&(i.add(r.url),(t.has(r.url)?n:o).push(r.url))}return n.concat(o).slice(0,Ue)}(r,new Set(s.map(e=>e.url)));if(l.length>0){let e={};try{e=await(t?t(l):async function(e){const t={};if("function"!=typeof fetch)return t;let n=0;const o=async()=>{for(;n<e.length;){const o=e[n++],i=await _e(o);i&&(t[o]=i)}},i=[];for(let t=0;t<Math.min(Te,e.length);t++)i.push(o());return await Promise.all(i),t}(l))}catch{e={}}for(const t of r){const n=e[t.url];n&&(n.contentType&&!t.contentType&&(t.contentType=n.contentType),"number"==typeof n.bytes&&n.bytes>0&&Ie(t)&&(t.contentLength=n.bytes))}}return{resources:r,images:s,nav:a,devicePixelRatio:i,viewportWidth:n,viewportHeight:o,collectedAt:Date.now()}}()).then(e=>this.sendMessage(oe.MFM_RES_IMAGE_ANALYSIS,e)).catch(()=>{this.sendMessage(oe.MFM_RES_IMAGE_ANALYSIS,{resources:[],images:[],nav:{domContentLoaded:0,loadEvent:0},devicePixelRatio:1,viewportWidth:0,viewportHeight:0,collectedAt:Date.now(),unsupported:!0})})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const o=await fetch(`${M}/api/${t}/toggle-state`,{method:"PUT",headers:I(e),body:JSON.stringify({enabled:!!n})});return _(o)})(this.token,e,t).then(n=>{this.sendMessage(oe.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage(oe.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage(oe.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&U(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(Le),localStorage.removeItem(He)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage(oe.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage(oe.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(He,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(He);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(oe.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage(oe.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||{},i=o.activeAction||"MODIFY";let r="MODIFY";"delay"===i?r="DELAY":"delay_and_timeout"===i?r="TIMEOUT":"delay_and_redirect"===i&&(r="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:r,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==r||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=p.length,o=r(e||"");return p=p.filter(e=>!(r(e.apiMethod)===o&&e.apiEndpoint===t)),p.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 i=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage(oe.MFM_MOCK_DISABLED,{method:e,url:t,message:`${i} mock was disabled and has been removed.`})}addRequest(e,t){if(!this.interceptionEnabled)return;if((e=>{if(!e)return!1;const t=String(e);return D.some(e=>e&&t.includes(e))})(t&&t.url))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,i,r;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,i=String(t.status))}t.aborted||"Aborted"===t.status?r="aborted":t.timeout||"Timeout"===t.status?r="timeout":"Cancelled"===t.status?r="cancelled":(t.error||"Error"===i)&&(r="error");const s=t.pending&&void 0===t.status?null:{statusCode:o,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...i?{statusText:i}:{},...r?{errorReason:r,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,..."GRAPHQL"===t.requestType?{requestType:"GRAPHQL",graphqlOperationName:t.graphqlOperationName,graphqlOperationType:t.graphqlOperationType}:{}},response:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage(oe.MFM_REQ,a);else if(this.sendMessage(oe.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(oe.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}maybeAnnounceConflict(){try{if(!re())return;const e=function(){const e=ie();return e?e.adapters.slice():[]}();this.sendMessage(oe.MFM_CONFLICT,{adapters:e,message:se(e)}),console.warn("[MockForMe] "+se(e))}catch{}}};function Re(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 je{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:o,queryParams:i,body:r}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:l,operator:A,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(i&&void 0!==i[l])t=String(i[l]);else try{t=new URL(n,s).searchParams.get(l)||""}catch{t=""}break;case"REQUEST_BODY":if(l){if("object"==typeof r&&null!==r)t=void 0!==r[l]?String(r[l]):"";else if("string"==typeof r)try{const e=JSON.parse(r);t=void 0!==e[l]?String(e[l]):""}catch{t=""}}else t="object"==typeof r?JSON.stringify(r):String(r||"");break;case"REQUEST_HEADER":if(l){const e=l?.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,A,c))return!1}return!0}static evaluate(e,t,n){const o=t?.toLowerCase(),i=String(e),r=String(n);switch(o){case"contains":return i.includes(r);case"equal":case"equals":return i===r;case"regexp":try{let e=r;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(i)}return new RegExp(e).test(i)}catch{return!1}default:return!1}}}class Ke{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 i={type:"passThrough",delay:0},r=Number(o.value||0);switch(t){case"delay":i.delay=r,i.delay>0&&await new Promise(e=>setTimeout(e,1e3*i.delay));break;case"redirect":case"delay_and_redirect":i.type="redirect",i.delay=r,i.redirectUrl=o.redirectUrl,i.delay>0&&await new Promise(e=>setTimeout(e,1e3*i.delay));break;case"delay_and_timeout":i.type="timeout",i.delay=r,i.delay>0&&await new Promise(e=>setTimeout(e,1e3*i.delay))}return i}}class Ve{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:o,headers:i,queryParams:r,body:s}={...e};i&&(i={...i}),r&&(r={...r});const{modifyQueryParams:a,modifyRequestBody:l,modifyRequestHeaders:A}=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),r&&delete r[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),r&&(r[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}A?.enabled&&(i={...i},Array.isArray(A.remove)&&A.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(i).find(e=>e.toLowerCase()===t);n&&delete i[n]}),Array.isArray(A.add)&&A.add.forEach(({key:e,value:t})=>{i[e]=t}));const c=String(o||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(l?.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(l.add)&&l.add.length>0||Array.isArray(l.update)&&l.update.length>0)&&(e={});e&&(Array.isArray(l.remove)&&l.remove.forEach(t=>delete e[t]),Array.isArray(l.add)&&l.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(l.update)&&l.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:i,queryParams:r,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 Ge{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)&&je.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=Ve.applyRequestModifications(t,n.modificationActions);return{...await Ke.apply(n.timingAction),modifiedRequest:o,rule:n}}static applyResponseModifications(e,t){return Ve.applyResponseModifications(e,t)}}class qe{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:i=e=>{},onRuleMatch:r=async(e,t,n,o,i)=>null,onMockMatch:s=async(e,t,n,o,i)=>null,onOtherRequest:a=async(e,t,n,o)=>null,isEnabled:l=()=>!0,shouldBypassRequest:A=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!l())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(),r=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:r,queryParams:qe.getQueryParams(n)},e instanceof Request&&null==c.body&&"GET"!==o&&"HEAD"!==o)try{d.body=await e.clone().text()}catch{}if(A(d))return t(e,c);i(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const i=n(),l=Ge.match(d,i);if(l){const n=await r(l,d,e,c,t);if(n)return n}const A=o(d);if(A){const n=await s(A,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 We{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:i=e=>{},onRuleMatch:r=(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:l=()=>!0,shouldBypassRequest:A=()=>!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 i=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}),i("readystatechange"),"Aborted"===e||o.aborted?i("abort"):0===e||"Error"===e||o.error?i("error"):"Timeout"===e||o.timeout?i("timeout"):i("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,o=null,i=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,i)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!l())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:We.getQueryParams(this._url)};if(A(t))return this._xhr.send(e);i(t);const c=n(),d=Ge.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,r(d,t,this,u);const p=o(t);return p?(this._isMocked=!0,s(p,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 Je=[b,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function $e(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Je.some(e=>{const o=new URL(e,t);return n.origin===o.origin&&n.pathname===o.pathname})}catch{return!1}}const Xe=(e,t=null,n=m)=>{if(i())return;let o="string"==typeof e?e:e?.token,r="object"==typeof e?e?.widgetKey:null;if(n===m)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),Pe.token=o,Pe.isAuthenticated=!0),!o&&Pe.token&&(o=Pe.token),Pe.onAuthSuccess=(e,t,n)=>{f(t),E(n),Pe.updateMappings(t,n)},r?Pe.setWidgetKey(r):Pe.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:l,_mck:A,_rules:c=[]}=t;return f(s),E({_o:a,mk:l,_mck:A,_rules:c}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}!function(e){const t=ie();t&&(t.adapters.includes(e)||t.adapters.push(e))}(t||"JAVASCRIPT"),Pe.maybeAnnounceConflict();const n=()=>Pe.token||e;qe.apply({isEnabled:()=>Pe.interceptionEnabled&&!re(),shouldBypassRequest:$e,ruleProvider:()=>S(),mappingProvider:e=>{try{return g(new URL(e.url,window.location.origin).pathname,e.method,e.body)}catch{return null}},onRuleMatch:async(e,t,n,o,i)=>{const r=t.requestId||Math.random().toString(36).substring(7),s=Date.now();Pe.addRequest("mocked",{...t,requestId:r,pending:!0,startTime:s,rule:e});const a=await Ge.apply(e,t),{modifiedRequest:l,type:A,delay:c,redirectUrl:d}=a;if("timeout"!==A&&Pe.addRequest("mocked",{...l,requestId:r,pending:!0,startTime:s,rule:e}),"timeout"===A){const t=Date.now()-s;throw Pe.addRequest("mocked",{...l,requestId:r,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===A&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===A?d:l.url,p={...o};l.headers&&(p.headers=l.headers),l.body&&(p.body=l.body);let f=null;if("redirect"===A){f=Math.random().toString(36).substring(7);const e={url:d,method:l.method,headers:p.headers||{},body:p.body,requestId:f,queryParams:qe.getQueryParams(d),requestHeaders:p.headers||{},requestBody:p.body,pending:!0,startTime:Date.now()};Pe.addRequest("mocked",e)}return i(u,p).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=Ge.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===A&&f){const t=e.clone(),o=t.headers.get("content-type")||"",i=Date.now()-s;try{let r;r=o.includes("application/json")?await t.json():await t.text(),Pe.addRequest("mocked",{url:d,method:l.method,requestId:f,status:e.status,pending:!1,duration:i,responseHeaders:n,responseBody:r,requestHeaders:p.headers||{},requestBody:p.body})}catch(t){Pe.addRequest("mocked",{url:d,method:l.method,requestId:f,status:e.status,pending:!1,duration:i,responseHeaders:n,requestHeaders:p.headers||{},requestBody:p.body})}}return Pe.addRequest("mocked",{...l,requestId:r,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(Pe.addRequest("mocked",{...l,requestId:r,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===A&&f&&Pe.addRequest("mocked",{url:d,method:l.method,requestId:f,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===A){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e})},onMockMatch:async(e,o,i,r,s)=>{const a=o.requestId||Math.random().toString(36).substring(7),l=Date.now();e&&"GRAPHQL"===e.requestType&&(o.requestType="GRAPHQL",o.graphqlOperationName=e.graphqlOperationName,o.graphqlOperationType=e.graphqlOperationType),Pe.addRequest("mocked",{...o,requestId:a,pending:!0,startTime:l});const A=n(),c=new URL(o.url,window.location.origin).search;let d=`${F()}${e.url}${c}`,u={[y]:A,mfmver:"15.7.0","x-mfm-adaptor":t};const p=Q();p&&e._ack&&(u["x-mfm-key"]=`${p}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const f=i instanceof Request?i.headers:r.headers,h=new Headers(f||{});Object.entries(u).forEach(([e,t])=>h.set(e,t)),h.set("x-mfm-internal","true");let g=r.body;if(!g&&i instanceof Request){const e=i.clone();"GET"!==e.method&&"HEAD"!==e.method&&(g=await e.text())}const m={method:o.method,headers:h,credentials:i instanceof Request&&i.credentials||r.credentials||"include",mode:i instanceof Request&&i.mode||r.mode||"cors",signal:i instanceof Request&&i.signal||r.signal};return g&&(m.body=g),s(d,m).then(async t=>{const n=t.clone(),i=n.headers.get("content-type")||"",r=Date.now()-l;Re(t.headers)&&Pe.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(Pe.addRequest("mocked",{...o,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:r}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return i.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-l,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(Pe.addRequest("mocked",{...o,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(i,r)})},onOtherRequest:async(e,t,n,o)=>{const i=n?.headers||(t instanceof Request?t.headers:{});let r=!1;i instanceof Headers?r="true"===i.get("x-mfm-internal"):"object"==typeof i&&(r="true"===i["x-mfm-internal"]);const s=F();if(e.url.startsWith(s)&&(r=!0),"OPTIONS"===e.method||r)return o(t,n);const a=e.requestId,l=Date.now();Pe.addRequest("other",{...e,requestId:a,pending:!0,startTime:l});const A=W(e.method,e.url),c=P(e.method,e.url);let d=t,u=n,p=e;if(A){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 $({requestId:a,ruleId:A.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(o.cancel){Pe.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-l,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}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){}const r=String(e.method||"GET").toUpperCase(),s="GET"!==r&&"HEAD"!==r;u={...n,method:e.method,headers:o.headers||{},body:s?null==o.body?void 0:o.body:void 0},d=i,p={...e,url:i,headers:o.headers||{},body:s?o.body:null}}const f=te();f>0&&await new Promise(e=>setTimeout(e,f));let h=null,g=null;try{h=await o(d,u)}catch(e){g=e}if(c){let t="",n=0,o={};if(h){try{t=await h.clone().text()}catch(e){}n=h.status,o=Object.fromEntries(h.headers.entries())}else g&&(t=g.message||"Network error",n=0);const i=await R({requestId:a,ruleId:c.id,request:{method:p.method,url:p.url,headers:p.headers,body:p.body},response:{statusCode:n,headers:o,body:t}});if(i.simulateTimeout){Pe.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-l,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const r=Number(i.statusCode),s=Number.isFinite(r)&&r>=200&&r<=599?r:n>=200?n:200,A=i.headers&&"object"==typeof i.headers?i.headers:o,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);Pe.addRequest("other",{...e,requestId:a,status:s,responseHeaders:A,responseBody:d,pending:!1,duration:Date.now()-l});const u={};return Object.entries(A).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:h?h.statusText:"",headers:new Headers(u)})}const m=Date.now()-l;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw Pe.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(h.headers.entries());let w;try{const e=h.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 Pe.addRequest("other",{...e,requestId:a,status:h.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),h}}),We.apply({isEnabled:()=>Pe.interceptionEnabled&&!re(),shouldBypassRequest:$e,ruleProvider:()=>S(),mappingProvider:e=>{try{return g(new URL(e.url,window.location.origin).pathname,e.method,e.body)}catch{return null}},onRuleMatch:async(e,t,n,o)=>{const i=t.requestId,r=Date.now();Pe.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:r,rule:e});const s=await Ge.apply(e,t),{modifiedRequest:a,type:l,redirectUrl:A}=s;"timeout"!==l&&Pe.addRequest("mocked",{...a,requestId:i,pending:!0,startTime:r,rule:e});let c=null;if("redirect"===l){c=Math.random().toString(36).substring(7);const e={url:A,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(A,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};Pe.addRequest("mocked",e)}const d=(e,t,o,d={})=>{const u=Date.now()-r;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=Ge.applyResponseModifications(e,s.rule.modificationActions),o=e}Pe.addRequest("mocked",{...a,requestId:i,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===l&&c&&Pe.addRequest("mocked",{url:A,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"===l)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===l){if(!A)return void d(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,A,!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,i,r)=>{const s=o.requestId,a=Date.now(),l=n(),A=new URL(o.url,window.location.origin);e&&"GRAPHQL"===e.requestType&&(o.requestType="GRAPHQL",o.graphqlOperationName=e.graphqlOperationName,o.graphqlOperationType=e.graphqlOperationType);let c=`${F()}${e.url}${A.search}`,d={[y]:l,mfmver:"15.7.0","x-mfm-adaptor":t};const u=Q();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const p={...o.headers,...d};Pe.addRequest("mocked",{...o,requestId:s,pending:!0,startTime:a});const f=(t,n,r,l={})=>{if(i._captured)return;const A=Date.now()-a;Re(r)&&Pe.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),Pe.addRequest("mocked",{...o,requestId:s,status:t,responseBody:n,responseHeaders:r,pending:!1,duration:A,...l}),i._capture(t,n,r,l)};i._xhr.addEventListener("abort",()=>f("Aborted","Aborted",{},{aborted:!0}),{once:!0}),i._xhr.addEventListener("error",()=>f(0,"Error",{},{error:!0}),{once:!0}),i._xhr.addEventListener("timeout",()=>f("Timeout","Timeout",{},{timeout:!0}),{once:!0});const h=new window.XMLHttpRequest;h.open(o.method,c,!0);for(const e in p)h.setRequestHeader(e,p[e]);h.withCredentials=i.proxy.withCredentials,i._onAbort=()=>{try{h.abort()}catch(e){}f("Aborted","Aborted",{},{aborted:!0})},h.onload=()=>f(h.status,h.responseText,h.getAllResponseHeaders()),h.onerror=()=>f(0,"Network Error",{},{error:!0}),h.ontimeout=()=>f("Timeout","Request timed out",{},{timeout:!0}),h.send(o.body)},onOtherRequest:(e,t,n)=>{const o="true"===e.headers?.["x-mfm-internal"],i=F(),r=e.url.startsWith(i);if("OPTIONS"===e.method||o||r)return n(e.body);const s=Date.now();Pe.addRequest("other",{...e,pending:!0,startTime:s});const a=W(e.method,e.url),l=P(e.method,e.url);let A=e;const c=(n,o,i,r={})=>{const a=Date.now()-s;Pe.addRequest("other",{...e,status:n,responseBody:o,responseHeaders:i,pending:!1,duration:a,...r}),t._capture(n,o,i,r)};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,i=t._xhr.getAllResponseHeaders();if(l){const t={};"string"==typeof i&&i.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const r=await R({requestId:e.requestId,ruleId:l.id,request:{method:A.method,url:A.url,headers:A.headers,body:A.body},response:{statusCode:n,headers:t,body:o}});if(r.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});r.delayMs>0&&await new Promise(e=>setTimeout(e,r.delayMs));const s=Number(r.statusCode)||n,a=r.headers&&"object"==typeof r.headers?r.headers:t,d="string"==typeof r.body?r.body:null==r.body?"":JSON.stringify(r.body);return void c(s,d,a)}c(n,o,i)},{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;Pe.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 i=await $({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:o});if(i.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}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(i.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){}if(r!==e.url)try{t._xhr.open(e.method,r,!0)}catch(e){}Object.entries(i.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),A={...e,url:r,headers:i.headers||{},body:i.body};const s=String(e.method||"GET").toUpperCase(),l="GET"!==s&&"HEAD"!==s?null==i.body?null:i.body:null,d=te();d>0?setTimeout(()=>{try{n(l)}catch(e){}},d):n(l)})();const d=te();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&l)Pe.mappings=s,Pe.rules=c,e?.(s,{_o:a,mk:l,_mck:A,_rules:c});else if(o){const t=Pe.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return Pe.mappings=t.mappings,Pe.rules=t.meta?._rules||[],f(t.mappings),E(t.meta),Pe.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);Pe.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:g,getMappings:h,doFetchMappings:(e,t)=>{U(o||Pe.token,n,(t,i)=>{Pe.saveMappings(t,i,o||Pe.token,n),Pe.updateMappings(t,i),e?.(t,i)},t)},recheckWidgetVisibility:()=>{Pe.init()}}},Ye=i();Ye||(globalThis.mockforme=Xe);let Ze=Xe;Ye&&(Ze=e=>({run:()=>{}}));const et=Ze;module.exports=o})();